blob: 49a0dde8cd3c3fa6542e545ce6c1995037fa9fbe [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 Laurente191d1b2022-04-15 11:59:25 +0200290 // "outputs" vector never contains duplicated outputs
Eric Laurentcad6c0d2021-07-13 15:12:39 +0200291 if ((state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE)
292 || (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != 0) &&
Eric Laurente191d1b2022-04-15 11:59:25 +0200293 (desc->mDirectOpenCount == 0))
294 || (((desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0) &&
295 !isOutputOnlyAvailableRouteToSomeDevice(desc))) {
Francois Gaffieff1eb522020-05-06 18:37:04 +0200296 clearAudioSourcesForOutput(output);
Mikhail Naganov37977152018-07-11 15:54:44 -0700297 closeOutput(output);
298 }
Eric Laurente552edb2014-03-10 17:42:56 -0700299 }
Mikhail Naganov37977152018-07-11 15:54:44 -0700300 // check A2DP again after closing A2DP output to reset mA2dpSuspended if needed
301 return true;
Eric Laurente552edb2014-03-10 17:42:56 -0700302 }
Mikhail Naganov37977152018-07-11 15:54:44 -0700303 return false;
Eric Laurentae970022019-01-29 14:25:04 -0800304 };
305
306 if (doCheckForDeviceAndOutputChanges) {
307 checkForDeviceAndOutputChanges(checkCloseOutputs);
308 } else {
309 checkCloseOutputs();
310 }
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100311 (void)updateCallRouting(false /*fromCache*/);
jiabinbce0c1d2020-10-05 11:20:18 -0700312 std::vector<audio_io_handle_t> outputsToReopen;
François Gaffie11d30102018-11-02 16:09:09 +0100313 const DeviceVector msdOutDevices = getMsdAudioOutDevices();
jiabinbce0c1d2020-10-05 11:20:18 -0700314 const DeviceVector activeMediaDevices =
315 mEngine->getActiveMediaDevices(mAvailableOutputDevices);
Eric Laurente552edb2014-03-10 17:42:56 -0700316 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700317 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Jaideep Sharma89b5b852020-11-23 16:41:33 +0530318 if (desc->isActive() && ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) ||
319 (desc != mPrimaryOutput))) {
François Gaffie11d30102018-11-02 16:09:09 +0100320 DeviceVector newDevices = getNewOutputDevices(desc, true /*fromCache*/);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700321 // do not force device change on duplicated output because if device is 0, it will
322 // also force a device 0 for the two outputs it is duplicated to which may override
323 // a valid device selection on those outputs.
François Gaffie11d30102018-11-02 16:09:09 +0100324 bool force = (msdOutDevices.isEmpty() || msdOutDevices != desc->devices())
Mikhail Naganov15be9d22017-11-08 14:18:13 +1100325 && !desc->isDuplicated()
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700326 && (!device_distinguishes_on_address(device->type())
Eric Laurentc2730ba2014-07-20 15:47:07 -0700327 // always force when disconnecting (a non-duplicated device)
328 || (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE));
François Gaffie11d30102018-11-02 16:09:09 +0100329 setOutputDevices(desc, newDevices, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700330 }
jiabinbce0c1d2020-10-05 11:20:18 -0700331 if (!desc->isDuplicated() && desc->mProfile->hasDynamicAudioProfile() &&
jiabin498d2152021-04-02 00:26:46 +0000332 !activeMediaDevices.empty() && desc->devices() != activeMediaDevices &&
jiabinbce0c1d2020-10-05 11:20:18 -0700333 desc->supportsDevicesForPlayback(activeMediaDevices)) {
334 // Reopen the output to query the dynamic profiles when there is not active
335 // clients or all active clients will be rerouted. Otherwise, set the flag
336 // `mPendingReopenToQueryProfiles` in the SwOutputDescriptor so that the output
337 // can be reopened to query dynamic profiles when all clients are inactive.
338 if (areAllActiveTracksRerouted(desc)) {
339 outputsToReopen.push_back(mOutputs.keyAt(i));
340 } else {
341 desc->mPendingReopenToQueryProfiles = true;
342 }
343 }
344 if (!desc->supportsDevicesForPlayback(activeMediaDevices)) {
345 // Clear the flag that previously set for re-querying profiles.
346 desc->mPendingReopenToQueryProfiles = false;
347 }
348 }
349 for (const auto& output : outputsToReopen) {
350 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
351 closeOutput(output);
352 openOutputWithProfileAndDevice(desc->mProfile, activeMediaDevices);
Eric Laurente552edb2014-03-10 17:42:56 -0700353 }
354
Eric Laurentd60560a2015-04-10 11:31:20 -0700355 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
François Gaffie11d30102018-11-02 16:09:09 +0100356 cleanUpForDevice(device);
Eric Laurentd60560a2015-04-10 11:31:20 -0700357 }
358
Eric Laurent72aa32f2014-05-30 18:51:48 -0700359 mpClientInterface->onAudioPortListUpdate();
Eric Laurentb71e58b2014-05-29 16:08:11 -0700360 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700361 } // end if is output device
362
Eric Laurente552edb2014-03-10 17:42:56 -0700363 // handle input devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700364 if (audio_is_input_device(device->type())) {
François Gaffie11d30102018-11-02 16:09:09 +0100365 ssize_t index = mAvailableInputDevices.indexOf(device);
Eric Laurente552edb2014-03-10 17:42:56 -0700366 switch (state)
367 {
368 // handle input device connection
Eric Laurent3b73df72014-03-11 09:06:29 -0700369 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700370 if (index >= 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100371 ALOGW("%s() device already connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700372 return INVALID_OPERATION;
373 }
Eric Laurent0dd51852019-04-19 18:18:58 -0700374
375 if (mAvailableInputDevices.add(device) < 0) {
376 return NO_MEMORY;
377 }
378
François Gaffie44481e72016-04-20 07:49:57 +0200379 // Before checking intputs, broadcast connect event to allow HAL to retrieve dynamic
380 // parameters on newly connected devices (instead of opening the inputs...)
François Gaffie11d30102018-11-02 16:09:09 +0100381 broadcastDeviceConnectionState(device, state);
François Gaffie44481e72016-04-20 07:49:57 +0200382
Eric Laurent0dd51852019-04-19 18:18:58 -0700383 if (checkInputsForDevice(device, state) != NO_ERROR) {
384 mAvailableInputDevices.remove(device);
385
François Gaffie11d30102018-11-02 16:09:09 +0100386 broadcastDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE);
Francois Gaffie716e1432019-01-14 16:58:59 +0100387
388 mHwModules.cleanUpForDevice(device);
389
Eric Laurentd4692962014-05-05 18:13:44 -0700390 return INVALID_OPERATION;
391 }
392
Eric Laurentd4692962014-05-05 18:13:44 -0700393 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700394
395 // handle input device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700396 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700397 if (index < 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100398 ALOGW("%s() device not connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700399 return INVALID_OPERATION;
400 }
Paul McLean5c477aa2014-08-20 16:47:57 -0700401
François Gaffie11d30102018-11-02 16:09:09 +0100402 ALOGV("%s() disconnecting input device %s", __func__, device->toString().c_str());
Paul McLean5c477aa2014-08-20 16:47:57 -0700403
404 // Set Disconnect to HALs
François Gaffie11d30102018-11-02 16:09:09 +0100405 broadcastDeviceConnectionState(device, state);
Paul McLean5c477aa2014-08-20 16:47:57 -0700406
François Gaffie11d30102018-11-02 16:09:09 +0100407 mAvailableInputDevices.remove(device);
Eric Laurent0dd51852019-04-19 18:18:58 -0700408
409 checkInputsForDevice(device, state);
Kriti Dangef6be8f2020-11-05 11:58:19 +0100410
411 // remove device from mReportedFormatsMap cache
412 mReportedFormatsMap.erase(device);
Eric Laurentd4692962014-05-05 18:13:44 -0700413 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700414
415 default:
François Gaffie11d30102018-11-02 16:09:09 +0100416 ALOGE("%s() invalid state: %x", __func__, state);
Eric Laurente552edb2014-03-10 17:42:56 -0700417 return BAD_VALUE;
418 }
419
Eric Laurent736a1022019-03-27 18:28:46 -0700420 // Propagate device availability to Engine
421 setEngineDeviceConnectionState(device, state);
422
Eric Laurent0dd51852019-04-19 18:18:58 -0700423 checkCloseInputs();
Eric Laurent5f5fca52016-08-04 11:48:57 -0700424 // As the input device list can impact the output device selection, update
425 // getDeviceForStrategy() cache
426 updateDevicesAndOutputs();
Eric Laurente552edb2014-03-10 17:42:56 -0700427
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100428 (void)updateCallRouting(false /*fromCache*/);
Francois Gaffiea0e5c992020-09-29 16:05:07 +0200429 // Reconnect Audio Source
430 for (const auto &strategy : mEngine->getOrderedProductStrategies()) {
431 auto attributes = mEngine->getAllAttributesForProductStrategy(strategy).front();
432 checkAudioSourceForAttributes(attributes);
433 }
Eric Laurentd60560a2015-04-10 11:31:20 -0700434 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
François Gaffie11d30102018-11-02 16:09:09 +0100435 cleanUpForDevice(device);
Eric Laurentd60560a2015-04-10 11:31:20 -0700436 }
437
Eric Laurentb52c1522014-05-20 11:27:36 -0700438 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -0700439 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700440 } // end if is input device
Eric Laurente552edb2014-03-10 17:42:56 -0700441
François Gaffie11d30102018-11-02 16:09:09 +0100442 ALOGW("%s() invalid device: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700443 return BAD_VALUE;
444}
445
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100446status_t AudioPolicyManager::deviceToAudioPort(audio_devices_t device, const char* device_address,
447 const char* device_name,
448 media::AudioPort* aidlPort) {
449 DeviceDescriptorBase devDescr(device, device_address);
450 devDescr.setName(device_name);
451 return devDescr.writeToParcelable(aidlPort);
452}
453
Eric Laurent736a1022019-03-27 18:28:46 -0700454void AudioPolicyManager::setEngineDeviceConnectionState(const sp<DeviceDescriptor> device,
455 audio_policy_dev_state_t state) {
456
457 // the Engine does not have to know about remote submix devices used by dynamic audio policies
458 if (audio_is_remote_submix_device(device->type()) && device->address() != "0") {
459 return;
460 }
461 mEngine->setDeviceConnectionState(device, state);
462}
463
464
Eric Laurente0720872014-03-11 09:30:41 -0700465audio_policy_dev_state_t AudioPolicyManager::getDeviceConnectionState(audio_devices_t device,
François Gaffie53615e22015-03-19 09:24:12 +0100466 const char *device_address)
Eric Laurente552edb2014-03-10 17:42:56 -0700467{
Eric Laurent634b7142016-04-20 13:48:02 -0700468 sp<DeviceDescriptor> devDesc =
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800469 mHwModules.getDeviceDescriptor(device, device_address, "", AUDIO_FORMAT_DEFAULT,
470 false /* allowToCreate */,
Eric Laurent634b7142016-04-20 13:48:02 -0700471 (strlen(device_address) != 0)/*matchAddress*/);
472
473 if (devDesc == 0) {
François Gaffie251c7f02018-11-07 10:41:08 +0100474 ALOGV("getDeviceConnectionState() undeclared device, type %08x, address: %s",
Eric Laurent634b7142016-04-20 13:48:02 -0700475 device, device_address);
476 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
477 }
François Gaffie53615e22015-03-19 09:24:12 +0100478
Eric Laurent3a4311c2014-03-17 12:00:47 -0700479 DeviceVector *deviceVector;
480
Eric Laurente552edb2014-03-10 17:42:56 -0700481 if (audio_is_output_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700482 deviceVector = &mAvailableOutputDevices;
Eric Laurente552edb2014-03-10 17:42:56 -0700483 } else if (audio_is_input_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700484 deviceVector = &mAvailableInputDevices;
485 } else {
François Gaffie11d30102018-11-02 16:09:09 +0100486 ALOGW("%s() invalid device type %08x", __func__, device);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700487 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurente552edb2014-03-10 17:42:56 -0700488 }
Eric Laurent634b7142016-04-20 13:48:02 -0700489
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800490 return (deviceVector->getDevice(
491 device, String8(device_address), AUDIO_FORMAT_DEFAULT) != 0) ?
Eric Laurent634b7142016-04-20 13:48:02 -0700492 AUDIO_POLICY_DEVICE_STATE_AVAILABLE : AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurenta1d525f2015-01-29 13:36:45 -0800493}
494
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800495status_t AudioPolicyManager::handleDeviceConfigChange(audio_devices_t device,
496 const char *device_address,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800497 const char *device_name,
498 audio_format_t encodedFormat)
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800499{
500 status_t status;
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700501 String8 reply;
502 AudioParameter param;
503 int isReconfigA2dpSupported = 0;
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800504
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800505 ALOGV("handleDeviceConfigChange(() device: 0x%X, address %s name %s encodedFormat: 0x%X",
506 device, device_address, device_name, encodedFormat);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800507
Pavlin Radoslavovc694ff42017-01-09 23:27:29 -0800508 // connect/disconnect only 1 device at a time
509 if (!audio_is_output_device(device) && !audio_is_input_device(device)) return BAD_VALUE;
510
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800511 // Check if the device is currently connected
jiabin9a3361e2019-10-01 09:38:30 -0700512 DeviceVector deviceList = mAvailableOutputDevices.getDevicesFromType(device);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800513 if (deviceList.empty()) {
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800514 // Nothing to do: device is not connected
515 return NO_ERROR;
516 }
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800517 sp<DeviceDescriptor> devDesc = deviceList.itemAt(0);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800518
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700519 // For offloaded A2DP, Hw modules may have the capability to
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800520 // configure codecs.
521 // Handle two specific cases by sending a set parameter to
522 // configure A2DP codecs. No need to toggle device state.
523 // Case 1: A2DP active device switches from primary to primary
524 // module
525 // Case 2: A2DP device config changes on primary module.
Francois Gaffiebce7cd42020-10-14 16:13:20 +0200526 if (audio_is_a2dp_out_device(device) && hasPrimaryOutput()) {
jiabin9a3361e2019-10-01 09:38:30 -0700527 sp<HwModule> module = mHwModules.getModuleForDeviceType(device, encodedFormat);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800528 audio_module_handle_t primaryHandle = mPrimaryOutput->getModuleHandle();
529 if (availablePrimaryOutputDevices().contains(devDesc) &&
530 (module != 0 && module->getHandle() == primaryHandle)) {
531 reply = mpClientInterface->getParameters(
532 AUDIO_IO_HANDLE_NONE,
533 String8(AudioParameter::keyReconfigA2dpSupported));
534 AudioParameter repliedParameters(reply);
535 repliedParameters.getInt(
536 String8(AudioParameter::keyReconfigA2dpSupported), isReconfigA2dpSupported);
537 if (isReconfigA2dpSupported) {
538 const String8 key(AudioParameter::keyReconfigA2dp);
539 param.add(key, String8("true"));
540 mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString());
541 devDesc->setEncodedFormat(encodedFormat);
542 return NO_ERROR;
543 }
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700544 }
545 }
cnx421bd2dcc42020-07-11 14:58:44 +0800546 auto musicStrategy = streamToStrategy(AUDIO_STREAM_MUSIC);
547 for (size_t i = 0; i < mOutputs.size(); i++) {
548 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
549 // mute media strategies and delay device switch by the largest
550 // This avoid sending the music tail into the earpiece or headset.
551 setStrategyMute(musicStrategy, true, desc);
552 setStrategyMute(musicStrategy, false, desc, MUTE_TIME_MS,
553 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
554 nullptr, true /*fromCache*/).types());
555 }
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800556 // Toggle the device state: UNAVAILABLE -> AVAILABLE
557 // This will force reading again the device configuration
558 status = setDeviceConnectionState(device,
559 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800560 device_address, device_name,
561 devDesc->getEncodedFormat());
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800562 if (status != NO_ERROR) {
563 ALOGW("handleDeviceConfigChange() error disabling connection state: %d",
564 status);
565 return status;
566 }
567
568 status = setDeviceConnectionState(device,
569 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800570 device_address, device_name, encodedFormat);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800571 if (status != NO_ERROR) {
572 ALOGW("handleDeviceConfigChange() error enabling connection state: %d",
573 status);
574 return status;
575 }
576
577 return NO_ERROR;
578}
579
Pattydd807582021-11-04 21:01:03 +0800580status_t AudioPolicyManager::getHwOffloadFormatsSupportedForBluetoothMedia(
581 audio_devices_t device, std::vector<audio_format_t> *formats)
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800582{
Pattydd807582021-11-04 21:01:03 +0800583 ALOGV("getHwOffloadFormatsSupportedForBluetoothMedia()");
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800584 status_t status = NO_ERROR;
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800585 std::unordered_set<audio_format_t> formatSet;
586 sp<HwModule> primaryModule =
587 mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_PRIMARY);
Aniket Kumar Latafedb5982019-07-03 11:20:36 -0700588 if (primaryModule == nullptr) {
589 ALOGE("%s() unable to get primary module", __func__);
590 return NO_INIT;
591 }
Pattydd807582021-11-04 21:01:03 +0800592
593 DeviceTypeSet audioDeviceSet;
594
595 switch(device) {
596 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP:
597 audioDeviceSet = getAudioDeviceOutAllA2dpSet();
598 break;
599 case AUDIO_DEVICE_OUT_BLE_HEADSET:
600 audioDeviceSet = getAudioDeviceOutAllBleSet();
601 break;
602 default:
603 ALOGE("%s() device type 0x%08x not supported", __func__, device);
604 return BAD_VALUE;
605 }
606
jiabin9a3361e2019-10-01 09:38:30 -0700607 DeviceVector declaredDevices = primaryModule->getDeclaredDevices().getDevicesFromTypes(
Pattydd807582021-11-04 21:01:03 +0800608 audioDeviceSet);
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800609 for (const auto& device : declaredDevices) {
610 formatSet.insert(device->encodedFormats().begin(), device->encodedFormats().end());
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800611 }
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800612 formats->assign(formatSet.begin(), formatSet.end());
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800613 return status;
614}
615
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100616DeviceVector AudioPolicyManager::selectBestRxSinkDevicesForCall(bool fromCache)
617{
618 DeviceVector rxSinkdevices{};
619 rxSinkdevices = mEngine->getOutputDevicesForAttributes(
620 attributes_initializer(AUDIO_USAGE_VOICE_COMMUNICATION), nullptr, fromCache);
621 if (!rxSinkdevices.isEmpty() && mAvailableOutputDevices.contains(rxSinkdevices.itemAt(0))) {
622 auto rxSinkDevice = rxSinkdevices.itemAt(0);
623 auto telephonyRxModule = mHwModules.getModuleForDeviceType(
624 AUDIO_DEVICE_IN_TELEPHONY_RX, AUDIO_FORMAT_DEFAULT);
625 // retrieve Rx Source device descriptor
626 sp<DeviceDescriptor> rxSourceDevice = mAvailableInputDevices.getDevice(
627 AUDIO_DEVICE_IN_TELEPHONY_RX, String8(), AUDIO_FORMAT_DEFAULT);
628
629 // RX Telephony and Rx sink devices are declared by Primary Audio HAL
630 if (isPrimaryModule(telephonyRxModule) && (telephonyRxModule->getHalVersionMajor() >= 3) &&
631 telephonyRxModule->supportsPatch(rxSourceDevice, rxSinkDevice)) {
632 ALOGW("%s() device %s using HW Bridge", __func__, rxSinkDevice->toString().c_str());
633 return DeviceVector(rxSinkDevice);
634 }
635 }
636 // Note that despite the fact that getNewOutputDevices() is called on the primary output,
637 // the device returned is not necessarily reachable via this output
638 // (filter later by setOutputDevices())
639 return getNewOutputDevices(mPrimaryOutput, fromCache);
640}
641
642status_t AudioPolicyManager::updateCallRouting(bool fromCache, uint32_t delayMs, uint32_t *waitMs)
643{
644 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL && hasPrimaryOutput()) {
645 DeviceVector rxDevices = selectBestRxSinkDevicesForCall(fromCache);
646 return updateCallRoutingInternal(rxDevices, delayMs, waitMs);
647 }
648 return INVALID_OPERATION;
649}
650
651status_t AudioPolicyManager::updateCallRoutingInternal(
652 const DeviceVector &rxDevices, uint32_t delayMs, uint32_t *waitMs)
Eric Laurentc2730ba2014-07-20 15:47:07 -0700653{
654 bool createTxPatch = false;
François Gaffie9eb18552018-11-05 10:33:26 +0100655 bool createRxPatch = false;
Eric Laurentdc462862016-07-19 12:29:53 -0700656 uint32_t muteWaitMs = 0;
jiabin9a3361e2019-10-01 09:38:30 -0700657 if(!hasPrimaryOutput() ||
658 mPrimaryOutput->devices().onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_STUB)) {
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100659 return INVALID_OPERATION;
Eric Laurent87ffa392015-05-22 10:32:38 -0700660 }
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100661 ALOG_ASSERT(!rxDevices.isEmpty(), "%s() no selected output device", __func__);
François Gaffie11d30102018-11-02 16:09:09 +0100662
Francois Gaffie716e1432019-01-14 16:58:59 +0100663 audio_attributes_t attr = { .source = AUDIO_SOURCE_VOICE_COMMUNICATION };
François Gaffiec005e562018-11-06 15:04:49 +0100664 auto txSourceDevice = mEngine->getInputDeviceForAttributes(attr);
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100665 ALOG_ASSERT(txSourceDevice != 0, "%s() input selected device not available", __func__);
François Gaffiec005e562018-11-06 15:04:49 +0100666
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100667 ALOGV("%s device rxDevice %s txDevice %s", __func__,
François Gaffie9eb18552018-11-05 10:33:26 +0100668 rxDevices.itemAt(0)->toString().c_str(), txSourceDevice->toString().c_str());
Eric Laurentc2730ba2014-07-20 15:47:07 -0700669
Francois Gaffie601801d2021-06-22 13:27:39 +0200670 disconnectTelephonyAudioSource(mCallRxSourceClient);
671 disconnectTelephonyAudioSource(mCallTxSourceClient);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700672
François Gaffie9eb18552018-11-05 10:33:26 +0100673 auto telephonyRxModule =
jiabin9a3361e2019-10-01 09:38:30 -0700674 mHwModules.getModuleForDeviceType(AUDIO_DEVICE_IN_TELEPHONY_RX, AUDIO_FORMAT_DEFAULT);
François Gaffie9eb18552018-11-05 10:33:26 +0100675 auto telephonyTxModule =
jiabin9a3361e2019-10-01 09:38:30 -0700676 mHwModules.getModuleForDeviceType(AUDIO_DEVICE_OUT_TELEPHONY_TX, AUDIO_FORMAT_DEFAULT);
François Gaffie9eb18552018-11-05 10:33:26 +0100677 // retrieve Rx Source and Tx Sink device descriptors
678 sp<DeviceDescriptor> rxSourceDevice =
679 mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_TELEPHONY_RX,
680 String8(),
681 AUDIO_FORMAT_DEFAULT);
682 sp<DeviceDescriptor> txSinkDevice =
683 mAvailableOutputDevices.getDevice(AUDIO_DEVICE_OUT_TELEPHONY_TX,
684 String8(),
685 AUDIO_FORMAT_DEFAULT);
686
687 // RX and TX Telephony device are declared by Primary Audio HAL
688 if (isPrimaryModule(telephonyRxModule) && isPrimaryModule(telephonyTxModule) &&
689 (telephonyRxModule->getHalVersionMajor() >= 3)) {
690 if (rxSourceDevice == 0 || txSinkDevice == 0) {
691 // RX / TX Telephony device(s) is(are) not currently available
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100692 ALOGE("%s() no telephony Tx and/or RX device", __func__);
693 return INVALID_OPERATION;
François Gaffie9eb18552018-11-05 10:33:26 +0100694 }
François Gaffieafd4cea2019-11-18 15:50:22 +0100695 // createAudioPatchInternal now supports both HW / SW bridging
696 createRxPatch = true;
697 createTxPatch = true;
François Gaffie9eb18552018-11-05 10:33:26 +0100698 } else {
699 // If the RX device is on the primary HW module, then use legacy routing method for
700 // voice calls via setOutputDevice() on primary output.
701 // Otherwise, create two audio patches for TX and RX path.
702 createRxPatch = !(availablePrimaryOutputDevices().contains(rxDevices.itemAt(0))) &&
703 (rxSourceDevice != 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700704 // If the TX device is also on the primary HW module, setOutputDevice() will take care
705 // of it due to legacy implementation. If not, create a patch.
François Gaffie9eb18552018-11-05 10:33:26 +0100706 createTxPatch = !(availablePrimaryModuleInputDevices().contains(txSourceDevice)) &&
707 (txSinkDevice != 0);
708 }
709 // Use legacy routing method for voice calls via setOutputDevice() on primary output.
710 // Otherwise, create two audio patches for TX and RX path.
711 if (!createRxPatch) {
712 muteWaitMs = setOutputDevices(mPrimaryOutput, rxDevices, true, delayMs);
Eric Laurent8ae73122016-04-12 10:13:29 -0700713 } else { // create RX path audio patch
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200714 connectTelephonyRxAudioSource();
juyuchen2224c5a2019-01-21 12:00:58 +0800715 // If the TX device is on the primary HW module but RX device is
716 // on other HW module, SinkMetaData of telephony input should handle it
717 // assuming the device uses audio HAL V5.0 and above
Eric Laurentc2730ba2014-07-20 15:47:07 -0700718 }
Eric Laurent8ae73122016-04-12 10:13:29 -0700719 if (createTxPatch) { // create TX path audio patch
François Gaffieafd4cea2019-11-18 15:50:22 +0100720 // terminate active capture if on the same HW module as the call TX source device
721 // FIXME: would be better to refine to only inputs whose profile connects to the
722 // call TX device but this information is not in the audio patch and logic here must be
723 // symmetric to the one in startInput()
724 for (const auto& activeDesc : mInputs.getActiveInputs()) {
725 if (activeDesc->hasSameHwModuleAs(txSourceDevice)) {
726 closeActiveClients(activeDesc);
727 }
728 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200729 connectTelephonyTxAudioSource(txSourceDevice, txSinkDevice, delayMs);
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800730 }
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100731 if (waitMs != nullptr) {
732 *waitMs = muteWaitMs;
733 }
734 return NO_ERROR;
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800735}
Eric Laurentc2730ba2014-07-20 15:47:07 -0700736
Mikhail Naganov100f0122018-11-29 11:22:16 -0800737bool AudioPolicyManager::isDeviceOfModule(
738 const sp<DeviceDescriptor>& devDesc, const char *moduleId) const {
739 sp<HwModule> module = mHwModules.getModuleFromName(moduleId);
740 if (module != 0) {
741 return mAvailableOutputDevices.getDevicesFromHwModule(module->getHandle())
742 .indexOf(devDesc) != NAME_NOT_FOUND
743 || mAvailableInputDevices.getDevicesFromHwModule(module->getHandle())
744 .indexOf(devDesc) != NAME_NOT_FOUND;
745 }
746 return false;
747}
748
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200749void AudioPolicyManager::connectTelephonyRxAudioSource()
750{
Francois Gaffie601801d2021-06-22 13:27:39 +0200751 disconnectTelephonyAudioSource(mCallRxSourceClient);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200752 const struct audio_port_config source = {
753 .role = AUDIO_PORT_ROLE_SOURCE, .type = AUDIO_PORT_TYPE_DEVICE,
754 .ext.device.type = AUDIO_DEVICE_IN_TELEPHONY_RX, .ext.device.address = ""
755 };
756 const auto aa = mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL);
Francois Gaffie601801d2021-06-22 13:27:39 +0200757 mCallRxSourceClient = startAudioSourceInternal(&source, &aa, 0/*uid*/);
758 ALOGE_IF(mCallRxSourceClient == nullptr,
759 "%s failed to start Telephony Rx AudioSource", __func__);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200760}
761
Francois Gaffie601801d2021-06-22 13:27:39 +0200762void AudioPolicyManager::disconnectTelephonyAudioSource(sp<SourceClientDescriptor> &clientDesc)
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200763{
Francois Gaffie601801d2021-06-22 13:27:39 +0200764 if (clientDesc == nullptr) {
765 return;
766 }
767 ALOGW_IF(stopAudioSource(clientDesc->portId()) != NO_ERROR,
768 "%s error stopping audio source", __func__);
769 clientDesc.clear();
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200770}
771
772void AudioPolicyManager::connectTelephonyTxAudioSource(
773 const sp<DeviceDescriptor> &srcDevice, const sp<DeviceDescriptor> &sinkDevice,
774 uint32_t delayMs)
775{
Francois Gaffie601801d2021-06-22 13:27:39 +0200776 disconnectTelephonyAudioSource(mCallTxSourceClient);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200777 if (srcDevice == nullptr || sinkDevice == nullptr) {
778 ALOGW("%s could not create patch, invalid sink and/or source device(s)", __func__);
779 return;
780 }
781 PatchBuilder patchBuilder;
782 patchBuilder.addSource(srcDevice).addSink(sinkDevice);
783 ALOGV("%s between source %s and sink %s", __func__,
784 srcDevice->toString().c_str(), sinkDevice->toString().c_str());
Francois Gaffie601801d2021-06-22 13:27:39 +0200785 auto callTxSourceClientPortId = PolicyAudioPort::getNextUniqueId();
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200786 const audio_attributes_t aa = { .source = AUDIO_SOURCE_VOICE_COMMUNICATION };
787 struct audio_port_config source = {};
788 srcDevice->toAudioPortConfig(&source);
Francois Gaffie601801d2021-06-22 13:27:39 +0200789 mCallTxSourceClient = new InternalSourceClientDescriptor(
790 callTxSourceClientPortId, mUidCached, aa, source, srcDevice, sinkDevice,
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200791 mCommunnicationStrategy, toVolumeSource(aa));
792 audio_patch_handle_t patchHandle = AUDIO_PATCH_HANDLE_NONE;
793 status_t status = connectAudioSourceToSink(
Francois Gaffie601801d2021-06-22 13:27:39 +0200794 mCallTxSourceClient, sinkDevice, patchBuilder.patch(), patchHandle, mUidCached,
795 delayMs);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200796 ALOGE_IF(status != NO_ERROR, "%s() error %d creating TX audio patch", __func__, status);
797 if (status == NO_ERROR) {
Francois Gaffie601801d2021-06-22 13:27:39 +0200798 mAudioSources.add(callTxSourceClientPortId, mCallTxSourceClient);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200799 }
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200800}
801
Eric Laurente0720872014-03-11 09:30:41 -0700802void AudioPolicyManager::setPhoneState(audio_mode_t state)
Eric Laurente552edb2014-03-10 17:42:56 -0700803{
804 ALOGV("setPhoneState() state %d", state);
François Gaffie2110e042015-03-24 08:41:51 +0100805 // store previous phone state for management of sonification strategy below
806 int oldState = mEngine->getPhoneState();
807
808 if (mEngine->setPhoneState(state) != NO_ERROR) {
809 ALOGW("setPhoneState() invalid or same state %d", state);
Eric Laurente552edb2014-03-10 17:42:56 -0700810 return;
811 }
François Gaffie2110e042015-03-24 08:41:51 +0100812 /// Opens: can these line be executed after the switch of volume curves???
Eric Laurent63dea1d2015-07-02 17:10:28 -0700813 if (isStateInCall(oldState)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700814 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent63dea1d2015-07-02 17:10:28 -0700815 // force reevaluating accessibility routing when call stops
Eric Laurent2cbe89a2014-12-19 11:49:08 -0800816 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -0700817 }
818
François Gaffie2110e042015-03-24 08:41:51 +0100819 /**
820 * Switching to or from incall state or switching between telephony and VoIP lead to force
821 * routing command.
822 */
Eric Laurent74b71512019-11-06 17:21:57 -0800823 bool force = ((isStateInCall(oldState) != isStateInCall(state))
824 || (isStateInCall(state) && (state != oldState)));
Eric Laurente552edb2014-03-10 17:42:56 -0700825
826 // check for device and output changes triggered by new phone state
Mikhail Naganov37977152018-07-11 15:54:44 -0700827 checkForDeviceAndOutputChanges();
Eric Laurente552edb2014-03-10 17:42:56 -0700828
Eric Laurente552edb2014-03-10 17:42:56 -0700829 int delayMs = 0;
830 if (isStateInCall(state)) {
831 nsecs_t sysTime = systemTime();
François Gaffiec005e562018-11-06 15:04:49 +0100832 auto musicStrategy = streamToStrategy(AUDIO_STREAM_MUSIC);
833 auto sonificationStrategy = streamToStrategy(AUDIO_STREAM_ALARM);
Eric Laurente552edb2014-03-10 17:42:56 -0700834 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700835 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700836 // mute media and sonification strategies and delay device switch by the largest
837 // latency of any output where either strategy is active.
838 // This avoid sending the ring tone or music tail into the earpiece or headset.
François Gaffiec005e562018-11-06 15:04:49 +0100839 if ((desc->isStrategyActive(musicStrategy, SONIFICATION_HEADSET_MUSIC_DELAY, sysTime) ||
840 desc->isStrategyActive(sonificationStrategy, SONIFICATION_HEADSET_MUSIC_DELAY,
841 sysTime)) &&
Eric Laurentc75307b2015-03-17 15:29:32 -0700842 (delayMs < (int)desc->latency()*2)) {
843 delayMs = desc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -0700844 }
François Gaffiec005e562018-11-06 15:04:49 +0100845 setStrategyMute(musicStrategy, true, desc);
846 setStrategyMute(musicStrategy, false, desc, MUTE_TIME_MS,
847 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
848 nullptr, true /*fromCache*/).types());
849 setStrategyMute(sonificationStrategy, true, desc);
850 setStrategyMute(sonificationStrategy, false, desc, MUTE_TIME_MS,
851 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_ALARM),
852 nullptr, true /*fromCache*/).types());
Eric Laurente552edb2014-03-10 17:42:56 -0700853 }
854 }
855
Eric Laurent87ffa392015-05-22 10:32:38 -0700856 if (hasPrimaryOutput()) {
Eric Laurent87ffa392015-05-22 10:32:38 -0700857 if (state == AUDIO_MODE_IN_CALL) {
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100858 (void)updateCallRouting(false /*fromCache*/, delayMs);
Eric Laurent87ffa392015-05-22 10:32:38 -0700859 } else {
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100860 DeviceVector rxDevices = getNewOutputDevices(mPrimaryOutput, false /*fromCache*/);
861 // force routing command to audio hardware when ending call
862 // even if no device change is needed
863 if (isStateInCall(oldState) && rxDevices.isEmpty()) {
864 rxDevices = mPrimaryOutput->devices();
865 }
866 if (oldState == AUDIO_MODE_IN_CALL) {
Francois Gaffie601801d2021-06-22 13:27:39 +0200867 disconnectTelephonyAudioSource(mCallRxSourceClient);
868 disconnectTelephonyAudioSource(mCallTxSourceClient);
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100869 }
François Gaffie11d30102018-11-02 16:09:09 +0100870 setOutputDevices(mPrimaryOutput, rxDevices, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700871 }
Eric Laurentc2730ba2014-07-20 15:47:07 -0700872 }
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700873
874 // reevaluate routing on all outputs in case tracks have been started during the call
875 for (size_t i = 0; i < mOutputs.size(); i++) {
876 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
François Gaffie11d30102018-11-02 16:09:09 +0100877 DeviceVector newDevices = getNewOutputDevices(desc, true /*fromCache*/);
Francois Gaffie601801d2021-06-22 13:27:39 +0200878 if (state != AUDIO_MODE_IN_CALL || (desc != mPrimaryOutput && !isTelephonyRxOrTx(desc))) {
879 bool forceRouting = !newDevices.isEmpty();
880 setOutputDevices(desc, newDevices, forceRouting, 0 /*delayMs*/, nullptr,
881 true /*requiresMuteCheck*/, !forceRouting /*requiresVolumeCheck*/);
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700882 }
883 }
884
Eric Laurente552edb2014-03-10 17:42:56 -0700885 if (isStateInCall(state)) {
886 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent63dea1d2015-07-02 17:10:28 -0700887 // force reevaluating accessibility routing when call starts
888 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -0700889 }
890
891 // Flag that ringtone volume must be limited to music volume until we exit MODE_RINGTONE
François Gaffiec005e562018-11-06 15:04:49 +0100892 mLimitRingtoneVolume = (state == AUDIO_MODE_RINGTONE &&
893 isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY));
Eric Laurente552edb2014-03-10 17:42:56 -0700894}
895
Jean-Michel Trivi887a9ed2015-03-31 18:02:24 -0700896audio_mode_t AudioPolicyManager::getPhoneState() {
897 return mEngine->getPhoneState();
898}
899
Eric Laurente0720872014-03-11 09:30:41 -0700900void AudioPolicyManager::setForceUse(audio_policy_force_use_t usage,
François Gaffie11d30102018-11-02 16:09:09 +0100901 audio_policy_forced_cfg_t config)
Eric Laurente552edb2014-03-10 17:42:56 -0700902{
François Gaffie2110e042015-03-24 08:41:51 +0100903 ALOGV("setForceUse() usage %d, config %d, mPhoneState %d", usage, config, mEngine->getPhoneState());
Eric Laurent8dc87a62017-05-16 19:00:40 -0700904 if (config == mEngine->getForceUse(usage)) {
905 return;
906 }
Eric Laurente552edb2014-03-10 17:42:56 -0700907
François Gaffie2110e042015-03-24 08:41:51 +0100908 if (mEngine->setForceUse(usage, config) != NO_ERROR) {
909 ALOGW("setForceUse() could not set force cfg %d for usage %d", config, usage);
910 return;
Eric Laurente552edb2014-03-10 17:42:56 -0700911 }
François Gaffie2110e042015-03-24 08:41:51 +0100912 bool forceVolumeReeval = (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) ||
913 (usage == AUDIO_POLICY_FORCE_FOR_DOCK) ||
914 (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM);
Eric Laurente552edb2014-03-10 17:42:56 -0700915
916 // check for device and output changes triggered by new force usage
Mikhail Naganov37977152018-07-11 15:54:44 -0700917 checkForDeviceAndOutputChanges();
Phil Burk09bc4612016-02-24 15:58:15 -0800918
Eric Laurent22fcda22019-05-17 16:28:47 -0700919 // force client reconnection to reevaluate flag AUDIO_FLAG_AUDIBILITY_ENFORCED
920 if (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM) {
921 mpClientInterface->invalidateStream(AUDIO_STREAM_SYSTEM);
922 mpClientInterface->invalidateStream(AUDIO_STREAM_ENFORCED_AUDIBLE);
923 }
924
Eric Laurentdc462862016-07-19 12:29:53 -0700925 //FIXME: workaround for truncated touch sounds
926 // to be removed when the problem is handled by system UI
927 uint32_t delayMs = 0;
Eric Laurentdc462862016-07-19 12:29:53 -0700928 if (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) {
929 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
930 }
Jean-Michel Trivi30857152019-11-01 11:04:15 -0700931
932 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Eric Laurent2517af32020-11-25 15:31:27 +0100933 updateInputRouting();
Eric Laurente552edb2014-03-10 17:42:56 -0700934}
935
Eric Laurente0720872014-03-11 09:30:41 -0700936void AudioPolicyManager::setSystemProperty(const char* property, const char* value)
Eric Laurente552edb2014-03-10 17:42:56 -0700937{
938 ALOGV("setSystemProperty() property %s, value %s", property, value);
939}
940
Dorin Drimusecc9f422022-03-09 17:57:40 +0100941// Find an MSD output profile compatible with the parameters passed.
942// When "directOnly" is set, restrict search to profiles for direct outputs.
943sp<IOProfile> AudioPolicyManager::getMsdProfileForOutput(
944 const DeviceVector& devices,
945 uint32_t samplingRate,
946 audio_format_t format,
947 audio_channel_mask_t channelMask,
948 audio_output_flags_t flags,
949 bool directOnly)
950{
951 flags = getRelevantFlags(flags, directOnly);
952
953 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
954 if (msdModule != nullptr) {
955 // for the msd module check if there are patches to the output devices
956 if (msdHasPatchesToAllDevices(devices.toTypeAddrVector())) {
957 HwModuleCollection modules;
958 modules.add(msdModule);
959 return searchCompatibleProfileHwModules(
960 modules, getMsdAudioOutDevices(), samplingRate, format, channelMask,
961 flags, directOnly);
962 }
963 }
964 return nullptr;
965}
966
Michael Chana94fbb22018-04-24 14:31:19 +1000967// Find an output profile compatible with the parameters passed. When "directOnly" is set, restrict
968// search to profiles for direct outputs.
969sp<IOProfile> AudioPolicyManager::getProfileForOutput(
François Gaffie11d30102018-11-02 16:09:09 +0100970 const DeviceVector& devices,
Michael Chana94fbb22018-04-24 14:31:19 +1000971 uint32_t samplingRate,
972 audio_format_t format,
973 audio_channel_mask_t channelMask,
974 audio_output_flags_t flags,
975 bool directOnly)
Eric Laurente552edb2014-03-10 17:42:56 -0700976{
Dorin Drimusecc9f422022-03-09 17:57:40 +0100977 flags = getRelevantFlags(flags, directOnly);
978
979 return searchCompatibleProfileHwModules(
980 mHwModules, devices, samplingRate, format, channelMask, flags, directOnly);
981}
982
983audio_output_flags_t AudioPolicyManager::getRelevantFlags (
984 audio_output_flags_t flags, bool directOnly) {
Michael Chana94fbb22018-04-24 14:31:19 +1000985 if (directOnly) {
Dorin Drimusecc9f422022-03-09 17:57:40 +0100986 // only retain flags that will drive the direct output profile selection
987 // if explicitly requested
988 static const uint32_t kRelevantFlags =
Michael Chana94fbb22018-04-24 14:31:19 +1000989 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD |
Dorin Drimusecc9f422022-03-09 17:57:40 +0100990 AUDIO_OUTPUT_FLAG_VOIP_RX | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ);
991 flags = (audio_output_flags_t)((flags & kRelevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
Michael Chana94fbb22018-04-24 14:31:19 +1000992 }
Dorin Drimusecc9f422022-03-09 17:57:40 +0100993 return flags;
994}
Eric Laurent861a6282015-05-18 15:40:16 -0700995
Dorin Drimusecc9f422022-03-09 17:57:40 +0100996sp<IOProfile> AudioPolicyManager::searchCompatibleProfileHwModules (
997 const HwModuleCollection& hwModules,
998 const DeviceVector& devices,
999 uint32_t samplingRate,
1000 audio_format_t format,
1001 audio_channel_mask_t channelMask,
1002 audio_output_flags_t flags,
1003 bool directOnly) {
Eric Laurent861a6282015-05-18 15:40:16 -07001004 sp<IOProfile> profile;
Dorin Drimusecc9f422022-03-09 17:57:40 +01001005 for (const auto& hwModule : hwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08001006 for (const auto& curProfile : hwModule->getOutputProfiles()) {
Dorin Drimusecc9f422022-03-09 17:57:40 +01001007 if (!curProfile->isCompatibleProfile(devices,
1008 samplingRate, NULL /*updatedSamplingRate*/,
1009 format, NULL /*updatedFormat*/,
1010 channelMask, NULL /*updatedChannelMask*/,
1011 flags)) {
1012 continue;
1013 }
1014 // reject profiles not corresponding to a device currently available
1015 if (!mAvailableOutputDevices.containsAtLeastOne(curProfile->getSupportedDevices())) {
1016 continue;
1017 }
1018 // reject profiles if connected device does not support codec
1019 if (!curProfile->devicesSupportEncodedFormats(devices.types())) {
1020 continue;
1021 }
1022 if (!directOnly) {
1023 return curProfile;
1024 }
1025
1026 // when searching for direct outputs, if several profiles are compatible, give priority
1027 // to one with offload capability
1028 if (profile != 0 &&
1029 ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0)) {
Eric Laurent861a6282015-05-18 15:40:16 -07001030 continue;
Dorin Drimusecc9f422022-03-09 17:57:40 +01001031 }
1032 profile = curProfile;
1033 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1034 break;
1035 }
Eric Laurente552edb2014-03-10 17:42:56 -07001036 }
1037 }
Eric Laurent861a6282015-05-18 15:40:16 -07001038 return profile;
Eric Laurente552edb2014-03-10 17:42:56 -07001039}
1040
Eric Laurentfa0f6742021-08-17 18:39:44 +02001041sp<IOProfile> AudioPolicyManager::getSpatializerOutputProfile(
Eric Laurent39095982021-08-24 18:29:27 +02001042 const audio_config_t *config __unused, const AudioDeviceTypeAddrVector &devices) const
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001043{
1044 for (const auto& hwModule : mHwModules) {
1045 for (const auto& curProfile : hwModule->getOutputProfiles()) {
Eric Laurent1c5e2e32021-08-18 18:50:28 +02001046 if (curProfile->getFlags() != AUDIO_OUTPUT_FLAG_SPATIALIZER) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001047 continue;
1048 }
1049 // reject profiles not corresponding to a device currently available
1050 DeviceVector supportedDevices = curProfile->getSupportedDevices();
1051 if (!mAvailableOutputDevices.containsAtLeastOne(supportedDevices)) {
1052 continue;
1053 }
1054 if (!devices.empty()) {
1055 if (supportedDevices.getDevicesFromDeviceTypeAddrVec(devices).size()
1056 != devices.size()) {
1057 continue;
1058 }
1059 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001060 ALOGV("%s found profile %s", __func__, curProfile->getName().c_str());
1061 return curProfile;
1062 }
1063 }
1064 return nullptr;
1065}
1066
Eric Laurentf4e63452017-11-06 19:31:46 +00001067audio_io_handle_t AudioPolicyManager::getOutput(audio_stream_type_t stream)
Eric Laurente552edb2014-03-10 17:42:56 -07001068{
François Gaffiec005e562018-11-06 15:04:49 +01001069 DeviceVector devices = mEngine->getOutputDevicesForStream(stream, false /*fromCache*/);
Andy Hungc9901522017-11-10 20:07:54 -08001070
1071 // Note that related method getOutputForAttr() uses getOutputForDevice() not selectOutput().
1072 // We use selectOutput() here since we don't have the desired AudioTrack sample rate,
1073 // format, flags, etc. This may result in some discrepancy for functions that utilize
1074 // getOutput() solely on audio_stream_type such as AudioSystem::getOutputFrameCount()
1075 // and AudioSystem::getOutputSamplingRate().
1076
François Gaffie11d30102018-11-02 16:09:09 +01001077 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurent16c66dd2019-05-01 17:54:10 -07001078 const audio_io_handle_t output = selectOutput(outputs);
Eric Laurente552edb2014-03-10 17:42:56 -07001079
François Gaffie11d30102018-11-02 16:09:09 +01001080 ALOGV("getOutput() stream %d selected devices %s, output %d", stream,
1081 devices.toString().c_str(), output);
Eric Laurentf4e63452017-11-06 19:31:46 +00001082 return output;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001083}
1084
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001085status_t AudioPolicyManager::getAudioAttributes(audio_attributes_t *dstAttr,
1086 const audio_attributes_t *srcAttr,
1087 audio_stream_type_t srcStream)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001088{
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001089 if (srcAttr != NULL) {
1090 if (!isValidAttributes(srcAttr)) {
1091 ALOGE("%s invalid attributes: usage=%d content=%d flags=0x%x tags=[%s]",
1092 __func__,
1093 srcAttr->usage, srcAttr->content_type, srcAttr->flags,
1094 srcAttr->tags);
1095 return BAD_VALUE;
1096 }
1097 *dstAttr = *srcAttr;
1098 } else {
1099 if (srcStream < AUDIO_STREAM_MIN || srcStream >= AUDIO_STREAM_PUBLIC_CNT) {
1100 ALOGE("%s: invalid stream type", __func__);
1101 return BAD_VALUE;
1102 }
François Gaffiec005e562018-11-06 15:04:49 +01001103 *dstAttr = mEngine->getAttributesForStreamType(srcStream);
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001104 }
Eric Laurent22fcda22019-05-17 16:28:47 -07001105
1106 // Only honor audibility enforced when required. The client will be
1107 // forced to reconnect if the forced usage changes.
1108 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Mikhail Naganov55773032020-10-01 15:08:13 -07001109 dstAttr->flags = static_cast<audio_flags_mask_t>(
1110 dstAttr->flags & ~AUDIO_FLAG_AUDIBILITY_ENFORCED);
Eric Laurent22fcda22019-05-17 16:28:47 -07001111 }
1112
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001113 return NO_ERROR;
1114}
1115
Kevin Rocard153f92d2018-12-18 18:33:28 -08001116status_t AudioPolicyManager::getOutputForAttrInt(
1117 audio_attributes_t *resultAttr,
1118 audio_io_handle_t *output,
1119 audio_session_t session,
1120 const audio_attributes_t *attr,
1121 audio_stream_type_t *stream,
1122 uid_t uid,
1123 const audio_config_t *config,
1124 audio_output_flags_t *flags,
1125 audio_port_handle_t *selectedDeviceId,
1126 bool *isRequestedDeviceForExclusiveUse,
Eric Laurentc529cf62020-04-17 18:19:10 -07001127 std::vector<sp<AudioPolicyMix>> *secondaryMixes,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001128 output_type_t *outputType,
1129 bool *isSpatialized)
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001130{
François Gaffiec005e562018-11-06 15:04:49 +01001131 DeviceVector outputDevices;
Francois Gaffie716e1432019-01-14 16:58:59 +01001132 const audio_port_handle_t requestedPortId = *selectedDeviceId;
François Gaffie11d30102018-11-02 16:09:09 +01001133 DeviceVector msdDevices = getMsdAudioOutDevices();
François Gaffiec005e562018-11-06 15:04:49 +01001134 const sp<DeviceDescriptor> requestedDevice =
1135 mAvailableOutputDevices.getDeviceFromId(requestedPortId);
1136
Eric Laurent8a1095a2019-11-08 14:44:16 -08001137 *outputType = API_OUTPUT_INVALID;
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001138 *isSpatialized = false;
1139
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001140 status_t status = getAudioAttributes(resultAttr, attr, *stream);
1141 if (status != NO_ERROR) {
1142 return status;
Eric Laurent8f42ea12018-08-08 09:08:25 -07001143 }
Kevin Rocardb99cc752019-03-21 20:52:24 -07001144 if (auto it = mAllowedCapturePolicies.find(uid); it != end(mAllowedCapturePolicies)) {
Mikhail Naganov55773032020-10-01 15:08:13 -07001145 resultAttr->flags = static_cast<audio_flags_mask_t>(resultAttr->flags | it->second);
Kevin Rocardb99cc752019-03-21 20:52:24 -07001146 }
François Gaffiec005e562018-11-06 15:04:49 +01001147 *stream = mEngine->getStreamTypeForAttributes(*resultAttr);
Eric Laurent8f42ea12018-08-08 09:08:25 -07001148
François Gaffiec005e562018-11-06 15:04:49 +01001149 ALOGV("%s() attributes=%s stream=%s session %d selectedDeviceId %d", __func__,
1150 toString(*resultAttr).c_str(), toString(*stream).c_str(), session, requestedPortId);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001151
Kevin Rocard153f92d2018-12-18 18:33:28 -08001152 // The primary output is the explicit routing (eg. setPreferredDevice) if specified,
1153 // otherwise, fallback to the dynamic policies, if none match, query the engine.
1154 // Secondary outputs are always found by dynamic policies as the engine do not support them
Eric Laurentc529cf62020-04-17 18:19:10 -07001155 sp<AudioPolicyMix> primaryMix;
1156 status = mPolicyMixes.getOutputForAttr(*resultAttr, uid, *flags, primaryMix, secondaryMixes);
Kevin Rocard94114a22019-04-01 19:38:23 -07001157 if (status != OK) {
1158 return status;
Kevin Rocard153f92d2018-12-18 18:33:28 -08001159 }
Kevin Rocard94114a22019-04-01 19:38:23 -07001160
Kevin Rocard153f92d2018-12-18 18:33:28 -08001161 // Explicit routing is higher priority then any dynamic policy primary output
Eric Laurentc529cf62020-04-17 18:19:10 -07001162 bool usePrimaryOutputFromPolicyMixes = requestedDevice == nullptr && primaryMix != nullptr;
Kevin Rocard153f92d2018-12-18 18:33:28 -08001163
1164 // FIXME: in case of RENDER policy, the output capabilities should be checked
Eric Laurentc529cf62020-04-17 18:19:10 -07001165 if ((usePrimaryOutputFromPolicyMixes
1166 || (secondaryMixes != nullptr && !secondaryMixes->empty()))
Kevin Rocardc2afbdf2019-01-31 18:18:06 -08001167 && !audio_is_linear_pcm(config->format)) {
1168 ALOGD("%s: rejecting request as dynamic audio policy only support pcm", __func__);
Kevin Rocard153f92d2018-12-18 18:33:28 -08001169 return BAD_VALUE;
1170 }
1171 if (usePrimaryOutputFromPolicyMixes) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001172 sp<DeviceDescriptor> deviceDesc =
1173 mAvailableOutputDevices.getDevice(primaryMix->mDeviceType,
1174 primaryMix->mDeviceAddress,
1175 AUDIO_FORMAT_DEFAULT);
1176 sp<SwAudioOutputDescriptor> policyDesc = primaryMix->getOutput();
Eric Laurentc64e0ab2020-04-30 15:59:34 -07001177 if (deviceDesc != nullptr
1178 && (policyDesc == nullptr || (policyDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT))) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001179 audio_io_handle_t newOutput;
1180 status = openDirectOutput(
1181 *stream, session, config,
1182 (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT),
1183 DeviceVector(deviceDesc), &newOutput);
1184 if (status != NO_ERROR) {
1185 policyDesc = nullptr;
1186 } else {
1187 policyDesc = mOutputs.valueFor(newOutput);
1188 primaryMix->setOutput(policyDesc);
1189 }
1190 }
1191 if (policyDesc != nullptr) {
1192 policyDesc->mPolicyMix = primaryMix;
1193 *output = policyDesc->mIoHandle;
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08001194 *selectedDeviceId = deviceDesc != 0 ? deviceDesc->getId() : AUDIO_PORT_HANDLE_NONE;
Eric Laurent8a1095a2019-11-08 14:44:16 -08001195
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08001196 ALOGV("getOutputForAttr() returns output %d", *output);
1197 if (resultAttr->usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
1198 *outputType = API_OUT_MIX_PLAYBACK;
1199 } else {
1200 *outputType = API_OUTPUT_LEGACY;
1201 }
1202 return NO_ERROR;
Eric Laurent8a1095a2019-11-08 14:44:16 -08001203 }
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001204 }
François Gaffiec005e562018-11-06 15:04:49 +01001205 // Virtual sources must always be dynamicaly or explicitly routed
1206 if (resultAttr->usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
1207 ALOGW("getOutputForAttr() no policy mix found for usage AUDIO_USAGE_VIRTUAL_SOURCE");
1208 return BAD_VALUE;
1209 }
1210 // explicit routing managed by getDeviceForStrategy in APM is now handled by engine
1211 // in order to let the choice of the order to future vendor engine
1212 outputDevices = mEngine->getOutputDevicesForAttributes(*resultAttr, requestedDevice, false);
Scott Randolph7b1fd232018-06-18 15:33:03 -07001213
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001214 if ((resultAttr->flags & AUDIO_FLAG_HW_AV_SYNC) != 0) {
Nadav Bar766fb022018-01-07 12:18:03 +02001215 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
Eric Laurent93c3d412014-08-01 14:48:35 -07001216 }
1217
Nadav Barb2f18162018-07-18 13:01:53 +03001218 // Set incall music only if device was explicitly set, and fallback to the device which is
1219 // chosen by the engine if not.
1220 // FIXME: provide a more generic approach which is not device specific and move this back
1221 // to getOutputForDevice.
Nadav Bar20919492018-11-20 10:20:51 +02001222 // TODO: Remove check of AUDIO_STREAM_MUSIC once migration is completed on the app side.
jiabin9a3361e2019-10-01 09:38:30 -07001223 if (outputDevices.onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_TELEPHONY_TX) &&
François Gaffiec005e562018-11-06 15:04:49 +01001224 (*stream == AUDIO_STREAM_MUSIC || resultAttr->usage == AUDIO_USAGE_VOICE_COMMUNICATION) &&
Nadav Barb2f18162018-07-18 13:01:53 +03001225 audio_is_linear_pcm(config->format) &&
Eric Laurent74b71512019-11-06 17:21:57 -08001226 isCallAudioAccessible()) {
Francois Gaffie716e1432019-01-14 16:58:59 +01001227 if (requestedPortId != AUDIO_PORT_HANDLE_NONE) {
Nadav Barb2f18162018-07-18 13:01:53 +03001228 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_INCALL_MUSIC;
François Gaffief579db52018-11-13 11:25:16 +01001229 *isRequestedDeviceForExclusiveUse = true;
Nadav Barb2f18162018-07-18 13:01:53 +03001230 }
1231 }
1232
François Gaffiec005e562018-11-06 15:04:49 +01001233 ALOGV("%s() device %s, sampling rate %d, format %#x, channel mask %#x, flags %#x stream %s",
1234 __func__, outputDevices.toString().c_str(), config->sample_rate, config->format,
1235 config->channel_mask, *flags, toString(*stream).c_str());
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001236
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001237 *output = AUDIO_IO_HANDLE_NONE;
François Gaffie11d30102018-11-02 16:09:09 +01001238 if (!msdDevices.isEmpty()) {
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001239 *output = getOutputForDevices(msdDevices, session, resultAttr, config, flags, isSpatialized);
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001240 if (*output != AUDIO_IO_HANDLE_NONE && setMsdOutputPatches(&outputDevices) == NO_ERROR) {
François Gaffiec005e562018-11-06 15:04:49 +01001241 ALOGV("%s() Using MSD devices %s instead of devices %s",
1242 __func__, msdDevices.toString().c_str(), outputDevices.toString().c_str());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001243 } else {
1244 *output = AUDIO_IO_HANDLE_NONE;
1245 }
1246 }
1247 if (*output == AUDIO_IO_HANDLE_NONE) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001248 *output = getOutputForDevices(outputDevices, session, resultAttr, config,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001249 flags, isSpatialized, resultAttr->flags & AUDIO_FLAG_MUTE_HAPTIC);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001250 }
Eric Laurente83b55d2014-11-14 10:06:21 -08001251 if (*output == AUDIO_IO_HANDLE_NONE) {
1252 return INVALID_OPERATION;
1253 }
Paul McLeanaa981192015-03-21 09:55:15 -07001254
François Gaffiec005e562018-11-06 15:04:49 +01001255 *selectedDeviceId = getFirstDeviceId(outputDevices);
Michael Chan6fb34492020-12-08 15:44:49 +11001256 for (auto &outputDevice : outputDevices) {
1257 if (outputDevice->getId() == getConfig().getDefaultOutputDevice()->getId()) {
1258 *selectedDeviceId = outputDevice->getId();
1259 break;
1260 }
1261 }
Eric Laurent2ac76942017-06-22 17:17:09 -07001262
Eric Laurent8a1095a2019-11-08 14:44:16 -08001263 if (outputDevices.onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_TELEPHONY_TX)) {
1264 *outputType = API_OUTPUT_TELEPHONY_TX;
1265 } else {
1266 *outputType = API_OUTPUT_LEGACY;
1267 }
1268
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001269 ALOGV("%s returns output %d selectedDeviceId %d", __func__, *output, *selectedDeviceId);
1270
1271 return NO_ERROR;
1272}
1273
1274status_t AudioPolicyManager::getOutputForAttr(const audio_attributes_t *attr,
1275 audio_io_handle_t *output,
1276 audio_session_t session,
1277 audio_stream_type_t *stream,
Svet Ganov3e5f14f2021-05-13 22:51:08 +00001278 const AttributionSourceState& attributionSource,
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001279 const audio_config_t *config,
1280 audio_output_flags_t *flags,
1281 audio_port_handle_t *selectedDeviceId,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001282 audio_port_handle_t *portId,
Eric Laurent8a1095a2019-11-08 14:44:16 -08001283 std::vector<audio_io_handle_t> *secondaryOutputs,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001284 output_type_t *outputType,
1285 bool *isSpatialized)
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001286{
1287 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
1288 if (*portId != AUDIO_PORT_HANDLE_NONE) {
1289 return INVALID_OPERATION;
1290 }
Philip P. Moltmannbda45752020-07-17 16:41:18 -07001291 const uid_t uid = VALUE_OR_RETURN_STATUS(
Svet Ganov3e5f14f2021-05-13 22:51:08 +00001292 aidl2legacy_int32_t_uid_t(attributionSource.uid));
Francois Gaffie716e1432019-01-14 16:58:59 +01001293 const audio_port_handle_t requestedPortId = *selectedDeviceId;
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001294 audio_attributes_t resultAttr;
François Gaffief579db52018-11-13 11:25:16 +01001295 bool isRequestedDeviceForExclusiveUse = false;
Eric Laurentc529cf62020-04-17 18:19:10 -07001296 std::vector<sp<AudioPolicyMix>> secondaryMixes;
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001297 const sp<DeviceDescriptor> requestedDevice =
1298 mAvailableOutputDevices.getDeviceFromId(requestedPortId);
1299
1300 // Prevent from storing invalid requested device id in clients
1301 const audio_port_handle_t sanitizedRequestedPortId =
1302 requestedDevice != nullptr ? requestedPortId : AUDIO_PORT_HANDLE_NONE;
1303 *selectedDeviceId = sanitizedRequestedPortId;
1304
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001305 status_t status = getOutputForAttrInt(&resultAttr, output, session, attr, stream, uid,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001306 config, flags, selectedDeviceId, &isRequestedDeviceForExclusiveUse,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001307 secondaryOutputs != nullptr ? &secondaryMixes : nullptr, outputType, isSpatialized);
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001308 if (status != NO_ERROR) {
1309 return status;
1310 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001311 std::vector<wp<SwAudioOutputDescriptor>> weakSecondaryOutputDescs;
Eric Laurentc529cf62020-04-17 18:19:10 -07001312 if (secondaryOutputs != nullptr) {
1313 for (auto &secondaryMix : secondaryMixes) {
1314 sp<SwAudioOutputDescriptor> outputDesc = secondaryMix->getOutput();
1315 if (outputDesc != nullptr &&
1316 outputDesc->mIoHandle != AUDIO_IO_HANDLE_NONE) {
1317 secondaryOutputs->push_back(outputDesc->mIoHandle);
1318 weakSecondaryOutputDescs.push_back(outputDesc);
1319 }
1320 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001321 }
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001322
Eric Laurent8fc147b2018-07-22 19:13:55 -07001323 audio_config_base_t clientConfig = {.sample_rate = config->sample_rate,
Nick Desaulniersa30e3202019-10-18 13:38:23 -07001324 .channel_mask = config->channel_mask,
Eric Laurent8fc147b2018-07-22 19:13:55 -07001325 .format = config->format,
Nick Desaulniersa30e3202019-10-18 13:38:23 -07001326 };
jiabin4ef93452019-09-10 14:29:54 -07001327 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurent8f42ea12018-08-08 09:08:25 -07001328
Eric Laurentc209fe42020-06-05 18:11:23 -07001329 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(*output);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001330 sp<TrackClientDescriptor> clientDesc =
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001331 new TrackClientDescriptor(*portId, uid, session, resultAttr, clientConfig,
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001332 sanitizedRequestedPortId, *stream,
François Gaffiec005e562018-11-06 15:04:49 +01001333 mEngine->getProductStrategyForAttributes(resultAttr),
François Gaffieaaac0fd2018-11-22 17:56:39 +01001334 toVolumeSource(resultAttr),
Kevin Rocard153f92d2018-12-18 18:33:28 -08001335 *flags, isRequestedDeviceForExclusiveUse,
Eric Laurentc209fe42020-06-05 18:11:23 -07001336 std::move(weakSecondaryOutputDescs),
1337 outputDesc->mPolicyMix);
Andy Hung39efb7a2018-09-26 15:39:28 -07001338 outputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001339
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001340 ALOGV("%s() returns output %d requestedPortId %d selectedDeviceId %d for port ID %d", __func__,
1341 *output, requestedPortId, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07001342
Eric Laurente83b55d2014-11-14 10:06:21 -08001343 return NO_ERROR;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001344}
1345
Eric Laurentc529cf62020-04-17 18:19:10 -07001346status_t AudioPolicyManager::openDirectOutput(audio_stream_type_t stream,
1347 audio_session_t session,
1348 const audio_config_t *config,
1349 audio_output_flags_t flags,
1350 const DeviceVector &devices,
1351 audio_io_handle_t *output) {
1352
1353 *output = AUDIO_IO_HANDLE_NONE;
1354
1355 // skip direct output selection if the request can obviously be attached to a mixed output
1356 // and not explicitly requested
1357 if (((flags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
1358 audio_is_linear_pcm(config->format) && config->sample_rate <= SAMPLE_RATE_HZ_MAX &&
1359 audio_channel_count_from_out_mask(config->channel_mask) <= 2) {
1360 return NAME_NOT_FOUND;
1361 }
1362
1363 // Do not allow offloading if one non offloadable effect is enabled or MasterMono is enabled.
1364 // This prevents creating an offloaded track and tearing it down immediately after start
1365 // when audioflinger detects there is an active non offloadable effect.
1366 // FIXME: We should check the audio session here but we do not have it in this context.
1367 // This may prevent offloading in rare situations where effects are left active by apps
1368 // in the background.
1369 sp<IOProfile> profile;
1370 if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) ||
1371 !(mEffects.isNonOffloadableEffectEnabled() || mMasterMono)) {
1372 profile = getProfileForOutput(
1373 devices, config->sample_rate, config->format, config->channel_mask,
1374 flags, true /* directOnly */);
1375 }
1376
1377 if (profile == nullptr) {
1378 return NAME_NOT_FOUND;
1379 }
1380
1381 // exclusive outputs for MMAP and Offload are enforced by different session ids.
1382 for (size_t i = 0; i < mOutputs.size(); i++) {
1383 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
1384 if (!desc->isDuplicated() && (profile == desc->mProfile)) {
1385 // reuse direct output if currently open by the same client
1386 // and configured with same parameters
1387 if ((config->sample_rate == desc->getSamplingRate()) &&
1388 (config->format == desc->getFormat()) &&
1389 (config->channel_mask == desc->getChannelMask()) &&
1390 (session == desc->mDirectClientSession)) {
1391 desc->mDirectOpenCount++;
Eric Laurentfecbceb2021-02-09 14:46:43 +01001392 ALOGV("%s reusing direct output %d for session %d", __func__,
Eric Laurentc529cf62020-04-17 18:19:10 -07001393 mOutputs.keyAt(i), session);
1394 *output = mOutputs.keyAt(i);
1395 return NO_ERROR;
1396 }
1397 }
1398 }
1399
1400 if (!profile->canOpenNewIo()) {
1401 return NAME_NOT_FOUND;
1402 }
1403
1404 sp<SwAudioOutputDescriptor> outputDesc =
1405 new SwAudioOutputDescriptor(profile, mpClientInterface);
1406
Michael Chan6fb34492020-12-08 15:44:49 +11001407 // An MSD patch may be using the only output stream that can service this request. Release
1408 // all MSD patches to prioritize this request over any active output on MSD.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001409 releaseMsdOutputPatches(devices);
Eric Laurentc529cf62020-04-17 18:19:10 -07001410
Eric Laurentf1f22e72021-07-13 14:04:14 +02001411 status_t status =
1412 outputDesc->open(config, nullptr /* mixerConfig */, devices, stream, flags, output);
Eric Laurentc529cf62020-04-17 18:19:10 -07001413
1414 // only accept an output with the requested parameters
1415 if (status != NO_ERROR ||
1416 (config->sample_rate != 0 && config->sample_rate != outputDesc->getSamplingRate()) ||
1417 (config->format != AUDIO_FORMAT_DEFAULT && config->format != outputDesc->getFormat()) ||
1418 (config->channel_mask != 0 && config->channel_mask != outputDesc->getChannelMask())) {
1419 ALOGV("%s failed opening direct output: output %d sample rate %d %d,"
1420 "format %d %d, channel mask %04x %04x", __func__, *output, config->sample_rate,
1421 outputDesc->getSamplingRate(), config->format, outputDesc->getFormat(),
1422 config->channel_mask, outputDesc->getChannelMask());
1423 if (*output != AUDIO_IO_HANDLE_NONE) {
1424 outputDesc->close();
1425 }
1426 // fall back to mixer output if possible when the direct output could not be open
1427 if (audio_is_linear_pcm(config->format) &&
1428 config->sample_rate <= SAMPLE_RATE_HZ_MAX) {
1429 return NAME_NOT_FOUND;
1430 }
1431 *output = AUDIO_IO_HANDLE_NONE;
1432 return BAD_VALUE;
1433 }
1434 outputDesc->mDirectOpenCount = 1;
1435 outputDesc->mDirectClientSession = session;
1436
1437 addOutput(*output, outputDesc);
1438 mPreviousOutputs = mOutputs;
1439 ALOGV("%s returns new direct output %d", __func__, *output);
1440 mpClientInterface->onAudioPortListUpdate();
1441 return NO_ERROR;
1442}
1443
François Gaffie11d30102018-11-02 16:09:09 +01001444audio_io_handle_t AudioPolicyManager::getOutputForDevices(
1445 const DeviceVector &devices,
Kevin Rocard169753c2017-03-06 14:18:23 -08001446 audio_session_t session,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001447 const audio_attributes_t *attr,
Eric Laurentfe231122017-11-17 17:48:06 -08001448 const audio_config_t *config,
jiabine375d412019-02-26 12:54:53 -08001449 audio_output_flags_t *flags,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001450 bool *isSpatialized,
jiabine375d412019-02-26 12:54:53 -08001451 bool forceMutingHaptic)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001452{
Andy Hungc88b0642018-04-27 15:42:35 -07001453 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001454
jiabine375d412019-02-26 12:54:53 -08001455 // Discard haptic channel mask when forcing muting haptic channels.
1456 audio_channel_mask_t channelMask = forceMutingHaptic
Mikhail Naganov55773032020-10-01 15:08:13 -07001457 ? static_cast<audio_channel_mask_t>(config->channel_mask & ~AUDIO_CHANNEL_HAPTIC_ALL)
1458 : config->channel_mask;
jiabine375d412019-02-26 12:54:53 -08001459
Eric Laurente552edb2014-03-10 17:42:56 -07001460 // open a direct output if required by specified parameters
1461 //force direct flag if offload flag is set: offloading implies a direct output stream
1462 // and all common behaviors are driven by checking only the direct flag
1463 // this should normally be set appropriately in the policy configuration file
Nadav Bar766fb022018-01-07 12:18:03 +02001464 if ((*flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1465 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurente552edb2014-03-10 17:42:56 -07001466 }
Nadav Bar766fb022018-01-07 12:18:03 +02001467 if ((*flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
1468 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent93c3d412014-08-01 14:48:35 -07001469 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001470
1471 audio_stream_type_t stream = mEngine->getStreamTypeForAttributes(*attr);
1472
Eric Laurente83b55d2014-11-14 10:06:21 -08001473 // only allow deep buffering for music stream type
1474 if (stream != AUDIO_STREAM_MUSIC) {
Nadav Bar766fb022018-01-07 12:18:03 +02001475 *flags = (audio_output_flags_t)(*flags &~AUDIO_OUTPUT_FLAG_DEEP_BUFFER);
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -07001476 } else if (/* stream == AUDIO_STREAM_MUSIC && */
Nadav Bar766fb022018-01-07 12:18:03 +02001477 *flags == AUDIO_OUTPUT_FLAG_NONE &&
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -07001478 property_get_bool("audio.deep_buffer.media", false /* default_value */)) {
1479 // use DEEP_BUFFER as default output for music stream type
Nadav Bar766fb022018-01-07 12:18:03 +02001480 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
Eric Laurente83b55d2014-11-14 10:06:21 -08001481 }
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -07001482 if (stream == AUDIO_STREAM_TTS) {
Nadav Bar766fb022018-01-07 12:18:03 +02001483 *flags = AUDIO_OUTPUT_FLAG_TTS;
Haynes Mathew George84c621e2017-04-25 11:41:50 -07001484 } else if (stream == AUDIO_STREAM_VOICE_CALL &&
Nadav Bar20919492018-11-20 10:20:51 +02001485 audio_is_linear_pcm(config->format) &&
1486 (*flags & AUDIO_OUTPUT_FLAG_INCALL_MUSIC) == 0) {
Nadav Bar766fb022018-01-07 12:18:03 +02001487 *flags = (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_VOIP_RX |
Haynes Mathew George84c621e2017-04-25 11:41:50 -07001488 AUDIO_OUTPUT_FLAG_DIRECT);
1489 ALOGV("Set VoIP and Direct output flags for PCM format");
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -07001490 }
Eric Laurente552edb2014-03-10 17:42:56 -07001491
Carter Hsua3abb402021-10-26 11:11:20 +08001492 // Attach the Ultrasound flag for the AUDIO_CONTENT_TYPE_ULTRASOUND
1493 if (attr->content_type == AUDIO_CONTENT_TYPE_ULTRASOUND) {
1494 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_ULTRASOUND);
1495 }
1496
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001497 *isSpatialized = false;
Eric Laurentfa0f6742021-08-17 18:39:44 +02001498 if (mSpatializerOutput != nullptr
Eric Laurentb4f42a92022-01-17 17:37:31 +01001499 && canBeSpatializedInt(attr, config,
1500 devices.toTypeAddrVector(), false /* allowCurrentOutputReconfig */)) {
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001501 *isSpatialized = true;
Eric Laurentfa0f6742021-08-17 18:39:44 +02001502 return mSpatializerOutput->mIoHandle;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001503 }
1504
Eric Laurentc529cf62020-04-17 18:19:10 -07001505 audio_config_t directConfig = *config;
1506 directConfig.channel_mask = channelMask;
1507 status_t status = openDirectOutput(stream, session, &directConfig, *flags, devices, &output);
1508 if (status != NAME_NOT_FOUND) {
Eric Laurente552edb2014-03-10 17:42:56 -07001509 return output;
1510 }
1511
Eric Laurent14cbfca2016-03-17 09:42:16 -07001512 // A request for HW A/V sync cannot fallback to a mixed output because time
1513 // stamps are embedded in audio data
Phil Burk2d059932018-02-15 15:55:11 -08001514 if ((*flags & (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ)) != 0) {
Eric Laurent14cbfca2016-03-17 09:42:16 -07001515 return AUDIO_IO_HANDLE_NONE;
1516 }
1517
Eric Laurente552edb2014-03-10 17:42:56 -07001518 // ignoring channel mask due to downmix capability in mixer
1519
1520 // open a non direct output
1521
1522 // for non direct outputs, only PCM is supported
Eric Laurentfe231122017-11-17 17:48:06 -08001523 if (audio_is_linear_pcm(config->format)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001524 // get which output is suitable for the specified stream. The actual
1525 // routing change will happen when startOutput() will be called
François Gaffie11d30102018-11-02 16:09:09 +01001526 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07001527
Eric Laurent8838a382014-09-08 16:44:28 -07001528 // at this stage we should ignore the DIRECT flag as no direct output could be found earlier
Nadav Bar766fb022018-01-07 12:18:03 +02001529 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
jiabinebb6af42020-06-09 17:31:17 -07001530 output = selectOutput(
1531 outputs, *flags, config->format, channelMask, config->sample_rate, session);
Eric Laurente552edb2014-03-10 17:42:56 -07001532 }
François Gaffie11d30102018-11-02 16:09:09 +01001533 ALOGW_IF((output == 0), "getOutputForDevices() could not find output for stream %d, "
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001534 "sampling rate %d, format %#x, channels %#x, flags %#x",
jiabine375d412019-02-26 12:54:53 -08001535 stream, config->sample_rate, config->format, channelMask, *flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001536
Eric Laurente552edb2014-03-10 17:42:56 -07001537 return output;
1538}
1539
Mikhail Naganovf02f3672018-11-09 12:44:16 -08001540sp<DeviceDescriptor> AudioPolicyManager::getMsdAudioInDevice() const {
François Gaffie11d30102018-11-02 16:09:09 +01001541 auto msdInDevices = mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1542 mAvailableInputDevices);
1543 return msdInDevices.isEmpty()? nullptr : msdInDevices.itemAt(0);
1544}
1545
1546DeviceVector AudioPolicyManager::getMsdAudioOutDevices() const {
1547 return mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1548 mAvailableOutputDevices);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001549}
1550
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001551const AudioPatchCollection AudioPolicyManager::getMsdOutputPatches() const {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001552 AudioPatchCollection msdPatches;
Mikhail Naganov86112352018-10-04 09:02:49 -07001553 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1554 if (msdModule != 0) {
1555 for (size_t i = 0; i < mAudioPatches.size(); ++i) {
1556 sp<AudioPatch> patch = mAudioPatches.valueAt(i);
1557 for (size_t j = 0; j < patch->mPatch.num_sources; ++j) {
1558 const struct audio_port_config *source = &patch->mPatch.sources[j];
1559 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
1560 source->ext.device.hw_module == msdModule->getHandle()) {
François Gaffieafd4cea2019-11-18 15:50:22 +01001561 msdPatches.addAudioPatch(patch->getHandle(), patch);
Mikhail Naganov86112352018-10-04 09:02:49 -07001562 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001563 }
1564 }
1565 }
1566 return msdPatches;
1567}
1568
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02001569bool AudioPolicyManager::isMsdPatch(const audio_patch_handle_t &handle) const {
1570 ssize_t index = mAudioPatches.indexOfKey(handle);
1571 if (index < 0) {
1572 return false;
1573 }
1574 const sp<AudioPatch> patch = mAudioPatches.valueAt(index);
1575 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1576 if (msdModule == nullptr) {
1577 return false;
1578 }
1579 const struct audio_port_config *sink = &patch->mPatch.sinks[0];
1580 if (getMsdAudioOutDevices().contains(mAvailableOutputDevices.getDeviceFromId(sink->id))) {
1581 return true;
1582 }
1583 index = getMsdOutputPatches().indexOfKey(handle);
1584 if (index < 0) {
1585 return false;
1586 }
1587 return true;
1588}
1589
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001590status_t AudioPolicyManager::getMsdProfiles(bool hwAvSync,
1591 const InputProfileCollection &inputProfiles,
1592 const OutputProfileCollection &outputProfiles,
1593 const sp<DeviceDescriptor> &sourceDevice,
1594 const sp<DeviceDescriptor> &sinkDevice,
1595 AudioProfileVector& sourceProfiles,
1596 AudioProfileVector& sinkProfiles) const {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001597 if (inputProfiles.isEmpty()) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001598 ALOGE("%s() no input profiles for source module", __func__);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001599 return NO_INIT;
1600 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001601 if (outputProfiles.isEmpty()) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001602 ALOGE("%s() no output profiles for sink module", __func__);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001603 return NO_INIT;
1604 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001605 for (const auto &inProfile : inputProfiles) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001606 if (hwAvSync == ((inProfile->getFlags() & AUDIO_INPUT_FLAG_HW_AV_SYNC) != 0) &&
1607 inProfile->supportsDevice(sourceDevice)) {
1608 appendAudioProfiles(sourceProfiles, inProfile->getAudioProfiles());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001609 }
1610 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001611 for (const auto &outProfile : outputProfiles) {
Michael Chan6fb34492020-12-08 15:44:49 +11001612 if (hwAvSync == ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) &&
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001613 outProfile->supportsDevice(sinkDevice)) {
1614 appendAudioProfiles(sinkProfiles, outProfile->getAudioProfiles());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001615 }
1616 }
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001617 return NO_ERROR;
1618}
1619
1620status_t AudioPolicyManager::getBestMsdConfig(bool hwAvSync,
1621 const AudioProfileVector &sourceProfiles, const AudioProfileVector &sinkProfiles,
1622 audio_port_config *sourceConfig, audio_port_config *sinkConfig) const
1623{
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001624 struct audio_config_base bestSinkConfig;
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001625 status_t result = findBestMatchingOutputConfig(sourceProfiles, sinkProfiles,
1626 msdCompressedFormatsOrder, msdSurroundChannelMasksOrder,
1627 true /*preferHigherSamplingRates*/, bestSinkConfig);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001628 if (result != NO_ERROR) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001629 ALOGD("%s() no matching config found for sink, hwAvSync: %d",
1630 __func__, hwAvSync);
Greg Kaiser83289652018-07-30 06:13:57 -07001631 return result;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001632 }
1633 sinkConfig->sample_rate = bestSinkConfig.sample_rate;
1634 sinkConfig->channel_mask = bestSinkConfig.channel_mask;
1635 sinkConfig->format = bestSinkConfig.format;
1636 // For encoded streams force direct flag to prevent downstream mixing.
1637 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1638 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_DIRECT);
Dean Wheatley5c9f0832019-11-21 13:39:31 +11001639 if (audio_is_iec61937_compatible(sinkConfig->format)) {
1640 // For formats compatible with IEC61937 encapsulation, assume that
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001641 // the input is IEC61937 framed (for proportional buffer sizing).
Dean Wheatley5c9f0832019-11-21 13:39:31 +11001642 // Add the AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO flag so downstream HAL can distinguish between
1643 // raw and IEC61937 framed streams.
1644 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1645 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO);
1646 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001647 sourceConfig->sample_rate = bestSinkConfig.sample_rate;
1648 // Specify exact channel mask to prevent guessing by bit count in PatchPanel.
1649 sourceConfig->channel_mask = audio_channel_mask_out_to_in(bestSinkConfig.channel_mask);
1650 sourceConfig->format = bestSinkConfig.format;
1651 // Copy input stream directly without any processing (e.g. resampling).
1652 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1653 sourceConfig->flags.input | AUDIO_INPUT_FLAG_DIRECT);
1654 if (hwAvSync) {
1655 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1656 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
1657 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1658 sourceConfig->flags.input | AUDIO_INPUT_FLAG_HW_AV_SYNC);
1659 }
1660 const unsigned int config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE |
1661 AUDIO_PORT_CONFIG_CHANNEL_MASK | AUDIO_PORT_CONFIG_FORMAT | AUDIO_PORT_CONFIG_FLAGS;
1662 sinkConfig->config_mask |= config_mask;
1663 sourceConfig->config_mask |= config_mask;
1664 return NO_ERROR;
1665}
1666
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001667PatchBuilder AudioPolicyManager::buildMsdPatch(bool msdIsSource,
1668 const sp<DeviceDescriptor> &device) const
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001669{
1670 PatchBuilder patchBuilder;
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001671 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1672 ALOG_ASSERT(msdModule != nullptr, "MSD module not available");
1673 sp<HwModule> deviceModule = mHwModules.getModuleForDevice(device, AUDIO_FORMAT_DEFAULT);
1674 if (deviceModule == nullptr) {
1675 ALOGE("%s() unable to get module for %s", __func__, device->toString().c_str());
1676 return patchBuilder;
1677 }
1678 const InputProfileCollection inputProfiles = msdIsSource ?
1679 msdModule->getInputProfiles() : deviceModule->getInputProfiles();
1680 const OutputProfileCollection outputProfiles = msdIsSource ?
1681 deviceModule->getOutputProfiles() : msdModule->getOutputProfiles();
1682
1683 const sp<DeviceDescriptor> sourceDevice = msdIsSource ? getMsdAudioInDevice() : device;
1684 const sp<DeviceDescriptor> sinkDevice = msdIsSource ?
1685 device : getMsdAudioOutDevices().itemAt(0);
1686 patchBuilder.addSource(sourceDevice).addSink(sinkDevice);
1687
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001688 audio_port_config sourceConfig = patchBuilder.patch()->sources[0];
1689 audio_port_config sinkConfig = patchBuilder.patch()->sinks[0];
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001690 AudioProfileVector sourceProfiles;
1691 AudioProfileVector sinkProfiles;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001692 // TODO: Figure out whether MSD module has HW_AV_SYNC flag set in the AP config file.
1693 // For now, we just forcefully try with HwAvSync first.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001694 for (auto hwAvSync : { true, false }) {
1695 if (getMsdProfiles(hwAvSync, inputProfiles, outputProfiles, sourceDevice, sinkDevice,
1696 sourceProfiles, sinkProfiles) != NO_ERROR) {
1697 continue;
1698 }
1699 if (getBestMsdConfig(hwAvSync, sourceProfiles, sinkProfiles, &sourceConfig,
1700 &sinkConfig) == NO_ERROR) {
1701 // Found a matching config. Re-create PatchBuilder with this config.
1702 return (PatchBuilder()).addSource(sourceConfig).addSink(sinkConfig);
1703 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001704 }
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001705 ALOGV("%s() no matching config found. Fall through to default PCM patch"
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001706 " supporting PCM format conversion.", __func__);
1707 return patchBuilder;
1708}
1709
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001710status_t AudioPolicyManager::setMsdOutputPatches(const DeviceVector *outputDevices) {
Michael Chan6fb34492020-12-08 15:44:49 +11001711 DeviceVector devices;
1712 if (outputDevices != nullptr && outputDevices->size() > 0) {
1713 devices.add(*outputDevices);
1714 } else {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001715 // Use media strategy for unspecified output device. This should only
1716 // occur on checkForDeviceAndOutputChanges(). Device connection events may
1717 // therefore invalidate explicit routing requests.
Michael Chan6fb34492020-12-08 15:44:49 +11001718 devices = mEngine->getOutputDevicesForAttributes(
François Gaffiec005e562018-11-06 15:04:49 +01001719 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
Michael Chan6fb34492020-12-08 15:44:49 +11001720 LOG_ALWAYS_FATAL_IF(devices.isEmpty(), "no output device to set MSD patch");
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001721 }
Michael Chan6fb34492020-12-08 15:44:49 +11001722 std::vector<PatchBuilder> patchesToCreate;
1723 for (auto i = 0u; i < devices.size(); ++i) {
1724 ALOGV("%s() for device %s", __func__, devices[i]->toString().c_str());
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001725 patchesToCreate.push_back(buildMsdPatch(true /*msdIsSource*/, devices[i]));
Michael Chan6fb34492020-12-08 15:44:49 +11001726 }
1727 // Retain only the MSD patches associated with outputDevices request.
1728 // Tear down the others, and create new ones as needed.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001729 AudioPatchCollection patchesToRemove = getMsdOutputPatches();
Michael Chan6fb34492020-12-08 15:44:49 +11001730 for (auto it = patchesToCreate.begin(); it != patchesToCreate.end(); ) {
1731 auto retainedPatch = false;
1732 for (auto i = 0u; i < patchesToRemove.size(); ++i) {
1733 if (audio_patches_are_equal(it->patch(), &patchesToRemove[i]->mPatch)) {
1734 patchesToRemove.removeItemsAt(i);
1735 retainedPatch = true;
1736 break;
1737 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001738 }
Michael Chan6fb34492020-12-08 15:44:49 +11001739 if (retainedPatch) {
1740 it = patchesToCreate.erase(it);
1741 continue;
1742 }
1743 ++it;
1744 }
1745 if (patchesToCreate.size() == 0 && patchesToRemove.size() == 0) {
1746 return NO_ERROR;
1747 }
1748 for (auto i = 0u; i < patchesToRemove.size(); ++i) {
1749 auto &currentPatch = patchesToRemove.valueAt(i);
François Gaffieafd4cea2019-11-18 15:50:22 +01001750 releaseAudioPatch(currentPatch->getHandle(), mUidCached);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001751 }
Michael Chan6fb34492020-12-08 15:44:49 +11001752 status_t status = NO_ERROR;
1753 for (const auto &p : patchesToCreate) {
1754 auto currStatus = installPatch(__func__, -1 /*index*/, nullptr /*patchHandle*/,
1755 p.patch(), 0 /*delayMs*/, mUidCached, nullptr /*patchDescPtr*/);
1756 char message[256];
1757 snprintf(message, sizeof(message), "%s() %s: creating MSD patch from device:IN_BUS to "
1758 "device:%#x (format:%#x channels:%#x samplerate:%d)", __func__,
1759 currStatus == NO_ERROR ? "Success" : "Error",
1760 p.patch()->sinks[0].ext.device.type, p.patch()->sources[0].format,
1761 p.patch()->sources[0].channel_mask, p.patch()->sources[0].sample_rate);
1762 if (currStatus == NO_ERROR) {
1763 ALOGD("%s", message);
1764 } else {
1765 ALOGE("%s", message);
1766 if (status == NO_ERROR) {
1767 status = currStatus;
1768 }
1769 }
1770 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001771 return status;
1772}
1773
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001774void AudioPolicyManager::releaseMsdOutputPatches(const DeviceVector& devices) {
1775 AudioPatchCollection msdPatches = getMsdOutputPatches();
Michael Chan6fb34492020-12-08 15:44:49 +11001776 for (size_t i = 0; i < msdPatches.size(); i++) {
1777 const auto& patch = msdPatches[i];
1778 for (size_t j = 0; j < patch->mPatch.num_sinks; ++j) {
1779 const struct audio_port_config *sink = &patch->mPatch.sinks[j];
1780 if (sink->type == AUDIO_PORT_TYPE_DEVICE && devices.getDevice(sink->ext.device.type,
1781 String8(sink->ext.device.address), AUDIO_FORMAT_DEFAULT) != nullptr) {
1782 releaseAudioPatch(patch->getHandle(), mUidCached);
1783 break;
1784 }
1785 }
1786 }
1787}
1788
Dorin Drimus94d94412022-02-02 09:05:02 +01001789bool AudioPolicyManager::msdHasPatchesToAllDevices(const AudioDeviceTypeAddrVector& devices) {
1790 DeviceVector devicesToCheck = mOutputDevicesAll.getDevicesFromDeviceTypeAddrVec(devices);
1791 AudioPatchCollection msdPatches = getMsdOutputPatches();
1792 for (size_t i = 0; i < msdPatches.size(); i++) {
1793 const auto& patch = msdPatches[i];
1794 for (size_t j = 0; j < patch->mPatch.num_sinks; ++j) {
1795 const struct audio_port_config *sink = &patch->mPatch.sinks[j];
1796 if (sink->type == AUDIO_PORT_TYPE_DEVICE) {
1797 const auto& foundDevice = devicesToCheck.getDevice(
1798 sink->ext.device.type, String8(sink->ext.device.address), AUDIO_FORMAT_DEFAULT);
1799 if (foundDevice != nullptr) {
1800 devicesToCheck.remove(foundDevice);
1801 if (devicesToCheck.isEmpty()) {
1802 return true;
1803 }
1804 }
1805 }
1806 }
1807 }
1808 return false;
1809}
1810
Eric Laurente0720872014-03-11 09:30:41 -07001811audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
jiabinebb6af42020-06-09 17:31:17 -07001812 audio_output_flags_t flags,
1813 audio_format_t format,
1814 audio_channel_mask_t channelMask,
1815 uint32_t samplingRate,
1816 audio_session_t sessionId)
Eric Laurente552edb2014-03-10 17:42:56 -07001817{
Eric Laurent16c66dd2019-05-01 17:54:10 -07001818 LOG_ALWAYS_FATAL_IF(!(format == AUDIO_FORMAT_INVALID || audio_is_linear_pcm(format)),
1819 "%s called with format %#x", __func__, format);
1820
jiabinebb6af42020-06-09 17:31:17 -07001821 // Return the output that haptic-generating attached to when 1) session id is specified,
1822 // 2) haptic-generating effect exists for given session id and 3) the output that
1823 // haptic-generating effect attached to is in given outputs.
1824 if (sessionId != AUDIO_SESSION_NONE) {
1825 audio_io_handle_t hapticGeneratingOutput = mEffects.getIoForSession(
1826 sessionId, FX_IID_HAPTICGENERATOR);
1827 if (outputs.indexOf(hapticGeneratingOutput) >= 0) {
1828 return hapticGeneratingOutput;
1829 }
1830 }
1831
Eric Laurent16c66dd2019-05-01 17:54:10 -07001832 // Flags disqualifying an output: the match must happen before calling selectOutput()
1833 static const audio_output_flags_t kExcludedFlags = (audio_output_flags_t)
1834 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ | AUDIO_OUTPUT_FLAG_DIRECT);
1835
1836 // Flags expressing a functional request: must be honored in priority over
1837 // other criteria
1838 static const audio_output_flags_t kFunctionalFlags = (audio_output_flags_t)
1839 (AUDIO_OUTPUT_FLAG_VOIP_RX | AUDIO_OUTPUT_FLAG_INCALL_MUSIC |
Eric Laurente28c66d2022-01-21 13:40:41 +01001840 AUDIO_OUTPUT_FLAG_TTS | AUDIO_OUTPUT_FLAG_DIRECT_PCM | AUDIO_OUTPUT_FLAG_ULTRASOUND |
1841 AUDIO_OUTPUT_FLAG_SPATIALIZER);
Eric Laurent16c66dd2019-05-01 17:54:10 -07001842 // Flags expressing a performance request: have lower priority than serving
1843 // requested sampling rate or channel mask
1844 static const audio_output_flags_t kPerformanceFlags = (audio_output_flags_t)
1845 (AUDIO_OUTPUT_FLAG_FAST | AUDIO_OUTPUT_FLAG_DEEP_BUFFER |
1846 AUDIO_OUTPUT_FLAG_RAW | AUDIO_OUTPUT_FLAG_SYNC);
1847
1848 const audio_output_flags_t functionalFlags =
1849 (audio_output_flags_t)(flags & kFunctionalFlags);
1850 const audio_output_flags_t performanceFlags =
1851 (audio_output_flags_t)(flags & kPerformanceFlags);
1852
1853 audio_io_handle_t bestOutput = (outputs.size() == 0) ? AUDIO_IO_HANDLE_NONE : outputs[0];
1854
Eric Laurente552edb2014-03-10 17:42:56 -07001855 // select one output among several that provide a path to a particular device or set of
François Gaffie11d30102018-11-02 16:09:09 +01001856 // devices (the list was previously build by getOutputsForDevices()).
Eric Laurente552edb2014-03-10 17:42:56 -07001857 // The priority is as follows:
jiabin40573322018-11-08 12:08:02 -08001858 // 1: the output supporting haptic playback when requesting haptic playback
Eric Laurent16c66dd2019-05-01 17:54:10 -07001859 // 2: the output with the highest number of requested functional flags
Carter Hsu199f1892021-10-15 15:47:29 +08001860 // with tiebreak preferring the minimum number of extra functional flags
1861 // (see b/200293124, the incorrect selection of AUDIO_OUTPUT_FLAG_VOIP_RX).
Eric Laurent16c66dd2019-05-01 17:54:10 -07001862 // 3: the output supporting the exact channel mask
1863 // 4: the output with a higher channel count than requested
1864 // 5: the output with a higher sampling rate than requested
1865 // 6: the output with the highest number of requested performance flags
1866 // 7: the output with the bit depth the closest to the requested one
1867 // 8: the primary output
1868 // 9: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07001869
Eric Laurent16c66dd2019-05-01 17:54:10 -07001870 // matching criteria values in priority order for best matching output so far
1871 std::vector<uint32_t> bestMatchCriteria(8, 0);
Eric Laurente552edb2014-03-10 17:42:56 -07001872
Eric Laurent16c66dd2019-05-01 17:54:10 -07001873 const uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
1874 const uint32_t hapticChannelCount = audio_channel_count_from_out_mask(
1875 channelMask & AUDIO_CHANNEL_HAPTIC_ALL);
Eric Laurente78b6762018-12-19 16:29:01 -08001876
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001877 for (audio_io_handle_t output : outputs) {
1878 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent16c66dd2019-05-01 17:54:10 -07001879 // matching criteria values in priority order for current output
1880 std::vector<uint32_t> currentMatchCriteria(8, 0);
jiabin40573322018-11-08 12:08:02 -08001881
Eric Laurent16c66dd2019-05-01 17:54:10 -07001882 if (outputDesc->isDuplicated()) {
1883 continue;
1884 }
1885 if ((kExcludedFlags & outputDesc->mFlags) != 0) {
1886 continue;
1887 }
Eric Laurent8838a382014-09-08 16:44:28 -07001888
Eric Laurent16c66dd2019-05-01 17:54:10 -07001889 // If haptic channel is specified, use the haptic output if present.
1890 // When using haptic output, same audio format and sample rate are required.
1891 const uint32_t outputHapticChannelCount = audio_channel_count_from_out_mask(
jiabin5740f082019-08-19 15:08:30 -07001892 outputDesc->getChannelMask() & AUDIO_CHANNEL_HAPTIC_ALL);
Eric Laurent16c66dd2019-05-01 17:54:10 -07001893 if ((hapticChannelCount == 0) != (outputHapticChannelCount == 0)) {
1894 continue;
1895 }
1896 if (outputHapticChannelCount >= hapticChannelCount
jiabin5740f082019-08-19 15:08:30 -07001897 && format == outputDesc->getFormat()
1898 && samplingRate == outputDesc->getSamplingRate()) {
Eric Laurent16c66dd2019-05-01 17:54:10 -07001899 currentMatchCriteria[0] = outputHapticChannelCount;
1900 }
1901
1902 // functional flags match
Carter Hsu199f1892021-10-15 15:47:29 +08001903 const int matchingFunctionalFlags =
1904 __builtin_popcount(outputDesc->mFlags & functionalFlags);
1905 const int totalFunctionalFlags =
1906 __builtin_popcount(outputDesc->mFlags & kFunctionalFlags);
1907 // Prefer matching functional flags, but subtract unnecessary functional flags.
1908 currentMatchCriteria[1] = 100 * (matchingFunctionalFlags + 1) - totalFunctionalFlags;
Eric Laurent16c66dd2019-05-01 17:54:10 -07001909
1910 // channel mask and channel count match
jiabin5740f082019-08-19 15:08:30 -07001911 uint32_t outputChannelCount = audio_channel_count_from_out_mask(
1912 outputDesc->getChannelMask());
Eric Laurent16c66dd2019-05-01 17:54:10 -07001913 if (channelMask != AUDIO_CHANNEL_NONE && channelCount > 2 &&
1914 channelCount <= outputChannelCount) {
1915 if ((audio_channel_mask_get_representation(channelMask) ==
jiabin5740f082019-08-19 15:08:30 -07001916 audio_channel_mask_get_representation(outputDesc->getChannelMask())) &&
1917 ((channelMask & outputDesc->getChannelMask()) == channelMask)) {
Eric Laurent16c66dd2019-05-01 17:54:10 -07001918 currentMatchCriteria[2] = outputChannelCount;
Eric Laurente552edb2014-03-10 17:42:56 -07001919 }
Eric Laurent16c66dd2019-05-01 17:54:10 -07001920 currentMatchCriteria[3] = outputChannelCount;
1921 }
1922
1923 // sampling rate match
1924 if (samplingRate > SAMPLE_RATE_HZ_DEFAULT &&
jiabin5740f082019-08-19 15:08:30 -07001925 samplingRate <= outputDesc->getSamplingRate()) {
1926 currentMatchCriteria[4] = outputDesc->getSamplingRate();
Eric Laurent16c66dd2019-05-01 17:54:10 -07001927 }
1928
1929 // performance flags match
1930 currentMatchCriteria[5] = popcount(outputDesc->mFlags & performanceFlags);
1931
1932 // format match
1933 if (format != AUDIO_FORMAT_INVALID) {
1934 currentMatchCriteria[6] =
jiabin4ef93452019-09-10 14:29:54 -07001935 PolicyAudioPort::kFormatDistanceMax -
1936 PolicyAudioPort::formatDistance(format, outputDesc->getFormat());
Eric Laurent16c66dd2019-05-01 17:54:10 -07001937 }
1938
1939 // primary output match
1940 currentMatchCriteria[7] = outputDesc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY;
1941
1942 // compare match criteria by priority then value
1943 if (std::lexicographical_compare(bestMatchCriteria.begin(), bestMatchCriteria.end(),
1944 currentMatchCriteria.begin(), currentMatchCriteria.end())) {
1945 bestMatchCriteria = currentMatchCriteria;
1946 bestOutput = output;
1947
1948 std::stringstream result;
1949 std::copy(bestMatchCriteria.begin(), bestMatchCriteria.end(),
1950 std::ostream_iterator<int>(result, " "));
1951 ALOGV("%s new bestOutput %d criteria %s",
1952 __func__, bestOutput, result.str().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07001953 }
1954 }
1955
Eric Laurent16c66dd2019-05-01 17:54:10 -07001956 return bestOutput;
Eric Laurente552edb2014-03-10 17:42:56 -07001957}
1958
Eric Laurent8fc147b2018-07-22 19:13:55 -07001959status_t AudioPolicyManager::startOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07001960{
Eric Laurent8fc147b2018-07-22 19:13:55 -07001961 ALOGV("%s portId %d", __FUNCTION__, portId);
1962
1963 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
1964 if (outputDesc == 0) {
1965 ALOGW("startOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001966 return BAD_VALUE;
1967 }
Andy Hung39efb7a2018-09-26 15:39:28 -07001968 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001969
Eric Laurent8fc147b2018-07-22 19:13:55 -07001970 ALOGV("startOutput() output %d, stream %d, session %d",
Eric Laurent97ac8712018-07-27 18:59:02 -07001971 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurentc75307b2015-03-17 15:29:32 -07001972
Eric Laurent733ce942017-12-07 12:18:25 -08001973 status_t status = outputDesc->start();
1974 if (status != NO_ERROR) {
1975 return status;
Eric Laurent3974e3b2017-12-07 17:58:43 -08001976 }
1977
Eric Laurent97ac8712018-07-27 18:59:02 -07001978 uint32_t delayMs;
1979 status = startSource(outputDesc, client, &delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07001980
1981 if (status != NO_ERROR) {
Eric Laurent733ce942017-12-07 12:18:25 -08001982 outputDesc->stop();
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001983 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07001984 }
Eric Laurentc75307b2015-03-17 15:29:32 -07001985 if (delayMs != 0) {
1986 usleep(delayMs * 1000);
1987 }
1988
1989 return status;
1990}
1991
Eric Laurent97ac8712018-07-27 18:59:02 -07001992status_t AudioPolicyManager::startSource(const sp<SwAudioOutputDescriptor>& outputDesc,
1993 const sp<TrackClientDescriptor>& client,
1994 uint32_t *delayMs)
Eric Laurentc75307b2015-03-17 15:29:32 -07001995{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001996 // cannot start playback of STREAM_TTS if any other output is being used
1997 uint32_t beaconMuteLatency = 0;
Eric Laurentc75307b2015-03-17 15:29:32 -07001998
1999 *delayMs = 0;
Eric Laurent97ac8712018-07-27 18:59:02 -07002000 audio_stream_type_t stream = client->stream();
François Gaffie1c878552018-11-22 16:53:21 +01002001 auto clientVolSrc = client->volumeSource();
François Gaffiec005e562018-11-06 15:04:49 +01002002 auto clientStrategy = client->strategy();
2003 auto clientAttr = client->attributes();
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002004 if (stream == AUDIO_STREAM_TTS) {
2005 ALOGV("\t found BEACON stream");
François Gaffie1c878552018-11-22 16:53:21 +01002006 if (!mTtsOutputAvailable && mOutputs.isAnyOutputActive(
Francois Gaffie4404ddb2021-02-04 17:03:38 +01002007 toVolumeSource(AUDIO_STREAM_TTS, false) /*sourceToIgnore*/)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002008 return INVALID_OPERATION;
2009 } else {
2010 beaconMuteLatency = handleEventForBeacon(STARTING_BEACON);
2011 }
2012 } else {
2013 // some playback other than beacon starts
2014 beaconMuteLatency = handleEventForBeacon(STARTING_OUTPUT);
2015 }
2016
Eric Laurent77305a62016-07-25 16:39:22 -07002017 // force device change if the output is inactive and no audio patch is already present.
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002018 // check active before incrementing usage count
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02002019 bool force = !outputDesc->isActive() && !outputDesc->isRouted();
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002020
François Gaffie11d30102018-11-02 16:09:09 +01002021 DeviceVector devices;
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002022 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
Eric Laurent97ac8712018-07-27 18:59:02 -07002023 const char *address = NULL;
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002024 if (policyMix != nullptr) {
François Gaffie11d30102018-11-02 16:09:09 +01002025 audio_devices_t newDeviceType;
Eric Laurent97ac8712018-07-27 18:59:02 -07002026 address = policyMix->mDeviceAddress.string();
Kevin Rocard153f92d2018-12-18 18:33:28 -08002027 if ((policyMix->mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie11d30102018-11-02 16:09:09 +01002028 newDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Kevin Rocard153f92d2018-12-18 18:33:28 -08002029 } else {
2030 newDeviceType = policyMix->mDeviceType;
Eric Laurent97ac8712018-07-27 18:59:02 -07002031 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08002032 sp device = mAvailableOutputDevices.getDevice(newDeviceType, String8(address),
2033 AUDIO_FORMAT_DEFAULT);
2034 ALOG_ASSERT(device, "%s: no device found t=%u, a=%s", __func__, newDeviceType, address);
2035 devices.add(device);
Eric Laurent97ac8712018-07-27 18:59:02 -07002036 }
2037
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002038 // requiresMuteCheck is false when we can bypass mute strategy.
2039 // It covers a common case when there is no materially active audio
2040 // and muting would result in unnecessary delay and dropped audio.
2041 const uint32_t outputLatencyMs = outputDesc->latency();
2042 bool requiresMuteCheck = outputDesc->isActive(outputLatencyMs * 2); // account for drain
2043
Eric Laurente552edb2014-03-10 17:42:56 -07002044 // increment usage count for this stream on the requested output:
2045 // NOTE that the usage count is the same for duplicated output and hardware output which is
2046 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
Eric Laurent592dd7b2018-08-05 18:58:48 -07002047 outputDesc->setClientActive(client, true);
Eric Laurent97ac8712018-07-27 18:59:02 -07002048
2049 if (client->hasPreferredDevice(true)) {
François Gaffief96e5432019-04-09 17:13:56 +02002050 if (outputDesc->clientsList(true /*activeOnly*/).size() == 1 &&
2051 client->isPreferredDeviceForExclusiveUse()) {
2052 // Preferred device may be exclusive, use only if no other active clients on this output
2053 devices = DeviceVector(
2054 mAvailableOutputDevices.getDeviceFromId(client->preferredDeviceId()));
2055 } else {
2056 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
2057 }
François Gaffie11d30102018-11-02 16:09:09 +01002058 if (devices != outputDesc->devices()) {
François Gaffiec005e562018-11-06 15:04:49 +01002059 checkStrategyRoute(clientStrategy, outputDesc->mIoHandle);
Eric Laurent97ac8712018-07-27 18:59:02 -07002060 }
2061 }
Eric Laurente552edb2014-03-10 17:42:56 -07002062
François Gaffiec005e562018-11-06 15:04:49 +01002063 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07002064 selectOutputForMusicEffects();
2065 }
2066
François Gaffie1c878552018-11-22 16:53:21 +01002067 if (outputDesc->getActivityCount(clientVolSrc) == 1 || !devices.isEmpty()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08002068 // starting an output being rerouted?
François Gaffie11d30102018-11-02 16:09:09 +01002069 if (devices.isEmpty()) {
2070 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Eric Laurent275e8e92014-11-30 15:14:47 -08002071 }
François Gaffiec005e562018-11-06 15:04:49 +01002072 bool shouldWait =
2073 (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM)) ||
2074 followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_NOTIFICATION)) ||
2075 (beaconMuteLatency > 0));
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002076 uint32_t waitMs = beaconMuteLatency;
Eric Laurente552edb2014-03-10 17:42:56 -07002077 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01002078 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07002079 if (desc != outputDesc) {
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002080 // An output has a shared device if
2081 // - managed by the same hw module
2082 // - supports the currently selected device
2083 const bool sharedDevice = outputDesc->sharesHwModuleWith(desc)
François Gaffie11d30102018-11-02 16:09:09 +01002084 && (!desc->filterSupportedDevices(devices).isEmpty());
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002085
Eric Laurent77305a62016-07-25 16:39:22 -07002086 // force a device change if any other output is:
2087 // - managed by the same hw module
Jean-Michel Trivi4a5b4812018-02-08 17:22:32 +00002088 // - supports currently selected device
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002089 // - has a current device selection that differs from selected device.
Eric Laurent77305a62016-07-25 16:39:22 -07002090 // - has an active audio patch
Eric Laurente552edb2014-03-10 17:42:56 -07002091 // In this case, the audio HAL must receive the new device selection so that it can
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002092 // change the device currently selected by the other output.
2093 if (sharedDevice &&
François Gaffie11d30102018-11-02 16:09:09 +01002094 desc->devices() != devices &&
Eric Laurent77305a62016-07-25 16:39:22 -07002095 desc->getPatchHandle() != AUDIO_PATCH_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07002096 force = true;
2097 }
2098 // wait for audio on other active outputs to be presented when starting
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002099 // a notification so that audio focus effect can propagate, or that a mute/unmute
2100 // event occurred for beacon
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002101 const uint32_t latencyMs = desc->latency();
2102 const bool isActive = desc->isActive(latencyMs * 2); // account for drain
2103
2104 if (shouldWait && isActive && (waitMs < latencyMs)) {
2105 waitMs = latencyMs;
Eric Laurente552edb2014-03-10 17:42:56 -07002106 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002107
2108 // Require mute check if another output is on a shared device
2109 // and currently active to have proper drain and avoid pops.
2110 // Note restoring AudioTracks onto this output needs to invoke
2111 // a volume ramp if there is no mute.
2112 requiresMuteCheck |= sharedDevice && isActive;
Eric Laurente552edb2014-03-10 17:42:56 -07002113 }
2114 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002115
2116 const uint32_t muteWaitMs =
François Gaffie11d30102018-11-02 16:09:09 +01002117 setOutputDevices(outputDesc, devices, force, 0, NULL, requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07002118
Eric Laurente552edb2014-03-10 17:42:56 -07002119 // apply volume rules for current stream and device if necessary
François Gaffieaaac0fd2018-11-22 17:56:39 +01002120 auto &curves = getVolumeCurves(client->attributes());
2121 checkAndSetVolume(curves, client->volumeSource(),
2122 curves.getVolumeIndex(outputDesc->devices().types()),
Eric Laurentc75307b2015-03-17 15:29:32 -07002123 outputDesc,
Francois Gaffied11442b2020-04-27 11:51:09 +02002124 outputDesc->devices().types(), 0 /*delay*/,
2125 outputDesc->useHwGain() /*force*/);
Eric Laurente552edb2014-03-10 17:42:56 -07002126
2127 // update the outputs if starting an output with a stream that can affect notification
2128 // routing
2129 handleNotificationRoutingForStream(stream);
Eric Laurentc722f302014-12-10 11:21:49 -08002130
Eric Laurent2cbe89a2014-12-19 11:49:08 -08002131 // force reevaluating accessibility routing when ringtone or alarm starts
François Gaffiec005e562018-11-06 15:04:49 +01002132 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM))) {
Eric Laurent2cbe89a2014-12-19 11:49:08 -08002133 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
2134 }
Eric Laurentdc462862016-07-19 12:29:53 -07002135
2136 if (waitMs > muteWaitMs) {
2137 *delayMs = waitMs - muteWaitMs;
2138 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002139
2140 // FIXME: A device change (muteWaitMs > 0) likely introduces a volume change.
2141 // A volume change enacted by APM with 0 delay is not synchronous, as it goes
2142 // via AudioCommandThread to AudioFlinger. Hence it is possible that the volume
2143 // change occurs after the MixerThread starts and causes a stream volume
2144 // glitch.
2145 //
2146 // We do not introduce additional delay here.
Eric Laurente552edb2014-03-10 17:42:56 -07002147 }
Eric Laurentdc462862016-07-19 12:29:53 -07002148
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002149 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
jiabin9a3361e2019-10-01 09:38:30 -07002150 mEngine->getForceUse(
2151 AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
François Gaffiec005e562018-11-06 15:04:49 +01002152 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), true, outputDesc);
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002153 }
2154
Eric Laurent97ac8712018-07-27 18:59:02 -07002155 // Automatically enable the remote submix input when output is started on a re routing mix
2156 // of type MIX_TYPE_RECORDERS
jiabin9a3361e2019-10-01 09:38:30 -07002157 if (isSingleDeviceType(devices.types(), &audio_is_remote_submix_device) &&
2158 policyMix != NULL && policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002159 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2160 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2161 address,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002162 "remote-submix",
2163 AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07002164 }
2165
Eric Laurente552edb2014-03-10 17:42:56 -07002166 return NO_ERROR;
2167}
2168
Eric Laurent8fc147b2018-07-22 19:13:55 -07002169status_t AudioPolicyManager::stopOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002170{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002171 ALOGV("%s portId %d", __FUNCTION__, portId);
2172
2173 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2174 if (outputDesc == 0) {
2175 ALOGW("stopOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002176 return BAD_VALUE;
2177 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002178 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002179
Eric Laurent97ac8712018-07-27 18:59:02 -07002180 ALOGV("stopOutput() output %d, stream %d, session %d",
2181 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurente552edb2014-03-10 17:42:56 -07002182
Eric Laurent97ac8712018-07-27 18:59:02 -07002183 status_t status = stopSource(outputDesc, client);
Eric Laurent3974e3b2017-12-07 17:58:43 -08002184
Eric Laurent733ce942017-12-07 12:18:25 -08002185 if (status == NO_ERROR ) {
2186 outputDesc->stop();
Eric Laurent3974e3b2017-12-07 17:58:43 -08002187 }
2188 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07002189}
2190
Eric Laurent97ac8712018-07-27 18:59:02 -07002191status_t AudioPolicyManager::stopSource(const sp<SwAudioOutputDescriptor>& outputDesc,
2192 const sp<TrackClientDescriptor>& client)
Eric Laurentc75307b2015-03-17 15:29:32 -07002193{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002194 // always handle stream stop, check which stream type is stopping
Eric Laurent97ac8712018-07-27 18:59:02 -07002195 audio_stream_type_t stream = client->stream();
François Gaffie1c878552018-11-22 16:53:21 +01002196 auto clientVolSrc = client->volumeSource();
Eric Laurent97ac8712018-07-27 18:59:02 -07002197
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002198 handleEventForBeacon(stream == AUDIO_STREAM_TTS ? STOPPING_BEACON : STOPPING_OUTPUT);
2199
François Gaffie1c878552018-11-22 16:53:21 +01002200 if (outputDesc->getActivityCount(clientVolSrc) > 0) {
2201 if (outputDesc->getActivityCount(clientVolSrc) == 1) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002202 // Automatically disable the remote submix input when output is stopped on a
2203 // re routing mix of type MIX_TYPE_RECORDERS
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002204 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
jiabin9a3361e2019-10-01 09:38:30 -07002205 if (isSingleDeviceType(
2206 outputDesc->devices().types(), &audio_is_remote_submix_device) &&
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002207 policyMix != nullptr &&
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002208 policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002209 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2210 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002211 policyMix->mDeviceAddress,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002212 "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07002213 }
2214 }
2215 bool forceDeviceUpdate = false;
2216 if (client->hasPreferredDevice(true)) {
François Gaffiec005e562018-11-06 15:04:49 +01002217 checkStrategyRoute(client->strategy(), AUDIO_IO_HANDLE_NONE);
Eric Laurent97ac8712018-07-27 18:59:02 -07002218 forceDeviceUpdate = true;
2219 }
2220
Eric Laurente552edb2014-03-10 17:42:56 -07002221 // decrement usage count of this stream on the output
Eric Laurent592dd7b2018-08-05 18:58:48 -07002222 outputDesc->setClientActive(client, false);
Paul McLeanaa981192015-03-21 09:55:15 -07002223
Eric Laurente552edb2014-03-10 17:42:56 -07002224 // store time at which the stream was stopped - see isStreamActive()
François Gaffie1c878552018-11-22 16:53:21 +01002225 if (outputDesc->getActivityCount(clientVolSrc) == 0 || forceDeviceUpdate) {
François Gaffiec005e562018-11-06 15:04:49 +01002226 outputDesc->setStopTime(client, systemTime());
François Gaffie11d30102018-11-02 16:09:09 +01002227 DeviceVector newDevices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Francois Gaffie3523ab32021-06-22 13:24:34 +02002228
2229 // If the routing does not change, if an output is routed on a device using HwGain
2230 // (aka setAudioPortConfig) and there are still active clients following different
2231 // volume group(s), force reapply volume
2232 bool requiresVolumeCheck = outputDesc->getActivityCount(clientVolSrc) == 0 &&
2233 outputDesc->useHwGain() && outputDesc->isAnyActive(VOLUME_SOURCE_NONE);
2234
Eric Laurente552edb2014-03-10 17:42:56 -07002235 // delay the device switch by twice the latency because stopOutput() is executed when
2236 // the track stop() command is received and at that time the audio track buffer can
2237 // still contain data that needs to be drained. The latency only covers the audio HAL
2238 // and kernel buffers. Also the latency does not always include additional delay in the
2239 // audio path (audio DSP, CODEC ...)
Francois Gaffie3523ab32021-06-22 13:24:34 +02002240 setOutputDevices(outputDesc, newDevices, false, outputDesc->latency()*2,
2241 nullptr, true /*requiresMuteCheck*/, requiresVolumeCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07002242
2243 // force restoring the device selection on other active outputs if it differs from the
2244 // one being selected for this output
Eric Laurent57de36c2016-09-28 16:59:11 -07002245 uint32_t delayMs = outputDesc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -07002246 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01002247 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07002248 if (desc != outputDesc &&
Eric Laurente552edb2014-03-10 17:42:56 -07002249 desc->isActive() &&
2250 outputDesc->sharesHwModuleWith(desc) &&
François Gaffie11d30102018-11-02 16:09:09 +01002251 (newDevices != desc->devices())) {
2252 DeviceVector newDevices2 = getNewOutputDevices(desc, false /*fromCache*/);
2253 bool force = desc->devices() != newDevices2;
Eric Laurentf3a5a602018-05-22 18:42:55 -07002254
François Gaffie11d30102018-11-02 16:09:09 +01002255 setOutputDevices(desc, newDevices2, force, delayMs);
2256
Eric Laurent57de36c2016-09-28 16:59:11 -07002257 // re-apply device specific volume if not done by setOutputDevice()
2258 if (!force) {
François Gaffie11d30102018-11-02 16:09:09 +01002259 applyStreamVolumes(desc, newDevices2.types(), delayMs);
Eric Laurent57de36c2016-09-28 16:59:11 -07002260 }
Eric Laurente552edb2014-03-10 17:42:56 -07002261 }
2262 }
2263 // update the outputs if stopping one with a stream that can affect notification routing
2264 handleNotificationRoutingForStream(stream);
2265 }
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002266
2267 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
2268 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Jean-Michel Trivi74e01fa2019-02-25 12:18:09 -08002269 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), false, outputDesc);
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002270 }
2271
François Gaffiec005e562018-11-06 15:04:49 +01002272 if (followsSameRouting(client->attributes(), attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07002273 selectOutputForMusicEffects();
2274 }
Eric Laurente552edb2014-03-10 17:42:56 -07002275 return NO_ERROR;
2276 } else {
Eric Laurentc75307b2015-03-17 15:29:32 -07002277 ALOGW("stopOutput() refcount is already 0");
Eric Laurente552edb2014-03-10 17:42:56 -07002278 return INVALID_OPERATION;
2279 }
2280}
2281
jiabinbce0c1d2020-10-05 11:20:18 -07002282bool AudioPolicyManager::releaseOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002283{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002284 ALOGV("%s portId %d", __FUNCTION__, portId);
2285
2286 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2287 if (outputDesc == 0) {
Andy Hung39efb7a2018-09-26 15:39:28 -07002288 // If an output descriptor is closed due to a device routing change,
2289 // then there are race conditions with releaseOutput from tracks
2290 // that may be destroyed (with no PlaybackThread) or a PlaybackThread
2291 // destroyed shortly thereafter.
2292 //
2293 // Here we just log a warning, instead of a fatal error.
Eric Laurent8fc147b2018-07-22 19:13:55 -07002294 ALOGW("releaseOutput() no output for client %d", portId);
jiabinbce0c1d2020-10-05 11:20:18 -07002295 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002296 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002297
2298 ALOGV("releaseOutput() %d", outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -07002299
Jaideep Sharma7bf382e2020-11-26 17:07:29 +05302300 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
2301 if (outputDesc->isClientActive(client)) {
2302 ALOGW("releaseOutput() inactivates portId %d in good faith", portId);
2303 stopOutput(portId);
2304 }
2305
Eric Laurent8fc147b2018-07-22 19:13:55 -07002306 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
2307 if (outputDesc->mDirectOpenCount <= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07002308 ALOGW("releaseOutput() invalid open count %d for output %d",
Eric Laurent8fc147b2018-07-22 19:13:55 -07002309 outputDesc->mDirectOpenCount, outputDesc->mIoHandle);
jiabinbce0c1d2020-10-05 11:20:18 -07002310 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002311 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002312 if (--outputDesc->mDirectOpenCount == 0) {
2313 closeOutput(outputDesc->mIoHandle);
Eric Laurentb52c1522014-05-20 11:27:36 -07002314 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07002315 }
2316 }
Jaideep Sharma7bf382e2020-11-26 17:07:29 +05302317
Andy Hung39efb7a2018-09-26 15:39:28 -07002318 outputDesc->removeClient(portId);
jiabinbce0c1d2020-10-05 11:20:18 -07002319 if (outputDesc->mPendingReopenToQueryProfiles && outputDesc->getClientCount() == 0) {
2320 // The output is pending reopened to query dynamic profiles and
2321 // there is no active clients
2322 closeOutput(outputDesc->mIoHandle);
2323 sp<SwAudioOutputDescriptor> newOutputDesc = openOutputWithProfileAndDevice(
2324 outputDesc->mProfile, mEngine->getActiveMediaDevices(mAvailableOutputDevices));
2325 if (newOutputDesc == nullptr) {
2326 ALOGE("%s failed to open output", __func__);
2327 }
2328 return true;
2329 }
2330 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002331}
2332
Eric Laurentcaf7f482014-11-25 17:50:47 -08002333status_t AudioPolicyManager::getInputForAttr(const audio_attributes_t *attr,
2334 audio_io_handle_t *input,
Mikhail Naganov2996f672019-04-18 12:29:59 -07002335 audio_unique_id_t riid,
Eric Laurentcaf7f482014-11-25 17:50:47 -08002336 audio_session_t session,
Svet Ganov3e5f14f2021-05-13 22:51:08 +00002337 const AttributionSourceState& attributionSource,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002338 const audio_config_base_t *config,
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002339 audio_input_flags_t flags,
Eric Laurent2ac76942017-06-22 17:17:09 -07002340 audio_port_handle_t *selectedDeviceId,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002341 input_type_t *inputType,
2342 audio_port_handle_t *portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002343{
François Gaffiec005e562018-11-06 15:04:49 +01002344 ALOGV("%s() source %d, sampling rate %d, format %#x, channel mask %#x, session %d, "
Eric Laurent2f2c1982021-06-02 14:03:11 +02002345 "flags %#x attributes=%s requested device ID %d",
2346 __func__, attr->source, config->sample_rate, config->format, config->channel_mask,
2347 session, flags, toString(*attr).c_str(), *selectedDeviceId);
Eric Laurente552edb2014-03-10 17:42:56 -07002348
Eric Laurentad2e7b92017-09-14 20:06:42 -07002349 status_t status = NO_ERROR;
Eric Laurentc447ded2015-01-06 08:47:05 -08002350 audio_source_t halInputSource;
Francois Gaffie716e1432019-01-14 16:58:59 +01002351 audio_attributes_t attributes = *attr;
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002352 sp<AudioPolicyMix> policyMix;
François Gaffie11d30102018-11-02 16:09:09 +01002353 sp<DeviceDescriptor> device;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002354 sp<AudioInputDescriptor> inputDesc;
2355 sp<RecordClientDescriptor> clientDesc;
2356 audio_port_handle_t requestedDeviceId = *selectedDeviceId;
Svet Ganov3e5f14f2021-05-13 22:51:08 +00002357 uid_t uid = VALUE_OR_RETURN_STATUS(aidl2legacy_int32_t_uid_t(attributionSource.uid));
Eric Laurent8f42ea12018-08-08 09:08:25 -07002358 bool isSoundTrigger;
Eric Laurent8f42ea12018-08-08 09:08:25 -07002359
2360 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
2361 if (*portId != AUDIO_PORT_HANDLE_NONE) {
2362 return INVALID_OPERATION;
2363 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08002364
Francois Gaffie716e1432019-01-14 16:58:59 +01002365 if (attr->source == AUDIO_SOURCE_DEFAULT) {
2366 attributes.source = AUDIO_SOURCE_MIC;
Eric Laurentfe231122017-11-17 17:48:06 -08002367 }
2368
Paul McLean466dc8e2015-04-17 13:15:36 -06002369 // Explicit routing?
Pattydd807582021-11-04 21:01:03 +08002370 sp<DeviceDescriptor> explicitRoutingDevice =
François Gaffie11d30102018-11-02 16:09:09 +01002371 mAvailableInputDevices.getDeviceFromId(*selectedDeviceId);
Paul McLean466dc8e2015-04-17 13:15:36 -06002372
Eric Laurentad2e7b92017-09-14 20:06:42 -07002373 // special case for mmap capture: if an input IO handle is specified, we reuse this input if
2374 // possible
2375 if ((flags & AUDIO_INPUT_FLAG_MMAP_NOIRQ) == AUDIO_INPUT_FLAG_MMAP_NOIRQ &&
2376 *input != AUDIO_IO_HANDLE_NONE) {
2377 ssize_t index = mInputs.indexOfKey(*input);
2378 if (index < 0) {
2379 ALOGW("getInputForAttr() unknown MMAP input %d", *input);
2380 status = BAD_VALUE;
2381 goto error;
2382 }
2383 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002384 RecordClientVector clients = inputDesc->getClientsForSession(session);
2385 if (clients.size() == 0) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07002386 ALOGW("getInputForAttr() unknown session %d on input %d", session, *input);
2387 status = BAD_VALUE;
2388 goto error;
2389 }
2390 // For MMAP mode, the first call to getInputForAttr() is made on behalf of audioflinger.
2391 // The second call is for the first active client and sets the UID. Any further call
Eric Laurent331679c2018-04-16 17:03:16 -07002392 // corresponds to a new client and is only permitted from the same UID.
2393 // If the first UID is silenced, allow a new UID connection and replace with new UID
Eric Laurent8f42ea12018-08-08 09:08:25 -07002394 if (clients.size() > 1) {
2395 for (const auto& client : clients) {
2396 // The client map is ordered by key values (portId) and portIds are allocated
2397 // incrementaly. So the first client in this list is the one opened by audio flinger
2398 // when the mmap stream is created and should be ignored as it does not correspond
2399 // to an actual client
2400 if (client == *clients.cbegin()) {
2401 continue;
2402 }
2403 if (uid != client->uid() && !client->isSilenced()) {
2404 ALOGW("getInputForAttr() bad uid %d for client %d uid %d",
2405 uid, client->portId(), client->uid());
2406 status = INVALID_OPERATION;
2407 goto error;
2408 }
Eric Laurent331679c2018-04-16 17:03:16 -07002409 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002410 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002411 *inputType = API_INPUT_LEGACY;
François Gaffie11d30102018-11-02 16:09:09 +01002412 device = inputDesc->getDevice();
Eric Laurentad2e7b92017-09-14 20:06:42 -07002413
Eric Laurentfecbceb2021-02-09 14:46:43 +01002414 ALOGV("%s reusing MMAP input %d for session %d", __FUNCTION__, *input, session);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002415 goto exit;
Eric Laurentad2e7b92017-09-14 20:06:42 -07002416 }
2417
2418 *input = AUDIO_IO_HANDLE_NONE;
2419 *inputType = API_INPUT_INVALID;
2420
Francois Gaffie716e1432019-01-14 16:58:59 +01002421 halInputSource = attributes.source;
Eric Laurentad2e7b92017-09-14 20:06:42 -07002422
Francois Gaffie716e1432019-01-14 16:58:59 +01002423 if (attributes.source == AUDIO_SOURCE_REMOTE_SUBMIX &&
2424 strncmp(attributes.tags, "addr=", strlen("addr=")) == 0) {
2425 status = mPolicyMixes.getInputMixForAttr(attributes, &policyMix);
Eric Laurentad2e7b92017-09-14 20:06:42 -07002426 if (status != NO_ERROR) {
jiabinc1de2df2019-05-07 14:26:40 -07002427 ALOGW("%s could not find input mix for attr %s",
2428 __func__, toString(attributes).c_str());
Eric Laurentad2e7b92017-09-14 20:06:42 -07002429 goto error;
François Gaffie036e1e92015-03-19 10:16:24 +01002430 }
jiabinc1de2df2019-05-07 14:26:40 -07002431 device = mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2432 String8(attr->tags + strlen("addr=")),
2433 AUDIO_FORMAT_DEFAULT);
2434 if (device == nullptr) {
Kevin Rocard04ed0462019-05-02 17:53:24 -07002435 ALOGW("%s could not find in Remote Submix device for source %d, tags %s",
jiabinc1de2df2019-05-07 14:26:40 -07002436 __func__, attributes.source, attributes.tags);
2437 status = BAD_VALUE;
2438 goto error;
2439 }
2440
Kevin Rocard25f9b052019-02-27 15:08:54 -08002441 if (is_mix_loopback_render(policyMix->mRouteFlags)) {
2442 *inputType = API_INPUT_MIX_PUBLIC_CAPTURE_PLAYBACK;
2443 } else {
2444 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
2445 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002446 } else {
François Gaffie11d30102018-11-02 16:09:09 +01002447 if (explicitRoutingDevice != nullptr) {
2448 device = explicitRoutingDevice;
Eric Laurent97ac8712018-07-27 18:59:02 -07002449 } else {
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01002450 // Prevent from storing invalid requested device id in clients
2451 requestedDeviceId = AUDIO_PORT_HANDLE_NONE;
yuanjiahsu0735bf32021-03-18 08:12:54 +08002452 device = mEngine->getInputDeviceForAttributes(attributes, uid, &policyMix);
yuanjiahsu4069d5d2021-04-19 07:54:27 +08002453 ALOGV_IF(device != nullptr, "%s found device type is 0x%X",
2454 __FUNCTION__, device->type());
Eric Laurent97ac8712018-07-27 18:59:02 -07002455 }
François Gaffie11d30102018-11-02 16:09:09 +01002456 if (device == nullptr) {
Francois Gaffie716e1432019-01-14 16:58:59 +01002457 ALOGW("getInputForAttr() could not find device for source %d", attributes.source);
Eric Laurentad2e7b92017-09-14 20:06:42 -07002458 status = BAD_VALUE;
2459 goto error;
Eric Laurent275e8e92014-11-30 15:14:47 -08002460 }
Alden DSouzab7d20782021-02-08 08:51:42 -08002461 if (device->type() == AUDIO_DEVICE_IN_ECHO_REFERENCE) {
2462 *inputType = API_INPUT_MIX_CAPTURE;
2463 } else if (policyMix) {
François Gaffie11d30102018-11-02 16:09:09 +01002464 ALOG_ASSERT(policyMix->mMixType == MIX_TYPE_RECORDERS, "Invalid Mix Type");
2465 // there is an external policy, but this input is attached to a mix of recorders,
2466 // meaning it receives audio injected into the framework, so the recorder doesn't
2467 // know about it and is therefore considered "legacy"
2468 *inputType = API_INPUT_LEGACY;
2469 } else if (audio_is_remote_submix_device(device->type())) {
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002470 *inputType = API_INPUT_MIX_CAPTURE;
François Gaffie11d30102018-11-02 16:09:09 +01002471 } else if (device->type() == AUDIO_DEVICE_IN_TELEPHONY_RX) {
Eric Laurent82db2692015-08-07 13:59:42 -07002472 *inputType = API_INPUT_TELEPHONY_RX;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002473 } else {
2474 *inputType = API_INPUT_LEGACY;
Eric Laurentc722f302014-12-10 11:21:49 -08002475 }
Ravi Kumar Alamandab367f5b2015-08-25 08:21:37 -07002476
Eric Laurent599c7582015-12-07 18:05:55 -08002477 }
2478
François Gaffiec005e562018-11-06 15:04:49 +01002479 *input = getInputForDevice(device, session, attributes, config, flags, policyMix);
Eric Laurent599c7582015-12-07 18:05:55 -08002480 if (*input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07002481 status = INVALID_OPERATION;
2482 goto error;
Eric Laurent599c7582015-12-07 18:05:55 -08002483 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08002484
Eric Laurent8f42ea12018-08-08 09:08:25 -07002485exit:
2486
François Gaffiec005e562018-11-06 15:04:49 +01002487 *selectedDeviceId = mAvailableInputDevices.contains(device) ?
2488 device->getId() : AUDIO_PORT_HANDLE_NONE;
Eric Laurent2ac76942017-06-22 17:17:09 -07002489
Francois Gaffie716e1432019-01-14 16:58:59 +01002490 isSoundTrigger = attributes.source == AUDIO_SOURCE_HOTWORD &&
Carter Hsud0cce2e2019-05-03 17:36:28 +08002491 mSoundTriggerSessions.indexOfKey(session) >= 0;
jiabin4ef93452019-09-10 14:29:54 -07002492 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002493
Mikhail Naganov2996f672019-04-18 12:29:59 -07002494 clientDesc = new RecordClientDescriptor(*portId, riid, uid, session, attributes, *config,
Francois Gaffie716e1432019-01-14 16:58:59 +01002495 requestedDeviceId, attributes.source, flags,
2496 isSoundTrigger);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002497 inputDesc = mInputs.valueFor(*input);
Andy Hung39efb7a2018-09-26 15:39:28 -07002498 inputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002499
2500 ALOGV("getInputForAttr() returns input %d type %d selectedDeviceId %d for port ID %d",
2501 *input, *inputType, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07002502
Eric Laurent599c7582015-12-07 18:05:55 -08002503 return NO_ERROR;
Eric Laurentad2e7b92017-09-14 20:06:42 -07002504
2505error:
Eric Laurentad2e7b92017-09-14 20:06:42 -07002506 return status;
Eric Laurent599c7582015-12-07 18:05:55 -08002507}
2508
2509
François Gaffie11d30102018-11-02 16:09:09 +01002510audio_io_handle_t AudioPolicyManager::getInputForDevice(const sp<DeviceDescriptor> &device,
Eric Laurent599c7582015-12-07 18:05:55 -08002511 audio_session_t session,
François Gaffiec005e562018-11-06 15:04:49 +01002512 const audio_attributes_t &attributes,
Eric Laurentfe231122017-11-17 17:48:06 -08002513 const audio_config_base_t *config,
Eric Laurent599c7582015-12-07 18:05:55 -08002514 audio_input_flags_t flags,
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002515 const sp<AudioPolicyMix> &policyMix)
Eric Laurent599c7582015-12-07 18:05:55 -08002516{
2517 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
François Gaffiec005e562018-11-06 15:04:49 +01002518 audio_source_t halInputSource = attributes.source;
Eric Laurent599c7582015-12-07 18:05:55 -08002519 bool isSoundTrigger = false;
2520
François Gaffiec005e562018-11-06 15:04:49 +01002521 if (attributes.source == AUDIO_SOURCE_HOTWORD) {
Eric Laurent599c7582015-12-07 18:05:55 -08002522 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
2523 if (index >= 0) {
2524 input = mSoundTriggerSessions.valueFor(session);
2525 isSoundTrigger = true;
2526 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_HW_HOTWORD);
2527 ALOGV("SoundTrigger capture on session %d input %d", session, input);
2528 } else {
2529 halInputSource = AUDIO_SOURCE_VOICE_RECOGNITION;
Eric Laurent5dbe4712014-09-19 19:04:57 -07002530 }
François Gaffiec005e562018-11-06 15:04:49 +01002531 } else if (attributes.source == AUDIO_SOURCE_VOICE_COMMUNICATION &&
Eric Laurentfe231122017-11-17 17:48:06 -08002532 audio_is_linear_pcm(config->format)) {
Haynes Mathew George851d3ff2017-06-19 20:01:57 -07002533 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_VOIP_TX);
Eric Laurent5dbe4712014-09-19 19:04:57 -07002534 }
2535
Carter Hsua3abb402021-10-26 11:11:20 +08002536 if (attributes.source == AUDIO_SOURCE_ULTRASOUND) {
2537 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_ULTRASOUND);
2538 }
2539
Andy Hungf129b032015-04-07 13:45:50 -07002540 // find a compatible input profile (not necessarily identical in parameters)
2541 sp<IOProfile> profile;
Eric Laurentfe231122017-11-17 17:48:06 -08002542 // sampling rate and flags may be updated by getInputProfile
2543 uint32_t profileSamplingRate = (config->sample_rate == 0) ?
2544 SAMPLE_RATE_HZ_DEFAULT : config->sample_rate;
Glenn Kasten730b9262018-03-29 15:01:26 -07002545 audio_format_t profileFormat;
Eric Laurentfe231122017-11-17 17:48:06 -08002546 audio_channel_mask_t profileChannelMask = config->channel_mask;
Andy Hungf129b032015-04-07 13:45:50 -07002547 audio_input_flags_t profileFlags = flags;
2548 for (;;) {
Glenn Kasten730b9262018-03-29 15:01:26 -07002549 profileFormat = config->format; // reset each time through loop, in case it is updated
François Gaffie11d30102018-11-02 16:09:09 +01002550 profile = getInputProfile(device, profileSamplingRate, profileFormat, profileChannelMask,
Andy Hungf129b032015-04-07 13:45:50 -07002551 profileFlags);
2552 if (profile != 0) {
2553 break; // success
Eric Laurent05067782016-06-01 18:27:28 -07002554 } else if (profileFlags & AUDIO_INPUT_FLAG_RAW) {
2555 profileFlags = (audio_input_flags_t) (profileFlags & ~AUDIO_INPUT_FLAG_RAW); // retry
Atneya Nair497fff12022-01-18 16:23:04 -05002556 } else if (profileFlags != AUDIO_INPUT_FLAG_NONE && audio_is_linear_pcm(config->format)) {
Andy Hungf129b032015-04-07 13:45:50 -07002557 profileFlags = AUDIO_INPUT_FLAG_NONE; // retry
2558 } else { // fail
François Gaffie11d30102018-11-02 16:09:09 +01002559 ALOGW("%s could not find profile for device %s, sampling rate %u, format %#x, "
Pattydd807582021-11-04 21:01:03 +08002560 "channel mask 0x%X, flags %#x", __func__, device->toString().c_str(),
François Gaffie11d30102018-11-02 16:09:09 +01002561 config->sample_rate, config->format, config->channel_mask, flags);
Eric Laurent599c7582015-12-07 18:05:55 -08002562 return input;
Eric Laurent5dbe4712014-09-19 19:04:57 -07002563 }
Eric Laurente552edb2014-03-10 17:42:56 -07002564 }
Glenn Kasten05ddca52016-02-11 08:17:12 -08002565 // Pick input sampling rate if not specified by client
Eric Laurentfe231122017-11-17 17:48:06 -08002566 uint32_t samplingRate = config->sample_rate;
Glenn Kasten05ddca52016-02-11 08:17:12 -08002567 if (samplingRate == 0) {
2568 samplingRate = profileSamplingRate;
2569 }
Eric Laurente552edb2014-03-10 17:42:56 -07002570
Eric Laurent322b4d22015-04-03 15:57:54 -07002571 if (profile->getModuleHandle() == 0) {
2572 ALOGE("getInputForAttr(): HW module %s not opened", profile->getModuleName());
Eric Laurent599c7582015-12-07 18:05:55 -08002573 return input;
Eric Laurentcf2c0212014-07-25 16:20:43 -07002574 }
2575
Eric Laurentec376dc2021-04-08 20:41:22 +02002576 // Reuse an already opened input if a client with the same session ID already exists
2577 // on that input
2578 for (size_t i = 0; i < mInputs.size(); i++) {
2579 sp <AudioInputDescriptor> desc = mInputs.valueAt(i);
2580 if (desc->mProfile != profile) {
2581 continue;
2582 }
2583 RecordClientVector clients = desc->clientsList();
2584 for (const auto &client : clients) {
2585 if (session == client->session()) {
2586 return desc->mIoHandle;
2587 }
2588 }
2589 }
2590
Eric Laurent3974e3b2017-12-07 17:58:43 -08002591 if (!profile->canOpenNewIo()) {
Eric Laurent4eb58f12018-12-07 16:41:02 -08002592 for (size_t i = 0; i < mInputs.size(); ) {
Eric Laurentc529cf62020-04-17 18:19:10 -07002593 sp<AudioInputDescriptor> desc = mInputs.valueAt(i);
Eric Laurent4eb58f12018-12-07 16:41:02 -08002594 if (desc->mProfile != profile) {
Carter Hsu9a645a92019-05-15 12:15:32 +08002595 i++;
Eric Laurent4eb58f12018-12-07 16:41:02 -08002596 continue;
2597 }
2598 // if sound trigger, reuse input if used by other sound trigger on same session
2599 // else
2600 // reuse input if active client app is not in IDLE state
2601 //
2602 RecordClientVector clients = desc->clientsList();
2603 bool doClose = false;
2604 for (const auto& client : clients) {
2605 if (isSoundTrigger != client->isSoundTrigger()) {
2606 continue;
2607 }
2608 if (client->isSoundTrigger()) {
2609 if (session == client->session()) {
2610 return desc->mIoHandle;
2611 }
2612 continue;
2613 }
2614 if (client->active() && client->appState() != APP_STATE_IDLE) {
2615 return desc->mIoHandle;
2616 }
2617 doClose = true;
2618 }
2619 if (doClose) {
2620 closeInput(desc->mIoHandle);
2621 } else {
2622 i++;
2623 }
2624 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002625 }
2626
Eric Laurentfe231122017-11-17 17:48:06 -08002627 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07002628
Eric Laurentfe231122017-11-17 17:48:06 -08002629 audio_config_t lConfig = AUDIO_CONFIG_INITIALIZER;
2630 lConfig.sample_rate = profileSamplingRate;
2631 lConfig.channel_mask = profileChannelMask;
2632 lConfig.format = profileFormat;
Eric Laurente3014102017-05-03 11:15:43 -07002633
François Gaffie11d30102018-11-02 16:09:09 +01002634 status_t status = inputDesc->open(&lConfig, device, halInputSource, profileFlags, &input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07002635
2636 // only accept input with the exact requested set of parameters
Eric Laurent599c7582015-12-07 18:05:55 -08002637 if (status != NO_ERROR || input == AUDIO_IO_HANDLE_NONE ||
Eric Laurentfe231122017-11-17 17:48:06 -08002638 (profileSamplingRate != lConfig.sample_rate) ||
2639 !audio_formats_match(profileFormat, lConfig.format) ||
2640 (profileChannelMask != lConfig.channel_mask)) {
2641 ALOGW("getInputForAttr() failed opening input: sampling rate %d"
Glenn Kasten49f36ba2017-12-06 13:02:02 -08002642 ", format %#x, channel mask %#x",
Eric Laurentfe231122017-11-17 17:48:06 -08002643 profileSamplingRate, profileFormat, profileChannelMask);
Eric Laurent599c7582015-12-07 18:05:55 -08002644 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfe231122017-11-17 17:48:06 -08002645 inputDesc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07002646 }
Eric Laurent599c7582015-12-07 18:05:55 -08002647 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07002648 }
2649
Eric Laurentc722f302014-12-10 11:21:49 -08002650 inputDesc->mPolicyMix = policyMix;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002651
Eric Laurent599c7582015-12-07 18:05:55 -08002652 addInput(input, inputDesc);
Eric Laurentb52c1522014-05-20 11:27:36 -07002653 mpClientInterface->onAudioPortListUpdate();
Paul McLean466dc8e2015-04-17 13:15:36 -06002654
Eric Laurent599c7582015-12-07 18:05:55 -08002655 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07002656}
2657
Eric Laurent4eb58f12018-12-07 16:41:02 -08002658status_t AudioPolicyManager::startInput(audio_port_handle_t portId)
Eric Laurentbb948092017-01-23 18:33:30 -08002659{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002660 ALOGV("%s portId %d", __FUNCTION__, portId);
2661
2662 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2663 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002664 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurentd52a28c2020-08-21 17:10:39 -07002665 return DEAD_OBJECT;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002666 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002667 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07002668 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002669 if (client->active()) {
2670 ALOGW("%s input %d client %d already started", __FUNCTION__, input, client->portId());
2671 return INVALID_OPERATION;
Eric Laurent4dc68062014-07-28 17:26:49 -07002672 }
2673
Eric Laurent8f42ea12018-08-08 09:08:25 -07002674 audio_session_t session = client->session();
2675
Eric Laurent4eb58f12018-12-07 16:41:02 -08002676 ALOGV("%s input:%d, session:%d)", __FUNCTION__, input, session);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002677
Eric Laurent4eb58f12018-12-07 16:41:02 -08002678 Vector<sp<AudioInputDescriptor>> activeInputs = mInputs.getActiveInputs();
Eric Laurent74708e72017-04-07 17:13:42 -07002679
Eric Laurent4eb58f12018-12-07 16:41:02 -08002680 status_t status = inputDesc->start();
2681 if (status != NO_ERROR) {
2682 return status;
Eric Laurent74708e72017-04-07 17:13:42 -07002683 }
Eric Laurente552edb2014-03-10 17:42:56 -07002684
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002685 // increment activity count before calling getNewInputDevice() below as only active sessions
Eric Laurent313d1e72016-01-29 09:56:57 -08002686 // are considered for device selection
Eric Laurent8f42ea12018-08-08 09:08:25 -07002687 inputDesc->setClientActive(client, true);
Eric Laurent313d1e72016-01-29 09:56:57 -08002688
Eric Laurent8f42ea12018-08-08 09:08:25 -07002689 // indicate active capture to sound trigger service if starting capture from a mic on
2690 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01002691 sp<DeviceDescriptor> device = getNewInputDevice(inputDesc);
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002692 if (device != nullptr) {
2693 status = setInputDevice(input, device, true /* force */);
2694 } else {
2695 ALOGW("%s no new input device can be found for descriptor %d",
2696 __FUNCTION__, inputDesc->getId());
2697 status = BAD_VALUE;
2698 }
Eric Laurente552edb2014-03-10 17:42:56 -07002699
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002700 if (status == NO_ERROR && inputDesc->activeCount() == 1) {
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002701 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002702 // if input maps to a dynamic policy with an activity listener, notify of state change
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002703 if ((policyMix != nullptr)
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002704 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
2705 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
Eric Laurent8f42ea12018-08-08 09:08:25 -07002706 MIX_STATE_MIXING);
Eric Laurent733ce942017-12-07 12:18:25 -08002707 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002708
François Gaffie11d30102018-11-02 16:09:09 +01002709 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
2710 if (primaryInputDevices.contains(device) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07002711 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 1) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07002712 mpClientInterface->setSoundTriggerCaptureState(true);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002713 }
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002714
Eric Laurent8f42ea12018-08-08 09:08:25 -07002715 // automatically enable the remote submix output when input is started if not
2716 // used by a policy mix of type MIX_TYPE_RECORDERS
2717 // For remote submix (a virtual device), we open only one input per capture request.
François Gaffie11d30102018-11-02 16:09:09 +01002718 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002719 String8 address = String8("");
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002720 if (policyMix == nullptr) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002721 address = String8("0");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002722 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
2723 address = policyMix->mDeviceAddress;
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002724 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07002725 if (address != "") {
2726 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2727 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002728 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurentc722f302014-12-10 11:21:49 -08002729 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07002730 }
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002731 } else if (status != NO_ERROR) {
2732 // Restore client activity state.
2733 inputDesc->setClientActive(client, false);
2734 inputDesc->stop();
Eric Laurente552edb2014-03-10 17:42:56 -07002735 }
2736
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002737 ALOGV("%s input %d source = %d status = %d exit",
2738 __FUNCTION__, input, client->source(), status);
Eric Laurente552edb2014-03-10 17:42:56 -07002739
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002740 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07002741}
2742
Eric Laurent8fc147b2018-07-22 19:13:55 -07002743status_t AudioPolicyManager::stopInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002744{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002745 ALOGV("%s portId %d", __FUNCTION__, portId);
2746
2747 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2748 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002749 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002750 return BAD_VALUE;
2751 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002752 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07002753 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002754 if (!client->active()) {
2755 ALOGW("%s input %d client %d already stopped", __FUNCTION__, input, client->portId());
Eric Laurente552edb2014-03-10 17:42:56 -07002756 return INVALID_OPERATION;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002757 }
Carter Hsue6139d52021-07-08 10:30:20 +08002758 auto old_source = inputDesc->source();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002759 inputDesc->setClientActive(client, false);
Paul McLean466dc8e2015-04-17 13:15:36 -06002760
Eric Laurent8f42ea12018-08-08 09:08:25 -07002761 inputDesc->stop();
2762 if (inputDesc->isActive()) {
Carter Hsue6139d52021-07-08 10:30:20 +08002763 auto current_source = inputDesc->source();
2764 setInputDevice(input, getNewInputDevice(inputDesc),
2765 old_source != current_source /* force */);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002766 } else {
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002767 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002768 // if input maps to a dynamic policy with an activity listener, notify of state change
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002769 if ((policyMix != nullptr)
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002770 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
2771 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
Eric Laurent8f42ea12018-08-08 09:08:25 -07002772 MIX_STATE_IDLE);
Eric Laurent84332aa2016-01-28 22:19:18 +00002773 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07002774
2775 // automatically disable the remote submix output when input is stopped if not
2776 // used by a policy mix of type MIX_TYPE_RECORDERS
François Gaffie11d30102018-11-02 16:09:09 +01002777 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002778 String8 address = String8("");
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002779 if (policyMix == nullptr) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002780 address = String8("0");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002781 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
2782 address = policyMix->mDeviceAddress;
Eric Laurent8f42ea12018-08-08 09:08:25 -07002783 }
2784 if (address != "") {
2785 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2786 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002787 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002788 }
2789 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07002790 resetInputDevice(input);
2791
2792 // indicate inactive capture to sound trigger service if stopping capture from a mic on
2793 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01002794 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
2795 if (primaryInputDevices.contains(inputDesc->getDevice()) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07002796 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07002797 mpClientInterface->setSoundTriggerCaptureState(false);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002798 }
2799 inputDesc->clearPreemptedSessions();
Eric Laurente552edb2014-03-10 17:42:56 -07002800 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002801 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07002802}
2803
Eric Laurent8fc147b2018-07-22 19:13:55 -07002804void AudioPolicyManager::releaseInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002805{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002806 ALOGV("%s portId %d", __FUNCTION__, portId);
2807
2808 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2809 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002810 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002811 return;
2812 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002813 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002814 audio_io_handle_t input = inputDesc->mIoHandle;
2815
Eric Laurent8f42ea12018-08-08 09:08:25 -07002816 ALOGV("%s %d", __FUNCTION__, input);
Paul McLean466dc8e2015-04-17 13:15:36 -06002817
Andy Hung39efb7a2018-09-26 15:39:28 -07002818 inputDesc->removeClient(portId);
Eric Laurent599c7582015-12-07 18:05:55 -08002819
Andy Hung39efb7a2018-09-26 15:39:28 -07002820 if (inputDesc->getClientCount() > 0) {
2821 ALOGV("%s(%d) %zu clients remaining", __func__, portId, inputDesc->getClientCount());
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002822 return;
2823 }
2824
Eric Laurent05b90f82014-08-27 15:32:29 -07002825 closeInput(input);
Eric Laurentb52c1522014-05-20 11:27:36 -07002826 mpClientInterface->onAudioPortListUpdate();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002827 ALOGV("%s exit", __FUNCTION__);
Eric Laurente552edb2014-03-10 17:42:56 -07002828}
2829
Eric Laurent8f42ea12018-08-08 09:08:25 -07002830void AudioPolicyManager::closeActiveClients(const sp<AudioInputDescriptor>& input)
Eric Laurent8fc147b2018-07-22 19:13:55 -07002831{
Eric Laurent8f42ea12018-08-08 09:08:25 -07002832 RecordClientVector clients = input->clientsList(true);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002833
2834 for (const auto& client : clients) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002835 closeClient(client->portId());
Eric Laurent8fc147b2018-07-22 19:13:55 -07002836 }
2837}
2838
Eric Laurent8f42ea12018-08-08 09:08:25 -07002839void AudioPolicyManager::closeClient(audio_port_handle_t portId)
2840{
2841 stopInput(portId);
2842 releaseInput(portId);
2843}
Eric Laurent8fc147b2018-07-22 19:13:55 -07002844
Eric Laurent0dd51852019-04-19 18:18:58 -07002845void AudioPolicyManager::checkCloseInputs() {
2846 // After connecting or disconnecting an input device, close input if:
2847 // - it has no client (was just opened to check profile) OR
2848 // - none of its supported devices are connected anymore OR
2849 // - one of its clients cannot be routed to one of its supported
2850 // devices anymore. Otherwise update device selection
2851 std::vector<audio_io_handle_t> inputsToClose;
2852 for (size_t i = 0; i < mInputs.size(); i++) {
2853 const sp<AudioInputDescriptor> input = mInputs.valueAt(i);
2854 if (input->clientsList().size() == 0
Eric Laurent85732f42020-03-19 11:31:10 -07002855 || !mAvailableInputDevices.containsAtLeastOne(input->supportedDevices())) {
Eric Laurent0dd51852019-04-19 18:18:58 -07002856 inputsToClose.push_back(mInputs.keyAt(i));
2857 } else {
2858 bool close = false;
2859 for (const auto& client : input->clientsList()) {
2860 sp<DeviceDescriptor> device =
yuanjiahsu0735bf32021-03-18 08:12:54 +08002861 mEngine->getInputDeviceForAttributes(client->attributes(), client->uid());
Eric Laurent0dd51852019-04-19 18:18:58 -07002862 if (!input->supportedDevices().contains(device)) {
2863 close = true;
2864 break;
2865 }
2866 }
2867 if (close) {
2868 inputsToClose.push_back(mInputs.keyAt(i));
2869 } else {
2870 setInputDevice(input->mIoHandle, getNewInputDevice(input));
2871 }
2872 }
2873 }
2874
2875 for (const audio_io_handle_t handle : inputsToClose) {
2876 ALOGV("%s closing input %d", __func__, handle);
2877 closeInput(handle);
Eric Laurent05b90f82014-08-27 15:32:29 -07002878 }
Eric Laurentd4692962014-05-05 18:13:44 -07002879}
2880
François Gaffie251c7f02018-11-07 10:41:08 +01002881void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream, int indexMin, int indexMax)
Eric Laurente552edb2014-03-10 17:42:56 -07002882{
2883 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08002884 if (indexMin < 0 || indexMax < 0) {
2885 ALOGE("%s for stream %d: invalid min %d or max %d", __func__, stream , indexMin, indexMax);
2886 return;
2887 }
Eric Laurentf5aa58d2019-02-22 18:20:11 -08002888 getVolumeCurves(stream).initVolume(indexMin, indexMax);
Eric Laurent28d09f02016-03-08 10:43:05 -08002889
2890 // initialize other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08002891 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
2892 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002893 continue;
2894 }
Eric Laurentf5aa58d2019-02-22 18:20:11 -08002895 getVolumeCurves((audio_stream_type_t)curStream).initVolume(indexMin, indexMax);
Eric Laurent223fd5c2014-11-11 13:43:36 -08002896 }
Eric Laurente552edb2014-03-10 17:42:56 -07002897}
2898
Eric Laurente0720872014-03-11 09:30:41 -07002899status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
François Gaffie53615e22015-03-19 09:24:12 +01002900 int index,
2901 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07002902{
François Gaffieaaac0fd2018-11-22 17:56:39 +01002903 auto attributes = mEngine->getAttributesForStreamType(stream);
Eric Laurent242a9f82020-03-23 15:57:04 -07002904 if (attributes == AUDIO_ATTRIBUTES_INITIALIZER) {
2905 ALOGW("%s: no group for stream %s, bailing out", __func__, toString(stream).c_str());
2906 return NO_ERROR;
2907 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01002908 ALOGV("%s: stream %s attributes=%s", __func__,
2909 toString(stream).c_str(), toString(attributes).c_str());
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002910 return setVolumeIndexForAttributes(attributes, index, device);
Eric Laurente552edb2014-03-10 17:42:56 -07002911}
2912
Eric Laurente0720872014-03-11 09:30:41 -07002913status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
François Gaffieaaac0fd2018-11-22 17:56:39 +01002914 int *index,
2915 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07002916{
François Gaffiec005e562018-11-06 15:04:49 +01002917 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
2918 // stream by the engine.
jiabin9a3361e2019-10-01 09:38:30 -07002919 DeviceTypeSet deviceTypes = {device};
Eric Laurent5a2b6292016-04-14 18:05:57 -07002920 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
jiabin9a3361e2019-10-01 09:38:30 -07002921 deviceTypes = mEngine->getOutputDevicesForStream(
2922 stream, true /*fromCache*/).types();
Eric Laurente552edb2014-03-10 17:42:56 -07002923 }
jiabin9a3361e2019-10-01 09:38:30 -07002924 return getVolumeIndex(getVolumeCurves(stream), *index, deviceTypes);
Eric Laurente552edb2014-03-10 17:42:56 -07002925}
2926
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002927status_t AudioPolicyManager::setVolumeIndexForAttributes(const audio_attributes_t &attributes,
François Gaffiecfe17322018-11-07 13:41:29 +01002928 int index,
2929 audio_devices_t device)
2930{
2931 // Get Volume group matching the Audio Attributes
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002932 auto group = mEngine->getVolumeGroupForAttributes(attributes);
2933 if (group == VOLUME_GROUP_NONE) {
2934 ALOGD("%s: no group matching with %s", __FUNCTION__, toString(attributes).c_str());
François Gaffiecfe17322018-11-07 13:41:29 +01002935 return BAD_VALUE;
2936 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002937 ALOGV("%s: group %d matching with %s", __FUNCTION__, group, toString(attributes).c_str());
François Gaffiecfe17322018-11-07 13:41:29 +01002938 status_t status = NO_ERROR;
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002939 IVolumeCurves &curves = getVolumeCurves(attributes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01002940 VolumeSource vs = toVolumeSource(group);
2941 product_strategy_t strategy = mEngine->getProductStrategyForAttributes(attributes);
2942
2943 status = setVolumeCurveIndex(index, device, curves);
2944 if (status != NO_ERROR) {
2945 ALOGE("%s failed to set curve index for group %d device 0x%X", __func__, group, device);
2946 return status;
2947 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002948
jiabin9a3361e2019-10-01 09:38:30 -07002949 DeviceTypeSet curSrcDevices;
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002950 auto curCurvAttrs = curves.getAttributes();
2951 if (!curCurvAttrs.empty() && curCurvAttrs.front() != defaultAttr) {
2952 auto attr = curCurvAttrs.front();
jiabin9a3361e2019-10-01 09:38:30 -07002953 curSrcDevices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false).types();
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002954 } else if (!curves.getStreamTypes().empty()) {
2955 auto stream = curves.getStreamTypes().front();
jiabin9a3361e2019-10-01 09:38:30 -07002956 curSrcDevices = mEngine->getOutputDevicesForStream(stream, false).types();
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002957 } else {
2958 ALOGE("%s: Invalid src %d: no valid attributes nor stream",__func__, vs);
2959 return BAD_VALUE;
2960 }
jiabin9a3361e2019-10-01 09:38:30 -07002961 audio_devices_t curSrcDevice = Volume::getDeviceForVolume(curSrcDevices);
2962 resetDeviceTypes(curSrcDevices, curSrcDevice);
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002963
François Gaffiecfe17322018-11-07 13:41:29 +01002964 // update volume on all outputs and streams matching the following:
2965 // - The requested stream (or a stream matching for volume control) is active on the output
2966 // - The device (or devices) selected by the engine for this stream includes
2967 // the requested device
2968 // - For non default requested device, currently selected device on the output is either the
2969 // requested device or one of the devices selected by the engine for this stream
2970 // - For default requested device (AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME), apply volume only if
2971 // no specific device volume value exists for currently selected device.
François Gaffieaaac0fd2018-11-22 17:56:39 +01002972 for (size_t i = 0; i < mOutputs.size(); i++) {
2973 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
jiabin9a3361e2019-10-01 09:38:30 -07002974 DeviceTypeSet curDevices = desc->devices().types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01002975
jiabin9a3361e2019-10-01 09:38:30 -07002976 if (curDevices.erase(AUDIO_DEVICE_OUT_SPEAKER_SAFE)) {
2977 curDevices.insert(AUDIO_DEVICE_OUT_SPEAKER);
Robert Lee5e66e792019-04-03 18:37:15 +08002978 }
François Gaffieed91f582020-01-31 10:35:37 +01002979 if (!(desc->isActive(vs) || isInCall())) {
2980 continue;
2981 }
2982 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME &&
2983 curDevices.find(device) == curDevices.end()) {
2984 continue;
2985 }
2986 bool applyVolume = false;
2987 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
2988 curSrcDevices.insert(device);
2989 applyVolume = (curSrcDevices.find(
2990 Volume::getDeviceForVolume(curDevices)) != curSrcDevices.end());
2991 } else {
2992 applyVolume = !curves.hasVolumeIndexForDevice(curSrcDevice);
2993 }
2994 if (!applyVolume) {
2995 continue; // next output
2996 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01002997 // Inter / intra volume group priority management: Loop on strategies arranged by priority
2998 // If a higher priority strategy is active, and the output is routed to a device with a
2999 // HW Gain management, do not change the volume
François Gaffieaaac0fd2018-11-22 17:56:39 +01003000 if (desc->useHwGain()) {
François Gaffieed91f582020-01-31 10:35:37 +01003001 applyVolume = false;
Francois Gaffie593634d2021-06-22 13:31:31 +02003002 // If the volume source is active with higher priority source, ensure at least Sw Muted
3003 desc->setSwMute((index == 0), vs, curves.getStreamTypes(), curDevices, 0 /*delayMs*/);
François Gaffieaaac0fd2018-11-22 17:56:39 +01003004 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
3005 auto activeClients = desc->clientsList(true /*activeOnly*/, productStrategy,
3006 false /*preferredDevice*/);
3007 if (activeClients.empty()) {
3008 continue;
3009 }
3010 bool isPreempted = false;
3011 bool isHigherPriority = productStrategy < strategy;
3012 for (const auto &client : activeClients) {
3013 if (isHigherPriority && (client->volumeSource() != vs)) {
3014 ALOGV("%s: Strategy=%d (\nrequester:\n"
3015 " group %d, volumeGroup=%d attributes=%s)\n"
3016 " higher priority source active:\n"
3017 " volumeGroup=%d attributes=%s) \n"
3018 " on output %zu, bailing out", __func__, productStrategy,
3019 group, group, toString(attributes).c_str(),
3020 client->volumeSource(), toString(client->attributes()).c_str(), i);
3021 applyVolume = false;
3022 isPreempted = true;
3023 break;
3024 }
3025 // However, continue for loop to ensure no higher prio clients running on output
3026 if (client->volumeSource() == vs) {
3027 applyVolume = true;
3028 }
3029 }
3030 if (isPreempted || applyVolume) {
3031 break;
3032 }
3033 }
3034 if (!applyVolume) {
3035 continue; // next output
3036 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01003037 }
François Gaffieed91f582020-01-31 10:35:37 +01003038 //FIXME: workaround for truncated touch sounds
3039 // delayed volume change for system stream to be removed when the problem is
3040 // handled by system UI
3041 status_t volStatus = checkAndSetVolume(
3042 curves, vs, index, desc, curDevices,
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003043 ((vs == toVolumeSource(AUDIO_STREAM_SYSTEM, false))?
François Gaffieed91f582020-01-31 10:35:37 +01003044 TOUCH_SOUND_FIXED_DELAY_MS : 0));
3045 if (volStatus != NO_ERROR) {
3046 status = volStatus;
François Gaffieaaac0fd2018-11-22 17:56:39 +01003047 }
3048 }
François Gaffiecfe17322018-11-07 13:41:29 +01003049 mpClientInterface->onAudioVolumeGroupChanged(group, 0 /*flags*/);
3050 return status;
3051}
3052
François Gaffieaaac0fd2018-11-22 17:56:39 +01003053status_t AudioPolicyManager::setVolumeCurveIndex(int index,
François Gaffiecfe17322018-11-07 13:41:29 +01003054 audio_devices_t device,
3055 IVolumeCurves &volumeCurves)
3056{
3057 // VOICE_CALL stream has minVolumeIndex > 0 but can be muted directly by an
3058 // app that has MODIFY_PHONE_STATE permission.
François Gaffieaaac0fd2018-11-22 17:56:39 +01003059 bool hasVoice = hasVoiceStream(volumeCurves.getStreamTypes());
3060 if (((index < volumeCurves.getVolumeIndexMin()) && !(hasVoice && index == 0)) ||
François Gaffiecfe17322018-11-07 13:41:29 +01003061 (index > volumeCurves.getVolumeIndexMax())) {
3062 ALOGD("%s: wrong index %d min=%d max=%d", __FUNCTION__, index,
3063 volumeCurves.getVolumeIndexMin(), volumeCurves.getVolumeIndexMax());
3064 return BAD_VALUE;
3065 }
3066 if (!audio_is_output_device(device)) {
3067 return BAD_VALUE;
3068 }
3069
3070 // Force max volume if stream cannot be muted
3071 if (!volumeCurves.canBeMuted()) index = volumeCurves.getVolumeIndexMax();
3072
François Gaffieaaac0fd2018-11-22 17:56:39 +01003073 ALOGV("%s device %08x, index %d", __FUNCTION__ , device, index);
François Gaffiecfe17322018-11-07 13:41:29 +01003074 volumeCurves.addCurrentVolumeIndex(device, index);
3075 return NO_ERROR;
3076}
3077
3078status_t AudioPolicyManager::getVolumeIndexForAttributes(const audio_attributes_t &attr,
3079 int &index,
3080 audio_devices_t device)
3081{
3082 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
3083 // stream by the engine.
jiabin9a3361e2019-10-01 09:38:30 -07003084 DeviceTypeSet deviceTypes = {device};
François Gaffiecfe17322018-11-07 13:41:29 +01003085 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
jiabin9a3361e2019-10-01 09:38:30 -07003086 DeviceTypeSet deviceTypes = mEngine->getOutputDevicesForAttributes(
3087 attr, nullptr, true /*fromCache*/).types();
François Gaffiecfe17322018-11-07 13:41:29 +01003088 }
jiabin9a3361e2019-10-01 09:38:30 -07003089 return getVolumeIndex(getVolumeCurves(attr), index, deviceTypes);
François Gaffiecfe17322018-11-07 13:41:29 +01003090}
3091
3092status_t AudioPolicyManager::getVolumeIndex(const IVolumeCurves &curves,
3093 int &index,
jiabin9a3361e2019-10-01 09:38:30 -07003094 const DeviceTypeSet& deviceTypes) const
François Gaffiecfe17322018-11-07 13:41:29 +01003095{
jiabin9a3361e2019-10-01 09:38:30 -07003096 if (isSingleDeviceType(deviceTypes, audio_is_output_device)) {
François Gaffiecfe17322018-11-07 13:41:29 +01003097 return BAD_VALUE;
3098 }
jiabin9a3361e2019-10-01 09:38:30 -07003099 index = curves.getVolumeIndex(deviceTypes);
3100 ALOGV("%s: device %s index %d", __FUNCTION__, dumpDeviceTypes(deviceTypes).c_str(), index);
François Gaffiecfe17322018-11-07 13:41:29 +01003101 return NO_ERROR;
3102}
3103
3104status_t AudioPolicyManager::getMinVolumeIndexForAttributes(const audio_attributes_t &attr,
3105 int &index)
3106{
3107 index = getVolumeCurves(attr).getVolumeIndexMin();
3108 return NO_ERROR;
3109}
3110
3111status_t AudioPolicyManager::getMaxVolumeIndexForAttributes(const audio_attributes_t &attr,
3112 int &index)
3113{
3114 index = getVolumeCurves(attr).getVolumeIndexMax();
3115 return NO_ERROR;
3116}
3117
Eric Laurent36829f92017-04-07 19:04:42 -07003118audio_io_handle_t AudioPolicyManager::selectOutputForMusicEffects()
Eric Laurente552edb2014-03-10 17:42:56 -07003119{
3120 // select one output among several suitable for global effects.
3121 // The priority is as follows:
3122 // 1: An offloaded output. If the effect ends up not being offloadable,
3123 // AudioFlinger will invalidate the track and the offloaded output
3124 // will be closed causing the effect to be moved to a PCM output.
3125 // 2: A deep buffer output
Eric Laurent36829f92017-04-07 19:04:42 -07003126 // 3: The primary output
3127 // 4: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07003128
François Gaffiec005e562018-11-06 15:04:49 +01003129 DeviceVector devices = mEngine->getOutputDevicesForAttributes(
3130 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
François Gaffie11d30102018-11-02 16:09:09 +01003131 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07003132
Eric Laurent36829f92017-04-07 19:04:42 -07003133 if (outputs.size() == 0) {
3134 return AUDIO_IO_HANDLE_NONE;
3135 }
Eric Laurente552edb2014-03-10 17:42:56 -07003136
Eric Laurent36829f92017-04-07 19:04:42 -07003137 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
3138 bool activeOnly = true;
3139
3140 while (output == AUDIO_IO_HANDLE_NONE) {
3141 audio_io_handle_t outputOffloaded = AUDIO_IO_HANDLE_NONE;
3142 audio_io_handle_t outputDeepBuffer = AUDIO_IO_HANDLE_NONE;
3143 audio_io_handle_t outputPrimary = AUDIO_IO_HANDLE_NONE;
3144
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003145 for (audio_io_handle_t output : outputs) {
3146 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
Eric Laurent83d17c22019-04-02 17:10:01 -07003147 if (activeOnly && !desc->isActive(toVolumeSource(AUDIO_STREAM_MUSIC))) {
Eric Laurent36829f92017-04-07 19:04:42 -07003148 continue;
3149 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003150 ALOGV("selectOutputForMusicEffects activeOnly %d output %d flags 0x%08x",
3151 activeOnly, output, desc->mFlags);
Eric Laurent36829f92017-04-07 19:04:42 -07003152 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003153 outputOffloaded = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003154 }
3155 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003156 outputDeepBuffer = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003157 }
3158 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003159 outputPrimary = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003160 }
3161 }
3162 if (outputOffloaded != AUDIO_IO_HANDLE_NONE) {
3163 output = outputOffloaded;
3164 } else if (outputDeepBuffer != AUDIO_IO_HANDLE_NONE) {
3165 output = outputDeepBuffer;
3166 } else if (outputPrimary != AUDIO_IO_HANDLE_NONE) {
3167 output = outputPrimary;
3168 } else {
3169 output = outputs[0];
3170 }
3171 activeOnly = false;
3172 }
3173
3174 if (output != mMusicEffectOutput) {
Eric Laurent6c796322019-04-09 14:13:17 -07003175 mEffects.moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output);
Eric Laurent36829f92017-04-07 19:04:42 -07003176 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output);
3177 mMusicEffectOutput = output;
3178 }
3179
3180 ALOGV("selectOutputForMusicEffects selected output %d", output);
Eric Laurente552edb2014-03-10 17:42:56 -07003181 return output;
3182}
3183
Eric Laurent36829f92017-04-07 19:04:42 -07003184audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc __unused)
3185{
3186 return selectOutputForMusicEffects();
3187}
3188
Eric Laurente0720872014-03-11 09:30:41 -07003189status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07003190 audio_io_handle_t io,
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08003191 product_strategy_t strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07003192 int session,
3193 int id)
3194{
Eric Laurentb82e6b72019-11-22 17:25:04 -08003195 if (session != AUDIO_SESSION_DEVICE) {
3196 ssize_t index = mOutputs.indexOfKey(io);
Eric Laurente552edb2014-03-10 17:42:56 -07003197 if (index < 0) {
Eric Laurentb82e6b72019-11-22 17:25:04 -08003198 index = mInputs.indexOfKey(io);
3199 if (index < 0) {
3200 ALOGW("registerEffect() unknown io %d", io);
3201 return INVALID_OPERATION;
3202 }
Eric Laurente552edb2014-03-10 17:42:56 -07003203 }
3204 }
Eric Laurentbf8f69f2022-03-25 17:48:38 +01003205 bool isMusicEffect = (session != AUDIO_SESSION_OUTPUT_STAGE)
3206 && ((strategy == streamToStrategy(AUDIO_STREAM_MUSIC)
3207 || strategy == PRODUCT_STRATEGY_NONE));
3208 return mEffects.registerEffect(desc, io, session, id, isMusicEffect);
Eric Laurente552edb2014-03-10 17:42:56 -07003209}
3210
Eric Laurentc241b0d2018-11-28 09:08:49 -08003211status_t AudioPolicyManager::unregisterEffect(int id)
3212{
3213 if (mEffects.getEffect(id) == nullptr) {
3214 return INVALID_OPERATION;
3215 }
Eric Laurentc241b0d2018-11-28 09:08:49 -08003216 if (mEffects.isEffectEnabled(id)) {
3217 ALOGW("%s effect %d enabled", __FUNCTION__, id);
3218 setEffectEnabled(id, false);
3219 }
3220 return mEffects.unregisterEffect(id);
3221}
3222
3223status_t AudioPolicyManager::setEffectEnabled(int id, bool enabled)
3224{
3225 sp<EffectDescriptor> effect = mEffects.getEffect(id);
3226 if (effect == nullptr) {
3227 return INVALID_OPERATION;
3228 }
3229
3230 status_t status = mEffects.setEffectEnabled(id, enabled);
3231 if (status == NO_ERROR) {
3232 mInputs.trackEffectEnabled(effect, enabled);
3233 }
3234 return status;
3235}
3236
Eric Laurent6c796322019-04-09 14:13:17 -07003237
3238status_t AudioPolicyManager::moveEffectsToIo(const std::vector<int>& ids, audio_io_handle_t io)
3239{
3240 mEffects.moveEffects(ids, io);
3241 return NO_ERROR;
3242}
3243
Eric Laurentc75307b2015-03-17 15:29:32 -07003244bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
3245{
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003246 auto vs = toVolumeSource(stream, false);
3247 return vs != VOLUME_SOURCE_NONE ? mOutputs.isActive(vs, inPastMs) : false;
Eric Laurentc75307b2015-03-17 15:29:32 -07003248}
3249
3250bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream, uint32_t inPastMs) const
3251{
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003252 auto vs = toVolumeSource(stream, false);
3253 return vs != VOLUME_SOURCE_NONE ? mOutputs.isActiveRemotely(vs, inPastMs) : false;
Eric Laurentc75307b2015-03-17 15:29:32 -07003254}
3255
Eric Laurente0720872014-03-11 09:30:41 -07003256bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07003257{
3258 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003259 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08003260 if (inputDescriptor->isSourceActive(source)) {
Eric Laurente552edb2014-03-10 17:42:56 -07003261 return true;
3262 }
3263 }
3264 return false;
3265}
3266
Eric Laurent275e8e92014-11-30 15:14:47 -08003267// Register a list of custom mixes with their attributes and format.
3268// When a mix is registered, corresponding input and output profiles are
3269// added to the remote submix hw module. The profile contains only the
3270// parameters (sampling rate, format...) specified by the mix.
3271// The corresponding input remote submix device is also connected.
3272//
3273// When a remote submix device is connected, the address is checked to select the
3274// appropriate profile and the corresponding input or output stream is opened.
3275//
3276// When capture starts, getInputForAttr() will:
3277// - 1 look for a mix matching the address passed in attribtutes tags if any
3278// - 2 if none found, getDeviceForInputSource() will:
3279// - 2.1 look for a mix matching the attributes source
3280// - 2.2 if none found, default to device selection by policy rules
3281// At this time, the corresponding output remote submix device is also connected
3282// and active playback use cases can be transferred to this mix if needed when reconnecting
3283// after AudioTracks are invalidated
3284//
3285// When playback starts, getOutputForAttr() will:
3286// - 1 look for a mix matching the address passed in attribtutes tags if any
3287// - 2 if none found, look for a mix matching the attributes usage
3288// - 3 if none found, default to device and output selection by policy rules.
3289
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003290status_t AudioPolicyManager::registerPolicyMixes(const Vector<AudioMix>& mixes)
Eric Laurent275e8e92014-11-30 15:14:47 -08003291{
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003292 ALOGV("registerPolicyMixes() %zu mix(es)", mixes.size());
3293 status_t res = NO_ERROR;
Eric Laurentc209fe42020-06-05 18:11:23 -07003294 bool checkOutputs = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003295 sp<HwModule> rSubmixModule;
3296 // examine each mix's route type
3297 for (size_t i = 0; i < mixes.size(); i++) {
Eric Laurent97ac8712018-07-27 18:59:02 -07003298 AudioMix mix = mixes[i];
Kevin Rocard153f92d2018-12-18 18:33:28 -08003299 // Only capture of playback is allowed in LOOP_BACK & RENDER mode
3300 if (is_mix_loopback_render(mix.mRouteFlags) && mix.mMixType != MIX_TYPE_PLAYERS) {
3301 ALOGE("Unsupported Policy Mix %zu of %zu: "
3302 "Only capture of playback is allowed in LOOP_BACK & RENDER mode",
3303 i, mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003304 res = INVALID_OPERATION;
Eric Laurent275e8e92014-11-30 15:14:47 -08003305 break;
3306 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08003307 // LOOP_BACK and LOOP_BACK | RENDER have the same remote submix backend and are handled
3308 // in the same way.
Eric Laurent97ac8712018-07-27 18:59:02 -07003309 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003310 ALOGV("registerPolicyMixes() mix %zu of %zu is LOOP_BACK %d", i, mixes.size(),
3311 mix.mRouteFlags);
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003312 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003313 rSubmixModule = mHwModules.getModuleFromName(
3314 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
3315 if (rSubmixModule == 0) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003316 ALOGE("Unable to find audio module for submix, aborting mix %zu registration",
Mikhail Naganovd4120142017-12-06 15:49:22 -08003317 i);
3318 res = INVALID_OPERATION;
3319 break;
3320 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003321 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003322
Eric Laurent97ac8712018-07-27 18:59:02 -07003323 String8 address = mix.mDeviceAddress;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003324 audio_devices_t deviceTypeToMakeAvailable;
Eric Laurent97ac8712018-07-27 18:59:02 -07003325 if (mix.mMixType == MIX_TYPE_PLAYERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07003326 mix.mDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003327 deviceTypeToMakeAvailable = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
3328 } else {
3329 mix.mDeviceType = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
3330 deviceTypeToMakeAvailable = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Eric Laurent97ac8712018-07-27 18:59:02 -07003331 }
François Gaffie036e1e92015-03-19 10:16:24 +01003332
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003333 if (mPolicyMixes.registerMix(mix, 0 /*output desc*/) != NO_ERROR) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003334 ALOGE("Error registering mix %zu for address %s", i, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003335 res = INVALID_OPERATION;
3336 break;
3337 }
Eric Laurent97ac8712018-07-27 18:59:02 -07003338 audio_config_t outputConfig = mix.mFormat;
3339 audio_config_t inputConfig = mix.mFormat;
Eric Laurentc529cf62020-04-17 18:19:10 -07003340 // NOTE: audio flinger mixer does not support mono output: configure remote submix HAL
3341 // in stereo and let audio flinger do the channel conversion if needed.
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003342 outputConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
3343 inputConfig.channel_mask = AUDIO_CHANNEL_IN_STEREO;
jiabin5740f082019-08-19 15:08:30 -07003344 rSubmixModule->addOutputProfile(address.c_str(), &outputConfig,
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003345 AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address);
jiabin5740f082019-08-19 15:08:30 -07003346 rSubmixModule->addInputProfile(address.c_str(), &inputConfig,
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003347 AUDIO_DEVICE_IN_REMOTE_SUBMIX, address);
François Gaffie036e1e92015-03-19 10:16:24 +01003348
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003349 if ((res = setDeviceConnectionStateInt(deviceTypeToMakeAvailable,
jiabinc1de2df2019-05-07 14:26:40 -07003350 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
3351 address.string(), "remote-submix", AUDIO_FORMAT_DEFAULT)) != NO_ERROR) {
3352 ALOGE("Failed to set remote submix device available, type %u, address %s",
3353 mix.mDeviceType, address.string());
3354 break;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003355 }
Eric Laurent97ac8712018-07-27 18:59:02 -07003356 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
3357 String8 address = mix.mDeviceAddress;
Eric Laurent2c80be02019-01-23 18:06:37 -08003358 audio_devices_t type = mix.mDeviceType;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003359 ALOGV(" registerPolicyMixes() mix %zu of %zu is RENDER, dev=0x%X addr=%s",
Eric Laurent2c80be02019-01-23 18:06:37 -08003360 i, mixes.size(), type, address.string());
3361
3362 sp<DeviceDescriptor> device = mHwModules.getDeviceDescriptor(
3363 mix.mDeviceType, mix.mDeviceAddress,
3364 String8(), AUDIO_FORMAT_DEFAULT);
3365 if (device == nullptr) {
3366 res = INVALID_OPERATION;
3367 break;
3368 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003369
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003370 bool foundOutput = false;
Eric Laurentc529cf62020-04-17 18:19:10 -07003371 // First try to find an already opened output supporting the device
3372 for (size_t j = 0 ; j < mOutputs.size() && !foundOutput && res == NO_ERROR; j++) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003373 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurent2c80be02019-01-23 18:06:37 -08003374
Eric Laurentc529cf62020-04-17 18:19:10 -07003375 if (!desc->isDuplicated() && desc->supportedDevices().contains(device)) {
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003376 if (mPolicyMixes.registerMix(mix, desc) != NO_ERROR) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003377 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
3378 address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003379 res = INVALID_OPERATION;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003380 } else {
3381 foundOutput = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003382 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003383 }
3384 }
Eric Laurentc529cf62020-04-17 18:19:10 -07003385 // If no output found, try to find a direct output profile supporting the device
3386 for (size_t i = 0; i < mHwModules.size() && !foundOutput && res == NO_ERROR; i++) {
3387 sp<HwModule> module = mHwModules[i];
3388 for (size_t j = 0;
3389 j < module->getOutputProfiles().size() && !foundOutput && res == NO_ERROR;
3390 j++) {
3391 sp<IOProfile> profile = module->getOutputProfiles()[j];
3392 if (profile->isDirectOutput() && profile->supportsDevice(device)) {
3393 if (mPolicyMixes.registerMix(mix, nullptr) != NO_ERROR) {
3394 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
3395 address.string());
3396 res = INVALID_OPERATION;
3397 } else {
3398 foundOutput = true;
3399 }
3400 }
3401 }
3402 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003403 if (res != NO_ERROR) {
3404 ALOGE(" Error registering mix %zu for device 0x%X addr %s",
Eric Laurent2c80be02019-01-23 18:06:37 -08003405 i, type, address.string());
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003406 res = INVALID_OPERATION;
3407 break;
3408 } else if (!foundOutput) {
3409 ALOGE(" Output not found for mix %zu for device 0x%X addr %s",
Eric Laurent2c80be02019-01-23 18:06:37 -08003410 i, type, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003411 res = INVALID_OPERATION;
3412 break;
Eric Laurentc209fe42020-06-05 18:11:23 -07003413 } else {
3414 checkOutputs = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003415 }
Eric Laurentc722f302014-12-10 11:21:49 -08003416 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003417 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003418 if (res != NO_ERROR) {
3419 unregisterPolicyMixes(mixes);
Eric Laurentc209fe42020-06-05 18:11:23 -07003420 } else if (checkOutputs) {
3421 checkForDeviceAndOutputChanges();
3422 updateCallAndOutputRouting();
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003423 }
3424 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08003425}
3426
3427status_t AudioPolicyManager::unregisterPolicyMixes(Vector<AudioMix> mixes)
3428{
Eric Laurent7b279bb2015-12-14 10:18:23 -08003429 ALOGV("unregisterPolicyMixes() num mixes %zu", mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003430 status_t res = NO_ERROR;
Eric Laurentc209fe42020-06-05 18:11:23 -07003431 bool checkOutputs = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003432 sp<HwModule> rSubmixModule;
3433 // examine each mix's route type
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003434 for (const auto& mix : mixes) {
3435 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie036e1e92015-03-19 10:16:24 +01003436
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003437 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003438 rSubmixModule = mHwModules.getModuleFromName(
3439 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
3440 if (rSubmixModule == 0) {
3441 res = INVALID_OPERATION;
3442 continue;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003443 }
3444 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003445
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003446 String8 address = mix.mDeviceAddress;
Eric Laurent275e8e92014-11-30 15:14:47 -08003447
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003448 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003449 res = INVALID_OPERATION;
3450 continue;
3451 }
3452
Kevin Rocard04ed0462019-05-02 17:53:24 -07003453 for (auto device : {AUDIO_DEVICE_IN_REMOTE_SUBMIX, AUDIO_DEVICE_OUT_REMOTE_SUBMIX}) {
3454 if (getDeviceConnectionState(device, address.string()) ==
3455 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
3456 res = setDeviceConnectionStateInt(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
3457 address.string(), "remote-submix",
3458 AUDIO_FORMAT_DEFAULT);
3459 if (res != OK) {
3460 ALOGE("Error making RemoteSubmix device unavailable for mix "
3461 "with type %d, address %s", device, address.string());
3462 }
3463 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003464 }
jiabin5740f082019-08-19 15:08:30 -07003465 rSubmixModule->removeOutputProfile(address.c_str());
3466 rSubmixModule->removeInputProfile(address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003467
Kevin Rocard153f92d2018-12-18 18:33:28 -08003468 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003469 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003470 res = INVALID_OPERATION;
3471 continue;
Eric Laurentc209fe42020-06-05 18:11:23 -07003472 } else {
3473 checkOutputs = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003474 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003475 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003476 }
Eric Laurentc209fe42020-06-05 18:11:23 -07003477 if (res == NO_ERROR && checkOutputs) {
3478 checkForDeviceAndOutputChanges();
3479 updateCallAndOutputRouting();
3480 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003481 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08003482}
3483
Mikhail Naganov100f0122018-11-29 11:22:16 -08003484void AudioPolicyManager::dumpManualSurroundFormats(String8 *dst) const
3485{
3486 size_t i = 0;
3487 constexpr size_t audioFormatPrefixLen = sizeof("AUDIO_FORMAT_");
3488 for (const auto& fmt : mManualSurroundFormats) {
3489 if (i++ != 0) dst->append(", ");
3490 std::string sfmt;
3491 FormatConverter::toString(fmt, sfmt);
3492 dst->append(sfmt.size() >= audioFormatPrefixLen ?
3493 sfmt.c_str() + audioFormatPrefixLen - 1 : sfmt.c_str());
3494 }
3495}
3496
Eric Laurentc529cf62020-04-17 18:19:10 -07003497// Returns true if all devices types match the predicate and are supported by one HW module
3498bool AudioPolicyManager::areAllDevicesSupported(
jiabin6a02d532020-08-07 11:56:38 -07003499 const AudioDeviceTypeAddrVector& devices,
Eric Laurentc529cf62020-04-17 18:19:10 -07003500 std::function<bool(audio_devices_t)> predicate,
3501 const char *context) {
3502 for (size_t i = 0; i < devices.size(); i++) {
3503 sp<DeviceDescriptor> devDesc = mHwModules.getDeviceDescriptor(
jiabin0a488932020-08-07 17:32:40 -07003504 devices[i].mType, devices[i].getAddress(), String8(),
Eric Laurent0e26e3f2020-04-29 14:24:16 -07003505 AUDIO_FORMAT_DEFAULT, false /*allowToCreate*/, true /*matchAddress*/);
Eric Laurentc529cf62020-04-17 18:19:10 -07003506 if (devDesc == nullptr || (predicate != nullptr && !predicate(devices[i].mType))) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003507 ALOGE("%s: device type %#x address %s not supported or not match predicate",
jiabin0a488932020-08-07 17:32:40 -07003508 context, devices[i].mType, devices[i].getAddress());
Eric Laurentc529cf62020-04-17 18:19:10 -07003509 return false;
3510 }
3511 }
3512 return true;
3513}
3514
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003515status_t AudioPolicyManager::setUidDeviceAffinities(uid_t uid,
jiabin6a02d532020-08-07 11:56:38 -07003516 const AudioDeviceTypeAddrVector& devices) {
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003517 ALOGV("%s() uid=%d num devices %zu", __FUNCTION__, uid, devices.size());
Eric Laurentc529cf62020-04-17 18:19:10 -07003518 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
3519 return BAD_VALUE;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003520 }
3521 status_t res = mPolicyMixes.setUidDeviceAffinities(uid, devices);
Eric Laurentc529cf62020-04-17 18:19:10 -07003522 if (res != NO_ERROR) {
3523 ALOGE("%s() Could not set all device affinities for uid = %d", __FUNCTION__, uid);
3524 return res;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003525 }
Eric Laurentc529cf62020-04-17 18:19:10 -07003526
3527 checkForDeviceAndOutputChanges();
3528 updateCallAndOutputRouting();
3529
3530 return NO_ERROR;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003531}
3532
3533status_t AudioPolicyManager::removeUidDeviceAffinities(uid_t uid) {
3534 ALOGV("%s() uid=%d", __FUNCTION__, uid);
Oscar Azucena4b2a8212019-04-26 23:48:59 -07003535 status_t res = mPolicyMixes.removeUidDeviceAffinities(uid);
3536 if (res != NO_ERROR) {
Eric Laurentc529cf62020-04-17 18:19:10 -07003537 ALOGE("%s() Could not remove all device affinities for uid = %d",
Oscar Azucena4b2a8212019-04-26 23:48:59 -07003538 __FUNCTION__, uid);
3539 return INVALID_OPERATION;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003540 }
3541
Eric Laurentc529cf62020-04-17 18:19:10 -07003542 checkForDeviceAndOutputChanges();
3543 updateCallAndOutputRouting();
3544
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003545 return res;
3546}
3547
Eric Laurent2517af32020-11-25 15:31:27 +01003548
jiabin0a488932020-08-07 17:32:40 -07003549status_t AudioPolicyManager::setDevicesRoleForStrategy(product_strategy_t strategy,
3550 device_role_t role,
3551 const AudioDeviceTypeAddrVector &devices) {
3552 ALOGV("%s() strategy=%d role=%d %s", __func__, strategy, role,
3553 dumpAudioDeviceTypeAddrVector(devices).c_str());
Eric Laurentc529cf62020-04-17 18:19:10 -07003554
Eric Laurentc529cf62020-04-17 18:19:10 -07003555 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003556 return BAD_VALUE;
3557 }
jiabin0a488932020-08-07 17:32:40 -07003558 status_t status = mEngine->setDevicesRoleForStrategy(strategy, role, devices);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003559 if (status != NO_ERROR) {
jiabin0a488932020-08-07 17:32:40 -07003560 ALOGW("Engine could not set preferred devices %s for strategy %d role %d",
3561 dumpAudioDeviceTypeAddrVector(devices).c_str(), strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003562 return status;
3563 }
3564
3565 checkForDeviceAndOutputChanges();
Eric Laurent2517af32020-11-25 15:31:27 +01003566
3567 bool forceVolumeReeval = false;
3568 // FIXME: workaround for truncated touch sounds
3569 // to be removed when the problem is handled by system UI
3570 uint32_t delayMs = 0;
3571 if (strategy == mCommunnicationStrategy) {
3572 forceVolumeReeval = true;
3573 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
3574 updateInputRouting();
3575 }
3576 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003577
3578 return NO_ERROR;
3579}
3580
3581void AudioPolicyManager::updateCallAndOutputRouting(bool forceVolumeReeval, uint32_t delayMs)
3582{
3583 uint32_t waitMs = 0;
Francois Gaffie19fd6c52021-02-04 17:02:59 +01003584 if (updateCallRouting(true /*fromCache*/, delayMs, &waitMs) == NO_ERROR) {
Eric Laurentb36b4ac2020-08-21 12:50:41 -07003585 // Only apply special touch sound delay once
3586 delayMs = 0;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003587 }
3588 for (size_t i = 0; i < mOutputs.size(); i++) {
3589 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
3590 DeviceVector newDevices = getNewOutputDevices(outputDesc, true /*fromCache*/);
Francois Gaffie601801d2021-06-22 13:27:39 +02003591 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) ||
3592 (outputDesc != mPrimaryOutput && !isTelephonyRxOrTx(outputDesc))) {
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003593 // As done in setDeviceConnectionState, we could also fix default device issue by
3594 // preventing the force re-routing in case of default dev that distinguishes on address.
3595 // Let's give back to engine full device choice decision however.
Francois Gaffie601801d2021-06-22 13:27:39 +02003596 bool forceRouting = !newDevices.isEmpty();
3597 waitMs = setOutputDevices(outputDesc, newDevices, forceRouting, delayMs, nullptr,
3598 true /*requiresMuteCheck*/,
3599 !forceRouting /*requiresVolumeCheck*/);
Eric Laurentb36b4ac2020-08-21 12:50:41 -07003600 // Only apply special touch sound delay once
3601 delayMs = 0;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003602 }
3603 if (forceVolumeReeval && !newDevices.isEmpty()) {
3604 applyStreamVolumes(outputDesc, newDevices.types(), waitMs, true);
3605 }
3606 }
3607}
3608
Eric Laurent2517af32020-11-25 15:31:27 +01003609void AudioPolicyManager::updateInputRouting() {
3610 for (const auto& activeDesc : mInputs.getActiveInputs()) {
Jaideep Sharma408349a2020-11-27 14:47:17 +05303611 // Skip for hotword recording as the input device switch
3612 // is handled within sound trigger HAL
3613 if (activeDesc->isSoundTrigger() && activeDesc->source() == AUDIO_SOURCE_HOTWORD) {
3614 continue;
3615 }
Eric Laurent2517af32020-11-25 15:31:27 +01003616 auto newDevice = getNewInputDevice(activeDesc);
3617 // Force new input selection if the new device can not be reached via current input
3618 if (activeDesc->mProfile->getSupportedDevices().contains(newDevice)) {
3619 setInputDevice(activeDesc->mIoHandle, newDevice);
3620 } else {
3621 closeInput(activeDesc->mIoHandle);
3622 }
3623 }
3624}
3625
jiabin0a488932020-08-07 17:32:40 -07003626status_t AudioPolicyManager::removeDevicesRoleForStrategy(product_strategy_t strategy,
3627 device_role_t role)
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003628{
Eric Laurentfecbceb2021-02-09 14:46:43 +01003629 ALOGV("%s() strategy=%d role=%d", __func__, strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003630
jiabin0a488932020-08-07 17:32:40 -07003631 status_t status = mEngine->removeDevicesRoleForStrategy(strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003632 if (status != NO_ERROR) {
Eric Laurent2517af32020-11-25 15:31:27 +01003633 ALOGV("Engine could not remove preferred device for strategy %d status %d",
3634 strategy, status);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003635 return status;
3636 }
3637
3638 checkForDeviceAndOutputChanges();
Eric Laurent2517af32020-11-25 15:31:27 +01003639
3640 bool forceVolumeReeval = false;
3641 // FIXME: workaround for truncated touch sounds
3642 // to be removed when the problem is handled by system UI
3643 uint32_t delayMs = 0;
3644 if (strategy == mCommunnicationStrategy) {
3645 forceVolumeReeval = true;
3646 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
3647 updateInputRouting();
3648 }
3649 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003650
3651 return NO_ERROR;
3652}
3653
jiabin0a488932020-08-07 17:32:40 -07003654status_t AudioPolicyManager::getDevicesForRoleAndStrategy(product_strategy_t strategy,
3655 device_role_t role,
3656 AudioDeviceTypeAddrVector &devices) {
3657 return mEngine->getDevicesForRoleAndStrategy(strategy, role, devices);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003658}
3659
Jiabin Huang3b98d322020-09-03 17:54:16 +00003660status_t AudioPolicyManager::setDevicesRoleForCapturePreset(
3661 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices) {
3662 ALOGV("%s() audioSource=%d role=%d %s", __func__, audioSource, role,
3663 dumpAudioDeviceTypeAddrVector(devices).c_str());
3664
Mikhail Naganov55773032020-10-01 15:08:13 -07003665 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003666 return BAD_VALUE;
3667 }
3668 status_t status = mEngine->setDevicesRoleForCapturePreset(audioSource, role, devices);
3669 ALOGW_IF(status != NO_ERROR,
3670 "Engine could not set preferred devices %s for audio source %d role %d",
3671 dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
3672
3673 return status;
3674}
3675
3676status_t AudioPolicyManager::addDevicesRoleForCapturePreset(
3677 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices) {
3678 ALOGV("%s() audioSource=%d role=%d %s", __func__, audioSource, role,
3679 dumpAudioDeviceTypeAddrVector(devices).c_str());
3680
Mikhail Naganov55773032020-10-01 15:08:13 -07003681 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003682 return BAD_VALUE;
3683 }
3684 status_t status = mEngine->addDevicesRoleForCapturePreset(audioSource, role, devices);
3685 ALOGW_IF(status != NO_ERROR,
3686 "Engine could not add preferred devices %s for audio source %d role %d",
3687 dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
3688
Eric Laurent2517af32020-11-25 15:31:27 +01003689 updateInputRouting();
Jiabin Huang3b98d322020-09-03 17:54:16 +00003690 return status;
3691}
3692
3693status_t AudioPolicyManager::removeDevicesRoleForCapturePreset(
3694 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector& devices)
3695{
3696 ALOGV("%s() audioSource=%d role=%d devices=%s", __func__, audioSource, role,
3697 dumpAudioDeviceTypeAddrVector(devices).c_str());
3698
Mikhail Naganov55773032020-10-01 15:08:13 -07003699 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003700 return BAD_VALUE;
3701 }
3702
3703 status_t status = mEngine->removeDevicesRoleForCapturePreset(
3704 audioSource, role, devices);
3705 ALOGW_IF(status != NO_ERROR,
3706 "Engine could not remove devices role (%d) for capture preset %d", role, audioSource);
3707
Eric Laurent2517af32020-11-25 15:31:27 +01003708 updateInputRouting();
Jiabin Huang3b98d322020-09-03 17:54:16 +00003709 return status;
3710}
3711
3712status_t AudioPolicyManager::clearDevicesRoleForCapturePreset(audio_source_t audioSource,
3713 device_role_t role) {
3714 ALOGV("%s() audioSource=%d role=%d", __func__, audioSource, role);
3715
3716 status_t status = mEngine->clearDevicesRoleForCapturePreset(audioSource, role);
3717 ALOGW_IF(status != NO_ERROR,
3718 "Engine could not clear devices role (%d) for capture preset %d", role, audioSource);
3719
Eric Laurent2517af32020-11-25 15:31:27 +01003720 updateInputRouting();
Jiabin Huang3b98d322020-09-03 17:54:16 +00003721 return status;
3722}
3723
3724status_t AudioPolicyManager::getDevicesForRoleAndCapturePreset(
3725 audio_source_t audioSource, device_role_t role, AudioDeviceTypeAddrVector &devices) {
3726 return mEngine->getDevicesForRoleAndCapturePreset(audioSource, role, devices);
3727}
3728
Oscar Azucena90e77632019-11-27 17:12:28 -08003729status_t AudioPolicyManager::setUserIdDeviceAffinities(int userId,
jiabin6a02d532020-08-07 11:56:38 -07003730 const AudioDeviceTypeAddrVector& devices) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01003731 ALOGV("%s() userId=%d num devices %zu", __func__, userId, devices.size());
Eric Laurentc529cf62020-04-17 18:19:10 -07003732 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
3733 return BAD_VALUE;
Oscar Azucena90e77632019-11-27 17:12:28 -08003734 }
Oscar Azucena90e77632019-11-27 17:12:28 -08003735 status_t status = mPolicyMixes.setUserIdDeviceAffinities(userId, devices);
3736 if (status != NO_ERROR) {
3737 ALOGE("%s() could not set device affinity for userId %d",
3738 __FUNCTION__, userId);
3739 return status;
3740 }
3741
3742 // reevaluate outputs for all devices
3743 checkForDeviceAndOutputChanges();
3744 updateCallAndOutputRouting();
3745
3746 return NO_ERROR;
3747}
3748
3749status_t AudioPolicyManager::removeUserIdDeviceAffinities(int userId) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01003750 ALOGV("%s() userId=%d", __FUNCTION__, userId);
Oscar Azucena90e77632019-11-27 17:12:28 -08003751 status_t status = mPolicyMixes.removeUserIdDeviceAffinities(userId);
3752 if (status != NO_ERROR) {
3753 ALOGE("%s() Could not remove all device affinities fo userId = %d",
3754 __FUNCTION__, userId);
3755 return status;
3756 }
3757
3758 // reevaluate outputs for all devices
3759 checkForDeviceAndOutputChanges();
3760 updateCallAndOutputRouting();
3761
3762 return NO_ERROR;
3763}
3764
Andy Hungc29d82b2018-10-05 12:23:17 -07003765void AudioPolicyManager::dump(String8 *dst) const
Eric Laurente552edb2014-03-10 17:42:56 -07003766{
Andy Hungc29d82b2018-10-05 12:23:17 -07003767 dst->appendFormat("\nAudioPolicyManager Dump: %p\n", this);
Mikhail Naganov0dbe87b2021-12-01 02:03:31 +00003768 dst->appendFormat(" Primary Output I/O handle: %d\n",
Eric Laurent87ffa392015-05-22 10:32:38 -07003769 hasPrimaryOutput() ? mPrimaryOutput->mIoHandle : AUDIO_IO_HANDLE_NONE);
Mikhail Naganov0d6a0332016-04-19 17:12:38 -07003770 std::string stateLiteral;
3771 AudioModeConverter::toString(mEngine->getPhoneState(), stateLiteral);
Andy Hungc29d82b2018-10-05 12:23:17 -07003772 dst->appendFormat(" Phone state: %s\n", stateLiteral.c_str());
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07003773 const char* forceUses[AUDIO_POLICY_FORCE_USE_CNT] = {
3774 "communications", "media", "record", "dock", "system",
3775 "HDMI system audio", "encoded surround output", "vibrate ringing" };
3776 for (audio_policy_force_use_t i = AUDIO_POLICY_FORCE_FOR_COMMUNICATION;
3777 i < AUDIO_POLICY_FORCE_USE_CNT; i = (audio_policy_force_use_t)((int)i + 1)) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08003778 audio_policy_forced_cfg_t forceUseValue = mEngine->getForceUse(i);
3779 dst->appendFormat(" Force use for %s: %d", forceUses[i], forceUseValue);
3780 if (i == AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND &&
3781 forceUseValue == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
3782 dst->append(" (MANUAL: ");
3783 dumpManualSurroundFormats(dst);
3784 dst->append(")");
3785 }
3786 dst->append("\n");
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07003787 }
Andy Hungc29d82b2018-10-05 12:23:17 -07003788 dst->appendFormat(" TTS output %savailable\n", mTtsOutputAvailable ? "" : "not ");
3789 dst->appendFormat(" Master mono: %s\n", mMasterMono ? "on" : "off");
Mikhail Naganovb3bcb4f2022-02-23 23:46:56 +00003790 dst->appendFormat(" Communication Strategy id: %d\n", mCommunnicationStrategy);
Andy Hungc29d82b2018-10-05 12:23:17 -07003791 dst->appendFormat(" Config source: %s\n", mConfig.getSource().c_str()); // getConfig not const
Eric Laurent2517af32020-11-25 15:31:27 +01003792
Mikhail Naganov0f413b22021-12-02 05:29:27 +00003793 dst->append("\n");
3794 mAvailableOutputDevices.dump(dst, String8("Available output"), 1);
3795 dst->append("\n");
3796 mAvailableInputDevices.dump(dst, String8("Available input"), 1);
Andy Hungc29d82b2018-10-05 12:23:17 -07003797 mHwModulesAll.dump(dst);
3798 mOutputs.dump(dst);
3799 mInputs.dump(dst);
Mikhail Naganov0f413b22021-12-02 05:29:27 +00003800 mEffects.dump(dst, 1);
Andy Hungc29d82b2018-10-05 12:23:17 -07003801 mAudioPatches.dump(dst);
3802 mPolicyMixes.dump(dst);
3803 mAudioSources.dump(dst);
François Gaffiec005e562018-11-06 15:04:49 +01003804
Kevin Rocardb99cc752019-03-21 20:52:24 -07003805 dst->appendFormat(" AllowedCapturePolicies:\n");
3806 for (auto& policy : mAllowedCapturePolicies) {
3807 dst->appendFormat(" - uid=%d flag_mask=%#x\n", policy.first, policy.second);
3808 }
3809
François Gaffiec005e562018-11-06 15:04:49 +01003810 dst->appendFormat("\nPolicy Engine dump:\n");
3811 mEngine->dump(dst);
Andy Hungc29d82b2018-10-05 12:23:17 -07003812}
3813
3814status_t AudioPolicyManager::dump(int fd)
3815{
3816 String8 result;
3817 dump(&result);
Andy Hungbb54e202018-10-05 11:42:02 -07003818 write(fd, result.string(), result.size());
Eric Laurente552edb2014-03-10 17:42:56 -07003819 return NO_ERROR;
3820}
3821
Kevin Rocardb99cc752019-03-21 20:52:24 -07003822status_t AudioPolicyManager::setAllowedCapturePolicy(uid_t uid, audio_flags_mask_t capturePolicy)
3823{
3824 mAllowedCapturePolicies[uid] = capturePolicy;
3825 return NO_ERROR;
3826}
3827
Eric Laurente552edb2014-03-10 17:42:56 -07003828// This function checks for the parameters which can be offloaded.
3829// This can be enhanced depending on the capability of the DSP and policy
3830// of the system.
Eric Laurent90fe31c2020-11-26 20:06:35 +01003831audio_offload_mode_t AudioPolicyManager::getOffloadSupport(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07003832{
Eric Laurent90fe31c2020-11-26 20:06:35 +01003833 ALOGV("%s: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07003834 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurent90fe31c2020-11-26 20:06:35 +01003835 __func__, offloadInfo.sample_rate, offloadInfo.channel_mask,
Eric Laurente552edb2014-03-10 17:42:56 -07003836 offloadInfo.format,
3837 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
3838 offloadInfo.has_video);
3839
jiabin2b9d5a12021-12-10 01:06:29 +00003840 if (!isOffloadPossible(offloadInfo)) {
Eric Laurent90fe31c2020-11-26 20:06:35 +01003841 return AUDIO_OFFLOAD_NOT_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07003842 }
3843
3844 // See if there is a profile to support this.
3845 // AUDIO_DEVICE_NONE
François Gaffie11d30102018-11-02 16:09:09 +01003846 sp<IOProfile> profile = getProfileForOutput(DeviceVector() /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07003847 offloadInfo.sample_rate,
3848 offloadInfo.format,
3849 offloadInfo.channel_mask,
Michael Chana94fbb22018-04-24 14:31:19 +10003850 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD,
3851 true /* directOnly */);
Eric Laurent94365442021-01-08 18:36:05 +01003852 ALOGV("%s: profile %sfound%s", __func__, profile != nullptr ? "" : "NOT ",
3853 (profile != nullptr && (profile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD) != 0)
3854 ? ", supports gapless" : "");
Eric Laurent90fe31c2020-11-26 20:06:35 +01003855 if (profile == nullptr) {
3856 return AUDIO_OFFLOAD_NOT_SUPPORTED;
3857 }
3858 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD) != 0) {
3859 return AUDIO_OFFLOAD_GAPLESS_SUPPORTED;
3860 }
3861 return AUDIO_OFFLOAD_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07003862}
3863
Michael Chana94fbb22018-04-24 14:31:19 +10003864bool AudioPolicyManager::isDirectOutputSupported(const audio_config_base_t& config,
3865 const audio_attributes_t& attributes) {
3866 audio_output_flags_t output_flags = AUDIO_OUTPUT_FLAG_NONE;
François Gaffie58d4be52018-11-06 15:30:12 +01003867 audio_flags_to_audio_output_flags(attributes.flags, &output_flags);
Dorin Drimus9901eb02022-01-14 11:36:51 +00003868 DeviceVector outputDevices = mEngine->getOutputDevicesForAttributes(attributes);
3869 sp<IOProfile> profile = getProfileForOutput(outputDevices,
Michael Chana94fbb22018-04-24 14:31:19 +10003870 config.sample_rate,
3871 config.format,
3872 config.channel_mask,
3873 output_flags,
3874 true /* directOnly */);
3875 ALOGV("%s() profile %sfound with name: %s, "
3876 "sample rate: %u, format: 0x%x, channel_mask: 0x%x, output flags: 0x%x",
3877 __FUNCTION__, profile != 0 ? "" : "NOT ",
jiabin5740f082019-08-19 15:08:30 -07003878 (profile != 0 ? profile->getTagName().c_str() : "null"),
Michael Chana94fbb22018-04-24 14:31:19 +10003879 config.sample_rate, config.format, config.channel_mask, output_flags);
Dorin Drimusecc9f422022-03-09 17:57:40 +01003880
3881 // also try the MSD module if compatible profile not found
3882 if (profile == nullptr) {
3883 profile = getMsdProfileForOutput(outputDevices,
3884 config.sample_rate,
3885 config.format,
3886 config.channel_mask,
3887 output_flags,
3888 true /* directOnly */);
3889 ALOGV("%s() MSD profile %sfound with name: %s, "
3890 "sample rate: %u, format: 0x%x, channel_mask: 0x%x, output flags: 0x%x",
3891 __FUNCTION__, profile != 0 ? "" : "NOT ",
3892 (profile != 0 ? profile->getTagName().c_str() : "null"),
3893 config.sample_rate, config.format, config.channel_mask, output_flags);
3894 }
3895 return (profile != nullptr);
Michael Chana94fbb22018-04-24 14:31:19 +10003896}
3897
jiabin2b9d5a12021-12-10 01:06:29 +00003898bool AudioPolicyManager::isOffloadPossible(const audio_offload_info_t &offloadInfo,
3899 bool durationIgnored) {
3900 if (mMasterMono) {
3901 return false; // no offloading if mono is set.
3902 }
3903
3904 // Check if offload has been disabled
3905 if (property_get_bool("audio.offload.disable", false /* default_value */)) {
3906 ALOGV("%s: offload disabled by audio.offload.disable", __func__);
3907 return false;
3908 }
3909
3910 // Check if stream type is music, then only allow offload as of now.
3911 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
3912 {
3913 ALOGV("%s: stream_type != MUSIC, returning false", __func__);
3914 return false;
3915 }
3916
3917 //TODO: enable audio offloading with video when ready
3918 const bool allowOffloadWithVideo =
3919 property_get_bool("audio.offload.video", false /* default_value */);
3920 if (offloadInfo.has_video && !allowOffloadWithVideo) {
3921 ALOGV("%s: has_video == true, returning false", __func__);
3922 return false;
3923 }
3924
3925 //If duration is less than minimum value defined in property, return false
3926 const int min_duration_secs = property_get_int32(
3927 "audio.offload.min.duration.secs", -1 /* default_value */);
3928 if (!durationIgnored) {
3929 if (min_duration_secs >= 0) {
3930 if (offloadInfo.duration_us < min_duration_secs * 1000000LL) {
3931 ALOGV("%s: Offload denied by duration < audio.offload.min.duration.secs(=%d)",
3932 __func__, min_duration_secs);
3933 return false;
3934 }
3935 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
3936 ALOGV("%s: Offload denied by duration < default min(=%u)",
3937 __func__, OFFLOAD_DEFAULT_MIN_DURATION_SECS);
3938 return false;
3939 }
3940 }
3941
3942 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
3943 // creating an offloaded track and tearing it down immediately after start when audioflinger
3944 // detects there is an active non offloadable effect.
3945 // FIXME: We should check the audio session here but we do not have it in this context.
3946 // This may prevent offloading in rare situations where effects are left active by apps
3947 // in the background.
3948 if (mEffects.isNonOffloadableEffectEnabled()) {
3949 return false;
3950 }
3951
3952 return true;
3953}
3954
3955audio_direct_mode_t AudioPolicyManager::getDirectPlaybackSupport(const audio_attributes_t *attr,
3956 const audio_config_t *config) {
3957 audio_offload_info_t offloadInfo = AUDIO_INFO_INITIALIZER;
3958 offloadInfo.format = config->format;
3959 offloadInfo.sample_rate = config->sample_rate;
3960 offloadInfo.channel_mask = config->channel_mask;
3961 offloadInfo.stream_type = mEngine->getStreamTypeForAttributes(*attr);
3962 offloadInfo.has_video = false;
3963 offloadInfo.is_streaming = false;
3964 const bool offloadPossible = isOffloadPossible(offloadInfo, true /*durationIgnored*/);
3965
3966 audio_direct_mode_t directMode = AUDIO_DIRECT_NOT_SUPPORTED;
3967 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
3968 audio_flags_to_audio_output_flags(attr->flags, &flags);
3969 // only retain flags that will drive compressed offload or passthrough
3970 uint32_t relevantFlags = AUDIO_OUTPUT_FLAG_HW_AV_SYNC;
3971 if (offloadPossible) {
3972 relevantFlags |= AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD;
3973 }
3974 flags = (audio_output_flags_t)((flags & relevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
3975
Dorin Drimusfae3c642022-03-17 18:36:30 +01003976 DeviceVector engineOutputDevices = mEngine->getOutputDevicesForAttributes(*attr);
jiabin2b9d5a12021-12-10 01:06:29 +00003977 for (const auto& hwModule : mHwModules) {
Dorin Drimusfae3c642022-03-17 18:36:30 +01003978 DeviceVector outputDevices = engineOutputDevices;
3979 // the MSD module checks for different conditions and output devices
3980 if (strcmp(hwModule->getName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0) {
3981 if (!msdHasPatchesToAllDevices(engineOutputDevices.toTypeAddrVector())) {
3982 continue;
3983 }
3984 outputDevices = getMsdAudioOutDevices();
3985 }
jiabin2b9d5a12021-12-10 01:06:29 +00003986 for (const auto& curProfile : hwModule->getOutputProfiles()) {
jiabinc8f7dfc2022-01-06 18:42:08 +00003987 if (!curProfile->isCompatibleProfile(outputDevices,
jiabin2b9d5a12021-12-10 01:06:29 +00003988 config->sample_rate, nullptr /*updatedSamplingRate*/,
3989 config->format, nullptr /*updatedFormat*/,
3990 config->channel_mask, nullptr /*updatedChannelMask*/,
3991 flags)) {
3992 continue;
3993 }
3994 // reject profiles not corresponding to a device currently available
3995 if (!mAvailableOutputDevices.containsAtLeastOne(curProfile->getSupportedDevices())) {
3996 continue;
3997 }
3998 if ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)
3999 != AUDIO_OUTPUT_FLAG_NONE) {
jiabinc6132d62022-01-01 07:36:31 +00004000 if ((directMode & AUDIO_DIRECT_OFFLOAD_GAPLESS_SUPPORTED)
jiabin2b9d5a12021-12-10 01:06:29 +00004001 != AUDIO_DIRECT_NOT_SUPPORTED) {
4002 // Already reports offload gapless supported. No need to report offload support.
4003 continue;
4004 }
4005 if ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD)
4006 != AUDIO_OUTPUT_FLAG_NONE) {
4007 // If offload gapless is reported, no need to report offload support.
4008 directMode = (audio_direct_mode_t) ((directMode &
4009 ~AUDIO_DIRECT_OFFLOAD_SUPPORTED) |
4010 AUDIO_DIRECT_OFFLOAD_GAPLESS_SUPPORTED);
4011 } else {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004012 directMode = (audio_direct_mode_t)(directMode | AUDIO_DIRECT_OFFLOAD_SUPPORTED);
jiabin2b9d5a12021-12-10 01:06:29 +00004013 }
4014 } else {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004015 directMode = (audio_direct_mode_t) (directMode | AUDIO_DIRECT_BITSTREAM_SUPPORTED);
jiabin2b9d5a12021-12-10 01:06:29 +00004016 }
4017 }
4018 }
4019 return directMode;
4020}
4021
Dorin Drimusf2196d82022-01-03 12:11:18 +01004022status_t AudioPolicyManager::getDirectProfilesForAttributes(const audio_attributes_t* attr,
4023 AudioProfileVector& audioProfilesVector) {
4024 AudioDeviceTypeAddrVector devices;
Andy Hung6d23c0f2022-02-16 09:37:15 -08004025 status_t status = getDevicesForAttributes(*attr, &devices, false /* forVolume */);
Dorin Drimusf2196d82022-01-03 12:11:18 +01004026 if (status != OK) {
4027 return status;
4028 }
4029 ALOGV("%s: found %zu output devices for attributes.", __func__, devices.size());
4030 if (devices.empty()) {
4031 return OK; // no output devices for the attributes
4032 }
4033
4034 for (const auto& hwModule : mHwModules) {
Dorin Drimus94d94412022-02-02 09:05:02 +01004035 // the MSD module checks for different conditions
4036 if (strcmp(hwModule->getName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0) {
4037 continue;
4038 }
4039 for (const auto& outputProfile : hwModule->getOutputProfiles()) {
4040 if (!outputProfile->asAudioPort()->isDirectOutput()) {
Dorin Drimusf2196d82022-01-03 12:11:18 +01004041 continue;
4042 }
Dorin Drimus94d94412022-02-02 09:05:02 +01004043 // allow only profiles that support all the available and routed devices
4044 if (outputProfile->getSupportedDevices().getDevicesFromDeviceTypeAddrVec(devices).size()
Dorin Drimusf2196d82022-01-03 12:11:18 +01004045 != devices.size()) {
4046 continue;
4047 }
Dorin Drimus94d94412022-02-02 09:05:02 +01004048 audioProfilesVector.addAllValidProfiles(
4049 outputProfile->asAudioPort()->getAudioProfiles());
Dorin Drimusf2196d82022-01-03 12:11:18 +01004050 }
4051 }
Dorin Drimus94d94412022-02-02 09:05:02 +01004052
4053 // add the direct profiles from MSD if present and has audio patches to all the output(s)
4054 const auto& msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
4055 if (msdModule != nullptr) {
4056 if (msdHasPatchesToAllDevices(devices)) {
4057 ALOGV("%s: MSD audio patches set to all output devices.", __func__);
4058 for (const auto& outputProfile : msdModule->getOutputProfiles()) {
4059 if (!outputProfile->asAudioPort()->isDirectOutput()) {
4060 continue;
4061 }
4062 audioProfilesVector.addAllValidProfiles(
4063 outputProfile->asAudioPort()->getAudioProfiles());
4064 }
4065 } else {
4066 ALOGV("%s: MSD audio patches NOT set to all output devices.", __func__);
4067 }
4068 }
4069
Dorin Drimusf2196d82022-01-03 12:11:18 +01004070 return NO_ERROR;
4071}
4072
Eric Laurent6a94d692014-05-20 11:18:06 -07004073status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
4074 audio_port_type_t type,
4075 unsigned int *num_ports,
jiabin19cdba52020-11-24 11:28:58 -08004076 struct audio_port_v7 *ports,
Eric Laurent6a94d692014-05-20 11:18:06 -07004077 unsigned int *generation)
4078{
jiabin19cdba52020-11-24 11:28:58 -08004079 if (num_ports == nullptr || (*num_ports != 0 && ports == nullptr) ||
4080 generation == nullptr) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004081 return BAD_VALUE;
4082 }
4083 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
jiabin19cdba52020-11-24 11:28:58 -08004084 if (ports == nullptr) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004085 *num_ports = 0;
4086 }
4087
4088 size_t portsWritten = 0;
4089 size_t portsMax = *num_ports;
4090 *num_ports = 0;
4091 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07004092 // do not report devices with type AUDIO_DEVICE_IN_STUB or AUDIO_DEVICE_OUT_STUB
4093 // as they are used by stub HALs by convention
Eric Laurent6a94d692014-05-20 11:18:06 -07004094 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004095 for (const auto& dev : mAvailableOutputDevices) {
4096 if (dev->type() == AUDIO_DEVICE_OUT_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07004097 continue;
4098 }
4099 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004100 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07004101 }
4102 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07004103 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004104 }
4105 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004106 for (const auto& dev : mAvailableInputDevices) {
4107 if (dev->type() == AUDIO_DEVICE_IN_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07004108 continue;
4109 }
4110 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004111 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07004112 }
4113 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07004114 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004115 }
4116 }
4117 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
4118 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
4119 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
4120 mInputs[i]->toAudioPort(&ports[portsWritten++]);
4121 }
4122 *num_ports += mInputs.size();
4123 }
4124 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent84c70242014-06-23 08:46:27 -07004125 size_t numOutputs = 0;
4126 for (size_t i = 0; i < mOutputs.size(); i++) {
4127 if (!mOutputs[i]->isDuplicated()) {
4128 numOutputs++;
4129 if (portsWritten < portsMax) {
4130 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
4131 }
4132 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004133 }
Eric Laurent84c70242014-06-23 08:46:27 -07004134 *num_ports += numOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07004135 }
4136 }
4137 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07004138 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
Eric Laurent6a94d692014-05-20 11:18:06 -07004139 return NO_ERROR;
4140}
4141
jiabin19cdba52020-11-24 11:28:58 -08004142status_t AudioPolicyManager::getAudioPort(struct audio_port_v7 *port)
Eric Laurent6a94d692014-05-20 11:18:06 -07004143{
Eric Laurent99fcae42018-05-17 16:59:18 -07004144 if (port == nullptr || port->id == AUDIO_PORT_HANDLE_NONE) {
4145 return BAD_VALUE;
4146 }
4147 sp<DeviceDescriptor> dev = mAvailableOutputDevices.getDeviceFromId(port->id);
4148 if (dev != 0) {
4149 dev->toAudioPort(port);
4150 return NO_ERROR;
4151 }
4152 dev = mAvailableInputDevices.getDeviceFromId(port->id);
4153 if (dev != 0) {
4154 dev->toAudioPort(port);
4155 return NO_ERROR;
4156 }
4157 sp<SwAudioOutputDescriptor> out = mOutputs.getOutputFromId(port->id);
4158 if (out != 0) {
4159 out->toAudioPort(port);
4160 return NO_ERROR;
4161 }
4162 sp<AudioInputDescriptor> in = mInputs.getInputFromId(port->id);
4163 if (in != 0) {
4164 in->toAudioPort(port);
4165 return NO_ERROR;
4166 }
4167 return BAD_VALUE;
Eric Laurent6a94d692014-05-20 11:18:06 -07004168}
4169
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004170status_t AudioPolicyManager::createAudioPatch(const struct audio_patch *patch,
4171 audio_patch_handle_t *handle,
4172 uid_t uid)
Eric Laurent6a94d692014-05-20 11:18:06 -07004173{
François Gaffieafd4cea2019-11-18 15:50:22 +01004174 ALOGV("%s", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004175 if (handle == NULL || patch == NULL) {
4176 return BAD_VALUE;
4177 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004178 ALOGV("%s num sources %d num sinks %d", __func__, patch->num_sources, patch->num_sinks);
Mikhail Naganovac9858b2018-06-15 13:12:37 -07004179 if (!audio_patch_is_valid(patch)) {
Eric Laurent874c42872014-08-08 15:13:39 -07004180 return BAD_VALUE;
4181 }
4182 // only one source per audio patch supported for now
4183 if (patch->num_sources > 1) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004184 return INVALID_OPERATION;
4185 }
Eric Laurent874c42872014-08-08 15:13:39 -07004186 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004187 return INVALID_OPERATION;
4188 }
Eric Laurent874c42872014-08-08 15:13:39 -07004189 for (size_t i = 0; i < patch->num_sinks; i++) {
4190 if (patch->sinks[i].role != AUDIO_PORT_ROLE_SINK) {
4191 return INVALID_OPERATION;
4192 }
4193 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004194
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004195 sp<DeviceDescriptor> srcDevice = mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
4196 sp<DeviceDescriptor> sinkDevice = mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id);
4197 if (srcDevice == nullptr || sinkDevice == nullptr) {
4198 ALOGW("%s could not create patch, invalid sink and/or source device(s)", __func__);
4199 return BAD_VALUE;
4200 }
4201 ALOGV("%s between source %s and sink %s", __func__,
4202 srcDevice->toString().c_str(), sinkDevice->toString().c_str());
4203 audio_port_handle_t portId = PolicyAudioPort::getNextUniqueId();
4204 // Default attributes, default volume priority, not to infer with non raw audio patches.
4205 audio_attributes_t attributes = attributes_initializer(AUDIO_USAGE_MEDIA);
4206 const struct audio_port_config *source = &patch->sources[0];
4207 sp<SourceClientDescriptor> sourceDesc =
4208 new InternalSourceClientDescriptor(
4209 portId, uid, attributes, *source, srcDevice, sinkDevice,
4210 mEngine->getProductStrategyForAttributes(attributes), toVolumeSource(attributes));
4211
4212 status_t status =
4213 connectAudioSourceToSink(sourceDesc, sinkDevice, patch, *handle, uid, 0 /* delayMs */);
4214
4215 if (status != NO_ERROR) {
4216 return INVALID_OPERATION;
4217 }
4218 mAudioSources.add(portId, sourceDesc);
4219 return NO_ERROR;
4220}
4221
4222status_t AudioPolicyManager::connectAudioSourceToSink(
4223 const sp<SourceClientDescriptor>& sourceDesc, const sp<DeviceDescriptor> &sinkDevice,
4224 const struct audio_patch *patch,
4225 audio_patch_handle_t &handle,
4226 uid_t uid, uint32_t delayMs)
4227{
4228 status_t status = createAudioPatchInternal(patch, &handle, uid, delayMs, sourceDesc);
4229 if (status != NO_ERROR || mAudioPatches.indexOfKey(handle) < 0) {
4230 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
4231 return INVALID_OPERATION;
4232 }
4233 sourceDesc->connect(handle, sinkDevice);
4234 if (isMsdPatch(handle)) {
4235 return NO_ERROR;
4236 }
4237 // SW Bridge? (@todo: HW bridge, keep track of HwOutput for device selection "reconsideration")
4238 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
4239 ALOG_ASSERT(swOutput != nullptr, "%s: a swOutput shall always be associated", __func__);
4240 if (swOutput->getClient(sourceDesc->portId()) != nullptr) {
4241 ALOGW("%s source portId has already been attached to outputDesc", __func__);
4242 goto FailurePatchAdded;
4243 }
4244 status = swOutput->start();
4245 if (status != NO_ERROR) {
4246 goto FailureSourceAdded;
4247 }
4248 swOutput->addClient(sourceDesc);
4249 status = startSource(swOutput, sourceDesc, &delayMs);
4250 if (status != NO_ERROR) {
4251 ALOGW("%s failed to start source, error %d", __FUNCTION__, status);
4252 goto FailureSourceActive;
4253 }
4254 if (delayMs != 0) {
4255 usleep(delayMs * 1000);
4256 }
4257 return NO_ERROR;
4258
4259FailureSourceActive:
4260 swOutput->stop();
4261 releaseOutput(sourceDesc->portId());
4262FailureSourceAdded:
4263 sourceDesc->setSwOutput(nullptr);
4264FailurePatchAdded:
4265 releaseAudioPatchInternal(handle);
4266 return INVALID_OPERATION;
4267}
4268
4269status_t AudioPolicyManager::createAudioPatchInternal(const struct audio_patch *patch,
4270 audio_patch_handle_t *handle,
4271 uid_t uid, uint32_t delayMs,
4272 const sp<SourceClientDescriptor>& sourceDesc)
4273{
4274 ALOGV("%s num sources %d num sinks %d", __func__, patch->num_sources, patch->num_sinks);
Eric Laurent6a94d692014-05-20 11:18:06 -07004275 sp<AudioPatch> patchDesc;
4276 ssize_t index = mAudioPatches.indexOfKey(*handle);
4277
François Gaffieafd4cea2019-11-18 15:50:22 +01004278 ALOGV("%s source id %d role %d type %d", __func__, patch->sources[0].id,
4279 patch->sources[0].role,
4280 patch->sources[0].type);
Eric Laurent874c42872014-08-08 15:13:39 -07004281#if LOG_NDEBUG == 0
4282 for (size_t i = 0; i < patch->num_sinks; i++) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004283 ALOGV("%s sink %zu: id %d role %d type %d", __func__ ,i, patch->sinks[i].id,
4284 patch->sinks[i].role,
4285 patch->sinks[i].type);
Eric Laurent874c42872014-08-08 15:13:39 -07004286 }
4287#endif
Eric Laurent6a94d692014-05-20 11:18:06 -07004288
4289 if (index >= 0) {
4290 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01004291 ALOGV("%s mUidCached %d patchDesc->mUid %d uid %d",
4292 __func__, mUidCached, patchDesc->getUid(), uid);
4293 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004294 return INVALID_OPERATION;
4295 }
4296 } else {
Glenn Kastena13cde92016-03-28 15:26:02 -07004297 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07004298 }
4299
4300 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004301 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004302 if (outputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004303 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004304 return BAD_VALUE;
4305 }
Eric Laurent84c70242014-06-23 08:46:27 -07004306 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
4307 outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004308 if (patchDesc != 0) {
4309 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004310 ALOGV("%s source id differs for patch current id %d new id %d",
4311 __func__, patchDesc->mPatch.sources[0].id, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004312 return BAD_VALUE;
4313 }
4314 }
Eric Laurent874c42872014-08-08 15:13:39 -07004315 DeviceVector devices;
4316 for (size_t i = 0; i < patch->num_sinks; i++) {
4317 // Only support mix to devices connection
4318 // TODO add support for mix to mix connection
4319 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004320 ALOGV("%s source mix but sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07004321 return INVALID_OPERATION;
4322 }
4323 sp<DeviceDescriptor> devDesc =
4324 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
4325 if (devDesc == 0) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004326 ALOGV("%s out device not found for id %d", __func__, patch->sinks[i].id);
Eric Laurent874c42872014-08-08 15:13:39 -07004327 return BAD_VALUE;
4328 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004329
François Gaffie11d30102018-11-02 16:09:09 +01004330 if (!outputDesc->mProfile->isCompatibleProfile(DeviceVector(devDesc),
Eric Laurent874c42872014-08-08 15:13:39 -07004331 patch->sources[0].sample_rate,
François Gaffie53615e22015-03-19 09:24:12 +01004332 NULL, // updatedSamplingRate
4333 patch->sources[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07004334 NULL, // updatedFormat
François Gaffie53615e22015-03-19 09:24:12 +01004335 patch->sources[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07004336 NULL, // updatedChannelMask
François Gaffie53615e22015-03-19 09:24:12 +01004337 AUDIO_OUTPUT_FLAG_NONE /*FIXME*/)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004338 ALOGV("%s profile not supported for device %08x", __func__, devDesc->type());
Eric Laurent874c42872014-08-08 15:13:39 -07004339 return INVALID_OPERATION;
4340 }
4341 devices.add(devDesc);
4342 }
4343 if (devices.size() == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004344 return INVALID_OPERATION;
4345 }
Eric Laurent874c42872014-08-08 15:13:39 -07004346
Eric Laurent6a94d692014-05-20 11:18:06 -07004347 // TODO: reconfigure output format and channels here
François Gaffieafd4cea2019-11-18 15:50:22 +01004348 ALOGV("%s setting device %s on output %d",
4349 __func__, dumpDeviceTypes(devices.types()).c_str(), outputDesc->mIoHandle);
François Gaffie11d30102018-11-02 16:09:09 +01004350 setOutputDevices(outputDesc, devices, true, 0, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004351 index = mAudioPatches.indexOfKey(*handle);
4352 if (index >= 0) {
4353 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004354 ALOGW("%s setOutputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004355 }
4356 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01004357 patchDesc->setUid(uid);
4358 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004359 } else {
François Gaffieafd4cea2019-11-18 15:50:22 +01004360 ALOGW("%s setOutputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004361 return INVALID_OPERATION;
4362 }
4363 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
4364 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
4365 // input device to input mix connection
Eric Laurent874c42872014-08-08 15:13:39 -07004366 // only one sink supported when connecting an input device to a mix
4367 if (patch->num_sinks > 1) {
4368 return INVALID_OPERATION;
4369 }
François Gaffie53615e22015-03-19 09:24:12 +01004370 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004371 if (inputDesc == NULL) {
4372 return BAD_VALUE;
4373 }
4374 if (patchDesc != 0) {
4375 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
4376 return BAD_VALUE;
4377 }
4378 }
François Gaffie11d30102018-11-02 16:09:09 +01004379 sp<DeviceDescriptor> device =
Eric Laurent6a94d692014-05-20 11:18:06 -07004380 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01004381 if (device == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004382 return BAD_VALUE;
4383 }
4384
François Gaffie11d30102018-11-02 16:09:09 +01004385 if (!inputDesc->mProfile->isCompatibleProfile(DeviceVector(device),
Eric Laurent275e8e92014-11-30 15:14:47 -08004386 patch->sinks[0].sample_rate,
4387 NULL, /*updatedSampleRate*/
4388 patch->sinks[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07004389 NULL, /*updatedFormat*/
Eric Laurent275e8e92014-11-30 15:14:47 -08004390 patch->sinks[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07004391 NULL, /*updatedChannelMask*/
Eric Laurent275e8e92014-11-30 15:14:47 -08004392 // FIXME for the parameter type,
4393 // and the NONE
4394 (audio_output_flags_t)
Glenn Kasten6a8ab052014-07-24 14:08:35 -07004395 AUDIO_INPUT_FLAG_NONE)) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004396 return INVALID_OPERATION;
4397 }
4398 // TODO: reconfigure output format and channels here
François Gaffieafd4cea2019-11-18 15:50:22 +01004399 ALOGV("%s setting device %s on output %d", __func__,
François Gaffie11d30102018-11-02 16:09:09 +01004400 device->toString().c_str(), inputDesc->mIoHandle);
4401 setInputDevice(inputDesc->mIoHandle, device, true, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004402 index = mAudioPatches.indexOfKey(*handle);
4403 if (index >= 0) {
4404 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004405 ALOGW("%s setInputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004406 }
4407 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01004408 patchDesc->setUid(uid);
4409 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004410 } else {
François Gaffieafd4cea2019-11-18 15:50:22 +01004411 ALOGW("%s setInputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004412 return INVALID_OPERATION;
4413 }
4414 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
4415 // device to device connection
4416 if (patchDesc != 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07004417 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004418 return BAD_VALUE;
4419 }
4420 }
François Gaffie11d30102018-11-02 16:09:09 +01004421 sp<DeviceDescriptor> srcDevice =
Eric Laurent6a94d692014-05-20 11:18:06 -07004422 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01004423 if (srcDevice == 0) {
Eric Laurent58f8eb72014-09-12 16:19:41 -07004424 return BAD_VALUE;
4425 }
Eric Laurent874c42872014-08-08 15:13:39 -07004426
Eric Laurent6a94d692014-05-20 11:18:06 -07004427 //update source and sink with our own data as the data passed in the patch may
4428 // be incomplete.
François Gaffieafd4cea2019-11-18 15:50:22 +01004429 PatchBuilder patchBuilder;
4430 audio_port_config sourcePortConfig = {};
Dean Wheatley8bee85a2021-02-10 16:02:23 +11004431
4432 // if first sink is to MSD, establish single MSD patch
4433 if (getMsdAudioOutDevices().contains(
4434 mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id))) {
4435 ALOGV("%s patching to MSD", __FUNCTION__);
4436 patchBuilder = buildMsdPatch(false /*msdIsSource*/, srcDevice);
4437 goto installPatch;
4438 }
4439
François Gaffieafd4cea2019-11-18 15:50:22 +01004440 srcDevice->toAudioPortConfig(&sourcePortConfig, &patch->sources[0]);
4441 patchBuilder.addSource(sourcePortConfig);
Eric Laurent6a94d692014-05-20 11:18:06 -07004442
Eric Laurent874c42872014-08-08 15:13:39 -07004443 for (size_t i = 0; i < patch->num_sinks; i++) {
4444 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004445 ALOGV("%s source device but one sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07004446 return INVALID_OPERATION;
4447 }
François Gaffie11d30102018-11-02 16:09:09 +01004448 sp<DeviceDescriptor> sinkDevice =
Eric Laurent874c42872014-08-08 15:13:39 -07004449 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
François Gaffie11d30102018-11-02 16:09:09 +01004450 if (sinkDevice == 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07004451 return BAD_VALUE;
4452 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004453 audio_port_config sinkPortConfig = {};
4454 sinkDevice->toAudioPortConfig(&sinkPortConfig, &patch->sinks[i]);
4455 patchBuilder.addSink(sinkPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07004456
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004457 // Whatever Sw or Hw bridge, we do attach an SwOutput to an Audio Source for
4458 // volume management purpose (tracking activity)
4459 // In case of Hw bridge, it is a Work Around. The mixPort used is the one declared
4460 // in config XML to reach the sink so that is can be declared as available.
4461 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
4462 sp<SwAudioOutputDescriptor> outputDesc = nullptr;
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004463 if (!sourceDesc->isInternal()) {
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004464 // take care of dynamic routing for SwOutput selection,
4465 audio_attributes_t attributes = sourceDesc->attributes();
4466 audio_stream_type_t stream = sourceDesc->stream();
4467 audio_attributes_t resultAttr;
4468 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
4469 config.sample_rate = sourceDesc->config().sample_rate;
4470 config.channel_mask = sourceDesc->config().channel_mask;
4471 config.format = sourceDesc->config().format;
4472 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
4473 audio_port_handle_t selectedDeviceId = AUDIO_PORT_HANDLE_NONE;
4474 bool isRequestedDeviceForExclusiveUse = false;
4475 output_type_t outputType;
Eric Laurentb0a7bc92022-04-05 15:06:08 +02004476 bool isSpatialized;
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004477 getOutputForAttrInt(&resultAttr, &output, AUDIO_SESSION_NONE, &attributes,
4478 &stream, sourceDesc->uid(), &config, &flags,
4479 &selectedDeviceId, &isRequestedDeviceForExclusiveUse,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02004480 nullptr, &outputType, &isSpatialized);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004481 if (output == AUDIO_IO_HANDLE_NONE) {
4482 ALOGV("%s no output for device %s",
4483 __FUNCTION__, sinkDevice->toString().c_str());
4484 return INVALID_OPERATION;
4485 }
4486 outputDesc = mOutputs.valueFor(output);
4487 if (outputDesc->isDuplicated()) {
4488 ALOGE("%s output is duplicated", __func__);
4489 return INVALID_OPERATION;
4490 }
4491 sourceDesc->setSwOutput(outputDesc);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004492 } else {
4493 // Same for "raw patches" aka created from createAudioPatch API
4494 SortedVector<audio_io_handle_t> outputs =
4495 getOutputsForDevices(DeviceVector(sinkDevice), mOutputs);
4496 // if the sink device is reachable via an opened output stream, request to
4497 // go via this output stream by adding a second source to the patch
4498 // description
4499 output = selectOutput(outputs);
4500 if (output == AUDIO_IO_HANDLE_NONE) {
4501 ALOGE("%s no output available for internal patch sink", __func__);
4502 return INVALID_OPERATION;
4503 }
4504 outputDesc = mOutputs.valueFor(output);
4505 if (outputDesc->isDuplicated()) {
4506 ALOGV("%s output for device %s is duplicated",
4507 __func__, sinkDevice->toString().c_str());
4508 return INVALID_OPERATION;
4509 }
4510 sourceDesc->setSwOutput(outputDesc);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004511 }
Eric Laurent3bcf8592015-04-03 12:13:24 -07004512 // create a software bridge in PatchPanel if:
Scott Randolphf3172402018-01-23 17:06:53 -08004513 // - source and sink devices are on different HW modules OR
Eric Laurent3bcf8592015-04-03 12:13:24 -07004514 // - audio HAL version is < 3.0
Francois Gaffie99896da2018-04-09 11:05:33 +02004515 // - audio HAL version is >= 3.0 but no route has been declared between devices
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004516 // - called from startAudioSource (aka sourceDesc is not internal) and source device
4517 // does not have a gain controller
François Gaffie11d30102018-11-02 16:09:09 +01004518 if (!srcDevice->hasSameHwModuleAs(sinkDevice) ||
4519 (srcDevice->getModuleVersionMajor() < 3) ||
François Gaffieafd4cea2019-11-18 15:50:22 +01004520 !srcDevice->getModule()->supportsPatch(srcDevice, sinkDevice) ||
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004521 (!sourceDesc->isInternal() &&
François Gaffieafd4cea2019-11-18 15:50:22 +01004522 srcDevice->getAudioPort()->getGains().size() == 0)) {
Eric Laurent3bcf8592015-04-03 12:13:24 -07004523 // support only one sink device for now to simplify output selection logic
Eric Laurent874c42872014-08-08 15:13:39 -07004524 if (patch->num_sinks > 1) {
Eric Laurent83b88082014-06-20 18:31:16 -07004525 return INVALID_OPERATION;
4526 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004527 sourceDesc->setUseSwBridge();
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004528 if (outputDesc != nullptr) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004529 audio_port_config srcMixPortConfig = {};
Ytai Ben-Tsvic9d2a912021-11-22 16:43:09 -08004530 outputDesc->toAudioPortConfig(&srcMixPortConfig, nullptr);
François Gaffieafd4cea2019-11-18 15:50:22 +01004531 // for volume control, we may need a valid stream
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004532 srcMixPortConfig.ext.mix.usecase.stream = !sourceDesc->isInternal() ?
4533 mEngine->getStreamTypeForAttributes(sourceDesc->attributes()) :
4534 AUDIO_STREAM_PATCH;
François Gaffieafd4cea2019-11-18 15:50:22 +01004535 patchBuilder.addSource(srcMixPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07004536 }
Eric Laurent83b88082014-06-20 18:31:16 -07004537 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004538 }
4539 // TODO: check from routing capabilities in config file and other conflicting patches
4540
Dean Wheatley8bee85a2021-02-10 16:02:23 +11004541installPatch:
François Gaffieafd4cea2019-11-18 15:50:22 +01004542 status_t status = installPatch(
4543 __func__, index, handle, patchBuilder.patch(), delayMs, uid, &patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07004544 if (status != NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004545 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
Eric Laurent6a94d692014-05-20 11:18:06 -07004546 return INVALID_OPERATION;
4547 }
4548 } else {
4549 return BAD_VALUE;
4550 }
4551 } else {
4552 return BAD_VALUE;
4553 }
4554 return NO_ERROR;
4555}
4556
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004557status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle, uid_t uid)
Eric Laurent6a94d692014-05-20 11:18:06 -07004558{
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004559 ALOGV("%s patch %d", __func__, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004560 ssize_t index = mAudioPatches.indexOfKey(handle);
4561
4562 if (index < 0) {
4563 return BAD_VALUE;
4564 }
4565 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01004566 ALOGV("%s() mUidCached %d patchDesc->mUid %d uid %d",
4567 __func__, mUidCached, patchDesc->getUid(), uid);
4568 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004569 return INVALID_OPERATION;
4570 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004571 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
4572 for (size_t i = 0; i < mAudioSources.size(); i++) {
4573 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
4574 if (sourceDesc != nullptr && sourceDesc->getPatchHandle() == handle) {
4575 portId = sourceDesc->portId();
4576 break;
4577 }
4578 }
4579 return portId != AUDIO_PORT_HANDLE_NONE ?
4580 stopAudioSource(portId) : releaseAudioPatchInternal(handle);
François Gaffieafd4cea2019-11-18 15:50:22 +01004581}
Eric Laurent6a94d692014-05-20 11:18:06 -07004582
François Gaffieafd4cea2019-11-18 15:50:22 +01004583status_t AudioPolicyManager::releaseAudioPatchInternal(audio_patch_handle_t handle,
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004584 uint32_t delayMs,
4585 const sp<SourceClientDescriptor>& sourceDesc)
François Gaffieafd4cea2019-11-18 15:50:22 +01004586{
4587 ALOGV("%s patch %d", __func__, handle);
4588 if (mAudioPatches.indexOfKey(handle) < 0) {
4589 ALOGE("%s: no patch found with handle=%d", __func__, handle);
4590 return BAD_VALUE;
4591 }
4592 sp<AudioPatch> patchDesc = mAudioPatches.valueFor(handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004593 struct audio_patch *patch = &patchDesc->mPatch;
François Gaffieafd4cea2019-11-18 15:50:22 +01004594 patchDesc->setUid(mUidCached);
Eric Laurent6a94d692014-05-20 11:18:06 -07004595 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004596 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004597 if (outputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004598 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004599 return BAD_VALUE;
4600 }
4601
François Gaffie11d30102018-11-02 16:09:09 +01004602 setOutputDevices(outputDesc,
4603 getNewOutputDevices(outputDesc, true /*fromCache*/),
4604 true,
4605 0,
4606 NULL);
Eric Laurent6a94d692014-05-20 11:18:06 -07004607 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
4608 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
François Gaffie53615e22015-03-19 09:24:12 +01004609 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004610 if (inputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004611 ALOGV("%s input not found for id %d", __func__, patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004612 return BAD_VALUE;
4613 }
4614 setInputDevice(inputDesc->mIoHandle,
Eric Laurentfb66dd92016-01-28 18:32:03 -08004615 getNewInputDevice(inputDesc),
Eric Laurent6a94d692014-05-20 11:18:06 -07004616 true,
4617 NULL);
4618 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004619 status_t status =
4620 mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
4621 ALOGV("%s patch panel returned %d patchHandle %d",
4622 __func__, status, patchDesc->getAfHandle());
4623 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004624 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004625 mpClientInterface->onAudioPatchListUpdate();
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004626 // SW or HW Bridge
4627 sp<SwAudioOutputDescriptor> outputDesc = nullptr;
4628 audio_patch_handle_t patchHandle = AUDIO_PATCH_HANDLE_NONE;
Francois Gaffie7feb8542020-04-06 17:39:47 +02004629 if (patch->num_sources > 1 && patch->sources[1].type == AUDIO_PORT_TYPE_MIX) {
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004630 outputDesc = mOutputs.getOutputFromId(patch->sources[1].id);
4631 } else if (patch->num_sources == 1 && sourceDesc != nullptr) {
4632 outputDesc = sourceDesc->swOutput().promote();
4633 }
4634 if (outputDesc == nullptr) {
4635 ALOGW("%s no output for id %d", __func__, patch->sources[0].id);
4636 // releaseOutput has already called closeOutput in case of direct output
4637 return NO_ERROR;
4638 }
4639 if (!outputDesc->isActive() && !sourceDesc->useSwBridge()) {
4640 resetOutputDevice(outputDesc);
4641 } else {
4642 // Reuse patch handle if still valid / do not force rerouting if still routed
4643 patchHandle = outputDesc->getPatchHandle();
Francois Gaffie7feb8542020-04-06 17:39:47 +02004644 setOutputDevices(outputDesc,
4645 getNewOutputDevices(outputDesc, true /*fromCache*/),
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004646 patchHandle == AUDIO_PATCH_HANDLE_NONE, /*force*/
Francois Gaffie7feb8542020-04-06 17:39:47 +02004647 0,
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004648 patchHandle == AUDIO_PATCH_HANDLE_NONE ? nullptr : &patchHandle);
Francois Gaffie7feb8542020-04-06 17:39:47 +02004649 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004650 } else {
4651 return BAD_VALUE;
4652 }
4653 } else {
4654 return BAD_VALUE;
4655 }
4656 return NO_ERROR;
4657}
4658
4659status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
4660 struct audio_patch *patches,
4661 unsigned int *generation)
4662{
François Gaffie53615e22015-03-19 09:24:12 +01004663 if (generation == NULL) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004664 return BAD_VALUE;
4665 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004666 *generation = curAudioPortGeneration();
François Gaffie53615e22015-03-19 09:24:12 +01004667 return mAudioPatches.listAudioPatches(num_patches, patches);
Eric Laurent6a94d692014-05-20 11:18:06 -07004668}
4669
Eric Laurente1715a42014-05-20 11:30:42 -07004670status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07004671{
Eric Laurente1715a42014-05-20 11:30:42 -07004672 ALOGV("setAudioPortConfig()");
4673
4674 if (config == NULL) {
4675 return BAD_VALUE;
4676 }
4677 ALOGV("setAudioPortConfig() on port handle %d", config->id);
4678 // Only support gain configuration for now
Eric Laurenta121f902014-06-03 13:32:54 -07004679 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
4680 return INVALID_OPERATION;
Eric Laurente1715a42014-05-20 11:30:42 -07004681 }
4682
Eric Laurenta121f902014-06-03 13:32:54 -07004683 sp<AudioPortConfig> audioPortConfig;
Eric Laurente1715a42014-05-20 11:30:42 -07004684 if (config->type == AUDIO_PORT_TYPE_MIX) {
4685 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004686 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07004687 if (outputDesc == NULL) {
4688 return BAD_VALUE;
4689 }
Eric Laurent84c70242014-06-23 08:46:27 -07004690 ALOG_ASSERT(!outputDesc->isDuplicated(),
4691 "setAudioPortConfig() called on duplicated output %d",
4692 outputDesc->mIoHandle);
Eric Laurenta121f902014-06-03 13:32:54 -07004693 audioPortConfig = outputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07004694 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
François Gaffie53615e22015-03-19 09:24:12 +01004695 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07004696 if (inputDesc == NULL) {
4697 return BAD_VALUE;
4698 }
Eric Laurenta121f902014-06-03 13:32:54 -07004699 audioPortConfig = inputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07004700 } else {
4701 return BAD_VALUE;
4702 }
4703 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
4704 sp<DeviceDescriptor> deviceDesc;
4705 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
4706 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
4707 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
4708 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
4709 } else {
4710 return BAD_VALUE;
4711 }
4712 if (deviceDesc == NULL) {
4713 return BAD_VALUE;
4714 }
Eric Laurenta121f902014-06-03 13:32:54 -07004715 audioPortConfig = deviceDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07004716 } else {
4717 return BAD_VALUE;
4718 }
4719
Mikhail Naganov7be71d22018-05-23 16:51:46 -07004720 struct audio_port_config backupConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07004721 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
4722 if (status == NO_ERROR) {
Mikhail Naganov7be71d22018-05-23 16:51:46 -07004723 struct audio_port_config newConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07004724 audioPortConfig->toAudioPortConfig(&newConfig, config);
4725 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
Eric Laurente1715a42014-05-20 11:30:42 -07004726 }
Eric Laurenta121f902014-06-03 13:32:54 -07004727 if (status != NO_ERROR) {
4728 audioPortConfig->applyAudioPortConfig(&backupConfig);
Eric Laurente1715a42014-05-20 11:30:42 -07004729 }
Eric Laurente1715a42014-05-20 11:30:42 -07004730
4731 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07004732}
4733
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004734void AudioPolicyManager::releaseResourcesForUid(uid_t uid)
4735{
Eric Laurentd60560a2015-04-10 11:31:20 -07004736 clearAudioSources(uid);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004737 clearAudioPatches(uid);
4738 clearSessionRoutes(uid);
4739}
4740
Eric Laurent6a94d692014-05-20 11:18:06 -07004741void AudioPolicyManager::clearAudioPatches(uid_t uid)
4742{
Eric Laurent0add0fd2014-12-04 18:58:14 -08004743 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004744 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
François Gaffieafd4cea2019-11-18 15:50:22 +01004745 if (patchDesc->getUid() == uid) {
Eric Laurent0add0fd2014-12-04 18:58:14 -08004746 releaseAudioPatch(mAudioPatches.keyAt(i), uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07004747 }
4748 }
4749}
4750
François Gaffiec005e562018-11-06 15:04:49 +01004751void AudioPolicyManager::checkStrategyRoute(product_strategy_t ps, audio_io_handle_t ouptutToSkip)
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004752{
François Gaffiec005e562018-11-06 15:04:49 +01004753 // Take the first attributes following the product strategy as it is used to retrieve the routed
4754 // device. All attributes wihin a strategy follows the same "routing strategy"
4755 auto attributes = mEngine->getAllAttributesForProductStrategy(ps).front();
4756 DeviceVector devices = mEngine->getOutputDevicesForAttributes(attributes, nullptr, false);
François Gaffie11d30102018-11-02 16:09:09 +01004757 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004758 for (size_t j = 0; j < mOutputs.size(); j++) {
4759 if (mOutputs.keyAt(j) == ouptutToSkip) {
4760 continue;
4761 }
4762 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(j);
François Gaffiec005e562018-11-06 15:04:49 +01004763 if (!outputDesc->isStrategyActive(ps)) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004764 continue;
4765 }
4766 // If the default device for this strategy is on another output mix,
4767 // invalidate all tracks in this strategy to force re connection.
4768 // Otherwise select new device on the output mix.
4769 if (outputs.indexOf(mOutputs.keyAt(j)) < 0) {
François Gaffiec005e562018-11-06 15:04:49 +01004770 for (auto stream : mEngine->getStreamTypesForProductStrategy(ps)) {
4771 mpClientInterface->invalidateStream(stream);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004772 }
4773 } else {
François Gaffie11d30102018-11-02 16:09:09 +01004774 setOutputDevices(
4775 outputDesc, getNewOutputDevices(outputDesc, false /*fromCache*/), false);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004776 }
4777 }
4778}
4779
4780void AudioPolicyManager::clearSessionRoutes(uid_t uid)
4781{
4782 // remove output routes associated with this uid
François Gaffiec005e562018-11-06 15:04:49 +01004783 std::vector<product_strategy_t> affectedStrategies;
Eric Laurent97ac8712018-07-27 18:59:02 -07004784 for (size_t i = 0; i < mOutputs.size(); i++) {
4785 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07004786 for (const auto& client : outputDesc->getClientIterable()) {
4787 if (client->hasPreferredDevice() && client->uid() == uid) {
4788 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
François Gaffiec005e562018-11-06 15:04:49 +01004789 auto clientStrategy = client->strategy();
4790 if (std::find(begin(affectedStrategies), end(affectedStrategies), clientStrategy) !=
4791 end(affectedStrategies)) {
4792 continue;
4793 }
4794 affectedStrategies.push_back(client->strategy());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004795 }
4796 }
4797 }
4798 // reroute outputs if necessary
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004799 for (const auto& strategy : affectedStrategies) {
4800 checkStrategyRoute(strategy, AUDIO_IO_HANDLE_NONE);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004801 }
4802
4803 // remove input routes associated with this uid
4804 SortedVector<audio_source_t> affectedSources;
Eric Laurent97ac8712018-07-27 18:59:02 -07004805 for (size_t i = 0; i < mInputs.size(); i++) {
4806 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07004807 for (const auto& client : inputDesc->getClientIterable()) {
4808 if (client->hasPreferredDevice() && client->uid() == uid) {
4809 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
4810 affectedSources.add(client->source());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004811 }
4812 }
4813 }
4814 // reroute inputs if necessary
4815 SortedVector<audio_io_handle_t> inputsToClose;
4816 for (size_t i = 0; i < mInputs.size(); i++) {
4817 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Eric Laurent4eb58f12018-12-07 16:41:02 -08004818 if (affectedSources.indexOf(inputDesc->source()) >= 0) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004819 inputsToClose.add(inputDesc->mIoHandle);
4820 }
4821 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004822 for (const auto& input : inputsToClose) {
4823 closeInput(input);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004824 }
4825}
4826
Eric Laurentd60560a2015-04-10 11:31:20 -07004827void AudioPolicyManager::clearAudioSources(uid_t uid)
4828{
4829 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004830 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
4831 if (sourceDesc->uid() == uid) {
Eric Laurentd60560a2015-04-10 11:31:20 -07004832 stopAudioSource(mAudioSources.keyAt(i));
4833 }
4834 }
4835}
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004836
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07004837status_t AudioPolicyManager::acquireSoundTriggerSession(audio_session_t *session,
4838 audio_io_handle_t *ioHandle,
4839 audio_devices_t *device)
4840{
Glenn Kastenf0c6d7d2016-02-26 10:44:04 -08004841 *session = (audio_session_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
4842 *ioHandle = (audio_io_handle_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
Francois Gaffie716e1432019-01-14 16:58:59 +01004843 audio_attributes_t attr = { .source = AUDIO_SOURCE_HOTWORD };
François Gaffiec005e562018-11-06 15:04:49 +01004844 *device = mEngine->getInputDeviceForAttributes(attr)->type();
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07004845
François Gaffiedf372692015-03-19 10:43:27 +01004846 return mSoundTriggerSessions.acquireSession(*session, *ioHandle);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07004847}
4848
Eric Laurentd60560a2015-04-10 11:31:20 -07004849status_t AudioPolicyManager::startAudioSource(const struct audio_port_config *source,
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004850 const audio_attributes_t *attributes,
4851 audio_port_handle_t *portId,
4852 uid_t uid)
Eric Laurent554a2772015-04-10 11:29:24 -07004853{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004854 ALOGV("%s", __FUNCTION__);
4855 *portId = AUDIO_PORT_HANDLE_NONE;
4856
4857 if (source == NULL || attributes == NULL || portId == NULL) {
4858 ALOGW("%s invalid argument: source %p attributes %p handle %p",
4859 __FUNCTION__, source, attributes, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07004860 return BAD_VALUE;
4861 }
4862
Eric Laurentd60560a2015-04-10 11:31:20 -07004863 if (source->role != AUDIO_PORT_ROLE_SOURCE ||
4864 source->type != AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004865 ALOGW("%s INVALID_OPERATION source->role %d source->type %d",
4866 __FUNCTION__, source->role, source->type);
Eric Laurentd60560a2015-04-10 11:31:20 -07004867 return INVALID_OPERATION;
4868 }
4869
François Gaffie11d30102018-11-02 16:09:09 +01004870 sp<DeviceDescriptor> srcDevice =
Eric Laurentd60560a2015-04-10 11:31:20 -07004871 mAvailableInputDevices.getDevice(source->ext.device.type,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08004872 String8(source->ext.device.address),
4873 AUDIO_FORMAT_DEFAULT);
François Gaffie11d30102018-11-02 16:09:09 +01004874 if (srcDevice == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004875 ALOGW("%s source->ext.device.type %08x not found", __FUNCTION__, source->ext.device.type);
Eric Laurentd60560a2015-04-10 11:31:20 -07004876 return BAD_VALUE;
4877 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004878
jiabin4ef93452019-09-10 14:29:54 -07004879 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurentd60560a2015-04-10 11:31:20 -07004880
François Gaffieaaac0fd2018-11-22 17:56:39 +01004881 sp<SourceClientDescriptor> sourceDesc =
François Gaffieafd4cea2019-11-18 15:50:22 +01004882 new SourceClientDescriptor(*portId, uid, *attributes, *source, srcDevice,
François Gaffieaaac0fd2018-11-22 17:56:39 +01004883 mEngine->getStreamTypeForAttributes(*attributes),
4884 mEngine->getProductStrategyForAttributes(*attributes),
4885 toVolumeSource(*attributes));
Eric Laurentd60560a2015-04-10 11:31:20 -07004886
4887 status_t status = connectAudioSource(sourceDesc);
4888 if (status == NO_ERROR) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004889 mAudioSources.add(*portId, sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07004890 }
4891 return status;
4892}
4893
Francois Gaffie601801d2021-06-22 13:27:39 +02004894sp<SourceClientDescriptor> AudioPolicyManager::startAudioSourceInternal(
4895 const struct audio_port_config *source, const audio_attributes_t *attributes, uid_t uid)
4896{
4897 ALOGV("%s", __FUNCTION__);
4898 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
4899
4900 status_t status = startAudioSource(source, attributes, &portId, uid);
4901 ALOGE_IF(status != OK, "%s: failed to start audio source (%d)", __func__, status);
4902 return mAudioSources.valueFor(portId);
4903}
4904
4905
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004906status_t AudioPolicyManager::connectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07004907{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004908 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->portId());
Eric Laurentd60560a2015-04-10 11:31:20 -07004909
4910 // make sure we only have one patch per source.
4911 disconnectAudioSource(sourceDesc);
4912
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004913 audio_attributes_t attributes = sourceDesc->attributes();
Francois Gaffiea0e5c992020-09-29 16:05:07 +02004914 // May the device (dynamic) have been disconnected/reconnected, id has changed.
4915 sp<DeviceDescriptor> srcDevice = mAvailableInputDevices.getDevice(
4916 sourceDesc->srcDevice()->type(),
4917 String8(sourceDesc->srcDevice()->address().c_str()),
4918 AUDIO_FORMAT_DEFAULT);
François Gaffiec005e562018-11-06 15:04:49 +01004919 DeviceVector sinkDevices =
Francois Gaffieff1eb522020-05-06 18:37:04 +02004920 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false /*fromCache*/);
François Gaffiec005e562018-11-06 15:04:49 +01004921 ALOG_ASSERT(!sinkDevices.isEmpty(), "connectAudioSource(): no device found for attributes");
François Gaffie11d30102018-11-02 16:09:09 +01004922 sp<DeviceDescriptor> sinkDevice = sinkDevices.itemAt(0);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02004923 if (!mAvailableOutputDevices.contains(sinkDevice)) {
4924 ALOGE("%s Device %s not available", __func__, sinkDevice->toString().c_str());
4925 return INVALID_OPERATION;
4926 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004927 PatchBuilder patchBuilder;
4928 patchBuilder.addSink(sinkDevice).addSource(srcDevice);
4929 audio_patch_handle_t handle = AUDIO_PATCH_HANDLE_NONE;
François Gaffieafd4cea2019-11-18 15:50:22 +01004930
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004931 return connectAudioSourceToSink(
4932 sourceDesc, sinkDevice, patchBuilder.patch(), handle, mUidCached, 0 /*delayMs*/);
Eric Laurent554a2772015-04-10 11:29:24 -07004933}
4934
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004935status_t AudioPolicyManager::stopAudioSource(audio_port_handle_t portId)
Eric Laurent554a2772015-04-10 11:29:24 -07004936{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004937 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueFor(portId);
4938 ALOGV("%s port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07004939 if (sourceDesc == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004940 ALOGW("%s unknown source for port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07004941 return BAD_VALUE;
4942 }
4943 status_t status = disconnectAudioSource(sourceDesc);
4944
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004945 mAudioSources.removeItem(portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07004946 return status;
4947}
4948
Andy Hung2ddee192015-12-18 17:34:44 -08004949status_t AudioPolicyManager::setMasterMono(bool mono)
4950{
4951 if (mMasterMono == mono) {
4952 return NO_ERROR;
4953 }
4954 mMasterMono = mono;
4955 // if enabling mono we close all offloaded devices, which will invalidate the
4956 // corresponding AudioTrack. The AudioTrack client/MediaPlayer is responsible
4957 // for recreating the new AudioTrack as non-offloaded PCM.
4958 //
4959 // If disabling mono, we leave all tracks as is: we don't know which clients
4960 // and tracks are able to be recreated as offloaded. The next "song" should
4961 // play back offloaded.
4962 if (mMasterMono) {
4963 Vector<audio_io_handle_t> offloaded;
4964 for (size_t i = 0; i < mOutputs.size(); ++i) {
4965 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
4966 if (desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
4967 offloaded.push(desc->mIoHandle);
4968 }
4969 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004970 for (const auto& handle : offloaded) {
4971 closeOutput(handle);
Andy Hung2ddee192015-12-18 17:34:44 -08004972 }
4973 }
4974 // update master mono for all remaining outputs
4975 for (size_t i = 0; i < mOutputs.size(); ++i) {
4976 updateMono(mOutputs.keyAt(i));
4977 }
4978 return NO_ERROR;
4979}
4980
4981status_t AudioPolicyManager::getMasterMono(bool *mono)
4982{
4983 *mono = mMasterMono;
4984 return NO_ERROR;
4985}
4986
Eric Laurentac9cef52017-06-09 15:46:26 -07004987float AudioPolicyManager::getStreamVolumeDB(
4988 audio_stream_type_t stream, int index, audio_devices_t device)
4989{
jiabin9a3361e2019-10-01 09:38:30 -07004990 return computeVolume(getVolumeCurves(stream), toVolumeSource(stream), index, {device});
Eric Laurentac9cef52017-06-09 15:46:26 -07004991}
4992
jiabin81772902018-04-02 17:52:27 -07004993status_t AudioPolicyManager::getSurroundFormats(unsigned int *numSurroundFormats,
4994 audio_format_t *surroundFormats,
Kriti Dang6537def2021-03-02 13:46:59 +01004995 bool *surroundFormatsEnabled)
jiabin81772902018-04-02 17:52:27 -07004996{
Kriti Dang6537def2021-03-02 13:46:59 +01004997 if (numSurroundFormats == nullptr || (*numSurroundFormats != 0 &&
4998 (surroundFormats == nullptr || surroundFormatsEnabled == nullptr))) {
jiabin81772902018-04-02 17:52:27 -07004999 return BAD_VALUE;
5000 }
Kriti Dang6537def2021-03-02 13:46:59 +01005001 ALOGV("%s() numSurroundFormats %d surroundFormats %p surroundFormatsEnabled %p",
5002 __func__, *numSurroundFormats, surroundFormats, surroundFormatsEnabled);
jiabin81772902018-04-02 17:52:27 -07005003
5004 size_t formatsWritten = 0;
5005 size_t formatsMax = *numSurroundFormats;
Kriti Dangef6be8f2020-11-05 11:58:19 +01005006
Kriti Dang6537def2021-03-02 13:46:59 +01005007 *numSurroundFormats = mConfig.getSurroundFormats().size();
Mikhail Naganov100f0122018-11-29 11:22:16 -08005008 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
5009 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Kriti Dang6537def2021-03-02 13:46:59 +01005010 for (const auto& format: mConfig.getSurroundFormats()) {
jiabin81772902018-04-02 17:52:27 -07005011 if (formatsWritten < formatsMax) {
Kriti Dang6537def2021-03-02 13:46:59 +01005012 surroundFormats[formatsWritten] = format.first;
Mikhail Naganov100f0122018-11-29 11:22:16 -08005013 bool formatEnabled = true;
5014 switch (forceUse) {
5015 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL:
Kriti Dang6537def2021-03-02 13:46:59 +01005016 formatEnabled = mManualSurroundFormats.count(format.first) != 0;
Mikhail Naganov100f0122018-11-29 11:22:16 -08005017 break;
5018 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER:
5019 formatEnabled = false;
5020 break;
5021 default: // AUTO or ALWAYS => true
5022 break;
jiabin81772902018-04-02 17:52:27 -07005023 }
5024 surroundFormatsEnabled[formatsWritten++] = formatEnabled;
5025 }
jiabin81772902018-04-02 17:52:27 -07005026 }
5027 return NO_ERROR;
5028}
5029
Kriti Dang6537def2021-03-02 13:46:59 +01005030status_t AudioPolicyManager::getReportedSurroundFormats(unsigned int *numSurroundFormats,
5031 audio_format_t *surroundFormats) {
5032 if (numSurroundFormats == nullptr || (*numSurroundFormats != 0 && surroundFormats == nullptr)) {
5033 return BAD_VALUE;
5034 }
5035 ALOGV("%s() numSurroundFormats %d surroundFormats %p",
5036 __func__, *numSurroundFormats, surroundFormats);
5037
5038 size_t formatsWritten = 0;
5039 size_t formatsMax = *numSurroundFormats;
5040 std::unordered_set<audio_format_t> formats; // Uses primary surround formats only
5041
5042 // Return formats from all device profiles that have already been resolved by
5043 // checkOutputsForDevice().
5044 for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
5045 sp<DeviceDescriptor> device = mAvailableOutputDevices[i];
5046 audio_devices_t deviceType = device->type();
5047 // Enabling/disabling formats are applied to only HDMI devices. So, this function
5048 // returns formats reported by HDMI devices.
5049 if (deviceType != AUDIO_DEVICE_OUT_HDMI) {
5050 continue;
5051 }
5052 // Formats reported by sink devices
5053 std::unordered_set<audio_format_t> formatset;
5054 if (auto it = mReportedFormatsMap.find(device); it != mReportedFormatsMap.end()) {
5055 formatset.insert(it->second.begin(), it->second.end());
5056 }
5057
5058 // Formats hard-coded in the in policy configuration file (if any).
5059 FormatVector encodedFormats = device->encodedFormats();
5060 formatset.insert(encodedFormats.begin(), encodedFormats.end());
5061 // Filter the formats which are supported by the vendor hardware.
5062 for (auto it = formatset.begin(); it != formatset.end(); ++it) {
5063 if (mConfig.getSurroundFormats().count(*it) != 0) {
5064 formats.insert(*it);
5065 } else {
5066 for (const auto& pair : mConfig.getSurroundFormats()) {
5067 if (pair.second.count(*it) != 0) {
5068 formats.insert(pair.first);
5069 break;
5070 }
5071 }
5072 }
5073 }
5074 }
5075 *numSurroundFormats = formats.size();
5076 for (const auto& format: formats) {
5077 if (formatsWritten < formatsMax) {
5078 surroundFormats[formatsWritten++] = format;
5079 }
5080 }
5081 return NO_ERROR;
5082}
5083
jiabin81772902018-04-02 17:52:27 -07005084status_t AudioPolicyManager::setSurroundFormatEnabled(audio_format_t audioFormat, bool enabled)
5085{
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005086 ALOGV("%s() format 0x%X enabled %d", __func__, audioFormat, enabled);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07005087 const auto& formatIter = mConfig.getSurroundFormats().find(audioFormat);
5088 if (formatIter == mConfig.getSurroundFormats().end()) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005089 ALOGW("%s() format 0x%X is not a known surround format", __func__, audioFormat);
jiabin81772902018-04-02 17:52:27 -07005090 return BAD_VALUE;
5091 }
5092
Mikhail Naganov100f0122018-11-29 11:22:16 -08005093 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND) !=
5094 AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005095 ALOGW("%s() not in manual mode for surround sound format selection", __func__);
jiabin81772902018-04-02 17:52:27 -07005096 return INVALID_OPERATION;
5097 }
5098
Mikhail Naganov100f0122018-11-29 11:22:16 -08005099 if ((mManualSurroundFormats.count(audioFormat) != 0) == enabled) {
jiabin81772902018-04-02 17:52:27 -07005100 return NO_ERROR;
5101 }
5102
Mikhail Naganov100f0122018-11-29 11:22:16 -08005103 std::unordered_set<audio_format_t> surroundFormatsBackup(mManualSurroundFormats);
jiabin81772902018-04-02 17:52:27 -07005104 if (enabled) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005105 mManualSurroundFormats.insert(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07005106 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005107 mManualSurroundFormats.insert(subFormat);
jiabin81772902018-04-02 17:52:27 -07005108 }
5109 } else {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005110 mManualSurroundFormats.erase(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07005111 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005112 mManualSurroundFormats.erase(subFormat);
jiabin81772902018-04-02 17:52:27 -07005113 }
5114 }
5115
5116 sp<SwAudioOutputDescriptor> outputDesc;
5117 bool profileUpdated = false;
jiabin9a3361e2019-10-01 09:38:30 -07005118 DeviceVector hdmiOutputDevices = mAvailableOutputDevices.getDevicesFromType(
5119 AUDIO_DEVICE_OUT_HDMI);
jiabin81772902018-04-02 17:52:27 -07005120 for (size_t i = 0; i < hdmiOutputDevices.size(); i++) {
5121 // Simulate reconnection to update enabled surround sound formats.
jiabince9f20e2019-09-12 16:29:15 -07005122 String8 address = String8(hdmiOutputDevices[i]->address().c_str());
jiabin5740f082019-08-19 15:08:30 -07005123 std::string name = hdmiOutputDevices[i]->getName();
jiabin81772902018-04-02 17:52:27 -07005124 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
5125 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
5126 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005127 name.c_str(),
5128 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005129 if (status != NO_ERROR) {
5130 continue;
5131 }
5132 status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
5133 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
5134 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005135 name.c_str(),
5136 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005137 profileUpdated |= (status == NO_ERROR);
5138 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08005139 // FIXME: Why doing this for input HDMI devices if we don't augment their reported formats?
jiabin9a3361e2019-10-01 09:38:30 -07005140 DeviceVector hdmiInputDevices = mAvailableInputDevices.getDevicesFromType(
jiabin81772902018-04-02 17:52:27 -07005141 AUDIO_DEVICE_IN_HDMI);
5142 for (size_t i = 0; i < hdmiInputDevices.size(); i++) {
5143 // Simulate reconnection to update enabled surround sound formats.
jiabince9f20e2019-09-12 16:29:15 -07005144 String8 address = String8(hdmiInputDevices[i]->address().c_str());
jiabin5740f082019-08-19 15:08:30 -07005145 std::string name = hdmiInputDevices[i]->getName();
jiabin81772902018-04-02 17:52:27 -07005146 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
5147 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
5148 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005149 name.c_str(),
5150 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005151 if (status != NO_ERROR) {
5152 continue;
5153 }
5154 status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
5155 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
5156 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005157 name.c_str(),
5158 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005159 profileUpdated |= (status == NO_ERROR);
5160 }
5161
jiabin81772902018-04-02 17:52:27 -07005162 if (!profileUpdated) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005163 ALOGW("%s() no audio profiles updated, undoing surround formats change", __func__);
Mikhail Naganov100f0122018-11-29 11:22:16 -08005164 mManualSurroundFormats = std::move(surroundFormatsBackup);
jiabin81772902018-04-02 17:52:27 -07005165 }
5166
5167 return profileUpdated ? NO_ERROR : INVALID_OPERATION;
5168}
5169
Eric Laurent5ada82e2019-08-29 17:53:54 -07005170void AudioPolicyManager::setAppState(audio_port_handle_t portId, app_state_t state)
Svet Ganovf4ddfef2018-01-16 07:37:58 -08005171{
Eric Laurent5ada82e2019-08-29 17:53:54 -07005172 ALOGV("%s(portId:%d, state:%d)", __func__, portId, state);
Eric Laurenta9f86652018-11-28 17:23:11 -08005173 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent5ada82e2019-08-29 17:53:54 -07005174 mInputs.valueAt(i)->setAppState(portId, state);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08005175 }
5176}
5177
jiabin6012f912018-11-02 17:06:30 -07005178bool AudioPolicyManager::isHapticPlaybackSupported()
5179{
5180 for (const auto& hwModule : mHwModules) {
5181 const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
5182 for (const auto &outProfile : outputProfiles) {
5183 struct audio_port audioPort;
5184 outProfile->toAudioPort(&audioPort);
5185 for (size_t i = 0; i < audioPort.num_channel_masks; i++) {
5186 if (audioPort.channel_masks[i] & AUDIO_CHANNEL_HAPTIC_ALL) {
5187 return true;
5188 }
5189 }
5190 }
5191 }
5192 return false;
5193}
5194
Carter Hsu325a8eb2022-01-19 19:56:51 +08005195bool AudioPolicyManager::isUltrasoundSupported()
5196{
5197 bool hasUltrasoundOutput = false;
5198 bool hasUltrasoundInput = false;
5199 for (const auto& hwModule : mHwModules) {
5200 const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
5201 if (!hasUltrasoundOutput) {
5202 for (const auto &outProfile : outputProfiles) {
5203 if (outProfile->getFlags() & AUDIO_OUTPUT_FLAG_ULTRASOUND) {
5204 hasUltrasoundOutput = true;
5205 break;
5206 }
5207 }
5208 }
5209
5210 const InputProfileCollection &inputProfiles = hwModule->getInputProfiles();
5211 if (!hasUltrasoundInput) {
5212 for (const auto &inputProfile : inputProfiles) {
5213 if (inputProfile->getFlags() & AUDIO_INPUT_FLAG_ULTRASOUND) {
5214 hasUltrasoundInput = true;
5215 break;
5216 }
5217 }
5218 }
5219
5220 if (hasUltrasoundOutput && hasUltrasoundInput)
5221 return true;
5222 }
5223 return false;
5224}
5225
Eric Laurent8340e672019-11-06 11:01:08 -08005226bool AudioPolicyManager::isCallScreenModeSupported()
5227{
5228 return getConfig().isCallScreenModeSupported();
5229}
5230
5231
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005232status_t AudioPolicyManager::disconnectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07005233{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005234 ALOGV("%s port Id %d", __FUNCTION__, sourceDesc->portId());
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005235 if (!sourceDesc->isConnected()) {
5236 ALOGV("%s port Id %d already disconnected", __FUNCTION__, sourceDesc->portId());
5237 return NO_ERROR;
5238 }
François Gaffieafd4cea2019-11-18 15:50:22 +01005239 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
5240 if (swOutput != 0) {
5241 status_t status = stopSource(swOutput, sourceDesc);
Eric Laurent733ce942017-12-07 12:18:25 -08005242 if (status == NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005243 swOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08005244 }
jiabinbce0c1d2020-10-05 11:20:18 -07005245 if (releaseOutput(sourceDesc->portId())) {
5246 // The output descriptor is reopened to query dynamic profiles. In that case, there is
5247 // no need to release audio patch here but just return NO_ERROR.
5248 return NO_ERROR;
5249 }
Eric Laurentd60560a2015-04-10 11:31:20 -07005250 } else {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005251 sp<HwAudioOutputDescriptor> hwOutputDesc = sourceDesc->hwOutput().promote();
Eric Laurentd60560a2015-04-10 11:31:20 -07005252 if (hwOutputDesc != 0) {
Eric Laurentd60560a2015-04-10 11:31:20 -07005253 // close Hwoutput and remove from mHwOutputs
5254 } else {
5255 ALOGW("%s source has neither SW nor HW output", __FUNCTION__);
5256 }
5257 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005258 status_t status = releaseAudioPatchInternal(sourceDesc->getPatchHandle(), 0, sourceDesc);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005259 sourceDesc->disconnect();
5260 return status;
Eric Laurentd60560a2015-04-10 11:31:20 -07005261}
5262
François Gaffiec005e562018-11-06 15:04:49 +01005263sp<SourceClientDescriptor> AudioPolicyManager::getSourceForAttributesOnOutput(
5264 audio_io_handle_t output, const audio_attributes_t &attr)
Eric Laurentd60560a2015-04-10 11:31:20 -07005265{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005266 sp<SourceClientDescriptor> source;
Eric Laurentd60560a2015-04-10 11:31:20 -07005267 for (size_t i = 0; i < mAudioSources.size(); i++) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005268 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005269 sp<SwAudioOutputDescriptor> outputDesc = sourceDesc->swOutput().promote();
François Gaffiec005e562018-11-06 15:04:49 +01005270 if (followsSameRouting(attr, sourceDesc->attributes()) &&
5271 outputDesc != 0 && outputDesc->mIoHandle == output) {
Eric Laurentd60560a2015-04-10 11:31:20 -07005272 source = sourceDesc;
5273 break;
5274 }
5275 }
5276 return source;
Eric Laurent554a2772015-04-10 11:29:24 -07005277}
5278
Eric Laurent39095982021-08-24 18:29:27 +02005279/* static */
5280bool AudioPolicyManager::isChannelMaskSpatialized(audio_channel_mask_t channels) {
5281 switch (channels) {
5282 case AUDIO_CHANNEL_OUT_5POINT1:
5283 case AUDIO_CHANNEL_OUT_5POINT1POINT2:
5284 case AUDIO_CHANNEL_OUT_5POINT1POINT4:
5285 case AUDIO_CHANNEL_OUT_7POINT1:
5286 case AUDIO_CHANNEL_OUT_7POINT1POINT2:
5287 case AUDIO_CHANNEL_OUT_7POINT1POINT4:
5288 return true;
5289 default:
5290 return false;
5291 }
5292}
5293
Eric Laurentb4f42a92022-01-17 17:37:31 +01005294bool AudioPolicyManager::canBeSpatializedInt(const audio_attributes_t *attr,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005295 const audio_config_t *config,
Eric Laurentb4f42a92022-01-17 17:37:31 +01005296 const AudioDeviceTypeAddrVector &devices,
5297 bool allowCurrentOutputReconfig) const
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005298{
5299 // The caller can have the audio attributes criteria ignored by either passing a null ptr or
5300 // the AUDIO_ATTRIBUTES_INITIALIZER value.
Eric Laurentfa0f6742021-08-17 18:39:44 +02005301 // If attributes are specified, current policy is to only allow spatialization for media
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005302 // and game usages.
Eric Laurent39095982021-08-24 18:29:27 +02005303 if (attr != nullptr && *attr != AUDIO_ATTRIBUTES_INITIALIZER) {
5304 if (attr->usage != AUDIO_USAGE_MEDIA && attr->usage != AUDIO_USAGE_GAME) {
5305 return false;
5306 }
5307 if ((attr->flags & (AUDIO_FLAG_CONTENT_SPATIALIZED | AUDIO_FLAG_NEVER_SPATIALIZE)) != 0) {
5308 return false;
5309 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005310 }
5311
5312 // The caller can have the devices criteria ignored by passing and empty vector, and
Eric Laurentfa0f6742021-08-17 18:39:44 +02005313 // getSpatializerOutputProfile() will ignore the devices when looking for a match.
5314 // Otherwise an output profile supporting a spatializer effect that can be routed
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005315 // to the specified devices must exist.
5316 sp<IOProfile> profile =
Eric Laurent39095982021-08-24 18:29:27 +02005317 getSpatializerOutputProfile(config, devices);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005318 if (profile == nullptr) {
5319 return false;
5320 }
5321
5322 // The caller can have the audio config criteria ignored by either passing a null ptr or
5323 // the AUDIO_CONFIG_INITIALIZER value.
Eric Laurentfa0f6742021-08-17 18:39:44 +02005324 // If an audio config is specified, current policy is to only allow spatialization for
Eric Laurent39095982021-08-24 18:29:27 +02005325 // some positional channel masks.
Eric Laurentfa0f6742021-08-17 18:39:44 +02005326 // If the spatializer output is already opened, only channel masks included in the
5327 // spatializer output mixer channel mask are allowed.
Eric Laurent39095982021-08-24 18:29:27 +02005328
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005329 if (config != nullptr && *config != AUDIO_CONFIG_INITIALIZER) {
Eric Laurent39095982021-08-24 18:29:27 +02005330 if (!isChannelMaskSpatialized(config->channel_mask)) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005331 return false;
5332 }
Eric Laurentb4f42a92022-01-17 17:37:31 +01005333 if (!allowCurrentOutputReconfig && mSpatializerOutput != nullptr
5334 && mSpatializerOutput->mProfile == profile) {
Eric Laurentfa0f6742021-08-17 18:39:44 +02005335 if ((config->channel_mask & mSpatializerOutput->mMixerChannelMask)
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005336 != config->channel_mask) {
5337 return false;
5338 }
5339 }
5340 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005341 return true;
5342}
5343
5344void AudioPolicyManager::checkVirtualizerClientRoutes() {
5345 std::set<audio_stream_type_t> streamsToInvalidate;
5346 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent39095982021-08-24 18:29:27 +02005347 const sp<SwAudioOutputDescriptor>& desc = mOutputs[i];
5348 for (const sp<TrackClientDescriptor>& client : desc->getClientIterable()) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005349 audio_attributes_t attr = client->attributes();
5350 DeviceVector devices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false);
5351 AudioDeviceTypeAddrVector devicesTypeAddress = devices.toTypeAddrVector();
5352 audio_config_base_t clientConfig = client->config();
5353 audio_config_t config = audio_config_initializer(&clientConfig);
Eric Laurent39095982021-08-24 18:29:27 +02005354 if (desc != mSpatializerOutput
Eric Laurentb4f42a92022-01-17 17:37:31 +01005355 && canBeSpatializedInt(&attr, &config,
5356 devicesTypeAddress, false /* allowCurrentOutputReconfig */)) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005357 streamsToInvalidate.insert(client->stream());
5358 }
5359 }
5360 }
5361
5362 for (audio_stream_type_t stream : streamsToInvalidate) {
5363 mpClientInterface->invalidateStream(stream);
5364 }
5365}
5366
Eric Laurente191d1b2022-04-15 11:59:25 +02005367
5368bool AudioPolicyManager::isOutputOnlyAvailableRouteToSomeDevice(
5369 const sp<SwAudioOutputDescriptor>& outputDesc) {
5370 if (outputDesc->isDuplicated()) {
5371 return false;
5372 }
5373 DeviceVector devices = outputDesc->supportedDevices();
5374 for (size_t i = 0; i < mOutputs.size(); i++) {
5375 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
5376 if (desc == outputDesc || desc->isDuplicated()) {
5377 continue;
5378 }
5379 DeviceVector sharedDevices = desc->filterSupportedDevices(devices);
5380 if (!sharedDevices.isEmpty()
5381 && (desc->devicesSupportEncodedFormats(sharedDevices.types())
5382 == outputDesc->devicesSupportEncodedFormats(sharedDevices.types()))) {
5383 return false;
5384 }
5385 }
5386 return true;
5387}
5388
5389
Eric Laurentfa0f6742021-08-17 18:39:44 +02005390status_t AudioPolicyManager::getSpatializerOutput(const audio_config_base_t *mixerConfig,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005391 const audio_attributes_t *attr,
5392 audio_io_handle_t *output) {
5393 *output = AUDIO_IO_HANDLE_NONE;
5394
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005395 DeviceVector devices = mEngine->getOutputDevicesForAttributes(*attr, nullptr, false);
5396 AudioDeviceTypeAddrVector devicesTypeAddress = devices.toTypeAddrVector();
5397 audio_config_t *configPtr = nullptr;
5398 audio_config_t config;
5399 if (mixerConfig != nullptr) {
5400 config = audio_config_initializer(mixerConfig);
5401 configPtr = &config;
5402 }
Eric Laurentb4f42a92022-01-17 17:37:31 +01005403 if (!canBeSpatializedInt(
5404 attr, configPtr, devicesTypeAddress)) {
Eric Laurente191d1b2022-04-15 11:59:25 +02005405 ALOGV("%s provided attributes or mixer config cannot be spatialized", __func__);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005406 return BAD_VALUE;
5407 }
5408
5409 sp<IOProfile> profile =
Eric Laurent39095982021-08-24 18:29:27 +02005410 getSpatializerOutputProfile(configPtr, devicesTypeAddress);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005411 if (profile == nullptr) {
Eric Laurente191d1b2022-04-15 11:59:25 +02005412 ALOGV("%s no suitable output profile for provided attributes or mixer config", __func__);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005413 return BAD_VALUE;
5414 }
5415
Eric Laurente191d1b2022-04-15 11:59:25 +02005416 std::vector<sp<SwAudioOutputDescriptor>> spatializerOutputs;
Eric Laurent39095982021-08-24 18:29:27 +02005417 for (size_t i = 0; i < mOutputs.size(); i++) {
5418 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente191d1b2022-04-15 11:59:25 +02005419 if (!desc->isDuplicated()
5420 && (desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0) {
5421 spatializerOutputs.push_back(desc);
5422 ALOGV("%s adding opened spatializer Output %d", __func__, desc->mIoHandle);
Eric Laurent39095982021-08-24 18:29:27 +02005423 }
5424 }
Eric Laurente191d1b2022-04-15 11:59:25 +02005425 mSpatializerOutput.clear();
5426 bool outputsChanged = false;
5427 for (const auto& desc : spatializerOutputs) {
5428 if (desc->mProfile == profile
5429 && (configPtr == nullptr
5430 || configPtr->channel_mask == desc->mMixerChannelMask)) {
5431 mSpatializerOutput = desc;
5432 ALOGV("%s reusing current spatializer output %d", __func__, desc->mIoHandle);
5433 } else {
5434 ALOGV("%s closing spatializerOutput output %d to match channel mask %#x"
5435 " and devices %s", __func__, desc->mIoHandle,
5436 configPtr != nullptr ? configPtr->channel_mask : 0,
5437 devices.toString().c_str());
5438 closeOutput(desc->mIoHandle);
5439 outputsChanged = true;
5440 }
Eric Laurent39095982021-08-24 18:29:27 +02005441 }
5442
Eric Laurente191d1b2022-04-15 11:59:25 +02005443 if (mSpatializerOutput == nullptr) {
Eric Laurentb4f42a92022-01-17 17:37:31 +01005444 sp<SwAudioOutputDescriptor> desc =
5445 openOutputWithProfileAndDevice(profile, devices, mixerConfig);
Eric Laurente191d1b2022-04-15 11:59:25 +02005446 if (desc != nullptr) {
5447 mSpatializerOutput = desc;
5448 outputsChanged = true;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005449 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005450 }
5451
5452 checkVirtualizerClientRoutes();
5453
Eric Laurente191d1b2022-04-15 11:59:25 +02005454 if (outputsChanged) {
5455 mPreviousOutputs = mOutputs;
5456 mpClientInterface->onAudioPortListUpdate();
5457 }
5458
5459 if (mSpatializerOutput == nullptr) {
5460 ALOGV("%s could not open spatializer output with requested config", __func__);
5461 return BAD_VALUE;
5462 }
Eric Laurent39095982021-08-24 18:29:27 +02005463 *output = mSpatializerOutput->mIoHandle;
Eric Laurente191d1b2022-04-15 11:59:25 +02005464 ALOGV("%s returning new spatializer output %d", __func__, *output);
5465 return OK;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005466}
5467
Eric Laurentfa0f6742021-08-17 18:39:44 +02005468status_t AudioPolicyManager::releaseSpatializerOutput(audio_io_handle_t output) {
5469 if (mSpatializerOutput == nullptr) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005470 return INVALID_OPERATION;
5471 }
Eric Laurentfa0f6742021-08-17 18:39:44 +02005472 if (mSpatializerOutput->mIoHandle != output) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005473 return BAD_VALUE;
5474 }
Eric Laurent39095982021-08-24 18:29:27 +02005475
Eric Laurente191d1b2022-04-15 11:59:25 +02005476 if (!isOutputOnlyAvailableRouteToSomeDevice(mSpatializerOutput)) {
5477 ALOGV("%s closing spatializer output %d", __func__, mSpatializerOutput->mIoHandle);
5478 closeOutput(mSpatializerOutput->mIoHandle);
5479 //from now on mSpatializerOutput is null
5480 checkVirtualizerClientRoutes();
5481 }
Eric Laurent39095982021-08-24 18:29:27 +02005482
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005483 return NO_ERROR;
5484}
5485
Eric Laurente552edb2014-03-10 17:42:56 -07005486// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07005487// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07005488// ----------------------------------------------------------------------------
Eric Laurent6a94d692014-05-20 11:18:06 -07005489uint32_t AudioPolicyManager::nextAudioPortGeneration()
5490{
Mikhail Naganov2773dd72017-12-08 10:12:11 -08005491 return mAudioPortGeneration++;
Eric Laurent6a94d692014-05-20 11:18:06 -07005492}
5493
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09005494static status_t deserializeAudioPolicyXmlConfig(AudioPolicyConfig &config) {
Mikhail Naganov946c0032020-10-21 13:04:58 -07005495 if (std::string audioPolicyXmlConfigFile = audio_get_audio_policy_config_file();
5496 !audioPolicyXmlConfigFile.empty()) {
5497 status_t ret = deserializeAudioPolicyFile(audioPolicyXmlConfigFile.c_str(), &config);
5498 if (ret == NO_ERROR) {
5499 config.setSource(audioPolicyXmlConfigFile);
Cheney Ni6851adb2018-11-01 06:30:37 +08005500 }
Mikhail Naganov946c0032020-10-21 13:04:58 -07005501 return ret;
Petri Gyntherf497f292018-04-17 18:46:10 -07005502 }
Mikhail Naganov946c0032020-10-21 13:04:58 -07005503 return BAD_VALUE;
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09005504}
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09005505
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005506AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface,
5507 bool /*forTesting*/)
Eric Laurente552edb2014-03-10 17:42:56 -07005508 :
Andy Hung4ef19fa2018-05-15 19:35:29 -07005509 mUidCached(AID_AUDIOSERVER), // no need to call getuid(), there's only one of us running.
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005510 mpClientInterface(clientInterface),
Eric Laurente552edb2014-03-10 17:42:56 -07005511 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
Eric Laurent3a4311c2014-03-17 12:00:47 -07005512 mA2dpSuspended(false),
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005513 mConfig(mHwModulesAll, mOutputDevicesAll, mInputDevicesAll, mDefaultOutputDevice),
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005514 mAudioPortGeneration(1),
5515 mBeaconMuteRefCount(0),
5516 mBeaconPlayingRefCount(0),
Eric Laurent9459fb02015-08-12 18:36:32 -07005517 mBeaconMuted(false),
Andy Hung2ddee192015-12-18 17:34:44 -08005518 mTtsOutputAvailable(false),
Eric Laurent36829f92017-04-07 19:04:42 -07005519 mMasterMono(false),
Eric Laurent4eb58f12018-12-07 16:41:02 -08005520 mMusicEffectOutput(AUDIO_IO_HANDLE_NONE)
Eric Laurente552edb2014-03-10 17:42:56 -07005521{
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005522}
François Gaffied1ab2bd2015-12-02 18:20:06 +01005523
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005524AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface)
5525 : AudioPolicyManager(clientInterface, false /*forTesting*/)
5526{
5527 loadConfig();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005528}
François Gaffied1ab2bd2015-12-02 18:20:06 +01005529
Kevin Rocarddfa1e8a2018-10-26 16:42:07 -07005530void AudioPolicyManager::loadConfig() {
5531 if (deserializeAudioPolicyXmlConfig(getConfig()) != NO_ERROR) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01005532 ALOGE("could not load audio policy configuration file, setting defaults");
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005533 getConfig().setDefault();
François Gaffied1ab2bd2015-12-02 18:20:06 +01005534 }
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005535}
5536
5537status_t AudioPolicyManager::initialize() {
Mikhail Naganov47835552019-05-14 10:32:51 -07005538 {
5539 auto engLib = EngineLibrary::load(
5540 "libaudiopolicyengine" + getConfig().getEngineLibraryNameSuffix() + ".so");
5541 if (!engLib) {
5542 ALOGE("%s: Failed to load the engine library", __FUNCTION__);
5543 return NO_INIT;
5544 }
5545 mEngine = engLib->createEngine();
5546 if (mEngine == nullptr) {
5547 ALOGE("%s: Failed to instantiate the APM engine", __FUNCTION__);
5548 return NO_INIT;
5549 }
François Gaffie2110e042015-03-24 08:41:51 +01005550 }
5551 mEngine->setObserver(this);
5552 status_t status = mEngine->initCheck();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005553 if (status != NO_ERROR) {
5554 LOG_FATAL("Policy engine not initialized(err=%d)", status);
5555 return status;
5556 }
François Gaffie2110e042015-03-24 08:41:51 +01005557
Eric Laurent1a8b45f2022-04-13 16:01:47 +02005558 mEngine->updateDeviceSelectionCache();
Eric Laurent1d69c872021-01-11 18:53:01 +01005559 mCommunnicationStrategy = mEngine->getProductStrategyForAttributes(
5560 mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL));
5561
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005562 // after parsing the config, mOutputDevicesAll and mInputDevicesAll contain all known devices;
Eric Laurente552edb2014-03-10 17:42:56 -07005563 // open all output streams needed to access attached devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07005564 onNewAudioModulesAvailableInt(nullptr /*newDevices*/);
François Gaffie11d30102018-11-02 16:09:09 +01005565
Eric Laurent3a4311c2014-03-17 12:00:47 -07005566 // make sure default device is reachable
François Gaffie11d30102018-11-02 16:09:09 +01005567 if (mDefaultOutputDevice == 0 || !mAvailableOutputDevices.contains(mDefaultOutputDevice)) {
5568 ALOGE_IF(mDefaultOutputDevice != 0, "Default device %s is unreachable",
5569 mDefaultOutputDevice->toString().c_str());
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005570 status = NO_INIT;
Eric Laurent3a4311c2014-03-17 12:00:47 -07005571 }
jiabin9ff780e2018-03-19 18:19:52 -07005572 // If microphones address is empty, set it according to device type
Eric Laurent736a1022019-03-27 18:28:46 -07005573 for (size_t i = 0; i < mAvailableInputDevices.size(); i++) {
jiabince9f20e2019-09-12 16:29:15 -07005574 if (mAvailableInputDevices[i]->address().empty()) {
jiabin9ff780e2018-03-19 18:19:52 -07005575 if (mAvailableInputDevices[i]->type() == AUDIO_DEVICE_IN_BUILTIN_MIC) {
jiabince9f20e2019-09-12 16:29:15 -07005576 mAvailableInputDevices[i]->setAddress(AUDIO_BOTTOM_MICROPHONE_ADDRESS);
jiabin9ff780e2018-03-19 18:19:52 -07005577 } else if (mAvailableInputDevices[i]->type() == AUDIO_DEVICE_IN_BACK_MIC) {
jiabince9f20e2019-09-12 16:29:15 -07005578 mAvailableInputDevices[i]->setAddress(AUDIO_BACK_MICROPHONE_ADDRESS);
jiabin9ff780e2018-03-19 18:19:52 -07005579 }
5580 }
5581 }
Eric Laurente552edb2014-03-10 17:42:56 -07005582
Francois Gaffiebce7cd42020-10-14 16:13:20 +02005583 ALOGW_IF(mPrimaryOutput == nullptr, "The policy configuration does not declare a primary output");
Eric Laurente552edb2014-03-10 17:42:56 -07005584
Tomoharu Kasahara71c90912018-10-31 09:10:12 +09005585 // Silence ALOGV statements
5586 property_set("log.tag." LOG_TAG, "D");
5587
Eric Laurente552edb2014-03-10 17:42:56 -07005588 updateDevicesAndOutputs();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005589 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07005590}
5591
Eric Laurente0720872014-03-11 09:30:41 -07005592AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07005593{
Eric Laurente552edb2014-03-10 17:42:56 -07005594 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08005595 mOutputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07005596 }
5597 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08005598 mInputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07005599 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07005600 mAvailableOutputDevices.clear();
5601 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07005602 mOutputs.clear();
5603 mInputs.clear();
5604 mHwModules.clear();
Mikhail Naganovd4120142017-12-06 15:49:22 -08005605 mHwModulesAll.clear();
Mikhail Naganov100f0122018-11-29 11:22:16 -08005606 mManualSurroundFormats.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07005607}
5608
Eric Laurente0720872014-03-11 09:30:41 -07005609status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07005610{
Eric Laurent87ffa392015-05-22 10:32:38 -07005611 return hasPrimaryOutput() ? NO_ERROR : NO_INIT;
Eric Laurente552edb2014-03-10 17:42:56 -07005612}
5613
Eric Laurente552edb2014-03-10 17:42:56 -07005614// ---
5615
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005616void AudioPolicyManager::onNewAudioModulesAvailable()
5617{
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07005618 DeviceVector newDevices;
5619 onNewAudioModulesAvailableInt(&newDevices);
5620 if (!newDevices.empty()) {
5621 nextAudioPortGeneration();
5622 mpClientInterface->onAudioPortListUpdate();
5623 }
5624}
5625
5626void AudioPolicyManager::onNewAudioModulesAvailableInt(DeviceVector *newDevices)
5627{
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005628 for (const auto& hwModule : mHwModulesAll) {
5629 if (std::find(mHwModules.begin(), mHwModules.end(), hwModule) != mHwModules.end()) {
5630 continue;
5631 }
5632 hwModule->setHandle(mpClientInterface->loadHwModule(hwModule->getName()));
5633 if (hwModule->getHandle() == AUDIO_MODULE_HANDLE_NONE) {
5634 ALOGW("could not open HW module %s", hwModule->getName());
5635 continue;
5636 }
5637 mHwModules.push_back(hwModule);
Dean Wheatley12a87132021-04-16 10:08:49 +10005638 // open all output streams needed to access attached devices.
5639 // direct outputs are closed immediately after checking the availability of attached devices
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005640 // This also validates mAvailableOutputDevices list
5641 for (const auto& outProfile : hwModule->getOutputProfiles()) {
5642 if (!outProfile->canOpenNewIo()) {
5643 ALOGE("Invalid Output profile max open count %u for profile %s",
5644 outProfile->maxOpenCount, outProfile->getTagName().c_str());
5645 continue;
5646 }
5647 if (!outProfile->hasSupportedDevices()) {
5648 ALOGW("Output profile contains no device on module %s", hwModule->getName());
5649 continue;
5650 }
Carter Hsu1a3364a2022-01-21 15:32:56 +08005651 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_TTS) != 0 ||
5652 (outProfile->getFlags() & AUDIO_OUTPUT_FLAG_ULTRASOUND) != 0) {
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005653 mTtsOutputAvailable = true;
5654 }
5655
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005656 const DeviceVector &supportedDevices = outProfile->getSupportedDevices();
5657 DeviceVector availProfileDevices = supportedDevices.filter(mOutputDevicesAll);
5658 sp<DeviceDescriptor> supportedDevice = 0;
5659 if (supportedDevices.contains(mDefaultOutputDevice)) {
5660 supportedDevice = mDefaultOutputDevice;
5661 } else {
5662 // choose first device present in profile's SupportedDevices also part of
5663 // mAvailableOutputDevices.
5664 if (availProfileDevices.isEmpty()) {
5665 continue;
5666 }
5667 supportedDevice = availProfileDevices.itemAt(0);
5668 }
5669 if (!mOutputDevicesAll.contains(supportedDevice)) {
5670 continue;
5671 }
5672 sp<SwAudioOutputDescriptor> outputDesc = new SwAudioOutputDescriptor(outProfile,
5673 mpClientInterface);
5674 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentf1f22e72021-07-13 14:04:14 +02005675 status_t status = outputDesc->open(nullptr /* halConfig */, nullptr /* mixerConfig */,
5676 DeviceVector(supportedDevice),
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005677 AUDIO_STREAM_DEFAULT,
5678 AUDIO_OUTPUT_FLAG_NONE, &output);
5679 if (status != NO_ERROR) {
5680 ALOGW("Cannot open output stream for devices %s on hw module %s",
5681 supportedDevice->toString().c_str(), hwModule->getName());
5682 continue;
5683 }
5684 for (const auto &device : availProfileDevices) {
5685 // give a valid ID to an attached device once confirmed it is reachable
5686 if (!device->isAttached()) {
5687 device->attach(hwModule);
5688 mAvailableOutputDevices.add(device);
jiabin1c4794b2020-05-05 10:08:05 -07005689 device->setEncapsulationInfoFromHal(mpClientInterface);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07005690 if (newDevices) newDevices->add(device);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005691 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
5692 }
5693 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02005694 if (mPrimaryOutput == nullptr &&
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005695 outProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
5696 mPrimaryOutput = outputDesc;
5697 }
Eric Laurent39095982021-08-24 18:29:27 +02005698 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
Eric Laurentc529cf62020-04-17 18:19:10 -07005699 outputDesc->close();
5700 } else {
5701 addOutput(output, outputDesc);
5702 setOutputDevices(outputDesc,
5703 DeviceVector(supportedDevice),
5704 true,
5705 0,
5706 NULL);
5707 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005708 }
5709 // open input streams needed to access attached devices to validate
5710 // mAvailableInputDevices list
5711 for (const auto& inProfile : hwModule->getInputProfiles()) {
5712 if (!inProfile->canOpenNewIo()) {
5713 ALOGE("Invalid Input profile max open count %u for profile %s",
5714 inProfile->maxOpenCount, inProfile->getTagName().c_str());
5715 continue;
5716 }
5717 if (!inProfile->hasSupportedDevices()) {
5718 ALOGW("Input profile contains no device on module %s", hwModule->getName());
5719 continue;
5720 }
5721 // chose first device present in profile's SupportedDevices also part of
5722 // available input devices
5723 const DeviceVector &supportedDevices = inProfile->getSupportedDevices();
5724 DeviceVector availProfileDevices = supportedDevices.filter(mInputDevicesAll);
5725 if (availProfileDevices.isEmpty()) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01005726 ALOGV("%s: Input device list is empty! for profile %s",
5727 __func__, inProfile->getTagName().c_str());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005728 continue;
5729 }
5730 sp<AudioInputDescriptor> inputDesc =
5731 new AudioInputDescriptor(inProfile, mpClientInterface);
5732
5733 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
5734 status_t status = inputDesc->open(nullptr,
5735 availProfileDevices.itemAt(0),
5736 AUDIO_SOURCE_MIC,
5737 AUDIO_INPUT_FLAG_NONE,
5738 &input);
5739 if (status != NO_ERROR) {
5740 ALOGW("Cannot open input stream for device %s on hw module %s",
5741 availProfileDevices.toString().c_str(),
5742 hwModule->getName());
5743 continue;
5744 }
5745 for (const auto &device : availProfileDevices) {
5746 // give a valid ID to an attached device once confirmed it is reachable
5747 if (!device->isAttached()) {
5748 device->attach(hwModule);
5749 device->importAudioPortAndPickAudioProfile(inProfile, true);
5750 mAvailableInputDevices.add(device);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07005751 if (newDevices) newDevices->add(device);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005752 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
5753 }
5754 }
5755 inputDesc->close();
5756 }
5757 }
Eric Laurente191d1b2022-04-15 11:59:25 +02005758
5759 // Check if spatializer outputs can be closed until used.
5760 // mOutputs vector never contains duplicated outputs at this point.
5761 std::vector<audio_io_handle_t> outputsClosed;
5762 for (size_t i = 0; i < mOutputs.size(); i++) {
5763 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
5764 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0
5765 && !isOutputOnlyAvailableRouteToSomeDevice(desc)) {
5766 outputsClosed.push_back(desc->mIoHandle);
5767 desc->close();
5768 }
5769 }
5770 for (auto output : outputsClosed) {
5771 removeOutput(output);
5772 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005773}
5774
Eric Laurent98e38192018-02-15 18:31:53 -08005775void AudioPolicyManager::addOutput(audio_io_handle_t output,
5776 const sp<SwAudioOutputDescriptor>& outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07005777{
Eric Laurent1c333e22014-05-20 10:48:17 -07005778 mOutputs.add(output, outputDesc);
jiabin9a3361e2019-10-01 09:38:30 -07005779 applyStreamVolumes(outputDesc, DeviceTypeSet(), 0 /* delayMs */, true /* force */);
Andy Hung2ddee192015-12-18 17:34:44 -08005780 updateMono(output); // update mono status when adding to output list
Eric Laurent36829f92017-04-07 19:04:42 -07005781 selectOutputForMusicEffects();
Eric Laurent6a94d692014-05-20 11:18:06 -07005782 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07005783}
5784
François Gaffie53615e22015-03-19 09:24:12 +01005785void AudioPolicyManager::removeOutput(audio_io_handle_t output)
5786{
Francois Gaffiebce7cd42020-10-14 16:13:20 +02005787 if (mPrimaryOutput != 0 && mPrimaryOutput == mOutputs.valueFor(output)) {
5788 ALOGV("%s: removing primary output", __func__);
5789 mPrimaryOutput = nullptr;
5790 }
François Gaffie53615e22015-03-19 09:24:12 +01005791 mOutputs.removeItem(output);
Eric Laurent36829f92017-04-07 19:04:42 -07005792 selectOutputForMusicEffects();
François Gaffie53615e22015-03-19 09:24:12 +01005793}
5794
Eric Laurent98e38192018-02-15 18:31:53 -08005795void AudioPolicyManager::addInput(audio_io_handle_t input,
5796 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07005797{
Eric Laurent1c333e22014-05-20 10:48:17 -07005798 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07005799 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07005800}
Eric Laurente552edb2014-03-10 17:42:56 -07005801
François Gaffie11d30102018-11-02 16:09:09 +01005802status_t AudioPolicyManager::checkOutputsForDevice(const sp<DeviceDescriptor>& device,
François Gaffie53615e22015-03-19 09:24:12 +01005803 audio_policy_dev_state_t state,
François Gaffie11d30102018-11-02 16:09:09 +01005804 SortedVector<audio_io_handle_t>& outputs)
Eric Laurente552edb2014-03-10 17:42:56 -07005805{
François Gaffie11d30102018-11-02 16:09:09 +01005806 audio_devices_t deviceType = device->type();
jiabince9f20e2019-09-12 16:29:15 -07005807 const String8 &address = String8(device->address().c_str());
Eric Laurentc75307b2015-03-17 15:29:32 -07005808 sp<SwAudioOutputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07005809
François Gaffie11d30102018-11-02 16:09:09 +01005810 if (audio_device_is_digital(deviceType)) {
Eric Laurentcc750d32015-06-25 11:48:20 -07005811 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01005812 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07005813 }
Eric Laurente552edb2014-03-10 17:42:56 -07005814
Eric Laurent3b73df72014-03-11 09:06:29 -07005815 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
jiabinb4fed192020-09-22 14:45:40 -07005816 // first call getAudioPort to get the supported attributes from the HAL
5817 struct audio_port_v7 port = {};
5818 device->toAudioPort(&port);
5819 status_t status = mpClientInterface->getAudioPort(&port);
5820 if (status == NO_ERROR) {
5821 device->importAudioPort(port);
5822 }
5823
5824 // then list already open outputs that can be routed to this device
Eric Laurente552edb2014-03-10 17:42:56 -07005825 for (size_t i = 0; i < mOutputs.size(); i++) {
5826 desc = mOutputs.valueAt(i);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005827 if (!desc->isDuplicated() && desc->supportsDevice(device)
jiabin9a3361e2019-10-01 09:38:30 -07005828 && desc->devicesSupportEncodedFormats({deviceType})) {
François Gaffie11d30102018-11-02 16:09:09 +01005829 ALOGV("checkOutputsForDevice(): adding opened output %d on device %s",
5830 mOutputs.keyAt(i), device->toString().c_str());
5831 outputs.add(mOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07005832 }
5833 }
5834 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07005835 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08005836 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005837 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
5838 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
François Gaffie11d30102018-11-02 16:09:09 +01005839 if (profile->supportsDevice(device)) {
5840 profiles.add(profile);
5841 ALOGV("checkOutputsForDevice(): adding profile %zu from module %s",
5842 j, hwModule->getName());
Eric Laurente552edb2014-03-10 17:42:56 -07005843 }
5844 }
5845 }
5846
Eric Laurent7b279bb2015-12-14 10:18:23 -08005847 ALOGV(" found %zu profiles, %zu outputs", profiles.size(), outputs.size());
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005848
Eric Laurente552edb2014-03-10 17:42:56 -07005849 if (profiles.isEmpty() && outputs.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01005850 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07005851 return BAD_VALUE;
5852 }
5853
5854 // open outputs for matching profiles if needed. Direct outputs are also opened to
5855 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
5856 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07005857 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07005858
5859 // nothing to do if one output is already opened for this profile
5860 size_t j;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005861 for (j = 0; j < outputs.size(); j++) {
5862 desc = mOutputs.valueFor(outputs.itemAt(j));
Eric Laurente552edb2014-03-10 17:42:56 -07005863 if (!desc->isDuplicated() && desc->mProfile == profile) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07005864 // matching profile: save the sample rates, format and channel masks supported
5865 // by the profile in our device descriptor
François Gaffie11d30102018-11-02 16:09:09 +01005866 if (audio_device_is_digital(deviceType)) {
jiabin4ef93452019-09-10 14:29:54 -07005867 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07005868 }
Eric Laurente552edb2014-03-10 17:42:56 -07005869 break;
5870 }
5871 }
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005872 if (j != outputs.size()) {
Eric Laurente552edb2014-03-10 17:42:56 -07005873 continue;
5874 }
5875
Eric Laurent3974e3b2017-12-07 17:58:43 -08005876 if (!profile->canOpenNewIo()) {
5877 ALOGW("Max Output number %u already opened for this profile %s",
5878 profile->maxOpenCount, profile->getTagName().c_str());
5879 continue;
5880 }
5881
Eric Laurent83efe1c2017-07-09 16:51:08 -07005882 ALOGV("opening output for device %08x with params %s profile %p name %s",
jiabin5740f082019-08-19 15:08:30 -07005883 deviceType, address.string(), profile.get(), profile->getName().c_str());
jiabinbce0c1d2020-10-05 11:20:18 -07005884 desc = openOutputWithProfileAndDevice(profile, DeviceVector(device));
5885 audio_io_handle_t output = desc == nullptr ? AUDIO_IO_HANDLE_NONE : desc->mIoHandle;
Eric Laurentcf2c0212014-07-25 16:20:43 -07005886 if (output == AUDIO_IO_HANDLE_NONE) {
François Gaffie11d30102018-11-02 16:09:09 +01005887 ALOGW("checkOutputsForDevice() could not open output for device %x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07005888 profiles.removeAt(profile_index);
5889 profile_index--;
5890 } else {
5891 outputs.add(output);
Paul McLean9080a4c2015-06-18 08:24:02 -07005892 // Load digital format info only for digital devices
François Gaffie11d30102018-11-02 16:09:09 +01005893 if (audio_device_is_digital(deviceType)) {
jiabinbce0c1d2020-10-05 11:20:18 -07005894 // TODO: when getAudioPort is ready, it may not be needed to import the audio
5895 // port but just pick audio profile
jiabin4ef93452019-09-10 14:29:54 -07005896 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07005897 }
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07005898
François Gaffie11d30102018-11-02 16:09:09 +01005899 if (device_distinguishes_on_address(deviceType)) {
5900 ALOGV("checkOutputsForDevice(): setOutputDevices %s",
5901 device->toString().c_str());
5902 setOutputDevices(desc, DeviceVector(device), true/*force*/, 0/*delay*/,
5903 NULL/*patch handle*/);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005904 }
Eric Laurente552edb2014-03-10 17:42:56 -07005905 ALOGV("checkOutputsForDevice(): adding output %d", output);
5906 }
5907 }
5908
5909 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01005910 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07005911 return BAD_VALUE;
5912 }
Eric Laurentd4692962014-05-05 18:13:44 -07005913 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07005914 // check if one opened output is not needed any more after disconnecting one device
5915 for (size_t i = 0; i < mOutputs.size(); i++) {
5916 desc = mOutputs.valueAt(i);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005917 if (!desc->isDuplicated()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08005918 // exact match on device
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005919 if (device_distinguishes_on_address(deviceType) && desc->supportsDevice(device)
Francois Gaffiec7d4c222021-12-02 11:12:52 +01005920 && desc->containsSingleDeviceSupportingEncodedFormats(device)) {
François Gaffie11d30102018-11-02 16:09:09 +01005921 outputs.add(mOutputs.keyAt(i));
Francois Gaffie716e1432019-01-14 16:58:59 +01005922 } else if (!mAvailableOutputDevices.containsAtLeastOne(desc->supportedDevices())) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005923 ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
5924 mOutputs.keyAt(i));
5925 outputs.add(mOutputs.keyAt(i));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005926 }
Eric Laurente552edb2014-03-10 17:42:56 -07005927 }
5928 }
Eric Laurentd4692962014-05-05 18:13:44 -07005929 // Clear any profiles associated with the disconnected device.
Mikhail Naganov7e22e942017-12-07 10:04:29 -08005930 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005931 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
5932 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
jiabinbce0c1d2020-10-05 11:20:18 -07005933 if (!profile->supportsDevice(device)) {
5934 continue;
5935 }
5936 ALOGV("checkOutputsForDevice(): "
5937 "clearing direct output profile %zu on module %s",
5938 j, hwModule->getName());
5939 profile->clearAudioProfiles();
5940 if (!profile->hasDynamicAudioProfile()) {
5941 continue;
5942 }
5943 // When a device is disconnected, if there is an IOProfile that contains dynamic
5944 // profiles and supports the disconnected device, call getAudioPort to repopulate
5945 // the capabilities of the devices that is supported by the IOProfile.
5946 for (const auto& supportedDevice : profile->getSupportedDevices()) {
5947 if (supportedDevice == device ||
5948 !mAvailableOutputDevices.contains(supportedDevice)) {
5949 continue;
5950 }
5951 struct audio_port_v7 port;
5952 supportedDevice->toAudioPort(&port);
5953 status_t status = mpClientInterface->getAudioPort(&port);
5954 if (status == NO_ERROR) {
5955 supportedDevice->importAudioPort(port);
5956 }
Eric Laurente552edb2014-03-10 17:42:56 -07005957 }
5958 }
5959 }
5960 }
5961 return NO_ERROR;
5962}
5963
François Gaffie11d30102018-11-02 16:09:09 +01005964status_t AudioPolicyManager::checkInputsForDevice(const sp<DeviceDescriptor>& device,
Eric Laurent0dd51852019-04-19 18:18:58 -07005965 audio_policy_dev_state_t state)
Eric Laurentd4692962014-05-05 18:13:44 -07005966{
Eric Laurent1f2f2232014-06-02 12:01:23 -07005967 sp<AudioInputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07005968
François Gaffie11d30102018-11-02 16:09:09 +01005969 if (audio_device_is_digital(device->type())) {
Eric Laurentcc750d32015-06-25 11:48:20 -07005970 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01005971 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07005972 }
5973
Eric Laurentd4692962014-05-05 18:13:44 -07005974 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
Eric Laurent0dd51852019-04-19 18:18:58 -07005975 // look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07005976 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08005977 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07005978 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005979 profile_index < hwModule->getInputProfiles().size();
Mikhail Naganov7e22e942017-12-07 10:04:29 -08005980 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005981 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Eric Laurent275e8e92014-11-30 15:14:47 -08005982
François Gaffie11d30102018-11-02 16:09:09 +01005983 if (profile->supportsDevice(device)) {
5984 profiles.add(profile);
5985 ALOGV("checkInputsForDevice(): adding profile %zu from module %s",
5986 profile_index, hwModule->getName());
Eric Laurentd4692962014-05-05 18:13:44 -07005987 }
5988 }
5989 }
5990
Eric Laurent0dd51852019-04-19 18:18:58 -07005991 if (profiles.isEmpty()) {
5992 ALOGW("%s: No input profile available for device %s",
5993 __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07005994 return BAD_VALUE;
5995 }
5996
5997 // open inputs for matching profiles if needed. Direct inputs are also opened to
5998 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
5999 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
6000
Eric Laurent1c333e22014-05-20 10:48:17 -07006001 sp<IOProfile> profile = profiles[profile_index];
Eric Laurent3974e3b2017-12-07 17:58:43 -08006002
Eric Laurentd4692962014-05-05 18:13:44 -07006003 // nothing to do if one input is already opened for this profile
6004 size_t input_index;
6005 for (input_index = 0; input_index < mInputs.size(); input_index++) {
6006 desc = mInputs.valueAt(input_index);
6007 if (desc->mProfile == profile) {
François Gaffie11d30102018-11-02 16:09:09 +01006008 if (audio_device_is_digital(device->type())) {
jiabin4ef93452019-09-10 14:29:54 -07006009 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006010 }
Eric Laurentd4692962014-05-05 18:13:44 -07006011 break;
6012 }
6013 }
6014 if (input_index != mInputs.size()) {
6015 continue;
6016 }
6017
Eric Laurent3974e3b2017-12-07 17:58:43 -08006018 if (!profile->canOpenNewIo()) {
6019 ALOGW("Max Input number %u already opened for this profile %s",
6020 profile->maxOpenCount, profile->getTagName().c_str());
6021 continue;
6022 }
6023
Eric Laurentfe231122017-11-17 17:48:06 -08006024 desc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentcf2c0212014-07-25 16:20:43 -07006025 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08006026 status_t status = desc->open(nullptr,
6027 device,
Eric Laurentfe231122017-11-17 17:48:06 -08006028 AUDIO_SOURCE_MIC,
6029 AUDIO_INPUT_FLAG_NONE,
6030 &input);
Eric Laurentd4692962014-05-05 18:13:44 -07006031
Eric Laurentcf2c0212014-07-25 16:20:43 -07006032 if (status == NO_ERROR) {
jiabince9f20e2019-09-12 16:29:15 -07006033 const String8& address = String8(device->address().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07006034 if (!address.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006035 char *param = audio_device_address_to_parameter(device->type(), address);
Eric Laurentcf2c0212014-07-25 16:20:43 -07006036 mpClientInterface->setParameters(input, String8(param));
6037 free(param);
Eric Laurentd4692962014-05-05 18:13:44 -07006038 }
François Gaffie11d30102018-11-02 16:09:09 +01006039 updateAudioProfiles(device, input, profile->getAudioProfiles());
François Gaffie112b0af2015-11-19 16:13:25 +01006040 if (!profile->hasValidAudioProfile()) {
Eric Laurentd4692962014-05-05 18:13:44 -07006041 ALOGW("checkInputsForDevice() direct input missing param");
Eric Laurentfe231122017-11-17 17:48:06 -08006042 desc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07006043 input = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07006044 }
6045
Eric Laurent0dd51852019-04-19 18:18:58 -07006046 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07006047 addInput(input, desc);
6048 }
6049 } // endif input != 0
6050
Eric Laurentcf2c0212014-07-25 16:20:43 -07006051 if (input == AUDIO_IO_HANDLE_NONE) {
Pattydd807582021-11-04 21:01:03 +08006052 ALOGW("%s could not open input for device %s", __func__,
François Gaffie11d30102018-11-02 16:09:09 +01006053 device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07006054 profiles.removeAt(profile_index);
6055 profile_index--;
6056 } else {
François Gaffie11d30102018-11-02 16:09:09 +01006057 if (audio_device_is_digital(device->type())) {
jiabin4ef93452019-09-10 14:29:54 -07006058 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006059 }
Eric Laurentd4692962014-05-05 18:13:44 -07006060 ALOGV("checkInputsForDevice(): adding input %d", input);
6061 }
6062 } // end scan profiles
6063
6064 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006065 ALOGW("%s: No input available for device %s", __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07006066 return BAD_VALUE;
6067 }
6068 } else {
6069 // Disconnect
Eric Laurentd4692962014-05-05 18:13:44 -07006070 // Clear any profiles associated with the disconnected device.
Mikhail Naganovd4120142017-12-06 15:49:22 -08006071 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07006072 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006073 profile_index < hwModule->getInputProfiles().size();
Eric Laurentd4692962014-05-05 18:13:44 -07006074 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006075 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Francois Gaffie716e1432019-01-14 16:58:59 +01006076 if (profile->supportsDevice(device)) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08006077 ALOGV("checkInputsForDevice(): clearing direct input profile %zu on module %s",
6078 profile_index, hwModule->getName());
François Gaffie112b0af2015-11-19 16:13:25 +01006079 profile->clearAudioProfiles();
Eric Laurentd4692962014-05-05 18:13:44 -07006080 }
6081 }
6082 }
6083 } // end disconnect
6084
6085 return NO_ERROR;
6086}
6087
6088
Eric Laurente0720872014-03-11 09:30:41 -07006089void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07006090{
6091 ALOGV("closeOutput(%d)", output);
6092
François Gaffie1c878552018-11-22 16:53:21 +01006093 sp<SwAudioOutputDescriptor> closingOutput = mOutputs.valueFor(output);
6094 if (closingOutput == NULL) {
Eric Laurente552edb2014-03-10 17:42:56 -07006095 ALOGW("closeOutput() unknown output %d", output);
6096 return;
6097 }
Mikhail Naganov32ebca32019-03-22 15:42:52 -07006098 const bool closingOutputWasActive = closingOutput->isActive();
François Gaffie1c878552018-11-22 16:53:21 +01006099 mPolicyMixes.closeOutput(closingOutput);
Eric Laurent275e8e92014-11-30 15:14:47 -08006100
Eric Laurente552edb2014-03-10 17:42:56 -07006101 // look for duplicated outputs connected to the output being removed.
6102 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie1c878552018-11-22 16:53:21 +01006103 sp<SwAudioOutputDescriptor> dupOutput = mOutputs.valueAt(i);
6104 if (dupOutput->isDuplicated() &&
6105 (dupOutput->mOutput1 == closingOutput || dupOutput->mOutput2 == closingOutput)) {
6106 sp<SwAudioOutputDescriptor> remainingOutput =
6107 dupOutput->mOutput1 == closingOutput ? dupOutput->mOutput2 : dupOutput->mOutput1;
Eric Laurente552edb2014-03-10 17:42:56 -07006108 // As all active tracks on duplicated output will be deleted,
6109 // and as they were also referenced on the other output, the reference
6110 // count for their stream type must be adjusted accordingly on
6111 // the other output.
François Gaffie1c878552018-11-22 16:53:21 +01006112 const bool wasActive = remainingOutput->isActive();
6113 // Note: no-op on the closing output where all clients has already been set inactive
6114 dupOutput->setAllClientsInactive();
Eric Laurent733ce942017-12-07 12:18:25 -08006115 // stop() will be a no op if the output is still active but is needed in case all
6116 // active streams refcounts where cleared above
6117 if (wasActive) {
François Gaffie1c878552018-11-22 16:53:21 +01006118 remainingOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08006119 }
Eric Laurente552edb2014-03-10 17:42:56 -07006120 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
6121 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
6122
6123 mpClientInterface->closeOutput(duplicatedOutput);
François Gaffie53615e22015-03-19 09:24:12 +01006124 removeOutput(duplicatedOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07006125 }
6126 }
6127
Eric Laurent05b90f82014-08-27 15:32:29 -07006128 nextAudioPortGeneration();
6129
François Gaffie1c878552018-11-22 16:53:21 +01006130 ssize_t index = mAudioPatches.indexOfKey(closingOutput->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07006131 if (index >= 0) {
6132 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006133 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
6134 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07006135 mAudioPatches.removeItemsAt(index);
6136 mpClientInterface->onAudioPatchListUpdate();
6137 }
6138
Mikhail Naganov32ebca32019-03-22 15:42:52 -07006139 if (closingOutputWasActive) {
6140 closingOutput->stop();
6141 }
François Gaffie1c878552018-11-22 16:53:21 +01006142 closingOutput->close();
Eric Laurente552edb2014-03-10 17:42:56 -07006143
François Gaffie53615e22015-03-19 09:24:12 +01006144 removeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07006145 mPreviousOutputs = mOutputs;
Eric Laurentb4f42a92022-01-17 17:37:31 +01006146 if (closingOutput == mSpatializerOutput) {
6147 mSpatializerOutput.clear();
6148 }
Dean Wheatley3023b382018-08-09 07:42:40 +10006149
6150 // MSD patches may have been released to support a non-MSD direct output. Reset MSD patch if
6151 // no direct outputs are open.
François Gaffie11d30102018-11-02 16:09:09 +01006152 if (!getMsdAudioOutDevices().isEmpty()) {
Dean Wheatley3023b382018-08-09 07:42:40 +10006153 bool directOutputOpen = false;
6154 for (size_t i = 0; i < mOutputs.size(); i++) {
6155 if (mOutputs[i]->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
6156 directOutputOpen = true;
6157 break;
6158 }
6159 }
6160 if (!directOutputOpen) {
Michael Chan6fb34492020-12-08 15:44:49 +11006161 ALOGV("no direct outputs open, reset MSD patches");
6162 // TODO: The MSD patches to be established here may differ to current MSD patches due to
6163 // how output devices for patching are resolved. Avoid by caching and reusing the
6164 // arguments to mEngine->getOutputDevicesForAttributes() when resolving which output
6165 // devices to patch to. This may be complicated by the fact that devices may become
6166 // unavailable.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11006167 setMsdOutputPatches();
Dean Wheatley3023b382018-08-09 07:42:40 +10006168 }
6169 }
Eric Laurent05b90f82014-08-27 15:32:29 -07006170}
6171
6172void AudioPolicyManager::closeInput(audio_io_handle_t input)
6173{
6174 ALOGV("closeInput(%d)", input);
6175
6176 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
6177 if (inputDesc == NULL) {
6178 ALOGW("closeInput() unknown input %d", input);
6179 return;
6180 }
6181
Eric Laurent6a94d692014-05-20 11:18:06 -07006182 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07006183
François Gaffie11d30102018-11-02 16:09:09 +01006184 sp<DeviceDescriptor> device = inputDesc->getDevice();
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08006185 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07006186 if (index >= 0) {
6187 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006188 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
6189 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07006190 mAudioPatches.removeItemsAt(index);
6191 mpClientInterface->onAudioPatchListUpdate();
6192 }
6193
Eric Laurentfe231122017-11-17 17:48:06 -08006194 inputDesc->close();
Eric Laurent05b90f82014-08-27 15:32:29 -07006195 mInputs.removeItem(input);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07006196
François Gaffie11d30102018-11-02 16:09:09 +01006197 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
6198 if (primaryInputDevices.contains(device) &&
Haynes Mathew George1d539d92018-03-16 11:40:49 -07006199 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07006200 mpClientInterface->setSoundTriggerCaptureState(false);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07006201 }
Eric Laurente552edb2014-03-10 17:42:56 -07006202}
6203
François Gaffie11d30102018-11-02 16:09:09 +01006204SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevices(
6205 const DeviceVector &devices,
6206 const SwAudioOutputCollection& openOutputs)
Eric Laurente552edb2014-03-10 17:42:56 -07006207{
6208 SortedVector<audio_io_handle_t> outputs;
6209
François Gaffie11d30102018-11-02 16:09:09 +01006210 ALOGVV("%s() devices %s", __func__, devices.toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07006211 for (size_t i = 0; i < openOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01006212 ALOGVV("output %zu isDuplicated=%d device=%s",
Eric Laurent8c7e6da2015-04-21 17:37:00 -07006213 i, openOutputs.valueAt(i)->isDuplicated(),
François Gaffie11d30102018-11-02 16:09:09 +01006214 openOutputs.valueAt(i)->supportedDevices().toString().c_str());
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006215 if (openOutputs.valueAt(i)->supportsAllDevices(devices)
jiabin9a3361e2019-10-01 09:38:30 -07006216 && openOutputs.valueAt(i)->devicesSupportEncodedFormats(devices.types())) {
François Gaffie11d30102018-11-02 16:09:09 +01006217 ALOGVV("%s() found output %d", __func__, openOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07006218 outputs.add(openOutputs.keyAt(i));
6219 }
6220 }
6221 return outputs;
6222}
6223
Mikhail Naganov37977152018-07-11 15:54:44 -07006224void AudioPolicyManager::checkForDeviceAndOutputChanges(std::function<bool()> onOutputsChecked)
6225{
6226 // checkA2dpSuspend must run before checkOutputForAllStrategies so that A2DP
6227 // output is suspended before any tracks are moved to it
6228 checkA2dpSuspend();
6229 checkOutputForAllStrategies();
Kevin Rocard153f92d2018-12-18 18:33:28 -08006230 checkSecondaryOutputs();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11006231 if (onOutputsChecked != nullptr && onOutputsChecked()) checkA2dpSuspend();
Mikhail Naganov37977152018-07-11 15:54:44 -07006232 updateDevicesAndOutputs();
Mikhail Naganov7bd9b8d2018-11-15 02:09:03 +00006233 if (mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD) != 0) {
Michael Chan6fb34492020-12-08 15:44:49 +11006234 // TODO: The MSD patches to be established here may differ to current MSD patches due to how
6235 // output devices for patching are resolved. Nevertheless, AudioTracks affected by device
6236 // configuration changes will ultimately be rerouted correctly. We can still avoid
6237 // unnecessary rerouting by caching and reusing the arguments to
6238 // mEngine->getOutputDevicesForAttributes() when resolving which output devices to patch to.
6239 // This may be complicated by the fact that devices may become unavailable.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11006240 setMsdOutputPatches();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11006241 }
Jean-Michel Trivi9a6b9ad2020-10-22 16:46:43 -07006242 // an event that changed routing likely occurred, inform upper layers
6243 mpClientInterface->onRoutingUpdated();
Mikhail Naganov37977152018-07-11 15:54:44 -07006244}
6245
François Gaffiec005e562018-11-06 15:04:49 +01006246bool AudioPolicyManager::followsSameRouting(const audio_attributes_t &lAttr,
6247 const audio_attributes_t &rAttr) const
Eric Laurente552edb2014-03-10 17:42:56 -07006248{
François Gaffiec005e562018-11-06 15:04:49 +01006249 return mEngine->getProductStrategyForAttributes(lAttr) ==
6250 mEngine->getProductStrategyForAttributes(rAttr);
6251}
6252
Francois Gaffieff1eb522020-05-06 18:37:04 +02006253void AudioPolicyManager::checkAudioSourceForAttributes(const audio_attributes_t &attr)
6254{
6255 for (size_t i = 0; i < mAudioSources.size(); i++) {
6256 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
6257 if (sourceDesc != nullptr && followsSameRouting(attr, sourceDesc->attributes())
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02006258 && sourceDesc->getPatchHandle() == AUDIO_PATCH_HANDLE_NONE
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02006259 && !isCallRxAudioSource(sourceDesc) && !sourceDesc->isInternal()) {
Francois Gaffieff1eb522020-05-06 18:37:04 +02006260 connectAudioSource(sourceDesc);
6261 }
6262 }
6263}
6264
6265void AudioPolicyManager::clearAudioSourcesForOutput(audio_io_handle_t output)
6266{
6267 for (size_t i = 0; i < mAudioSources.size(); i++) {
6268 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
6269 if (sourceDesc != nullptr && sourceDesc->swOutput().promote() != nullptr
6270 && sourceDesc->swOutput().promote()->mIoHandle == output) {
6271 disconnectAudioSource(sourceDesc);
6272 }
6273 }
6274}
6275
François Gaffiec005e562018-11-06 15:04:49 +01006276void AudioPolicyManager::checkOutputForAttributes(const audio_attributes_t &attr)
6277{
6278 auto psId = mEngine->getProductStrategyForAttributes(attr);
6279
6280 DeviceVector oldDevices = mEngine->getOutputDevicesForAttributes(attr, 0, true /*fromCache*/);
6281 DeviceVector newDevices = mEngine->getOutputDevicesForAttributes(attr, 0, false /*fromCache*/);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07006282
François Gaffie11d30102018-11-02 16:09:09 +01006283 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevices(oldDevices, mPreviousOutputs);
6284 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevices(newDevices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07006285
Eric Laurentc209fe42020-06-05 18:11:23 -07006286 uint32_t maxLatency = 0;
6287 bool invalidate = false;
6288 // take into account dynamic audio policies related changes: if a client is now associated
6289 // to a different policy mix than at creation time, invalidate corresponding stream
6290 for (size_t i = 0; i < mPreviousOutputs.size() && !invalidate; i++) {
6291 const sp<SwAudioOutputDescriptor>& desc = mPreviousOutputs.valueAt(i);
6292 if (desc->isDuplicated()) {
6293 continue;
Jean-Michel Trivife472e22014-12-16 14:23:13 -08006294 }
Eric Laurentc209fe42020-06-05 18:11:23 -07006295 for (const sp<TrackClientDescriptor>& client : desc->getClientIterable()) {
6296 if (mEngine->getProductStrategyForAttributes(client->attributes()) != psId) {
6297 continue;
6298 }
6299 sp<AudioPolicyMix> primaryMix;
6300 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->uid(),
6301 client->flags(), primaryMix, nullptr);
6302 if (status != OK) {
6303 continue;
6304 }
yucliuf4de36d2020-09-14 14:57:56 -07006305 if (client->getPrimaryMix() != primaryMix || client->hasLostPrimaryMix()) {
Eric Laurentc209fe42020-06-05 18:11:23 -07006306 invalidate = true;
6307 if (desc->isStrategyActive(psId)) {
6308 maxLatency = desc->latency();
6309 }
6310 break;
6311 }
Jean-Michel Trivife472e22014-12-16 14:23:13 -08006312 }
6313 }
6314
Eric Laurentc209fe42020-06-05 18:11:23 -07006315 if (srcOutputs != dstOutputs || invalidate) {
Eric Laurentac3a6902018-05-11 16:39:10 -07006316 // get maximum latency of all source outputs to determine the minimum mute time guaranteeing
6317 // audio from invalidated tracks will be rendered when unmuting
Eric Laurentac3a6902018-05-11 16:39:10 -07006318 for (audio_io_handle_t srcOut : srcOutputs) {
6319 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
Eric Laurentaa02db82019-09-05 17:31:49 -07006320 if (desc == nullptr) continue;
6321
6322 if (desc->isStrategyActive(psId) && maxLatency < desc->latency()) {
Eric Laurentac3a6902018-05-11 16:39:10 -07006323 maxLatency = desc->latency();
6324 }
Eric Laurentaa02db82019-09-05 17:31:49 -07006325
6326 if (invalidate) continue;
6327
6328 for (auto client : desc->clientsList(false /*activeOnly*/)) {
Eric Laurent78aade82019-09-13 18:55:08 -07006329 if (desc->isDuplicated() || !desc->mProfile->isDirectOutput()) {
Eric Laurentaa02db82019-09-05 17:31:49 -07006330 // a client on a non direct outputs has necessarily a linear PCM format
6331 // so we can call selectOutput() safely
6332 const audio_io_handle_t newOutput = selectOutput(dstOutputs,
6333 client->flags(),
6334 client->config().format,
6335 client->config().channel_mask,
jiabinebb6af42020-06-09 17:31:17 -07006336 client->config().sample_rate,
6337 client->session());
Eric Laurentaa02db82019-09-05 17:31:49 -07006338 if (newOutput != srcOut) {
6339 invalidate = true;
6340 break;
6341 }
6342 } else {
6343 sp<IOProfile> profile = getProfileForOutput(newDevices,
6344 client->config().sample_rate,
6345 client->config().format,
6346 client->config().channel_mask,
6347 client->flags(),
6348 true /* directOnly */);
6349 if (profile != desc->mProfile) {
6350 invalidate = true;
6351 break;
6352 }
6353 }
6354 }
Eric Laurentac3a6902018-05-11 16:39:10 -07006355 }
Eric Laurentaa02db82019-09-05 17:31:49 -07006356
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006357 ALOGV_IF(!(srcOutputs.isEmpty() || dstOutputs.isEmpty()),
François Gaffiec005e562018-11-06 15:04:49 +01006358 "%s: strategy %d, moving from output %s to output %s", __func__, psId,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006359 std::to_string(srcOutputs[0]).c_str(),
6360 std::to_string(dstOutputs[0]).c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07006361 // mute strategy while moving tracks from one output to another
Mikhail Naganovcf84e592017-12-07 11:25:11 -08006362 for (audio_io_handle_t srcOut : srcOutputs) {
Eric Laurentac3a6902018-05-11 16:39:10 -07006363 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
Eric Laurentaa02db82019-09-05 17:31:49 -07006364 if (desc == nullptr) continue;
6365
6366 if (desc->isStrategyActive(psId)) {
François Gaffiec005e562018-11-06 15:04:49 +01006367 setStrategyMute(psId, true, desc);
6368 setStrategyMute(psId, false, desc, maxLatency * LATENCY_MUTE_FACTOR,
François Gaffie11d30102018-11-02 16:09:09 +01006369 newDevices.types());
Eric Laurente552edb2014-03-10 17:42:56 -07006370 }
François Gaffiec005e562018-11-06 15:04:49 +01006371 sp<SourceClientDescriptor> source = getSourceForAttributesOnOutput(srcOut, attr);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02006372 if (source != nullptr && !isCallRxAudioSource(source) && !source->isInternal()) {
Eric Laurentd60560a2015-04-10 11:31:20 -07006373 connectAudioSource(source);
6374 }
Eric Laurente552edb2014-03-10 17:42:56 -07006375 }
6376
François Gaffiec005e562018-11-06 15:04:49 +01006377 // Move effects associated to this stream from previous output to new output
6378 if (followsSameRouting(attr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07006379 selectOutputForMusicEffects();
Eric Laurente552edb2014-03-10 17:42:56 -07006380 }
François Gaffiec005e562018-11-06 15:04:49 +01006381 // Move tracks associated to this stream (and linked) from previous output to new output
Eric Laurentaa02db82019-09-05 17:31:49 -07006382 if (invalidate) {
6383 for (auto stream : mEngine->getStreamTypesForProductStrategy(psId)) {
6384 mpClientInterface->invalidateStream(stream);
6385 }
jiabin49256852022-03-09 11:21:35 -08006386 for (audio_io_handle_t srcOut : srcOutputs) {
6387 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
6388 if (desc == nullptr) continue;
6389
6390 desc->setTracksInvalidatedStatusByStrategy(psId);
6391 }
Eric Laurente552edb2014-03-10 17:42:56 -07006392 }
6393 }
6394}
6395
Eric Laurente0720872014-03-11 09:30:41 -07006396void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07006397{
François Gaffiec005e562018-11-06 15:04:49 +01006398 for (const auto &strategy : mEngine->getOrderedProductStrategies()) {
6399 auto attributes = mEngine->getAllAttributesForProductStrategy(strategy).front();
6400 checkOutputForAttributes(attributes);
Francois Gaffieff1eb522020-05-06 18:37:04 +02006401 checkAudioSourceForAttributes(attributes);
François Gaffiec005e562018-11-06 15:04:49 +01006402 }
Eric Laurente552edb2014-03-10 17:42:56 -07006403}
6404
Kevin Rocard153f92d2018-12-18 18:33:28 -08006405void AudioPolicyManager::checkSecondaryOutputs() {
6406 std::set<audio_stream_type_t> streamsToInvalidate;
jiabin10a03f12021-05-07 23:46:28 +00006407 TrackSecondaryOutputsMap trackSecondaryOutputs;
Kevin Rocard153f92d2018-12-18 18:33:28 -08006408 for (size_t i = 0; i < mOutputs.size(); i++) {
6409 const sp<SwAudioOutputDescriptor>& outputDescriptor = mOutputs[i];
6410 for (const sp<TrackClientDescriptor>& client : outputDescriptor->getClientIterable()) {
Eric Laurentc529cf62020-04-17 18:19:10 -07006411 sp<AudioPolicyMix> primaryMix;
6412 std::vector<sp<AudioPolicyMix>> secondaryMixes;
Kevin Rocard94114a22019-04-01 19:38:23 -07006413 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->uid(),
Eric Laurentc529cf62020-04-17 18:19:10 -07006414 client->flags(), primaryMix, &secondaryMixes);
6415 std::vector<sp<SwAudioOutputDescriptor>> secondaryDescs;
6416 for (auto &secondaryMix : secondaryMixes) {
6417 sp<SwAudioOutputDescriptor> outputDesc = secondaryMix->getOutput();
6418 if (outputDesc != nullptr &&
6419 outputDesc->mIoHandle != AUDIO_IO_HANDLE_NONE) {
6420 secondaryDescs.push_back(outputDesc);
6421 }
6422 }
6423
jiabin10a03f12021-05-07 23:46:28 +00006424 if (status != OK) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08006425 streamsToInvalidate.insert(client->stream());
jiabin10a03f12021-05-07 23:46:28 +00006426 } else if (!std::equal(
6427 client->getSecondaryOutputs().begin(),
6428 client->getSecondaryOutputs().end(),
6429 secondaryDescs.begin(), secondaryDescs.end())) {
jiabina5281062021-11-23 00:10:23 +00006430 if (!audio_is_linear_pcm(client->config().format)) {
6431 // If the format is not PCM, the tracks should be invalidated to get correct
6432 // behavior when the secondary output is changed.
6433 streamsToInvalidate.insert(client->stream());
6434 } else {
6435 std::vector<wp<SwAudioOutputDescriptor>> weakSecondaryDescs;
6436 std::vector<audio_io_handle_t> secondaryOutputIds;
6437 for (const auto &secondaryDesc: secondaryDescs) {
6438 secondaryOutputIds.push_back(secondaryDesc->mIoHandle);
6439 weakSecondaryDescs.push_back(secondaryDesc);
6440 }
6441 trackSecondaryOutputs.emplace(client->portId(), secondaryOutputIds);
6442 client->setSecondaryOutputs(std::move(weakSecondaryDescs));
jiabin10a03f12021-05-07 23:46:28 +00006443 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08006444 }
6445 }
6446 }
jiabin10a03f12021-05-07 23:46:28 +00006447 if (!trackSecondaryOutputs.empty()) {
6448 mpClientInterface->updateSecondaryOutputs(trackSecondaryOutputs);
6449 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08006450 for (audio_stream_type_t stream : streamsToInvalidate) {
jiabin10a03f12021-05-07 23:46:28 +00006451 ALOGD("%s Invalidate stream %d due to fail getting output for attr", __func__, stream);
Kevin Rocard153f92d2018-12-18 18:33:28 -08006452 mpClientInterface->invalidateStream(stream);
6453 }
6454}
6455
Eric Laurent2517af32020-11-25 15:31:27 +01006456bool AudioPolicyManager::isScoRequestedForComm() const {
6457 AudioDeviceTypeAddrVector devices;
6458 mEngine->getDevicesForRoleAndStrategy(mCommunnicationStrategy, DEVICE_ROLE_PREFERRED, devices);
6459 for (const auto &device : devices) {
6460 if (audio_is_bluetooth_out_sco_device(device.mType)) {
6461 return true;
6462 }
6463 }
6464 return false;
6465}
6466
Eric Laurent1a8b45f2022-04-13 16:01:47 +02006467bool AudioPolicyManager::isHearingAidUsedForComm() const {
6468 DeviceVector devices = mEngine->getOutputDevicesForStream(AUDIO_STREAM_VOICE_CALL,
6469 true /*fromCache*/);
6470 for (const auto &device : devices) {
6471 if (device->type() == AUDIO_DEVICE_OUT_HEARING_AID) {
6472 return true;
6473 }
6474 }
6475 return false;
6476}
6477
6478
Eric Laurente0720872014-03-11 09:30:41 -07006479void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07006480{
François Gaffie53615e22015-03-19 09:24:12 +01006481 audio_io_handle_t a2dpOutput = mOutputs.getA2dpOutput();
Aniket Kumar Lataa8ee9962018-01-31 20:24:23 -08006482 if (a2dpOutput == 0 || mOutputs.isA2dpOffloadedOnPrimary()) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07006483 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07006484 return;
6485 }
6486
Eric Laurent3a4311c2014-03-17 12:00:47 -07006487 bool isScoConnected =
jiabin9a3361e2019-10-01 09:38:30 -07006488 (mAvailableInputDevices.types().count(AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) != 0 ||
6489 !Intersection(mAvailableOutputDevices.types(), getAudioDeviceOutAllScoSet()).empty());
Eric Laurent2517af32020-11-25 15:31:27 +01006490 bool isScoRequested = isScoRequestedForComm();
Eric Laurentf732e072016-08-03 19:30:28 -07006491
6492 // if suspended, restore A2DP output if:
6493 // ((SCO device is NOT connected) ||
Eric Laurent2517af32020-11-25 15:31:27 +01006494 // ((SCO is not requested) &&
Eric Laurentf732e072016-08-03 19:30:28 -07006495 // (phone state is NOT in call) && (phone state is NOT ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07006496 //
Eric Laurentf732e072016-08-03 19:30:28 -07006497 // if not suspended, suspend A2DP output if:
6498 // (SCO device is connected) &&
Eric Laurent2517af32020-11-25 15:31:27 +01006499 // ((SCO is requested) ||
Eric Laurentf732e072016-08-03 19:30:28 -07006500 // ((phone state is in call) || (phone state is ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07006501 //
6502 if (mA2dpSuspended) {
Eric Laurentf732e072016-08-03 19:30:28 -07006503 if (!isScoConnected ||
Eric Laurent2517af32020-11-25 15:31:27 +01006504 (!isScoRequested &&
Eric Laurentf732e072016-08-03 19:30:28 -07006505 (mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) &&
François Gaffie2110e042015-03-24 08:41:51 +01006506 (mEngine->getPhoneState() != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07006507
6508 mpClientInterface->restoreOutput(a2dpOutput);
6509 mA2dpSuspended = false;
6510 }
6511 } else {
Eric Laurentf732e072016-08-03 19:30:28 -07006512 if (isScoConnected &&
Eric Laurent2517af32020-11-25 15:31:27 +01006513 (isScoRequested ||
Eric Laurentf732e072016-08-03 19:30:28 -07006514 (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) ||
François Gaffie2110e042015-03-24 08:41:51 +01006515 (mEngine->getPhoneState() == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07006516
6517 mpClientInterface->suspendOutput(a2dpOutput);
6518 mA2dpSuspended = true;
6519 }
6520 }
6521}
6522
François Gaffie11d30102018-11-02 16:09:09 +01006523DeviceVector AudioPolicyManager::getNewOutputDevices(const sp<SwAudioOutputDescriptor>& outputDesc,
6524 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07006525{
François Gaffie11d30102018-11-02 16:09:09 +01006526 DeviceVector devices;
6527
Jean-Michel Triviff155c62016-02-26 12:07:16 -08006528 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07006529 if (index >= 0) {
6530 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006531 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01006532 ALOGV("%s device %s forced by patch %d", __func__,
6533 outputDesc->devices().toString().c_str(), outputDesc->getPatchHandle());
6534 return outputDesc->devices();
Eric Laurent6a94d692014-05-20 11:18:06 -07006535 }
6536 }
6537
Dean Wheatley514b4312020-06-17 21:45:00 +10006538 // Do not retrieve engine device for outputs through MSD
6539 // TODO: support explicit routing requests by resetting MSD patch to engine device.
6540 if (outputDesc->devices() == getMsdAudioOutDevices()) {
6541 return outputDesc->devices();
6542 }
6543
Eric Laurent97ac8712018-07-27 18:59:02 -07006544 // Honor explicit routing requests only if no client using default routing is active on this
6545 // input: a specific app can not force routing for other apps by setting a preferred device.
6546 bool active; // unused
François Gaffie11d30102018-11-02 16:09:09 +01006547 sp<DeviceDescriptor> device =
François Gaffiec005e562018-11-06 15:04:49 +01006548 findPreferredDevice(outputDesc, PRODUCT_STRATEGY_NONE, active, mAvailableOutputDevices);
François Gaffie11d30102018-11-02 16:09:09 +01006549 if (device != nullptr) {
6550 return DeviceVector(device);
Eric Laurentf3a5a602018-05-22 18:42:55 -07006551 }
6552
François Gaffiea807ef92018-11-05 10:44:33 +01006553 // Legacy Engine cannot take care of bus devices and mix, so we need to handle the conflict
6554 // of setForceUse / Default Bus device here
6555 device = mPolicyMixes.getDeviceAndMixForOutput(outputDesc, mAvailableOutputDevices);
6556 if (device != nullptr) {
6557 return DeviceVector(device);
6558 }
6559
François Gaffiec005e562018-11-06 15:04:49 +01006560 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
6561 StreamTypeVector streams = mEngine->getStreamTypesForProductStrategy(productStrategy);
6562 auto attr = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05306563 auto hasStreamActive = [&](auto stream) {
6564 return hasStream(streams, stream) && isStreamActive(stream, 0);
6565 };
Eric Laurent484e9272018-06-07 17:29:23 -07006566
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05306567 auto doGetOutputDevicesForVoice = [&]() {
6568 return hasVoiceStream(streams) && (outputDesc == mPrimaryOutput ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01006569 outputDesc->isActive(toVolumeSource(AUDIO_STREAM_VOICE_CALL, false))) &&
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05306570 (isInCall() ||
Henrik Backlund07c654a2021-10-14 15:57:10 +02006571 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc)) &&
6572 !isStreamActive(AUDIO_STREAM_ENFORCED_AUDIBLE, 0);
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05306573 };
6574
6575 // With low-latency playing on speaker, music on WFD, when the first low-latency
6576 // output is stopped, getNewOutputDevices checks for a product strategy
6577 // from the list, as STRATEGY_SONIFICATION comes prior to STRATEGY_MEDIA.
Carter Hsucc58a6b2021-07-20 08:44:50 +00006578 // If an ALARM or ENFORCED_AUDIBLE stream is supported by the product strategy,
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05306579 // devices are returned for STRATEGY_SONIFICATION without checking whether the
6580 // stream is associated to the output descriptor.
6581 if (doGetOutputDevicesForVoice() || outputDesc->isStrategyActive(productStrategy) ||
6582 ((hasStreamActive(AUDIO_STREAM_ALARM) ||
6583 hasStreamActive(AUDIO_STREAM_ENFORCED_AUDIBLE)) &&
6584 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc))) {
François Gaffiec005e562018-11-06 15:04:49 +01006585 // Retrieval of devices for voice DL is done on primary output profile, cannot
6586 // check the route (would force modifying configuration file for this profile)
6587 devices = mEngine->getOutputDevicesForAttributes(attr, nullptr, fromCache);
6588 break;
6589 }
Eric Laurente552edb2014-03-10 17:42:56 -07006590 }
François Gaffiec005e562018-11-06 15:04:49 +01006591 ALOGV("%s selected devices %s", __func__, devices.toString().c_str());
François Gaffie11d30102018-11-02 16:09:09 +01006592 return devices;
Eric Laurent1c333e22014-05-20 10:48:17 -07006593}
6594
François Gaffie11d30102018-11-02 16:09:09 +01006595sp<DeviceDescriptor> AudioPolicyManager::getNewInputDevice(
6596 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurent1c333e22014-05-20 10:48:17 -07006597{
François Gaffie11d30102018-11-02 16:09:09 +01006598 sp<DeviceDescriptor> device;
Eric Laurent6a94d692014-05-20 11:18:06 -07006599
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08006600 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07006601 if (index >= 0) {
6602 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006603 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01006604 ALOGV("getNewInputDevice() device %s forced by patch %d",
6605 inputDesc->getDevice()->toString().c_str(), inputDesc->getPatchHandle());
6606 return inputDesc->getDevice();
Eric Laurent6a94d692014-05-20 11:18:06 -07006607 }
6608 }
6609
Eric Laurent97ac8712018-07-27 18:59:02 -07006610 // Honor explicit routing requests only if no client using default routing is active on this
6611 // input: a specific app can not force routing for other apps by setting a preferred device.
6612 bool active;
François Gaffie11d30102018-11-02 16:09:09 +01006613 device = findPreferredDevice(inputDesc, AUDIO_SOURCE_DEFAULT, active, mAvailableInputDevices);
6614 if (device != nullptr) {
6615 return device;
Eric Laurent97ac8712018-07-27 18:59:02 -07006616 }
6617
Eric Laurentdc95a252018-04-12 12:46:56 -07006618 // If we are not in call and no client is active on this input, this methods returns
Andy Hungf024a9e2019-01-30 16:01:02 -08006619 // a null sp<>, causing the patch on the input stream to be released.
yuanjiahsu0735bf32021-03-18 08:12:54 +08006620 audio_attributes_t attributes;
6621 uid_t uid;
6622 sp<RecordClientDescriptor> topClient = inputDesc->getHighestPriorityClient();
6623 if (topClient != nullptr) {
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01006624 attributes = topClient->attributes();
6625 uid = topClient->uid();
yuanjiahsu0735bf32021-03-18 08:12:54 +08006626 } else {
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01006627 attributes = { .source = AUDIO_SOURCE_DEFAULT };
6628 uid = 0;
yuanjiahsu0735bf32021-03-18 08:12:54 +08006629 }
6630
Francois Gaffie716e1432019-01-14 16:58:59 +01006631 if (attributes.source == AUDIO_SOURCE_DEFAULT && isInCall()) {
6632 attributes.source = AUDIO_SOURCE_VOICE_COMMUNICATION;
Eric Laurentdc95a252018-04-12 12:46:56 -07006633 }
Francois Gaffie716e1432019-01-14 16:58:59 +01006634 if (attributes.source != AUDIO_SOURCE_DEFAULT) {
yuanjiahsu0735bf32021-03-18 08:12:54 +08006635 device = mEngine->getInputDeviceForAttributes(attributes, uid);
Eric Laurentfb66dd92016-01-28 18:32:03 -08006636 }
Eric Laurent1c333e22014-05-20 10:48:17 -07006637
Eric Laurente552edb2014-03-10 17:42:56 -07006638 return device;
6639}
6640
Eric Laurent794fde22016-03-11 09:50:45 -08006641bool AudioPolicyManager::streamsMatchForvolume(audio_stream_type_t stream1,
6642 audio_stream_type_t stream2) {
Jean-Michel Trivi99bb2f92016-11-23 15:52:07 -08006643 return (stream1 == stream2);
Eric Laurent28d09f02016-03-08 10:43:05 -08006644}
6645
Dorin Drimusf2196d82022-01-03 12:11:18 +01006646// TODO - consider MSD routes b/214971780
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08006647status_t AudioPolicyManager::getDevicesForAttributes(
Andy Hung6d23c0f2022-02-16 09:37:15 -08006648 const audio_attributes_t &attr, AudioDeviceTypeAddrVector *devices, bool forVolume) {
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08006649 if (devices == nullptr) {
6650 return BAD_VALUE;
6651 }
Andy Hung6d23c0f2022-02-16 09:37:15 -08006652
6653 // Devices are determined in the following precedence:
6654 //
6655 // 1) Devices associated with a dynamic policy matching the attributes. This is often
6656 // a remote submix from MIX_ROUTE_FLAG_LOOP_BACK.
6657 //
6658 // If no such dynamic policy then
6659 // 2) Devices containing an active client using setPreferredDevice
6660 // with same strategy as the attributes.
6661 // (from the default Engine::getOutputDevicesForAttributes() implementation).
6662 //
6663 // If no corresponding active client with setPreferredDevice then
6664 // 3) Devices associated with the strategy determined by the attributes
6665 // (from the default Engine::getOutputDevicesForAttributes() implementation).
6666 //
6667 // See related getOutputForAttrInt().
6668
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08006669 // check dynamic policies but only for primary descriptors (secondary not used for audible
6670 // audio routing, only used for duplication for playback capture)
Eric Laurentc529cf62020-04-17 18:19:10 -07006671 sp<AudioPolicyMix> policyMix;
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08006672 status_t status = mPolicyMixes.getOutputForAttr(attr, 0 /*uid unknown here*/,
Andy Hung6d23c0f2022-02-16 09:37:15 -08006673 AUDIO_OUTPUT_FLAG_NONE, policyMix, nullptr /* secondaryMixes */);
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08006674 if (status != OK) {
6675 return status;
6676 }
Andy Hung6d23c0f2022-02-16 09:37:15 -08006677
6678 DeviceVector curDevices;
6679 if (policyMix != nullptr && policyMix->getOutput() != nullptr &&
6680 // For volume control, skip LOOPBACK mixes which use AUDIO_DEVICE_OUT_REMOTE_SUBMIX
6681 // as they are unaffected by device/stream volume
6682 // (per SwAudioOutputDescriptor::isFixedVolume()).
6683 (!forVolume || policyMix->mDeviceType != AUDIO_DEVICE_OUT_REMOTE_SUBMIX)
6684 ) {
6685 sp<DeviceDescriptor> deviceDesc = mAvailableOutputDevices.getDevice(
6686 policyMix->mDeviceType, policyMix->mDeviceAddress, AUDIO_FORMAT_DEFAULT);
6687 curDevices.add(deviceDesc);
6688 } else {
6689 // The default Engine::getOutputDevicesForAttributes() uses findPreferredDevice()
6690 // which selects setPreferredDevice if active. This means forVolume call
6691 // will take an active setPreferredDevice, if such exists.
6692
6693 curDevices = mEngine->getOutputDevicesForAttributes(
6694 attr, nullptr /* preferredDevice */, false /* fromCache */);
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08006695 }
Andy Hung6d23c0f2022-02-16 09:37:15 -08006696
6697 if (forVolume) {
6698 // We alias the device AUDIO_DEVICE_OUT_SPEAKER_SAFE to AUDIO_DEVICE_OUT_SPEAKER
6699 // for single volume control in AudioService (such relationship should exist if
6700 // SPEAKER_SAFE is present).
6701 //
6702 // (This is unrelated to a different device grouping as Volume::getDeviceCategory)
6703 DeviceVector speakerSafeDevices =
6704 curDevices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER_SAFE);
6705 if (!speakerSafeDevices.isEmpty()) {
6706 curDevices.merge(
6707 mAvailableOutputDevices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER));
6708 curDevices.remove(speakerSafeDevices);
6709 }
6710 }
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08006711 for (const auto& device : curDevices) {
6712 devices->push_back(device->getDeviceTypeAddr());
6713 }
6714 return NO_ERROR;
6715}
6716
Eric Laurente0720872014-03-11 09:30:41 -07006717void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07006718 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07006719 case AUDIO_STREAM_MUSIC:
François Gaffiec005e562018-11-06 15:04:49 +01006720 checkOutputForAttributes(attributes_initializer(AUDIO_USAGE_NOTIFICATION));
Eric Laurente552edb2014-03-10 17:42:56 -07006721 updateDevicesAndOutputs();
6722 break;
6723 default:
6724 break;
6725 }
6726}
6727
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006728uint32_t AudioPolicyManager::handleEventForBeacon(int event) {
Eric Laurent9459fb02015-08-12 18:36:32 -07006729
6730 // skip beacon mute management if a dedicated TTS output is available
6731 if (mTtsOutputAvailable) {
6732 return 0;
6733 }
6734
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006735 switch(event) {
6736 case STARTING_OUTPUT:
6737 mBeaconMuteRefCount++;
6738 break;
6739 case STOPPING_OUTPUT:
6740 if (mBeaconMuteRefCount > 0) {
6741 mBeaconMuteRefCount--;
6742 }
6743 break;
6744 case STARTING_BEACON:
6745 mBeaconPlayingRefCount++;
6746 break;
6747 case STOPPING_BEACON:
6748 if (mBeaconPlayingRefCount > 0) {
6749 mBeaconPlayingRefCount--;
6750 }
6751 break;
6752 }
6753
6754 if (mBeaconMuteRefCount > 0) {
6755 // any playback causes beacon to be muted
6756 return setBeaconMute(true);
6757 } else {
6758 // no other playback: unmute when beacon starts playing, mute when it stops
6759 return setBeaconMute(mBeaconPlayingRefCount == 0);
6760 }
6761}
6762
6763uint32_t AudioPolicyManager::setBeaconMute(bool mute) {
6764 ALOGV("setBeaconMute(%d) mBeaconMuteRefCount=%d mBeaconPlayingRefCount=%d",
6765 mute, mBeaconMuteRefCount, mBeaconPlayingRefCount);
6766 // keep track of muted state to avoid repeating mute/unmute operations
6767 if (mBeaconMuted != mute) {
6768 // mute/unmute AUDIO_STREAM_TTS on all outputs
6769 ALOGV("\t muting %d", mute);
6770 uint32_t maxLatency = 0;
Francois Gaffie4404ddb2021-02-04 17:03:38 +01006771 auto ttsVolumeSource = toVolumeSource(AUDIO_STREAM_TTS, false);
6772 if (ttsVolumeSource == VOLUME_SOURCE_NONE) {
6773 ALOGV("\t no tts volume source available");
6774 return 0;
6775 }
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006776 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07006777 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
jiabin9a3361e2019-10-01 09:38:30 -07006778 setVolumeSourceMute(ttsVolumeSource, mute/*on*/, desc, 0 /*delay*/, DeviceTypeSet());
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006779 const uint32_t latency = desc->latency() * 2;
Eric Laurentcdb2b352020-07-23 10:57:02 -07006780 if (desc->isActive(latency * 2) && latency > maxLatency) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006781 maxLatency = latency;
6782 }
6783 }
6784 mBeaconMuted = mute;
6785 return maxLatency;
6786 }
6787 return 0;
6788}
6789
Eric Laurente0720872014-03-11 09:30:41 -07006790void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07006791{
François Gaffiec005e562018-11-06 15:04:49 +01006792 mEngine->updateDeviceSelectionCache();
Eric Laurente552edb2014-03-10 17:42:56 -07006793 mPreviousOutputs = mOutputs;
6794}
6795
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07006796uint32_t AudioPolicyManager::checkDeviceMuteStrategies(const sp<AudioOutputDescriptor>& outputDesc,
François Gaffiec005e562018-11-06 15:04:49 +01006797 const DeviceVector &prevDevices,
Eric Laurente552edb2014-03-10 17:42:56 -07006798 uint32_t delayMs)
6799{
6800 // mute/unmute strategies using an incompatible device combination
6801 // if muting, wait for the audio in pcm buffer to be drained before proceeding
6802 // if unmuting, unmute only after the specified delay
6803 if (outputDesc->isDuplicated()) {
6804 return 0;
6805 }
6806
6807 uint32_t muteWaitMs = 0;
François Gaffiec005e562018-11-06 15:04:49 +01006808 DeviceVector devices = outputDesc->devices();
6809 bool shouldMute = outputDesc->isActive() && (devices.size() >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07006810
François Gaffiec005e562018-11-06 15:04:49 +01006811 auto productStrategies = mEngine->getOrderedProductStrategies();
6812 for (const auto &productStrategy : productStrategies) {
6813 auto attributes = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
6814 DeviceVector curDevices =
6815 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false/*fromCache*/);
6816 curDevices = curDevices.filter(outputDesc->supportedDevices());
6817 bool mute = shouldMute && curDevices.containsAtLeastOne(devices) && curDevices != devices;
Eric Laurente552edb2014-03-10 17:42:56 -07006818 bool doMute = false;
6819
François Gaffiec005e562018-11-06 15:04:49 +01006820 if (mute && !outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07006821 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01006822 outputDesc->setStrategyMutedByDevice(productStrategy, true);
6823 } else if (!mute && outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07006824 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01006825 outputDesc->setStrategyMutedByDevice(productStrategy, false);
Eric Laurente552edb2014-03-10 17:42:56 -07006826 }
Eric Laurent99401132014-05-07 19:48:15 -07006827 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07006828 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07006829 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07006830 // skip output if it does not share any device with current output
François Gaffie11d30102018-11-02 16:09:09 +01006831 if (!desc->supportedDevices().containsAtLeastOne(outputDesc->supportedDevices())) {
Eric Laurente552edb2014-03-10 17:42:56 -07006832 continue;
6833 }
François Gaffiec005e562018-11-06 15:04:49 +01006834 ALOGVV("%s() %s (curDevice %s)", __func__,
6835 mute ? "muting" : "unmuting", curDevices.toString().c_str());
6836 setStrategyMute(productStrategy, mute, desc, mute ? 0 : delayMs);
6837 if (desc->isStrategyActive(productStrategy)) {
Eric Laurent99401132014-05-07 19:48:15 -07006838 if (mute) {
6839 // FIXME: should not need to double latency if volume could be applied
6840 // immediately by the audioflinger mixer. We must account for the delay
6841 // between now and the next time the audioflinger thread for this output
6842 // will process a buffer (which corresponds to one buffer size,
6843 // usually 1/2 or 1/4 of the latency).
6844 if (muteWaitMs < desc->latency() * 2) {
6845 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07006846 }
6847 }
6848 }
6849 }
6850 }
6851 }
6852
Eric Laurent99401132014-05-07 19:48:15 -07006853 // temporary mute output if device selection changes to avoid volume bursts due to
6854 // different per device volumes
François Gaffiec005e562018-11-06 15:04:49 +01006855 if (outputDesc->isActive() && (devices != prevDevices)) {
Eric Laurentdc462862016-07-19 12:29:53 -07006856 uint32_t tempMuteWaitMs = outputDesc->latency() * 2;
Jasmine Chaf6074fe2021-08-17 13:44:31 +08006857
Eric Laurentdc462862016-07-19 12:29:53 -07006858 if (muteWaitMs < tempMuteWaitMs) {
6859 muteWaitMs = tempMuteWaitMs;
Eric Laurent99401132014-05-07 19:48:15 -07006860 }
Jasmine Chaf6074fe2021-08-17 13:44:31 +08006861
6862 // If recommended duration is defined, replace temporary mute duration to avoid
6863 // truncated notifications at beginning, which depends on duration of changing path in HAL.
6864 // Otherwise, temporary mute duration is conservatively set to 4 times the reported latency.
6865 uint32_t tempRecommendedMuteDuration = outputDesc->getRecommendedMuteDurationMs();
6866 uint32_t tempMuteDurationMs = tempRecommendedMuteDuration > 0 ?
6867 tempRecommendedMuteDuration : outputDesc->latency() * 4;
6868
François Gaffieaaac0fd2018-11-22 17:56:39 +01006869 for (const auto &activeVs : outputDesc->getActiveVolumeSources()) {
6870 // make sure that we do not start the temporary mute period too early in case of
6871 // delayed device change
6872 setVolumeSourceMute(activeVs, true, outputDesc, delayMs);
6873 setVolumeSourceMute(activeVs, false, outputDesc, delayMs + tempMuteDurationMs,
François Gaffiec005e562018-11-06 15:04:49 +01006874 devices.types());
Eric Laurent99401132014-05-07 19:48:15 -07006875 }
6876 }
6877
Eric Laurente552edb2014-03-10 17:42:56 -07006878 // wait for the PCM output buffers to empty before proceeding with the rest of the command
6879 if (muteWaitMs > delayMs) {
6880 muteWaitMs -= delayMs;
6881 usleep(muteWaitMs * 1000);
6882 return muteWaitMs;
6883 }
6884 return 0;
6885}
6886
François Gaffie11d30102018-11-02 16:09:09 +01006887uint32_t AudioPolicyManager::setOutputDevices(const sp<SwAudioOutputDescriptor>& outputDesc,
6888 const DeviceVector &devices,
6889 bool force,
6890 int delayMs,
6891 audio_patch_handle_t *patchHandle,
Francois Gaffie3523ab32021-06-22 13:24:34 +02006892 bool requiresMuteCheck, bool requiresVolumeCheck)
Eric Laurente552edb2014-03-10 17:42:56 -07006893{
François Gaffie11d30102018-11-02 16:09:09 +01006894 ALOGV("%s device %s delayMs %d", __func__, devices.toString().c_str(), delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07006895 uint32_t muteWaitMs;
6896
6897 if (outputDesc->isDuplicated()) {
François Gaffie11d30102018-11-02 16:09:09 +01006898 muteWaitMs = setOutputDevices(outputDesc->subOutput1(), devices, force, delayMs,
6899 nullptr /* patchHandle */, requiresMuteCheck);
6900 muteWaitMs += setOutputDevices(outputDesc->subOutput2(), devices, force, delayMs,
6901 nullptr /* patchHandle */, requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07006902 return muteWaitMs;
6903 }
Eric Laurente552edb2014-03-10 17:42:56 -07006904
6905 // filter devices according to output selected
Francois Gaffie716e1432019-01-14 16:58:59 +01006906 DeviceVector filteredDevices = outputDesc->filterSupportedDevices(devices);
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01006907 DeviceVector prevDevices = outputDesc->devices();
Francois Gaffie3523ab32021-06-22 13:24:34 +02006908 DeviceVector availPrevDevices = mAvailableOutputDevices.filter(prevDevices);
Eric Laurente552edb2014-03-10 17:42:56 -07006909
François Gaffie11d30102018-11-02 16:09:09 +01006910 ALOGV("setOutputDevices() prevDevice %s", prevDevices.toString().c_str());
6911
6912 if (!filteredDevices.isEmpty()) {
6913 outputDesc->setDevices(filteredDevices);
Eric Laurente552edb2014-03-10 17:42:56 -07006914 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00006915
6916 // if the outputs are not materially active, there is no need to mute.
6917 if (requiresMuteCheck) {
François Gaffiec005e562018-11-06 15:04:49 +01006918 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevices, delayMs);
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00006919 } else {
6920 ALOGV("%s: suppressing checkDeviceMuteStrategies", __func__);
6921 muteWaitMs = 0;
6922 }
Eric Laurente552edb2014-03-10 17:42:56 -07006923
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02006924 bool outputRouted = outputDesc->isRouted();
6925
Eric Laurent79ea9582020-06-11 18:49:24 -07006926 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
6927 // output profile or if new device is not supported AND previous device(s) is(are) still
6928 // available (otherwise reset device must be done on the output)
Francois Gaffie3523ab32021-06-22 13:24:34 +02006929 if (!devices.isEmpty() && filteredDevices.isEmpty() && !availPrevDevices.empty()) {
Eric Laurent79ea9582020-06-11 18:49:24 -07006930 ALOGV("%s: unsupported device %s for output", __func__, devices.toString().c_str());
6931 // restore previous device after evaluating strategy mute state
6932 outputDesc->setDevices(prevDevices);
6933 return muteWaitMs;
6934 }
6935
Eric Laurente552edb2014-03-10 17:42:56 -07006936 // Do not change the routing if:
Eric Laurentb80a2a82014-10-27 16:07:59 -07006937 // the requested device is AUDIO_DEVICE_NONE
6938 // OR the requested device is the same as current device
6939 // AND force is not specified
6940 // AND the output is connected by a valid audio patch.
François Gaffie11d30102018-11-02 16:09:09 +01006941 // Doing this check here allows the caller to call setOutputDevices() without conditions
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02006942 if ((filteredDevices.isEmpty() || filteredDevices == prevDevices) && !force && outputRouted) {
François Gaffie11d30102018-11-02 16:09:09 +01006943 ALOGV("%s setting same device %s or null device, force=%d, patch handle=%d", __func__,
6944 filteredDevices.toString().c_str(), force, outputDesc->getPatchHandle());
Francois Gaffie3523ab32021-06-22 13:24:34 +02006945 if (requiresVolumeCheck && !filteredDevices.isEmpty()) {
6946 ALOGV("%s setting same device on routed output, force apply volumes", __func__);
6947 applyStreamVolumes(outputDesc, filteredDevices.types(), delayMs, true /*force*/);
6948 }
Eric Laurente552edb2014-03-10 17:42:56 -07006949 return muteWaitMs;
6950 }
6951
François Gaffie11d30102018-11-02 16:09:09 +01006952 ALOGV("%s changing device to %s", __func__, filteredDevices.toString().c_str());
Eric Laurent1c333e22014-05-20 10:48:17 -07006953
Eric Laurente552edb2014-03-10 17:42:56 -07006954 // do the routing
Francois Gaffie3523ab32021-06-22 13:24:34 +02006955 if (filteredDevices.isEmpty() || mAvailableOutputDevices.filter(filteredDevices).empty()) {
Eric Laurentc75307b2015-03-17 15:29:32 -07006956 resetOutputDevice(outputDesc, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07006957 } else {
François Gaffie11d30102018-11-02 16:09:09 +01006958 PatchBuilder patchBuilder;
6959 patchBuilder.addSource(outputDesc);
6960 ALOG_ASSERT(filteredDevices.size() <= AUDIO_PATCH_PORTS_MAX, "Too many sink ports");
6961 for (const auto &filteredDevice : filteredDevices) {
6962 patchBuilder.addSink(filteredDevice);
Eric Laurentc40d9692016-04-13 19:14:13 -07006963 }
6964
Jasmine Cha7f82d1a2020-03-16 13:21:47 +08006965 // Add half reported latency to delayMs when muteWaitMs is null in order
6966 // to avoid disordered sequence of muting volume and changing devices.
6967 installPatch(__func__, patchHandle, outputDesc.get(), patchBuilder.patch(),
6968 muteWaitMs == 0 ? (delayMs + (outputDesc->latency() / 2)) : delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07006969 }
Eric Laurente552edb2014-03-10 17:42:56 -07006970
6971 // update stream volumes according to new device
François Gaffie11d30102018-11-02 16:09:09 +01006972 applyStreamVolumes(outputDesc, filteredDevices.types(), delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07006973
6974 return muteWaitMs;
6975}
6976
Eric Laurentc75307b2015-03-17 15:29:32 -07006977status_t AudioPolicyManager::resetOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurent6a94d692014-05-20 11:18:06 -07006978 int delayMs,
6979 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07006980{
Eric Laurent6a94d692014-05-20 11:18:06 -07006981 ssize_t index;
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02006982 if (patchHandle == nullptr && !outputDesc->isRouted()) {
6983 return INVALID_OPERATION;
6984 }
Eric Laurent6a94d692014-05-20 11:18:06 -07006985 if (patchHandle) {
6986 index = mAudioPatches.indexOfKey(*patchHandle);
6987 } else {
Jean-Michel Triviff155c62016-02-26 12:07:16 -08006988 index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07006989 }
6990 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07006991 return INVALID_OPERATION;
6992 }
Eric Laurent6a94d692014-05-20 11:18:06 -07006993 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006994 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07006995 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07006996 outputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
François Gaffieafd4cea2019-11-18 15:50:22 +01006997 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07006998 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07006999 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07007000 return status;
7001}
7002
7003status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
François Gaffie11d30102018-11-02 16:09:09 +01007004 const sp<DeviceDescriptor> &device,
Eric Laurent6a94d692014-05-20 11:18:06 -07007005 bool force,
7006 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07007007{
7008 status_t status = NO_ERROR;
7009
Eric Laurent1f2f2232014-06-02 12:01:23 -07007010 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
François Gaffie11d30102018-11-02 16:09:09 +01007011 if ((device != nullptr) && ((device != inputDesc->getDevice()) || force)) {
7012 inputDesc->setDevice(device);
Eric Laurent1c333e22014-05-20 10:48:17 -07007013
François Gaffie11d30102018-11-02 16:09:09 +01007014 if (mAvailableInputDevices.contains(device)) {
Mikhail Naganovdc769682018-05-04 15:34:08 -07007015 PatchBuilder patchBuilder;
7016 patchBuilder.addSink(inputDesc,
Eric Laurentdaf92cc2014-07-22 15:36:10 -07007017 // AUDIO_SOURCE_HOTWORD is for internal use only:
7018 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
Mikhail Naganovdc769682018-05-04 15:34:08 -07007019 [inputDesc](const PatchBuilder::mix_usecase_t& usecase) {
7020 auto result = usecase;
7021 if (result.source == AUDIO_SOURCE_HOTWORD && !inputDesc->isSoundTrigger()) {
7022 result.source = AUDIO_SOURCE_VOICE_RECOGNITION;
7023 }
7024 return result; }).
Eric Laurent1c333e22014-05-20 10:48:17 -07007025 //only one input device for now
François Gaffie11d30102018-11-02 16:09:09 +01007026 addSource(device);
Mikhail Naganovdc769682018-05-04 15:34:08 -07007027 status = installPatch(__func__, patchHandle, inputDesc.get(), patchBuilder.patch(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07007028 }
7029 }
7030 return status;
7031}
7032
Eric Laurent6a94d692014-05-20 11:18:06 -07007033status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
7034 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07007035{
Eric Laurent1f2f2232014-06-02 12:01:23 -07007036 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07007037 ssize_t index;
7038 if (patchHandle) {
7039 index = mAudioPatches.indexOfKey(*patchHandle);
7040 } else {
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08007041 index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007042 }
7043 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07007044 return INVALID_OPERATION;
7045 }
Eric Laurent6a94d692014-05-20 11:18:06 -07007046 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007047 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07007048 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07007049 inputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
François Gaffieafd4cea2019-11-18 15:50:22 +01007050 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007051 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07007052 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07007053 return status;
7054}
7055
François Gaffie11d30102018-11-02 16:09:09 +01007056sp<IOProfile> AudioPolicyManager::getInputProfile(const sp<DeviceDescriptor> &device,
François Gaffie53615e22015-03-19 09:24:12 +01007057 uint32_t& samplingRate,
Andy Hungf129b032015-04-07 13:45:50 -07007058 audio_format_t& format,
7059 audio_channel_mask_t& channelMask,
François Gaffie53615e22015-03-19 09:24:12 +01007060 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07007061{
7062 // Choose an input profile based on the requested capture parameters: select the first available
7063 // profile supporting all requested parameters.
Andy Hungf129b032015-04-07 13:45:50 -07007064 //
7065 // TODO: perhaps isCompatibleProfile should return a "matching" score so we can return
7066 // the best matching profile, not the first one.
Eric Laurente552edb2014-03-10 17:42:56 -07007067
Glenn Kasten730b9262018-03-29 15:01:26 -07007068 sp<IOProfile> firstInexact;
7069 uint32_t updatedSamplingRate = 0;
7070 audio_format_t updatedFormat = AUDIO_FORMAT_INVALID;
7071 audio_channel_mask_t updatedChannelMask = AUDIO_CHANNEL_INVALID;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08007072 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08007073 for (const auto& profile : hwModule->getInputProfiles()) {
Eric Laurentd4692962014-05-05 18:13:44 -07007074 // profile->log();
Glenn Kasten730b9262018-03-29 15:01:26 -07007075 //updatedFormat = format;
François Gaffie11d30102018-11-02 16:09:09 +01007076 if (profile->isCompatibleProfile(DeviceVector(device), samplingRate,
Glenn Kasten730b9262018-03-29 15:01:26 -07007077 &samplingRate /*updatedSamplingRate*/,
Andy Hungf129b032015-04-07 13:45:50 -07007078 format,
Glenn Kasten730b9262018-03-29 15:01:26 -07007079 &format, /*updatedFormat*/
Andy Hungf129b032015-04-07 13:45:50 -07007080 channelMask,
Glenn Kasten730b9262018-03-29 15:01:26 -07007081 &channelMask /*updatedChannelMask*/,
7082 // FIXME ugly cast
7083 (audio_output_flags_t) flags,
7084 true /*exactMatchRequiredForInputFlags*/)) {
Eric Laurente552edb2014-03-10 17:42:56 -07007085 return profile;
7086 }
François Gaffie11d30102018-11-02 16:09:09 +01007087 if (firstInexact == nullptr && profile->isCompatibleProfile(DeviceVector(device),
Glenn Kasten730b9262018-03-29 15:01:26 -07007088 samplingRate,
7089 &updatedSamplingRate,
7090 format,
7091 &updatedFormat,
7092 channelMask,
7093 &updatedChannelMask,
7094 // FIXME ugly cast
7095 (audio_output_flags_t) flags,
7096 false /*exactMatchRequiredForInputFlags*/)) {
7097 firstInexact = profile;
7098 }
7099
Eric Laurente552edb2014-03-10 17:42:56 -07007100 }
7101 }
Glenn Kasten730b9262018-03-29 15:01:26 -07007102 if (firstInexact != nullptr) {
7103 samplingRate = updatedSamplingRate;
7104 format = updatedFormat;
7105 channelMask = updatedChannelMask;
7106 return firstInexact;
7107 }
Eric Laurente552edb2014-03-10 17:42:56 -07007108 return NULL;
7109}
7110
François Gaffieaaac0fd2018-11-22 17:56:39 +01007111float AudioPolicyManager::computeVolume(IVolumeCurves &curves,
7112 VolumeSource volumeSource,
François Gaffied1ab2bd2015-12-02 18:20:06 +01007113 int index,
jiabin9a3361e2019-10-01 09:38:30 -07007114 const DeviceTypeSet& deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07007115{
jiabin9a3361e2019-10-01 09:38:30 -07007116 float volumeDb = curves.volIndexToDb(Volume::getDeviceCategory(deviceTypes), index);
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07007117
7118 // handle the case of accessibility active while a ringtone is playing: if the ringtone is much
7119 // louder than the accessibility prompt, the prompt cannot be heard, thus masking the touch
7120 // exploration of the dialer UI. In this situation, bring the accessibility volume closer to
7121 // the ringtone volume
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007122 const auto callVolumeSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL, false);
7123 const auto ringVolumeSrc = toVolumeSource(AUDIO_STREAM_RING, false);
7124 const auto musicVolumeSrc = toVolumeSource(AUDIO_STREAM_MUSIC, false);
7125 const auto alarmVolumeSrc = toVolumeSource(AUDIO_STREAM_ALARM, false);
7126 const auto a11yVolumeSrc = toVolumeSource(AUDIO_STREAM_ACCESSIBILITY, false);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007127
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07007128 if (volumeSource == a11yVolumeSrc
François Gaffieaaac0fd2018-11-22 17:56:39 +01007129 && (AUDIO_MODE_RINGTONE == mEngine->getPhoneState()) &&
7130 mOutputs.isActive(ringVolumeSrc, 0)) {
7131 auto &ringCurves = getVolumeCurves(AUDIO_STREAM_RING);
jiabin9a3361e2019-10-01 09:38:30 -07007132 const float ringVolumeDb = computeVolume(ringCurves, ringVolumeSrc, index, deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007133 return ringVolumeDb - 4 > volumeDb ? ringVolumeDb - 4 : volumeDb;
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07007134 }
7135
Eric Laurentdcd4ab12018-06-29 17:45:13 -07007136 // in-call: always cap volume by voice volume + some low headroom
François Gaffieaaac0fd2018-11-22 17:56:39 +01007137 if ((volumeSource != callVolumeSrc && (isInCall() ||
7138 mOutputs.isActiveLocally(callVolumeSrc))) &&
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007139 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM, false) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01007140 volumeSource == ringVolumeSrc || volumeSource == musicVolumeSrc ||
7141 volumeSource == alarmVolumeSrc ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007142 volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION, false) ||
7143 volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false) ||
7144 volumeSource == toVolumeSource(AUDIO_STREAM_DTMF, false) ||
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07007145 volumeSource == a11yVolumeSrc)) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007146 auto &voiceCurves = getVolumeCurves(callVolumeSrc);
jiabin9a3361e2019-10-01 09:38:30 -07007147 int voiceVolumeIndex = voiceCurves.getVolumeIndex(deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007148 const float maxVoiceVolDb =
jiabin9a3361e2019-10-01 09:38:30 -07007149 computeVolume(voiceCurves, callVolumeSrc, voiceVolumeIndex, deviceTypes)
Eric Laurent7731b5a2018-04-06 15:47:22 -07007150 + IN_CALL_EARPIECE_HEADROOM_DB;
Abhijith Shastry329ddab2019-04-23 11:53:26 -07007151 // FIXME: Workaround for call screening applications until a proper audio mode is defined
7152 // to support this scenario : Exempt the RING stream from the audio cap if the audio was
7153 // programmatically muted.
7154 // VOICE_CALL stream has minVolumeIndex > 0 : Users cannot set the volume of voice calls to
7155 // 0. We don't want to cap volume when the system has programmatically muted the voice call
7156 // stream. See setVolumeCurveIndex() for more information.
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07007157 bool exemptFromCapping =
7158 ((volumeSource == ringVolumeSrc) || (volumeSource == a11yVolumeSrc))
7159 && (voiceVolumeIndex == 0);
Abhijith Shastry329ddab2019-04-23 11:53:26 -07007160 ALOGV_IF(exemptFromCapping, "%s volume source %d at vol=%f not capped", __func__,
7161 volumeSource, volumeDb);
7162 if ((volumeDb > maxVoiceVolDb) && !exemptFromCapping) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007163 ALOGV("%s volume source %d at vol=%f overriden by volume group %d at vol=%f", __func__,
7164 volumeSource, volumeDb, callVolumeSrc, maxVoiceVolDb);
7165 volumeDb = maxVoiceVolDb;
Jean-Michel Trivi719a9872017-08-05 13:51:35 -07007166 }
7167 }
Eric Laurente552edb2014-03-10 17:42:56 -07007168 // if a headset is connected, apply the following rules to ring tones and notifications
7169 // to avoid sound level bursts in user's ears:
Eric Laurent6af1c1d2016-04-14 11:20:44 -07007170 // - always attenuate notifications volume by 6dB
7171 // - attenuate ring tones volume by 6dB unless music is not playing and
7172 // speaker is part of the select devices
Eric Laurente552edb2014-03-10 17:42:56 -07007173 // - if music is playing, always limit the volume to current music volume,
7174 // with a minimum threshold at -36dB so that notification is always perceived.
jiabin9a3361e2019-10-01 09:38:30 -07007175 if (!Intersection(deviceTypes,
7176 {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP, AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES,
7177 AUDIO_DEVICE_OUT_WIRED_HEADSET, AUDIO_DEVICE_OUT_WIRED_HEADPHONE,
Eric Laurentc42df452020-08-07 10:51:53 -07007178 AUDIO_DEVICE_OUT_USB_HEADSET, AUDIO_DEVICE_OUT_HEARING_AID,
7179 AUDIO_DEVICE_OUT_BLE_HEADSET}).empty() &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01007180 ((volumeSource == alarmVolumeSrc ||
7181 volumeSource == ringVolumeSrc) ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007182 (volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION, false)) ||
7183 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM, false)) ||
7184 ((volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false)) &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01007185 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) &&
7186 curves.canBeMuted()) {
7187
Eric Laurente552edb2014-03-10 17:42:56 -07007188 // when the phone is ringing we must consider that music could have been paused just before
7189 // by the music application and behave as if music was active if the last music track was
7190 // just stopped
Eric Laurent3b73df72014-03-11 09:06:29 -07007191 if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY) ||
Eric Laurente552edb2014-03-10 17:42:56 -07007192 mLimitRingtoneVolume) {
François Gaffie43c73442018-11-08 08:21:55 +01007193 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
jiabin9a3361e2019-10-01 09:38:30 -07007194 DeviceTypeSet musicDevice =
François Gaffiec005e562018-11-06 15:04:49 +01007195 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
7196 nullptr, true /*fromCache*/).types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01007197 auto &musicCurves = getVolumeCurves(AUDIO_STREAM_MUSIC);
jiabin9a3361e2019-10-01 09:38:30 -07007198 float musicVolDb = computeVolume(musicCurves,
7199 musicVolumeSrc,
7200 musicCurves.getVolumeIndex(musicDevice),
7201 musicDevice);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007202 float minVolDb = (musicVolDb > SONIFICATION_HEADSET_VOLUME_MIN_DB) ?
7203 musicVolDb : SONIFICATION_HEADSET_VOLUME_MIN_DB;
7204 if (volumeDb > minVolDb) {
7205 volumeDb = minVolDb;
7206 ALOGV("computeVolume limiting volume to %f musicVol %f", minVolDb, musicVolDb);
Eric Laurente552edb2014-03-10 17:42:56 -07007207 }
Eric Laurent7b6385c2021-05-12 17:55:36 +02007208 if (Volume::getDeviceForVolume(deviceTypes) != AUDIO_DEVICE_OUT_SPEAKER
7209 && !Intersection(deviceTypes, {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP,
7210 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES}).empty()) {
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07007211 // on A2DP, also ensure notification volume is not too low compared to media when
7212 // intended to be played
François Gaffie43c73442018-11-08 08:21:55 +01007213 if ((volumeDb > -96.0f) &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01007214 (musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB > volumeDb)) {
jiabin9a3361e2019-10-01 09:38:30 -07007215 ALOGV("%s increasing volume for volume source=%d device=%s from %f to %f",
7216 __func__, volumeSource, dumpDeviceTypes(deviceTypes).c_str(), volumeDb,
François Gaffieaaac0fd2018-11-22 17:56:39 +01007217 musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB);
7218 volumeDb = musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB;
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07007219 }
7220 }
jiabin9a3361e2019-10-01 09:38:30 -07007221 } else if ((Volume::getDeviceForVolume(deviceTypes) != AUDIO_DEVICE_OUT_SPEAKER) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01007222 (!(volumeSource == alarmVolumeSrc || volumeSource == ringVolumeSrc))) {
François Gaffie43c73442018-11-08 08:21:55 +01007223 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07007224 }
7225 }
7226
François Gaffie43c73442018-11-08 08:21:55 +01007227 return volumeDb;
Eric Laurente552edb2014-03-10 17:42:56 -07007228}
7229
Eric Laurent3839bc02018-07-10 18:33:34 -07007230int AudioPolicyManager::rescaleVolumeIndex(int srcIndex,
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01007231 VolumeSource fromVolumeSource,
7232 VolumeSource toVolumeSource)
Eric Laurent3839bc02018-07-10 18:33:34 -07007233{
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01007234 if (fromVolumeSource == toVolumeSource) {
Eric Laurent3839bc02018-07-10 18:33:34 -07007235 return srcIndex;
7236 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01007237 auto &srcCurves = getVolumeCurves(fromVolumeSource);
7238 auto &dstCurves = getVolumeCurves(toVolumeSource);
Eric Laurentf5aa58d2019-02-22 18:20:11 -08007239 float minSrc = (float)srcCurves.getVolumeIndexMin();
7240 float maxSrc = (float)srcCurves.getVolumeIndexMax();
7241 float minDst = (float)dstCurves.getVolumeIndexMin();
7242 float maxDst = (float)dstCurves.getVolumeIndexMax();
Eric Laurent3839bc02018-07-10 18:33:34 -07007243
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08007244 // preserve mute request or correct range
7245 if (srcIndex < minSrc) {
7246 if (srcIndex == 0) {
7247 return 0;
7248 }
7249 srcIndex = minSrc;
7250 } else if (srcIndex > maxSrc) {
7251 srcIndex = maxSrc;
7252 }
Eric Laurent3839bc02018-07-10 18:33:34 -07007253 return (int)(minDst + ((srcIndex - minSrc) * (maxDst - minDst)) / (maxSrc - minSrc));
7254}
7255
François Gaffieaaac0fd2018-11-22 17:56:39 +01007256status_t AudioPolicyManager::checkAndSetVolume(IVolumeCurves &curves,
7257 VolumeSource volumeSource,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08007258 int index,
7259 const sp<AudioOutputDescriptor>& outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07007260 DeviceTypeSet deviceTypes,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08007261 int delayMs,
7262 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07007263{
François Gaffieaaac0fd2018-11-22 17:56:39 +01007264 // do not change actual attributes volume if the attributes is muted
7265 if (outputDesc->isMuted(volumeSource)) {
7266 ALOGVV("%s: volume source %d muted count %d active=%d", __func__, volumeSource,
7267 outputDesc->getMuteCount(volumeSource), outputDesc->isActive(volumeSource));
Eric Laurente552edb2014-03-10 17:42:56 -07007268 return NO_ERROR;
7269 }
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007270 VolumeSource callVolSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL, false);
7271 VolumeSource btScoVolSrc = toVolumeSource(AUDIO_STREAM_BLUETOOTH_SCO, false);
7272 bool isVoiceVolSrc = (volumeSource != VOLUME_SOURCE_NONE) && (callVolSrc == volumeSource);
7273 bool isBtScoVolSrc = (volumeSource != VOLUME_SOURCE_NONE) && (btScoVolSrc == volumeSource);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007274
Eric Laurent2517af32020-11-25 15:31:27 +01007275 bool isScoRequested = isScoRequestedForComm();
Eric Laurent1a8b45f2022-04-13 16:01:47 +02007276 bool isHAUsed = isHearingAidUsedForComm();
7277
Eric Laurente552edb2014-03-10 17:42:56 -07007278 // do not change in call volume if bluetooth is connected and vice versa
François Gaffieaaac0fd2018-11-22 17:56:39 +01007279 // if sco and call follow same curves, bypass forceUseForComm
7280 if ((callVolSrc != btScoVolSrc) &&
Eric Laurent2517af32020-11-25 15:31:27 +01007281 ((isVoiceVolSrc && isScoRequested) ||
Eric Laurent1a8b45f2022-04-13 16:01:47 +02007282 (isBtScoVolSrc && !(isScoRequested || isHAUsed)))) {
Eric Laurent2517af32020-11-25 15:31:27 +01007283 ALOGV("%s cannot set volume group %d volume when is%srequested for comm", __func__,
Eric Laurent1a8b45f2022-04-13 16:01:47 +02007284 volumeSource, isScoRequested ? " " : " not ");
Eric Laurent571ef962020-07-24 11:43:48 -07007285 // Do not return an error here as AudioService will always set both voice call
7286 // and bluetooth SCO volumes due to stream aliasing.
7287 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07007288 }
jiabin9a3361e2019-10-01 09:38:30 -07007289 if (deviceTypes.empty()) {
7290 deviceTypes = outputDesc->devices().types();
Eric Laurentc75307b2015-03-17 15:29:32 -07007291 }
Eric Laurent275e8e92014-11-30 15:14:47 -08007292
jiabin9a3361e2019-10-01 09:38:30 -07007293 float volumeDb = computeVolume(curves, volumeSource, index, deviceTypes);
7294 if (outputDesc->isFixedVolume(deviceTypes) ||
Eric Laurent9698a4c2020-10-12 17:10:23 -07007295 // Force VoIP volume to max for bluetooth SCO device except if muted
7296 (index != 0 && (isVoiceVolSrc || isBtScoVolSrc) &&
jiabin9a3361e2019-10-01 09:38:30 -07007297 isSingleDeviceType(deviceTypes, audio_is_bluetooth_out_sco_device))) {
Eric Laurentffbc80f2015-03-18 18:30:19 -07007298 volumeDb = 0.0f;
Eric Laurent275e8e92014-11-30 15:14:47 -08007299 }
Francois Gaffie593634d2021-06-22 13:31:31 +02007300 const bool muted = (index == 0) && (volumeDb != 0.0f);
jiabin9a3361e2019-10-01 09:38:30 -07007301 outputDesc->setVolume(
Francois Gaffie593634d2021-06-22 13:31:31 +02007302 volumeDb, muted, volumeSource, curves.getStreamTypes(), deviceTypes, delayMs, force);
Eric Laurentc75307b2015-03-17 15:29:32 -07007303
Eric Laurente8f2c0f2021-08-17 11:17:19 +02007304 if (outputDesc == mPrimaryOutput && (isVoiceVolSrc || isBtScoVolSrc)) {
Eric Laurente552edb2014-03-10 17:42:56 -07007305 float voiceVolume;
Eric Laurentfad001d2019-06-11 19:17:57 -07007306 // 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 +01007307 if (isVoiceVolSrc) {
7308 voiceVolume = (float)index/(float)curves.getVolumeIndexMax();
Eric Laurente552edb2014-03-10 17:42:56 -07007309 } else {
Eric Laurentfad001d2019-06-11 19:17:57 -07007310 voiceVolume = index == 0 ? 0.0 : 1.0;
Eric Laurente552edb2014-03-10 17:42:56 -07007311 }
Eric Laurent18fba842016-03-31 14:41:26 -07007312 if (voiceVolume != mLastVoiceVolume) {
Eric Laurente552edb2014-03-10 17:42:56 -07007313 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
7314 mLastVoiceVolume = voiceVolume;
7315 }
7316 }
Eric Laurente552edb2014-03-10 17:42:56 -07007317 return NO_ERROR;
7318}
7319
Eric Laurentc75307b2015-03-17 15:29:32 -07007320void AudioPolicyManager::applyStreamVolumes(const sp<AudioOutputDescriptor>& outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07007321 const DeviceTypeSet& deviceTypes,
7322 int delayMs,
7323 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07007324{
jiabincd510522020-01-22 09:40:55 -08007325 ALOGVV("applyStreamVolumes() for device %s", dumpDeviceTypes(deviceTypes).c_str());
François Gaffieaaac0fd2018-11-22 17:56:39 +01007326 for (const auto &volumeGroup : mEngine->getVolumeGroups()) {
7327 auto &curves = getVolumeCurves(toVolumeSource(volumeGroup));
7328 checkAndSetVolume(curves, toVolumeSource(volumeGroup),
jiabin9a3361e2019-10-01 09:38:30 -07007329 curves.getVolumeIndex(deviceTypes),
7330 outputDesc, deviceTypes, delayMs, force);
Eric Laurente552edb2014-03-10 17:42:56 -07007331 }
7332}
7333
François Gaffiec005e562018-11-06 15:04:49 +01007334void AudioPolicyManager::setStrategyMute(product_strategy_t strategy,
7335 bool on,
7336 const sp<AudioOutputDescriptor>& outputDesc,
7337 int delayMs,
jiabin9a3361e2019-10-01 09:38:30 -07007338 DeviceTypeSet deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07007339{
François Gaffieaaac0fd2018-11-22 17:56:39 +01007340 std::vector<VolumeSource> sourcesToMute;
7341 for (auto attributes: mEngine->getAllAttributesForProductStrategy(strategy)) {
7342 ALOGVV("%s() attributes %s, mute %d, output ID %d", __func__,
7343 toString(attributes).c_str(), on, outputDesc->getId());
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007344 VolumeSource source = toVolumeSource(attributes, false);
7345 if ((source != VOLUME_SOURCE_NONE) &&
7346 (std::find(begin(sourcesToMute), end(sourcesToMute), source)
7347 == end(sourcesToMute))) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007348 sourcesToMute.push_back(source);
7349 }
Eric Laurente552edb2014-03-10 17:42:56 -07007350 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01007351 for (auto source : sourcesToMute) {
jiabin9a3361e2019-10-01 09:38:30 -07007352 setVolumeSourceMute(source, on, outputDesc, delayMs, deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007353 }
7354
Eric Laurente552edb2014-03-10 17:42:56 -07007355}
7356
François Gaffieaaac0fd2018-11-22 17:56:39 +01007357void AudioPolicyManager::setVolumeSourceMute(VolumeSource volumeSource,
7358 bool on,
7359 const sp<AudioOutputDescriptor>& outputDesc,
7360 int delayMs,
jiabin9a3361e2019-10-01 09:38:30 -07007361 DeviceTypeSet deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07007362{
jiabin9a3361e2019-10-01 09:38:30 -07007363 if (deviceTypes.empty()) {
7364 deviceTypes = outputDesc->devices().types();
Eric Laurente552edb2014-03-10 17:42:56 -07007365 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01007366 auto &curves = getVolumeCurves(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07007367 if (on) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007368 if (!outputDesc->isMuted(volumeSource)) {
Eric Laurentf5aa58d2019-02-22 18:20:11 -08007369 if (curves.canBeMuted() &&
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007370 (volumeSource != toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01007371 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) ==
7372 AUDIO_POLICY_FORCE_NONE))) {
jiabin9a3361e2019-10-01 09:38:30 -07007373 checkAndSetVolume(curves, volumeSource, 0, outputDesc, deviceTypes, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07007374 }
7375 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01007376 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not
7377 // ignored
7378 outputDesc->incMuteCount(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07007379 } else {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007380 if (!outputDesc->isMuted(volumeSource)) {
7381 ALOGV("%s unmuting non muted attributes!", __func__);
Eric Laurente552edb2014-03-10 17:42:56 -07007382 return;
7383 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01007384 if (outputDesc->decMuteCount(volumeSource) == 0) {
7385 checkAndSetVolume(curves, volumeSource,
jiabin9a3361e2019-10-01 09:38:30 -07007386 curves.getVolumeIndex(deviceTypes),
Eric Laurentc75307b2015-03-17 15:29:32 -07007387 outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07007388 deviceTypes,
Eric Laurente552edb2014-03-10 17:42:56 -07007389 delayMs);
7390 }
7391 }
7392}
7393
François Gaffie53615e22015-03-19 09:24:12 +01007394bool AudioPolicyManager::isValidAttributes(const audio_attributes_t *paa)
7395{
François Gaffiec005e562018-11-06 15:04:49 +01007396 // has flags that map to a stream type?
Eric Laurente83b55d2014-11-14 10:06:21 -08007397 if ((paa->flags & (AUDIO_FLAG_AUDIBILITY_ENFORCED | AUDIO_FLAG_SCO | AUDIO_FLAG_BEACON)) != 0) {
7398 return true;
7399 }
7400
7401 // has known usage?
7402 switch (paa->usage) {
7403 case AUDIO_USAGE_UNKNOWN:
7404 case AUDIO_USAGE_MEDIA:
7405 case AUDIO_USAGE_VOICE_COMMUNICATION:
7406 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
7407 case AUDIO_USAGE_ALARM:
7408 case AUDIO_USAGE_NOTIFICATION:
7409 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
7410 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
7411 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
7412 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
7413 case AUDIO_USAGE_NOTIFICATION_EVENT:
7414 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
7415 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
7416 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
7417 case AUDIO_USAGE_GAME:
Eric Laurent275e8e92014-11-30 15:14:47 -08007418 case AUDIO_USAGE_VIRTUAL_SOURCE:
Jean-Michel Trivi36867762016-12-29 12:03:28 -08007419 case AUDIO_USAGE_ASSISTANT:
Eric Laurent21777f82019-12-06 18:12:06 -08007420 case AUDIO_USAGE_CALL_ASSISTANT:
Hayden Gomes524159d2019-12-23 14:41:47 -08007421 case AUDIO_USAGE_EMERGENCY:
7422 case AUDIO_USAGE_SAFETY:
7423 case AUDIO_USAGE_VEHICLE_STATUS:
7424 case AUDIO_USAGE_ANNOUNCEMENT:
Eric Laurente83b55d2014-11-14 10:06:21 -08007425 break;
7426 default:
7427 return false;
7428 }
7429 return true;
7430}
7431
François Gaffie2110e042015-03-24 08:41:51 +01007432audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
7433{
7434 return mEngine->getForceUse(usage);
7435}
7436
7437bool AudioPolicyManager::isInCall()
7438{
7439 return isStateInCall(mEngine->getPhoneState());
7440}
7441
7442bool AudioPolicyManager::isStateInCall(int state)
7443{
7444 return is_state_in_call(state);
7445}
7446
Eric Laurent74b71512019-11-06 17:21:57 -08007447bool AudioPolicyManager::isCallAudioAccessible()
7448{
7449 audio_mode_t mode = mEngine->getPhoneState();
7450 return (mode == AUDIO_MODE_IN_CALL)
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01007451 || (mode == AUDIO_MODE_CALL_SCREEN)
7452 || (mode == AUDIO_MODE_CALL_REDIRECT);
Eric Laurent74b71512019-11-06 17:21:57 -08007453}
7454
Eric Laurentd60560a2015-04-10 11:31:20 -07007455void AudioPolicyManager::cleanUpForDevice(const sp<DeviceDescriptor>& deviceDesc)
7456{
7457 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07007458 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02007459 if (sourceDesc->isConnected() && (sourceDesc->srcDevice()->equals(deviceDesc) ||
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02007460 sourceDesc->sinkDevice()->equals(deviceDesc))
7461 && !isCallRxAudioSource(sourceDesc)) {
Francois Gaffiea0e5c992020-09-29 16:05:07 +02007462 disconnectAudioSource(sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07007463 }
7464 }
7465
7466 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
7467 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
7468 bool release = false;
7469 for (size_t j = 0; j < patchDesc->mPatch.num_sources && !release; j++) {
7470 const struct audio_port_config *source = &patchDesc->mPatch.sources[j];
7471 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
7472 source->ext.device.type == deviceDesc->type()) {
7473 release = true;
7474 }
7475 }
Francois Gaffiea0e5c992020-09-29 16:05:07 +02007476 const char *address = deviceDesc->address().c_str();
Eric Laurentd60560a2015-04-10 11:31:20 -07007477 for (size_t j = 0; j < patchDesc->mPatch.num_sinks && !release; j++) {
7478 const struct audio_port_config *sink = &patchDesc->mPatch.sinks[j];
7479 if (sink->type == AUDIO_PORT_TYPE_DEVICE &&
Francois Gaffiea0e5c992020-09-29 16:05:07 +02007480 sink->ext.device.type == deviceDesc->type() &&
7481 (strnlen(address, AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0
7482 || strncmp(sink->ext.device.address, address,
7483 AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0)) {
Eric Laurentd60560a2015-04-10 11:31:20 -07007484 release = true;
7485 }
7486 }
7487 if (release) {
François Gaffieafd4cea2019-11-18 15:50:22 +01007488 ALOGV("%s releasing patch %u", __FUNCTION__, patchDesc->getHandle());
7489 releaseAudioPatch(patchDesc->getHandle(), patchDesc->getUid());
Eric Laurentd60560a2015-04-10 11:31:20 -07007490 }
7491 }
Francois Gaffie716e1432019-01-14 16:58:59 +01007492
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01007493 mInputs.clearSessionRoutesForDevice(deviceDesc);
7494
Francois Gaffie716e1432019-01-14 16:58:59 +01007495 mHwModules.cleanUpForDevice(deviceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07007496}
7497
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007498void AudioPolicyManager::modifySurroundFormats(
7499 const sp<DeviceDescriptor>& devDesc, FormatVector *formatsPtr) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007500 std::unordered_set<audio_format_t> enforcedSurround(
7501 devDesc->encodedFormats().begin(), devDesc->encodedFormats().end());
Mikhail Naganov100f0122018-11-29 11:22:16 -08007502 std::unordered_set<audio_format_t> allSurround; // A flat set of all known surround formats
7503 for (const auto& pair : mConfig.getSurroundFormats()) {
7504 allSurround.insert(pair.first);
7505 for (const auto& subformat : pair.second) allSurround.insert(subformat);
7506 }
Phil Burk09bc4612016-02-24 15:58:15 -08007507
7508 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
7509 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Phil Burk0709b0a2016-03-31 12:54:57 -07007510 ALOGD("%s: forced use = %d", __FUNCTION__, forceUse);
Mikhail Naganov100f0122018-11-29 11:22:16 -08007511 // This is the resulting set of formats depending on the surround mode:
7512 // 'all surround' = allSurround
7513 // 'enforced surround' = enforcedSurround [may include IEC69137 which isn't raw surround fmt]
7514 // 'non-surround' = not in 'all surround' and not in 'enforced surround'
7515 // 'manual surround' = mManualSurroundFormats
7516 // AUTO: formats v 'enforced surround'
7517 // ALWAYS: formats v 'all surround' v 'enforced surround'
7518 // NEVER: formats ^ 'non-surround'
7519 // MANUAL: formats ^ ('non-surround' v 'manual surround' v (IEC69137 ^ 'enforced surround'))
Phil Burk09bc4612016-02-24 15:58:15 -08007520
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007521 std::unordered_set<audio_format_t> formatSet;
7522 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL
7523 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08007524 // formatSet is (formats ^ 'non-surround')
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007525 for (auto formatIter = formatsPtr->begin(); formatIter != formatsPtr->end(); ++formatIter) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08007526 if (allSurround.count(*formatIter) == 0 && enforcedSurround.count(*formatIter) == 0) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007527 formatSet.insert(*formatIter);
7528 }
7529 }
7530 } else {
7531 formatSet.insert(formatsPtr->begin(), formatsPtr->end());
7532 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08007533 formatsPtr->clear(); // Re-filled from the formatSet at the end.
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007534
jiabin81772902018-04-02 17:52:27 -07007535 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08007536 formatSet.insert(mManualSurroundFormats.begin(), mManualSurroundFormats.end());
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007537 // Enable IEC61937 when in MANUAL mode if it's enforced for this device.
7538 if (enforcedSurround.count(AUDIO_FORMAT_IEC61937) != 0) {
7539 formatSet.insert(AUDIO_FORMAT_IEC61937);
Phil Burk09bc4612016-02-24 15:58:15 -08007540 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08007541 } else if (forceUse != AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) { // AUTO or ALWAYS
7542 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS) {
7543 formatSet.insert(allSurround.begin(), allSurround.end());
Phil Burk07ac1142016-03-25 13:39:29 -07007544 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08007545 formatSet.insert(enforcedSurround.begin(), enforcedSurround.end());
Phil Burk09bc4612016-02-24 15:58:15 -08007546 }
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007547 for (const auto& format : formatSet) {
jiabin06e4bab2019-07-29 10:13:34 -07007548 formatsPtr->push_back(format);
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007549 }
Phil Burk0709b0a2016-03-31 12:54:57 -07007550}
7551
jiabin06e4bab2019-07-29 10:13:34 -07007552void AudioPolicyManager::modifySurroundChannelMasks(ChannelMaskSet *channelMasksPtr) {
7553 ChannelMaskSet &channelMasks = *channelMasksPtr;
Phil Burk0709b0a2016-03-31 12:54:57 -07007554 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
7555 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
7556
7557 // If NEVER, then remove support for channelMasks > stereo.
7558 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
jiabin06e4bab2019-07-29 10:13:34 -07007559 for (auto it = channelMasks.begin(); it != channelMasks.end();) {
7560 audio_channel_mask_t channelMask = *it;
Phil Burk0709b0a2016-03-31 12:54:57 -07007561 if (channelMask & ~AUDIO_CHANNEL_OUT_STEREO) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01007562 ALOGV("%s: force NEVER, so remove channelMask 0x%08x", __FUNCTION__, channelMask);
jiabin06e4bab2019-07-29 10:13:34 -07007563 it = channelMasks.erase(it);
Phil Burk0709b0a2016-03-31 12:54:57 -07007564 } else {
jiabin06e4bab2019-07-29 10:13:34 -07007565 ++it;
Phil Burk0709b0a2016-03-31 12:54:57 -07007566 }
7567 }
jiabin81772902018-04-02 17:52:27 -07007568 // If ALWAYS or MANUAL, then make sure we at least support 5.1
7569 } else if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS
7570 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Phil Burk0709b0a2016-03-31 12:54:57 -07007571 bool supports5dot1 = false;
7572 // Are there any channel masks that can be considered "surround"?
Mikhail Naganovcf84e592017-12-07 11:25:11 -08007573 for (audio_channel_mask_t channelMask : channelMasks) {
Phil Burk0709b0a2016-03-31 12:54:57 -07007574 if ((channelMask & AUDIO_CHANNEL_OUT_5POINT1) == AUDIO_CHANNEL_OUT_5POINT1) {
7575 supports5dot1 = true;
7576 break;
7577 }
7578 }
7579 // If not then add 5.1 support.
7580 if (!supports5dot1) {
jiabin06e4bab2019-07-29 10:13:34 -07007581 channelMasks.insert(AUDIO_CHANNEL_OUT_5POINT1);
Eric Laurentfecbceb2021-02-09 14:46:43 +01007582 ALOGV("%s: force MANUAL or ALWAYS, so adding channelMask for 5.1 surround", __func__);
Phil Burk0709b0a2016-03-31 12:54:57 -07007583 }
Phil Burk09bc4612016-02-24 15:58:15 -08007584 }
7585}
7586
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007587void AudioPolicyManager::updateAudioProfiles(const sp<DeviceDescriptor>& devDesc,
Phil Burk00eeb322016-03-31 12:41:00 -07007588 audio_io_handle_t ioHandle,
François Gaffie112b0af2015-11-19 16:13:25 +01007589 AudioProfileVector &profiles)
7590{
7591 String8 reply;
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007592 audio_devices_t device = devDesc->type();
Phil Burk0709b0a2016-03-31 12:54:57 -07007593
François Gaffie112b0af2015-11-19 16:13:25 +01007594 // Format MUST be checked first to update the list of AudioProfile
7595 if (profiles.hasDynamicFormat()) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07007596 reply = mpClientInterface->getParameters(
7597 ioHandle, String8(AudioParameter::keyStreamSupportedFormats));
jiabin81772902018-04-02 17:52:27 -07007598 ALOGV("%s: supported formats %d, %s", __FUNCTION__, ioHandle, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08007599 AudioParameter repliedParameters(reply);
7600 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07007601 String8(AudioParameter::keyStreamSupportedFormats), reply) != NO_ERROR) {
François Gaffie112b0af2015-11-19 16:13:25 +01007602 ALOGE("%s: failed to retrieve format, bailing out", __FUNCTION__);
7603 return;
7604 }
Phil Burk09bc4612016-02-24 15:58:15 -08007605 FormatVector formats = formatsFromString(reply.string());
Kriti Dangef6be8f2020-11-05 11:58:19 +01007606 mReportedFormatsMap[devDesc] = formats;
Mikhail Naganov100f0122018-11-29 11:22:16 -08007607 if (device == AUDIO_DEVICE_OUT_HDMI
7608 || isDeviceOfModule(devDesc, AUDIO_HARDWARE_MODULE_ID_MSD)) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007609 modifySurroundFormats(devDesc, &formats);
Phil Burk00eeb322016-03-31 12:41:00 -07007610 }
jiabin3e277cc2019-09-10 14:27:34 -07007611 addProfilesForFormats(profiles, formats);
François Gaffie112b0af2015-11-19 16:13:25 +01007612 }
François Gaffie112b0af2015-11-19 16:13:25 +01007613
Mikhail Naganovcf84e592017-12-07 11:25:11 -08007614 for (audio_format_t format : profiles.getSupportedFormats()) {
jiabin06e4bab2019-07-29 10:13:34 -07007615 ChannelMaskSet channelMasks;
7616 SampleRateSet samplingRates;
François Gaffie112b0af2015-11-19 16:13:25 +01007617 AudioParameter requestedParameters;
Mikhail Naganov388360c2016-10-17 17:09:41 -07007618 requestedParameters.addInt(String8(AudioParameter::keyFormat), format);
François Gaffie112b0af2015-11-19 16:13:25 +01007619
7620 if (profiles.hasDynamicRateFor(format)) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07007621 reply = mpClientInterface->getParameters(
7622 ioHandle,
7623 requestedParameters.toString() + ";" +
7624 AudioParameter::keyStreamSupportedSamplingRates);
François Gaffie112b0af2015-11-19 16:13:25 +01007625 ALOGV("%s: supported sampling rates %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08007626 AudioParameter repliedParameters(reply);
7627 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07007628 String8(AudioParameter::keyStreamSupportedSamplingRates), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08007629 samplingRates = samplingRatesFromString(reply.string());
François Gaffie112b0af2015-11-19 16:13:25 +01007630 }
7631 }
7632 if (profiles.hasDynamicChannelsFor(format)) {
7633 reply = mpClientInterface->getParameters(ioHandle,
7634 requestedParameters.toString() + ";" +
Mikhail Naganov388360c2016-10-17 17:09:41 -07007635 AudioParameter::keyStreamSupportedChannels);
François Gaffie112b0af2015-11-19 16:13:25 +01007636 ALOGV("%s: supported channel masks %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08007637 AudioParameter repliedParameters(reply);
7638 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07007639 String8(AudioParameter::keyStreamSupportedChannels), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08007640 channelMasks = channelMasksFromString(reply.string());
Mikhail Naganov100f0122018-11-29 11:22:16 -08007641 if (device == AUDIO_DEVICE_OUT_HDMI
7642 || isDeviceOfModule(devDesc, AUDIO_HARDWARE_MODULE_ID_MSD)) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007643 modifySurroundChannelMasks(&channelMasks);
Phil Burk0709b0a2016-03-31 12:54:57 -07007644 }
François Gaffie112b0af2015-11-19 16:13:25 +01007645 }
7646 }
jiabin3e277cc2019-09-10 14:27:34 -07007647 addDynamicAudioProfileAndSort(
7648 profiles, new AudioProfile(format, channelMasks, samplingRates));
François Gaffie112b0af2015-11-19 16:13:25 +01007649 }
7650}
Eric Laurentd60560a2015-04-10 11:31:20 -07007651
Mikhail Naganovdc769682018-05-04 15:34:08 -07007652status_t AudioPolicyManager::installPatch(const char *caller,
7653 audio_patch_handle_t *patchHandle,
7654 AudioIODescriptorInterface *ioDescriptor,
7655 const struct audio_patch *patch,
7656 int delayMs)
7657{
7658 ssize_t index = mAudioPatches.indexOfKey(
7659 patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE ?
7660 *patchHandle : ioDescriptor->getPatchHandle());
7661 sp<AudioPatch> patchDesc;
7662 status_t status = installPatch(
7663 caller, index, patchHandle, patch, delayMs, mUidCached, &patchDesc);
7664 if (status == NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01007665 ioDescriptor->setPatchHandle(patchDesc->getHandle());
Mikhail Naganovdc769682018-05-04 15:34:08 -07007666 }
7667 return status;
7668}
7669
7670status_t AudioPolicyManager::installPatch(const char *caller,
7671 ssize_t index,
7672 audio_patch_handle_t *patchHandle,
7673 const struct audio_patch *patch,
7674 int delayMs,
7675 uid_t uid,
7676 sp<AudioPatch> *patchDescPtr)
7677{
7678 sp<AudioPatch> patchDesc;
7679 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
7680 if (index >= 0) {
7681 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007682 afPatchHandle = patchDesc->getAfHandle();
Mikhail Naganovdc769682018-05-04 15:34:08 -07007683 }
7684
7685 status_t status = mpClientInterface->createAudioPatch(patch, &afPatchHandle, delayMs);
7686 ALOGV("%s() AF::createAudioPatch returned %d patchHandle %d num_sources %d num_sinks %d",
7687 caller, status, afPatchHandle, patch->num_sources, patch->num_sinks);
7688 if (status == NO_ERROR) {
7689 if (index < 0) {
7690 patchDesc = new AudioPatch(patch, uid);
François Gaffieafd4cea2019-11-18 15:50:22 +01007691 addAudioPatch(patchDesc->getHandle(), patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07007692 } else {
7693 patchDesc->mPatch = *patch;
7694 }
François Gaffieafd4cea2019-11-18 15:50:22 +01007695 patchDesc->setAfHandle(afPatchHandle);
Mikhail Naganovdc769682018-05-04 15:34:08 -07007696 if (patchHandle) {
François Gaffieafd4cea2019-11-18 15:50:22 +01007697 *patchHandle = patchDesc->getHandle();
Mikhail Naganovdc769682018-05-04 15:34:08 -07007698 }
7699 nextAudioPortGeneration();
7700 mpClientInterface->onAudioPatchListUpdate();
7701 }
7702 if (patchDescPtr) *patchDescPtr = patchDesc;
7703 return status;
7704}
7705
jiabinbce0c1d2020-10-05 11:20:18 -07007706bool AudioPolicyManager::areAllActiveTracksRerouted(const sp<SwAudioOutputDescriptor>& output)
7707{
7708 const TrackClientVector activeClients = output->getActiveClients();
7709 if (activeClients.empty()) {
7710 return true;
7711 }
7712 ssize_t index = mAudioPatches.indexOfKey(output->getPatchHandle());
7713 if (index < 0) {
7714 ALOGE("%s, no audio patch found while there are active clients on output %d",
7715 __func__, output->getId());
7716 return false;
7717 }
7718 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
7719 DeviceVector routedDevices;
7720 for (int i = 0; i < patchDesc->mPatch.num_sinks; ++i) {
7721 sp<DeviceDescriptor> device = mAvailableOutputDevices.getDeviceFromId(
7722 patchDesc->mPatch.sinks[i].id);
7723 if (device == nullptr) {
7724 ALOGE("%s, no audio device found with id(%d)",
7725 __func__, patchDesc->mPatch.sinks[i].id);
7726 return false;
7727 }
7728 routedDevices.add(device);
7729 }
7730 for (const auto& client : activeClients) {
jiabin49256852022-03-09 11:21:35 -08007731 if (client->isInvalid()) {
7732 // No need to take care about invalidated clients.
7733 continue;
7734 }
jiabinbce0c1d2020-10-05 11:20:18 -07007735 sp<DeviceDescriptor> preferredDevice =
7736 mAvailableOutputDevices.getDeviceFromId(client->preferredDeviceId());
7737 if (mEngine->getOutputDevicesForAttributes(
7738 client->attributes(), preferredDevice, false) == routedDevices) {
7739 return false;
7740 }
7741 }
7742 return true;
7743}
7744
7745sp<SwAudioOutputDescriptor> AudioPolicyManager::openOutputWithProfileAndDevice(
Eric Laurentb4f42a92022-01-17 17:37:31 +01007746 const sp<IOProfile>& profile, const DeviceVector& devices,
7747 const audio_config_base_t *mixerConfig)
jiabinbce0c1d2020-10-05 11:20:18 -07007748{
7749 for (const auto& device : devices) {
7750 // TODO: This should be checking if the profile supports the device combo.
7751 if (!profile->supportsDevice(device)) {
7752 return nullptr;
7753 }
7754 }
7755 sp<SwAudioOutputDescriptor> desc = new SwAudioOutputDescriptor(profile, mpClientInterface);
7756 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentb4f42a92022-01-17 17:37:31 +01007757 status_t status = desc->open(nullptr /* halConfig */, mixerConfig, devices,
jiabinbce0c1d2020-10-05 11:20:18 -07007758 AUDIO_STREAM_DEFAULT, AUDIO_OUTPUT_FLAG_NONE, &output);
7759 if (status != NO_ERROR) {
7760 return nullptr;
7761 }
7762
7763 // Here is where the out_set_parameters() for card & device gets called
7764 sp<DeviceDescriptor> device = devices.getDeviceForOpening();
7765 const audio_devices_t deviceType = device->type();
7766 const String8 &address = String8(device->address().c_str());
7767 if (!address.isEmpty()) {
7768 char *param = audio_device_address_to_parameter(deviceType, address.c_str());
7769 mpClientInterface->setParameters(output, String8(param));
7770 free(param);
7771 }
7772 updateAudioProfiles(device, output, profile->getAudioProfiles());
7773 if (!profile->hasValidAudioProfile()) {
7774 ALOGW("%s() missing param", __func__);
7775 desc->close();
7776 return nullptr;
7777 } else if (profile->hasDynamicAudioProfile()) {
7778 desc->close();
7779 output = AUDIO_IO_HANDLE_NONE;
7780 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
7781 profile->pickAudioProfile(
7782 config.sample_rate, config.channel_mask, config.format);
7783 config.offload_info.sample_rate = config.sample_rate;
7784 config.offload_info.channel_mask = config.channel_mask;
7785 config.offload_info.format = config.format;
7786
Eric Laurentb4f42a92022-01-17 17:37:31 +01007787 status = desc->open(&config, mixerConfig, devices,
jiabinbce0c1d2020-10-05 11:20:18 -07007788 AUDIO_STREAM_DEFAULT, AUDIO_OUTPUT_FLAG_NONE, &output);
7789 if (status != NO_ERROR) {
7790 return nullptr;
7791 }
7792 }
7793
7794 addOutput(output, desc);
Eric Laurentb4f42a92022-01-17 17:37:31 +01007795
jiabinbce0c1d2020-10-05 11:20:18 -07007796 if (audio_is_remote_submix_device(deviceType) && address != "0") {
7797 sp<AudioPolicyMix> policyMix;
7798 if (mPolicyMixes.getAudioPolicyMix(deviceType, address, policyMix) == NO_ERROR) {
7799 policyMix->setOutput(desc);
7800 desc->mPolicyMix = policyMix;
7801 } else {
7802 ALOGW("checkOutputsForDevice() cannot find policy for address %s",
7803 address.string());
7804 }
7805
Eric Laurentb4f42a92022-01-17 17:37:31 +01007806 } else if (hasPrimaryOutput() && profile->getModule()
7807 != mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_PRIMARY)
7808 && ((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0)) {
7809 // no duplicated output for:
7810 // - direct outputs
7811 // - outputs used by dynamic policy mixes
7812 // - outputs opened on the primary HW module
jiabinbce0c1d2020-10-05 11:20:18 -07007813 audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE;
7814
7815 //TODO: configure audio effect output stage here
7816
7817 // open a duplicating output thread for the new output and the primary output
7818 sp<SwAudioOutputDescriptor> dupOutputDesc =
7819 new SwAudioOutputDescriptor(nullptr, mpClientInterface);
7820 status = dupOutputDesc->openDuplicating(mPrimaryOutput, desc, &duplicatedOutput);
7821 if (status == NO_ERROR) {
7822 // add duplicated output descriptor
7823 addOutput(duplicatedOutput, dupOutputDesc);
7824 } else {
7825 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
7826 mPrimaryOutput->mIoHandle, output);
7827 desc->close();
7828 removeOutput(output);
7829 nextAudioPortGeneration();
7830 return nullptr;
7831 }
7832 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02007833 if (mPrimaryOutput == nullptr && profile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
7834 ALOGV("%s(): re-assigning mPrimaryOutput", __func__);
7835 mPrimaryOutput = desc;
7836 }
jiabinbce0c1d2020-10-05 11:20:18 -07007837 return desc;
7838}
7839
Mikhail Naganov1b2a7942017-12-08 10:18:09 -08007840} // namespace android