blob: 199a1d59ab2f0753a0c1b718e7b2293108fb4bf6 [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) {
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100143 if (port.ext.getTag() != AudioPortExt::device) {
144 return BAD_VALUE;
145 }
146 audio_devices_t device_type;
147 std::string device_address;
148 if (status_t status = aidl2legacy_AudioDevice_audio_device(
149 port.ext.get<AudioPortExt::device>().device, &device_type, &device_address);
150 status != OK) {
151 return status;
152 };
153 const char* device_name = port.name.c_str();
154 // connect/disconnect only 1 device at a time
155 if (!audio_is_output_device(device_type) && !audio_is_input_device(device_type))
156 return BAD_VALUE;
157
158 sp<DeviceDescriptor> device = mHwModules.getDeviceDescriptor(
159 device_type, device_address.c_str(), device_name, encodedFormat,
160 state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
Mikhail Naganovddc5f312022-06-11 00:47:52 +0000161 if (device == nullptr) {
162 return INVALID_OPERATION;
163 }
164 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
165 device->setExtraAudioDescriptors(port.extraAudioDescriptors);
166 }
167 return setDeviceConnectionStateInt(device, state);
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100168}
169
François Gaffie11d30102018-11-02 16:09:09 +0100170status_t AudioPolicyManager::setDeviceConnectionStateInt(audio_devices_t deviceType,
Eric Laurenta1d525f2015-01-29 13:36:45 -0800171 audio_policy_dev_state_t state,
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100172 const char* device_address,
173 const char* device_name,
174 audio_format_t encodedFormat) {
175 media::AudioPort aidlPort;
176 if (status_t status = deviceToAudioPort(deviceType, device_address, device_name, &aidlPort);
177 status == OK) {
178 return setDeviceConnectionStateInt(state, aidlPort.hal, encodedFormat);
179 } else {
180 ALOGE("Failed to convert to AudioPort Parcelable: %s", statusToString(status).c_str());
181 return status;
182 }
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700183}
Paul McLeane743a472015-01-28 11:07:31 -0800184
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700185status_t AudioPolicyManager::setDeviceConnectionStateInt(const sp<DeviceDescriptor> &device,
186 audio_policy_dev_state_t state)
187{
Eric Laurente552edb2014-03-10 17:42:56 -0700188 // handle output devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700189 if (audio_is_output_device(device->type())) {
Eric Laurentd4692962014-05-05 18:13:44 -0700190 SortedVector <audio_io_handle_t> outputs;
191
François Gaffie11d30102018-11-02 16:09:09 +0100192 ssize_t index = mAvailableOutputDevices.indexOf(device);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700193
Eric Laurente552edb2014-03-10 17:42:56 -0700194 // save a copy of the opened output descriptors before any output is opened or closed
195 // by checkOutputsForDevice(). This will be needed by checkOutputForAllStrategies()
196 mPreviousOutputs = mOutputs;
Eric Laurent96d1dda2022-03-14 17:14:19 +0100197
198 bool wasLeUnicastActive = isLeUnicastActive();
199
Eric Laurente552edb2014-03-10 17:42:56 -0700200 switch (state)
201 {
202 // handle output device connection
Eric Laurent3ae5f312015-02-03 17:12:08 -0800203 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700204 if (index >= 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100205 ALOGW("%s() device already connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700206 return INVALID_OPERATION;
207 }
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800208 ALOGV("%s() connecting device %s format %x",
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700209 __func__, device->toString().c_str(), device->getEncodedFormat());
Eric Laurente552edb2014-03-10 17:42:56 -0700210
Eric Laurente552edb2014-03-10 17:42:56 -0700211 // register new device as available
Francois Gaffie993f3902019-04-10 15:39:27 +0200212 if (mAvailableOutputDevices.add(device) < 0) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700213 return NO_MEMORY;
Eric Laurente552edb2014-03-10 17:42:56 -0700214 }
215
François Gaffie44481e72016-04-20 07:49:57 +0200216 // Before checking outputs, broadcast connect event to allow HAL to retrieve dynamic
217 // parameters on newly connected devices (instead of opening the outputs...)
François Gaffie11d30102018-11-02 16:09:09 +0100218 broadcastDeviceConnectionState(device, state);
François Gaffie44481e72016-04-20 07:49:57 +0200219
François Gaffie11d30102018-11-02 16:09:09 +0100220 if (checkOutputsForDevice(device, state, outputs) != NO_ERROR) {
221 mAvailableOutputDevices.remove(device);
François Gaffie44481e72016-04-20 07:49:57 +0200222
Francois Gaffie716e1432019-01-14 16:58:59 +0100223 mHwModules.cleanUpForDevice(device);
224
François Gaffie11d30102018-11-02 16:09:09 +0100225 broadcastDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700226 return INVALID_OPERATION;
227 }
François Gaffie2110e042015-03-24 08:41:51 +0100228
jiabin1c4794b2020-05-05 10:08:05 -0700229 // Populate encapsulation information when a output device is connected.
230 device->setEncapsulationInfoFromHal(mpClientInterface);
231
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700232 // outputs should never be empty here
233 ALOG_ASSERT(outputs.size() != 0, "setDeviceConnectionState():"
234 "checkOutputsForDevice() returned no outputs but status OK");
François Gaffie11d30102018-11-02 16:09:09 +0100235 ALOGV("%s() checkOutputsForDevice() returned %zu outputs", __func__, outputs.size());
Eric Laurent3ae5f312015-02-03 17:12:08 -0800236
Eric Laurent3ae5f312015-02-03 17:12:08 -0800237 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700238 // handle output device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700239 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700240 if (index < 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100241 ALOGW("%s() device not connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700242 return INVALID_OPERATION;
243 }
244
François Gaffie11d30102018-11-02 16:09:09 +0100245 ALOGV("%s() disconnecting output device %s", __func__, device->toString().c_str());
Paul McLean5c477aa2014-08-20 16:47:57 -0700246
Paul McLeane743a472015-01-28 11:07:31 -0800247 // Send Disconnect to HALs
François Gaffie11d30102018-11-02 16:09:09 +0100248 broadcastDeviceConnectionState(device, state);
Paul McLean5c477aa2014-08-20 16:47:57 -0700249
Eric Laurente552edb2014-03-10 17:42:56 -0700250 // remove device from available output devices
François Gaffie11d30102018-11-02 16:09:09 +0100251 mAvailableOutputDevices.remove(device);
Eric Laurente552edb2014-03-10 17:42:56 -0700252
Francois Gaffieba2cf0f2018-12-12 16:40:25 +0100253 mOutputs.clearSessionRoutesForDevice(device);
254
François Gaffie11d30102018-11-02 16:09:09 +0100255 checkOutputsForDevice(device, state, outputs);
François Gaffie2110e042015-03-24 08:41:51 +0100256
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800257 // Reset active device codec
258 device->setEncodedFormat(AUDIO_FORMAT_DEFAULT);
259
Kriti Dangef6be8f2020-11-05 11:58:19 +0100260 // remove device from mReportedFormatsMap cache
261 mReportedFormatsMap.erase(device);
262
Eric Laurente552edb2014-03-10 17:42:56 -0700263 } break;
264
265 default:
François Gaffie11d30102018-11-02 16:09:09 +0100266 ALOGE("%s() invalid state: %x", __func__, state);
Eric Laurente552edb2014-03-10 17:42:56 -0700267 return BAD_VALUE;
268 }
269
Eric Laurent736a1022019-03-27 18:28:46 -0700270 // Propagate device availability to Engine
271 setEngineDeviceConnectionState(device, state);
272
Eric Laurentae970022019-01-29 14:25:04 -0800273 // No need to evaluate playback routing when connecting a remote submix
274 // output device used by a dynamic policy of type recorder as no
275 // playback use case is affected.
276 bool doCheckForDeviceAndOutputChanges = true;
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700277 if (device->type() == AUDIO_DEVICE_OUT_REMOTE_SUBMIX && device->address() != "0") {
Eric Laurentae970022019-01-29 14:25:04 -0800278 for (audio_io_handle_t output : outputs) {
279 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
Mikhail Naganovbfac5832019-03-05 16:55:28 -0800280 sp<AudioPolicyMix> policyMix = desc->mPolicyMix.promote();
281 if (policyMix != nullptr
282 && policyMix->mMixType == MIX_TYPE_RECORDERS
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700283 && device->address() == policyMix->mDeviceAddress.string()) {
Eric Laurentae970022019-01-29 14:25:04 -0800284 doCheckForDeviceAndOutputChanges = false;
285 break;
286 }
287 }
288 }
289
290 auto checkCloseOutputs = [&]() {
Mikhail Naganov37977152018-07-11 15:54:44 -0700291 // outputs must be closed after checkOutputForAllStrategies() is executed
292 if (!outputs.isEmpty()) {
293 for (audio_io_handle_t output : outputs) {
294 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
François Gaffie11d30102018-11-02 16:09:09 +0100295 // close unused outputs after device disconnection or direct outputs that have
296 // been opened by checkOutputsForDevice() to query dynamic parameters
Eric Laurente191d1b2022-04-15 11:59:25 +0200297 // "outputs" vector never contains duplicated outputs
Eric Laurentcad6c0d2021-07-13 15:12:39 +0200298 if ((state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE)
299 || (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != 0) &&
Eric Laurente191d1b2022-04-15 11:59:25 +0200300 (desc->mDirectOpenCount == 0))
301 || (((desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0) &&
302 !isOutputOnlyAvailableRouteToSomeDevice(desc))) {
Francois Gaffieff1eb522020-05-06 18:37:04 +0200303 clearAudioSourcesForOutput(output);
Mikhail Naganov37977152018-07-11 15:54:44 -0700304 closeOutput(output);
305 }
Eric Laurente552edb2014-03-10 17:42:56 -0700306 }
Mikhail Naganov37977152018-07-11 15:54:44 -0700307 // check A2DP again after closing A2DP output to reset mA2dpSuspended if needed
308 return true;
Eric Laurente552edb2014-03-10 17:42:56 -0700309 }
Mikhail Naganov37977152018-07-11 15:54:44 -0700310 return false;
Eric Laurentae970022019-01-29 14:25:04 -0800311 };
312
313 if (doCheckForDeviceAndOutputChanges) {
314 checkForDeviceAndOutputChanges(checkCloseOutputs);
315 } else {
316 checkCloseOutputs();
317 }
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100318 (void)updateCallRouting(false /*fromCache*/);
jiabinbce0c1d2020-10-05 11:20:18 -0700319 std::vector<audio_io_handle_t> outputsToReopen;
François Gaffie11d30102018-11-02 16:09:09 +0100320 const DeviceVector msdOutDevices = getMsdAudioOutDevices();
jiabinbce0c1d2020-10-05 11:20:18 -0700321 const DeviceVector activeMediaDevices =
322 mEngine->getActiveMediaDevices(mAvailableOutputDevices);
Eric Laurente552edb2014-03-10 17:42:56 -0700323 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700324 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Jaideep Sharma89b5b852020-11-23 16:41:33 +0530325 if (desc->isActive() && ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) ||
326 (desc != mPrimaryOutput))) {
François Gaffie11d30102018-11-02 16:09:09 +0100327 DeviceVector newDevices = getNewOutputDevices(desc, true /*fromCache*/);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700328 // do not force device change on duplicated output because if device is 0, it will
329 // also force a device 0 for the two outputs it is duplicated to which may override
330 // a valid device selection on those outputs.
François Gaffie11d30102018-11-02 16:09:09 +0100331 bool force = (msdOutDevices.isEmpty() || msdOutDevices != desc->devices())
Mikhail Naganov15be9d22017-11-08 14:18:13 +1100332 && !desc->isDuplicated()
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700333 && (!device_distinguishes_on_address(device->type())
Eric Laurentc2730ba2014-07-20 15:47:07 -0700334 // always force when disconnecting (a non-duplicated device)
335 || (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE));
François Gaffie11d30102018-11-02 16:09:09 +0100336 setOutputDevices(desc, newDevices, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700337 }
jiabinbce0c1d2020-10-05 11:20:18 -0700338 if (!desc->isDuplicated() && desc->mProfile->hasDynamicAudioProfile() &&
jiabin498d2152021-04-02 00:26:46 +0000339 !activeMediaDevices.empty() && desc->devices() != activeMediaDevices &&
jiabinbce0c1d2020-10-05 11:20:18 -0700340 desc->supportsDevicesForPlayback(activeMediaDevices)) {
341 // Reopen the output to query the dynamic profiles when there is not active
342 // clients or all active clients will be rerouted. Otherwise, set the flag
343 // `mPendingReopenToQueryProfiles` in the SwOutputDescriptor so that the output
344 // can be reopened to query dynamic profiles when all clients are inactive.
345 if (areAllActiveTracksRerouted(desc)) {
346 outputsToReopen.push_back(mOutputs.keyAt(i));
347 } else {
348 desc->mPendingReopenToQueryProfiles = true;
349 }
350 }
351 if (!desc->supportsDevicesForPlayback(activeMediaDevices)) {
352 // Clear the flag that previously set for re-querying profiles.
353 desc->mPendingReopenToQueryProfiles = false;
354 }
355 }
356 for (const auto& output : outputsToReopen) {
357 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
358 closeOutput(output);
359 openOutputWithProfileAndDevice(desc->mProfile, activeMediaDevices);
Eric Laurente552edb2014-03-10 17:42:56 -0700360 }
361
Eric Laurentd60560a2015-04-10 11:31:20 -0700362 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
François Gaffie11d30102018-11-02 16:09:09 +0100363 cleanUpForDevice(device);
Eric Laurentd60560a2015-04-10 11:31:20 -0700364 }
365
Eric Laurent96d1dda2022-03-14 17:14:19 +0100366 checkLeBroadcastRoutes(wasLeUnicastActive, nullptr, 0);
367
Eric Laurent72aa32f2014-05-30 18:51:48 -0700368 mpClientInterface->onAudioPortListUpdate();
Eric Laurentb71e58b2014-05-29 16:08:11 -0700369 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700370 } // end if is output device
371
Eric Laurente552edb2014-03-10 17:42:56 -0700372 // handle input devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700373 if (audio_is_input_device(device->type())) {
François Gaffie11d30102018-11-02 16:09:09 +0100374 ssize_t index = mAvailableInputDevices.indexOf(device);
Eric Laurente552edb2014-03-10 17:42:56 -0700375 switch (state)
376 {
377 // handle input device connection
Eric Laurent3b73df72014-03-11 09:06:29 -0700378 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700379 if (index >= 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100380 ALOGW("%s() device already connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700381 return INVALID_OPERATION;
382 }
Eric Laurent0dd51852019-04-19 18:18:58 -0700383
384 if (mAvailableInputDevices.add(device) < 0) {
385 return NO_MEMORY;
386 }
387
François Gaffie44481e72016-04-20 07:49:57 +0200388 // Before checking intputs, broadcast connect event to allow HAL to retrieve dynamic
389 // parameters on newly connected devices (instead of opening the inputs...)
François Gaffie11d30102018-11-02 16:09:09 +0100390 broadcastDeviceConnectionState(device, state);
François Gaffie44481e72016-04-20 07:49:57 +0200391
Eric Laurent0dd51852019-04-19 18:18:58 -0700392 if (checkInputsForDevice(device, state) != NO_ERROR) {
393 mAvailableInputDevices.remove(device);
394
François Gaffie11d30102018-11-02 16:09:09 +0100395 broadcastDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE);
Francois Gaffie716e1432019-01-14 16:58:59 +0100396
397 mHwModules.cleanUpForDevice(device);
398
Eric Laurentd4692962014-05-05 18:13:44 -0700399 return INVALID_OPERATION;
400 }
401
Eric Laurentd4692962014-05-05 18:13:44 -0700402 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700403
404 // handle input device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700405 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700406 if (index < 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100407 ALOGW("%s() device not connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700408 return INVALID_OPERATION;
409 }
Paul McLean5c477aa2014-08-20 16:47:57 -0700410
François Gaffie11d30102018-11-02 16:09:09 +0100411 ALOGV("%s() disconnecting input device %s", __func__, device->toString().c_str());
Paul McLean5c477aa2014-08-20 16:47:57 -0700412
413 // Set Disconnect to HALs
François Gaffie11d30102018-11-02 16:09:09 +0100414 broadcastDeviceConnectionState(device, state);
Paul McLean5c477aa2014-08-20 16:47:57 -0700415
François Gaffie11d30102018-11-02 16:09:09 +0100416 mAvailableInputDevices.remove(device);
Eric Laurent0dd51852019-04-19 18:18:58 -0700417
418 checkInputsForDevice(device, state);
Kriti Dangef6be8f2020-11-05 11:58:19 +0100419
420 // remove device from mReportedFormatsMap cache
421 mReportedFormatsMap.erase(device);
Eric Laurentd4692962014-05-05 18:13:44 -0700422 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700423
424 default:
François Gaffie11d30102018-11-02 16:09:09 +0100425 ALOGE("%s() invalid state: %x", __func__, state);
Eric Laurente552edb2014-03-10 17:42:56 -0700426 return BAD_VALUE;
427 }
428
Eric Laurent736a1022019-03-27 18:28:46 -0700429 // Propagate device availability to Engine
430 setEngineDeviceConnectionState(device, state);
431
Eric Laurent0dd51852019-04-19 18:18:58 -0700432 checkCloseInputs();
Eric Laurent5f5fca52016-08-04 11:48:57 -0700433 // As the input device list can impact the output device selection, update
434 // getDeviceForStrategy() cache
435 updateDevicesAndOutputs();
Eric Laurente552edb2014-03-10 17:42:56 -0700436
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100437 (void)updateCallRouting(false /*fromCache*/);
Francois Gaffiea0e5c992020-09-29 16:05:07 +0200438 // Reconnect Audio Source
439 for (const auto &strategy : mEngine->getOrderedProductStrategies()) {
440 auto attributes = mEngine->getAllAttributesForProductStrategy(strategy).front();
441 checkAudioSourceForAttributes(attributes);
442 }
Eric Laurentd60560a2015-04-10 11:31:20 -0700443 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
François Gaffie11d30102018-11-02 16:09:09 +0100444 cleanUpForDevice(device);
Eric Laurentd60560a2015-04-10 11:31:20 -0700445 }
446
Eric Laurentb52c1522014-05-20 11:27:36 -0700447 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -0700448 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700449 } // end if is input device
Eric Laurente552edb2014-03-10 17:42:56 -0700450
François Gaffie11d30102018-11-02 16:09:09 +0100451 ALOGW("%s() invalid device: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700452 return BAD_VALUE;
453}
454
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100455status_t AudioPolicyManager::deviceToAudioPort(audio_devices_t device, const char* device_address,
456 const char* device_name,
457 media::AudioPort* aidlPort) {
458 DeviceDescriptorBase devDescr(device, device_address);
459 devDescr.setName(device_name);
460 return devDescr.writeToParcelable(aidlPort);
461}
462
Eric Laurent736a1022019-03-27 18:28:46 -0700463void AudioPolicyManager::setEngineDeviceConnectionState(const sp<DeviceDescriptor> device,
464 audio_policy_dev_state_t state) {
465
466 // the Engine does not have to know about remote submix devices used by dynamic audio policies
467 if (audio_is_remote_submix_device(device->type()) && device->address() != "0") {
468 return;
469 }
470 mEngine->setDeviceConnectionState(device, state);
471}
472
473
Eric Laurente0720872014-03-11 09:30:41 -0700474audio_policy_dev_state_t AudioPolicyManager::getDeviceConnectionState(audio_devices_t device,
François Gaffie53615e22015-03-19 09:24:12 +0100475 const char *device_address)
Eric Laurente552edb2014-03-10 17:42:56 -0700476{
Eric Laurent634b7142016-04-20 13:48:02 -0700477 sp<DeviceDescriptor> devDesc =
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800478 mHwModules.getDeviceDescriptor(device, device_address, "", AUDIO_FORMAT_DEFAULT,
479 false /* allowToCreate */,
Eric Laurent634b7142016-04-20 13:48:02 -0700480 (strlen(device_address) != 0)/*matchAddress*/);
481
482 if (devDesc == 0) {
François Gaffie251c7f02018-11-07 10:41:08 +0100483 ALOGV("getDeviceConnectionState() undeclared device, type %08x, address: %s",
Eric Laurent634b7142016-04-20 13:48:02 -0700484 device, device_address);
485 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
486 }
François Gaffie53615e22015-03-19 09:24:12 +0100487
Eric Laurent3a4311c2014-03-17 12:00:47 -0700488 DeviceVector *deviceVector;
489
Eric Laurente552edb2014-03-10 17:42:56 -0700490 if (audio_is_output_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700491 deviceVector = &mAvailableOutputDevices;
Eric Laurente552edb2014-03-10 17:42:56 -0700492 } else if (audio_is_input_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700493 deviceVector = &mAvailableInputDevices;
494 } else {
François Gaffie11d30102018-11-02 16:09:09 +0100495 ALOGW("%s() invalid device type %08x", __func__, device);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700496 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurente552edb2014-03-10 17:42:56 -0700497 }
Eric Laurent634b7142016-04-20 13:48:02 -0700498
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800499 return (deviceVector->getDevice(
500 device, String8(device_address), AUDIO_FORMAT_DEFAULT) != 0) ?
Eric Laurent634b7142016-04-20 13:48:02 -0700501 AUDIO_POLICY_DEVICE_STATE_AVAILABLE : AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurenta1d525f2015-01-29 13:36:45 -0800502}
503
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800504status_t AudioPolicyManager::handleDeviceConfigChange(audio_devices_t device,
505 const char *device_address,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800506 const char *device_name,
507 audio_format_t encodedFormat)
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800508{
509 status_t status;
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700510 String8 reply;
511 AudioParameter param;
512 int isReconfigA2dpSupported = 0;
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800513
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800514 ALOGV("handleDeviceConfigChange(() device: 0x%X, address %s name %s encodedFormat: 0x%X",
515 device, device_address, device_name, encodedFormat);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800516
Pavlin Radoslavovc694ff42017-01-09 23:27:29 -0800517 // connect/disconnect only 1 device at a time
518 if (!audio_is_output_device(device) && !audio_is_input_device(device)) return BAD_VALUE;
519
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800520 // Check if the device is currently connected
jiabin9a3361e2019-10-01 09:38:30 -0700521 DeviceVector deviceList = mAvailableOutputDevices.getDevicesFromType(device);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800522 if (deviceList.empty()) {
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800523 // Nothing to do: device is not connected
524 return NO_ERROR;
525 }
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800526 sp<DeviceDescriptor> devDesc = deviceList.itemAt(0);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800527
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700528 // For offloaded A2DP, Hw modules may have the capability to
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800529 // configure codecs.
530 // Handle two specific cases by sending a set parameter to
531 // configure A2DP codecs. No need to toggle device state.
532 // Case 1: A2DP active device switches from primary to primary
533 // module
534 // Case 2: A2DP device config changes on primary module.
Francois Gaffiebce7cd42020-10-14 16:13:20 +0200535 if (audio_is_a2dp_out_device(device) && hasPrimaryOutput()) {
jiabin9a3361e2019-10-01 09:38:30 -0700536 sp<HwModule> module = mHwModules.getModuleForDeviceType(device, encodedFormat);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800537 audio_module_handle_t primaryHandle = mPrimaryOutput->getModuleHandle();
538 if (availablePrimaryOutputDevices().contains(devDesc) &&
539 (module != 0 && module->getHandle() == primaryHandle)) {
540 reply = mpClientInterface->getParameters(
541 AUDIO_IO_HANDLE_NONE,
542 String8(AudioParameter::keyReconfigA2dpSupported));
543 AudioParameter repliedParameters(reply);
544 repliedParameters.getInt(
545 String8(AudioParameter::keyReconfigA2dpSupported), isReconfigA2dpSupported);
546 if (isReconfigA2dpSupported) {
547 const String8 key(AudioParameter::keyReconfigA2dp);
548 param.add(key, String8("true"));
549 mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString());
550 devDesc->setEncodedFormat(encodedFormat);
551 return NO_ERROR;
552 }
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700553 }
554 }
cnx421bd2dcc42020-07-11 14:58:44 +0800555 auto musicStrategy = streamToStrategy(AUDIO_STREAM_MUSIC);
556 for (size_t i = 0; i < mOutputs.size(); i++) {
557 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
558 // mute media strategies and delay device switch by the largest
559 // This avoid sending the music tail into the earpiece or headset.
560 setStrategyMute(musicStrategy, true, desc);
561 setStrategyMute(musicStrategy, false, desc, MUTE_TIME_MS,
562 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
563 nullptr, true /*fromCache*/).types());
564 }
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800565 // Toggle the device state: UNAVAILABLE -> AVAILABLE
566 // This will force reading again the device configuration
567 status = setDeviceConnectionState(device,
568 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800569 device_address, device_name,
570 devDesc->getEncodedFormat());
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800571 if (status != NO_ERROR) {
572 ALOGW("handleDeviceConfigChange() error disabling connection state: %d",
573 status);
574 return status;
575 }
576
577 status = setDeviceConnectionState(device,
578 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800579 device_address, device_name, encodedFormat);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800580 if (status != NO_ERROR) {
581 ALOGW("handleDeviceConfigChange() error enabling connection state: %d",
582 status);
583 return status;
584 }
585
586 return NO_ERROR;
587}
588
Pattydd807582021-11-04 21:01:03 +0800589status_t AudioPolicyManager::getHwOffloadFormatsSupportedForBluetoothMedia(
590 audio_devices_t device, std::vector<audio_format_t> *formats)
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800591{
Pattydd807582021-11-04 21:01:03 +0800592 ALOGV("getHwOffloadFormatsSupportedForBluetoothMedia()");
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800593 status_t status = NO_ERROR;
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800594 std::unordered_set<audio_format_t> formatSet;
595 sp<HwModule> primaryModule =
596 mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_PRIMARY);
Aniket Kumar Latafedb5982019-07-03 11:20:36 -0700597 if (primaryModule == nullptr) {
598 ALOGE("%s() unable to get primary module", __func__);
599 return NO_INIT;
600 }
Pattydd807582021-11-04 21:01:03 +0800601
602 DeviceTypeSet audioDeviceSet;
603
604 switch(device) {
605 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP:
606 audioDeviceSet = getAudioDeviceOutAllA2dpSet();
607 break;
608 case AUDIO_DEVICE_OUT_BLE_HEADSET:
609 audioDeviceSet = getAudioDeviceOutAllBleSet();
610 break;
611 default:
612 ALOGE("%s() device type 0x%08x not supported", __func__, device);
613 return BAD_VALUE;
614 }
615
jiabin9a3361e2019-10-01 09:38:30 -0700616 DeviceVector declaredDevices = primaryModule->getDeclaredDevices().getDevicesFromTypes(
Pattydd807582021-11-04 21:01:03 +0800617 audioDeviceSet);
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800618 for (const auto& device : declaredDevices) {
619 formatSet.insert(device->encodedFormats().begin(), device->encodedFormats().end());
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800620 }
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800621 formats->assign(formatSet.begin(), formatSet.end());
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800622 return status;
623}
624
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100625DeviceVector AudioPolicyManager::selectBestRxSinkDevicesForCall(bool fromCache)
626{
627 DeviceVector rxSinkdevices{};
628 rxSinkdevices = mEngine->getOutputDevicesForAttributes(
629 attributes_initializer(AUDIO_USAGE_VOICE_COMMUNICATION), nullptr, fromCache);
630 if (!rxSinkdevices.isEmpty() && mAvailableOutputDevices.contains(rxSinkdevices.itemAt(0))) {
631 auto rxSinkDevice = rxSinkdevices.itemAt(0);
632 auto telephonyRxModule = mHwModules.getModuleForDeviceType(
633 AUDIO_DEVICE_IN_TELEPHONY_RX, AUDIO_FORMAT_DEFAULT);
634 // retrieve Rx Source device descriptor
635 sp<DeviceDescriptor> rxSourceDevice = mAvailableInputDevices.getDevice(
636 AUDIO_DEVICE_IN_TELEPHONY_RX, String8(), AUDIO_FORMAT_DEFAULT);
637
638 // RX Telephony and Rx sink devices are declared by Primary Audio HAL
639 if (isPrimaryModule(telephonyRxModule) && (telephonyRxModule->getHalVersionMajor() >= 3) &&
640 telephonyRxModule->supportsPatch(rxSourceDevice, rxSinkDevice)) {
641 ALOGW("%s() device %s using HW Bridge", __func__, rxSinkDevice->toString().c_str());
642 return DeviceVector(rxSinkDevice);
643 }
644 }
645 // Note that despite the fact that getNewOutputDevices() is called on the primary output,
646 // the device returned is not necessarily reachable via this output
647 // (filter later by setOutputDevices())
648 return getNewOutputDevices(mPrimaryOutput, fromCache);
649}
650
651status_t AudioPolicyManager::updateCallRouting(bool fromCache, uint32_t delayMs, uint32_t *waitMs)
652{
653 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL && hasPrimaryOutput()) {
654 DeviceVector rxDevices = selectBestRxSinkDevicesForCall(fromCache);
655 return updateCallRoutingInternal(rxDevices, delayMs, waitMs);
656 }
657 return INVALID_OPERATION;
658}
659
660status_t AudioPolicyManager::updateCallRoutingInternal(
661 const DeviceVector &rxDevices, uint32_t delayMs, uint32_t *waitMs)
Eric Laurentc2730ba2014-07-20 15:47:07 -0700662{
663 bool createTxPatch = false;
François Gaffie9eb18552018-11-05 10:33:26 +0100664 bool createRxPatch = false;
Eric Laurentdc462862016-07-19 12:29:53 -0700665 uint32_t muteWaitMs = 0;
jiabin9a3361e2019-10-01 09:38:30 -0700666 if(!hasPrimaryOutput() ||
667 mPrimaryOutput->devices().onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_STUB)) {
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100668 return INVALID_OPERATION;
Eric Laurent87ffa392015-05-22 10:32:38 -0700669 }
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100670 ALOG_ASSERT(!rxDevices.isEmpty(), "%s() no selected output device", __func__);
François Gaffie11d30102018-11-02 16:09:09 +0100671
Francois Gaffie716e1432019-01-14 16:58:59 +0100672 audio_attributes_t attr = { .source = AUDIO_SOURCE_VOICE_COMMUNICATION };
François Gaffiec005e562018-11-06 15:04:49 +0100673 auto txSourceDevice = mEngine->getInputDeviceForAttributes(attr);
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100674 ALOG_ASSERT(txSourceDevice != 0, "%s() input selected device not available", __func__);
François Gaffiec005e562018-11-06 15:04:49 +0100675
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100676 ALOGV("%s device rxDevice %s txDevice %s", __func__,
François Gaffie9eb18552018-11-05 10:33:26 +0100677 rxDevices.itemAt(0)->toString().c_str(), txSourceDevice->toString().c_str());
Eric Laurentc2730ba2014-07-20 15:47:07 -0700678
Francois Gaffie601801d2021-06-22 13:27:39 +0200679 disconnectTelephonyAudioSource(mCallRxSourceClient);
680 disconnectTelephonyAudioSource(mCallTxSourceClient);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700681
François Gaffie9eb18552018-11-05 10:33:26 +0100682 auto telephonyRxModule =
jiabin9a3361e2019-10-01 09:38:30 -0700683 mHwModules.getModuleForDeviceType(AUDIO_DEVICE_IN_TELEPHONY_RX, AUDIO_FORMAT_DEFAULT);
François Gaffie9eb18552018-11-05 10:33:26 +0100684 auto telephonyTxModule =
jiabin9a3361e2019-10-01 09:38:30 -0700685 mHwModules.getModuleForDeviceType(AUDIO_DEVICE_OUT_TELEPHONY_TX, AUDIO_FORMAT_DEFAULT);
François Gaffie9eb18552018-11-05 10:33:26 +0100686 // retrieve Rx Source and Tx Sink device descriptors
687 sp<DeviceDescriptor> rxSourceDevice =
688 mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_TELEPHONY_RX,
689 String8(),
690 AUDIO_FORMAT_DEFAULT);
691 sp<DeviceDescriptor> txSinkDevice =
692 mAvailableOutputDevices.getDevice(AUDIO_DEVICE_OUT_TELEPHONY_TX,
693 String8(),
694 AUDIO_FORMAT_DEFAULT);
695
696 // RX and TX Telephony device are declared by Primary Audio HAL
697 if (isPrimaryModule(telephonyRxModule) && isPrimaryModule(telephonyTxModule) &&
698 (telephonyRxModule->getHalVersionMajor() >= 3)) {
699 if (rxSourceDevice == 0 || txSinkDevice == 0) {
700 // RX / TX Telephony device(s) is(are) not currently available
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100701 ALOGE("%s() no telephony Tx and/or RX device", __func__);
702 return INVALID_OPERATION;
François Gaffie9eb18552018-11-05 10:33:26 +0100703 }
François Gaffieafd4cea2019-11-18 15:50:22 +0100704 // createAudioPatchInternal now supports both HW / SW bridging
705 createRxPatch = true;
706 createTxPatch = true;
François Gaffie9eb18552018-11-05 10:33:26 +0100707 } else {
708 // If the RX device is on the primary HW module, then use legacy routing method for
709 // voice calls via setOutputDevice() on primary output.
710 // Otherwise, create two audio patches for TX and RX path.
711 createRxPatch = !(availablePrimaryOutputDevices().contains(rxDevices.itemAt(0))) &&
712 (rxSourceDevice != 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700713 // If the TX device is also on the primary HW module, setOutputDevice() will take care
714 // of it due to legacy implementation. If not, create a patch.
François Gaffie9eb18552018-11-05 10:33:26 +0100715 createTxPatch = !(availablePrimaryModuleInputDevices().contains(txSourceDevice)) &&
716 (txSinkDevice != 0);
717 }
718 // Use legacy routing method for voice calls via setOutputDevice() on primary output.
719 // Otherwise, create two audio patches for TX and RX path.
720 if (!createRxPatch) {
721 muteWaitMs = setOutputDevices(mPrimaryOutput, rxDevices, true, delayMs);
Eric Laurent8ae73122016-04-12 10:13:29 -0700722 } else { // create RX path audio patch
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200723 connectTelephonyRxAudioSource();
juyuchen2224c5a2019-01-21 12:00:58 +0800724 // If the TX device is on the primary HW module but RX device is
725 // on other HW module, SinkMetaData of telephony input should handle it
726 // assuming the device uses audio HAL V5.0 and above
Eric Laurentc2730ba2014-07-20 15:47:07 -0700727 }
Eric Laurent8ae73122016-04-12 10:13:29 -0700728 if (createTxPatch) { // create TX path audio patch
François Gaffieafd4cea2019-11-18 15:50:22 +0100729 // terminate active capture if on the same HW module as the call TX source device
730 // FIXME: would be better to refine to only inputs whose profile connects to the
731 // call TX device but this information is not in the audio patch and logic here must be
732 // symmetric to the one in startInput()
733 for (const auto& activeDesc : mInputs.getActiveInputs()) {
734 if (activeDesc->hasSameHwModuleAs(txSourceDevice)) {
735 closeActiveClients(activeDesc);
736 }
737 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200738 connectTelephonyTxAudioSource(txSourceDevice, txSinkDevice, delayMs);
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800739 }
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100740 if (waitMs != nullptr) {
741 *waitMs = muteWaitMs;
742 }
743 return NO_ERROR;
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800744}
Eric Laurentc2730ba2014-07-20 15:47:07 -0700745
Mikhail Naganov100f0122018-11-29 11:22:16 -0800746bool AudioPolicyManager::isDeviceOfModule(
747 const sp<DeviceDescriptor>& devDesc, const char *moduleId) const {
748 sp<HwModule> module = mHwModules.getModuleFromName(moduleId);
749 if (module != 0) {
750 return mAvailableOutputDevices.getDevicesFromHwModule(module->getHandle())
751 .indexOf(devDesc) != NAME_NOT_FOUND
752 || mAvailableInputDevices.getDevicesFromHwModule(module->getHandle())
753 .indexOf(devDesc) != NAME_NOT_FOUND;
754 }
755 return false;
756}
757
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200758void AudioPolicyManager::connectTelephonyRxAudioSource()
759{
Francois Gaffie601801d2021-06-22 13:27:39 +0200760 disconnectTelephonyAudioSource(mCallRxSourceClient);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200761 const struct audio_port_config source = {
762 .role = AUDIO_PORT_ROLE_SOURCE, .type = AUDIO_PORT_TYPE_DEVICE,
763 .ext.device.type = AUDIO_DEVICE_IN_TELEPHONY_RX, .ext.device.address = ""
764 };
765 const auto aa = mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL);
Francois Gaffie601801d2021-06-22 13:27:39 +0200766 mCallRxSourceClient = startAudioSourceInternal(&source, &aa, 0/*uid*/);
767 ALOGE_IF(mCallRxSourceClient == nullptr,
768 "%s failed to start Telephony Rx AudioSource", __func__);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200769}
770
Francois Gaffie601801d2021-06-22 13:27:39 +0200771void AudioPolicyManager::disconnectTelephonyAudioSource(sp<SourceClientDescriptor> &clientDesc)
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200772{
Francois Gaffie601801d2021-06-22 13:27:39 +0200773 if (clientDesc == nullptr) {
774 return;
775 }
776 ALOGW_IF(stopAudioSource(clientDesc->portId()) != NO_ERROR,
777 "%s error stopping audio source", __func__);
778 clientDesc.clear();
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200779}
780
781void AudioPolicyManager::connectTelephonyTxAudioSource(
782 const sp<DeviceDescriptor> &srcDevice, const sp<DeviceDescriptor> &sinkDevice,
783 uint32_t delayMs)
784{
Francois Gaffie601801d2021-06-22 13:27:39 +0200785 disconnectTelephonyAudioSource(mCallTxSourceClient);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200786 if (srcDevice == nullptr || sinkDevice == nullptr) {
787 ALOGW("%s could not create patch, invalid sink and/or source device(s)", __func__);
788 return;
789 }
790 PatchBuilder patchBuilder;
791 patchBuilder.addSource(srcDevice).addSink(sinkDevice);
792 ALOGV("%s between source %s and sink %s", __func__,
793 srcDevice->toString().c_str(), sinkDevice->toString().c_str());
Francois Gaffie601801d2021-06-22 13:27:39 +0200794 auto callTxSourceClientPortId = PolicyAudioPort::getNextUniqueId();
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200795 const audio_attributes_t aa = { .source = AUDIO_SOURCE_VOICE_COMMUNICATION };
796 struct audio_port_config source = {};
797 srcDevice->toAudioPortConfig(&source);
Francois Gaffie601801d2021-06-22 13:27:39 +0200798 mCallTxSourceClient = new InternalSourceClientDescriptor(
799 callTxSourceClientPortId, mUidCached, aa, source, srcDevice, sinkDevice,
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200800 mCommunnicationStrategy, toVolumeSource(aa));
801 audio_patch_handle_t patchHandle = AUDIO_PATCH_HANDLE_NONE;
802 status_t status = connectAudioSourceToSink(
Francois Gaffie601801d2021-06-22 13:27:39 +0200803 mCallTxSourceClient, sinkDevice, patchBuilder.patch(), patchHandle, mUidCached,
804 delayMs);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200805 ALOGE_IF(status != NO_ERROR, "%s() error %d creating TX audio patch", __func__, status);
806 if (status == NO_ERROR) {
Francois Gaffie601801d2021-06-22 13:27:39 +0200807 mAudioSources.add(callTxSourceClientPortId, mCallTxSourceClient);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200808 }
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200809}
810
Eric Laurente0720872014-03-11 09:30:41 -0700811void AudioPolicyManager::setPhoneState(audio_mode_t state)
Eric Laurente552edb2014-03-10 17:42:56 -0700812{
813 ALOGV("setPhoneState() state %d", state);
François Gaffie2110e042015-03-24 08:41:51 +0100814 // store previous phone state for management of sonification strategy below
815 int oldState = mEngine->getPhoneState();
Eric Laurent96d1dda2022-03-14 17:14:19 +0100816 bool wasLeUnicastActive = isLeUnicastActive();
François Gaffie2110e042015-03-24 08:41:51 +0100817
818 if (mEngine->setPhoneState(state) != NO_ERROR) {
819 ALOGW("setPhoneState() invalid or same state %d", state);
Eric Laurente552edb2014-03-10 17:42:56 -0700820 return;
821 }
François Gaffie2110e042015-03-24 08:41:51 +0100822 /// Opens: can these line be executed after the switch of volume curves???
Eric Laurent63dea1d2015-07-02 17:10:28 -0700823 if (isStateInCall(oldState)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700824 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent63dea1d2015-07-02 17:10:28 -0700825 // force reevaluating accessibility routing when call stops
Eric Laurent2cbe89a2014-12-19 11:49:08 -0800826 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -0700827 }
828
François Gaffie2110e042015-03-24 08:41:51 +0100829 /**
830 * Switching to or from incall state or switching between telephony and VoIP lead to force
831 * routing command.
832 */
Eric Laurent74b71512019-11-06 17:21:57 -0800833 bool force = ((isStateInCall(oldState) != isStateInCall(state))
834 || (isStateInCall(state) && (state != oldState)));
Eric Laurente552edb2014-03-10 17:42:56 -0700835
836 // check for device and output changes triggered by new phone state
Mikhail Naganov37977152018-07-11 15:54:44 -0700837 checkForDeviceAndOutputChanges();
Eric Laurente552edb2014-03-10 17:42:56 -0700838
Eric Laurente552edb2014-03-10 17:42:56 -0700839 int delayMs = 0;
840 if (isStateInCall(state)) {
841 nsecs_t sysTime = systemTime();
François Gaffiec005e562018-11-06 15:04:49 +0100842 auto musicStrategy = streamToStrategy(AUDIO_STREAM_MUSIC);
843 auto sonificationStrategy = streamToStrategy(AUDIO_STREAM_ALARM);
Eric Laurente552edb2014-03-10 17:42:56 -0700844 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700845 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700846 // mute media and sonification strategies and delay device switch by the largest
847 // latency of any output where either strategy is active.
848 // This avoid sending the ring tone or music tail into the earpiece or headset.
François Gaffiec005e562018-11-06 15:04:49 +0100849 if ((desc->isStrategyActive(musicStrategy, SONIFICATION_HEADSET_MUSIC_DELAY, sysTime) ||
850 desc->isStrategyActive(sonificationStrategy, SONIFICATION_HEADSET_MUSIC_DELAY,
851 sysTime)) &&
Eric Laurentc75307b2015-03-17 15:29:32 -0700852 (delayMs < (int)desc->latency()*2)) {
853 delayMs = desc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -0700854 }
François Gaffiec005e562018-11-06 15:04:49 +0100855 setStrategyMute(musicStrategy, true, desc);
856 setStrategyMute(musicStrategy, false, desc, MUTE_TIME_MS,
857 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
858 nullptr, true /*fromCache*/).types());
859 setStrategyMute(sonificationStrategy, true, desc);
860 setStrategyMute(sonificationStrategy, false, desc, MUTE_TIME_MS,
861 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_ALARM),
862 nullptr, true /*fromCache*/).types());
Eric Laurente552edb2014-03-10 17:42:56 -0700863 }
864 }
865
Eric Laurent87ffa392015-05-22 10:32:38 -0700866 if (hasPrimaryOutput()) {
Eric Laurent87ffa392015-05-22 10:32:38 -0700867 if (state == AUDIO_MODE_IN_CALL) {
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100868 (void)updateCallRouting(false /*fromCache*/, delayMs);
Eric Laurent87ffa392015-05-22 10:32:38 -0700869 } else {
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100870 DeviceVector rxDevices = getNewOutputDevices(mPrimaryOutput, false /*fromCache*/);
871 // force routing command to audio hardware when ending call
872 // even if no device change is needed
873 if (isStateInCall(oldState) && rxDevices.isEmpty()) {
874 rxDevices = mPrimaryOutput->devices();
875 }
876 if (oldState == AUDIO_MODE_IN_CALL) {
Francois Gaffie601801d2021-06-22 13:27:39 +0200877 disconnectTelephonyAudioSource(mCallRxSourceClient);
878 disconnectTelephonyAudioSource(mCallTxSourceClient);
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100879 }
François Gaffie11d30102018-11-02 16:09:09 +0100880 setOutputDevices(mPrimaryOutput, rxDevices, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700881 }
Eric Laurentc2730ba2014-07-20 15:47:07 -0700882 }
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700883
884 // reevaluate routing on all outputs in case tracks have been started during the call
885 for (size_t i = 0; i < mOutputs.size(); i++) {
886 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
François Gaffie11d30102018-11-02 16:09:09 +0100887 DeviceVector newDevices = getNewOutputDevices(desc, true /*fromCache*/);
Francois Gaffie601801d2021-06-22 13:27:39 +0200888 if (state != AUDIO_MODE_IN_CALL || (desc != mPrimaryOutput && !isTelephonyRxOrTx(desc))) {
889 bool forceRouting = !newDevices.isEmpty();
890 setOutputDevices(desc, newDevices, forceRouting, 0 /*delayMs*/, nullptr,
891 true /*requiresMuteCheck*/, !forceRouting /*requiresVolumeCheck*/);
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700892 }
893 }
894
Eric Laurent96d1dda2022-03-14 17:14:19 +0100895 checkLeBroadcastRoutes(wasLeUnicastActive, nullptr, delayMs);
896
Eric Laurente552edb2014-03-10 17:42:56 -0700897 if (isStateInCall(state)) {
898 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent63dea1d2015-07-02 17:10:28 -0700899 // force reevaluating accessibility routing when call starts
900 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -0700901 }
902
903 // Flag that ringtone volume must be limited to music volume until we exit MODE_RINGTONE
François Gaffiec005e562018-11-06 15:04:49 +0100904 mLimitRingtoneVolume = (state == AUDIO_MODE_RINGTONE &&
905 isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY));
Eric Laurente552edb2014-03-10 17:42:56 -0700906}
907
Jean-Michel Trivi887a9ed2015-03-31 18:02:24 -0700908audio_mode_t AudioPolicyManager::getPhoneState() {
909 return mEngine->getPhoneState();
910}
911
Eric Laurente0720872014-03-11 09:30:41 -0700912void AudioPolicyManager::setForceUse(audio_policy_force_use_t usage,
François Gaffie11d30102018-11-02 16:09:09 +0100913 audio_policy_forced_cfg_t config)
Eric Laurente552edb2014-03-10 17:42:56 -0700914{
François Gaffie2110e042015-03-24 08:41:51 +0100915 ALOGV("setForceUse() usage %d, config %d, mPhoneState %d", usage, config, mEngine->getPhoneState());
Eric Laurent8dc87a62017-05-16 19:00:40 -0700916 if (config == mEngine->getForceUse(usage)) {
917 return;
918 }
Eric Laurente552edb2014-03-10 17:42:56 -0700919
François Gaffie2110e042015-03-24 08:41:51 +0100920 if (mEngine->setForceUse(usage, config) != NO_ERROR) {
921 ALOGW("setForceUse() could not set force cfg %d for usage %d", config, usage);
922 return;
Eric Laurente552edb2014-03-10 17:42:56 -0700923 }
François Gaffie2110e042015-03-24 08:41:51 +0100924 bool forceVolumeReeval = (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) ||
925 (usage == AUDIO_POLICY_FORCE_FOR_DOCK) ||
926 (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM);
Eric Laurente552edb2014-03-10 17:42:56 -0700927
928 // check for device and output changes triggered by new force usage
Mikhail Naganov37977152018-07-11 15:54:44 -0700929 checkForDeviceAndOutputChanges();
Phil Burk09bc4612016-02-24 15:58:15 -0800930
Eric Laurent22fcda22019-05-17 16:28:47 -0700931 // force client reconnection to reevaluate flag AUDIO_FLAG_AUDIBILITY_ENFORCED
932 if (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM) {
933 mpClientInterface->invalidateStream(AUDIO_STREAM_SYSTEM);
934 mpClientInterface->invalidateStream(AUDIO_STREAM_ENFORCED_AUDIBLE);
935 }
936
Eric Laurentdc462862016-07-19 12:29:53 -0700937 //FIXME: workaround for truncated touch sounds
938 // to be removed when the problem is handled by system UI
939 uint32_t delayMs = 0;
Eric Laurentdc462862016-07-19 12:29:53 -0700940 if (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) {
941 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
942 }
Jean-Michel Trivi30857152019-11-01 11:04:15 -0700943
944 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Eric Laurent2517af32020-11-25 15:31:27 +0100945 updateInputRouting();
Eric Laurente552edb2014-03-10 17:42:56 -0700946}
947
Eric Laurente0720872014-03-11 09:30:41 -0700948void AudioPolicyManager::setSystemProperty(const char* property, const char* value)
Eric Laurente552edb2014-03-10 17:42:56 -0700949{
950 ALOGV("setSystemProperty() property %s, value %s", property, value);
951}
952
Dorin Drimusecc9f422022-03-09 17:57:40 +0100953// Find an MSD output profile compatible with the parameters passed.
954// When "directOnly" is set, restrict search to profiles for direct outputs.
955sp<IOProfile> AudioPolicyManager::getMsdProfileForOutput(
956 const DeviceVector& devices,
957 uint32_t samplingRate,
958 audio_format_t format,
959 audio_channel_mask_t channelMask,
960 audio_output_flags_t flags,
961 bool directOnly)
962{
963 flags = getRelevantFlags(flags, directOnly);
964
965 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
966 if (msdModule != nullptr) {
967 // for the msd module check if there are patches to the output devices
968 if (msdHasPatchesToAllDevices(devices.toTypeAddrVector())) {
969 HwModuleCollection modules;
970 modules.add(msdModule);
971 return searchCompatibleProfileHwModules(
972 modules, getMsdAudioOutDevices(), samplingRate, format, channelMask,
973 flags, directOnly);
974 }
975 }
976 return nullptr;
977}
978
Michael Chana94fbb22018-04-24 14:31:19 +1000979// Find an output profile compatible with the parameters passed. When "directOnly" is set, restrict
980// search to profiles for direct outputs.
981sp<IOProfile> AudioPolicyManager::getProfileForOutput(
François Gaffie11d30102018-11-02 16:09:09 +0100982 const DeviceVector& devices,
Michael Chana94fbb22018-04-24 14:31:19 +1000983 uint32_t samplingRate,
984 audio_format_t format,
985 audio_channel_mask_t channelMask,
986 audio_output_flags_t flags,
987 bool directOnly)
Eric Laurente552edb2014-03-10 17:42:56 -0700988{
Dorin Drimusecc9f422022-03-09 17:57:40 +0100989 flags = getRelevantFlags(flags, directOnly);
990
991 return searchCompatibleProfileHwModules(
992 mHwModules, devices, samplingRate, format, channelMask, flags, directOnly);
993}
994
995audio_output_flags_t AudioPolicyManager::getRelevantFlags (
996 audio_output_flags_t flags, bool directOnly) {
Michael Chana94fbb22018-04-24 14:31:19 +1000997 if (directOnly) {
Dorin Drimusecc9f422022-03-09 17:57:40 +0100998 // only retain flags that will drive the direct output profile selection
999 // if explicitly requested
1000 static const uint32_t kRelevantFlags =
Michael Chana94fbb22018-04-24 14:31:19 +10001001 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD |
Dorin Drimusecc9f422022-03-09 17:57:40 +01001002 AUDIO_OUTPUT_FLAG_VOIP_RX | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ);
1003 flags = (audio_output_flags_t)((flags & kRelevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
Michael Chana94fbb22018-04-24 14:31:19 +10001004 }
Dorin Drimusecc9f422022-03-09 17:57:40 +01001005 return flags;
1006}
Eric Laurent861a6282015-05-18 15:40:16 -07001007
Dorin Drimusecc9f422022-03-09 17:57:40 +01001008sp<IOProfile> AudioPolicyManager::searchCompatibleProfileHwModules (
1009 const HwModuleCollection& hwModules,
1010 const DeviceVector& devices,
1011 uint32_t samplingRate,
1012 audio_format_t format,
1013 audio_channel_mask_t channelMask,
1014 audio_output_flags_t flags,
1015 bool directOnly) {
Eric Laurent861a6282015-05-18 15:40:16 -07001016 sp<IOProfile> profile;
Dorin Drimusecc9f422022-03-09 17:57:40 +01001017 for (const auto& hwModule : hwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08001018 for (const auto& curProfile : hwModule->getOutputProfiles()) {
Dorin Drimusecc9f422022-03-09 17:57:40 +01001019 if (!curProfile->isCompatibleProfile(devices,
1020 samplingRate, NULL /*updatedSamplingRate*/,
1021 format, NULL /*updatedFormat*/,
1022 channelMask, NULL /*updatedChannelMask*/,
1023 flags)) {
1024 continue;
1025 }
1026 // reject profiles not corresponding to a device currently available
1027 if (!mAvailableOutputDevices.containsAtLeastOne(curProfile->getSupportedDevices())) {
1028 continue;
1029 }
1030 // reject profiles if connected device does not support codec
1031 if (!curProfile->devicesSupportEncodedFormats(devices.types())) {
1032 continue;
1033 }
1034 if (!directOnly) {
1035 return curProfile;
1036 }
1037
1038 // when searching for direct outputs, if several profiles are compatible, give priority
1039 // to one with offload capability
1040 if (profile != 0 &&
1041 ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0)) {
Eric Laurent861a6282015-05-18 15:40:16 -07001042 continue;
Dorin Drimusecc9f422022-03-09 17:57:40 +01001043 }
1044 profile = curProfile;
1045 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1046 break;
1047 }
Eric Laurente552edb2014-03-10 17:42:56 -07001048 }
1049 }
Eric Laurent861a6282015-05-18 15:40:16 -07001050 return profile;
Eric Laurente552edb2014-03-10 17:42:56 -07001051}
1052
Eric Laurentfa0f6742021-08-17 18:39:44 +02001053sp<IOProfile> AudioPolicyManager::getSpatializerOutputProfile(
Eric Laurent39095982021-08-24 18:29:27 +02001054 const audio_config_t *config __unused, const AudioDeviceTypeAddrVector &devices) const
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001055{
1056 for (const auto& hwModule : mHwModules) {
1057 for (const auto& curProfile : hwModule->getOutputProfiles()) {
Eric Laurent1c5e2e32021-08-18 18:50:28 +02001058 if (curProfile->getFlags() != AUDIO_OUTPUT_FLAG_SPATIALIZER) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001059 continue;
1060 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001061 if (!devices.empty()) {
Eric Laurent0c8f7cc2022-06-24 14:32:36 +02001062 // reject profiles not corresponding to a device currently available
1063 DeviceVector supportedDevices = curProfile->getSupportedDevices();
1064 if (!mAvailableOutputDevices.containsAtLeastOne(supportedDevices)) {
1065 continue;
1066 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001067 if (supportedDevices.getDevicesFromDeviceTypeAddrVec(devices).size()
1068 != devices.size()) {
1069 continue;
1070 }
1071 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001072 ALOGV("%s found profile %s", __func__, curProfile->getName().c_str());
1073 return curProfile;
1074 }
1075 }
1076 return nullptr;
1077}
1078
Eric Laurentf4e63452017-11-06 19:31:46 +00001079audio_io_handle_t AudioPolicyManager::getOutput(audio_stream_type_t stream)
Eric Laurente552edb2014-03-10 17:42:56 -07001080{
François Gaffiec005e562018-11-06 15:04:49 +01001081 DeviceVector devices = mEngine->getOutputDevicesForStream(stream, false /*fromCache*/);
Andy Hungc9901522017-11-10 20:07:54 -08001082
1083 // Note that related method getOutputForAttr() uses getOutputForDevice() not selectOutput().
1084 // We use selectOutput() here since we don't have the desired AudioTrack sample rate,
1085 // format, flags, etc. This may result in some discrepancy for functions that utilize
1086 // getOutput() solely on audio_stream_type such as AudioSystem::getOutputFrameCount()
1087 // and AudioSystem::getOutputSamplingRate().
1088
François Gaffie11d30102018-11-02 16:09:09 +01001089 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurent16c66dd2019-05-01 17:54:10 -07001090 const audio_io_handle_t output = selectOutput(outputs);
Eric Laurente552edb2014-03-10 17:42:56 -07001091
François Gaffie11d30102018-11-02 16:09:09 +01001092 ALOGV("getOutput() stream %d selected devices %s, output %d", stream,
1093 devices.toString().c_str(), output);
Eric Laurentf4e63452017-11-06 19:31:46 +00001094 return output;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001095}
1096
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001097status_t AudioPolicyManager::getAudioAttributes(audio_attributes_t *dstAttr,
1098 const audio_attributes_t *srcAttr,
1099 audio_stream_type_t srcStream)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001100{
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001101 if (srcAttr != NULL) {
1102 if (!isValidAttributes(srcAttr)) {
1103 ALOGE("%s invalid attributes: usage=%d content=%d flags=0x%x tags=[%s]",
1104 __func__,
1105 srcAttr->usage, srcAttr->content_type, srcAttr->flags,
1106 srcAttr->tags);
1107 return BAD_VALUE;
1108 }
1109 *dstAttr = *srcAttr;
1110 } else {
1111 if (srcStream < AUDIO_STREAM_MIN || srcStream >= AUDIO_STREAM_PUBLIC_CNT) {
1112 ALOGE("%s: invalid stream type", __func__);
1113 return BAD_VALUE;
1114 }
François Gaffiec005e562018-11-06 15:04:49 +01001115 *dstAttr = mEngine->getAttributesForStreamType(srcStream);
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001116 }
Eric Laurent22fcda22019-05-17 16:28:47 -07001117
1118 // Only honor audibility enforced when required. The client will be
1119 // forced to reconnect if the forced usage changes.
1120 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Mikhail Naganov55773032020-10-01 15:08:13 -07001121 dstAttr->flags = static_cast<audio_flags_mask_t>(
1122 dstAttr->flags & ~AUDIO_FLAG_AUDIBILITY_ENFORCED);
Eric Laurent22fcda22019-05-17 16:28:47 -07001123 }
1124
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001125 return NO_ERROR;
1126}
1127
Kevin Rocard153f92d2018-12-18 18:33:28 -08001128status_t AudioPolicyManager::getOutputForAttrInt(
1129 audio_attributes_t *resultAttr,
1130 audio_io_handle_t *output,
1131 audio_session_t session,
1132 const audio_attributes_t *attr,
1133 audio_stream_type_t *stream,
1134 uid_t uid,
jiabinf1c73972022-04-14 16:28:52 -07001135 audio_config_t *config,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001136 audio_output_flags_t *flags,
1137 audio_port_handle_t *selectedDeviceId,
1138 bool *isRequestedDeviceForExclusiveUse,
Eric Laurentc529cf62020-04-17 18:19:10 -07001139 std::vector<sp<AudioPolicyMix>> *secondaryMixes,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001140 output_type_t *outputType,
1141 bool *isSpatialized)
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001142{
François Gaffiec005e562018-11-06 15:04:49 +01001143 DeviceVector outputDevices;
Francois Gaffie716e1432019-01-14 16:58:59 +01001144 const audio_port_handle_t requestedPortId = *selectedDeviceId;
François Gaffie11d30102018-11-02 16:09:09 +01001145 DeviceVector msdDevices = getMsdAudioOutDevices();
François Gaffiec005e562018-11-06 15:04:49 +01001146 const sp<DeviceDescriptor> requestedDevice =
1147 mAvailableOutputDevices.getDeviceFromId(requestedPortId);
1148
Eric Laurent8a1095a2019-11-08 14:44:16 -08001149 *outputType = API_OUTPUT_INVALID;
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001150 *isSpatialized = false;
1151
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001152 status_t status = getAudioAttributes(resultAttr, attr, *stream);
1153 if (status != NO_ERROR) {
1154 return status;
Eric Laurent8f42ea12018-08-08 09:08:25 -07001155 }
Kevin Rocardb99cc752019-03-21 20:52:24 -07001156 if (auto it = mAllowedCapturePolicies.find(uid); it != end(mAllowedCapturePolicies)) {
Mikhail Naganov55773032020-10-01 15:08:13 -07001157 resultAttr->flags = static_cast<audio_flags_mask_t>(resultAttr->flags | it->second);
Kevin Rocardb99cc752019-03-21 20:52:24 -07001158 }
François Gaffiec005e562018-11-06 15:04:49 +01001159 *stream = mEngine->getStreamTypeForAttributes(*resultAttr);
Eric Laurent8f42ea12018-08-08 09:08:25 -07001160
François Gaffiec005e562018-11-06 15:04:49 +01001161 ALOGV("%s() attributes=%s stream=%s session %d selectedDeviceId %d", __func__,
1162 toString(*resultAttr).c_str(), toString(*stream).c_str(), session, requestedPortId);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001163
Kevin Rocard153f92d2018-12-18 18:33:28 -08001164 // The primary output is the explicit routing (eg. setPreferredDevice) if specified,
1165 // otherwise, fallback to the dynamic policies, if none match, query the engine.
1166 // Secondary outputs are always found by dynamic policies as the engine do not support them
Eric Laurentc529cf62020-04-17 18:19:10 -07001167 sp<AudioPolicyMix> primaryMix;
Dean Wheatleyd082f472022-02-04 11:10:48 +11001168 const audio_config_base_t clientConfig = {.sample_rate = config->sample_rate,
1169 .channel_mask = config->channel_mask,
1170 .format = config->format,
1171 };
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02001172 status = mPolicyMixes.getOutputForAttr(*resultAttr, clientConfig, uid, session, *flags,
1173 primaryMix, secondaryMixes);
Kevin Rocard94114a22019-04-01 19:38:23 -07001174 if (status != OK) {
1175 return status;
Kevin Rocard153f92d2018-12-18 18:33:28 -08001176 }
Kevin Rocard94114a22019-04-01 19:38:23 -07001177
Kevin Rocard153f92d2018-12-18 18:33:28 -08001178 // Explicit routing is higher priority then any dynamic policy primary output
Eric Laurentc529cf62020-04-17 18:19:10 -07001179 bool usePrimaryOutputFromPolicyMixes = requestedDevice == nullptr && primaryMix != nullptr;
Kevin Rocard153f92d2018-12-18 18:33:28 -08001180
1181 // FIXME: in case of RENDER policy, the output capabilities should be checked
Dean Wheatleyd082f472022-02-04 11:10:48 +11001182 if ((secondaryMixes != nullptr && !secondaryMixes->empty())
1183 && !audio_is_linear_pcm(config->format)) {
1184 ALOGD("%s: rejecting request as secondary mixes only support pcm", __func__);
Kevin Rocard153f92d2018-12-18 18:33:28 -08001185 return BAD_VALUE;
1186 }
1187 if (usePrimaryOutputFromPolicyMixes) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001188 sp<DeviceDescriptor> deviceDesc =
1189 mAvailableOutputDevices.getDevice(primaryMix->mDeviceType,
1190 primaryMix->mDeviceAddress,
1191 AUDIO_FORMAT_DEFAULT);
1192 sp<SwAudioOutputDescriptor> policyDesc = primaryMix->getOutput();
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001193 bool tryDirectForFlags = policyDesc == nullptr ||
1194 (policyDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT);
1195 // if a direct output can be opened to deliver the track's multi-channel content to the
1196 // output rather than being downmixed by the primary output, then use this direct
1197 // output by by-passing the primary mix if possible, otherwise fall-through to primary
1198 // mix.
1199 bool tryDirectForChannelMask = policyDesc != nullptr
1200 && (audio_channel_count_from_out_mask(policyDesc->getConfig().channel_mask) <
1201 audio_channel_count_from_out_mask(config->channel_mask));
1202 if (deviceDesc != nullptr && (tryDirectForFlags || tryDirectForChannelMask)) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001203 audio_io_handle_t newOutput;
1204 status = openDirectOutput(
1205 *stream, session, config,
1206 (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT),
1207 DeviceVector(deviceDesc), &newOutput);
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001208 if (status == NO_ERROR) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001209 policyDesc = mOutputs.valueFor(newOutput);
1210 primaryMix->setOutput(policyDesc);
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001211 } else if (tryDirectForFlags) {
1212 policyDesc = nullptr;
1213 } // otherwise use primary if available.
Eric Laurentc529cf62020-04-17 18:19:10 -07001214 }
1215 if (policyDesc != nullptr) {
1216 policyDesc->mPolicyMix = primaryMix;
1217 *output = policyDesc->mIoHandle;
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08001218 *selectedDeviceId = deviceDesc != 0 ? deviceDesc->getId() : AUDIO_PORT_HANDLE_NONE;
Eric Laurent8a1095a2019-11-08 14:44:16 -08001219
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08001220 ALOGV("getOutputForAttr() returns output %d", *output);
1221 if (resultAttr->usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
1222 *outputType = API_OUT_MIX_PLAYBACK;
1223 } else {
1224 *outputType = API_OUTPUT_LEGACY;
1225 }
1226 return NO_ERROR;
Eric Laurent8a1095a2019-11-08 14:44:16 -08001227 }
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001228 }
François Gaffiec005e562018-11-06 15:04:49 +01001229 // Virtual sources must always be dynamicaly or explicitly routed
1230 if (resultAttr->usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
1231 ALOGW("getOutputForAttr() no policy mix found for usage AUDIO_USAGE_VIRTUAL_SOURCE");
1232 return BAD_VALUE;
1233 }
1234 // explicit routing managed by getDeviceForStrategy in APM is now handled by engine
1235 // in order to let the choice of the order to future vendor engine
1236 outputDevices = mEngine->getOutputDevicesForAttributes(*resultAttr, requestedDevice, false);
Scott Randolph7b1fd232018-06-18 15:33:03 -07001237
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001238 if ((resultAttr->flags & AUDIO_FLAG_HW_AV_SYNC) != 0) {
Nadav Bar766fb022018-01-07 12:18:03 +02001239 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
Eric Laurent93c3d412014-08-01 14:48:35 -07001240 }
1241
Nadav Barb2f18162018-07-18 13:01:53 +03001242 // Set incall music only if device was explicitly set, and fallback to the device which is
1243 // chosen by the engine if not.
1244 // FIXME: provide a more generic approach which is not device specific and move this back
1245 // to getOutputForDevice.
Nadav Bar20919492018-11-20 10:20:51 +02001246 // TODO: Remove check of AUDIO_STREAM_MUSIC once migration is completed on the app side.
jiabin9a3361e2019-10-01 09:38:30 -07001247 if (outputDevices.onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_TELEPHONY_TX) &&
François Gaffiec005e562018-11-06 15:04:49 +01001248 (*stream == AUDIO_STREAM_MUSIC || resultAttr->usage == AUDIO_USAGE_VOICE_COMMUNICATION) &&
Nadav Barb2f18162018-07-18 13:01:53 +03001249 audio_is_linear_pcm(config->format) &&
Eric Laurent74b71512019-11-06 17:21:57 -08001250 isCallAudioAccessible()) {
Francois Gaffie716e1432019-01-14 16:58:59 +01001251 if (requestedPortId != AUDIO_PORT_HANDLE_NONE) {
Nadav Barb2f18162018-07-18 13:01:53 +03001252 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_INCALL_MUSIC;
François Gaffief579db52018-11-13 11:25:16 +01001253 *isRequestedDeviceForExclusiveUse = true;
Nadav Barb2f18162018-07-18 13:01:53 +03001254 }
1255 }
1256
François Gaffiec005e562018-11-06 15:04:49 +01001257 ALOGV("%s() device %s, sampling rate %d, format %#x, channel mask %#x, flags %#x stream %s",
1258 __func__, outputDevices.toString().c_str(), config->sample_rate, config->format,
1259 config->channel_mask, *flags, toString(*stream).c_str());
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001260
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001261 *output = AUDIO_IO_HANDLE_NONE;
François Gaffie11d30102018-11-02 16:09:09 +01001262 if (!msdDevices.isEmpty()) {
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001263 *output = getOutputForDevices(msdDevices, session, resultAttr, config, flags, isSpatialized);
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001264 if (*output != AUDIO_IO_HANDLE_NONE && setMsdOutputPatches(&outputDevices) == NO_ERROR) {
François Gaffiec005e562018-11-06 15:04:49 +01001265 ALOGV("%s() Using MSD devices %s instead of devices %s",
1266 __func__, msdDevices.toString().c_str(), outputDevices.toString().c_str());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001267 } else {
1268 *output = AUDIO_IO_HANDLE_NONE;
1269 }
1270 }
1271 if (*output == AUDIO_IO_HANDLE_NONE) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001272 *output = getOutputForDevices(outputDevices, session, resultAttr, config,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001273 flags, isSpatialized, resultAttr->flags & AUDIO_FLAG_MUTE_HAPTIC);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001274 }
Eric Laurente83b55d2014-11-14 10:06:21 -08001275 if (*output == AUDIO_IO_HANDLE_NONE) {
jiabinf1c73972022-04-14 16:28:52 -07001276 AudioProfileVector profiles;
1277 status_t ret = getProfilesForDevices(outputDevices, profiles, *flags, false /*isInput*/);
1278 if (ret == NO_ERROR && !profiles.empty()) {
1279 config->channel_mask = profiles[0]->getChannels().empty() ? config->channel_mask
1280 : *profiles[0]->getChannels().begin();
1281 config->sample_rate = profiles[0]->getSampleRates().empty() ? config->sample_rate
1282 : *profiles[0]->getSampleRates().begin();
1283 config->format = profiles[0]->getFormat();
1284 }
Eric Laurente83b55d2014-11-14 10:06:21 -08001285 return INVALID_OPERATION;
1286 }
Paul McLeanaa981192015-03-21 09:55:15 -07001287
François Gaffiec005e562018-11-06 15:04:49 +01001288 *selectedDeviceId = getFirstDeviceId(outputDevices);
Michael Chan6fb34492020-12-08 15:44:49 +11001289 for (auto &outputDevice : outputDevices) {
1290 if (outputDevice->getId() == getConfig().getDefaultOutputDevice()->getId()) {
1291 *selectedDeviceId = outputDevice->getId();
1292 break;
1293 }
1294 }
Eric Laurent2ac76942017-06-22 17:17:09 -07001295
Eric Laurent8a1095a2019-11-08 14:44:16 -08001296 if (outputDevices.onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_TELEPHONY_TX)) {
1297 *outputType = API_OUTPUT_TELEPHONY_TX;
1298 } else {
1299 *outputType = API_OUTPUT_LEGACY;
1300 }
1301
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001302 ALOGV("%s returns output %d selectedDeviceId %d", __func__, *output, *selectedDeviceId);
1303
1304 return NO_ERROR;
1305}
1306
1307status_t AudioPolicyManager::getOutputForAttr(const audio_attributes_t *attr,
1308 audio_io_handle_t *output,
1309 audio_session_t session,
1310 audio_stream_type_t *stream,
Svet Ganov3e5f14f2021-05-13 22:51:08 +00001311 const AttributionSourceState& attributionSource,
jiabinf1c73972022-04-14 16:28:52 -07001312 audio_config_t *config,
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001313 audio_output_flags_t *flags,
1314 audio_port_handle_t *selectedDeviceId,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001315 audio_port_handle_t *portId,
Eric Laurent8a1095a2019-11-08 14:44:16 -08001316 std::vector<audio_io_handle_t> *secondaryOutputs,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001317 output_type_t *outputType,
1318 bool *isSpatialized)
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001319{
1320 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
1321 if (*portId != AUDIO_PORT_HANDLE_NONE) {
1322 return INVALID_OPERATION;
1323 }
Philip P. Moltmannbda45752020-07-17 16:41:18 -07001324 const uid_t uid = VALUE_OR_RETURN_STATUS(
Svet Ganov3e5f14f2021-05-13 22:51:08 +00001325 aidl2legacy_int32_t_uid_t(attributionSource.uid));
Francois Gaffie716e1432019-01-14 16:58:59 +01001326 const audio_port_handle_t requestedPortId = *selectedDeviceId;
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001327 audio_attributes_t resultAttr;
François Gaffief579db52018-11-13 11:25:16 +01001328 bool isRequestedDeviceForExclusiveUse = false;
Eric Laurentc529cf62020-04-17 18:19:10 -07001329 std::vector<sp<AudioPolicyMix>> secondaryMixes;
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001330 const sp<DeviceDescriptor> requestedDevice =
1331 mAvailableOutputDevices.getDeviceFromId(requestedPortId);
1332
1333 // Prevent from storing invalid requested device id in clients
1334 const audio_port_handle_t sanitizedRequestedPortId =
1335 requestedDevice != nullptr ? requestedPortId : AUDIO_PORT_HANDLE_NONE;
1336 *selectedDeviceId = sanitizedRequestedPortId;
1337
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001338 status_t status = getOutputForAttrInt(&resultAttr, output, session, attr, stream, uid,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001339 config, flags, selectedDeviceId, &isRequestedDeviceForExclusiveUse,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001340 secondaryOutputs != nullptr ? &secondaryMixes : nullptr, outputType, isSpatialized);
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001341 if (status != NO_ERROR) {
1342 return status;
1343 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001344 std::vector<wp<SwAudioOutputDescriptor>> weakSecondaryOutputDescs;
Eric Laurentc529cf62020-04-17 18:19:10 -07001345 if (secondaryOutputs != nullptr) {
1346 for (auto &secondaryMix : secondaryMixes) {
1347 sp<SwAudioOutputDescriptor> outputDesc = secondaryMix->getOutput();
1348 if (outputDesc != nullptr &&
1349 outputDesc->mIoHandle != AUDIO_IO_HANDLE_NONE) {
1350 secondaryOutputs->push_back(outputDesc->mIoHandle);
1351 weakSecondaryOutputDescs.push_back(outputDesc);
1352 }
1353 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001354 }
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001355
Eric Laurent8fc147b2018-07-22 19:13:55 -07001356 audio_config_base_t clientConfig = {.sample_rate = config->sample_rate,
Nick Desaulniersa30e3202019-10-18 13:38:23 -07001357 .channel_mask = config->channel_mask,
Eric Laurent8fc147b2018-07-22 19:13:55 -07001358 .format = config->format,
Nick Desaulniersa30e3202019-10-18 13:38:23 -07001359 };
jiabin4ef93452019-09-10 14:29:54 -07001360 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurent8f42ea12018-08-08 09:08:25 -07001361
Eric Laurentc209fe42020-06-05 18:11:23 -07001362 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(*output);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001363 sp<TrackClientDescriptor> clientDesc =
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001364 new TrackClientDescriptor(*portId, uid, session, resultAttr, clientConfig,
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001365 sanitizedRequestedPortId, *stream,
François Gaffiec005e562018-11-06 15:04:49 +01001366 mEngine->getProductStrategyForAttributes(resultAttr),
François Gaffieaaac0fd2018-11-22 17:56:39 +01001367 toVolumeSource(resultAttr),
Kevin Rocard153f92d2018-12-18 18:33:28 -08001368 *flags, isRequestedDeviceForExclusiveUse,
Eric Laurentc209fe42020-06-05 18:11:23 -07001369 std::move(weakSecondaryOutputDescs),
1370 outputDesc->mPolicyMix);
Andy Hung39efb7a2018-09-26 15:39:28 -07001371 outputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001372
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001373 ALOGV("%s() returns output %d requestedPortId %d selectedDeviceId %d for port ID %d", __func__,
1374 *output, requestedPortId, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07001375
Eric Laurente83b55d2014-11-14 10:06:21 -08001376 return NO_ERROR;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001377}
1378
Eric Laurentc529cf62020-04-17 18:19:10 -07001379status_t AudioPolicyManager::openDirectOutput(audio_stream_type_t stream,
1380 audio_session_t session,
1381 const audio_config_t *config,
1382 audio_output_flags_t flags,
1383 const DeviceVector &devices,
1384 audio_io_handle_t *output) {
1385
1386 *output = AUDIO_IO_HANDLE_NONE;
1387
1388 // skip direct output selection if the request can obviously be attached to a mixed output
1389 // and not explicitly requested
1390 if (((flags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
1391 audio_is_linear_pcm(config->format) && config->sample_rate <= SAMPLE_RATE_HZ_MAX &&
1392 audio_channel_count_from_out_mask(config->channel_mask) <= 2) {
1393 return NAME_NOT_FOUND;
1394 }
1395
1396 // Do not allow offloading if one non offloadable effect is enabled or MasterMono is enabled.
1397 // This prevents creating an offloaded track and tearing it down immediately after start
1398 // when audioflinger detects there is an active non offloadable effect.
1399 // FIXME: We should check the audio session here but we do not have it in this context.
1400 // This may prevent offloading in rare situations where effects are left active by apps
1401 // in the background.
1402 sp<IOProfile> profile;
1403 if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) ||
1404 !(mEffects.isNonOffloadableEffectEnabled() || mMasterMono)) {
1405 profile = getProfileForOutput(
1406 devices, config->sample_rate, config->format, config->channel_mask,
1407 flags, true /* directOnly */);
1408 }
1409
1410 if (profile == nullptr) {
1411 return NAME_NOT_FOUND;
1412 }
1413
1414 // exclusive outputs for MMAP and Offload are enforced by different session ids.
1415 for (size_t i = 0; i < mOutputs.size(); i++) {
1416 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
1417 if (!desc->isDuplicated() && (profile == desc->mProfile)) {
1418 // reuse direct output if currently open by the same client
1419 // and configured with same parameters
1420 if ((config->sample_rate == desc->getSamplingRate()) &&
1421 (config->format == desc->getFormat()) &&
1422 (config->channel_mask == desc->getChannelMask()) &&
1423 (session == desc->mDirectClientSession)) {
1424 desc->mDirectOpenCount++;
Eric Laurentfecbceb2021-02-09 14:46:43 +01001425 ALOGV("%s reusing direct output %d for session %d", __func__,
Eric Laurentc529cf62020-04-17 18:19:10 -07001426 mOutputs.keyAt(i), session);
1427 *output = mOutputs.keyAt(i);
1428 return NO_ERROR;
1429 }
1430 }
1431 }
1432
1433 if (!profile->canOpenNewIo()) {
1434 return NAME_NOT_FOUND;
1435 }
1436
1437 sp<SwAudioOutputDescriptor> outputDesc =
1438 new SwAudioOutputDescriptor(profile, mpClientInterface);
1439
Michael Chan6fb34492020-12-08 15:44:49 +11001440 // An MSD patch may be using the only output stream that can service this request. Release
1441 // all MSD patches to prioritize this request over any active output on MSD.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001442 releaseMsdOutputPatches(devices);
Eric Laurentc529cf62020-04-17 18:19:10 -07001443
Eric Laurentf1f22e72021-07-13 14:04:14 +02001444 status_t status =
1445 outputDesc->open(config, nullptr /* mixerConfig */, devices, stream, flags, output);
Eric Laurentc529cf62020-04-17 18:19:10 -07001446
1447 // only accept an output with the requested parameters
1448 if (status != NO_ERROR ||
1449 (config->sample_rate != 0 && config->sample_rate != outputDesc->getSamplingRate()) ||
1450 (config->format != AUDIO_FORMAT_DEFAULT && config->format != outputDesc->getFormat()) ||
1451 (config->channel_mask != 0 && config->channel_mask != outputDesc->getChannelMask())) {
1452 ALOGV("%s failed opening direct output: output %d sample rate %d %d,"
1453 "format %d %d, channel mask %04x %04x", __func__, *output, config->sample_rate,
1454 outputDesc->getSamplingRate(), config->format, outputDesc->getFormat(),
1455 config->channel_mask, outputDesc->getChannelMask());
1456 if (*output != AUDIO_IO_HANDLE_NONE) {
1457 outputDesc->close();
1458 }
1459 // fall back to mixer output if possible when the direct output could not be open
1460 if (audio_is_linear_pcm(config->format) &&
1461 config->sample_rate <= SAMPLE_RATE_HZ_MAX) {
1462 return NAME_NOT_FOUND;
1463 }
1464 *output = AUDIO_IO_HANDLE_NONE;
1465 return BAD_VALUE;
1466 }
1467 outputDesc->mDirectOpenCount = 1;
1468 outputDesc->mDirectClientSession = session;
1469
1470 addOutput(*output, outputDesc);
1471 mPreviousOutputs = mOutputs;
1472 ALOGV("%s returns new direct output %d", __func__, *output);
1473 mpClientInterface->onAudioPortListUpdate();
1474 return NO_ERROR;
1475}
1476
François Gaffie11d30102018-11-02 16:09:09 +01001477audio_io_handle_t AudioPolicyManager::getOutputForDevices(
1478 const DeviceVector &devices,
Kevin Rocard169753c2017-03-06 14:18:23 -08001479 audio_session_t session,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001480 const audio_attributes_t *attr,
Eric Laurentfe231122017-11-17 17:48:06 -08001481 const audio_config_t *config,
jiabine375d412019-02-26 12:54:53 -08001482 audio_output_flags_t *flags,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001483 bool *isSpatialized,
jiabine375d412019-02-26 12:54:53 -08001484 bool forceMutingHaptic)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001485{
Andy Hungc88b0642018-04-27 15:42:35 -07001486 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001487
jiabine375d412019-02-26 12:54:53 -08001488 // Discard haptic channel mask when forcing muting haptic channels.
1489 audio_channel_mask_t channelMask = forceMutingHaptic
Mikhail Naganov55773032020-10-01 15:08:13 -07001490 ? static_cast<audio_channel_mask_t>(config->channel_mask & ~AUDIO_CHANNEL_HAPTIC_ALL)
1491 : config->channel_mask;
jiabine375d412019-02-26 12:54:53 -08001492
Eric Laurente552edb2014-03-10 17:42:56 -07001493 // open a direct output if required by specified parameters
1494 //force direct flag if offload flag is set: offloading implies a direct output stream
1495 // and all common behaviors are driven by checking only the direct flag
1496 // this should normally be set appropriately in the policy configuration file
Nadav Bar766fb022018-01-07 12:18:03 +02001497 if ((*flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1498 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurente552edb2014-03-10 17:42:56 -07001499 }
Nadav Bar766fb022018-01-07 12:18:03 +02001500 if ((*flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
1501 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent93c3d412014-08-01 14:48:35 -07001502 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001503
1504 audio_stream_type_t stream = mEngine->getStreamTypeForAttributes(*attr);
1505
Eric Laurente83b55d2014-11-14 10:06:21 -08001506 // only allow deep buffering for music stream type
1507 if (stream != AUDIO_STREAM_MUSIC) {
Nadav Bar766fb022018-01-07 12:18:03 +02001508 *flags = (audio_output_flags_t)(*flags &~AUDIO_OUTPUT_FLAG_DEEP_BUFFER);
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -07001509 } else if (/* stream == AUDIO_STREAM_MUSIC && */
Nadav Bar766fb022018-01-07 12:18:03 +02001510 *flags == AUDIO_OUTPUT_FLAG_NONE &&
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -07001511 property_get_bool("audio.deep_buffer.media", false /* default_value */)) {
1512 // use DEEP_BUFFER as default output for music stream type
Nadav Bar766fb022018-01-07 12:18:03 +02001513 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
Eric Laurente83b55d2014-11-14 10:06:21 -08001514 }
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -07001515 if (stream == AUDIO_STREAM_TTS) {
Nadav Bar766fb022018-01-07 12:18:03 +02001516 *flags = AUDIO_OUTPUT_FLAG_TTS;
Haynes Mathew George84c621e2017-04-25 11:41:50 -07001517 } else if (stream == AUDIO_STREAM_VOICE_CALL &&
Nadav Bar20919492018-11-20 10:20:51 +02001518 audio_is_linear_pcm(config->format) &&
1519 (*flags & AUDIO_OUTPUT_FLAG_INCALL_MUSIC) == 0) {
Nadav Bar766fb022018-01-07 12:18:03 +02001520 *flags = (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_VOIP_RX |
Haynes Mathew George84c621e2017-04-25 11:41:50 -07001521 AUDIO_OUTPUT_FLAG_DIRECT);
1522 ALOGV("Set VoIP and Direct output flags for PCM format");
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -07001523 }
Eric Laurente552edb2014-03-10 17:42:56 -07001524
Carter Hsua3abb402021-10-26 11:11:20 +08001525 // Attach the Ultrasound flag for the AUDIO_CONTENT_TYPE_ULTRASOUND
1526 if (attr->content_type == AUDIO_CONTENT_TYPE_ULTRASOUND) {
1527 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_ULTRASOUND);
1528 }
1529
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001530 *isSpatialized = false;
Eric Laurentfa0f6742021-08-17 18:39:44 +02001531 if (mSpatializerOutput != nullptr
Andy Hung9dd1a5b2022-05-10 15:39:39 -07001532 && canBeSpatializedInt(attr, config, devices.toTypeAddrVector())) {
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001533 *isSpatialized = true;
Eric Laurentfa0f6742021-08-17 18:39:44 +02001534 return mSpatializerOutput->mIoHandle;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001535 }
1536
Eric Laurentc529cf62020-04-17 18:19:10 -07001537 audio_config_t directConfig = *config;
1538 directConfig.channel_mask = channelMask;
1539 status_t status = openDirectOutput(stream, session, &directConfig, *flags, devices, &output);
1540 if (status != NAME_NOT_FOUND) {
Eric Laurente552edb2014-03-10 17:42:56 -07001541 return output;
1542 }
1543
Eric Laurent14cbfca2016-03-17 09:42:16 -07001544 // A request for HW A/V sync cannot fallback to a mixed output because time
1545 // stamps are embedded in audio data
Phil Burk2d059932018-02-15 15:55:11 -08001546 if ((*flags & (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ)) != 0) {
Eric Laurent14cbfca2016-03-17 09:42:16 -07001547 return AUDIO_IO_HANDLE_NONE;
1548 }
1549
Eric Laurente552edb2014-03-10 17:42:56 -07001550 // ignoring channel mask due to downmix capability in mixer
1551
1552 // open a non direct output
1553
1554 // for non direct outputs, only PCM is supported
Eric Laurentfe231122017-11-17 17:48:06 -08001555 if (audio_is_linear_pcm(config->format)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001556 // get which output is suitable for the specified stream. The actual
1557 // routing change will happen when startOutput() will be called
François Gaffie11d30102018-11-02 16:09:09 +01001558 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07001559
Eric Laurent8838a382014-09-08 16:44:28 -07001560 // at this stage we should ignore the DIRECT flag as no direct output could be found earlier
Nadav Bar766fb022018-01-07 12:18:03 +02001561 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
jiabinebb6af42020-06-09 17:31:17 -07001562 output = selectOutput(
1563 outputs, *flags, config->format, channelMask, config->sample_rate, session);
Eric Laurente552edb2014-03-10 17:42:56 -07001564 }
François Gaffie11d30102018-11-02 16:09:09 +01001565 ALOGW_IF((output == 0), "getOutputForDevices() could not find output for stream %d, "
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001566 "sampling rate %d, format %#x, channels %#x, flags %#x",
jiabine375d412019-02-26 12:54:53 -08001567 stream, config->sample_rate, config->format, channelMask, *flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001568
Eric Laurente552edb2014-03-10 17:42:56 -07001569 return output;
1570}
1571
Mikhail Naganovf02f3672018-11-09 12:44:16 -08001572sp<DeviceDescriptor> AudioPolicyManager::getMsdAudioInDevice() const {
François Gaffie11d30102018-11-02 16:09:09 +01001573 auto msdInDevices = mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1574 mAvailableInputDevices);
1575 return msdInDevices.isEmpty()? nullptr : msdInDevices.itemAt(0);
1576}
1577
1578DeviceVector AudioPolicyManager::getMsdAudioOutDevices() const {
1579 return mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1580 mAvailableOutputDevices);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001581}
1582
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001583const AudioPatchCollection AudioPolicyManager::getMsdOutputPatches() const {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001584 AudioPatchCollection msdPatches;
Mikhail Naganov86112352018-10-04 09:02:49 -07001585 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1586 if (msdModule != 0) {
1587 for (size_t i = 0; i < mAudioPatches.size(); ++i) {
1588 sp<AudioPatch> patch = mAudioPatches.valueAt(i);
1589 for (size_t j = 0; j < patch->mPatch.num_sources; ++j) {
1590 const struct audio_port_config *source = &patch->mPatch.sources[j];
1591 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
1592 source->ext.device.hw_module == msdModule->getHandle()) {
François Gaffieafd4cea2019-11-18 15:50:22 +01001593 msdPatches.addAudioPatch(patch->getHandle(), patch);
Mikhail Naganov86112352018-10-04 09:02:49 -07001594 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001595 }
1596 }
1597 }
1598 return msdPatches;
1599}
1600
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02001601bool AudioPolicyManager::isMsdPatch(const audio_patch_handle_t &handle) const {
1602 ssize_t index = mAudioPatches.indexOfKey(handle);
1603 if (index < 0) {
1604 return false;
1605 }
1606 const sp<AudioPatch> patch = mAudioPatches.valueAt(index);
1607 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1608 if (msdModule == nullptr) {
1609 return false;
1610 }
1611 const struct audio_port_config *sink = &patch->mPatch.sinks[0];
1612 if (getMsdAudioOutDevices().contains(mAvailableOutputDevices.getDeviceFromId(sink->id))) {
1613 return true;
1614 }
1615 index = getMsdOutputPatches().indexOfKey(handle);
1616 if (index < 0) {
1617 return false;
1618 }
1619 return true;
1620}
1621
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001622status_t AudioPolicyManager::getMsdProfiles(bool hwAvSync,
1623 const InputProfileCollection &inputProfiles,
1624 const OutputProfileCollection &outputProfiles,
1625 const sp<DeviceDescriptor> &sourceDevice,
1626 const sp<DeviceDescriptor> &sinkDevice,
1627 AudioProfileVector& sourceProfiles,
1628 AudioProfileVector& sinkProfiles) const {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001629 if (inputProfiles.isEmpty()) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001630 ALOGE("%s() no input profiles for source module", __func__);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001631 return NO_INIT;
1632 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001633 if (outputProfiles.isEmpty()) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001634 ALOGE("%s() no output profiles for sink module", __func__);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001635 return NO_INIT;
1636 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001637 for (const auto &inProfile : inputProfiles) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001638 if (hwAvSync == ((inProfile->getFlags() & AUDIO_INPUT_FLAG_HW_AV_SYNC) != 0) &&
1639 inProfile->supportsDevice(sourceDevice)) {
1640 appendAudioProfiles(sourceProfiles, inProfile->getAudioProfiles());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001641 }
1642 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001643 for (const auto &outProfile : outputProfiles) {
Michael Chan6fb34492020-12-08 15:44:49 +11001644 if (hwAvSync == ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) &&
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001645 outProfile->supportsDevice(sinkDevice)) {
1646 appendAudioProfiles(sinkProfiles, outProfile->getAudioProfiles());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001647 }
1648 }
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001649 return NO_ERROR;
1650}
1651
1652status_t AudioPolicyManager::getBestMsdConfig(bool hwAvSync,
1653 const AudioProfileVector &sourceProfiles, const AudioProfileVector &sinkProfiles,
1654 audio_port_config *sourceConfig, audio_port_config *sinkConfig) const
1655{
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001656 struct audio_config_base bestSinkConfig;
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001657 status_t result = findBestMatchingOutputConfig(sourceProfiles, sinkProfiles,
1658 msdCompressedFormatsOrder, msdSurroundChannelMasksOrder,
1659 true /*preferHigherSamplingRates*/, bestSinkConfig);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001660 if (result != NO_ERROR) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001661 ALOGD("%s() no matching config found for sink, hwAvSync: %d",
1662 __func__, hwAvSync);
Greg Kaiser83289652018-07-30 06:13:57 -07001663 return result;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001664 }
1665 sinkConfig->sample_rate = bestSinkConfig.sample_rate;
1666 sinkConfig->channel_mask = bestSinkConfig.channel_mask;
1667 sinkConfig->format = bestSinkConfig.format;
1668 // For encoded streams force direct flag to prevent downstream mixing.
1669 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1670 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_DIRECT);
Dean Wheatley5c9f0832019-11-21 13:39:31 +11001671 if (audio_is_iec61937_compatible(sinkConfig->format)) {
1672 // For formats compatible with IEC61937 encapsulation, assume that
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001673 // the input is IEC61937 framed (for proportional buffer sizing).
Dean Wheatley5c9f0832019-11-21 13:39:31 +11001674 // Add the AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO flag so downstream HAL can distinguish between
1675 // raw and IEC61937 framed streams.
1676 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1677 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO);
1678 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001679 sourceConfig->sample_rate = bestSinkConfig.sample_rate;
1680 // Specify exact channel mask to prevent guessing by bit count in PatchPanel.
1681 sourceConfig->channel_mask = audio_channel_mask_out_to_in(bestSinkConfig.channel_mask);
1682 sourceConfig->format = bestSinkConfig.format;
1683 // Copy input stream directly without any processing (e.g. resampling).
1684 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1685 sourceConfig->flags.input | AUDIO_INPUT_FLAG_DIRECT);
1686 if (hwAvSync) {
1687 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1688 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
1689 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1690 sourceConfig->flags.input | AUDIO_INPUT_FLAG_HW_AV_SYNC);
1691 }
1692 const unsigned int config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE |
1693 AUDIO_PORT_CONFIG_CHANNEL_MASK | AUDIO_PORT_CONFIG_FORMAT | AUDIO_PORT_CONFIG_FLAGS;
1694 sinkConfig->config_mask |= config_mask;
1695 sourceConfig->config_mask |= config_mask;
1696 return NO_ERROR;
1697}
1698
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001699PatchBuilder AudioPolicyManager::buildMsdPatch(bool msdIsSource,
1700 const sp<DeviceDescriptor> &device) const
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001701{
1702 PatchBuilder patchBuilder;
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001703 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1704 ALOG_ASSERT(msdModule != nullptr, "MSD module not available");
1705 sp<HwModule> deviceModule = mHwModules.getModuleForDevice(device, AUDIO_FORMAT_DEFAULT);
1706 if (deviceModule == nullptr) {
1707 ALOGE("%s() unable to get module for %s", __func__, device->toString().c_str());
1708 return patchBuilder;
1709 }
1710 const InputProfileCollection inputProfiles = msdIsSource ?
1711 msdModule->getInputProfiles() : deviceModule->getInputProfiles();
1712 const OutputProfileCollection outputProfiles = msdIsSource ?
1713 deviceModule->getOutputProfiles() : msdModule->getOutputProfiles();
1714
1715 const sp<DeviceDescriptor> sourceDevice = msdIsSource ? getMsdAudioInDevice() : device;
1716 const sp<DeviceDescriptor> sinkDevice = msdIsSource ?
1717 device : getMsdAudioOutDevices().itemAt(0);
1718 patchBuilder.addSource(sourceDevice).addSink(sinkDevice);
1719
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001720 audio_port_config sourceConfig = patchBuilder.patch()->sources[0];
1721 audio_port_config sinkConfig = patchBuilder.patch()->sinks[0];
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001722 AudioProfileVector sourceProfiles;
1723 AudioProfileVector sinkProfiles;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001724 // TODO: Figure out whether MSD module has HW_AV_SYNC flag set in the AP config file.
1725 // For now, we just forcefully try with HwAvSync first.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001726 for (auto hwAvSync : { true, false }) {
1727 if (getMsdProfiles(hwAvSync, inputProfiles, outputProfiles, sourceDevice, sinkDevice,
1728 sourceProfiles, sinkProfiles) != NO_ERROR) {
1729 continue;
1730 }
1731 if (getBestMsdConfig(hwAvSync, sourceProfiles, sinkProfiles, &sourceConfig,
1732 &sinkConfig) == NO_ERROR) {
1733 // Found a matching config. Re-create PatchBuilder with this config.
1734 return (PatchBuilder()).addSource(sourceConfig).addSink(sinkConfig);
1735 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001736 }
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001737 ALOGV("%s() no matching config found. Fall through to default PCM patch"
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001738 " supporting PCM format conversion.", __func__);
1739 return patchBuilder;
1740}
1741
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001742status_t AudioPolicyManager::setMsdOutputPatches(const DeviceVector *outputDevices) {
Michael Chan6fb34492020-12-08 15:44:49 +11001743 DeviceVector devices;
1744 if (outputDevices != nullptr && outputDevices->size() > 0) {
1745 devices.add(*outputDevices);
1746 } else {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001747 // Use media strategy for unspecified output device. This should only
1748 // occur on checkForDeviceAndOutputChanges(). Device connection events may
1749 // therefore invalidate explicit routing requests.
Michael Chan6fb34492020-12-08 15:44:49 +11001750 devices = mEngine->getOutputDevicesForAttributes(
François Gaffiec005e562018-11-06 15:04:49 +01001751 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
Michael Chan6fb34492020-12-08 15:44:49 +11001752 LOG_ALWAYS_FATAL_IF(devices.isEmpty(), "no output device to set MSD patch");
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001753 }
Michael Chan6fb34492020-12-08 15:44:49 +11001754 std::vector<PatchBuilder> patchesToCreate;
1755 for (auto i = 0u; i < devices.size(); ++i) {
1756 ALOGV("%s() for device %s", __func__, devices[i]->toString().c_str());
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001757 patchesToCreate.push_back(buildMsdPatch(true /*msdIsSource*/, devices[i]));
Michael Chan6fb34492020-12-08 15:44:49 +11001758 }
1759 // Retain only the MSD patches associated with outputDevices request.
1760 // Tear down the others, and create new ones as needed.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001761 AudioPatchCollection patchesToRemove = getMsdOutputPatches();
Michael Chan6fb34492020-12-08 15:44:49 +11001762 for (auto it = patchesToCreate.begin(); it != patchesToCreate.end(); ) {
1763 auto retainedPatch = false;
1764 for (auto i = 0u; i < patchesToRemove.size(); ++i) {
1765 if (audio_patches_are_equal(it->patch(), &patchesToRemove[i]->mPatch)) {
1766 patchesToRemove.removeItemsAt(i);
1767 retainedPatch = true;
1768 break;
1769 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001770 }
Michael Chan6fb34492020-12-08 15:44:49 +11001771 if (retainedPatch) {
1772 it = patchesToCreate.erase(it);
1773 continue;
1774 }
1775 ++it;
1776 }
1777 if (patchesToCreate.size() == 0 && patchesToRemove.size() == 0) {
1778 return NO_ERROR;
1779 }
1780 for (auto i = 0u; i < patchesToRemove.size(); ++i) {
1781 auto &currentPatch = patchesToRemove.valueAt(i);
François Gaffieafd4cea2019-11-18 15:50:22 +01001782 releaseAudioPatch(currentPatch->getHandle(), mUidCached);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001783 }
Michael Chan6fb34492020-12-08 15:44:49 +11001784 status_t status = NO_ERROR;
1785 for (const auto &p : patchesToCreate) {
1786 auto currStatus = installPatch(__func__, -1 /*index*/, nullptr /*patchHandle*/,
1787 p.patch(), 0 /*delayMs*/, mUidCached, nullptr /*patchDescPtr*/);
1788 char message[256];
1789 snprintf(message, sizeof(message), "%s() %s: creating MSD patch from device:IN_BUS to "
1790 "device:%#x (format:%#x channels:%#x samplerate:%d)", __func__,
1791 currStatus == NO_ERROR ? "Success" : "Error",
1792 p.patch()->sinks[0].ext.device.type, p.patch()->sources[0].format,
1793 p.patch()->sources[0].channel_mask, p.patch()->sources[0].sample_rate);
1794 if (currStatus == NO_ERROR) {
1795 ALOGD("%s", message);
1796 } else {
1797 ALOGE("%s", message);
1798 if (status == NO_ERROR) {
1799 status = currStatus;
1800 }
1801 }
1802 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001803 return status;
1804}
1805
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001806void AudioPolicyManager::releaseMsdOutputPatches(const DeviceVector& devices) {
1807 AudioPatchCollection msdPatches = getMsdOutputPatches();
Michael Chan6fb34492020-12-08 15:44:49 +11001808 for (size_t i = 0; i < msdPatches.size(); i++) {
1809 const auto& patch = msdPatches[i];
1810 for (size_t j = 0; j < patch->mPatch.num_sinks; ++j) {
1811 const struct audio_port_config *sink = &patch->mPatch.sinks[j];
1812 if (sink->type == AUDIO_PORT_TYPE_DEVICE && devices.getDevice(sink->ext.device.type,
1813 String8(sink->ext.device.address), AUDIO_FORMAT_DEFAULT) != nullptr) {
1814 releaseAudioPatch(patch->getHandle(), mUidCached);
1815 break;
1816 }
1817 }
1818 }
1819}
1820
Dorin Drimus94d94412022-02-02 09:05:02 +01001821bool AudioPolicyManager::msdHasPatchesToAllDevices(const AudioDeviceTypeAddrVector& devices) {
1822 DeviceVector devicesToCheck = mOutputDevicesAll.getDevicesFromDeviceTypeAddrVec(devices);
1823 AudioPatchCollection msdPatches = getMsdOutputPatches();
1824 for (size_t i = 0; i < msdPatches.size(); i++) {
1825 const auto& patch = msdPatches[i];
1826 for (size_t j = 0; j < patch->mPatch.num_sinks; ++j) {
1827 const struct audio_port_config *sink = &patch->mPatch.sinks[j];
1828 if (sink->type == AUDIO_PORT_TYPE_DEVICE) {
1829 const auto& foundDevice = devicesToCheck.getDevice(
1830 sink->ext.device.type, String8(sink->ext.device.address), AUDIO_FORMAT_DEFAULT);
1831 if (foundDevice != nullptr) {
1832 devicesToCheck.remove(foundDevice);
1833 if (devicesToCheck.isEmpty()) {
1834 return true;
1835 }
1836 }
1837 }
1838 }
1839 }
1840 return false;
1841}
1842
Eric Laurente0720872014-03-11 09:30:41 -07001843audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
jiabinebb6af42020-06-09 17:31:17 -07001844 audio_output_flags_t flags,
1845 audio_format_t format,
1846 audio_channel_mask_t channelMask,
1847 uint32_t samplingRate,
1848 audio_session_t sessionId)
Eric Laurente552edb2014-03-10 17:42:56 -07001849{
Eric Laurent16c66dd2019-05-01 17:54:10 -07001850 LOG_ALWAYS_FATAL_IF(!(format == AUDIO_FORMAT_INVALID || audio_is_linear_pcm(format)),
1851 "%s called with format %#x", __func__, format);
1852
jiabinebb6af42020-06-09 17:31:17 -07001853 // Return the output that haptic-generating attached to when 1) session id is specified,
1854 // 2) haptic-generating effect exists for given session id and 3) the output that
1855 // haptic-generating effect attached to is in given outputs.
1856 if (sessionId != AUDIO_SESSION_NONE) {
1857 audio_io_handle_t hapticGeneratingOutput = mEffects.getIoForSession(
1858 sessionId, FX_IID_HAPTICGENERATOR);
1859 if (outputs.indexOf(hapticGeneratingOutput) >= 0) {
1860 return hapticGeneratingOutput;
1861 }
1862 }
1863
Eric Laurent16c66dd2019-05-01 17:54:10 -07001864 // Flags disqualifying an output: the match must happen before calling selectOutput()
1865 static const audio_output_flags_t kExcludedFlags = (audio_output_flags_t)
1866 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ | AUDIO_OUTPUT_FLAG_DIRECT);
1867
1868 // Flags expressing a functional request: must be honored in priority over
1869 // other criteria
1870 static const audio_output_flags_t kFunctionalFlags = (audio_output_flags_t)
1871 (AUDIO_OUTPUT_FLAG_VOIP_RX | AUDIO_OUTPUT_FLAG_INCALL_MUSIC |
Eric Laurente28c66d2022-01-21 13:40:41 +01001872 AUDIO_OUTPUT_FLAG_TTS | AUDIO_OUTPUT_FLAG_DIRECT_PCM | AUDIO_OUTPUT_FLAG_ULTRASOUND |
1873 AUDIO_OUTPUT_FLAG_SPATIALIZER);
Eric Laurent16c66dd2019-05-01 17:54:10 -07001874 // Flags expressing a performance request: have lower priority than serving
1875 // requested sampling rate or channel mask
1876 static const audio_output_flags_t kPerformanceFlags = (audio_output_flags_t)
1877 (AUDIO_OUTPUT_FLAG_FAST | AUDIO_OUTPUT_FLAG_DEEP_BUFFER |
1878 AUDIO_OUTPUT_FLAG_RAW | AUDIO_OUTPUT_FLAG_SYNC);
1879
1880 const audio_output_flags_t functionalFlags =
1881 (audio_output_flags_t)(flags & kFunctionalFlags);
1882 const audio_output_flags_t performanceFlags =
1883 (audio_output_flags_t)(flags & kPerformanceFlags);
1884
1885 audio_io_handle_t bestOutput = (outputs.size() == 0) ? AUDIO_IO_HANDLE_NONE : outputs[0];
1886
Eric Laurente552edb2014-03-10 17:42:56 -07001887 // select one output among several that provide a path to a particular device or set of
François Gaffie11d30102018-11-02 16:09:09 +01001888 // devices (the list was previously build by getOutputsForDevices()).
Eric Laurente552edb2014-03-10 17:42:56 -07001889 // The priority is as follows:
jiabin40573322018-11-08 12:08:02 -08001890 // 1: the output supporting haptic playback when requesting haptic playback
Eric Laurent16c66dd2019-05-01 17:54:10 -07001891 // 2: the output with the highest number of requested functional flags
Carter Hsu199f1892021-10-15 15:47:29 +08001892 // with tiebreak preferring the minimum number of extra functional flags
1893 // (see b/200293124, the incorrect selection of AUDIO_OUTPUT_FLAG_VOIP_RX).
Eric Laurent16c66dd2019-05-01 17:54:10 -07001894 // 3: the output supporting the exact channel mask
1895 // 4: the output with a higher channel count than requested
jiabinb12a6da2022-06-03 20:48:18 +00001896 // 5: the output with the highest sampling rate if the requested sample rate is
1897 // greater than default sampling rate
Eric Laurent16c66dd2019-05-01 17:54:10 -07001898 // 6: the output with the highest number of requested performance flags
1899 // 7: the output with the bit depth the closest to the requested one
1900 // 8: the primary output
1901 // 9: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07001902
Eric Laurent16c66dd2019-05-01 17:54:10 -07001903 // matching criteria values in priority order for best matching output so far
1904 std::vector<uint32_t> bestMatchCriteria(8, 0);
Eric Laurente552edb2014-03-10 17:42:56 -07001905
Eric Laurent16c66dd2019-05-01 17:54:10 -07001906 const uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
1907 const uint32_t hapticChannelCount = audio_channel_count_from_out_mask(
1908 channelMask & AUDIO_CHANNEL_HAPTIC_ALL);
Eric Laurente78b6762018-12-19 16:29:01 -08001909
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001910 for (audio_io_handle_t output : outputs) {
1911 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent16c66dd2019-05-01 17:54:10 -07001912 // matching criteria values in priority order for current output
1913 std::vector<uint32_t> currentMatchCriteria(8, 0);
jiabin40573322018-11-08 12:08:02 -08001914
Eric Laurent16c66dd2019-05-01 17:54:10 -07001915 if (outputDesc->isDuplicated()) {
1916 continue;
1917 }
1918 if ((kExcludedFlags & outputDesc->mFlags) != 0) {
1919 continue;
1920 }
Eric Laurent8838a382014-09-08 16:44:28 -07001921
Eric Laurent16c66dd2019-05-01 17:54:10 -07001922 // If haptic channel is specified, use the haptic output if present.
1923 // When using haptic output, same audio format and sample rate are required.
1924 const uint32_t outputHapticChannelCount = audio_channel_count_from_out_mask(
jiabin5740f082019-08-19 15:08:30 -07001925 outputDesc->getChannelMask() & AUDIO_CHANNEL_HAPTIC_ALL);
Eric Laurent16c66dd2019-05-01 17:54:10 -07001926 if ((hapticChannelCount == 0) != (outputHapticChannelCount == 0)) {
1927 continue;
1928 }
1929 if (outputHapticChannelCount >= hapticChannelCount
jiabin5740f082019-08-19 15:08:30 -07001930 && format == outputDesc->getFormat()
1931 && samplingRate == outputDesc->getSamplingRate()) {
Eric Laurent16c66dd2019-05-01 17:54:10 -07001932 currentMatchCriteria[0] = outputHapticChannelCount;
1933 }
1934
1935 // functional flags match
Carter Hsu199f1892021-10-15 15:47:29 +08001936 const int matchingFunctionalFlags =
1937 __builtin_popcount(outputDesc->mFlags & functionalFlags);
1938 const int totalFunctionalFlags =
1939 __builtin_popcount(outputDesc->mFlags & kFunctionalFlags);
1940 // Prefer matching functional flags, but subtract unnecessary functional flags.
1941 currentMatchCriteria[1] = 100 * (matchingFunctionalFlags + 1) - totalFunctionalFlags;
Eric Laurent16c66dd2019-05-01 17:54:10 -07001942
1943 // channel mask and channel count match
jiabin5740f082019-08-19 15:08:30 -07001944 uint32_t outputChannelCount = audio_channel_count_from_out_mask(
1945 outputDesc->getChannelMask());
Eric Laurent16c66dd2019-05-01 17:54:10 -07001946 if (channelMask != AUDIO_CHANNEL_NONE && channelCount > 2 &&
1947 channelCount <= outputChannelCount) {
1948 if ((audio_channel_mask_get_representation(channelMask) ==
jiabin5740f082019-08-19 15:08:30 -07001949 audio_channel_mask_get_representation(outputDesc->getChannelMask())) &&
1950 ((channelMask & outputDesc->getChannelMask()) == channelMask)) {
Eric Laurent16c66dd2019-05-01 17:54:10 -07001951 currentMatchCriteria[2] = outputChannelCount;
Eric Laurente552edb2014-03-10 17:42:56 -07001952 }
Eric Laurent16c66dd2019-05-01 17:54:10 -07001953 currentMatchCriteria[3] = outputChannelCount;
1954 }
1955
1956 // sampling rate match
jiabinb12a6da2022-06-03 20:48:18 +00001957 if (samplingRate > SAMPLE_RATE_HZ_DEFAULT) {
jiabin5740f082019-08-19 15:08:30 -07001958 currentMatchCriteria[4] = outputDesc->getSamplingRate();
Eric Laurent16c66dd2019-05-01 17:54:10 -07001959 }
1960
1961 // performance flags match
1962 currentMatchCriteria[5] = popcount(outputDesc->mFlags & performanceFlags);
1963
1964 // format match
1965 if (format != AUDIO_FORMAT_INVALID) {
1966 currentMatchCriteria[6] =
jiabin4ef93452019-09-10 14:29:54 -07001967 PolicyAudioPort::kFormatDistanceMax -
1968 PolicyAudioPort::formatDistance(format, outputDesc->getFormat());
Eric Laurent16c66dd2019-05-01 17:54:10 -07001969 }
1970
1971 // primary output match
1972 currentMatchCriteria[7] = outputDesc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY;
1973
1974 // compare match criteria by priority then value
1975 if (std::lexicographical_compare(bestMatchCriteria.begin(), bestMatchCriteria.end(),
1976 currentMatchCriteria.begin(), currentMatchCriteria.end())) {
1977 bestMatchCriteria = currentMatchCriteria;
1978 bestOutput = output;
1979
1980 std::stringstream result;
1981 std::copy(bestMatchCriteria.begin(), bestMatchCriteria.end(),
1982 std::ostream_iterator<int>(result, " "));
1983 ALOGV("%s new bestOutput %d criteria %s",
1984 __func__, bestOutput, result.str().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07001985 }
1986 }
1987
Eric Laurent16c66dd2019-05-01 17:54:10 -07001988 return bestOutput;
Eric Laurente552edb2014-03-10 17:42:56 -07001989}
1990
Eric Laurent8fc147b2018-07-22 19:13:55 -07001991status_t AudioPolicyManager::startOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07001992{
Eric Laurent8fc147b2018-07-22 19:13:55 -07001993 ALOGV("%s portId %d", __FUNCTION__, portId);
1994
1995 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
1996 if (outputDesc == 0) {
1997 ALOGW("startOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001998 return BAD_VALUE;
1999 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002000 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002001
Eric Laurent8fc147b2018-07-22 19:13:55 -07002002 ALOGV("startOutput() output %d, stream %d, session %d",
Eric Laurent97ac8712018-07-27 18:59:02 -07002003 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurentc75307b2015-03-17 15:29:32 -07002004
Eric Laurent733ce942017-12-07 12:18:25 -08002005 status_t status = outputDesc->start();
2006 if (status != NO_ERROR) {
2007 return status;
Eric Laurent3974e3b2017-12-07 17:58:43 -08002008 }
2009
Eric Laurent97ac8712018-07-27 18:59:02 -07002010 uint32_t delayMs;
2011 status = startSource(outputDesc, client, &delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07002012
2013 if (status != NO_ERROR) {
Eric Laurent733ce942017-12-07 12:18:25 -08002014 outputDesc->stop();
Eric Laurent8c7e6da2015-04-21 17:37:00 -07002015 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07002016 }
Eric Laurentc75307b2015-03-17 15:29:32 -07002017 if (delayMs != 0) {
2018 usleep(delayMs * 1000);
2019 }
2020
2021 return status;
2022}
2023
Eric Laurent96d1dda2022-03-14 17:14:19 +01002024bool AudioPolicyManager::isLeUnicastActive() const {
2025 if (isInCall()) {
2026 return true;
2027 }
2028 return isAnyDeviceTypeActive(getAudioDeviceOutLeAudioUnicastSet());
2029}
2030
2031bool AudioPolicyManager::isAnyDeviceTypeActive(const DeviceTypeSet& deviceTypes) const {
2032 if (mAvailableOutputDevices.getDevicesFromTypes(deviceTypes).isEmpty()) {
2033 return false;
2034 }
2035 bool active = mOutputs.isAnyDeviceTypeActive(deviceTypes);
2036 ALOGV("%s active %d", __func__, active);
2037 return active;
2038}
2039
Eric Laurent97ac8712018-07-27 18:59:02 -07002040status_t AudioPolicyManager::startSource(const sp<SwAudioOutputDescriptor>& outputDesc,
2041 const sp<TrackClientDescriptor>& client,
2042 uint32_t *delayMs)
Eric Laurentc75307b2015-03-17 15:29:32 -07002043{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002044 // cannot start playback of STREAM_TTS if any other output is being used
2045 uint32_t beaconMuteLatency = 0;
Eric Laurentc75307b2015-03-17 15:29:32 -07002046
2047 *delayMs = 0;
Eric Laurent97ac8712018-07-27 18:59:02 -07002048 audio_stream_type_t stream = client->stream();
François Gaffie1c878552018-11-22 16:53:21 +01002049 auto clientVolSrc = client->volumeSource();
François Gaffiec005e562018-11-06 15:04:49 +01002050 auto clientStrategy = client->strategy();
2051 auto clientAttr = client->attributes();
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002052 if (stream == AUDIO_STREAM_TTS) {
2053 ALOGV("\t found BEACON stream");
François Gaffie1c878552018-11-22 16:53:21 +01002054 if (!mTtsOutputAvailable && mOutputs.isAnyOutputActive(
Francois Gaffie4404ddb2021-02-04 17:03:38 +01002055 toVolumeSource(AUDIO_STREAM_TTS, false) /*sourceToIgnore*/)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002056 return INVALID_OPERATION;
2057 } else {
2058 beaconMuteLatency = handleEventForBeacon(STARTING_BEACON);
2059 }
2060 } else {
2061 // some playback other than beacon starts
2062 beaconMuteLatency = handleEventForBeacon(STARTING_OUTPUT);
2063 }
2064
Eric Laurent77305a62016-07-25 16:39:22 -07002065 // force device change if the output is inactive and no audio patch is already present.
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002066 // check active before incrementing usage count
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02002067 bool force = !outputDesc->isActive() && !outputDesc->isRouted();
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002068
François Gaffie11d30102018-11-02 16:09:09 +01002069 DeviceVector devices;
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002070 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
Eric Laurent97ac8712018-07-27 18:59:02 -07002071 const char *address = NULL;
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002072 if (policyMix != nullptr) {
François Gaffie11d30102018-11-02 16:09:09 +01002073 audio_devices_t newDeviceType;
Eric Laurent97ac8712018-07-27 18:59:02 -07002074 address = policyMix->mDeviceAddress.string();
Kevin Rocard153f92d2018-12-18 18:33:28 -08002075 if ((policyMix->mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie11d30102018-11-02 16:09:09 +01002076 newDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Kevin Rocard153f92d2018-12-18 18:33:28 -08002077 } else {
2078 newDeviceType = policyMix->mDeviceType;
Eric Laurent97ac8712018-07-27 18:59:02 -07002079 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08002080 sp device = mAvailableOutputDevices.getDevice(newDeviceType, String8(address),
2081 AUDIO_FORMAT_DEFAULT);
2082 ALOG_ASSERT(device, "%s: no device found t=%u, a=%s", __func__, newDeviceType, address);
2083 devices.add(device);
Eric Laurent97ac8712018-07-27 18:59:02 -07002084 }
2085
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002086 // requiresMuteCheck is false when we can bypass mute strategy.
2087 // It covers a common case when there is no materially active audio
2088 // and muting would result in unnecessary delay and dropped audio.
2089 const uint32_t outputLatencyMs = outputDesc->latency();
2090 bool requiresMuteCheck = outputDesc->isActive(outputLatencyMs * 2); // account for drain
Eric Laurent96d1dda2022-03-14 17:14:19 +01002091 bool wasLeUnicastActive = isLeUnicastActive();
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002092
Eric Laurente552edb2014-03-10 17:42:56 -07002093 // increment usage count for this stream on the requested output:
2094 // NOTE that the usage count is the same for duplicated output and hardware output which is
2095 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
Eric Laurent592dd7b2018-08-05 18:58:48 -07002096 outputDesc->setClientActive(client, true);
Eric Laurent97ac8712018-07-27 18:59:02 -07002097
2098 if (client->hasPreferredDevice(true)) {
François Gaffief96e5432019-04-09 17:13:56 +02002099 if (outputDesc->clientsList(true /*activeOnly*/).size() == 1 &&
2100 client->isPreferredDeviceForExclusiveUse()) {
2101 // Preferred device may be exclusive, use only if no other active clients on this output
2102 devices = DeviceVector(
2103 mAvailableOutputDevices.getDeviceFromId(client->preferredDeviceId()));
2104 } else {
2105 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
2106 }
François Gaffie11d30102018-11-02 16:09:09 +01002107 if (devices != outputDesc->devices()) {
François Gaffiec005e562018-11-06 15:04:49 +01002108 checkStrategyRoute(clientStrategy, outputDesc->mIoHandle);
Eric Laurent97ac8712018-07-27 18:59:02 -07002109 }
2110 }
Eric Laurente552edb2014-03-10 17:42:56 -07002111
François Gaffiec005e562018-11-06 15:04:49 +01002112 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07002113 selectOutputForMusicEffects();
2114 }
2115
François Gaffie1c878552018-11-22 16:53:21 +01002116 if (outputDesc->getActivityCount(clientVolSrc) == 1 || !devices.isEmpty()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08002117 // starting an output being rerouted?
François Gaffie11d30102018-11-02 16:09:09 +01002118 if (devices.isEmpty()) {
2119 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Eric Laurent275e8e92014-11-30 15:14:47 -08002120 }
François Gaffiec005e562018-11-06 15:04:49 +01002121 bool shouldWait =
2122 (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM)) ||
2123 followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_NOTIFICATION)) ||
2124 (beaconMuteLatency > 0));
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002125 uint32_t waitMs = beaconMuteLatency;
Eric Laurente552edb2014-03-10 17:42:56 -07002126 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01002127 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07002128 if (desc != outputDesc) {
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002129 // An output has a shared device if
2130 // - managed by the same hw module
2131 // - supports the currently selected device
2132 const bool sharedDevice = outputDesc->sharesHwModuleWith(desc)
François Gaffie11d30102018-11-02 16:09:09 +01002133 && (!desc->filterSupportedDevices(devices).isEmpty());
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002134
Eric Laurent77305a62016-07-25 16:39:22 -07002135 // force a device change if any other output is:
2136 // - managed by the same hw module
Jean-Michel Trivi4a5b4812018-02-08 17:22:32 +00002137 // - supports currently selected device
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002138 // - has a current device selection that differs from selected device.
Eric Laurent77305a62016-07-25 16:39:22 -07002139 // - has an active audio patch
Eric Laurente552edb2014-03-10 17:42:56 -07002140 // In this case, the audio HAL must receive the new device selection so that it can
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002141 // change the device currently selected by the other output.
2142 if (sharedDevice &&
François Gaffie11d30102018-11-02 16:09:09 +01002143 desc->devices() != devices &&
Eric Laurent77305a62016-07-25 16:39:22 -07002144 desc->getPatchHandle() != AUDIO_PATCH_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07002145 force = true;
2146 }
2147 // wait for audio on other active outputs to be presented when starting
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002148 // a notification so that audio focus effect can propagate, or that a mute/unmute
2149 // event occurred for beacon
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002150 const uint32_t latencyMs = desc->latency();
2151 const bool isActive = desc->isActive(latencyMs * 2); // account for drain
2152
2153 if (shouldWait && isActive && (waitMs < latencyMs)) {
2154 waitMs = latencyMs;
Eric Laurente552edb2014-03-10 17:42:56 -07002155 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002156
2157 // Require mute check if another output is on a shared device
2158 // and currently active to have proper drain and avoid pops.
2159 // Note restoring AudioTracks onto this output needs to invoke
2160 // a volume ramp if there is no mute.
2161 requiresMuteCheck |= sharedDevice && isActive;
Eric Laurente552edb2014-03-10 17:42:56 -07002162 }
2163 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002164
2165 const uint32_t muteWaitMs =
François Gaffie11d30102018-11-02 16:09:09 +01002166 setOutputDevices(outputDesc, devices, force, 0, NULL, requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07002167
Eric Laurente552edb2014-03-10 17:42:56 -07002168 // apply volume rules for current stream and device if necessary
François Gaffieaaac0fd2018-11-22 17:56:39 +01002169 auto &curves = getVolumeCurves(client->attributes());
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00002170 if (NO_ERROR != checkAndSetVolume(curves, client->volumeSource(),
François Gaffieaaac0fd2018-11-22 17:56:39 +01002171 curves.getVolumeIndex(outputDesc->devices().types()),
Eric Laurentc75307b2015-03-17 15:29:32 -07002172 outputDesc,
Francois Gaffied11442b2020-04-27 11:51:09 +02002173 outputDesc->devices().types(), 0 /*delay*/,
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00002174 outputDesc->useHwGain() /*force*/)) {
2175 // request AudioService to reinitialize the volume curves asynchronously
2176 ALOGE("checkAndSetVolume failed, requesting volume range init");
2177 mpClientInterface->onVolumeRangeInitRequest();
2178 };
Eric Laurente552edb2014-03-10 17:42:56 -07002179
2180 // update the outputs if starting an output with a stream that can affect notification
2181 // routing
2182 handleNotificationRoutingForStream(stream);
Eric Laurentc722f302014-12-10 11:21:49 -08002183
Eric Laurent2cbe89a2014-12-19 11:49:08 -08002184 // force reevaluating accessibility routing when ringtone or alarm starts
François Gaffiec005e562018-11-06 15:04:49 +01002185 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM))) {
Eric Laurent2cbe89a2014-12-19 11:49:08 -08002186 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
2187 }
Eric Laurentdc462862016-07-19 12:29:53 -07002188
2189 if (waitMs > muteWaitMs) {
2190 *delayMs = waitMs - muteWaitMs;
2191 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002192
2193 // FIXME: A device change (muteWaitMs > 0) likely introduces a volume change.
2194 // A volume change enacted by APM with 0 delay is not synchronous, as it goes
2195 // via AudioCommandThread to AudioFlinger. Hence it is possible that the volume
2196 // change occurs after the MixerThread starts and causes a stream volume
2197 // glitch.
2198 //
2199 // We do not introduce additional delay here.
Eric Laurente552edb2014-03-10 17:42:56 -07002200 }
Eric Laurentdc462862016-07-19 12:29:53 -07002201
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002202 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
jiabin9a3361e2019-10-01 09:38:30 -07002203 mEngine->getForceUse(
2204 AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
François Gaffiec005e562018-11-06 15:04:49 +01002205 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), true, outputDesc);
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002206 }
2207
Eric Laurent97ac8712018-07-27 18:59:02 -07002208 // Automatically enable the remote submix input when output is started on a re routing mix
2209 // of type MIX_TYPE_RECORDERS
jiabin9a3361e2019-10-01 09:38:30 -07002210 if (isSingleDeviceType(devices.types(), &audio_is_remote_submix_device) &&
2211 policyMix != NULL && policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002212 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2213 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2214 address,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002215 "remote-submix",
2216 AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07002217 }
2218
Eric Laurent96d1dda2022-03-14 17:14:19 +01002219 checkLeBroadcastRoutes(wasLeUnicastActive, outputDesc, *delayMs);
2220
Eric Laurente552edb2014-03-10 17:42:56 -07002221 return NO_ERROR;
2222}
2223
Eric Laurent96d1dda2022-03-14 17:14:19 +01002224void AudioPolicyManager::checkLeBroadcastRoutes(bool wasUnicastActive,
2225 sp<SwAudioOutputDescriptor> ignoredOutput, uint32_t delayMs) {
2226 bool isUnicastActive = isLeUnicastActive();
2227
2228 if (wasUnicastActive != isUnicastActive) {
2229 //reroute all outputs routed to LE broadcast if LE unicast activy changed on any output
2230 for (size_t i = 0; i < mOutputs.size(); i++) {
2231 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
2232 if (desc != ignoredOutput && desc->isActive()
2233 && ((isUnicastActive &&
2234 !desc->devices().
2235 getDevicesFromType(AUDIO_DEVICE_OUT_BLE_BROADCAST).isEmpty())
2236 || (wasUnicastActive &&
2237 !desc->devices().getDevicesFromTypes(
2238 getAudioDeviceOutLeAudioUnicastSet()).isEmpty()))) {
2239 DeviceVector newDevices = getNewOutputDevices(desc, false /*fromCache*/);
2240 bool force = desc->devices() != newDevices;
2241 setOutputDevices(desc, newDevices, force, delayMs);
2242 // re-apply device specific volume if not done by setOutputDevice()
2243 if (!force) {
2244 applyStreamVolumes(desc, newDevices.types(), delayMs);
2245 }
2246 }
2247 }
2248 }
2249}
2250
Eric Laurent8fc147b2018-07-22 19:13:55 -07002251status_t AudioPolicyManager::stopOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002252{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002253 ALOGV("%s portId %d", __FUNCTION__, portId);
2254
2255 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2256 if (outputDesc == 0) {
2257 ALOGW("stopOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002258 return BAD_VALUE;
2259 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002260 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002261
Eric Laurent97ac8712018-07-27 18:59:02 -07002262 ALOGV("stopOutput() output %d, stream %d, session %d",
2263 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurente552edb2014-03-10 17:42:56 -07002264
Eric Laurent97ac8712018-07-27 18:59:02 -07002265 status_t status = stopSource(outputDesc, client);
Eric Laurent3974e3b2017-12-07 17:58:43 -08002266
Eric Laurent733ce942017-12-07 12:18:25 -08002267 if (status == NO_ERROR ) {
2268 outputDesc->stop();
Eric Laurent3974e3b2017-12-07 17:58:43 -08002269 }
2270 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07002271}
2272
Eric Laurent97ac8712018-07-27 18:59:02 -07002273status_t AudioPolicyManager::stopSource(const sp<SwAudioOutputDescriptor>& outputDesc,
2274 const sp<TrackClientDescriptor>& client)
Eric Laurentc75307b2015-03-17 15:29:32 -07002275{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002276 // always handle stream stop, check which stream type is stopping
Eric Laurent97ac8712018-07-27 18:59:02 -07002277 audio_stream_type_t stream = client->stream();
François Gaffie1c878552018-11-22 16:53:21 +01002278 auto clientVolSrc = client->volumeSource();
Eric Laurent96d1dda2022-03-14 17:14:19 +01002279 bool wasLeUnicastActive = isLeUnicastActive();
Eric Laurent97ac8712018-07-27 18:59:02 -07002280
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002281 handleEventForBeacon(stream == AUDIO_STREAM_TTS ? STOPPING_BEACON : STOPPING_OUTPUT);
2282
François Gaffie1c878552018-11-22 16:53:21 +01002283 if (outputDesc->getActivityCount(clientVolSrc) > 0) {
2284 if (outputDesc->getActivityCount(clientVolSrc) == 1) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002285 // Automatically disable the remote submix input when output is stopped on a
2286 // re routing mix of type MIX_TYPE_RECORDERS
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002287 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
jiabin9a3361e2019-10-01 09:38:30 -07002288 if (isSingleDeviceType(
2289 outputDesc->devices().types(), &audio_is_remote_submix_device) &&
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002290 policyMix != nullptr &&
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002291 policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002292 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2293 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002294 policyMix->mDeviceAddress,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002295 "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07002296 }
2297 }
2298 bool forceDeviceUpdate = false;
2299 if (client->hasPreferredDevice(true)) {
François Gaffiec005e562018-11-06 15:04:49 +01002300 checkStrategyRoute(client->strategy(), AUDIO_IO_HANDLE_NONE);
Eric Laurent97ac8712018-07-27 18:59:02 -07002301 forceDeviceUpdate = true;
2302 }
2303
Eric Laurente552edb2014-03-10 17:42:56 -07002304 // decrement usage count of this stream on the output
Eric Laurent592dd7b2018-08-05 18:58:48 -07002305 outputDesc->setClientActive(client, false);
Paul McLeanaa981192015-03-21 09:55:15 -07002306
Eric Laurente552edb2014-03-10 17:42:56 -07002307 // store time at which the stream was stopped - see isStreamActive()
François Gaffie1c878552018-11-22 16:53:21 +01002308 if (outputDesc->getActivityCount(clientVolSrc) == 0 || forceDeviceUpdate) {
François Gaffiec005e562018-11-06 15:04:49 +01002309 outputDesc->setStopTime(client, systemTime());
François Gaffie11d30102018-11-02 16:09:09 +01002310 DeviceVector newDevices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Francois Gaffie3523ab32021-06-22 13:24:34 +02002311
2312 // If the routing does not change, if an output is routed on a device using HwGain
2313 // (aka setAudioPortConfig) and there are still active clients following different
2314 // volume group(s), force reapply volume
2315 bool requiresVolumeCheck = outputDesc->getActivityCount(clientVolSrc) == 0 &&
2316 outputDesc->useHwGain() && outputDesc->isAnyActive(VOLUME_SOURCE_NONE);
2317
Eric Laurente552edb2014-03-10 17:42:56 -07002318 // delay the device switch by twice the latency because stopOutput() is executed when
2319 // the track stop() command is received and at that time the audio track buffer can
2320 // still contain data that needs to be drained. The latency only covers the audio HAL
2321 // and kernel buffers. Also the latency does not always include additional delay in the
2322 // audio path (audio DSP, CODEC ...)
Francois Gaffie3523ab32021-06-22 13:24:34 +02002323 setOutputDevices(outputDesc, newDevices, false, outputDesc->latency()*2,
2324 nullptr, true /*requiresMuteCheck*/, requiresVolumeCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07002325
2326 // force restoring the device selection on other active outputs if it differs from the
2327 // one being selected for this output
Eric Laurent57de36c2016-09-28 16:59:11 -07002328 uint32_t delayMs = outputDesc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -07002329 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01002330 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07002331 if (desc != outputDesc &&
Eric Laurente552edb2014-03-10 17:42:56 -07002332 desc->isActive() &&
2333 outputDesc->sharesHwModuleWith(desc) &&
François Gaffie11d30102018-11-02 16:09:09 +01002334 (newDevices != desc->devices())) {
2335 DeviceVector newDevices2 = getNewOutputDevices(desc, false /*fromCache*/);
2336 bool force = desc->devices() != newDevices2;
Eric Laurentf3a5a602018-05-22 18:42:55 -07002337
François Gaffie11d30102018-11-02 16:09:09 +01002338 setOutputDevices(desc, newDevices2, force, delayMs);
2339
Eric Laurent57de36c2016-09-28 16:59:11 -07002340 // re-apply device specific volume if not done by setOutputDevice()
2341 if (!force) {
François Gaffie11d30102018-11-02 16:09:09 +01002342 applyStreamVolumes(desc, newDevices2.types(), delayMs);
Eric Laurent57de36c2016-09-28 16:59:11 -07002343 }
Eric Laurente552edb2014-03-10 17:42:56 -07002344 }
2345 }
2346 // update the outputs if stopping one with a stream that can affect notification routing
2347 handleNotificationRoutingForStream(stream);
2348 }
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002349
2350 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
2351 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Jean-Michel Trivi74e01fa2019-02-25 12:18:09 -08002352 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), false, outputDesc);
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002353 }
2354
François Gaffiec005e562018-11-06 15:04:49 +01002355 if (followsSameRouting(client->attributes(), attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07002356 selectOutputForMusicEffects();
2357 }
Eric Laurent96d1dda2022-03-14 17:14:19 +01002358
2359 checkLeBroadcastRoutes(wasLeUnicastActive, outputDesc, outputDesc->latency()*2);
2360
Eric Laurente552edb2014-03-10 17:42:56 -07002361 return NO_ERROR;
2362 } else {
Eric Laurentc75307b2015-03-17 15:29:32 -07002363 ALOGW("stopOutput() refcount is already 0");
Eric Laurente552edb2014-03-10 17:42:56 -07002364 return INVALID_OPERATION;
2365 }
2366}
2367
jiabinbce0c1d2020-10-05 11:20:18 -07002368bool AudioPolicyManager::releaseOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002369{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002370 ALOGV("%s portId %d", __FUNCTION__, portId);
2371
2372 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2373 if (outputDesc == 0) {
Andy Hung39efb7a2018-09-26 15:39:28 -07002374 // If an output descriptor is closed due to a device routing change,
2375 // then there are race conditions with releaseOutput from tracks
2376 // that may be destroyed (with no PlaybackThread) or a PlaybackThread
2377 // destroyed shortly thereafter.
2378 //
2379 // Here we just log a warning, instead of a fatal error.
Eric Laurent8fc147b2018-07-22 19:13:55 -07002380 ALOGW("releaseOutput() no output for client %d", portId);
jiabinbce0c1d2020-10-05 11:20:18 -07002381 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002382 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002383
2384 ALOGV("releaseOutput() %d", outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -07002385
Jaideep Sharma7bf382e2020-11-26 17:07:29 +05302386 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
2387 if (outputDesc->isClientActive(client)) {
2388 ALOGW("releaseOutput() inactivates portId %d in good faith", portId);
2389 stopOutput(portId);
2390 }
2391
Eric Laurent8fc147b2018-07-22 19:13:55 -07002392 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
2393 if (outputDesc->mDirectOpenCount <= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07002394 ALOGW("releaseOutput() invalid open count %d for output %d",
Eric Laurent8fc147b2018-07-22 19:13:55 -07002395 outputDesc->mDirectOpenCount, outputDesc->mIoHandle);
jiabinbce0c1d2020-10-05 11:20:18 -07002396 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002397 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002398 if (--outputDesc->mDirectOpenCount == 0) {
2399 closeOutput(outputDesc->mIoHandle);
Eric Laurentb52c1522014-05-20 11:27:36 -07002400 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07002401 }
2402 }
Jaideep Sharma7bf382e2020-11-26 17:07:29 +05302403
Andy Hung39efb7a2018-09-26 15:39:28 -07002404 outputDesc->removeClient(portId);
jiabinbce0c1d2020-10-05 11:20:18 -07002405 if (outputDesc->mPendingReopenToQueryProfiles && outputDesc->getClientCount() == 0) {
2406 // The output is pending reopened to query dynamic profiles and
2407 // there is no active clients
2408 closeOutput(outputDesc->mIoHandle);
2409 sp<SwAudioOutputDescriptor> newOutputDesc = openOutputWithProfileAndDevice(
2410 outputDesc->mProfile, mEngine->getActiveMediaDevices(mAvailableOutputDevices));
2411 if (newOutputDesc == nullptr) {
2412 ALOGE("%s failed to open output", __func__);
2413 }
2414 return true;
2415 }
2416 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002417}
2418
Eric Laurentcaf7f482014-11-25 17:50:47 -08002419status_t AudioPolicyManager::getInputForAttr(const audio_attributes_t *attr,
2420 audio_io_handle_t *input,
Mikhail Naganov2996f672019-04-18 12:29:59 -07002421 audio_unique_id_t riid,
Eric Laurentcaf7f482014-11-25 17:50:47 -08002422 audio_session_t session,
Svet Ganov3e5f14f2021-05-13 22:51:08 +00002423 const AttributionSourceState& attributionSource,
jiabinf1c73972022-04-14 16:28:52 -07002424 audio_config_base_t *config,
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002425 audio_input_flags_t flags,
Eric Laurent2ac76942017-06-22 17:17:09 -07002426 audio_port_handle_t *selectedDeviceId,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002427 input_type_t *inputType,
2428 audio_port_handle_t *portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002429{
François Gaffiec005e562018-11-06 15:04:49 +01002430 ALOGV("%s() source %d, sampling rate %d, format %#x, channel mask %#x, session %d, "
Eric Laurent2f2c1982021-06-02 14:03:11 +02002431 "flags %#x attributes=%s requested device ID %d",
2432 __func__, attr->source, config->sample_rate, config->format, config->channel_mask,
2433 session, flags, toString(*attr).c_str(), *selectedDeviceId);
Eric Laurente552edb2014-03-10 17:42:56 -07002434
Eric Laurentad2e7b92017-09-14 20:06:42 -07002435 status_t status = NO_ERROR;
Francois Gaffie716e1432019-01-14 16:58:59 +01002436 audio_attributes_t attributes = *attr;
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002437 sp<AudioPolicyMix> policyMix;
François Gaffie11d30102018-11-02 16:09:09 +01002438 sp<DeviceDescriptor> device;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002439 sp<AudioInputDescriptor> inputDesc;
2440 sp<RecordClientDescriptor> clientDesc;
2441 audio_port_handle_t requestedDeviceId = *selectedDeviceId;
Svet Ganov3e5f14f2021-05-13 22:51:08 +00002442 uid_t uid = VALUE_OR_RETURN_STATUS(aidl2legacy_int32_t_uid_t(attributionSource.uid));
Eric Laurent8f42ea12018-08-08 09:08:25 -07002443 bool isSoundTrigger;
Eric Laurent8f42ea12018-08-08 09:08:25 -07002444
2445 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
2446 if (*portId != AUDIO_PORT_HANDLE_NONE) {
2447 return INVALID_OPERATION;
2448 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08002449
Francois Gaffie716e1432019-01-14 16:58:59 +01002450 if (attr->source == AUDIO_SOURCE_DEFAULT) {
2451 attributes.source = AUDIO_SOURCE_MIC;
Eric Laurentfe231122017-11-17 17:48:06 -08002452 }
2453
Paul McLean466dc8e2015-04-17 13:15:36 -06002454 // Explicit routing?
Pattydd807582021-11-04 21:01:03 +08002455 sp<DeviceDescriptor> explicitRoutingDevice =
François Gaffie11d30102018-11-02 16:09:09 +01002456 mAvailableInputDevices.getDeviceFromId(*selectedDeviceId);
Paul McLean466dc8e2015-04-17 13:15:36 -06002457
Eric Laurentad2e7b92017-09-14 20:06:42 -07002458 // special case for mmap capture: if an input IO handle is specified, we reuse this input if
2459 // possible
2460 if ((flags & AUDIO_INPUT_FLAG_MMAP_NOIRQ) == AUDIO_INPUT_FLAG_MMAP_NOIRQ &&
2461 *input != AUDIO_IO_HANDLE_NONE) {
2462 ssize_t index = mInputs.indexOfKey(*input);
2463 if (index < 0) {
2464 ALOGW("getInputForAttr() unknown MMAP input %d", *input);
2465 status = BAD_VALUE;
2466 goto error;
2467 }
2468 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002469 RecordClientVector clients = inputDesc->getClientsForSession(session);
2470 if (clients.size() == 0) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07002471 ALOGW("getInputForAttr() unknown session %d on input %d", session, *input);
2472 status = BAD_VALUE;
2473 goto error;
2474 }
2475 // For MMAP mode, the first call to getInputForAttr() is made on behalf of audioflinger.
2476 // The second call is for the first active client and sets the UID. Any further call
Eric Laurent331679c2018-04-16 17:03:16 -07002477 // corresponds to a new client and is only permitted from the same UID.
2478 // If the first UID is silenced, allow a new UID connection and replace with new UID
Eric Laurent8f42ea12018-08-08 09:08:25 -07002479 if (clients.size() > 1) {
2480 for (const auto& client : clients) {
2481 // The client map is ordered by key values (portId) and portIds are allocated
2482 // incrementaly. So the first client in this list is the one opened by audio flinger
2483 // when the mmap stream is created and should be ignored as it does not correspond
2484 // to an actual client
2485 if (client == *clients.cbegin()) {
2486 continue;
2487 }
2488 if (uid != client->uid() && !client->isSilenced()) {
2489 ALOGW("getInputForAttr() bad uid %d for client %d uid %d",
2490 uid, client->portId(), client->uid());
2491 status = INVALID_OPERATION;
2492 goto error;
2493 }
Eric Laurent331679c2018-04-16 17:03:16 -07002494 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002495 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002496 *inputType = API_INPUT_LEGACY;
François Gaffie11d30102018-11-02 16:09:09 +01002497 device = inputDesc->getDevice();
Eric Laurentad2e7b92017-09-14 20:06:42 -07002498
Eric Laurentfecbceb2021-02-09 14:46:43 +01002499 ALOGV("%s reusing MMAP input %d for session %d", __FUNCTION__, *input, session);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002500 goto exit;
Eric Laurentad2e7b92017-09-14 20:06:42 -07002501 }
2502
2503 *input = AUDIO_IO_HANDLE_NONE;
2504 *inputType = API_INPUT_INVALID;
2505
Francois Gaffie716e1432019-01-14 16:58:59 +01002506 if (attributes.source == AUDIO_SOURCE_REMOTE_SUBMIX &&
2507 strncmp(attributes.tags, "addr=", strlen("addr=")) == 0) {
2508 status = mPolicyMixes.getInputMixForAttr(attributes, &policyMix);
Eric Laurentad2e7b92017-09-14 20:06:42 -07002509 if (status != NO_ERROR) {
jiabinc1de2df2019-05-07 14:26:40 -07002510 ALOGW("%s could not find input mix for attr %s",
2511 __func__, toString(attributes).c_str());
Eric Laurentad2e7b92017-09-14 20:06:42 -07002512 goto error;
François Gaffie036e1e92015-03-19 10:16:24 +01002513 }
jiabinc1de2df2019-05-07 14:26:40 -07002514 device = mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2515 String8(attr->tags + strlen("addr=")),
2516 AUDIO_FORMAT_DEFAULT);
2517 if (device == nullptr) {
Kevin Rocard04ed0462019-05-02 17:53:24 -07002518 ALOGW("%s could not find in Remote Submix device for source %d, tags %s",
jiabinc1de2df2019-05-07 14:26:40 -07002519 __func__, attributes.source, attributes.tags);
2520 status = BAD_VALUE;
2521 goto error;
2522 }
2523
Kevin Rocard25f9b052019-02-27 15:08:54 -08002524 if (is_mix_loopback_render(policyMix->mRouteFlags)) {
2525 *inputType = API_INPUT_MIX_PUBLIC_CAPTURE_PLAYBACK;
2526 } else {
2527 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
2528 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002529 } else {
François Gaffie11d30102018-11-02 16:09:09 +01002530 if (explicitRoutingDevice != nullptr) {
2531 device = explicitRoutingDevice;
Eric Laurent97ac8712018-07-27 18:59:02 -07002532 } else {
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01002533 // Prevent from storing invalid requested device id in clients
2534 requestedDeviceId = AUDIO_PORT_HANDLE_NONE;
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02002535 device = mEngine->getInputDeviceForAttributes(attributes, uid, session, &policyMix);
yuanjiahsu4069d5d2021-04-19 07:54:27 +08002536 ALOGV_IF(device != nullptr, "%s found device type is 0x%X",
2537 __FUNCTION__, device->type());
Eric Laurent97ac8712018-07-27 18:59:02 -07002538 }
François Gaffie11d30102018-11-02 16:09:09 +01002539 if (device == nullptr) {
Francois Gaffie716e1432019-01-14 16:58:59 +01002540 ALOGW("getInputForAttr() could not find device for source %d", attributes.source);
Eric Laurentad2e7b92017-09-14 20:06:42 -07002541 status = BAD_VALUE;
2542 goto error;
Eric Laurent275e8e92014-11-30 15:14:47 -08002543 }
Alden DSouzab7d20782021-02-08 08:51:42 -08002544 if (device->type() == AUDIO_DEVICE_IN_ECHO_REFERENCE) {
2545 *inputType = API_INPUT_MIX_CAPTURE;
2546 } else if (policyMix) {
François Gaffie11d30102018-11-02 16:09:09 +01002547 ALOG_ASSERT(policyMix->mMixType == MIX_TYPE_RECORDERS, "Invalid Mix Type");
2548 // there is an external policy, but this input is attached to a mix of recorders,
2549 // meaning it receives audio injected into the framework, so the recorder doesn't
2550 // know about it and is therefore considered "legacy"
2551 *inputType = API_INPUT_LEGACY;
2552 } else if (audio_is_remote_submix_device(device->type())) {
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002553 *inputType = API_INPUT_MIX_CAPTURE;
François Gaffie11d30102018-11-02 16:09:09 +01002554 } else if (device->type() == AUDIO_DEVICE_IN_TELEPHONY_RX) {
Eric Laurent82db2692015-08-07 13:59:42 -07002555 *inputType = API_INPUT_TELEPHONY_RX;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002556 } else {
2557 *inputType = API_INPUT_LEGACY;
Eric Laurentc722f302014-12-10 11:21:49 -08002558 }
Ravi Kumar Alamandab367f5b2015-08-25 08:21:37 -07002559
Eric Laurent599c7582015-12-07 18:05:55 -08002560 }
2561
François Gaffiec005e562018-11-06 15:04:49 +01002562 *input = getInputForDevice(device, session, attributes, config, flags, policyMix);
Eric Laurent599c7582015-12-07 18:05:55 -08002563 if (*input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07002564 status = INVALID_OPERATION;
jiabinf1c73972022-04-14 16:28:52 -07002565 AudioProfileVector profiles;
2566 status_t ret = getProfilesForDevices(
2567 DeviceVector(device), profiles, flags, true /*isInput*/);
2568 if (ret == NO_ERROR && !profiles.empty()) {
2569 config->channel_mask = profiles[0]->getChannels().empty() ? config->channel_mask
2570 : *profiles[0]->getChannels().begin();
2571 config->sample_rate = profiles[0]->getSampleRates().empty() ? config->sample_rate
2572 : *profiles[0]->getSampleRates().begin();
2573 config->format = profiles[0]->getFormat();
2574 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002575 goto error;
Eric Laurent599c7582015-12-07 18:05:55 -08002576 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08002577
Eric Laurent8f42ea12018-08-08 09:08:25 -07002578exit:
2579
François Gaffiec005e562018-11-06 15:04:49 +01002580 *selectedDeviceId = mAvailableInputDevices.contains(device) ?
2581 device->getId() : AUDIO_PORT_HANDLE_NONE;
Eric Laurent2ac76942017-06-22 17:17:09 -07002582
Francois Gaffie716e1432019-01-14 16:58:59 +01002583 isSoundTrigger = attributes.source == AUDIO_SOURCE_HOTWORD &&
Carter Hsud0cce2e2019-05-03 17:36:28 +08002584 mSoundTriggerSessions.indexOfKey(session) >= 0;
jiabin4ef93452019-09-10 14:29:54 -07002585 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002586
Mikhail Naganov2996f672019-04-18 12:29:59 -07002587 clientDesc = new RecordClientDescriptor(*portId, riid, uid, session, attributes, *config,
Francois Gaffie716e1432019-01-14 16:58:59 +01002588 requestedDeviceId, attributes.source, flags,
2589 isSoundTrigger);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002590 inputDesc = mInputs.valueFor(*input);
Andy Hung39efb7a2018-09-26 15:39:28 -07002591 inputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002592
2593 ALOGV("getInputForAttr() returns input %d type %d selectedDeviceId %d for port ID %d",
2594 *input, *inputType, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07002595
Eric Laurent599c7582015-12-07 18:05:55 -08002596 return NO_ERROR;
Eric Laurentad2e7b92017-09-14 20:06:42 -07002597
2598error:
Eric Laurentad2e7b92017-09-14 20:06:42 -07002599 return status;
Eric Laurent599c7582015-12-07 18:05:55 -08002600}
2601
2602
François Gaffie11d30102018-11-02 16:09:09 +01002603audio_io_handle_t AudioPolicyManager::getInputForDevice(const sp<DeviceDescriptor> &device,
Eric Laurent599c7582015-12-07 18:05:55 -08002604 audio_session_t session,
François Gaffiec005e562018-11-06 15:04:49 +01002605 const audio_attributes_t &attributes,
jiabinf1c73972022-04-14 16:28:52 -07002606 audio_config_base_t *config,
Eric Laurent599c7582015-12-07 18:05:55 -08002607 audio_input_flags_t flags,
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002608 const sp<AudioPolicyMix> &policyMix)
Eric Laurent599c7582015-12-07 18:05:55 -08002609{
2610 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
François Gaffiec005e562018-11-06 15:04:49 +01002611 audio_source_t halInputSource = attributes.source;
Eric Laurent599c7582015-12-07 18:05:55 -08002612 bool isSoundTrigger = false;
2613
François Gaffiec005e562018-11-06 15:04:49 +01002614 if (attributes.source == AUDIO_SOURCE_HOTWORD) {
Eric Laurent599c7582015-12-07 18:05:55 -08002615 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
2616 if (index >= 0) {
2617 input = mSoundTriggerSessions.valueFor(session);
2618 isSoundTrigger = true;
2619 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_HW_HOTWORD);
2620 ALOGV("SoundTrigger capture on session %d input %d", session, input);
2621 } else {
2622 halInputSource = AUDIO_SOURCE_VOICE_RECOGNITION;
Eric Laurent5dbe4712014-09-19 19:04:57 -07002623 }
François Gaffiec005e562018-11-06 15:04:49 +01002624 } else if (attributes.source == AUDIO_SOURCE_VOICE_COMMUNICATION &&
Eric Laurentfe231122017-11-17 17:48:06 -08002625 audio_is_linear_pcm(config->format)) {
Haynes Mathew George851d3ff2017-06-19 20:01:57 -07002626 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_VOIP_TX);
Eric Laurent5dbe4712014-09-19 19:04:57 -07002627 }
2628
Carter Hsua3abb402021-10-26 11:11:20 +08002629 if (attributes.source == AUDIO_SOURCE_ULTRASOUND) {
2630 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_ULTRASOUND);
2631 }
2632
Eric Laurentfe231122017-11-17 17:48:06 -08002633 // sampling rate and flags may be updated by getInputProfile
2634 uint32_t profileSamplingRate = (config->sample_rate == 0) ?
2635 SAMPLE_RATE_HZ_DEFAULT : config->sample_rate;
jiabin2fd710d2022-05-02 23:20:22 +00002636 audio_format_t profileFormat = config->format;
Eric Laurentfe231122017-11-17 17:48:06 -08002637 audio_channel_mask_t profileChannelMask = config->channel_mask;
Andy Hungf129b032015-04-07 13:45:50 -07002638 audio_input_flags_t profileFlags = flags;
jiabin2fd710d2022-05-02 23:20:22 +00002639 // find a compatible input profile (not necessarily identical in parameters)
2640 sp<IOProfile> profile = getInputProfile(
2641 device, profileSamplingRate, profileFormat, profileChannelMask, profileFlags);
2642 if (profile == nullptr) {
2643 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07002644 }
jiabin2fd710d2022-05-02 23:20:22 +00002645
Glenn Kasten05ddca52016-02-11 08:17:12 -08002646 // Pick input sampling rate if not specified by client
Eric Laurentfe231122017-11-17 17:48:06 -08002647 uint32_t samplingRate = config->sample_rate;
Glenn Kasten05ddca52016-02-11 08:17:12 -08002648 if (samplingRate == 0) {
2649 samplingRate = profileSamplingRate;
2650 }
Eric Laurente552edb2014-03-10 17:42:56 -07002651
Eric Laurent322b4d22015-04-03 15:57:54 -07002652 if (profile->getModuleHandle() == 0) {
2653 ALOGE("getInputForAttr(): HW module %s not opened", profile->getModuleName());
Eric Laurent599c7582015-12-07 18:05:55 -08002654 return input;
Eric Laurentcf2c0212014-07-25 16:20:43 -07002655 }
2656
Eric Laurentec376dc2021-04-08 20:41:22 +02002657 // Reuse an already opened input if a client with the same session ID already exists
2658 // on that input
2659 for (size_t i = 0; i < mInputs.size(); i++) {
2660 sp <AudioInputDescriptor> desc = mInputs.valueAt(i);
2661 if (desc->mProfile != profile) {
2662 continue;
2663 }
2664 RecordClientVector clients = desc->clientsList();
2665 for (const auto &client : clients) {
2666 if (session == client->session()) {
2667 return desc->mIoHandle;
2668 }
2669 }
2670 }
2671
Eric Laurent3974e3b2017-12-07 17:58:43 -08002672 if (!profile->canOpenNewIo()) {
Eric Laurent4eb58f12018-12-07 16:41:02 -08002673 for (size_t i = 0; i < mInputs.size(); ) {
Eric Laurentc529cf62020-04-17 18:19:10 -07002674 sp<AudioInputDescriptor> desc = mInputs.valueAt(i);
Eric Laurent4eb58f12018-12-07 16:41:02 -08002675 if (desc->mProfile != profile) {
Carter Hsu9a645a92019-05-15 12:15:32 +08002676 i++;
Eric Laurent4eb58f12018-12-07 16:41:02 -08002677 continue;
2678 }
2679 // if sound trigger, reuse input if used by other sound trigger on same session
2680 // else
2681 // reuse input if active client app is not in IDLE state
2682 //
2683 RecordClientVector clients = desc->clientsList();
2684 bool doClose = false;
2685 for (const auto& client : clients) {
2686 if (isSoundTrigger != client->isSoundTrigger()) {
2687 continue;
2688 }
2689 if (client->isSoundTrigger()) {
2690 if (session == client->session()) {
2691 return desc->mIoHandle;
2692 }
2693 continue;
2694 }
2695 if (client->active() && client->appState() != APP_STATE_IDLE) {
2696 return desc->mIoHandle;
2697 }
2698 doClose = true;
2699 }
2700 if (doClose) {
2701 closeInput(desc->mIoHandle);
2702 } else {
2703 i++;
2704 }
2705 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002706 }
2707
Eric Laurentfe231122017-11-17 17:48:06 -08002708 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07002709
Eric Laurentfe231122017-11-17 17:48:06 -08002710 audio_config_t lConfig = AUDIO_CONFIG_INITIALIZER;
2711 lConfig.sample_rate = profileSamplingRate;
2712 lConfig.channel_mask = profileChannelMask;
2713 lConfig.format = profileFormat;
Eric Laurente3014102017-05-03 11:15:43 -07002714
François Gaffie11d30102018-11-02 16:09:09 +01002715 status_t status = inputDesc->open(&lConfig, device, halInputSource, profileFlags, &input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07002716
2717 // only accept input with the exact requested set of parameters
Eric Laurent599c7582015-12-07 18:05:55 -08002718 if (status != NO_ERROR || input == AUDIO_IO_HANDLE_NONE ||
Eric Laurentfe231122017-11-17 17:48:06 -08002719 (profileSamplingRate != lConfig.sample_rate) ||
2720 !audio_formats_match(profileFormat, lConfig.format) ||
2721 (profileChannelMask != lConfig.channel_mask)) {
2722 ALOGW("getInputForAttr() failed opening input: sampling rate %d"
Glenn Kasten49f36ba2017-12-06 13:02:02 -08002723 ", format %#x, channel mask %#x",
Eric Laurentfe231122017-11-17 17:48:06 -08002724 profileSamplingRate, profileFormat, profileChannelMask);
Eric Laurent599c7582015-12-07 18:05:55 -08002725 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfe231122017-11-17 17:48:06 -08002726 inputDesc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07002727 }
Eric Laurent599c7582015-12-07 18:05:55 -08002728 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07002729 }
2730
Eric Laurentc722f302014-12-10 11:21:49 -08002731 inputDesc->mPolicyMix = policyMix;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002732
Eric Laurent599c7582015-12-07 18:05:55 -08002733 addInput(input, inputDesc);
Eric Laurentb52c1522014-05-20 11:27:36 -07002734 mpClientInterface->onAudioPortListUpdate();
Paul McLean466dc8e2015-04-17 13:15:36 -06002735
Eric Laurent599c7582015-12-07 18:05:55 -08002736 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07002737}
2738
Eric Laurent4eb58f12018-12-07 16:41:02 -08002739status_t AudioPolicyManager::startInput(audio_port_handle_t portId)
Eric Laurentbb948092017-01-23 18:33:30 -08002740{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002741 ALOGV("%s portId %d", __FUNCTION__, portId);
2742
2743 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2744 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002745 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurentd52a28c2020-08-21 17:10:39 -07002746 return DEAD_OBJECT;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002747 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002748 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07002749 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002750 if (client->active()) {
2751 ALOGW("%s input %d client %d already started", __FUNCTION__, input, client->portId());
2752 return INVALID_OPERATION;
Eric Laurent4dc68062014-07-28 17:26:49 -07002753 }
2754
Eric Laurent8f42ea12018-08-08 09:08:25 -07002755 audio_session_t session = client->session();
2756
Eric Laurent4eb58f12018-12-07 16:41:02 -08002757 ALOGV("%s input:%d, session:%d)", __FUNCTION__, input, session);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002758
Eric Laurent4eb58f12018-12-07 16:41:02 -08002759 Vector<sp<AudioInputDescriptor>> activeInputs = mInputs.getActiveInputs();
Eric Laurent74708e72017-04-07 17:13:42 -07002760
Eric Laurent4eb58f12018-12-07 16:41:02 -08002761 status_t status = inputDesc->start();
2762 if (status != NO_ERROR) {
2763 return status;
Eric Laurent74708e72017-04-07 17:13:42 -07002764 }
Eric Laurente552edb2014-03-10 17:42:56 -07002765
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002766 // increment activity count before calling getNewInputDevice() below as only active sessions
Eric Laurent313d1e72016-01-29 09:56:57 -08002767 // are considered for device selection
Eric Laurent8f42ea12018-08-08 09:08:25 -07002768 inputDesc->setClientActive(client, true);
Eric Laurent313d1e72016-01-29 09:56:57 -08002769
Eric Laurent8f42ea12018-08-08 09:08:25 -07002770 // indicate active capture to sound trigger service if starting capture from a mic on
2771 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01002772 sp<DeviceDescriptor> device = getNewInputDevice(inputDesc);
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002773 if (device != nullptr) {
2774 status = setInputDevice(input, device, true /* force */);
2775 } else {
2776 ALOGW("%s no new input device can be found for descriptor %d",
2777 __FUNCTION__, inputDesc->getId());
2778 status = BAD_VALUE;
2779 }
Eric Laurente552edb2014-03-10 17:42:56 -07002780
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002781 if (status == NO_ERROR && inputDesc->activeCount() == 1) {
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002782 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002783 // if input maps to a dynamic policy with an activity listener, notify of state change
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002784 if ((policyMix != nullptr)
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002785 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
2786 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
Eric Laurent8f42ea12018-08-08 09:08:25 -07002787 MIX_STATE_MIXING);
Eric Laurent733ce942017-12-07 12:18:25 -08002788 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002789
François Gaffie11d30102018-11-02 16:09:09 +01002790 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
2791 if (primaryInputDevices.contains(device) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07002792 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 1) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07002793 mpClientInterface->setSoundTriggerCaptureState(true);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002794 }
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002795
Eric Laurent8f42ea12018-08-08 09:08:25 -07002796 // automatically enable the remote submix output when input is started if not
2797 // used by a policy mix of type MIX_TYPE_RECORDERS
2798 // For remote submix (a virtual device), we open only one input per capture request.
François Gaffie11d30102018-11-02 16:09:09 +01002799 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002800 String8 address = String8("");
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002801 if (policyMix == nullptr) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002802 address = String8("0");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002803 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
2804 address = policyMix->mDeviceAddress;
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002805 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07002806 if (address != "") {
2807 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2808 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002809 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurentc722f302014-12-10 11:21:49 -08002810 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07002811 }
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002812 } else if (status != NO_ERROR) {
2813 // Restore client activity state.
2814 inputDesc->setClientActive(client, false);
2815 inputDesc->stop();
Eric Laurente552edb2014-03-10 17:42:56 -07002816 }
2817
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002818 ALOGV("%s input %d source = %d status = %d exit",
2819 __FUNCTION__, input, client->source(), status);
Eric Laurente552edb2014-03-10 17:42:56 -07002820
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002821 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07002822}
2823
Eric Laurent8fc147b2018-07-22 19:13:55 -07002824status_t AudioPolicyManager::stopInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002825{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002826 ALOGV("%s portId %d", __FUNCTION__, portId);
2827
2828 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2829 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002830 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002831 return BAD_VALUE;
2832 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002833 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07002834 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002835 if (!client->active()) {
2836 ALOGW("%s input %d client %d already stopped", __FUNCTION__, input, client->portId());
Eric Laurente552edb2014-03-10 17:42:56 -07002837 return INVALID_OPERATION;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002838 }
Carter Hsue6139d52021-07-08 10:30:20 +08002839 auto old_source = inputDesc->source();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002840 inputDesc->setClientActive(client, false);
Paul McLean466dc8e2015-04-17 13:15:36 -06002841
Eric Laurent8f42ea12018-08-08 09:08:25 -07002842 inputDesc->stop();
2843 if (inputDesc->isActive()) {
Carter Hsue6139d52021-07-08 10:30:20 +08002844 auto current_source = inputDesc->source();
2845 setInputDevice(input, getNewInputDevice(inputDesc),
2846 old_source != current_source /* force */);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002847 } else {
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002848 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002849 // if input maps to a dynamic policy with an activity listener, notify of state change
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002850 if ((policyMix != nullptr)
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002851 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
2852 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
Eric Laurent8f42ea12018-08-08 09:08:25 -07002853 MIX_STATE_IDLE);
Eric Laurent84332aa2016-01-28 22:19:18 +00002854 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07002855
2856 // automatically disable the remote submix output when input is stopped if not
2857 // used by a policy mix of type MIX_TYPE_RECORDERS
François Gaffie11d30102018-11-02 16:09:09 +01002858 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002859 String8 address = String8("");
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002860 if (policyMix == nullptr) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002861 address = String8("0");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002862 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
2863 address = policyMix->mDeviceAddress;
Eric Laurent8f42ea12018-08-08 09:08:25 -07002864 }
2865 if (address != "") {
2866 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2867 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002868 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002869 }
2870 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07002871 resetInputDevice(input);
2872
2873 // indicate inactive capture to sound trigger service if stopping capture from a mic on
2874 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01002875 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
2876 if (primaryInputDevices.contains(inputDesc->getDevice()) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07002877 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07002878 mpClientInterface->setSoundTriggerCaptureState(false);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002879 }
2880 inputDesc->clearPreemptedSessions();
Eric Laurente552edb2014-03-10 17:42:56 -07002881 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002882 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07002883}
2884
Eric Laurent8fc147b2018-07-22 19:13:55 -07002885void AudioPolicyManager::releaseInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002886{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002887 ALOGV("%s portId %d", __FUNCTION__, portId);
2888
2889 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2890 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002891 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002892 return;
2893 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002894 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002895 audio_io_handle_t input = inputDesc->mIoHandle;
2896
Eric Laurent8f42ea12018-08-08 09:08:25 -07002897 ALOGV("%s %d", __FUNCTION__, input);
Paul McLean466dc8e2015-04-17 13:15:36 -06002898
Andy Hung39efb7a2018-09-26 15:39:28 -07002899 inputDesc->removeClient(portId);
Eric Laurent599c7582015-12-07 18:05:55 -08002900
Andy Hung39efb7a2018-09-26 15:39:28 -07002901 if (inputDesc->getClientCount() > 0) {
2902 ALOGV("%s(%d) %zu clients remaining", __func__, portId, inputDesc->getClientCount());
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002903 return;
2904 }
2905
Eric Laurent05b90f82014-08-27 15:32:29 -07002906 closeInput(input);
Eric Laurentb52c1522014-05-20 11:27:36 -07002907 mpClientInterface->onAudioPortListUpdate();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002908 ALOGV("%s exit", __FUNCTION__);
Eric Laurente552edb2014-03-10 17:42:56 -07002909}
2910
Eric Laurent8f42ea12018-08-08 09:08:25 -07002911void AudioPolicyManager::closeActiveClients(const sp<AudioInputDescriptor>& input)
Eric Laurent8fc147b2018-07-22 19:13:55 -07002912{
Eric Laurent8f42ea12018-08-08 09:08:25 -07002913 RecordClientVector clients = input->clientsList(true);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002914
2915 for (const auto& client : clients) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002916 closeClient(client->portId());
Eric Laurent8fc147b2018-07-22 19:13:55 -07002917 }
2918}
2919
Eric Laurent8f42ea12018-08-08 09:08:25 -07002920void AudioPolicyManager::closeClient(audio_port_handle_t portId)
2921{
2922 stopInput(portId);
2923 releaseInput(portId);
2924}
Eric Laurent8fc147b2018-07-22 19:13:55 -07002925
Eric Laurent0dd51852019-04-19 18:18:58 -07002926void AudioPolicyManager::checkCloseInputs() {
2927 // After connecting or disconnecting an input device, close input if:
2928 // - it has no client (was just opened to check profile) OR
2929 // - none of its supported devices are connected anymore OR
2930 // - one of its clients cannot be routed to one of its supported
2931 // devices anymore. Otherwise update device selection
2932 std::vector<audio_io_handle_t> inputsToClose;
2933 for (size_t i = 0; i < mInputs.size(); i++) {
2934 const sp<AudioInputDescriptor> input = mInputs.valueAt(i);
2935 if (input->clientsList().size() == 0
Eric Laurent85732f42020-03-19 11:31:10 -07002936 || !mAvailableInputDevices.containsAtLeastOne(input->supportedDevices())) {
Eric Laurent0dd51852019-04-19 18:18:58 -07002937 inputsToClose.push_back(mInputs.keyAt(i));
2938 } else {
2939 bool close = false;
2940 for (const auto& client : input->clientsList()) {
2941 sp<DeviceDescriptor> device =
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02002942 mEngine->getInputDeviceForAttributes(client->attributes(), client->uid(),
2943 client->session());
Eric Laurent0dd51852019-04-19 18:18:58 -07002944 if (!input->supportedDevices().contains(device)) {
2945 close = true;
2946 break;
2947 }
2948 }
2949 if (close) {
2950 inputsToClose.push_back(mInputs.keyAt(i));
2951 } else {
2952 setInputDevice(input->mIoHandle, getNewInputDevice(input));
2953 }
2954 }
2955 }
2956
2957 for (const audio_io_handle_t handle : inputsToClose) {
2958 ALOGV("%s closing input %d", __func__, handle);
2959 closeInput(handle);
Eric Laurent05b90f82014-08-27 15:32:29 -07002960 }
Eric Laurentd4692962014-05-05 18:13:44 -07002961}
2962
François Gaffie251c7f02018-11-07 10:41:08 +01002963void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream, int indexMin, int indexMax)
Eric Laurente552edb2014-03-10 17:42:56 -07002964{
2965 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08002966 if (indexMin < 0 || indexMax < 0) {
2967 ALOGE("%s for stream %d: invalid min %d or max %d", __func__, stream , indexMin, indexMax);
2968 return;
2969 }
Eric Laurentf5aa58d2019-02-22 18:20:11 -08002970 getVolumeCurves(stream).initVolume(indexMin, indexMax);
Eric Laurent28d09f02016-03-08 10:43:05 -08002971
2972 // initialize other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08002973 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
2974 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002975 continue;
2976 }
Eric Laurentf5aa58d2019-02-22 18:20:11 -08002977 getVolumeCurves((audio_stream_type_t)curStream).initVolume(indexMin, indexMax);
Eric Laurent223fd5c2014-11-11 13:43:36 -08002978 }
Eric Laurente552edb2014-03-10 17:42:56 -07002979}
2980
Eric Laurente0720872014-03-11 09:30:41 -07002981status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
François Gaffie53615e22015-03-19 09:24:12 +01002982 int index,
2983 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07002984{
François Gaffieaaac0fd2018-11-22 17:56:39 +01002985 auto attributes = mEngine->getAttributesForStreamType(stream);
Eric Laurent242a9f82020-03-23 15:57:04 -07002986 if (attributes == AUDIO_ATTRIBUTES_INITIALIZER) {
2987 ALOGW("%s: no group for stream %s, bailing out", __func__, toString(stream).c_str());
2988 return NO_ERROR;
2989 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01002990 ALOGV("%s: stream %s attributes=%s", __func__,
2991 toString(stream).c_str(), toString(attributes).c_str());
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002992 return setVolumeIndexForAttributes(attributes, index, device);
Eric Laurente552edb2014-03-10 17:42:56 -07002993}
2994
Eric Laurente0720872014-03-11 09:30:41 -07002995status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
François Gaffieaaac0fd2018-11-22 17:56:39 +01002996 int *index,
2997 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07002998{
François Gaffiec005e562018-11-06 15:04:49 +01002999 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
3000 // stream by the engine.
jiabin9a3361e2019-10-01 09:38:30 -07003001 DeviceTypeSet deviceTypes = {device};
Eric Laurent5a2b6292016-04-14 18:05:57 -07003002 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
jiabin9a3361e2019-10-01 09:38:30 -07003003 deviceTypes = mEngine->getOutputDevicesForStream(
3004 stream, true /*fromCache*/).types();
Eric Laurente552edb2014-03-10 17:42:56 -07003005 }
jiabin9a3361e2019-10-01 09:38:30 -07003006 return getVolumeIndex(getVolumeCurves(stream), *index, deviceTypes);
Eric Laurente552edb2014-03-10 17:42:56 -07003007}
3008
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003009status_t AudioPolicyManager::setVolumeIndexForAttributes(const audio_attributes_t &attributes,
François Gaffiecfe17322018-11-07 13:41:29 +01003010 int index,
3011 audio_devices_t device)
3012{
3013 // Get Volume group matching the Audio Attributes
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003014 auto group = mEngine->getVolumeGroupForAttributes(attributes);
3015 if (group == VOLUME_GROUP_NONE) {
3016 ALOGD("%s: no group matching with %s", __FUNCTION__, toString(attributes).c_str());
François Gaffiecfe17322018-11-07 13:41:29 +01003017 return BAD_VALUE;
3018 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003019 ALOGV("%s: group %d matching with %s", __FUNCTION__, group, toString(attributes).c_str());
François Gaffiecfe17322018-11-07 13:41:29 +01003020 status_t status = NO_ERROR;
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003021 IVolumeCurves &curves = getVolumeCurves(attributes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01003022 VolumeSource vs = toVolumeSource(group);
3023 product_strategy_t strategy = mEngine->getProductStrategyForAttributes(attributes);
3024
3025 status = setVolumeCurveIndex(index, device, curves);
3026 if (status != NO_ERROR) {
3027 ALOGE("%s failed to set curve index for group %d device 0x%X", __func__, group, device);
3028 return status;
3029 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003030
jiabin9a3361e2019-10-01 09:38:30 -07003031 DeviceTypeSet curSrcDevices;
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003032 auto curCurvAttrs = curves.getAttributes();
3033 if (!curCurvAttrs.empty() && curCurvAttrs.front() != defaultAttr) {
3034 auto attr = curCurvAttrs.front();
jiabin9a3361e2019-10-01 09:38:30 -07003035 curSrcDevices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false).types();
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003036 } else if (!curves.getStreamTypes().empty()) {
3037 auto stream = curves.getStreamTypes().front();
jiabin9a3361e2019-10-01 09:38:30 -07003038 curSrcDevices = mEngine->getOutputDevicesForStream(stream, false).types();
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003039 } else {
3040 ALOGE("%s: Invalid src %d: no valid attributes nor stream",__func__, vs);
3041 return BAD_VALUE;
3042 }
jiabin9a3361e2019-10-01 09:38:30 -07003043 audio_devices_t curSrcDevice = Volume::getDeviceForVolume(curSrcDevices);
3044 resetDeviceTypes(curSrcDevices, curSrcDevice);
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003045
François Gaffiecfe17322018-11-07 13:41:29 +01003046 // update volume on all outputs and streams matching the following:
3047 // - The requested stream (or a stream matching for volume control) is active on the output
3048 // - The device (or devices) selected by the engine for this stream includes
3049 // the requested device
3050 // - For non default requested device, currently selected device on the output is either the
3051 // requested device or one of the devices selected by the engine for this stream
3052 // - For default requested device (AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME), apply volume only if
3053 // no specific device volume value exists for currently selected device.
François Gaffieaaac0fd2018-11-22 17:56:39 +01003054 for (size_t i = 0; i < mOutputs.size(); i++) {
3055 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
jiabin9a3361e2019-10-01 09:38:30 -07003056 DeviceTypeSet curDevices = desc->devices().types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01003057
jiabin9a3361e2019-10-01 09:38:30 -07003058 if (curDevices.erase(AUDIO_DEVICE_OUT_SPEAKER_SAFE)) {
3059 curDevices.insert(AUDIO_DEVICE_OUT_SPEAKER);
Robert Lee5e66e792019-04-03 18:37:15 +08003060 }
François Gaffieed91f582020-01-31 10:35:37 +01003061 if (!(desc->isActive(vs) || isInCall())) {
3062 continue;
3063 }
3064 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME &&
3065 curDevices.find(device) == curDevices.end()) {
3066 continue;
3067 }
3068 bool applyVolume = false;
3069 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
3070 curSrcDevices.insert(device);
3071 applyVolume = (curSrcDevices.find(
3072 Volume::getDeviceForVolume(curDevices)) != curSrcDevices.end());
3073 } else {
3074 applyVolume = !curves.hasVolumeIndexForDevice(curSrcDevice);
3075 }
3076 if (!applyVolume) {
3077 continue; // next output
3078 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01003079 // Inter / intra volume group priority management: Loop on strategies arranged by priority
3080 // If a higher priority strategy is active, and the output is routed to a device with a
3081 // HW Gain management, do not change the volume
François Gaffieaaac0fd2018-11-22 17:56:39 +01003082 if (desc->useHwGain()) {
François Gaffieed91f582020-01-31 10:35:37 +01003083 applyVolume = false;
Francois Gaffie593634d2021-06-22 13:31:31 +02003084 // If the volume source is active with higher priority source, ensure at least Sw Muted
3085 desc->setSwMute((index == 0), vs, curves.getStreamTypes(), curDevices, 0 /*delayMs*/);
François Gaffieaaac0fd2018-11-22 17:56:39 +01003086 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
3087 auto activeClients = desc->clientsList(true /*activeOnly*/, productStrategy,
3088 false /*preferredDevice*/);
3089 if (activeClients.empty()) {
3090 continue;
3091 }
3092 bool isPreempted = false;
3093 bool isHigherPriority = productStrategy < strategy;
3094 for (const auto &client : activeClients) {
3095 if (isHigherPriority && (client->volumeSource() != vs)) {
3096 ALOGV("%s: Strategy=%d (\nrequester:\n"
3097 " group %d, volumeGroup=%d attributes=%s)\n"
3098 " higher priority source active:\n"
3099 " volumeGroup=%d attributes=%s) \n"
3100 " on output %zu, bailing out", __func__, productStrategy,
3101 group, group, toString(attributes).c_str(),
3102 client->volumeSource(), toString(client->attributes()).c_str(), i);
3103 applyVolume = false;
3104 isPreempted = true;
3105 break;
3106 }
3107 // However, continue for loop to ensure no higher prio clients running on output
3108 if (client->volumeSource() == vs) {
3109 applyVolume = true;
3110 }
3111 }
3112 if (isPreempted || applyVolume) {
3113 break;
3114 }
3115 }
3116 if (!applyVolume) {
3117 continue; // next output
3118 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01003119 }
François Gaffieed91f582020-01-31 10:35:37 +01003120 //FIXME: workaround for truncated touch sounds
3121 // delayed volume change for system stream to be removed when the problem is
3122 // handled by system UI
3123 status_t volStatus = checkAndSetVolume(
3124 curves, vs, index, desc, curDevices,
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003125 ((vs == toVolumeSource(AUDIO_STREAM_SYSTEM, false))?
François Gaffieed91f582020-01-31 10:35:37 +01003126 TOUCH_SOUND_FIXED_DELAY_MS : 0));
3127 if (volStatus != NO_ERROR) {
3128 status = volStatus;
François Gaffieaaac0fd2018-11-22 17:56:39 +01003129 }
3130 }
François Gaffiecfe17322018-11-07 13:41:29 +01003131 mpClientInterface->onAudioVolumeGroupChanged(group, 0 /*flags*/);
3132 return status;
3133}
3134
François Gaffieaaac0fd2018-11-22 17:56:39 +01003135status_t AudioPolicyManager::setVolumeCurveIndex(int index,
François Gaffiecfe17322018-11-07 13:41:29 +01003136 audio_devices_t device,
3137 IVolumeCurves &volumeCurves)
3138{
3139 // VOICE_CALL stream has minVolumeIndex > 0 but can be muted directly by an
3140 // app that has MODIFY_PHONE_STATE permission.
François Gaffieaaac0fd2018-11-22 17:56:39 +01003141 bool hasVoice = hasVoiceStream(volumeCurves.getStreamTypes());
3142 if (((index < volumeCurves.getVolumeIndexMin()) && !(hasVoice && index == 0)) ||
François Gaffiecfe17322018-11-07 13:41:29 +01003143 (index > volumeCurves.getVolumeIndexMax())) {
3144 ALOGD("%s: wrong index %d min=%d max=%d", __FUNCTION__, index,
3145 volumeCurves.getVolumeIndexMin(), volumeCurves.getVolumeIndexMax());
3146 return BAD_VALUE;
3147 }
3148 if (!audio_is_output_device(device)) {
3149 return BAD_VALUE;
3150 }
3151
3152 // Force max volume if stream cannot be muted
3153 if (!volumeCurves.canBeMuted()) index = volumeCurves.getVolumeIndexMax();
3154
François Gaffieaaac0fd2018-11-22 17:56:39 +01003155 ALOGV("%s device %08x, index %d", __FUNCTION__ , device, index);
François Gaffiecfe17322018-11-07 13:41:29 +01003156 volumeCurves.addCurrentVolumeIndex(device, index);
3157 return NO_ERROR;
3158}
3159
3160status_t AudioPolicyManager::getVolumeIndexForAttributes(const audio_attributes_t &attr,
3161 int &index,
3162 audio_devices_t device)
3163{
3164 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
3165 // stream by the engine.
jiabin9a3361e2019-10-01 09:38:30 -07003166 DeviceTypeSet deviceTypes = {device};
François Gaffiecfe17322018-11-07 13:41:29 +01003167 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
Mikhail Naganovbb990f22022-06-15 00:46:43 +00003168 deviceTypes = mEngine->getOutputDevicesForAttributes(
jiabin9a3361e2019-10-01 09:38:30 -07003169 attr, nullptr, true /*fromCache*/).types();
François Gaffiecfe17322018-11-07 13:41:29 +01003170 }
jiabin9a3361e2019-10-01 09:38:30 -07003171 return getVolumeIndex(getVolumeCurves(attr), index, deviceTypes);
François Gaffiecfe17322018-11-07 13:41:29 +01003172}
3173
3174status_t AudioPolicyManager::getVolumeIndex(const IVolumeCurves &curves,
3175 int &index,
jiabin9a3361e2019-10-01 09:38:30 -07003176 const DeviceTypeSet& deviceTypes) const
François Gaffiecfe17322018-11-07 13:41:29 +01003177{
Mikhail Naganovbb990f22022-06-15 00:46:43 +00003178 if (!isSingleDeviceType(deviceTypes, audio_is_output_device)) {
François Gaffiecfe17322018-11-07 13:41:29 +01003179 return BAD_VALUE;
3180 }
jiabin9a3361e2019-10-01 09:38:30 -07003181 index = curves.getVolumeIndex(deviceTypes);
3182 ALOGV("%s: device %s index %d", __FUNCTION__, dumpDeviceTypes(deviceTypes).c_str(), index);
François Gaffiecfe17322018-11-07 13:41:29 +01003183 return NO_ERROR;
3184}
3185
3186status_t AudioPolicyManager::getMinVolumeIndexForAttributes(const audio_attributes_t &attr,
3187 int &index)
3188{
3189 index = getVolumeCurves(attr).getVolumeIndexMin();
3190 return NO_ERROR;
3191}
3192
3193status_t AudioPolicyManager::getMaxVolumeIndexForAttributes(const audio_attributes_t &attr,
3194 int &index)
3195{
3196 index = getVolumeCurves(attr).getVolumeIndexMax();
3197 return NO_ERROR;
3198}
3199
Eric Laurent36829f92017-04-07 19:04:42 -07003200audio_io_handle_t AudioPolicyManager::selectOutputForMusicEffects()
Eric Laurente552edb2014-03-10 17:42:56 -07003201{
3202 // select one output among several suitable for global effects.
3203 // The priority is as follows:
3204 // 1: An offloaded output. If the effect ends up not being offloadable,
3205 // AudioFlinger will invalidate the track and the offloaded output
3206 // will be closed causing the effect to be moved to a PCM output.
3207 // 2: A deep buffer output
Eric Laurent36829f92017-04-07 19:04:42 -07003208 // 3: The primary output
3209 // 4: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07003210
François Gaffiec005e562018-11-06 15:04:49 +01003211 DeviceVector devices = mEngine->getOutputDevicesForAttributes(
3212 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
François Gaffie11d30102018-11-02 16:09:09 +01003213 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07003214
Eric Laurent36829f92017-04-07 19:04:42 -07003215 if (outputs.size() == 0) {
3216 return AUDIO_IO_HANDLE_NONE;
3217 }
Eric Laurente552edb2014-03-10 17:42:56 -07003218
Eric Laurent36829f92017-04-07 19:04:42 -07003219 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
3220 bool activeOnly = true;
3221
3222 while (output == AUDIO_IO_HANDLE_NONE) {
3223 audio_io_handle_t outputOffloaded = AUDIO_IO_HANDLE_NONE;
3224 audio_io_handle_t outputDeepBuffer = AUDIO_IO_HANDLE_NONE;
3225 audio_io_handle_t outputPrimary = AUDIO_IO_HANDLE_NONE;
3226
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003227 for (audio_io_handle_t output : outputs) {
3228 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
Eric Laurent83d17c22019-04-02 17:10:01 -07003229 if (activeOnly && !desc->isActive(toVolumeSource(AUDIO_STREAM_MUSIC))) {
Eric Laurent36829f92017-04-07 19:04:42 -07003230 continue;
3231 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003232 ALOGV("selectOutputForMusicEffects activeOnly %d output %d flags 0x%08x",
3233 activeOnly, output, desc->mFlags);
Eric Laurent36829f92017-04-07 19:04:42 -07003234 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003235 outputOffloaded = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003236 }
3237 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003238 outputDeepBuffer = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003239 }
3240 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003241 outputPrimary = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003242 }
3243 }
3244 if (outputOffloaded != AUDIO_IO_HANDLE_NONE) {
3245 output = outputOffloaded;
3246 } else if (outputDeepBuffer != AUDIO_IO_HANDLE_NONE) {
3247 output = outputDeepBuffer;
3248 } else if (outputPrimary != AUDIO_IO_HANDLE_NONE) {
3249 output = outputPrimary;
3250 } else {
3251 output = outputs[0];
3252 }
3253 activeOnly = false;
3254 }
3255
3256 if (output != mMusicEffectOutput) {
Eric Laurent6c796322019-04-09 14:13:17 -07003257 mEffects.moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output);
Eric Laurent36829f92017-04-07 19:04:42 -07003258 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output);
3259 mMusicEffectOutput = output;
3260 }
3261
3262 ALOGV("selectOutputForMusicEffects selected output %d", output);
Eric Laurente552edb2014-03-10 17:42:56 -07003263 return output;
3264}
3265
Eric Laurent36829f92017-04-07 19:04:42 -07003266audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc __unused)
3267{
3268 return selectOutputForMusicEffects();
3269}
3270
Eric Laurente0720872014-03-11 09:30:41 -07003271status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07003272 audio_io_handle_t io,
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08003273 product_strategy_t strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07003274 int session,
3275 int id)
3276{
Eric Laurentb82e6b72019-11-22 17:25:04 -08003277 if (session != AUDIO_SESSION_DEVICE) {
3278 ssize_t index = mOutputs.indexOfKey(io);
Eric Laurente552edb2014-03-10 17:42:56 -07003279 if (index < 0) {
Eric Laurentb82e6b72019-11-22 17:25:04 -08003280 index = mInputs.indexOfKey(io);
3281 if (index < 0) {
3282 ALOGW("registerEffect() unknown io %d", io);
3283 return INVALID_OPERATION;
3284 }
Eric Laurente552edb2014-03-10 17:42:56 -07003285 }
3286 }
Eric Laurentbf8f69f2022-03-25 17:48:38 +01003287 bool isMusicEffect = (session != AUDIO_SESSION_OUTPUT_STAGE)
3288 && ((strategy == streamToStrategy(AUDIO_STREAM_MUSIC)
3289 || strategy == PRODUCT_STRATEGY_NONE));
3290 return mEffects.registerEffect(desc, io, session, id, isMusicEffect);
Eric Laurente552edb2014-03-10 17:42:56 -07003291}
3292
Eric Laurentc241b0d2018-11-28 09:08:49 -08003293status_t AudioPolicyManager::unregisterEffect(int id)
3294{
3295 if (mEffects.getEffect(id) == nullptr) {
3296 return INVALID_OPERATION;
3297 }
Eric Laurentc241b0d2018-11-28 09:08:49 -08003298 if (mEffects.isEffectEnabled(id)) {
3299 ALOGW("%s effect %d enabled", __FUNCTION__, id);
3300 setEffectEnabled(id, false);
3301 }
3302 return mEffects.unregisterEffect(id);
3303}
3304
3305status_t AudioPolicyManager::setEffectEnabled(int id, bool enabled)
3306{
3307 sp<EffectDescriptor> effect = mEffects.getEffect(id);
3308 if (effect == nullptr) {
3309 return INVALID_OPERATION;
3310 }
3311
3312 status_t status = mEffects.setEffectEnabled(id, enabled);
3313 if (status == NO_ERROR) {
3314 mInputs.trackEffectEnabled(effect, enabled);
3315 }
3316 return status;
3317}
3318
Eric Laurent6c796322019-04-09 14:13:17 -07003319
3320status_t AudioPolicyManager::moveEffectsToIo(const std::vector<int>& ids, audio_io_handle_t io)
3321{
3322 mEffects.moveEffects(ids, io);
3323 return NO_ERROR;
3324}
3325
Eric Laurentc75307b2015-03-17 15:29:32 -07003326bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
3327{
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003328 auto vs = toVolumeSource(stream, false);
3329 return vs != VOLUME_SOURCE_NONE ? mOutputs.isActive(vs, inPastMs) : false;
Eric Laurentc75307b2015-03-17 15:29:32 -07003330}
3331
3332bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream, uint32_t inPastMs) const
3333{
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003334 auto vs = toVolumeSource(stream, false);
3335 return vs != VOLUME_SOURCE_NONE ? mOutputs.isActiveRemotely(vs, inPastMs) : false;
Eric Laurentc75307b2015-03-17 15:29:32 -07003336}
3337
Eric Laurente0720872014-03-11 09:30:41 -07003338bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07003339{
3340 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003341 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08003342 if (inputDescriptor->isSourceActive(source)) {
Eric Laurente552edb2014-03-10 17:42:56 -07003343 return true;
3344 }
3345 }
3346 return false;
3347}
3348
Eric Laurent275e8e92014-11-30 15:14:47 -08003349// Register a list of custom mixes with their attributes and format.
3350// When a mix is registered, corresponding input and output profiles are
3351// added to the remote submix hw module. The profile contains only the
3352// parameters (sampling rate, format...) specified by the mix.
3353// The corresponding input remote submix device is also connected.
3354//
3355// When a remote submix device is connected, the address is checked to select the
3356// appropriate profile and the corresponding input or output stream is opened.
3357//
3358// When capture starts, getInputForAttr() will:
3359// - 1 look for a mix matching the address passed in attribtutes tags if any
3360// - 2 if none found, getDeviceForInputSource() will:
3361// - 2.1 look for a mix matching the attributes source
3362// - 2.2 if none found, default to device selection by policy rules
3363// At this time, the corresponding output remote submix device is also connected
3364// and active playback use cases can be transferred to this mix if needed when reconnecting
3365// after AudioTracks are invalidated
3366//
3367// When playback starts, getOutputForAttr() will:
3368// - 1 look for a mix matching the address passed in attribtutes tags if any
3369// - 2 if none found, look for a mix matching the attributes usage
3370// - 3 if none found, default to device and output selection by policy rules.
3371
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003372status_t AudioPolicyManager::registerPolicyMixes(const Vector<AudioMix>& mixes)
Eric Laurent275e8e92014-11-30 15:14:47 -08003373{
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003374 ALOGV("registerPolicyMixes() %zu mix(es)", mixes.size());
3375 status_t res = NO_ERROR;
Eric Laurentc209fe42020-06-05 18:11:23 -07003376 bool checkOutputs = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003377 sp<HwModule> rSubmixModule;
3378 // examine each mix's route type
3379 for (size_t i = 0; i < mixes.size(); i++) {
Eric Laurent97ac8712018-07-27 18:59:02 -07003380 AudioMix mix = mixes[i];
Kevin Rocard153f92d2018-12-18 18:33:28 -08003381 // Only capture of playback is allowed in LOOP_BACK & RENDER mode
3382 if (is_mix_loopback_render(mix.mRouteFlags) && mix.mMixType != MIX_TYPE_PLAYERS) {
3383 ALOGE("Unsupported Policy Mix %zu of %zu: "
3384 "Only capture of playback is allowed in LOOP_BACK & RENDER mode",
3385 i, mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003386 res = INVALID_OPERATION;
Eric Laurent275e8e92014-11-30 15:14:47 -08003387 break;
3388 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08003389 // LOOP_BACK and LOOP_BACK | RENDER have the same remote submix backend and are handled
3390 // in the same way.
Eric Laurent97ac8712018-07-27 18:59:02 -07003391 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003392 ALOGV("registerPolicyMixes() mix %zu of %zu is LOOP_BACK %d", i, mixes.size(),
3393 mix.mRouteFlags);
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003394 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003395 rSubmixModule = mHwModules.getModuleFromName(
3396 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
3397 if (rSubmixModule == 0) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003398 ALOGE("Unable to find audio module for submix, aborting mix %zu registration",
Mikhail Naganovd4120142017-12-06 15:49:22 -08003399 i);
3400 res = INVALID_OPERATION;
3401 break;
3402 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003403 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003404
Eric Laurent97ac8712018-07-27 18:59:02 -07003405 String8 address = mix.mDeviceAddress;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003406 audio_devices_t deviceTypeToMakeAvailable;
Eric Laurent97ac8712018-07-27 18:59:02 -07003407 if (mix.mMixType == MIX_TYPE_PLAYERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07003408 mix.mDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003409 deviceTypeToMakeAvailable = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
3410 } else {
3411 mix.mDeviceType = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
3412 deviceTypeToMakeAvailable = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Eric Laurent97ac8712018-07-27 18:59:02 -07003413 }
François Gaffie036e1e92015-03-19 10:16:24 +01003414
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003415 if (mPolicyMixes.registerMix(mix, 0 /*output desc*/) != NO_ERROR) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003416 ALOGE("Error registering mix %zu for address %s", i, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003417 res = INVALID_OPERATION;
3418 break;
3419 }
Eric Laurent97ac8712018-07-27 18:59:02 -07003420 audio_config_t outputConfig = mix.mFormat;
3421 audio_config_t inputConfig = mix.mFormat;
Eric Laurentc529cf62020-04-17 18:19:10 -07003422 // NOTE: audio flinger mixer does not support mono output: configure remote submix HAL
3423 // in stereo and let audio flinger do the channel conversion if needed.
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003424 outputConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
3425 inputConfig.channel_mask = AUDIO_CHANNEL_IN_STEREO;
jiabin5740f082019-08-19 15:08:30 -07003426 rSubmixModule->addOutputProfile(address.c_str(), &outputConfig,
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003427 AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address);
jiabin5740f082019-08-19 15:08:30 -07003428 rSubmixModule->addInputProfile(address.c_str(), &inputConfig,
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003429 AUDIO_DEVICE_IN_REMOTE_SUBMIX, address);
François Gaffie036e1e92015-03-19 10:16:24 +01003430
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003431 if ((res = setDeviceConnectionStateInt(deviceTypeToMakeAvailable,
jiabinc1de2df2019-05-07 14:26:40 -07003432 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
3433 address.string(), "remote-submix", AUDIO_FORMAT_DEFAULT)) != NO_ERROR) {
3434 ALOGE("Failed to set remote submix device available, type %u, address %s",
3435 mix.mDeviceType, address.string());
3436 break;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003437 }
Eric Laurent97ac8712018-07-27 18:59:02 -07003438 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
3439 String8 address = mix.mDeviceAddress;
Eric Laurent2c80be02019-01-23 18:06:37 -08003440 audio_devices_t type = mix.mDeviceType;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003441 ALOGV(" registerPolicyMixes() mix %zu of %zu is RENDER, dev=0x%X addr=%s",
Eric Laurent2c80be02019-01-23 18:06:37 -08003442 i, mixes.size(), type, address.string());
3443
3444 sp<DeviceDescriptor> device = mHwModules.getDeviceDescriptor(
3445 mix.mDeviceType, mix.mDeviceAddress,
3446 String8(), AUDIO_FORMAT_DEFAULT);
3447 if (device == nullptr) {
3448 res = INVALID_OPERATION;
3449 break;
3450 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003451
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003452 bool foundOutput = false;
Eric Laurentc529cf62020-04-17 18:19:10 -07003453 // First try to find an already opened output supporting the device
3454 for (size_t j = 0 ; j < mOutputs.size() && !foundOutput && res == NO_ERROR; j++) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003455 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurent2c80be02019-01-23 18:06:37 -08003456
Eric Laurentc529cf62020-04-17 18:19:10 -07003457 if (!desc->isDuplicated() && desc->supportedDevices().contains(device)) {
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003458 if (mPolicyMixes.registerMix(mix, desc) != NO_ERROR) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003459 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
3460 address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003461 res = INVALID_OPERATION;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003462 } else {
3463 foundOutput = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003464 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003465 }
3466 }
Eric Laurentc529cf62020-04-17 18:19:10 -07003467 // If no output found, try to find a direct output profile supporting the device
3468 for (size_t i = 0; i < mHwModules.size() && !foundOutput && res == NO_ERROR; i++) {
3469 sp<HwModule> module = mHwModules[i];
3470 for (size_t j = 0;
3471 j < module->getOutputProfiles().size() && !foundOutput && res == NO_ERROR;
3472 j++) {
3473 sp<IOProfile> profile = module->getOutputProfiles()[j];
3474 if (profile->isDirectOutput() && profile->supportsDevice(device)) {
3475 if (mPolicyMixes.registerMix(mix, nullptr) != NO_ERROR) {
3476 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
3477 address.string());
3478 res = INVALID_OPERATION;
3479 } else {
3480 foundOutput = true;
3481 }
3482 }
3483 }
3484 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003485 if (res != NO_ERROR) {
3486 ALOGE(" Error registering mix %zu for device 0x%X addr %s",
Eric Laurent2c80be02019-01-23 18:06:37 -08003487 i, type, address.string());
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003488 res = INVALID_OPERATION;
3489 break;
3490 } else if (!foundOutput) {
3491 ALOGE(" Output not found for mix %zu for device 0x%X addr %s",
Eric Laurent2c80be02019-01-23 18:06:37 -08003492 i, type, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003493 res = INVALID_OPERATION;
3494 break;
Eric Laurentc209fe42020-06-05 18:11:23 -07003495 } else {
3496 checkOutputs = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003497 }
Eric Laurentc722f302014-12-10 11:21:49 -08003498 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003499 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003500 if (res != NO_ERROR) {
3501 unregisterPolicyMixes(mixes);
Eric Laurentc209fe42020-06-05 18:11:23 -07003502 } else if (checkOutputs) {
3503 checkForDeviceAndOutputChanges();
3504 updateCallAndOutputRouting();
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003505 }
3506 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08003507}
3508
3509status_t AudioPolicyManager::unregisterPolicyMixes(Vector<AudioMix> mixes)
3510{
Eric Laurent7b279bb2015-12-14 10:18:23 -08003511 ALOGV("unregisterPolicyMixes() num mixes %zu", mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003512 status_t res = NO_ERROR;
Eric Laurentc209fe42020-06-05 18:11:23 -07003513 bool checkOutputs = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003514 sp<HwModule> rSubmixModule;
3515 // examine each mix's route type
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003516 for (const auto& mix : mixes) {
3517 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie036e1e92015-03-19 10:16:24 +01003518
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003519 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003520 rSubmixModule = mHwModules.getModuleFromName(
3521 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
3522 if (rSubmixModule == 0) {
3523 res = INVALID_OPERATION;
3524 continue;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003525 }
3526 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003527
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003528 String8 address = mix.mDeviceAddress;
Eric Laurent275e8e92014-11-30 15:14:47 -08003529
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003530 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003531 res = INVALID_OPERATION;
3532 continue;
3533 }
3534
Kevin Rocard04ed0462019-05-02 17:53:24 -07003535 for (auto device : {AUDIO_DEVICE_IN_REMOTE_SUBMIX, AUDIO_DEVICE_OUT_REMOTE_SUBMIX}) {
3536 if (getDeviceConnectionState(device, address.string()) ==
3537 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
3538 res = setDeviceConnectionStateInt(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
3539 address.string(), "remote-submix",
3540 AUDIO_FORMAT_DEFAULT);
3541 if (res != OK) {
3542 ALOGE("Error making RemoteSubmix device unavailable for mix "
3543 "with type %d, address %s", device, address.string());
3544 }
3545 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003546 }
jiabin5740f082019-08-19 15:08:30 -07003547 rSubmixModule->removeOutputProfile(address.c_str());
3548 rSubmixModule->removeInputProfile(address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003549
Kevin Rocard153f92d2018-12-18 18:33:28 -08003550 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003551 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003552 res = INVALID_OPERATION;
3553 continue;
Eric Laurentc209fe42020-06-05 18:11:23 -07003554 } else {
3555 checkOutputs = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003556 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003557 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003558 }
Eric Laurentc209fe42020-06-05 18:11:23 -07003559 if (res == NO_ERROR && checkOutputs) {
3560 checkForDeviceAndOutputChanges();
3561 updateCallAndOutputRouting();
3562 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003563 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08003564}
3565
Mikhail Naganov100f0122018-11-29 11:22:16 -08003566void AudioPolicyManager::dumpManualSurroundFormats(String8 *dst) const
3567{
3568 size_t i = 0;
3569 constexpr size_t audioFormatPrefixLen = sizeof("AUDIO_FORMAT_");
3570 for (const auto& fmt : mManualSurroundFormats) {
3571 if (i++ != 0) dst->append(", ");
3572 std::string sfmt;
3573 FormatConverter::toString(fmt, sfmt);
3574 dst->append(sfmt.size() >= audioFormatPrefixLen ?
3575 sfmt.c_str() + audioFormatPrefixLen - 1 : sfmt.c_str());
3576 }
3577}
3578
Eric Laurentc529cf62020-04-17 18:19:10 -07003579// Returns true if all devices types match the predicate and are supported by one HW module
3580bool AudioPolicyManager::areAllDevicesSupported(
jiabin6a02d532020-08-07 11:56:38 -07003581 const AudioDeviceTypeAddrVector& devices,
Eric Laurentc529cf62020-04-17 18:19:10 -07003582 std::function<bool(audio_devices_t)> predicate,
3583 const char *context) {
3584 for (size_t i = 0; i < devices.size(); i++) {
3585 sp<DeviceDescriptor> devDesc = mHwModules.getDeviceDescriptor(
jiabin0a488932020-08-07 17:32:40 -07003586 devices[i].mType, devices[i].getAddress(), String8(),
Eric Laurent0e26e3f2020-04-29 14:24:16 -07003587 AUDIO_FORMAT_DEFAULT, false /*allowToCreate*/, true /*matchAddress*/);
Eric Laurentc529cf62020-04-17 18:19:10 -07003588 if (devDesc == nullptr || (predicate != nullptr && !predicate(devices[i].mType))) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003589 ALOGE("%s: device type %#x address %s not supported or not match predicate",
jiabin0a488932020-08-07 17:32:40 -07003590 context, devices[i].mType, devices[i].getAddress());
Eric Laurentc529cf62020-04-17 18:19:10 -07003591 return false;
3592 }
3593 }
3594 return true;
3595}
3596
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003597status_t AudioPolicyManager::setUidDeviceAffinities(uid_t uid,
jiabin6a02d532020-08-07 11:56:38 -07003598 const AudioDeviceTypeAddrVector& devices) {
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003599 ALOGV("%s() uid=%d num devices %zu", __FUNCTION__, uid, devices.size());
Eric Laurentc529cf62020-04-17 18:19:10 -07003600 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
3601 return BAD_VALUE;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003602 }
3603 status_t res = mPolicyMixes.setUidDeviceAffinities(uid, devices);
Eric Laurentc529cf62020-04-17 18:19:10 -07003604 if (res != NO_ERROR) {
3605 ALOGE("%s() Could not set all device affinities for uid = %d", __FUNCTION__, uid);
3606 return res;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003607 }
Eric Laurentc529cf62020-04-17 18:19:10 -07003608
3609 checkForDeviceAndOutputChanges();
3610 updateCallAndOutputRouting();
3611
3612 return NO_ERROR;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003613}
3614
3615status_t AudioPolicyManager::removeUidDeviceAffinities(uid_t uid) {
3616 ALOGV("%s() uid=%d", __FUNCTION__, uid);
Oscar Azucena4b2a8212019-04-26 23:48:59 -07003617 status_t res = mPolicyMixes.removeUidDeviceAffinities(uid);
3618 if (res != NO_ERROR) {
Eric Laurentc529cf62020-04-17 18:19:10 -07003619 ALOGE("%s() Could not remove all device affinities for uid = %d",
Oscar Azucena4b2a8212019-04-26 23:48:59 -07003620 __FUNCTION__, uid);
3621 return INVALID_OPERATION;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003622 }
3623
Eric Laurentc529cf62020-04-17 18:19:10 -07003624 checkForDeviceAndOutputChanges();
3625 updateCallAndOutputRouting();
3626
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003627 return res;
3628}
3629
Eric Laurent2517af32020-11-25 15:31:27 +01003630
jiabin0a488932020-08-07 17:32:40 -07003631status_t AudioPolicyManager::setDevicesRoleForStrategy(product_strategy_t strategy,
3632 device_role_t role,
3633 const AudioDeviceTypeAddrVector &devices) {
3634 ALOGV("%s() strategy=%d role=%d %s", __func__, strategy, role,
3635 dumpAudioDeviceTypeAddrVector(devices).c_str());
Eric Laurentc529cf62020-04-17 18:19:10 -07003636
Eric Laurentc529cf62020-04-17 18:19:10 -07003637 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003638 return BAD_VALUE;
3639 }
jiabin0a488932020-08-07 17:32:40 -07003640 status_t status = mEngine->setDevicesRoleForStrategy(strategy, role, devices);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003641 if (status != NO_ERROR) {
jiabin0a488932020-08-07 17:32:40 -07003642 ALOGW("Engine could not set preferred devices %s for strategy %d role %d",
3643 dumpAudioDeviceTypeAddrVector(devices).c_str(), strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003644 return status;
3645 }
3646
3647 checkForDeviceAndOutputChanges();
Eric Laurent2517af32020-11-25 15:31:27 +01003648
3649 bool forceVolumeReeval = false;
3650 // FIXME: workaround for truncated touch sounds
3651 // to be removed when the problem is handled by system UI
3652 uint32_t delayMs = 0;
3653 if (strategy == mCommunnicationStrategy) {
3654 forceVolumeReeval = true;
3655 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
3656 updateInputRouting();
3657 }
3658 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003659
3660 return NO_ERROR;
3661}
3662
3663void AudioPolicyManager::updateCallAndOutputRouting(bool forceVolumeReeval, uint32_t delayMs)
3664{
3665 uint32_t waitMs = 0;
Eric Laurent96d1dda2022-03-14 17:14:19 +01003666 bool wasLeUnicastActive = isLeUnicastActive();
Francois Gaffie19fd6c52021-02-04 17:02:59 +01003667 if (updateCallRouting(true /*fromCache*/, delayMs, &waitMs) == NO_ERROR) {
Eric Laurentb36b4ac2020-08-21 12:50:41 -07003668 // Only apply special touch sound delay once
3669 delayMs = 0;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003670 }
3671 for (size_t i = 0; i < mOutputs.size(); i++) {
3672 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
3673 DeviceVector newDevices = getNewOutputDevices(outputDesc, true /*fromCache*/);
Francois Gaffie601801d2021-06-22 13:27:39 +02003674 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) ||
3675 (outputDesc != mPrimaryOutput && !isTelephonyRxOrTx(outputDesc))) {
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003676 // As done in setDeviceConnectionState, we could also fix default device issue by
3677 // preventing the force re-routing in case of default dev that distinguishes on address.
3678 // Let's give back to engine full device choice decision however.
Francois Gaffie601801d2021-06-22 13:27:39 +02003679 bool forceRouting = !newDevices.isEmpty();
3680 waitMs = setOutputDevices(outputDesc, newDevices, forceRouting, delayMs, nullptr,
3681 true /*requiresMuteCheck*/,
3682 !forceRouting /*requiresVolumeCheck*/);
Eric Laurentb36b4ac2020-08-21 12:50:41 -07003683 // Only apply special touch sound delay once
3684 delayMs = 0;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003685 }
3686 if (forceVolumeReeval && !newDevices.isEmpty()) {
3687 applyStreamVolumes(outputDesc, newDevices.types(), waitMs, true);
3688 }
3689 }
Eric Laurent96d1dda2022-03-14 17:14:19 +01003690 checkLeBroadcastRoutes(wasLeUnicastActive, nullptr, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003691}
3692
Eric Laurent2517af32020-11-25 15:31:27 +01003693void AudioPolicyManager::updateInputRouting() {
3694 for (const auto& activeDesc : mInputs.getActiveInputs()) {
Jaideep Sharma408349a2020-11-27 14:47:17 +05303695 // Skip for hotword recording as the input device switch
3696 // is handled within sound trigger HAL
3697 if (activeDesc->isSoundTrigger() && activeDesc->source() == AUDIO_SOURCE_HOTWORD) {
3698 continue;
3699 }
Eric Laurent2517af32020-11-25 15:31:27 +01003700 auto newDevice = getNewInputDevice(activeDesc);
3701 // Force new input selection if the new device can not be reached via current input
3702 if (activeDesc->mProfile->getSupportedDevices().contains(newDevice)) {
3703 setInputDevice(activeDesc->mIoHandle, newDevice);
3704 } else {
3705 closeInput(activeDesc->mIoHandle);
3706 }
3707 }
3708}
3709
jiabin0a488932020-08-07 17:32:40 -07003710status_t AudioPolicyManager::removeDevicesRoleForStrategy(product_strategy_t strategy,
3711 device_role_t role)
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003712{
Eric Laurentfecbceb2021-02-09 14:46:43 +01003713 ALOGV("%s() strategy=%d role=%d", __func__, strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003714
jiabin0a488932020-08-07 17:32:40 -07003715 status_t status = mEngine->removeDevicesRoleForStrategy(strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003716 if (status != NO_ERROR) {
Eric Laurent2517af32020-11-25 15:31:27 +01003717 ALOGV("Engine could not remove preferred device for strategy %d status %d",
3718 strategy, status);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003719 return status;
3720 }
3721
3722 checkForDeviceAndOutputChanges();
Eric Laurent2517af32020-11-25 15:31:27 +01003723
3724 bool forceVolumeReeval = false;
3725 // FIXME: workaround for truncated touch sounds
3726 // to be removed when the problem is handled by system UI
3727 uint32_t delayMs = 0;
3728 if (strategy == mCommunnicationStrategy) {
3729 forceVolumeReeval = true;
3730 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
3731 updateInputRouting();
3732 }
3733 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003734
3735 return NO_ERROR;
3736}
3737
jiabin0a488932020-08-07 17:32:40 -07003738status_t AudioPolicyManager::getDevicesForRoleAndStrategy(product_strategy_t strategy,
3739 device_role_t role,
3740 AudioDeviceTypeAddrVector &devices) {
3741 return mEngine->getDevicesForRoleAndStrategy(strategy, role, devices);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003742}
3743
Jiabin Huang3b98d322020-09-03 17:54:16 +00003744status_t AudioPolicyManager::setDevicesRoleForCapturePreset(
3745 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices) {
3746 ALOGV("%s() audioSource=%d role=%d %s", __func__, audioSource, role,
3747 dumpAudioDeviceTypeAddrVector(devices).c_str());
3748
Mikhail Naganov55773032020-10-01 15:08:13 -07003749 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003750 return BAD_VALUE;
3751 }
3752 status_t status = mEngine->setDevicesRoleForCapturePreset(audioSource, role, devices);
3753 ALOGW_IF(status != NO_ERROR,
3754 "Engine could not set preferred devices %s for audio source %d role %d",
3755 dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
3756
3757 return status;
3758}
3759
3760status_t AudioPolicyManager::addDevicesRoleForCapturePreset(
3761 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices) {
3762 ALOGV("%s() audioSource=%d role=%d %s", __func__, audioSource, role,
3763 dumpAudioDeviceTypeAddrVector(devices).c_str());
3764
Mikhail Naganov55773032020-10-01 15:08:13 -07003765 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003766 return BAD_VALUE;
3767 }
3768 status_t status = mEngine->addDevicesRoleForCapturePreset(audioSource, role, devices);
3769 ALOGW_IF(status != NO_ERROR,
3770 "Engine could not add preferred devices %s for audio source %d role %d",
3771 dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
3772
Eric Laurent2517af32020-11-25 15:31:27 +01003773 updateInputRouting();
Jiabin Huang3b98d322020-09-03 17:54:16 +00003774 return status;
3775}
3776
3777status_t AudioPolicyManager::removeDevicesRoleForCapturePreset(
3778 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector& devices)
3779{
3780 ALOGV("%s() audioSource=%d role=%d devices=%s", __func__, audioSource, role,
3781 dumpAudioDeviceTypeAddrVector(devices).c_str());
3782
Mikhail Naganov55773032020-10-01 15:08:13 -07003783 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003784 return BAD_VALUE;
3785 }
3786
3787 status_t status = mEngine->removeDevicesRoleForCapturePreset(
3788 audioSource, role, devices);
3789 ALOGW_IF(status != NO_ERROR,
3790 "Engine could not remove devices role (%d) for capture preset %d", role, audioSource);
3791
Eric Laurent2517af32020-11-25 15:31:27 +01003792 updateInputRouting();
Jiabin Huang3b98d322020-09-03 17:54:16 +00003793 return status;
3794}
3795
3796status_t AudioPolicyManager::clearDevicesRoleForCapturePreset(audio_source_t audioSource,
3797 device_role_t role) {
3798 ALOGV("%s() audioSource=%d role=%d", __func__, audioSource, role);
3799
3800 status_t status = mEngine->clearDevicesRoleForCapturePreset(audioSource, role);
3801 ALOGW_IF(status != NO_ERROR,
3802 "Engine could not clear devices role (%d) for capture preset %d", role, audioSource);
3803
Eric Laurent2517af32020-11-25 15:31:27 +01003804 updateInputRouting();
Jiabin Huang3b98d322020-09-03 17:54:16 +00003805 return status;
3806}
3807
3808status_t AudioPolicyManager::getDevicesForRoleAndCapturePreset(
3809 audio_source_t audioSource, device_role_t role, AudioDeviceTypeAddrVector &devices) {
3810 return mEngine->getDevicesForRoleAndCapturePreset(audioSource, role, devices);
3811}
3812
Oscar Azucena90e77632019-11-27 17:12:28 -08003813status_t AudioPolicyManager::setUserIdDeviceAffinities(int userId,
jiabin6a02d532020-08-07 11:56:38 -07003814 const AudioDeviceTypeAddrVector& devices) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01003815 ALOGV("%s() userId=%d num devices %zu", __func__, userId, devices.size());
Eric Laurentc529cf62020-04-17 18:19:10 -07003816 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
3817 return BAD_VALUE;
Oscar Azucena90e77632019-11-27 17:12:28 -08003818 }
Oscar Azucena90e77632019-11-27 17:12:28 -08003819 status_t status = mPolicyMixes.setUserIdDeviceAffinities(userId, devices);
3820 if (status != NO_ERROR) {
3821 ALOGE("%s() could not set device affinity for userId %d",
3822 __FUNCTION__, userId);
3823 return status;
3824 }
3825
3826 // reevaluate outputs for all devices
3827 checkForDeviceAndOutputChanges();
3828 updateCallAndOutputRouting();
3829
3830 return NO_ERROR;
3831}
3832
3833status_t AudioPolicyManager::removeUserIdDeviceAffinities(int userId) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01003834 ALOGV("%s() userId=%d", __FUNCTION__, userId);
Oscar Azucena90e77632019-11-27 17:12:28 -08003835 status_t status = mPolicyMixes.removeUserIdDeviceAffinities(userId);
3836 if (status != NO_ERROR) {
3837 ALOGE("%s() Could not remove all device affinities fo userId = %d",
3838 __FUNCTION__, userId);
3839 return status;
3840 }
3841
3842 // reevaluate outputs for all devices
3843 checkForDeviceAndOutputChanges();
3844 updateCallAndOutputRouting();
3845
3846 return NO_ERROR;
3847}
3848
Andy Hungc29d82b2018-10-05 12:23:17 -07003849void AudioPolicyManager::dump(String8 *dst) const
Eric Laurente552edb2014-03-10 17:42:56 -07003850{
Andy Hungc29d82b2018-10-05 12:23:17 -07003851 dst->appendFormat("\nAudioPolicyManager Dump: %p\n", this);
Mikhail Naganov0dbe87b2021-12-01 02:03:31 +00003852 dst->appendFormat(" Primary Output I/O handle: %d\n",
Eric Laurent87ffa392015-05-22 10:32:38 -07003853 hasPrimaryOutput() ? mPrimaryOutput->mIoHandle : AUDIO_IO_HANDLE_NONE);
Mikhail Naganov0d6a0332016-04-19 17:12:38 -07003854 std::string stateLiteral;
3855 AudioModeConverter::toString(mEngine->getPhoneState(), stateLiteral);
Andy Hungc29d82b2018-10-05 12:23:17 -07003856 dst->appendFormat(" Phone state: %s\n", stateLiteral.c_str());
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07003857 const char* forceUses[AUDIO_POLICY_FORCE_USE_CNT] = {
3858 "communications", "media", "record", "dock", "system",
3859 "HDMI system audio", "encoded surround output", "vibrate ringing" };
3860 for (audio_policy_force_use_t i = AUDIO_POLICY_FORCE_FOR_COMMUNICATION;
3861 i < AUDIO_POLICY_FORCE_USE_CNT; i = (audio_policy_force_use_t)((int)i + 1)) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08003862 audio_policy_forced_cfg_t forceUseValue = mEngine->getForceUse(i);
3863 dst->appendFormat(" Force use for %s: %d", forceUses[i], forceUseValue);
3864 if (i == AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND &&
3865 forceUseValue == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
3866 dst->append(" (MANUAL: ");
3867 dumpManualSurroundFormats(dst);
3868 dst->append(")");
3869 }
3870 dst->append("\n");
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07003871 }
Andy Hungc29d82b2018-10-05 12:23:17 -07003872 dst->appendFormat(" TTS output %savailable\n", mTtsOutputAvailable ? "" : "not ");
3873 dst->appendFormat(" Master mono: %s\n", mMasterMono ? "on" : "off");
Mikhail Naganovb3bcb4f2022-02-23 23:46:56 +00003874 dst->appendFormat(" Communication Strategy id: %d\n", mCommunnicationStrategy);
Andy Hungc29d82b2018-10-05 12:23:17 -07003875 dst->appendFormat(" Config source: %s\n", mConfig.getSource().c_str()); // getConfig not const
Eric Laurent2517af32020-11-25 15:31:27 +01003876
Mikhail Naganov0f413b22021-12-02 05:29:27 +00003877 dst->append("\n");
3878 mAvailableOutputDevices.dump(dst, String8("Available output"), 1);
3879 dst->append("\n");
3880 mAvailableInputDevices.dump(dst, String8("Available input"), 1);
Andy Hungc29d82b2018-10-05 12:23:17 -07003881 mHwModulesAll.dump(dst);
3882 mOutputs.dump(dst);
3883 mInputs.dump(dst);
Mikhail Naganov0f413b22021-12-02 05:29:27 +00003884 mEffects.dump(dst, 1);
Andy Hungc29d82b2018-10-05 12:23:17 -07003885 mAudioPatches.dump(dst);
3886 mPolicyMixes.dump(dst);
3887 mAudioSources.dump(dst);
François Gaffiec005e562018-11-06 15:04:49 +01003888
Kevin Rocardb99cc752019-03-21 20:52:24 -07003889 dst->appendFormat(" AllowedCapturePolicies:\n");
3890 for (auto& policy : mAllowedCapturePolicies) {
3891 dst->appendFormat(" - uid=%d flag_mask=%#x\n", policy.first, policy.second);
3892 }
3893
François Gaffiec005e562018-11-06 15:04:49 +01003894 dst->appendFormat("\nPolicy Engine dump:\n");
3895 mEngine->dump(dst);
Andy Hungc29d82b2018-10-05 12:23:17 -07003896}
3897
3898status_t AudioPolicyManager::dump(int fd)
3899{
3900 String8 result;
3901 dump(&result);
Andy Hungbb54e202018-10-05 11:42:02 -07003902 write(fd, result.string(), result.size());
Eric Laurente552edb2014-03-10 17:42:56 -07003903 return NO_ERROR;
3904}
3905
Kevin Rocardb99cc752019-03-21 20:52:24 -07003906status_t AudioPolicyManager::setAllowedCapturePolicy(uid_t uid, audio_flags_mask_t capturePolicy)
3907{
3908 mAllowedCapturePolicies[uid] = capturePolicy;
3909 return NO_ERROR;
3910}
3911
Eric Laurente552edb2014-03-10 17:42:56 -07003912// This function checks for the parameters which can be offloaded.
3913// This can be enhanced depending on the capability of the DSP and policy
3914// of the system.
Eric Laurent90fe31c2020-11-26 20:06:35 +01003915audio_offload_mode_t AudioPolicyManager::getOffloadSupport(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07003916{
Eric Laurent90fe31c2020-11-26 20:06:35 +01003917 ALOGV("%s: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07003918 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurent90fe31c2020-11-26 20:06:35 +01003919 __func__, offloadInfo.sample_rate, offloadInfo.channel_mask,
Eric Laurente552edb2014-03-10 17:42:56 -07003920 offloadInfo.format,
3921 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
3922 offloadInfo.has_video);
3923
jiabin2b9d5a12021-12-10 01:06:29 +00003924 if (!isOffloadPossible(offloadInfo)) {
Eric Laurent90fe31c2020-11-26 20:06:35 +01003925 return AUDIO_OFFLOAD_NOT_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07003926 }
3927
3928 // See if there is a profile to support this.
3929 // AUDIO_DEVICE_NONE
François Gaffie11d30102018-11-02 16:09:09 +01003930 sp<IOProfile> profile = getProfileForOutput(DeviceVector() /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07003931 offloadInfo.sample_rate,
3932 offloadInfo.format,
3933 offloadInfo.channel_mask,
Michael Chana94fbb22018-04-24 14:31:19 +10003934 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD,
3935 true /* directOnly */);
Eric Laurent94365442021-01-08 18:36:05 +01003936 ALOGV("%s: profile %sfound%s", __func__, profile != nullptr ? "" : "NOT ",
3937 (profile != nullptr && (profile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD) != 0)
3938 ? ", supports gapless" : "");
Eric Laurent90fe31c2020-11-26 20:06:35 +01003939 if (profile == nullptr) {
3940 return AUDIO_OFFLOAD_NOT_SUPPORTED;
3941 }
3942 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD) != 0) {
3943 return AUDIO_OFFLOAD_GAPLESS_SUPPORTED;
3944 }
3945 return AUDIO_OFFLOAD_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07003946}
3947
Michael Chana94fbb22018-04-24 14:31:19 +10003948bool AudioPolicyManager::isDirectOutputSupported(const audio_config_base_t& config,
3949 const audio_attributes_t& attributes) {
3950 audio_output_flags_t output_flags = AUDIO_OUTPUT_FLAG_NONE;
François Gaffie58d4be52018-11-06 15:30:12 +01003951 audio_flags_to_audio_output_flags(attributes.flags, &output_flags);
Dorin Drimus9901eb02022-01-14 11:36:51 +00003952 DeviceVector outputDevices = mEngine->getOutputDevicesForAttributes(attributes);
3953 sp<IOProfile> profile = getProfileForOutput(outputDevices,
Michael Chana94fbb22018-04-24 14:31:19 +10003954 config.sample_rate,
3955 config.format,
3956 config.channel_mask,
3957 output_flags,
3958 true /* directOnly */);
3959 ALOGV("%s() profile %sfound with name: %s, "
3960 "sample rate: %u, format: 0x%x, channel_mask: 0x%x, output flags: 0x%x",
3961 __FUNCTION__, profile != 0 ? "" : "NOT ",
jiabin5740f082019-08-19 15:08:30 -07003962 (profile != 0 ? profile->getTagName().c_str() : "null"),
Michael Chana94fbb22018-04-24 14:31:19 +10003963 config.sample_rate, config.format, config.channel_mask, output_flags);
Dorin Drimusecc9f422022-03-09 17:57:40 +01003964
3965 // also try the MSD module if compatible profile not found
3966 if (profile == nullptr) {
3967 profile = getMsdProfileForOutput(outputDevices,
3968 config.sample_rate,
3969 config.format,
3970 config.channel_mask,
3971 output_flags,
3972 true /* directOnly */);
3973 ALOGV("%s() MSD profile %sfound with name: %s, "
3974 "sample rate: %u, format: 0x%x, channel_mask: 0x%x, output flags: 0x%x",
3975 __FUNCTION__, profile != 0 ? "" : "NOT ",
3976 (profile != 0 ? profile->getTagName().c_str() : "null"),
3977 config.sample_rate, config.format, config.channel_mask, output_flags);
3978 }
3979 return (profile != nullptr);
Michael Chana94fbb22018-04-24 14:31:19 +10003980}
3981
jiabin2b9d5a12021-12-10 01:06:29 +00003982bool AudioPolicyManager::isOffloadPossible(const audio_offload_info_t &offloadInfo,
3983 bool durationIgnored) {
3984 if (mMasterMono) {
3985 return false; // no offloading if mono is set.
3986 }
3987
3988 // Check if offload has been disabled
3989 if (property_get_bool("audio.offload.disable", false /* default_value */)) {
3990 ALOGV("%s: offload disabled by audio.offload.disable", __func__);
3991 return false;
3992 }
3993
3994 // Check if stream type is music, then only allow offload as of now.
3995 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
3996 {
3997 ALOGV("%s: stream_type != MUSIC, returning false", __func__);
3998 return false;
3999 }
4000
4001 //TODO: enable audio offloading with video when ready
4002 const bool allowOffloadWithVideo =
4003 property_get_bool("audio.offload.video", false /* default_value */);
4004 if (offloadInfo.has_video && !allowOffloadWithVideo) {
4005 ALOGV("%s: has_video == true, returning false", __func__);
4006 return false;
4007 }
4008
4009 //If duration is less than minimum value defined in property, return false
4010 const int min_duration_secs = property_get_int32(
4011 "audio.offload.min.duration.secs", -1 /* default_value */);
4012 if (!durationIgnored) {
4013 if (min_duration_secs >= 0) {
4014 if (offloadInfo.duration_us < min_duration_secs * 1000000LL) {
4015 ALOGV("%s: Offload denied by duration < audio.offload.min.duration.secs(=%d)",
4016 __func__, min_duration_secs);
4017 return false;
4018 }
4019 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
4020 ALOGV("%s: Offload denied by duration < default min(=%u)",
4021 __func__, OFFLOAD_DEFAULT_MIN_DURATION_SECS);
4022 return false;
4023 }
4024 }
4025
4026 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
4027 // creating an offloaded track and tearing it down immediately after start when audioflinger
4028 // detects there is an active non offloadable effect.
4029 // FIXME: We should check the audio session here but we do not have it in this context.
4030 // This may prevent offloading in rare situations where effects are left active by apps
4031 // in the background.
4032 if (mEffects.isNonOffloadableEffectEnabled()) {
4033 return false;
4034 }
4035
4036 return true;
4037}
4038
4039audio_direct_mode_t AudioPolicyManager::getDirectPlaybackSupport(const audio_attributes_t *attr,
4040 const audio_config_t *config) {
4041 audio_offload_info_t offloadInfo = AUDIO_INFO_INITIALIZER;
4042 offloadInfo.format = config->format;
4043 offloadInfo.sample_rate = config->sample_rate;
4044 offloadInfo.channel_mask = config->channel_mask;
4045 offloadInfo.stream_type = mEngine->getStreamTypeForAttributes(*attr);
4046 offloadInfo.has_video = false;
4047 offloadInfo.is_streaming = false;
4048 const bool offloadPossible = isOffloadPossible(offloadInfo, true /*durationIgnored*/);
4049
4050 audio_direct_mode_t directMode = AUDIO_DIRECT_NOT_SUPPORTED;
4051 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
4052 audio_flags_to_audio_output_flags(attr->flags, &flags);
4053 // only retain flags that will drive compressed offload or passthrough
4054 uint32_t relevantFlags = AUDIO_OUTPUT_FLAG_HW_AV_SYNC;
4055 if (offloadPossible) {
4056 relevantFlags |= AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD;
4057 }
4058 flags = (audio_output_flags_t)((flags & relevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
4059
Dorin Drimusfae3c642022-03-17 18:36:30 +01004060 DeviceVector engineOutputDevices = mEngine->getOutputDevicesForAttributes(*attr);
jiabin2b9d5a12021-12-10 01:06:29 +00004061 for (const auto& hwModule : mHwModules) {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004062 DeviceVector outputDevices = engineOutputDevices;
4063 // the MSD module checks for different conditions and output devices
4064 if (strcmp(hwModule->getName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0) {
4065 if (!msdHasPatchesToAllDevices(engineOutputDevices.toTypeAddrVector())) {
4066 continue;
4067 }
4068 outputDevices = getMsdAudioOutDevices();
4069 }
jiabin2b9d5a12021-12-10 01:06:29 +00004070 for (const auto& curProfile : hwModule->getOutputProfiles()) {
jiabinc8f7dfc2022-01-06 18:42:08 +00004071 if (!curProfile->isCompatibleProfile(outputDevices,
jiabin2b9d5a12021-12-10 01:06:29 +00004072 config->sample_rate, nullptr /*updatedSamplingRate*/,
4073 config->format, nullptr /*updatedFormat*/,
4074 config->channel_mask, nullptr /*updatedChannelMask*/,
4075 flags)) {
4076 continue;
4077 }
4078 // reject profiles not corresponding to a device currently available
4079 if (!mAvailableOutputDevices.containsAtLeastOne(curProfile->getSupportedDevices())) {
4080 continue;
4081 }
4082 if ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)
4083 != AUDIO_OUTPUT_FLAG_NONE) {
jiabinc6132d62022-01-01 07:36:31 +00004084 if ((directMode & AUDIO_DIRECT_OFFLOAD_GAPLESS_SUPPORTED)
jiabin2b9d5a12021-12-10 01:06:29 +00004085 != AUDIO_DIRECT_NOT_SUPPORTED) {
4086 // Already reports offload gapless supported. No need to report offload support.
4087 continue;
4088 }
4089 if ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD)
4090 != AUDIO_OUTPUT_FLAG_NONE) {
4091 // If offload gapless is reported, no need to report offload support.
4092 directMode = (audio_direct_mode_t) ((directMode &
4093 ~AUDIO_DIRECT_OFFLOAD_SUPPORTED) |
4094 AUDIO_DIRECT_OFFLOAD_GAPLESS_SUPPORTED);
4095 } else {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004096 directMode = (audio_direct_mode_t)(directMode | AUDIO_DIRECT_OFFLOAD_SUPPORTED);
jiabin2b9d5a12021-12-10 01:06:29 +00004097 }
4098 } else {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004099 directMode = (audio_direct_mode_t) (directMode | AUDIO_DIRECT_BITSTREAM_SUPPORTED);
jiabin2b9d5a12021-12-10 01:06:29 +00004100 }
4101 }
4102 }
4103 return directMode;
4104}
4105
Dorin Drimusf2196d82022-01-03 12:11:18 +01004106status_t AudioPolicyManager::getDirectProfilesForAttributes(const audio_attributes_t* attr,
4107 AudioProfileVector& audioProfilesVector) {
Dorin Drimus17112632022-09-23 15:28:51 +00004108 if (mEffects.isNonOffloadableEffectEnabled()) {
4109 return OK;
4110 }
jiabinf1c73972022-04-14 16:28:52 -07004111 DeviceVector devices;
4112 status_t status = getDevicesForAttributes(*attr, devices, false /* forVolume */);
Dorin Drimusf2196d82022-01-03 12:11:18 +01004113 if (status != OK) {
4114 return status;
4115 }
4116 ALOGV("%s: found %zu output devices for attributes.", __func__, devices.size());
4117 if (devices.empty()) {
4118 return OK; // no output devices for the attributes
4119 }
jiabinf1c73972022-04-14 16:28:52 -07004120 return getProfilesForDevices(devices, audioProfilesVector,
4121 AUDIO_OUTPUT_FLAG_DIRECT /*flags*/, false /*isInput*/);
Dorin Drimusf2196d82022-01-03 12:11:18 +01004122}
4123
Eric Laurent6a94d692014-05-20 11:18:06 -07004124status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
4125 audio_port_type_t type,
4126 unsigned int *num_ports,
jiabin19cdba52020-11-24 11:28:58 -08004127 struct audio_port_v7 *ports,
Eric Laurent6a94d692014-05-20 11:18:06 -07004128 unsigned int *generation)
4129{
jiabin19cdba52020-11-24 11:28:58 -08004130 if (num_ports == nullptr || (*num_ports != 0 && ports == nullptr) ||
4131 generation == nullptr) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004132 return BAD_VALUE;
4133 }
4134 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
jiabin19cdba52020-11-24 11:28:58 -08004135 if (ports == nullptr) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004136 *num_ports = 0;
4137 }
4138
4139 size_t portsWritten = 0;
4140 size_t portsMax = *num_ports;
4141 *num_ports = 0;
4142 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07004143 // do not report devices with type AUDIO_DEVICE_IN_STUB or AUDIO_DEVICE_OUT_STUB
4144 // as they are used by stub HALs by convention
Eric Laurent6a94d692014-05-20 11:18:06 -07004145 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004146 for (const auto& dev : mAvailableOutputDevices) {
4147 if (dev->type() == AUDIO_DEVICE_OUT_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07004148 continue;
4149 }
4150 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004151 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07004152 }
4153 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07004154 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004155 }
4156 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004157 for (const auto& dev : mAvailableInputDevices) {
4158 if (dev->type() == AUDIO_DEVICE_IN_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07004159 continue;
4160 }
4161 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004162 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07004163 }
4164 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07004165 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004166 }
4167 }
4168 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
4169 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
4170 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
4171 mInputs[i]->toAudioPort(&ports[portsWritten++]);
4172 }
4173 *num_ports += mInputs.size();
4174 }
4175 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent84c70242014-06-23 08:46:27 -07004176 size_t numOutputs = 0;
4177 for (size_t i = 0; i < mOutputs.size(); i++) {
4178 if (!mOutputs[i]->isDuplicated()) {
4179 numOutputs++;
4180 if (portsWritten < portsMax) {
4181 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
4182 }
4183 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004184 }
Eric Laurent84c70242014-06-23 08:46:27 -07004185 *num_ports += numOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07004186 }
4187 }
4188 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07004189 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
Eric Laurent6a94d692014-05-20 11:18:06 -07004190 return NO_ERROR;
4191}
4192
jiabin19cdba52020-11-24 11:28:58 -08004193status_t AudioPolicyManager::getAudioPort(struct audio_port_v7 *port)
Eric Laurent6a94d692014-05-20 11:18:06 -07004194{
Eric Laurent99fcae42018-05-17 16:59:18 -07004195 if (port == nullptr || port->id == AUDIO_PORT_HANDLE_NONE) {
4196 return BAD_VALUE;
4197 }
4198 sp<DeviceDescriptor> dev = mAvailableOutputDevices.getDeviceFromId(port->id);
4199 if (dev != 0) {
4200 dev->toAudioPort(port);
4201 return NO_ERROR;
4202 }
4203 dev = mAvailableInputDevices.getDeviceFromId(port->id);
4204 if (dev != 0) {
4205 dev->toAudioPort(port);
4206 return NO_ERROR;
4207 }
4208 sp<SwAudioOutputDescriptor> out = mOutputs.getOutputFromId(port->id);
4209 if (out != 0) {
4210 out->toAudioPort(port);
4211 return NO_ERROR;
4212 }
4213 sp<AudioInputDescriptor> in = mInputs.getInputFromId(port->id);
4214 if (in != 0) {
4215 in->toAudioPort(port);
4216 return NO_ERROR;
4217 }
4218 return BAD_VALUE;
Eric Laurent6a94d692014-05-20 11:18:06 -07004219}
4220
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004221status_t AudioPolicyManager::createAudioPatch(const struct audio_patch *patch,
4222 audio_patch_handle_t *handle,
4223 uid_t uid)
Eric Laurent6a94d692014-05-20 11:18:06 -07004224{
François Gaffieafd4cea2019-11-18 15:50:22 +01004225 ALOGV("%s", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004226 if (handle == NULL || patch == NULL) {
4227 return BAD_VALUE;
4228 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004229 ALOGV("%s num sources %d num sinks %d", __func__, patch->num_sources, patch->num_sinks);
Mikhail Naganovac9858b2018-06-15 13:12:37 -07004230 if (!audio_patch_is_valid(patch)) {
Eric Laurent874c42872014-08-08 15:13:39 -07004231 return BAD_VALUE;
4232 }
4233 // only one source per audio patch supported for now
4234 if (patch->num_sources > 1) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004235 return INVALID_OPERATION;
4236 }
Eric Laurent874c42872014-08-08 15:13:39 -07004237 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004238 return INVALID_OPERATION;
4239 }
Eric Laurent874c42872014-08-08 15:13:39 -07004240 for (size_t i = 0; i < patch->num_sinks; i++) {
4241 if (patch->sinks[i].role != AUDIO_PORT_ROLE_SINK) {
4242 return INVALID_OPERATION;
4243 }
4244 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004245
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004246 sp<DeviceDescriptor> srcDevice = mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
4247 sp<DeviceDescriptor> sinkDevice = mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id);
4248 if (srcDevice == nullptr || sinkDevice == nullptr) {
4249 ALOGW("%s could not create patch, invalid sink and/or source device(s)", __func__);
4250 return BAD_VALUE;
4251 }
4252 ALOGV("%s between source %s and sink %s", __func__,
4253 srcDevice->toString().c_str(), sinkDevice->toString().c_str());
4254 audio_port_handle_t portId = PolicyAudioPort::getNextUniqueId();
4255 // Default attributes, default volume priority, not to infer with non raw audio patches.
4256 audio_attributes_t attributes = attributes_initializer(AUDIO_USAGE_MEDIA);
4257 const struct audio_port_config *source = &patch->sources[0];
4258 sp<SourceClientDescriptor> sourceDesc =
4259 new InternalSourceClientDescriptor(
4260 portId, uid, attributes, *source, srcDevice, sinkDevice,
4261 mEngine->getProductStrategyForAttributes(attributes), toVolumeSource(attributes));
4262
4263 status_t status =
4264 connectAudioSourceToSink(sourceDesc, sinkDevice, patch, *handle, uid, 0 /* delayMs */);
4265
4266 if (status != NO_ERROR) {
4267 return INVALID_OPERATION;
4268 }
4269 mAudioSources.add(portId, sourceDesc);
4270 return NO_ERROR;
4271}
4272
4273status_t AudioPolicyManager::connectAudioSourceToSink(
4274 const sp<SourceClientDescriptor>& sourceDesc, const sp<DeviceDescriptor> &sinkDevice,
4275 const struct audio_patch *patch,
4276 audio_patch_handle_t &handle,
4277 uid_t uid, uint32_t delayMs)
4278{
4279 status_t status = createAudioPatchInternal(patch, &handle, uid, delayMs, sourceDesc);
4280 if (status != NO_ERROR || mAudioPatches.indexOfKey(handle) < 0) {
4281 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
4282 return INVALID_OPERATION;
4283 }
4284 sourceDesc->connect(handle, sinkDevice);
4285 if (isMsdPatch(handle)) {
4286 return NO_ERROR;
4287 }
4288 // SW Bridge? (@todo: HW bridge, keep track of HwOutput for device selection "reconsideration")
4289 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
4290 ALOG_ASSERT(swOutput != nullptr, "%s: a swOutput shall always be associated", __func__);
4291 if (swOutput->getClient(sourceDesc->portId()) != nullptr) {
4292 ALOGW("%s source portId has already been attached to outputDesc", __func__);
4293 goto FailurePatchAdded;
4294 }
4295 status = swOutput->start();
4296 if (status != NO_ERROR) {
4297 goto FailureSourceAdded;
4298 }
4299 swOutput->addClient(sourceDesc);
4300 status = startSource(swOutput, sourceDesc, &delayMs);
4301 if (status != NO_ERROR) {
4302 ALOGW("%s failed to start source, error %d", __FUNCTION__, status);
4303 goto FailureSourceActive;
4304 }
4305 if (delayMs != 0) {
4306 usleep(delayMs * 1000);
4307 }
4308 return NO_ERROR;
4309
4310FailureSourceActive:
4311 swOutput->stop();
4312 releaseOutput(sourceDesc->portId());
4313FailureSourceAdded:
4314 sourceDesc->setSwOutput(nullptr);
4315FailurePatchAdded:
4316 releaseAudioPatchInternal(handle);
4317 return INVALID_OPERATION;
4318}
4319
4320status_t AudioPolicyManager::createAudioPatchInternal(const struct audio_patch *patch,
4321 audio_patch_handle_t *handle,
4322 uid_t uid, uint32_t delayMs,
4323 const sp<SourceClientDescriptor>& sourceDesc)
4324{
4325 ALOGV("%s num sources %d num sinks %d", __func__, patch->num_sources, patch->num_sinks);
Eric Laurent6a94d692014-05-20 11:18:06 -07004326 sp<AudioPatch> patchDesc;
4327 ssize_t index = mAudioPatches.indexOfKey(*handle);
4328
François Gaffieafd4cea2019-11-18 15:50:22 +01004329 ALOGV("%s source id %d role %d type %d", __func__, patch->sources[0].id,
4330 patch->sources[0].role,
4331 patch->sources[0].type);
Eric Laurent874c42872014-08-08 15:13:39 -07004332#if LOG_NDEBUG == 0
4333 for (size_t i = 0; i < patch->num_sinks; i++) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004334 ALOGV("%s sink %zu: id %d role %d type %d", __func__ ,i, patch->sinks[i].id,
4335 patch->sinks[i].role,
4336 patch->sinks[i].type);
Eric Laurent874c42872014-08-08 15:13:39 -07004337 }
4338#endif
Eric Laurent6a94d692014-05-20 11:18:06 -07004339
4340 if (index >= 0) {
4341 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01004342 ALOGV("%s mUidCached %d patchDesc->mUid %d uid %d",
4343 __func__, mUidCached, patchDesc->getUid(), uid);
4344 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004345 return INVALID_OPERATION;
4346 }
4347 } else {
Glenn Kastena13cde92016-03-28 15:26:02 -07004348 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07004349 }
4350
4351 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004352 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004353 if (outputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004354 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004355 return BAD_VALUE;
4356 }
Eric Laurent84c70242014-06-23 08:46:27 -07004357 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
4358 outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004359 if (patchDesc != 0) {
4360 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004361 ALOGV("%s source id differs for patch current id %d new id %d",
4362 __func__, patchDesc->mPatch.sources[0].id, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004363 return BAD_VALUE;
4364 }
4365 }
Eric Laurent874c42872014-08-08 15:13:39 -07004366 DeviceVector devices;
4367 for (size_t i = 0; i < patch->num_sinks; i++) {
4368 // Only support mix to devices connection
4369 // TODO add support for mix to mix connection
4370 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004371 ALOGV("%s source mix but sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07004372 return INVALID_OPERATION;
4373 }
4374 sp<DeviceDescriptor> devDesc =
4375 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
4376 if (devDesc == 0) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004377 ALOGV("%s out device not found for id %d", __func__, patch->sinks[i].id);
Eric Laurent874c42872014-08-08 15:13:39 -07004378 return BAD_VALUE;
4379 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004380
François Gaffie11d30102018-11-02 16:09:09 +01004381 if (!outputDesc->mProfile->isCompatibleProfile(DeviceVector(devDesc),
Eric Laurent874c42872014-08-08 15:13:39 -07004382 patch->sources[0].sample_rate,
François Gaffie53615e22015-03-19 09:24:12 +01004383 NULL, // updatedSamplingRate
4384 patch->sources[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07004385 NULL, // updatedFormat
François Gaffie53615e22015-03-19 09:24:12 +01004386 patch->sources[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07004387 NULL, // updatedChannelMask
François Gaffie53615e22015-03-19 09:24:12 +01004388 AUDIO_OUTPUT_FLAG_NONE /*FIXME*/)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004389 ALOGV("%s profile not supported for device %08x", __func__, devDesc->type());
Eric Laurent874c42872014-08-08 15:13:39 -07004390 return INVALID_OPERATION;
4391 }
4392 devices.add(devDesc);
4393 }
4394 if (devices.size() == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004395 return INVALID_OPERATION;
4396 }
Eric Laurent874c42872014-08-08 15:13:39 -07004397
Eric Laurent6a94d692014-05-20 11:18:06 -07004398 // TODO: reconfigure output format and channels here
François Gaffieafd4cea2019-11-18 15:50:22 +01004399 ALOGV("%s setting device %s on output %d",
4400 __func__, dumpDeviceTypes(devices.types()).c_str(), outputDesc->mIoHandle);
François Gaffie11d30102018-11-02 16:09:09 +01004401 setOutputDevices(outputDesc, devices, true, 0, 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 setOutputDevice() 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 setOutputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004412 return INVALID_OPERATION;
4413 }
4414 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
4415 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
4416 // input device to input mix connection
Eric Laurent874c42872014-08-08 15:13:39 -07004417 // only one sink supported when connecting an input device to a mix
4418 if (patch->num_sinks > 1) {
4419 return INVALID_OPERATION;
4420 }
François Gaffie53615e22015-03-19 09:24:12 +01004421 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004422 if (inputDesc == NULL) {
4423 return BAD_VALUE;
4424 }
4425 if (patchDesc != 0) {
4426 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
4427 return BAD_VALUE;
4428 }
4429 }
François Gaffie11d30102018-11-02 16:09:09 +01004430 sp<DeviceDescriptor> device =
Eric Laurent6a94d692014-05-20 11:18:06 -07004431 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01004432 if (device == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004433 return BAD_VALUE;
4434 }
4435
François Gaffie11d30102018-11-02 16:09:09 +01004436 if (!inputDesc->mProfile->isCompatibleProfile(DeviceVector(device),
Eric Laurent275e8e92014-11-30 15:14:47 -08004437 patch->sinks[0].sample_rate,
4438 NULL, /*updatedSampleRate*/
4439 patch->sinks[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07004440 NULL, /*updatedFormat*/
Eric Laurent275e8e92014-11-30 15:14:47 -08004441 patch->sinks[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07004442 NULL, /*updatedChannelMask*/
Eric Laurent275e8e92014-11-30 15:14:47 -08004443 // FIXME for the parameter type,
4444 // and the NONE
4445 (audio_output_flags_t)
Glenn Kasten6a8ab052014-07-24 14:08:35 -07004446 AUDIO_INPUT_FLAG_NONE)) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004447 return INVALID_OPERATION;
4448 }
4449 // TODO: reconfigure output format and channels here
François Gaffieafd4cea2019-11-18 15:50:22 +01004450 ALOGV("%s setting device %s on output %d", __func__,
François Gaffie11d30102018-11-02 16:09:09 +01004451 device->toString().c_str(), inputDesc->mIoHandle);
4452 setInputDevice(inputDesc->mIoHandle, device, true, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004453 index = mAudioPatches.indexOfKey(*handle);
4454 if (index >= 0) {
4455 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004456 ALOGW("%s setInputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004457 }
4458 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01004459 patchDesc->setUid(uid);
4460 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004461 } else {
François Gaffieafd4cea2019-11-18 15:50:22 +01004462 ALOGW("%s setInputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004463 return INVALID_OPERATION;
4464 }
4465 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
4466 // device to device connection
4467 if (patchDesc != 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07004468 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004469 return BAD_VALUE;
4470 }
4471 }
François Gaffie11d30102018-11-02 16:09:09 +01004472 sp<DeviceDescriptor> srcDevice =
Eric Laurent6a94d692014-05-20 11:18:06 -07004473 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01004474 if (srcDevice == 0) {
Eric Laurent58f8eb72014-09-12 16:19:41 -07004475 return BAD_VALUE;
4476 }
Eric Laurent874c42872014-08-08 15:13:39 -07004477
Eric Laurent6a94d692014-05-20 11:18:06 -07004478 //update source and sink with our own data as the data passed in the patch may
4479 // be incomplete.
François Gaffieafd4cea2019-11-18 15:50:22 +01004480 PatchBuilder patchBuilder;
4481 audio_port_config sourcePortConfig = {};
Dean Wheatley8bee85a2021-02-10 16:02:23 +11004482
4483 // if first sink is to MSD, establish single MSD patch
4484 if (getMsdAudioOutDevices().contains(
4485 mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id))) {
4486 ALOGV("%s patching to MSD", __FUNCTION__);
4487 patchBuilder = buildMsdPatch(false /*msdIsSource*/, srcDevice);
4488 goto installPatch;
4489 }
4490
François Gaffieafd4cea2019-11-18 15:50:22 +01004491 srcDevice->toAudioPortConfig(&sourcePortConfig, &patch->sources[0]);
4492 patchBuilder.addSource(sourcePortConfig);
Eric Laurent6a94d692014-05-20 11:18:06 -07004493
Eric Laurent874c42872014-08-08 15:13:39 -07004494 for (size_t i = 0; i < patch->num_sinks; i++) {
4495 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004496 ALOGV("%s source device but one sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07004497 return INVALID_OPERATION;
4498 }
François Gaffie11d30102018-11-02 16:09:09 +01004499 sp<DeviceDescriptor> sinkDevice =
Eric Laurent874c42872014-08-08 15:13:39 -07004500 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
François Gaffie11d30102018-11-02 16:09:09 +01004501 if (sinkDevice == 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07004502 return BAD_VALUE;
4503 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004504 audio_port_config sinkPortConfig = {};
4505 sinkDevice->toAudioPortConfig(&sinkPortConfig, &patch->sinks[i]);
4506 patchBuilder.addSink(sinkPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07004507
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004508 // Whatever Sw or Hw bridge, we do attach an SwOutput to an Audio Source for
4509 // volume management purpose (tracking activity)
4510 // In case of Hw bridge, it is a Work Around. The mixPort used is the one declared
4511 // in config XML to reach the sink so that is can be declared as available.
4512 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
4513 sp<SwAudioOutputDescriptor> outputDesc = nullptr;
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004514 if (!sourceDesc->isInternal()) {
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004515 // take care of dynamic routing for SwOutput selection,
4516 audio_attributes_t attributes = sourceDesc->attributes();
4517 audio_stream_type_t stream = sourceDesc->stream();
4518 audio_attributes_t resultAttr;
4519 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
4520 config.sample_rate = sourceDesc->config().sample_rate;
François Gaffie2a24db42022-04-04 16:45:02 +02004521 audio_channel_mask_t sourceMask = sourceDesc->config().channel_mask;
4522 config.channel_mask =
4523 (audio_channel_mask_get_representation(sourceMask)
4524 == AUDIO_CHANNEL_REPRESENTATION_INDEX) ? sourceMask
4525 : audio_channel_mask_in_to_out(sourceMask);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004526 config.format = sourceDesc->config().format;
4527 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
4528 audio_port_handle_t selectedDeviceId = AUDIO_PORT_HANDLE_NONE;
4529 bool isRequestedDeviceForExclusiveUse = false;
4530 output_type_t outputType;
Eric Laurentb0a7bc92022-04-05 15:06:08 +02004531 bool isSpatialized;
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004532 getOutputForAttrInt(&resultAttr, &output, AUDIO_SESSION_NONE, &attributes,
4533 &stream, sourceDesc->uid(), &config, &flags,
4534 &selectedDeviceId, &isRequestedDeviceForExclusiveUse,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02004535 nullptr, &outputType, &isSpatialized);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004536 if (output == AUDIO_IO_HANDLE_NONE) {
4537 ALOGV("%s no output for device %s",
4538 __FUNCTION__, sinkDevice->toString().c_str());
4539 return INVALID_OPERATION;
4540 }
4541 outputDesc = mOutputs.valueFor(output);
4542 if (outputDesc->isDuplicated()) {
4543 ALOGE("%s output is duplicated", __func__);
4544 return INVALID_OPERATION;
4545 }
François Gaffie7e39df22022-04-26 12:48:49 +02004546 bool closeOutput = outputDesc->mDirectOpenCount != 0;
4547 sourceDesc->setSwOutput(outputDesc, closeOutput);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004548 } else {
4549 // Same for "raw patches" aka created from createAudioPatch API
4550 SortedVector<audio_io_handle_t> outputs =
4551 getOutputsForDevices(DeviceVector(sinkDevice), mOutputs);
4552 // if the sink device is reachable via an opened output stream, request to
4553 // go via this output stream by adding a second source to the patch
4554 // description
4555 output = selectOutput(outputs);
4556 if (output == AUDIO_IO_HANDLE_NONE) {
4557 ALOGE("%s no output available for internal patch sink", __func__);
4558 return INVALID_OPERATION;
4559 }
4560 outputDesc = mOutputs.valueFor(output);
4561 if (outputDesc->isDuplicated()) {
4562 ALOGV("%s output for device %s is duplicated",
4563 __func__, sinkDevice->toString().c_str());
4564 return INVALID_OPERATION;
4565 }
François Gaffie7e39df22022-04-26 12:48:49 +02004566 sourceDesc->setSwOutput(outputDesc, /* closeOutput= */ false);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004567 }
Eric Laurent3bcf8592015-04-03 12:13:24 -07004568 // create a software bridge in PatchPanel if:
Scott Randolphf3172402018-01-23 17:06:53 -08004569 // - source and sink devices are on different HW modules OR
Eric Laurent3bcf8592015-04-03 12:13:24 -07004570 // - audio HAL version is < 3.0
Francois Gaffie99896da2018-04-09 11:05:33 +02004571 // - audio HAL version is >= 3.0 but no route has been declared between devices
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004572 // - called from startAudioSource (aka sourceDesc is not internal) and source device
4573 // does not have a gain controller
François Gaffie11d30102018-11-02 16:09:09 +01004574 if (!srcDevice->hasSameHwModuleAs(sinkDevice) ||
4575 (srcDevice->getModuleVersionMajor() < 3) ||
François Gaffieafd4cea2019-11-18 15:50:22 +01004576 !srcDevice->getModule()->supportsPatch(srcDevice, sinkDevice) ||
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004577 (!sourceDesc->isInternal() &&
François Gaffieafd4cea2019-11-18 15:50:22 +01004578 srcDevice->getAudioPort()->getGains().size() == 0)) {
Eric Laurent3bcf8592015-04-03 12:13:24 -07004579 // support only one sink device for now to simplify output selection logic
Eric Laurent874c42872014-08-08 15:13:39 -07004580 if (patch->num_sinks > 1) {
Eric Laurent83b88082014-06-20 18:31:16 -07004581 return INVALID_OPERATION;
4582 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004583 sourceDesc->setUseSwBridge();
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004584 if (outputDesc != nullptr) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004585 audio_port_config srcMixPortConfig = {};
Ytai Ben-Tsvic9d2a912021-11-22 16:43:09 -08004586 outputDesc->toAudioPortConfig(&srcMixPortConfig, nullptr);
François Gaffieafd4cea2019-11-18 15:50:22 +01004587 // for volume control, we may need a valid stream
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004588 srcMixPortConfig.ext.mix.usecase.stream = !sourceDesc->isInternal() ?
4589 mEngine->getStreamTypeForAttributes(sourceDesc->attributes()) :
4590 AUDIO_STREAM_PATCH;
François Gaffieafd4cea2019-11-18 15:50:22 +01004591 patchBuilder.addSource(srcMixPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07004592 }
Eric Laurent83b88082014-06-20 18:31:16 -07004593 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004594 }
4595 // TODO: check from routing capabilities in config file and other conflicting patches
4596
Dean Wheatley8bee85a2021-02-10 16:02:23 +11004597installPatch:
François Gaffieafd4cea2019-11-18 15:50:22 +01004598 status_t status = installPatch(
4599 __func__, index, handle, patchBuilder.patch(), delayMs, uid, &patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07004600 if (status != NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004601 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
Eric Laurent6a94d692014-05-20 11:18:06 -07004602 return INVALID_OPERATION;
4603 }
4604 } else {
4605 return BAD_VALUE;
4606 }
4607 } else {
4608 return BAD_VALUE;
4609 }
4610 return NO_ERROR;
4611}
4612
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004613status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle, uid_t uid)
Eric Laurent6a94d692014-05-20 11:18:06 -07004614{
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004615 ALOGV("%s patch %d", __func__, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004616 ssize_t index = mAudioPatches.indexOfKey(handle);
4617
4618 if (index < 0) {
4619 return BAD_VALUE;
4620 }
4621 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01004622 ALOGV("%s() mUidCached %d patchDesc->mUid %d uid %d",
4623 __func__, mUidCached, patchDesc->getUid(), uid);
4624 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004625 return INVALID_OPERATION;
4626 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004627 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
4628 for (size_t i = 0; i < mAudioSources.size(); i++) {
4629 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
4630 if (sourceDesc != nullptr && sourceDesc->getPatchHandle() == handle) {
4631 portId = sourceDesc->portId();
4632 break;
4633 }
4634 }
4635 return portId != AUDIO_PORT_HANDLE_NONE ?
4636 stopAudioSource(portId) : releaseAudioPatchInternal(handle);
François Gaffieafd4cea2019-11-18 15:50:22 +01004637}
Eric Laurent6a94d692014-05-20 11:18:06 -07004638
François Gaffieafd4cea2019-11-18 15:50:22 +01004639status_t AudioPolicyManager::releaseAudioPatchInternal(audio_patch_handle_t handle,
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004640 uint32_t delayMs,
4641 const sp<SourceClientDescriptor>& sourceDesc)
François Gaffieafd4cea2019-11-18 15:50:22 +01004642{
4643 ALOGV("%s patch %d", __func__, handle);
4644 if (mAudioPatches.indexOfKey(handle) < 0) {
4645 ALOGE("%s: no patch found with handle=%d", __func__, handle);
4646 return BAD_VALUE;
4647 }
4648 sp<AudioPatch> patchDesc = mAudioPatches.valueFor(handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004649 struct audio_patch *patch = &patchDesc->mPatch;
François Gaffieafd4cea2019-11-18 15:50:22 +01004650 patchDesc->setUid(mUidCached);
Eric Laurent6a94d692014-05-20 11:18:06 -07004651 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004652 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004653 if (outputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004654 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004655 return BAD_VALUE;
4656 }
4657
François Gaffie11d30102018-11-02 16:09:09 +01004658 setOutputDevices(outputDesc,
4659 getNewOutputDevices(outputDesc, true /*fromCache*/),
4660 true,
4661 0,
4662 NULL);
Eric Laurent6a94d692014-05-20 11:18:06 -07004663 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
4664 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
François Gaffie53615e22015-03-19 09:24:12 +01004665 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004666 if (inputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004667 ALOGV("%s input not found for id %d", __func__, patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004668 return BAD_VALUE;
4669 }
4670 setInputDevice(inputDesc->mIoHandle,
Eric Laurentfb66dd92016-01-28 18:32:03 -08004671 getNewInputDevice(inputDesc),
Eric Laurent6a94d692014-05-20 11:18:06 -07004672 true,
4673 NULL);
4674 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004675 status_t status =
4676 mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
4677 ALOGV("%s patch panel returned %d patchHandle %d",
4678 __func__, status, patchDesc->getAfHandle());
4679 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004680 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004681 mpClientInterface->onAudioPatchListUpdate();
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004682 // SW or HW Bridge
4683 sp<SwAudioOutputDescriptor> outputDesc = nullptr;
4684 audio_patch_handle_t patchHandle = AUDIO_PATCH_HANDLE_NONE;
Francois Gaffie7feb8542020-04-06 17:39:47 +02004685 if (patch->num_sources > 1 && patch->sources[1].type == AUDIO_PORT_TYPE_MIX) {
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004686 outputDesc = mOutputs.getOutputFromId(patch->sources[1].id);
4687 } else if (patch->num_sources == 1 && sourceDesc != nullptr) {
4688 outputDesc = sourceDesc->swOutput().promote();
4689 }
4690 if (outputDesc == nullptr) {
4691 ALOGW("%s no output for id %d", __func__, patch->sources[0].id);
4692 // releaseOutput has already called closeOutput in case of direct output
4693 return NO_ERROR;
4694 }
François Gaffie7e39df22022-04-26 12:48:49 +02004695 patchHandle = outputDesc->getPatchHandle();
4696 // When a Sw bridge is released, the mixer used by this bridge will release its
4697 // patch at AudioFlinger side. Hence, the mixer audio patch must be recreated
4698 // Reuse patch handle to force audio flinger removing initial mixer patch removal
4699 // updating hal patch handle (prevent leaks).
4700 // While using a HwBridge, force reconsidering device only if not reusing an existing
4701 // output and no more activity on output (will force to close).
4702 bool force = sourceDesc->useSwBridge() ||
4703 (sourceDesc->canCloseOutput() && !outputDesc->isActive());
4704 // APM pattern is to have always outputs opened / patch realized for reachable devices.
4705 // Update device may result to NONE (empty), coupled with force, it releases the patch.
4706 // Reconsider device only for cases:
4707 // 1 / Active Output
4708 // 2 / Inactive Output previously hosting HwBridge
4709 // 3 / Inactive Output previously hosting SwBridge that can be closed.
4710 bool updateDevice = outputDesc->isActive() || !sourceDesc->useSwBridge() ||
4711 sourceDesc->canCloseOutput();
4712 setOutputDevices(outputDesc,
4713 updateDevice ? getNewOutputDevices(outputDesc, true /*fromCache*/) :
4714 outputDesc->devices(),
4715 force,
4716 0,
4717 patchHandle == AUDIO_PATCH_HANDLE_NONE ? nullptr : &patchHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004718 } else {
4719 return BAD_VALUE;
4720 }
4721 } else {
4722 return BAD_VALUE;
4723 }
4724 return NO_ERROR;
4725}
4726
4727status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
4728 struct audio_patch *patches,
4729 unsigned int *generation)
4730{
François Gaffie53615e22015-03-19 09:24:12 +01004731 if (generation == NULL) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004732 return BAD_VALUE;
4733 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004734 *generation = curAudioPortGeneration();
François Gaffie53615e22015-03-19 09:24:12 +01004735 return mAudioPatches.listAudioPatches(num_patches, patches);
Eric Laurent6a94d692014-05-20 11:18:06 -07004736}
4737
Eric Laurente1715a42014-05-20 11:30:42 -07004738status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07004739{
Eric Laurente1715a42014-05-20 11:30:42 -07004740 ALOGV("setAudioPortConfig()");
4741
4742 if (config == NULL) {
4743 return BAD_VALUE;
4744 }
4745 ALOGV("setAudioPortConfig() on port handle %d", config->id);
4746 // Only support gain configuration for now
Eric Laurenta121f902014-06-03 13:32:54 -07004747 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
4748 return INVALID_OPERATION;
Eric Laurente1715a42014-05-20 11:30:42 -07004749 }
4750
Eric Laurenta121f902014-06-03 13:32:54 -07004751 sp<AudioPortConfig> audioPortConfig;
Eric Laurente1715a42014-05-20 11:30:42 -07004752 if (config->type == AUDIO_PORT_TYPE_MIX) {
4753 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004754 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07004755 if (outputDesc == NULL) {
4756 return BAD_VALUE;
4757 }
Eric Laurent84c70242014-06-23 08:46:27 -07004758 ALOG_ASSERT(!outputDesc->isDuplicated(),
4759 "setAudioPortConfig() called on duplicated output %d",
4760 outputDesc->mIoHandle);
Eric Laurenta121f902014-06-03 13:32:54 -07004761 audioPortConfig = outputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07004762 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
François Gaffie53615e22015-03-19 09:24:12 +01004763 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07004764 if (inputDesc == NULL) {
4765 return BAD_VALUE;
4766 }
Eric Laurenta121f902014-06-03 13:32:54 -07004767 audioPortConfig = inputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07004768 } else {
4769 return BAD_VALUE;
4770 }
4771 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
4772 sp<DeviceDescriptor> deviceDesc;
4773 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
4774 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
4775 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
4776 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
4777 } else {
4778 return BAD_VALUE;
4779 }
4780 if (deviceDesc == NULL) {
4781 return BAD_VALUE;
4782 }
Eric Laurenta121f902014-06-03 13:32:54 -07004783 audioPortConfig = deviceDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07004784 } else {
4785 return BAD_VALUE;
4786 }
4787
Mikhail Naganov7be71d22018-05-23 16:51:46 -07004788 struct audio_port_config backupConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07004789 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
4790 if (status == NO_ERROR) {
Mikhail Naganov7be71d22018-05-23 16:51:46 -07004791 struct audio_port_config newConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07004792 audioPortConfig->toAudioPortConfig(&newConfig, config);
4793 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
Eric Laurente1715a42014-05-20 11:30:42 -07004794 }
Eric Laurenta121f902014-06-03 13:32:54 -07004795 if (status != NO_ERROR) {
4796 audioPortConfig->applyAudioPortConfig(&backupConfig);
Eric Laurente1715a42014-05-20 11:30:42 -07004797 }
Eric Laurente1715a42014-05-20 11:30:42 -07004798
4799 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07004800}
4801
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004802void AudioPolicyManager::releaseResourcesForUid(uid_t uid)
4803{
Eric Laurentd60560a2015-04-10 11:31:20 -07004804 clearAudioSources(uid);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004805 clearAudioPatches(uid);
4806 clearSessionRoutes(uid);
4807}
4808
Eric Laurent6a94d692014-05-20 11:18:06 -07004809void AudioPolicyManager::clearAudioPatches(uid_t uid)
4810{
Eric Laurent0add0fd2014-12-04 18:58:14 -08004811 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004812 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
François Gaffieafd4cea2019-11-18 15:50:22 +01004813 if (patchDesc->getUid() == uid) {
Eric Laurent0add0fd2014-12-04 18:58:14 -08004814 releaseAudioPatch(mAudioPatches.keyAt(i), uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07004815 }
4816 }
4817}
4818
François Gaffiec005e562018-11-06 15:04:49 +01004819void AudioPolicyManager::checkStrategyRoute(product_strategy_t ps, audio_io_handle_t ouptutToSkip)
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004820{
François Gaffiec005e562018-11-06 15:04:49 +01004821 // Take the first attributes following the product strategy as it is used to retrieve the routed
4822 // device. All attributes wihin a strategy follows the same "routing strategy"
4823 auto attributes = mEngine->getAllAttributesForProductStrategy(ps).front();
4824 DeviceVector devices = mEngine->getOutputDevicesForAttributes(attributes, nullptr, false);
François Gaffie11d30102018-11-02 16:09:09 +01004825 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004826 for (size_t j = 0; j < mOutputs.size(); j++) {
4827 if (mOutputs.keyAt(j) == ouptutToSkip) {
4828 continue;
4829 }
4830 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(j);
François Gaffiec005e562018-11-06 15:04:49 +01004831 if (!outputDesc->isStrategyActive(ps)) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004832 continue;
4833 }
4834 // If the default device for this strategy is on another output mix,
4835 // invalidate all tracks in this strategy to force re connection.
4836 // Otherwise select new device on the output mix.
4837 if (outputs.indexOf(mOutputs.keyAt(j)) < 0) {
François Gaffiec005e562018-11-06 15:04:49 +01004838 for (auto stream : mEngine->getStreamTypesForProductStrategy(ps)) {
4839 mpClientInterface->invalidateStream(stream);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004840 }
4841 } else {
François Gaffie11d30102018-11-02 16:09:09 +01004842 setOutputDevices(
4843 outputDesc, getNewOutputDevices(outputDesc, false /*fromCache*/), false);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004844 }
4845 }
4846}
4847
4848void AudioPolicyManager::clearSessionRoutes(uid_t uid)
4849{
4850 // remove output routes associated with this uid
François Gaffiec005e562018-11-06 15:04:49 +01004851 std::vector<product_strategy_t> affectedStrategies;
Eric Laurent97ac8712018-07-27 18:59:02 -07004852 for (size_t i = 0; i < mOutputs.size(); i++) {
4853 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07004854 for (const auto& client : outputDesc->getClientIterable()) {
4855 if (client->hasPreferredDevice() && client->uid() == uid) {
4856 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
François Gaffiec005e562018-11-06 15:04:49 +01004857 auto clientStrategy = client->strategy();
4858 if (std::find(begin(affectedStrategies), end(affectedStrategies), clientStrategy) !=
4859 end(affectedStrategies)) {
4860 continue;
4861 }
4862 affectedStrategies.push_back(client->strategy());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004863 }
4864 }
4865 }
4866 // reroute outputs if necessary
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004867 for (const auto& strategy : affectedStrategies) {
4868 checkStrategyRoute(strategy, AUDIO_IO_HANDLE_NONE);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004869 }
4870
4871 // remove input routes associated with this uid
4872 SortedVector<audio_source_t> affectedSources;
Eric Laurent97ac8712018-07-27 18:59:02 -07004873 for (size_t i = 0; i < mInputs.size(); i++) {
4874 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07004875 for (const auto& client : inputDesc->getClientIterable()) {
4876 if (client->hasPreferredDevice() && client->uid() == uid) {
4877 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
4878 affectedSources.add(client->source());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004879 }
4880 }
4881 }
4882 // reroute inputs if necessary
4883 SortedVector<audio_io_handle_t> inputsToClose;
4884 for (size_t i = 0; i < mInputs.size(); i++) {
4885 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Eric Laurent4eb58f12018-12-07 16:41:02 -08004886 if (affectedSources.indexOf(inputDesc->source()) >= 0) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004887 inputsToClose.add(inputDesc->mIoHandle);
4888 }
4889 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004890 for (const auto& input : inputsToClose) {
4891 closeInput(input);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004892 }
4893}
4894
Eric Laurentd60560a2015-04-10 11:31:20 -07004895void AudioPolicyManager::clearAudioSources(uid_t uid)
4896{
4897 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004898 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
4899 if (sourceDesc->uid() == uid) {
Eric Laurentd60560a2015-04-10 11:31:20 -07004900 stopAudioSource(mAudioSources.keyAt(i));
4901 }
4902 }
4903}
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004904
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07004905status_t AudioPolicyManager::acquireSoundTriggerSession(audio_session_t *session,
4906 audio_io_handle_t *ioHandle,
4907 audio_devices_t *device)
4908{
Glenn Kastenf0c6d7d2016-02-26 10:44:04 -08004909 *session = (audio_session_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
4910 *ioHandle = (audio_io_handle_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
Francois Gaffie716e1432019-01-14 16:58:59 +01004911 audio_attributes_t attr = { .source = AUDIO_SOURCE_HOTWORD };
François Gaffiec005e562018-11-06 15:04:49 +01004912 *device = mEngine->getInputDeviceForAttributes(attr)->type();
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07004913
François Gaffiedf372692015-03-19 10:43:27 +01004914 return mSoundTriggerSessions.acquireSession(*session, *ioHandle);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07004915}
4916
Eric Laurentd60560a2015-04-10 11:31:20 -07004917status_t AudioPolicyManager::startAudioSource(const struct audio_port_config *source,
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004918 const audio_attributes_t *attributes,
4919 audio_port_handle_t *portId,
4920 uid_t uid)
Eric Laurent554a2772015-04-10 11:29:24 -07004921{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004922 ALOGV("%s", __FUNCTION__);
4923 *portId = AUDIO_PORT_HANDLE_NONE;
4924
4925 if (source == NULL || attributes == NULL || portId == NULL) {
4926 ALOGW("%s invalid argument: source %p attributes %p handle %p",
4927 __FUNCTION__, source, attributes, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07004928 return BAD_VALUE;
4929 }
4930
Eric Laurentd60560a2015-04-10 11:31:20 -07004931 if (source->role != AUDIO_PORT_ROLE_SOURCE ||
4932 source->type != AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004933 ALOGW("%s INVALID_OPERATION source->role %d source->type %d",
4934 __FUNCTION__, source->role, source->type);
Eric Laurentd60560a2015-04-10 11:31:20 -07004935 return INVALID_OPERATION;
4936 }
4937
François Gaffie11d30102018-11-02 16:09:09 +01004938 sp<DeviceDescriptor> srcDevice =
Eric Laurentd60560a2015-04-10 11:31:20 -07004939 mAvailableInputDevices.getDevice(source->ext.device.type,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08004940 String8(source->ext.device.address),
4941 AUDIO_FORMAT_DEFAULT);
François Gaffie11d30102018-11-02 16:09:09 +01004942 if (srcDevice == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004943 ALOGW("%s source->ext.device.type %08x not found", __FUNCTION__, source->ext.device.type);
Eric Laurentd60560a2015-04-10 11:31:20 -07004944 return BAD_VALUE;
4945 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004946
jiabin4ef93452019-09-10 14:29:54 -07004947 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurentd60560a2015-04-10 11:31:20 -07004948
François Gaffieaaac0fd2018-11-22 17:56:39 +01004949 sp<SourceClientDescriptor> sourceDesc =
François Gaffieafd4cea2019-11-18 15:50:22 +01004950 new SourceClientDescriptor(*portId, uid, *attributes, *source, srcDevice,
François Gaffieaaac0fd2018-11-22 17:56:39 +01004951 mEngine->getStreamTypeForAttributes(*attributes),
4952 mEngine->getProductStrategyForAttributes(*attributes),
4953 toVolumeSource(*attributes));
Eric Laurentd60560a2015-04-10 11:31:20 -07004954
4955 status_t status = connectAudioSource(sourceDesc);
4956 if (status == NO_ERROR) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004957 mAudioSources.add(*portId, sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07004958 }
4959 return status;
4960}
4961
Francois Gaffie601801d2021-06-22 13:27:39 +02004962sp<SourceClientDescriptor> AudioPolicyManager::startAudioSourceInternal(
4963 const struct audio_port_config *source, const audio_attributes_t *attributes, uid_t uid)
4964{
4965 ALOGV("%s", __FUNCTION__);
4966 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
4967
4968 status_t status = startAudioSource(source, attributes, &portId, uid);
4969 ALOGE_IF(status != OK, "%s: failed to start audio source (%d)", __func__, status);
4970 return mAudioSources.valueFor(portId);
4971}
4972
4973
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004974status_t AudioPolicyManager::connectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07004975{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004976 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->portId());
Eric Laurentd60560a2015-04-10 11:31:20 -07004977
4978 // make sure we only have one patch per source.
4979 disconnectAudioSource(sourceDesc);
4980
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004981 audio_attributes_t attributes = sourceDesc->attributes();
Francois Gaffiea0e5c992020-09-29 16:05:07 +02004982 // May the device (dynamic) have been disconnected/reconnected, id has changed.
4983 sp<DeviceDescriptor> srcDevice = mAvailableInputDevices.getDevice(
4984 sourceDesc->srcDevice()->type(),
4985 String8(sourceDesc->srcDevice()->address().c_str()),
4986 AUDIO_FORMAT_DEFAULT);
François Gaffiec005e562018-11-06 15:04:49 +01004987 DeviceVector sinkDevices =
Francois Gaffieff1eb522020-05-06 18:37:04 +02004988 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false /*fromCache*/);
François Gaffiec005e562018-11-06 15:04:49 +01004989 ALOG_ASSERT(!sinkDevices.isEmpty(), "connectAudioSource(): no device found for attributes");
François Gaffie11d30102018-11-02 16:09:09 +01004990 sp<DeviceDescriptor> sinkDevice = sinkDevices.itemAt(0);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02004991 if (!mAvailableOutputDevices.contains(sinkDevice)) {
4992 ALOGE("%s Device %s not available", __func__, sinkDevice->toString().c_str());
4993 return INVALID_OPERATION;
4994 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004995 PatchBuilder patchBuilder;
4996 patchBuilder.addSink(sinkDevice).addSource(srcDevice);
4997 audio_patch_handle_t handle = AUDIO_PATCH_HANDLE_NONE;
François Gaffieafd4cea2019-11-18 15:50:22 +01004998
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004999 return connectAudioSourceToSink(
5000 sourceDesc, sinkDevice, patchBuilder.patch(), handle, mUidCached, 0 /*delayMs*/);
Eric Laurent554a2772015-04-10 11:29:24 -07005001}
5002
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005003status_t AudioPolicyManager::stopAudioSource(audio_port_handle_t portId)
Eric Laurent554a2772015-04-10 11:29:24 -07005004{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005005 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueFor(portId);
5006 ALOGV("%s port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005007 if (sourceDesc == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005008 ALOGW("%s unknown source for port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005009 return BAD_VALUE;
5010 }
5011 status_t status = disconnectAudioSource(sourceDesc);
5012
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005013 mAudioSources.removeItem(portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005014 return status;
5015}
5016
Andy Hung2ddee192015-12-18 17:34:44 -08005017status_t AudioPolicyManager::setMasterMono(bool mono)
5018{
5019 if (mMasterMono == mono) {
5020 return NO_ERROR;
5021 }
5022 mMasterMono = mono;
5023 // if enabling mono we close all offloaded devices, which will invalidate the
5024 // corresponding AudioTrack. The AudioTrack client/MediaPlayer is responsible
5025 // for recreating the new AudioTrack as non-offloaded PCM.
5026 //
5027 // If disabling mono, we leave all tracks as is: we don't know which clients
5028 // and tracks are able to be recreated as offloaded. The next "song" should
5029 // play back offloaded.
5030 if (mMasterMono) {
5031 Vector<audio_io_handle_t> offloaded;
5032 for (size_t i = 0; i < mOutputs.size(); ++i) {
5033 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
5034 if (desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
5035 offloaded.push(desc->mIoHandle);
5036 }
5037 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005038 for (const auto& handle : offloaded) {
5039 closeOutput(handle);
Andy Hung2ddee192015-12-18 17:34:44 -08005040 }
5041 }
5042 // update master mono for all remaining outputs
5043 for (size_t i = 0; i < mOutputs.size(); ++i) {
5044 updateMono(mOutputs.keyAt(i));
5045 }
5046 return NO_ERROR;
5047}
5048
5049status_t AudioPolicyManager::getMasterMono(bool *mono)
5050{
5051 *mono = mMasterMono;
5052 return NO_ERROR;
5053}
5054
Eric Laurentac9cef52017-06-09 15:46:26 -07005055float AudioPolicyManager::getStreamVolumeDB(
5056 audio_stream_type_t stream, int index, audio_devices_t device)
5057{
jiabin9a3361e2019-10-01 09:38:30 -07005058 return computeVolume(getVolumeCurves(stream), toVolumeSource(stream), index, {device});
Eric Laurentac9cef52017-06-09 15:46:26 -07005059}
5060
jiabin81772902018-04-02 17:52:27 -07005061status_t AudioPolicyManager::getSurroundFormats(unsigned int *numSurroundFormats,
5062 audio_format_t *surroundFormats,
Kriti Dang6537def2021-03-02 13:46:59 +01005063 bool *surroundFormatsEnabled)
jiabin81772902018-04-02 17:52:27 -07005064{
Kriti Dang6537def2021-03-02 13:46:59 +01005065 if (numSurroundFormats == nullptr || (*numSurroundFormats != 0 &&
5066 (surroundFormats == nullptr || surroundFormatsEnabled == nullptr))) {
jiabin81772902018-04-02 17:52:27 -07005067 return BAD_VALUE;
5068 }
Kriti Dang6537def2021-03-02 13:46:59 +01005069 ALOGV("%s() numSurroundFormats %d surroundFormats %p surroundFormatsEnabled %p",
5070 __func__, *numSurroundFormats, surroundFormats, surroundFormatsEnabled);
jiabin81772902018-04-02 17:52:27 -07005071
5072 size_t formatsWritten = 0;
5073 size_t formatsMax = *numSurroundFormats;
Kriti Dangef6be8f2020-11-05 11:58:19 +01005074
Kriti Dang6537def2021-03-02 13:46:59 +01005075 *numSurroundFormats = mConfig.getSurroundFormats().size();
Mikhail Naganov100f0122018-11-29 11:22:16 -08005076 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
5077 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Kriti Dang6537def2021-03-02 13:46:59 +01005078 for (const auto& format: mConfig.getSurroundFormats()) {
jiabin81772902018-04-02 17:52:27 -07005079 if (formatsWritten < formatsMax) {
Kriti Dang6537def2021-03-02 13:46:59 +01005080 surroundFormats[formatsWritten] = format.first;
Mikhail Naganov100f0122018-11-29 11:22:16 -08005081 bool formatEnabled = true;
5082 switch (forceUse) {
5083 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL:
Kriti Dang6537def2021-03-02 13:46:59 +01005084 formatEnabled = mManualSurroundFormats.count(format.first) != 0;
Mikhail Naganov100f0122018-11-29 11:22:16 -08005085 break;
5086 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER:
5087 formatEnabled = false;
5088 break;
5089 default: // AUTO or ALWAYS => true
5090 break;
jiabin81772902018-04-02 17:52:27 -07005091 }
5092 surroundFormatsEnabled[formatsWritten++] = formatEnabled;
5093 }
jiabin81772902018-04-02 17:52:27 -07005094 }
5095 return NO_ERROR;
5096}
5097
Kriti Dang6537def2021-03-02 13:46:59 +01005098status_t AudioPolicyManager::getReportedSurroundFormats(unsigned int *numSurroundFormats,
5099 audio_format_t *surroundFormats) {
5100 if (numSurroundFormats == nullptr || (*numSurroundFormats != 0 && surroundFormats == nullptr)) {
5101 return BAD_VALUE;
5102 }
5103 ALOGV("%s() numSurroundFormats %d surroundFormats %p",
5104 __func__, *numSurroundFormats, surroundFormats);
5105
5106 size_t formatsWritten = 0;
5107 size_t formatsMax = *numSurroundFormats;
5108 std::unordered_set<audio_format_t> formats; // Uses primary surround formats only
5109
5110 // Return formats from all device profiles that have already been resolved by
5111 // checkOutputsForDevice().
5112 for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
5113 sp<DeviceDescriptor> device = mAvailableOutputDevices[i];
5114 audio_devices_t deviceType = device->type();
5115 // Enabling/disabling formats are applied to only HDMI devices. So, this function
5116 // returns formats reported by HDMI devices.
5117 if (deviceType != AUDIO_DEVICE_OUT_HDMI) {
5118 continue;
5119 }
5120 // Formats reported by sink devices
5121 std::unordered_set<audio_format_t> formatset;
5122 if (auto it = mReportedFormatsMap.find(device); it != mReportedFormatsMap.end()) {
5123 formatset.insert(it->second.begin(), it->second.end());
5124 }
5125
5126 // Formats hard-coded in the in policy configuration file (if any).
5127 FormatVector encodedFormats = device->encodedFormats();
5128 formatset.insert(encodedFormats.begin(), encodedFormats.end());
5129 // Filter the formats which are supported by the vendor hardware.
5130 for (auto it = formatset.begin(); it != formatset.end(); ++it) {
5131 if (mConfig.getSurroundFormats().count(*it) != 0) {
5132 formats.insert(*it);
5133 } else {
5134 for (const auto& pair : mConfig.getSurroundFormats()) {
5135 if (pair.second.count(*it) != 0) {
5136 formats.insert(pair.first);
5137 break;
5138 }
5139 }
5140 }
5141 }
5142 }
5143 *numSurroundFormats = formats.size();
5144 for (const auto& format: formats) {
5145 if (formatsWritten < formatsMax) {
5146 surroundFormats[formatsWritten++] = format;
5147 }
5148 }
5149 return NO_ERROR;
5150}
5151
jiabin81772902018-04-02 17:52:27 -07005152status_t AudioPolicyManager::setSurroundFormatEnabled(audio_format_t audioFormat, bool enabled)
5153{
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005154 ALOGV("%s() format 0x%X enabled %d", __func__, audioFormat, enabled);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07005155 const auto& formatIter = mConfig.getSurroundFormats().find(audioFormat);
5156 if (formatIter == mConfig.getSurroundFormats().end()) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005157 ALOGW("%s() format 0x%X is not a known surround format", __func__, audioFormat);
jiabin81772902018-04-02 17:52:27 -07005158 return BAD_VALUE;
5159 }
5160
Mikhail Naganov100f0122018-11-29 11:22:16 -08005161 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND) !=
5162 AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005163 ALOGW("%s() not in manual mode for surround sound format selection", __func__);
jiabin81772902018-04-02 17:52:27 -07005164 return INVALID_OPERATION;
5165 }
5166
Mikhail Naganov100f0122018-11-29 11:22:16 -08005167 if ((mManualSurroundFormats.count(audioFormat) != 0) == enabled) {
jiabin81772902018-04-02 17:52:27 -07005168 return NO_ERROR;
5169 }
5170
Mikhail Naganov100f0122018-11-29 11:22:16 -08005171 std::unordered_set<audio_format_t> surroundFormatsBackup(mManualSurroundFormats);
jiabin81772902018-04-02 17:52:27 -07005172 if (enabled) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005173 mManualSurroundFormats.insert(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07005174 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005175 mManualSurroundFormats.insert(subFormat);
jiabin81772902018-04-02 17:52:27 -07005176 }
5177 } else {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005178 mManualSurroundFormats.erase(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07005179 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005180 mManualSurroundFormats.erase(subFormat);
jiabin81772902018-04-02 17:52:27 -07005181 }
5182 }
5183
5184 sp<SwAudioOutputDescriptor> outputDesc;
5185 bool profileUpdated = false;
jiabin9a3361e2019-10-01 09:38:30 -07005186 DeviceVector hdmiOutputDevices = mAvailableOutputDevices.getDevicesFromType(
5187 AUDIO_DEVICE_OUT_HDMI);
jiabin81772902018-04-02 17:52:27 -07005188 for (size_t i = 0; i < hdmiOutputDevices.size(); i++) {
5189 // Simulate reconnection to update enabled surround sound formats.
jiabince9f20e2019-09-12 16:29:15 -07005190 String8 address = String8(hdmiOutputDevices[i]->address().c_str());
jiabin5740f082019-08-19 15:08:30 -07005191 std::string name = hdmiOutputDevices[i]->getName();
jiabin81772902018-04-02 17:52:27 -07005192 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
5193 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
5194 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005195 name.c_str(),
5196 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005197 if (status != NO_ERROR) {
5198 continue;
5199 }
5200 status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
5201 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
5202 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005203 name.c_str(),
5204 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005205 profileUpdated |= (status == NO_ERROR);
5206 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08005207 // FIXME: Why doing this for input HDMI devices if we don't augment their reported formats?
jiabin9a3361e2019-10-01 09:38:30 -07005208 DeviceVector hdmiInputDevices = mAvailableInputDevices.getDevicesFromType(
jiabin81772902018-04-02 17:52:27 -07005209 AUDIO_DEVICE_IN_HDMI);
5210 for (size_t i = 0; i < hdmiInputDevices.size(); i++) {
5211 // Simulate reconnection to update enabled surround sound formats.
jiabince9f20e2019-09-12 16:29:15 -07005212 String8 address = String8(hdmiInputDevices[i]->address().c_str());
jiabin5740f082019-08-19 15:08:30 -07005213 std::string name = hdmiInputDevices[i]->getName();
jiabin81772902018-04-02 17:52:27 -07005214 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
5215 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
5216 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005217 name.c_str(),
5218 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005219 if (status != NO_ERROR) {
5220 continue;
5221 }
5222 status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
5223 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
5224 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005225 name.c_str(),
5226 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005227 profileUpdated |= (status == NO_ERROR);
5228 }
5229
jiabin81772902018-04-02 17:52:27 -07005230 if (!profileUpdated) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005231 ALOGW("%s() no audio profiles updated, undoing surround formats change", __func__);
Mikhail Naganov100f0122018-11-29 11:22:16 -08005232 mManualSurroundFormats = std::move(surroundFormatsBackup);
jiabin81772902018-04-02 17:52:27 -07005233 }
5234
5235 return profileUpdated ? NO_ERROR : INVALID_OPERATION;
5236}
5237
Eric Laurent5ada82e2019-08-29 17:53:54 -07005238void AudioPolicyManager::setAppState(audio_port_handle_t portId, app_state_t state)
Svet Ganovf4ddfef2018-01-16 07:37:58 -08005239{
Eric Laurent5ada82e2019-08-29 17:53:54 -07005240 ALOGV("%s(portId:%d, state:%d)", __func__, portId, state);
Eric Laurenta9f86652018-11-28 17:23:11 -08005241 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent5ada82e2019-08-29 17:53:54 -07005242 mInputs.valueAt(i)->setAppState(portId, state);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08005243 }
5244}
5245
jiabin6012f912018-11-02 17:06:30 -07005246bool AudioPolicyManager::isHapticPlaybackSupported()
5247{
5248 for (const auto& hwModule : mHwModules) {
5249 const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
5250 for (const auto &outProfile : outputProfiles) {
5251 struct audio_port audioPort;
5252 outProfile->toAudioPort(&audioPort);
5253 for (size_t i = 0; i < audioPort.num_channel_masks; i++) {
5254 if (audioPort.channel_masks[i] & AUDIO_CHANNEL_HAPTIC_ALL) {
5255 return true;
5256 }
5257 }
5258 }
5259 }
5260 return false;
5261}
5262
Carter Hsu325a8eb2022-01-19 19:56:51 +08005263bool AudioPolicyManager::isUltrasoundSupported()
5264{
5265 bool hasUltrasoundOutput = false;
5266 bool hasUltrasoundInput = false;
5267 for (const auto& hwModule : mHwModules) {
5268 const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
5269 if (!hasUltrasoundOutput) {
5270 for (const auto &outProfile : outputProfiles) {
5271 if (outProfile->getFlags() & AUDIO_OUTPUT_FLAG_ULTRASOUND) {
5272 hasUltrasoundOutput = true;
5273 break;
5274 }
5275 }
5276 }
5277
5278 const InputProfileCollection &inputProfiles = hwModule->getInputProfiles();
5279 if (!hasUltrasoundInput) {
5280 for (const auto &inputProfile : inputProfiles) {
5281 if (inputProfile->getFlags() & AUDIO_INPUT_FLAG_ULTRASOUND) {
5282 hasUltrasoundInput = true;
5283 break;
5284 }
5285 }
5286 }
5287
5288 if (hasUltrasoundOutput && hasUltrasoundInput)
5289 return true;
5290 }
5291 return false;
5292}
5293
Eric Laurent8340e672019-11-06 11:01:08 -08005294bool AudioPolicyManager::isCallScreenModeSupported()
5295{
5296 return getConfig().isCallScreenModeSupported();
5297}
5298
5299
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005300status_t AudioPolicyManager::disconnectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07005301{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005302 ALOGV("%s port Id %d", __FUNCTION__, sourceDesc->portId());
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005303 if (!sourceDesc->isConnected()) {
5304 ALOGV("%s port Id %d already disconnected", __FUNCTION__, sourceDesc->portId());
5305 return NO_ERROR;
5306 }
François Gaffieafd4cea2019-11-18 15:50:22 +01005307 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
5308 if (swOutput != 0) {
5309 status_t status = stopSource(swOutput, sourceDesc);
Eric Laurent733ce942017-12-07 12:18:25 -08005310 if (status == NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005311 swOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08005312 }
jiabinbce0c1d2020-10-05 11:20:18 -07005313 if (releaseOutput(sourceDesc->portId())) {
5314 // The output descriptor is reopened to query dynamic profiles. In that case, there is
5315 // no need to release audio patch here but just return NO_ERROR.
5316 return NO_ERROR;
5317 }
Eric Laurentd60560a2015-04-10 11:31:20 -07005318 } else {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005319 sp<HwAudioOutputDescriptor> hwOutputDesc = sourceDesc->hwOutput().promote();
Eric Laurentd60560a2015-04-10 11:31:20 -07005320 if (hwOutputDesc != 0) {
Eric Laurentd60560a2015-04-10 11:31:20 -07005321 // close Hwoutput and remove from mHwOutputs
5322 } else {
5323 ALOGW("%s source has neither SW nor HW output", __FUNCTION__);
5324 }
5325 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005326 status_t status = releaseAudioPatchInternal(sourceDesc->getPatchHandle(), 0, sourceDesc);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005327 sourceDesc->disconnect();
5328 return status;
Eric Laurentd60560a2015-04-10 11:31:20 -07005329}
5330
François Gaffiec005e562018-11-06 15:04:49 +01005331sp<SourceClientDescriptor> AudioPolicyManager::getSourceForAttributesOnOutput(
5332 audio_io_handle_t output, const audio_attributes_t &attr)
Eric Laurentd60560a2015-04-10 11:31:20 -07005333{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005334 sp<SourceClientDescriptor> source;
Eric Laurentd60560a2015-04-10 11:31:20 -07005335 for (size_t i = 0; i < mAudioSources.size(); i++) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005336 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005337 sp<SwAudioOutputDescriptor> outputDesc = sourceDesc->swOutput().promote();
François Gaffiec005e562018-11-06 15:04:49 +01005338 if (followsSameRouting(attr, sourceDesc->attributes()) &&
5339 outputDesc != 0 && outputDesc->mIoHandle == output) {
Eric Laurentd60560a2015-04-10 11:31:20 -07005340 source = sourceDesc;
5341 break;
5342 }
5343 }
5344 return source;
Eric Laurent554a2772015-04-10 11:29:24 -07005345}
5346
Eric Laurentb4f42a92022-01-17 17:37:31 +01005347bool AudioPolicyManager::canBeSpatializedInt(const audio_attributes_t *attr,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005348 const audio_config_t *config,
Andy Hung9dd1a5b2022-05-10 15:39:39 -07005349 const AudioDeviceTypeAddrVector &devices) const
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005350{
5351 // The caller can have the audio attributes criteria ignored by either passing a null ptr or
5352 // the AUDIO_ATTRIBUTES_INITIALIZER value.
Eric Laurentfa0f6742021-08-17 18:39:44 +02005353 // If attributes are specified, current policy is to only allow spatialization for media
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005354 // and game usages.
Eric Laurent39095982021-08-24 18:29:27 +02005355 if (attr != nullptr && *attr != AUDIO_ATTRIBUTES_INITIALIZER) {
5356 if (attr->usage != AUDIO_USAGE_MEDIA && attr->usage != AUDIO_USAGE_GAME) {
5357 return false;
5358 }
5359 if ((attr->flags & (AUDIO_FLAG_CONTENT_SPATIALIZED | AUDIO_FLAG_NEVER_SPATIALIZE)) != 0) {
5360 return false;
5361 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005362 }
5363
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005364 sp<IOProfile> profile =
Eric Laurent39095982021-08-24 18:29:27 +02005365 getSpatializerOutputProfile(config, devices);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005366 if (profile == nullptr) {
5367 return false;
5368 }
5369
5370 // The caller can have the audio config criteria ignored by either passing a null ptr or
5371 // the AUDIO_CONFIG_INITIALIZER value.
Eric Laurentfa0f6742021-08-17 18:39:44 +02005372 // If an audio config is specified, current policy is to only allow spatialization for
Eric Laurent39095982021-08-24 18:29:27 +02005373 // some positional channel masks.
Eric Laurent39095982021-08-24 18:29:27 +02005374
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005375 if (config != nullptr && *config != AUDIO_CONFIG_INITIALIZER) {
Andy Hung9dd1a5b2022-05-10 15:39:39 -07005376 if (!audio_is_channel_mask_spatialized(config->channel_mask)) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005377 return false;
5378 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005379 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005380 return true;
5381}
5382
5383void AudioPolicyManager::checkVirtualizerClientRoutes() {
5384 std::set<audio_stream_type_t> streamsToInvalidate;
5385 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent39095982021-08-24 18:29:27 +02005386 const sp<SwAudioOutputDescriptor>& desc = mOutputs[i];
5387 for (const sp<TrackClientDescriptor>& client : desc->getClientIterable()) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005388 audio_attributes_t attr = client->attributes();
5389 DeviceVector devices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false);
5390 AudioDeviceTypeAddrVector devicesTypeAddress = devices.toTypeAddrVector();
5391 audio_config_base_t clientConfig = client->config();
5392 audio_config_t config = audio_config_initializer(&clientConfig);
Eric Laurent39095982021-08-24 18:29:27 +02005393 if (desc != mSpatializerOutput
Andy Hung9dd1a5b2022-05-10 15:39:39 -07005394 && canBeSpatializedInt(&attr, &config, devicesTypeAddress)) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005395 streamsToInvalidate.insert(client->stream());
5396 }
5397 }
5398 }
5399
5400 for (audio_stream_type_t stream : streamsToInvalidate) {
5401 mpClientInterface->invalidateStream(stream);
5402 }
5403}
5404
Eric Laurente191d1b2022-04-15 11:59:25 +02005405
5406bool AudioPolicyManager::isOutputOnlyAvailableRouteToSomeDevice(
5407 const sp<SwAudioOutputDescriptor>& outputDesc) {
5408 if (outputDesc->isDuplicated()) {
5409 return false;
5410 }
5411 DeviceVector devices = outputDesc->supportedDevices();
5412 for (size_t i = 0; i < mOutputs.size(); i++) {
5413 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
5414 if (desc == outputDesc || desc->isDuplicated()) {
5415 continue;
5416 }
5417 DeviceVector sharedDevices = desc->filterSupportedDevices(devices);
5418 if (!sharedDevices.isEmpty()
5419 && (desc->devicesSupportEncodedFormats(sharedDevices.types())
5420 == outputDesc->devicesSupportEncodedFormats(sharedDevices.types()))) {
5421 return false;
5422 }
5423 }
5424 return true;
5425}
5426
5427
Eric Laurentfa0f6742021-08-17 18:39:44 +02005428status_t AudioPolicyManager::getSpatializerOutput(const audio_config_base_t *mixerConfig,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005429 const audio_attributes_t *attr,
5430 audio_io_handle_t *output) {
5431 *output = AUDIO_IO_HANDLE_NONE;
5432
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005433 DeviceVector devices = mEngine->getOutputDevicesForAttributes(*attr, nullptr, false);
5434 AudioDeviceTypeAddrVector devicesTypeAddress = devices.toTypeAddrVector();
5435 audio_config_t *configPtr = nullptr;
5436 audio_config_t config;
5437 if (mixerConfig != nullptr) {
5438 config = audio_config_initializer(mixerConfig);
5439 configPtr = &config;
5440 }
Andy Hung9dd1a5b2022-05-10 15:39:39 -07005441 if (!canBeSpatializedInt(attr, configPtr, devicesTypeAddress)) {
Eric Laurente191d1b2022-04-15 11:59:25 +02005442 ALOGV("%s provided attributes or mixer config cannot be spatialized", __func__);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005443 return BAD_VALUE;
5444 }
5445
5446 sp<IOProfile> profile =
Eric Laurent39095982021-08-24 18:29:27 +02005447 getSpatializerOutputProfile(configPtr, devicesTypeAddress);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005448 if (profile == nullptr) {
Eric Laurente191d1b2022-04-15 11:59:25 +02005449 ALOGV("%s no suitable output profile for provided attributes or mixer config", __func__);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005450 return BAD_VALUE;
5451 }
5452
Eric Laurente191d1b2022-04-15 11:59:25 +02005453 std::vector<sp<SwAudioOutputDescriptor>> spatializerOutputs;
Eric Laurent39095982021-08-24 18:29:27 +02005454 for (size_t i = 0; i < mOutputs.size(); i++) {
5455 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente191d1b2022-04-15 11:59:25 +02005456 if (!desc->isDuplicated()
5457 && (desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0) {
5458 spatializerOutputs.push_back(desc);
5459 ALOGV("%s adding opened spatializer Output %d", __func__, desc->mIoHandle);
Eric Laurent39095982021-08-24 18:29:27 +02005460 }
5461 }
Eric Laurente191d1b2022-04-15 11:59:25 +02005462 mSpatializerOutput.clear();
5463 bool outputsChanged = false;
5464 for (const auto& desc : spatializerOutputs) {
5465 if (desc->mProfile == profile
5466 && (configPtr == nullptr
5467 || configPtr->channel_mask == desc->mMixerChannelMask)) {
5468 mSpatializerOutput = desc;
5469 ALOGV("%s reusing current spatializer output %d", __func__, desc->mIoHandle);
5470 } else {
5471 ALOGV("%s closing spatializerOutput output %d to match channel mask %#x"
5472 " and devices %s", __func__, desc->mIoHandle,
5473 configPtr != nullptr ? configPtr->channel_mask : 0,
5474 devices.toString().c_str());
5475 closeOutput(desc->mIoHandle);
5476 outputsChanged = true;
5477 }
Eric Laurent39095982021-08-24 18:29:27 +02005478 }
5479
Eric Laurente191d1b2022-04-15 11:59:25 +02005480 if (mSpatializerOutput == nullptr) {
Eric Laurentb4f42a92022-01-17 17:37:31 +01005481 sp<SwAudioOutputDescriptor> desc =
5482 openOutputWithProfileAndDevice(profile, devices, mixerConfig);
Eric Laurente191d1b2022-04-15 11:59:25 +02005483 if (desc != nullptr) {
5484 mSpatializerOutput = desc;
5485 outputsChanged = true;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005486 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005487 }
5488
5489 checkVirtualizerClientRoutes();
5490
Eric Laurente191d1b2022-04-15 11:59:25 +02005491 if (outputsChanged) {
5492 mPreviousOutputs = mOutputs;
5493 mpClientInterface->onAudioPortListUpdate();
5494 }
5495
5496 if (mSpatializerOutput == nullptr) {
5497 ALOGV("%s could not open spatializer output with requested config", __func__);
5498 return BAD_VALUE;
5499 }
Eric Laurent39095982021-08-24 18:29:27 +02005500 *output = mSpatializerOutput->mIoHandle;
Eric Laurente191d1b2022-04-15 11:59:25 +02005501 ALOGV("%s returning new spatializer output %d", __func__, *output);
5502 return OK;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005503}
5504
Eric Laurentfa0f6742021-08-17 18:39:44 +02005505status_t AudioPolicyManager::releaseSpatializerOutput(audio_io_handle_t output) {
5506 if (mSpatializerOutput == nullptr) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005507 return INVALID_OPERATION;
5508 }
Eric Laurentfa0f6742021-08-17 18:39:44 +02005509 if (mSpatializerOutput->mIoHandle != output) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005510 return BAD_VALUE;
5511 }
Eric Laurent39095982021-08-24 18:29:27 +02005512
Eric Laurente191d1b2022-04-15 11:59:25 +02005513 if (!isOutputOnlyAvailableRouteToSomeDevice(mSpatializerOutput)) {
5514 ALOGV("%s closing spatializer output %d", __func__, mSpatializerOutput->mIoHandle);
5515 closeOutput(mSpatializerOutput->mIoHandle);
5516 //from now on mSpatializerOutput is null
5517 checkVirtualizerClientRoutes();
5518 }
Eric Laurent39095982021-08-24 18:29:27 +02005519
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005520 return NO_ERROR;
5521}
5522
Eric Laurente552edb2014-03-10 17:42:56 -07005523// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07005524// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07005525// ----------------------------------------------------------------------------
Eric Laurent6a94d692014-05-20 11:18:06 -07005526uint32_t AudioPolicyManager::nextAudioPortGeneration()
5527{
Mikhail Naganov2773dd72017-12-08 10:12:11 -08005528 return mAudioPortGeneration++;
Eric Laurent6a94d692014-05-20 11:18:06 -07005529}
5530
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09005531static status_t deserializeAudioPolicyXmlConfig(AudioPolicyConfig &config) {
Mikhail Naganov946c0032020-10-21 13:04:58 -07005532 if (std::string audioPolicyXmlConfigFile = audio_get_audio_policy_config_file();
5533 !audioPolicyXmlConfigFile.empty()) {
5534 status_t ret = deserializeAudioPolicyFile(audioPolicyXmlConfigFile.c_str(), &config);
5535 if (ret == NO_ERROR) {
5536 config.setSource(audioPolicyXmlConfigFile);
Cheney Ni6851adb2018-11-01 06:30:37 +08005537 }
Mikhail Naganov946c0032020-10-21 13:04:58 -07005538 return ret;
Petri Gyntherf497f292018-04-17 18:46:10 -07005539 }
Mikhail Naganov946c0032020-10-21 13:04:58 -07005540 return BAD_VALUE;
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09005541}
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09005542
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005543AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface,
5544 bool /*forTesting*/)
Eric Laurente552edb2014-03-10 17:42:56 -07005545 :
Andy Hung4ef19fa2018-05-15 19:35:29 -07005546 mUidCached(AID_AUDIOSERVER), // no need to call getuid(), there's only one of us running.
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005547 mpClientInterface(clientInterface),
Eric Laurente552edb2014-03-10 17:42:56 -07005548 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
Eric Laurent3a4311c2014-03-17 12:00:47 -07005549 mA2dpSuspended(false),
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005550 mConfig(mHwModulesAll, mOutputDevicesAll, mInputDevicesAll, mDefaultOutputDevice),
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005551 mAudioPortGeneration(1),
5552 mBeaconMuteRefCount(0),
5553 mBeaconPlayingRefCount(0),
Eric Laurent9459fb02015-08-12 18:36:32 -07005554 mBeaconMuted(false),
Andy Hung2ddee192015-12-18 17:34:44 -08005555 mTtsOutputAvailable(false),
Eric Laurent36829f92017-04-07 19:04:42 -07005556 mMasterMono(false),
Eric Laurent4eb58f12018-12-07 16:41:02 -08005557 mMusicEffectOutput(AUDIO_IO_HANDLE_NONE)
Eric Laurente552edb2014-03-10 17:42:56 -07005558{
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005559}
François Gaffied1ab2bd2015-12-02 18:20:06 +01005560
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005561AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface)
5562 : AudioPolicyManager(clientInterface, false /*forTesting*/)
5563{
5564 loadConfig();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005565}
François Gaffied1ab2bd2015-12-02 18:20:06 +01005566
Kevin Rocarddfa1e8a2018-10-26 16:42:07 -07005567void AudioPolicyManager::loadConfig() {
5568 if (deserializeAudioPolicyXmlConfig(getConfig()) != NO_ERROR) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01005569 ALOGE("could not load audio policy configuration file, setting defaults");
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005570 getConfig().setDefault();
François Gaffied1ab2bd2015-12-02 18:20:06 +01005571 }
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005572}
5573
5574status_t AudioPolicyManager::initialize() {
Mikhail Naganov47835552019-05-14 10:32:51 -07005575 {
5576 auto engLib = EngineLibrary::load(
5577 "libaudiopolicyengine" + getConfig().getEngineLibraryNameSuffix() + ".so");
5578 if (!engLib) {
5579 ALOGE("%s: Failed to load the engine library", __FUNCTION__);
5580 return NO_INIT;
5581 }
5582 mEngine = engLib->createEngine();
5583 if (mEngine == nullptr) {
5584 ALOGE("%s: Failed to instantiate the APM engine", __FUNCTION__);
5585 return NO_INIT;
5586 }
François Gaffie2110e042015-03-24 08:41:51 +01005587 }
5588 mEngine->setObserver(this);
5589 status_t status = mEngine->initCheck();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005590 if (status != NO_ERROR) {
5591 LOG_FATAL("Policy engine not initialized(err=%d)", status);
5592 return status;
5593 }
François Gaffie2110e042015-03-24 08:41:51 +01005594
Eric Laurent1a8b45f2022-04-13 16:01:47 +02005595 mEngine->updateDeviceSelectionCache();
Eric Laurent1d69c872021-01-11 18:53:01 +01005596 mCommunnicationStrategy = mEngine->getProductStrategyForAttributes(
5597 mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL));
5598
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005599 // after parsing the config, mOutputDevicesAll and mInputDevicesAll contain all known devices;
Eric Laurente552edb2014-03-10 17:42:56 -07005600 // open all output streams needed to access attached devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07005601 onNewAudioModulesAvailableInt(nullptr /*newDevices*/);
François Gaffie11d30102018-11-02 16:09:09 +01005602
Eric Laurent3a4311c2014-03-17 12:00:47 -07005603 // make sure default device is reachable
François Gaffie11d30102018-11-02 16:09:09 +01005604 if (mDefaultOutputDevice == 0 || !mAvailableOutputDevices.contains(mDefaultOutputDevice)) {
5605 ALOGE_IF(mDefaultOutputDevice != 0, "Default device %s is unreachable",
5606 mDefaultOutputDevice->toString().c_str());
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005607 status = NO_INIT;
Eric Laurent3a4311c2014-03-17 12:00:47 -07005608 }
jiabin9ff780e2018-03-19 18:19:52 -07005609 // If microphones address is empty, set it according to device type
Eric Laurent736a1022019-03-27 18:28:46 -07005610 for (size_t i = 0; i < mAvailableInputDevices.size(); i++) {
jiabince9f20e2019-09-12 16:29:15 -07005611 if (mAvailableInputDevices[i]->address().empty()) {
jiabin9ff780e2018-03-19 18:19:52 -07005612 if (mAvailableInputDevices[i]->type() == AUDIO_DEVICE_IN_BUILTIN_MIC) {
jiabince9f20e2019-09-12 16:29:15 -07005613 mAvailableInputDevices[i]->setAddress(AUDIO_BOTTOM_MICROPHONE_ADDRESS);
jiabin9ff780e2018-03-19 18:19:52 -07005614 } else if (mAvailableInputDevices[i]->type() == AUDIO_DEVICE_IN_BACK_MIC) {
jiabince9f20e2019-09-12 16:29:15 -07005615 mAvailableInputDevices[i]->setAddress(AUDIO_BACK_MICROPHONE_ADDRESS);
jiabin9ff780e2018-03-19 18:19:52 -07005616 }
5617 }
5618 }
Eric Laurente552edb2014-03-10 17:42:56 -07005619
Francois Gaffiebce7cd42020-10-14 16:13:20 +02005620 ALOGW_IF(mPrimaryOutput == nullptr, "The policy configuration does not declare a primary output");
Eric Laurente552edb2014-03-10 17:42:56 -07005621
Tomoharu Kasahara71c90912018-10-31 09:10:12 +09005622 // Silence ALOGV statements
5623 property_set("log.tag." LOG_TAG, "D");
5624
Eric Laurente552edb2014-03-10 17:42:56 -07005625 updateDevicesAndOutputs();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005626 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07005627}
5628
Eric Laurente0720872014-03-11 09:30:41 -07005629AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07005630{
Eric Laurente552edb2014-03-10 17:42:56 -07005631 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08005632 mOutputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07005633 }
5634 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08005635 mInputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07005636 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07005637 mAvailableOutputDevices.clear();
5638 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07005639 mOutputs.clear();
5640 mInputs.clear();
5641 mHwModules.clear();
Mikhail Naganovd4120142017-12-06 15:49:22 -08005642 mHwModulesAll.clear();
Mikhail Naganov100f0122018-11-29 11:22:16 -08005643 mManualSurroundFormats.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07005644}
5645
Eric Laurente0720872014-03-11 09:30:41 -07005646status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07005647{
Eric Laurent87ffa392015-05-22 10:32:38 -07005648 return hasPrimaryOutput() ? NO_ERROR : NO_INIT;
Eric Laurente552edb2014-03-10 17:42:56 -07005649}
5650
Eric Laurente552edb2014-03-10 17:42:56 -07005651// ---
5652
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005653void AudioPolicyManager::onNewAudioModulesAvailable()
5654{
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07005655 DeviceVector newDevices;
5656 onNewAudioModulesAvailableInt(&newDevices);
5657 if (!newDevices.empty()) {
5658 nextAudioPortGeneration();
5659 mpClientInterface->onAudioPortListUpdate();
5660 }
5661}
5662
5663void AudioPolicyManager::onNewAudioModulesAvailableInt(DeviceVector *newDevices)
5664{
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005665 for (const auto& hwModule : mHwModulesAll) {
5666 if (std::find(mHwModules.begin(), mHwModules.end(), hwModule) != mHwModules.end()) {
5667 continue;
5668 }
5669 hwModule->setHandle(mpClientInterface->loadHwModule(hwModule->getName()));
5670 if (hwModule->getHandle() == AUDIO_MODULE_HANDLE_NONE) {
5671 ALOGW("could not open HW module %s", hwModule->getName());
5672 continue;
5673 }
5674 mHwModules.push_back(hwModule);
Dean Wheatley12a87132021-04-16 10:08:49 +10005675 // open all output streams needed to access attached devices.
5676 // direct outputs are closed immediately after checking the availability of attached devices
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005677 // This also validates mAvailableOutputDevices list
5678 for (const auto& outProfile : hwModule->getOutputProfiles()) {
5679 if (!outProfile->canOpenNewIo()) {
5680 ALOGE("Invalid Output profile max open count %u for profile %s",
5681 outProfile->maxOpenCount, outProfile->getTagName().c_str());
5682 continue;
5683 }
5684 if (!outProfile->hasSupportedDevices()) {
5685 ALOGW("Output profile contains no device on module %s", hwModule->getName());
5686 continue;
5687 }
Carter Hsu1a3364a2022-01-21 15:32:56 +08005688 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_TTS) != 0 ||
5689 (outProfile->getFlags() & AUDIO_OUTPUT_FLAG_ULTRASOUND) != 0) {
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005690 mTtsOutputAvailable = true;
5691 }
5692
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005693 const DeviceVector &supportedDevices = outProfile->getSupportedDevices();
5694 DeviceVector availProfileDevices = supportedDevices.filter(mOutputDevicesAll);
5695 sp<DeviceDescriptor> supportedDevice = 0;
5696 if (supportedDevices.contains(mDefaultOutputDevice)) {
5697 supportedDevice = mDefaultOutputDevice;
5698 } else {
5699 // choose first device present in profile's SupportedDevices also part of
5700 // mAvailableOutputDevices.
5701 if (availProfileDevices.isEmpty()) {
5702 continue;
5703 }
5704 supportedDevice = availProfileDevices.itemAt(0);
5705 }
5706 if (!mOutputDevicesAll.contains(supportedDevice)) {
5707 continue;
5708 }
5709 sp<SwAudioOutputDescriptor> outputDesc = new SwAudioOutputDescriptor(outProfile,
5710 mpClientInterface);
5711 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentf1f22e72021-07-13 14:04:14 +02005712 status_t status = outputDesc->open(nullptr /* halConfig */, nullptr /* mixerConfig */,
5713 DeviceVector(supportedDevice),
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005714 AUDIO_STREAM_DEFAULT,
5715 AUDIO_OUTPUT_FLAG_NONE, &output);
5716 if (status != NO_ERROR) {
5717 ALOGW("Cannot open output stream for devices %s on hw module %s",
5718 supportedDevice->toString().c_str(), hwModule->getName());
5719 continue;
5720 }
5721 for (const auto &device : availProfileDevices) {
5722 // give a valid ID to an attached device once confirmed it is reachable
5723 if (!device->isAttached()) {
5724 device->attach(hwModule);
5725 mAvailableOutputDevices.add(device);
jiabin1c4794b2020-05-05 10:08:05 -07005726 device->setEncapsulationInfoFromHal(mpClientInterface);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07005727 if (newDevices) newDevices->add(device);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005728 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
5729 }
5730 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02005731 if (mPrimaryOutput == nullptr &&
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005732 outProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
5733 mPrimaryOutput = outputDesc;
5734 }
Eric Laurent39095982021-08-24 18:29:27 +02005735 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
Eric Laurentc529cf62020-04-17 18:19:10 -07005736 outputDesc->close();
5737 } else {
5738 addOutput(output, outputDesc);
5739 setOutputDevices(outputDesc,
5740 DeviceVector(supportedDevice),
5741 true,
5742 0,
5743 NULL);
5744 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005745 }
5746 // open input streams needed to access attached devices to validate
5747 // mAvailableInputDevices list
5748 for (const auto& inProfile : hwModule->getInputProfiles()) {
5749 if (!inProfile->canOpenNewIo()) {
5750 ALOGE("Invalid Input profile max open count %u for profile %s",
5751 inProfile->maxOpenCount, inProfile->getTagName().c_str());
5752 continue;
5753 }
5754 if (!inProfile->hasSupportedDevices()) {
5755 ALOGW("Input profile contains no device on module %s", hwModule->getName());
5756 continue;
5757 }
5758 // chose first device present in profile's SupportedDevices also part of
5759 // available input devices
5760 const DeviceVector &supportedDevices = inProfile->getSupportedDevices();
5761 DeviceVector availProfileDevices = supportedDevices.filter(mInputDevicesAll);
5762 if (availProfileDevices.isEmpty()) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01005763 ALOGV("%s: Input device list is empty! for profile %s",
5764 __func__, inProfile->getTagName().c_str());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005765 continue;
5766 }
5767 sp<AudioInputDescriptor> inputDesc =
5768 new AudioInputDescriptor(inProfile, mpClientInterface);
5769
5770 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
5771 status_t status = inputDesc->open(nullptr,
5772 availProfileDevices.itemAt(0),
5773 AUDIO_SOURCE_MIC,
5774 AUDIO_INPUT_FLAG_NONE,
5775 &input);
5776 if (status != NO_ERROR) {
5777 ALOGW("Cannot open input stream for device %s on hw module %s",
5778 availProfileDevices.toString().c_str(),
5779 hwModule->getName());
5780 continue;
5781 }
5782 for (const auto &device : availProfileDevices) {
5783 // give a valid ID to an attached device once confirmed it is reachable
5784 if (!device->isAttached()) {
5785 device->attach(hwModule);
5786 device->importAudioPortAndPickAudioProfile(inProfile, true);
5787 mAvailableInputDevices.add(device);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07005788 if (newDevices) newDevices->add(device);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005789 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
5790 }
5791 }
5792 inputDesc->close();
5793 }
5794 }
Eric Laurente191d1b2022-04-15 11:59:25 +02005795
5796 // Check if spatializer outputs can be closed until used.
5797 // mOutputs vector never contains duplicated outputs at this point.
5798 std::vector<audio_io_handle_t> outputsClosed;
5799 for (size_t i = 0; i < mOutputs.size(); i++) {
5800 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
5801 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0
5802 && !isOutputOnlyAvailableRouteToSomeDevice(desc)) {
5803 outputsClosed.push_back(desc->mIoHandle);
5804 desc->close();
5805 }
5806 }
5807 for (auto output : outputsClosed) {
5808 removeOutput(output);
5809 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005810}
5811
Eric Laurent98e38192018-02-15 18:31:53 -08005812void AudioPolicyManager::addOutput(audio_io_handle_t output,
5813 const sp<SwAudioOutputDescriptor>& outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07005814{
Eric Laurent1c333e22014-05-20 10:48:17 -07005815 mOutputs.add(output, outputDesc);
jiabin9a3361e2019-10-01 09:38:30 -07005816 applyStreamVolumes(outputDesc, DeviceTypeSet(), 0 /* delayMs */, true /* force */);
Andy Hung2ddee192015-12-18 17:34:44 -08005817 updateMono(output); // update mono status when adding to output list
Eric Laurent36829f92017-04-07 19:04:42 -07005818 selectOutputForMusicEffects();
Eric Laurent6a94d692014-05-20 11:18:06 -07005819 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07005820}
5821
François Gaffie53615e22015-03-19 09:24:12 +01005822void AudioPolicyManager::removeOutput(audio_io_handle_t output)
5823{
Francois Gaffiebce7cd42020-10-14 16:13:20 +02005824 if (mPrimaryOutput != 0 && mPrimaryOutput == mOutputs.valueFor(output)) {
5825 ALOGV("%s: removing primary output", __func__);
5826 mPrimaryOutput = nullptr;
5827 }
François Gaffie53615e22015-03-19 09:24:12 +01005828 mOutputs.removeItem(output);
Eric Laurent36829f92017-04-07 19:04:42 -07005829 selectOutputForMusicEffects();
François Gaffie53615e22015-03-19 09:24:12 +01005830}
5831
Eric Laurent98e38192018-02-15 18:31:53 -08005832void AudioPolicyManager::addInput(audio_io_handle_t input,
5833 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07005834{
Eric Laurent1c333e22014-05-20 10:48:17 -07005835 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07005836 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07005837}
Eric Laurente552edb2014-03-10 17:42:56 -07005838
François Gaffie11d30102018-11-02 16:09:09 +01005839status_t AudioPolicyManager::checkOutputsForDevice(const sp<DeviceDescriptor>& device,
François Gaffie53615e22015-03-19 09:24:12 +01005840 audio_policy_dev_state_t state,
François Gaffie11d30102018-11-02 16:09:09 +01005841 SortedVector<audio_io_handle_t>& outputs)
Eric Laurente552edb2014-03-10 17:42:56 -07005842{
François Gaffie11d30102018-11-02 16:09:09 +01005843 audio_devices_t deviceType = device->type();
jiabince9f20e2019-09-12 16:29:15 -07005844 const String8 &address = String8(device->address().c_str());
Eric Laurentc75307b2015-03-17 15:29:32 -07005845 sp<SwAudioOutputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07005846
François Gaffie11d30102018-11-02 16:09:09 +01005847 if (audio_device_is_digital(deviceType)) {
Eric Laurentcc750d32015-06-25 11:48:20 -07005848 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01005849 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07005850 }
Eric Laurente552edb2014-03-10 17:42:56 -07005851
Eric Laurent3b73df72014-03-11 09:06:29 -07005852 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
jiabinb4fed192020-09-22 14:45:40 -07005853 // first call getAudioPort to get the supported attributes from the HAL
5854 struct audio_port_v7 port = {};
5855 device->toAudioPort(&port);
5856 status_t status = mpClientInterface->getAudioPort(&port);
5857 if (status == NO_ERROR) {
5858 device->importAudioPort(port);
5859 }
5860
5861 // then list already open outputs that can be routed to this device
Eric Laurente552edb2014-03-10 17:42:56 -07005862 for (size_t i = 0; i < mOutputs.size(); i++) {
5863 desc = mOutputs.valueAt(i);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005864 if (!desc->isDuplicated() && desc->supportsDevice(device)
jiabin9a3361e2019-10-01 09:38:30 -07005865 && desc->devicesSupportEncodedFormats({deviceType})) {
François Gaffie11d30102018-11-02 16:09:09 +01005866 ALOGV("checkOutputsForDevice(): adding opened output %d on device %s",
5867 mOutputs.keyAt(i), device->toString().c_str());
5868 outputs.add(mOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07005869 }
5870 }
5871 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07005872 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08005873 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005874 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
5875 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
François Gaffie11d30102018-11-02 16:09:09 +01005876 if (profile->supportsDevice(device)) {
5877 profiles.add(profile);
5878 ALOGV("checkOutputsForDevice(): adding profile %zu from module %s",
5879 j, hwModule->getName());
Eric Laurente552edb2014-03-10 17:42:56 -07005880 }
5881 }
5882 }
5883
Eric Laurent7b279bb2015-12-14 10:18:23 -08005884 ALOGV(" found %zu profiles, %zu outputs", profiles.size(), outputs.size());
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005885
Eric Laurente552edb2014-03-10 17:42:56 -07005886 if (profiles.isEmpty() && outputs.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01005887 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07005888 return BAD_VALUE;
5889 }
5890
5891 // open outputs for matching profiles if needed. Direct outputs are also opened to
5892 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
5893 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07005894 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07005895
5896 // nothing to do if one output is already opened for this profile
5897 size_t j;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005898 for (j = 0; j < outputs.size(); j++) {
5899 desc = mOutputs.valueFor(outputs.itemAt(j));
Eric Laurente552edb2014-03-10 17:42:56 -07005900 if (!desc->isDuplicated() && desc->mProfile == profile) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07005901 // matching profile: save the sample rates, format and channel masks supported
5902 // by the profile in our device descriptor
François Gaffie11d30102018-11-02 16:09:09 +01005903 if (audio_device_is_digital(deviceType)) {
jiabin4ef93452019-09-10 14:29:54 -07005904 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07005905 }
Eric Laurente552edb2014-03-10 17:42:56 -07005906 break;
5907 }
5908 }
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005909 if (j != outputs.size()) {
Eric Laurente552edb2014-03-10 17:42:56 -07005910 continue;
5911 }
5912
Eric Laurent3974e3b2017-12-07 17:58:43 -08005913 if (!profile->canOpenNewIo()) {
5914 ALOGW("Max Output number %u already opened for this profile %s",
5915 profile->maxOpenCount, profile->getTagName().c_str());
5916 continue;
5917 }
5918
Eric Laurent83efe1c2017-07-09 16:51:08 -07005919 ALOGV("opening output for device %08x with params %s profile %p name %s",
jiabin5740f082019-08-19 15:08:30 -07005920 deviceType, address.string(), profile.get(), profile->getName().c_str());
jiabinbce0c1d2020-10-05 11:20:18 -07005921 desc = openOutputWithProfileAndDevice(profile, DeviceVector(device));
5922 audio_io_handle_t output = desc == nullptr ? AUDIO_IO_HANDLE_NONE : desc->mIoHandle;
Eric Laurentcf2c0212014-07-25 16:20:43 -07005923 if (output == AUDIO_IO_HANDLE_NONE) {
François Gaffie11d30102018-11-02 16:09:09 +01005924 ALOGW("checkOutputsForDevice() could not open output for device %x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07005925 profiles.removeAt(profile_index);
5926 profile_index--;
5927 } else {
5928 outputs.add(output);
Paul McLean9080a4c2015-06-18 08:24:02 -07005929 // Load digital format info only for digital devices
François Gaffie11d30102018-11-02 16:09:09 +01005930 if (audio_device_is_digital(deviceType)) {
jiabinbce0c1d2020-10-05 11:20:18 -07005931 // TODO: when getAudioPort is ready, it may not be needed to import the audio
5932 // port but just pick audio profile
jiabin4ef93452019-09-10 14:29:54 -07005933 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07005934 }
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07005935
François Gaffie11d30102018-11-02 16:09:09 +01005936 if (device_distinguishes_on_address(deviceType)) {
5937 ALOGV("checkOutputsForDevice(): setOutputDevices %s",
5938 device->toString().c_str());
5939 setOutputDevices(desc, DeviceVector(device), true/*force*/, 0/*delay*/,
5940 NULL/*patch handle*/);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005941 }
Eric Laurente552edb2014-03-10 17:42:56 -07005942 ALOGV("checkOutputsForDevice(): adding output %d", output);
5943 }
5944 }
5945
5946 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01005947 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07005948 return BAD_VALUE;
5949 }
Eric Laurentd4692962014-05-05 18:13:44 -07005950 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07005951 // check if one opened output is not needed any more after disconnecting one device
5952 for (size_t i = 0; i < mOutputs.size(); i++) {
5953 desc = mOutputs.valueAt(i);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005954 if (!desc->isDuplicated()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08005955 // exact match on device
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005956 if (device_distinguishes_on_address(deviceType) && desc->supportsDevice(device)
Francois Gaffiec7d4c222021-12-02 11:12:52 +01005957 && desc->containsSingleDeviceSupportingEncodedFormats(device)) {
François Gaffie11d30102018-11-02 16:09:09 +01005958 outputs.add(mOutputs.keyAt(i));
Francois Gaffie716e1432019-01-14 16:58:59 +01005959 } else if (!mAvailableOutputDevices.containsAtLeastOne(desc->supportedDevices())) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005960 ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
5961 mOutputs.keyAt(i));
5962 outputs.add(mOutputs.keyAt(i));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005963 }
Eric Laurente552edb2014-03-10 17:42:56 -07005964 }
5965 }
Eric Laurentd4692962014-05-05 18:13:44 -07005966 // Clear any profiles associated with the disconnected device.
Mikhail Naganov7e22e942017-12-07 10:04:29 -08005967 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005968 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
5969 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
jiabinbce0c1d2020-10-05 11:20:18 -07005970 if (!profile->supportsDevice(device)) {
5971 continue;
5972 }
5973 ALOGV("checkOutputsForDevice(): "
5974 "clearing direct output profile %zu on module %s",
5975 j, hwModule->getName());
5976 profile->clearAudioProfiles();
5977 if (!profile->hasDynamicAudioProfile()) {
5978 continue;
5979 }
5980 // When a device is disconnected, if there is an IOProfile that contains dynamic
5981 // profiles and supports the disconnected device, call getAudioPort to repopulate
5982 // the capabilities of the devices that is supported by the IOProfile.
5983 for (const auto& supportedDevice : profile->getSupportedDevices()) {
5984 if (supportedDevice == device ||
5985 !mAvailableOutputDevices.contains(supportedDevice)) {
5986 continue;
5987 }
5988 struct audio_port_v7 port;
5989 supportedDevice->toAudioPort(&port);
5990 status_t status = mpClientInterface->getAudioPort(&port);
5991 if (status == NO_ERROR) {
5992 supportedDevice->importAudioPort(port);
5993 }
Eric Laurente552edb2014-03-10 17:42:56 -07005994 }
5995 }
5996 }
5997 }
5998 return NO_ERROR;
5999}
6000
François Gaffie11d30102018-11-02 16:09:09 +01006001status_t AudioPolicyManager::checkInputsForDevice(const sp<DeviceDescriptor>& device,
Eric Laurent0dd51852019-04-19 18:18:58 -07006002 audio_policy_dev_state_t state)
Eric Laurentd4692962014-05-05 18:13:44 -07006003{
Eric Laurent1f2f2232014-06-02 12:01:23 -07006004 sp<AudioInputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07006005
François Gaffie11d30102018-11-02 16:09:09 +01006006 if (audio_device_is_digital(device->type())) {
Eric Laurentcc750d32015-06-25 11:48:20 -07006007 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01006008 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07006009 }
6010
Eric Laurentd4692962014-05-05 18:13:44 -07006011 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
Eric Laurent0dd51852019-04-19 18:18:58 -07006012 // look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07006013 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006014 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07006015 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006016 profile_index < hwModule->getInputProfiles().size();
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006017 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006018 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Eric Laurent275e8e92014-11-30 15:14:47 -08006019
François Gaffie11d30102018-11-02 16:09:09 +01006020 if (profile->supportsDevice(device)) {
6021 profiles.add(profile);
6022 ALOGV("checkInputsForDevice(): adding profile %zu from module %s",
6023 profile_index, hwModule->getName());
Eric Laurentd4692962014-05-05 18:13:44 -07006024 }
6025 }
6026 }
6027
Eric Laurent0dd51852019-04-19 18:18:58 -07006028 if (profiles.isEmpty()) {
6029 ALOGW("%s: No input profile available for device %s",
6030 __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07006031 return BAD_VALUE;
6032 }
6033
6034 // open inputs for matching profiles if needed. Direct inputs are also opened to
6035 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
6036 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
6037
Eric Laurent1c333e22014-05-20 10:48:17 -07006038 sp<IOProfile> profile = profiles[profile_index];
Eric Laurent3974e3b2017-12-07 17:58:43 -08006039
Eric Laurentd4692962014-05-05 18:13:44 -07006040 // nothing to do if one input is already opened for this profile
6041 size_t input_index;
6042 for (input_index = 0; input_index < mInputs.size(); input_index++) {
6043 desc = mInputs.valueAt(input_index);
6044 if (desc->mProfile == profile) {
François Gaffie11d30102018-11-02 16:09:09 +01006045 if (audio_device_is_digital(device->type())) {
jiabin4ef93452019-09-10 14:29:54 -07006046 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006047 }
Eric Laurentd4692962014-05-05 18:13:44 -07006048 break;
6049 }
6050 }
6051 if (input_index != mInputs.size()) {
6052 continue;
6053 }
6054
Eric Laurent3974e3b2017-12-07 17:58:43 -08006055 if (!profile->canOpenNewIo()) {
6056 ALOGW("Max Input number %u already opened for this profile %s",
6057 profile->maxOpenCount, profile->getTagName().c_str());
6058 continue;
6059 }
6060
Eric Laurentfe231122017-11-17 17:48:06 -08006061 desc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentcf2c0212014-07-25 16:20:43 -07006062 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08006063 status_t status = desc->open(nullptr,
6064 device,
Eric Laurentfe231122017-11-17 17:48:06 -08006065 AUDIO_SOURCE_MIC,
6066 AUDIO_INPUT_FLAG_NONE,
6067 &input);
Eric Laurentd4692962014-05-05 18:13:44 -07006068
Eric Laurentcf2c0212014-07-25 16:20:43 -07006069 if (status == NO_ERROR) {
jiabince9f20e2019-09-12 16:29:15 -07006070 const String8& address = String8(device->address().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07006071 if (!address.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006072 char *param = audio_device_address_to_parameter(device->type(), address);
Eric Laurentcf2c0212014-07-25 16:20:43 -07006073 mpClientInterface->setParameters(input, String8(param));
6074 free(param);
Eric Laurentd4692962014-05-05 18:13:44 -07006075 }
François Gaffie11d30102018-11-02 16:09:09 +01006076 updateAudioProfiles(device, input, profile->getAudioProfiles());
François Gaffie112b0af2015-11-19 16:13:25 +01006077 if (!profile->hasValidAudioProfile()) {
Eric Laurentd4692962014-05-05 18:13:44 -07006078 ALOGW("checkInputsForDevice() direct input missing param");
Eric Laurentfe231122017-11-17 17:48:06 -08006079 desc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07006080 input = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07006081 }
6082
Eric Laurent0dd51852019-04-19 18:18:58 -07006083 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07006084 addInput(input, desc);
6085 }
6086 } // endif input != 0
6087
Eric Laurentcf2c0212014-07-25 16:20:43 -07006088 if (input == AUDIO_IO_HANDLE_NONE) {
Pattydd807582021-11-04 21:01:03 +08006089 ALOGW("%s could not open input for device %s", __func__,
François Gaffie11d30102018-11-02 16:09:09 +01006090 device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07006091 profiles.removeAt(profile_index);
6092 profile_index--;
6093 } else {
François Gaffie11d30102018-11-02 16:09:09 +01006094 if (audio_device_is_digital(device->type())) {
jiabin4ef93452019-09-10 14:29:54 -07006095 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006096 }
Eric Laurentd4692962014-05-05 18:13:44 -07006097 ALOGV("checkInputsForDevice(): adding input %d", input);
6098 }
6099 } // end scan profiles
6100
6101 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006102 ALOGW("%s: No input available for device %s", __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07006103 return BAD_VALUE;
6104 }
6105 } else {
6106 // Disconnect
Eric Laurentd4692962014-05-05 18:13:44 -07006107 // Clear any profiles associated with the disconnected device.
Mikhail Naganovd4120142017-12-06 15:49:22 -08006108 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07006109 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006110 profile_index < hwModule->getInputProfiles().size();
Eric Laurentd4692962014-05-05 18:13:44 -07006111 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006112 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Francois Gaffie716e1432019-01-14 16:58:59 +01006113 if (profile->supportsDevice(device)) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08006114 ALOGV("checkInputsForDevice(): clearing direct input profile %zu on module %s",
6115 profile_index, hwModule->getName());
François Gaffie112b0af2015-11-19 16:13:25 +01006116 profile->clearAudioProfiles();
Eric Laurentd4692962014-05-05 18:13:44 -07006117 }
6118 }
6119 }
6120 } // end disconnect
6121
6122 return NO_ERROR;
6123}
6124
6125
Eric Laurente0720872014-03-11 09:30:41 -07006126void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07006127{
6128 ALOGV("closeOutput(%d)", output);
6129
François Gaffie1c878552018-11-22 16:53:21 +01006130 sp<SwAudioOutputDescriptor> closingOutput = mOutputs.valueFor(output);
6131 if (closingOutput == NULL) {
Eric Laurente552edb2014-03-10 17:42:56 -07006132 ALOGW("closeOutput() unknown output %d", output);
6133 return;
6134 }
Mikhail Naganov32ebca32019-03-22 15:42:52 -07006135 const bool closingOutputWasActive = closingOutput->isActive();
François Gaffie1c878552018-11-22 16:53:21 +01006136 mPolicyMixes.closeOutput(closingOutput);
Eric Laurent275e8e92014-11-30 15:14:47 -08006137
Eric Laurente552edb2014-03-10 17:42:56 -07006138 // look for duplicated outputs connected to the output being removed.
6139 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie1c878552018-11-22 16:53:21 +01006140 sp<SwAudioOutputDescriptor> dupOutput = mOutputs.valueAt(i);
6141 if (dupOutput->isDuplicated() &&
6142 (dupOutput->mOutput1 == closingOutput || dupOutput->mOutput2 == closingOutput)) {
6143 sp<SwAudioOutputDescriptor> remainingOutput =
6144 dupOutput->mOutput1 == closingOutput ? dupOutput->mOutput2 : dupOutput->mOutput1;
Eric Laurente552edb2014-03-10 17:42:56 -07006145 // As all active tracks on duplicated output will be deleted,
6146 // and as they were also referenced on the other output, the reference
6147 // count for their stream type must be adjusted accordingly on
6148 // the other output.
François Gaffie1c878552018-11-22 16:53:21 +01006149 const bool wasActive = remainingOutput->isActive();
6150 // Note: no-op on the closing output where all clients has already been set inactive
6151 dupOutput->setAllClientsInactive();
Eric Laurent733ce942017-12-07 12:18:25 -08006152 // stop() will be a no op if the output is still active but is needed in case all
6153 // active streams refcounts where cleared above
6154 if (wasActive) {
François Gaffie1c878552018-11-22 16:53:21 +01006155 remainingOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08006156 }
Eric Laurente552edb2014-03-10 17:42:56 -07006157 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
6158 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
6159
6160 mpClientInterface->closeOutput(duplicatedOutput);
François Gaffie53615e22015-03-19 09:24:12 +01006161 removeOutput(duplicatedOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07006162 }
6163 }
6164
Eric Laurent05b90f82014-08-27 15:32:29 -07006165 nextAudioPortGeneration();
6166
François Gaffie1c878552018-11-22 16:53:21 +01006167 ssize_t index = mAudioPatches.indexOfKey(closingOutput->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07006168 if (index >= 0) {
6169 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006170 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
6171 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07006172 mAudioPatches.removeItemsAt(index);
6173 mpClientInterface->onAudioPatchListUpdate();
6174 }
6175
Mikhail Naganov32ebca32019-03-22 15:42:52 -07006176 if (closingOutputWasActive) {
6177 closingOutput->stop();
6178 }
François Gaffie1c878552018-11-22 16:53:21 +01006179 closingOutput->close();
Eric Laurente552edb2014-03-10 17:42:56 -07006180
François Gaffie53615e22015-03-19 09:24:12 +01006181 removeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07006182 mPreviousOutputs = mOutputs;
Eric Laurentb4f42a92022-01-17 17:37:31 +01006183 if (closingOutput == mSpatializerOutput) {
6184 mSpatializerOutput.clear();
6185 }
Dean Wheatley3023b382018-08-09 07:42:40 +10006186
6187 // MSD patches may have been released to support a non-MSD direct output. Reset MSD patch if
6188 // no direct outputs are open.
François Gaffie11d30102018-11-02 16:09:09 +01006189 if (!getMsdAudioOutDevices().isEmpty()) {
Dean Wheatley3023b382018-08-09 07:42:40 +10006190 bool directOutputOpen = false;
6191 for (size_t i = 0; i < mOutputs.size(); i++) {
6192 if (mOutputs[i]->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
6193 directOutputOpen = true;
6194 break;
6195 }
6196 }
6197 if (!directOutputOpen) {
Michael Chan6fb34492020-12-08 15:44:49 +11006198 ALOGV("no direct outputs open, reset MSD patches");
6199 // TODO: The MSD patches to be established here may differ to current MSD patches due to
6200 // how output devices for patching are resolved. Avoid by caching and reusing the
6201 // arguments to mEngine->getOutputDevicesForAttributes() when resolving which output
6202 // devices to patch to. This may be complicated by the fact that devices may become
6203 // unavailable.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11006204 setMsdOutputPatches();
Dean Wheatley3023b382018-08-09 07:42:40 +10006205 }
6206 }
Eric Laurent05b90f82014-08-27 15:32:29 -07006207}
6208
6209void AudioPolicyManager::closeInput(audio_io_handle_t input)
6210{
6211 ALOGV("closeInput(%d)", input);
6212
6213 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
6214 if (inputDesc == NULL) {
6215 ALOGW("closeInput() unknown input %d", input);
6216 return;
6217 }
6218
Eric Laurent6a94d692014-05-20 11:18:06 -07006219 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07006220
François Gaffie11d30102018-11-02 16:09:09 +01006221 sp<DeviceDescriptor> device = inputDesc->getDevice();
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08006222 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07006223 if (index >= 0) {
6224 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006225 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
6226 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07006227 mAudioPatches.removeItemsAt(index);
6228 mpClientInterface->onAudioPatchListUpdate();
6229 }
6230
Eric Laurentfe231122017-11-17 17:48:06 -08006231 inputDesc->close();
Eric Laurent05b90f82014-08-27 15:32:29 -07006232 mInputs.removeItem(input);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07006233
François Gaffie11d30102018-11-02 16:09:09 +01006234 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
6235 if (primaryInputDevices.contains(device) &&
Haynes Mathew George1d539d92018-03-16 11:40:49 -07006236 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07006237 mpClientInterface->setSoundTriggerCaptureState(false);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07006238 }
Eric Laurente552edb2014-03-10 17:42:56 -07006239}
6240
François Gaffie11d30102018-11-02 16:09:09 +01006241SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevices(
6242 const DeviceVector &devices,
6243 const SwAudioOutputCollection& openOutputs)
Eric Laurente552edb2014-03-10 17:42:56 -07006244{
6245 SortedVector<audio_io_handle_t> outputs;
6246
François Gaffie11d30102018-11-02 16:09:09 +01006247 ALOGVV("%s() devices %s", __func__, devices.toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07006248 for (size_t i = 0; i < openOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01006249 ALOGVV("output %zu isDuplicated=%d device=%s",
Eric Laurent8c7e6da2015-04-21 17:37:00 -07006250 i, openOutputs.valueAt(i)->isDuplicated(),
François Gaffie11d30102018-11-02 16:09:09 +01006251 openOutputs.valueAt(i)->supportedDevices().toString().c_str());
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006252 if (openOutputs.valueAt(i)->supportsAllDevices(devices)
jiabin9a3361e2019-10-01 09:38:30 -07006253 && openOutputs.valueAt(i)->devicesSupportEncodedFormats(devices.types())) {
François Gaffie11d30102018-11-02 16:09:09 +01006254 ALOGVV("%s() found output %d", __func__, openOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07006255 outputs.add(openOutputs.keyAt(i));
6256 }
6257 }
6258 return outputs;
6259}
6260
Mikhail Naganov37977152018-07-11 15:54:44 -07006261void AudioPolicyManager::checkForDeviceAndOutputChanges(std::function<bool()> onOutputsChecked)
6262{
6263 // checkA2dpSuspend must run before checkOutputForAllStrategies so that A2DP
6264 // output is suspended before any tracks are moved to it
6265 checkA2dpSuspend();
6266 checkOutputForAllStrategies();
Kevin Rocard153f92d2018-12-18 18:33:28 -08006267 checkSecondaryOutputs();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11006268 if (onOutputsChecked != nullptr && onOutputsChecked()) checkA2dpSuspend();
Mikhail Naganov37977152018-07-11 15:54:44 -07006269 updateDevicesAndOutputs();
Mikhail Naganov7bd9b8d2018-11-15 02:09:03 +00006270 if (mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD) != 0) {
Michael Chan6fb34492020-12-08 15:44:49 +11006271 // TODO: The MSD patches to be established here may differ to current MSD patches due to how
6272 // output devices for patching are resolved. Nevertheless, AudioTracks affected by device
6273 // configuration changes will ultimately be rerouted correctly. We can still avoid
6274 // unnecessary rerouting by caching and reusing the arguments to
6275 // mEngine->getOutputDevicesForAttributes() when resolving which output devices to patch to.
6276 // This may be complicated by the fact that devices may become unavailable.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11006277 setMsdOutputPatches();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11006278 }
Jean-Michel Trivi9a6b9ad2020-10-22 16:46:43 -07006279 // an event that changed routing likely occurred, inform upper layers
6280 mpClientInterface->onRoutingUpdated();
Mikhail Naganov37977152018-07-11 15:54:44 -07006281}
6282
François Gaffiec005e562018-11-06 15:04:49 +01006283bool AudioPolicyManager::followsSameRouting(const audio_attributes_t &lAttr,
6284 const audio_attributes_t &rAttr) const
Eric Laurente552edb2014-03-10 17:42:56 -07006285{
François Gaffiec005e562018-11-06 15:04:49 +01006286 return mEngine->getProductStrategyForAttributes(lAttr) ==
6287 mEngine->getProductStrategyForAttributes(rAttr);
6288}
6289
Francois Gaffieff1eb522020-05-06 18:37:04 +02006290void AudioPolicyManager::checkAudioSourceForAttributes(const audio_attributes_t &attr)
6291{
6292 for (size_t i = 0; i < mAudioSources.size(); i++) {
6293 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
6294 if (sourceDesc != nullptr && followsSameRouting(attr, sourceDesc->attributes())
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02006295 && sourceDesc->getPatchHandle() == AUDIO_PATCH_HANDLE_NONE
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02006296 && !isCallRxAudioSource(sourceDesc) && !sourceDesc->isInternal()) {
Francois Gaffieff1eb522020-05-06 18:37:04 +02006297 connectAudioSource(sourceDesc);
6298 }
6299 }
6300}
6301
6302void AudioPolicyManager::clearAudioSourcesForOutput(audio_io_handle_t output)
6303{
6304 for (size_t i = 0; i < mAudioSources.size(); i++) {
6305 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
6306 if (sourceDesc != nullptr && sourceDesc->swOutput().promote() != nullptr
6307 && sourceDesc->swOutput().promote()->mIoHandle == output) {
6308 disconnectAudioSource(sourceDesc);
6309 }
6310 }
6311}
6312
François Gaffiec005e562018-11-06 15:04:49 +01006313void AudioPolicyManager::checkOutputForAttributes(const audio_attributes_t &attr)
6314{
6315 auto psId = mEngine->getProductStrategyForAttributes(attr);
6316
6317 DeviceVector oldDevices = mEngine->getOutputDevicesForAttributes(attr, 0, true /*fromCache*/);
6318 DeviceVector newDevices = mEngine->getOutputDevicesForAttributes(attr, 0, false /*fromCache*/);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07006319
François Gaffie11d30102018-11-02 16:09:09 +01006320 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevices(oldDevices, mPreviousOutputs);
6321 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevices(newDevices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07006322
Eric Laurentc209fe42020-06-05 18:11:23 -07006323 uint32_t maxLatency = 0;
6324 bool invalidate = false;
6325 // take into account dynamic audio policies related changes: if a client is now associated
6326 // to a different policy mix than at creation time, invalidate corresponding stream
6327 for (size_t i = 0; i < mPreviousOutputs.size() && !invalidate; i++) {
6328 const sp<SwAudioOutputDescriptor>& desc = mPreviousOutputs.valueAt(i);
6329 if (desc->isDuplicated()) {
6330 continue;
Jean-Michel Trivife472e22014-12-16 14:23:13 -08006331 }
Eric Laurentc209fe42020-06-05 18:11:23 -07006332 for (const sp<TrackClientDescriptor>& client : desc->getClientIterable()) {
6333 if (mEngine->getProductStrategyForAttributes(client->attributes()) != psId) {
6334 continue;
6335 }
6336 sp<AudioPolicyMix> primaryMix;
Dean Wheatleyd082f472022-02-04 11:10:48 +11006337 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->config(),
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02006338 client->uid(), client->session(), client->flags(), primaryMix, nullptr);
Eric Laurentc209fe42020-06-05 18:11:23 -07006339 if (status != OK) {
6340 continue;
6341 }
yucliuf4de36d2020-09-14 14:57:56 -07006342 if (client->getPrimaryMix() != primaryMix || client->hasLostPrimaryMix()) {
Eric Laurentc209fe42020-06-05 18:11:23 -07006343 invalidate = true;
6344 if (desc->isStrategyActive(psId)) {
6345 maxLatency = desc->latency();
6346 }
6347 break;
6348 }
Jean-Michel Trivife472e22014-12-16 14:23:13 -08006349 }
6350 }
6351
Eric Laurentc209fe42020-06-05 18:11:23 -07006352 if (srcOutputs != dstOutputs || invalidate) {
Eric Laurentac3a6902018-05-11 16:39:10 -07006353 // get maximum latency of all source outputs to determine the minimum mute time guaranteeing
6354 // audio from invalidated tracks will be rendered when unmuting
Eric Laurentac3a6902018-05-11 16:39:10 -07006355 for (audio_io_handle_t srcOut : srcOutputs) {
6356 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
Eric Laurentaa02db82019-09-05 17:31:49 -07006357 if (desc == nullptr) continue;
6358
6359 if (desc->isStrategyActive(psId) && maxLatency < desc->latency()) {
Eric Laurentac3a6902018-05-11 16:39:10 -07006360 maxLatency = desc->latency();
6361 }
Eric Laurentaa02db82019-09-05 17:31:49 -07006362
6363 if (invalidate) continue;
6364
6365 for (auto client : desc->clientsList(false /*activeOnly*/)) {
Eric Laurent78aade82019-09-13 18:55:08 -07006366 if (desc->isDuplicated() || !desc->mProfile->isDirectOutput()) {
Eric Laurentaa02db82019-09-05 17:31:49 -07006367 // a client on a non direct outputs has necessarily a linear PCM format
6368 // so we can call selectOutput() safely
6369 const audio_io_handle_t newOutput = selectOutput(dstOutputs,
6370 client->flags(),
6371 client->config().format,
6372 client->config().channel_mask,
jiabinebb6af42020-06-09 17:31:17 -07006373 client->config().sample_rate,
6374 client->session());
Eric Laurentaa02db82019-09-05 17:31:49 -07006375 if (newOutput != srcOut) {
6376 invalidate = true;
6377 break;
6378 }
6379 } else {
6380 sp<IOProfile> profile = getProfileForOutput(newDevices,
6381 client->config().sample_rate,
6382 client->config().format,
6383 client->config().channel_mask,
6384 client->flags(),
6385 true /* directOnly */);
6386 if (profile != desc->mProfile) {
6387 invalidate = true;
6388 break;
6389 }
6390 }
6391 }
Eric Laurentac3a6902018-05-11 16:39:10 -07006392 }
Eric Laurentaa02db82019-09-05 17:31:49 -07006393
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006394 ALOGV_IF(!(srcOutputs.isEmpty() || dstOutputs.isEmpty()),
François Gaffiec005e562018-11-06 15:04:49 +01006395 "%s: strategy %d, moving from output %s to output %s", __func__, psId,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006396 std::to_string(srcOutputs[0]).c_str(),
6397 std::to_string(dstOutputs[0]).c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07006398 // mute strategy while moving tracks from one output to another
Mikhail Naganovcf84e592017-12-07 11:25:11 -08006399 for (audio_io_handle_t srcOut : srcOutputs) {
Eric Laurentac3a6902018-05-11 16:39:10 -07006400 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
Eric Laurentaa02db82019-09-05 17:31:49 -07006401 if (desc == nullptr) continue;
6402
6403 if (desc->isStrategyActive(psId)) {
François Gaffiec005e562018-11-06 15:04:49 +01006404 setStrategyMute(psId, true, desc);
6405 setStrategyMute(psId, false, desc, maxLatency * LATENCY_MUTE_FACTOR,
François Gaffie11d30102018-11-02 16:09:09 +01006406 newDevices.types());
Eric Laurente552edb2014-03-10 17:42:56 -07006407 }
François Gaffiec005e562018-11-06 15:04:49 +01006408 sp<SourceClientDescriptor> source = getSourceForAttributesOnOutput(srcOut, attr);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02006409 if (source != nullptr && !isCallRxAudioSource(source) && !source->isInternal()) {
Eric Laurentd60560a2015-04-10 11:31:20 -07006410 connectAudioSource(source);
6411 }
Eric Laurente552edb2014-03-10 17:42:56 -07006412 }
6413
François Gaffiec005e562018-11-06 15:04:49 +01006414 // Move effects associated to this stream from previous output to new output
6415 if (followsSameRouting(attr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07006416 selectOutputForMusicEffects();
Eric Laurente552edb2014-03-10 17:42:56 -07006417 }
François Gaffiec005e562018-11-06 15:04:49 +01006418 // Move tracks associated to this stream (and linked) from previous output to new output
Eric Laurentaa02db82019-09-05 17:31:49 -07006419 if (invalidate) {
6420 for (auto stream : mEngine->getStreamTypesForProductStrategy(psId)) {
6421 mpClientInterface->invalidateStream(stream);
6422 }
jiabin49256852022-03-09 11:21:35 -08006423 for (audio_io_handle_t srcOut : srcOutputs) {
6424 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
6425 if (desc == nullptr) continue;
6426
6427 desc->setTracksInvalidatedStatusByStrategy(psId);
6428 }
Eric Laurente552edb2014-03-10 17:42:56 -07006429 }
6430 }
6431}
6432
Eric Laurente0720872014-03-11 09:30:41 -07006433void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07006434{
François Gaffiec005e562018-11-06 15:04:49 +01006435 for (const auto &strategy : mEngine->getOrderedProductStrategies()) {
6436 auto attributes = mEngine->getAllAttributesForProductStrategy(strategy).front();
6437 checkOutputForAttributes(attributes);
Francois Gaffieff1eb522020-05-06 18:37:04 +02006438 checkAudioSourceForAttributes(attributes);
François Gaffiec005e562018-11-06 15:04:49 +01006439 }
Eric Laurente552edb2014-03-10 17:42:56 -07006440}
6441
Kevin Rocard153f92d2018-12-18 18:33:28 -08006442void AudioPolicyManager::checkSecondaryOutputs() {
6443 std::set<audio_stream_type_t> streamsToInvalidate;
jiabin10a03f12021-05-07 23:46:28 +00006444 TrackSecondaryOutputsMap trackSecondaryOutputs;
Kevin Rocard153f92d2018-12-18 18:33:28 -08006445 for (size_t i = 0; i < mOutputs.size(); i++) {
6446 const sp<SwAudioOutputDescriptor>& outputDescriptor = mOutputs[i];
6447 for (const sp<TrackClientDescriptor>& client : outputDescriptor->getClientIterable()) {
Eric Laurentc529cf62020-04-17 18:19:10 -07006448 sp<AudioPolicyMix> primaryMix;
6449 std::vector<sp<AudioPolicyMix>> secondaryMixes;
Dean Wheatleyd082f472022-02-04 11:10:48 +11006450 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->config(),
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02006451 client->uid(), client->session(), client->flags(), primaryMix, &secondaryMixes);
Eric Laurentc529cf62020-04-17 18:19:10 -07006452 std::vector<sp<SwAudioOutputDescriptor>> secondaryDescs;
6453 for (auto &secondaryMix : secondaryMixes) {
6454 sp<SwAudioOutputDescriptor> outputDesc = secondaryMix->getOutput();
6455 if (outputDesc != nullptr &&
6456 outputDesc->mIoHandle != AUDIO_IO_HANDLE_NONE) {
6457 secondaryDescs.push_back(outputDesc);
6458 }
6459 }
6460
jiabin10a03f12021-05-07 23:46:28 +00006461 if (status != OK) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08006462 streamsToInvalidate.insert(client->stream());
jiabin10a03f12021-05-07 23:46:28 +00006463 } else if (!std::equal(
6464 client->getSecondaryOutputs().begin(),
6465 client->getSecondaryOutputs().end(),
6466 secondaryDescs.begin(), secondaryDescs.end())) {
jiabina5281062021-11-23 00:10:23 +00006467 if (!audio_is_linear_pcm(client->config().format)) {
6468 // If the format is not PCM, the tracks should be invalidated to get correct
6469 // behavior when the secondary output is changed.
6470 streamsToInvalidate.insert(client->stream());
6471 } else {
6472 std::vector<wp<SwAudioOutputDescriptor>> weakSecondaryDescs;
6473 std::vector<audio_io_handle_t> secondaryOutputIds;
6474 for (const auto &secondaryDesc: secondaryDescs) {
6475 secondaryOutputIds.push_back(secondaryDesc->mIoHandle);
6476 weakSecondaryDescs.push_back(secondaryDesc);
6477 }
6478 trackSecondaryOutputs.emplace(client->portId(), secondaryOutputIds);
6479 client->setSecondaryOutputs(std::move(weakSecondaryDescs));
jiabin10a03f12021-05-07 23:46:28 +00006480 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08006481 }
6482 }
6483 }
jiabin10a03f12021-05-07 23:46:28 +00006484 if (!trackSecondaryOutputs.empty()) {
6485 mpClientInterface->updateSecondaryOutputs(trackSecondaryOutputs);
6486 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08006487 for (audio_stream_type_t stream : streamsToInvalidate) {
jiabin10a03f12021-05-07 23:46:28 +00006488 ALOGD("%s Invalidate stream %d due to fail getting output for attr", __func__, stream);
Kevin Rocard153f92d2018-12-18 18:33:28 -08006489 mpClientInterface->invalidateStream(stream);
6490 }
6491}
6492
Eric Laurent2517af32020-11-25 15:31:27 +01006493bool AudioPolicyManager::isScoRequestedForComm() const {
6494 AudioDeviceTypeAddrVector devices;
6495 mEngine->getDevicesForRoleAndStrategy(mCommunnicationStrategy, DEVICE_ROLE_PREFERRED, devices);
6496 for (const auto &device : devices) {
6497 if (audio_is_bluetooth_out_sco_device(device.mType)) {
6498 return true;
6499 }
6500 }
6501 return false;
6502}
6503
Eric Laurent1a8b45f2022-04-13 16:01:47 +02006504bool AudioPolicyManager::isHearingAidUsedForComm() const {
6505 DeviceVector devices = mEngine->getOutputDevicesForStream(AUDIO_STREAM_VOICE_CALL,
6506 true /*fromCache*/);
6507 for (const auto &device : devices) {
6508 if (device->type() == AUDIO_DEVICE_OUT_HEARING_AID) {
6509 return true;
6510 }
6511 }
6512 return false;
6513}
6514
6515
Eric Laurente0720872014-03-11 09:30:41 -07006516void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07006517{
François Gaffie53615e22015-03-19 09:24:12 +01006518 audio_io_handle_t a2dpOutput = mOutputs.getA2dpOutput();
Aniket Kumar Lataa8ee9962018-01-31 20:24:23 -08006519 if (a2dpOutput == 0 || mOutputs.isA2dpOffloadedOnPrimary()) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07006520 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07006521 return;
6522 }
6523
Eric Laurent3a4311c2014-03-17 12:00:47 -07006524 bool isScoConnected =
jiabin9a3361e2019-10-01 09:38:30 -07006525 (mAvailableInputDevices.types().count(AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) != 0 ||
6526 !Intersection(mAvailableOutputDevices.types(), getAudioDeviceOutAllScoSet()).empty());
Eric Laurent2517af32020-11-25 15:31:27 +01006527 bool isScoRequested = isScoRequestedForComm();
Eric Laurentf732e072016-08-03 19:30:28 -07006528
6529 // if suspended, restore A2DP output if:
6530 // ((SCO device is NOT connected) ||
Eric Laurent2517af32020-11-25 15:31:27 +01006531 // ((SCO is not requested) &&
Eric Laurentf732e072016-08-03 19:30:28 -07006532 // (phone state is NOT in call) && (phone state is NOT ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07006533 //
Eric Laurentf732e072016-08-03 19:30:28 -07006534 // if not suspended, suspend A2DP output if:
6535 // (SCO device is connected) &&
Eric Laurent2517af32020-11-25 15:31:27 +01006536 // ((SCO is requested) ||
Eric Laurentf732e072016-08-03 19:30:28 -07006537 // ((phone state is in call) || (phone state is ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07006538 //
6539 if (mA2dpSuspended) {
Eric Laurentf732e072016-08-03 19:30:28 -07006540 if (!isScoConnected ||
Eric Laurent2517af32020-11-25 15:31:27 +01006541 (!isScoRequested &&
Eric Laurentf732e072016-08-03 19:30:28 -07006542 (mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) &&
François Gaffie2110e042015-03-24 08:41:51 +01006543 (mEngine->getPhoneState() != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07006544
6545 mpClientInterface->restoreOutput(a2dpOutput);
6546 mA2dpSuspended = false;
6547 }
6548 } else {
Eric Laurentf732e072016-08-03 19:30:28 -07006549 if (isScoConnected &&
Eric Laurent2517af32020-11-25 15:31:27 +01006550 (isScoRequested ||
Eric Laurentf732e072016-08-03 19:30:28 -07006551 (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) ||
François Gaffie2110e042015-03-24 08:41:51 +01006552 (mEngine->getPhoneState() == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07006553
6554 mpClientInterface->suspendOutput(a2dpOutput);
6555 mA2dpSuspended = true;
6556 }
6557 }
6558}
6559
François Gaffie11d30102018-11-02 16:09:09 +01006560DeviceVector AudioPolicyManager::getNewOutputDevices(const sp<SwAudioOutputDescriptor>& outputDesc,
6561 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07006562{
François Gaffie11d30102018-11-02 16:09:09 +01006563 DeviceVector devices;
6564
Jean-Michel Triviff155c62016-02-26 12:07:16 -08006565 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07006566 if (index >= 0) {
6567 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006568 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01006569 ALOGV("%s device %s forced by patch %d", __func__,
6570 outputDesc->devices().toString().c_str(), outputDesc->getPatchHandle());
6571 return outputDesc->devices();
Eric Laurent6a94d692014-05-20 11:18:06 -07006572 }
6573 }
6574
Dean Wheatley514b4312020-06-17 21:45:00 +10006575 // Do not retrieve engine device for outputs through MSD
6576 // TODO: support explicit routing requests by resetting MSD patch to engine device.
6577 if (outputDesc->devices() == getMsdAudioOutDevices()) {
6578 return outputDesc->devices();
6579 }
6580
Eric Laurent97ac8712018-07-27 18:59:02 -07006581 // Honor explicit routing requests only if no client using default routing is active on this
6582 // input: a specific app can not force routing for other apps by setting a preferred device.
6583 bool active; // unused
François Gaffie11d30102018-11-02 16:09:09 +01006584 sp<DeviceDescriptor> device =
François Gaffiec005e562018-11-06 15:04:49 +01006585 findPreferredDevice(outputDesc, PRODUCT_STRATEGY_NONE, active, mAvailableOutputDevices);
François Gaffie11d30102018-11-02 16:09:09 +01006586 if (device != nullptr) {
6587 return DeviceVector(device);
Eric Laurentf3a5a602018-05-22 18:42:55 -07006588 }
6589
François Gaffiea807ef92018-11-05 10:44:33 +01006590 // Legacy Engine cannot take care of bus devices and mix, so we need to handle the conflict
6591 // of setForceUse / Default Bus device here
6592 device = mPolicyMixes.getDeviceAndMixForOutput(outputDesc, mAvailableOutputDevices);
6593 if (device != nullptr) {
6594 return DeviceVector(device);
6595 }
6596
François Gaffiec005e562018-11-06 15:04:49 +01006597 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
6598 StreamTypeVector streams = mEngine->getStreamTypesForProductStrategy(productStrategy);
6599 auto attr = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05306600 auto hasStreamActive = [&](auto stream) {
6601 return hasStream(streams, stream) && isStreamActive(stream, 0);
6602 };
Eric Laurent484e9272018-06-07 17:29:23 -07006603
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05306604 auto doGetOutputDevicesForVoice = [&]() {
6605 return hasVoiceStream(streams) && (outputDesc == mPrimaryOutput ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01006606 outputDesc->isActive(toVolumeSource(AUDIO_STREAM_VOICE_CALL, false))) &&
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05306607 (isInCall() ||
Henrik Backlund07c654a2021-10-14 15:57:10 +02006608 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc)) &&
6609 !isStreamActive(AUDIO_STREAM_ENFORCED_AUDIBLE, 0);
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05306610 };
6611
6612 // With low-latency playing on speaker, music on WFD, when the first low-latency
6613 // output is stopped, getNewOutputDevices checks for a product strategy
6614 // from the list, as STRATEGY_SONIFICATION comes prior to STRATEGY_MEDIA.
Carter Hsucc58a6b2021-07-20 08:44:50 +00006615 // If an ALARM or ENFORCED_AUDIBLE stream is supported by the product strategy,
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05306616 // devices are returned for STRATEGY_SONIFICATION without checking whether the
6617 // stream is associated to the output descriptor.
6618 if (doGetOutputDevicesForVoice() || outputDesc->isStrategyActive(productStrategy) ||
6619 ((hasStreamActive(AUDIO_STREAM_ALARM) ||
6620 hasStreamActive(AUDIO_STREAM_ENFORCED_AUDIBLE)) &&
6621 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc))) {
François Gaffiec005e562018-11-06 15:04:49 +01006622 // Retrieval of devices for voice DL is done on primary output profile, cannot
6623 // check the route (would force modifying configuration file for this profile)
6624 devices = mEngine->getOutputDevicesForAttributes(attr, nullptr, fromCache);
6625 break;
6626 }
Eric Laurente552edb2014-03-10 17:42:56 -07006627 }
François Gaffiec005e562018-11-06 15:04:49 +01006628 ALOGV("%s selected devices %s", __func__, devices.toString().c_str());
François Gaffie11d30102018-11-02 16:09:09 +01006629 return devices;
Eric Laurent1c333e22014-05-20 10:48:17 -07006630}
6631
François Gaffie11d30102018-11-02 16:09:09 +01006632sp<DeviceDescriptor> AudioPolicyManager::getNewInputDevice(
6633 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurent1c333e22014-05-20 10:48:17 -07006634{
François Gaffie11d30102018-11-02 16:09:09 +01006635 sp<DeviceDescriptor> device;
Eric Laurent6a94d692014-05-20 11:18:06 -07006636
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08006637 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07006638 if (index >= 0) {
6639 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006640 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01006641 ALOGV("getNewInputDevice() device %s forced by patch %d",
6642 inputDesc->getDevice()->toString().c_str(), inputDesc->getPatchHandle());
6643 return inputDesc->getDevice();
Eric Laurent6a94d692014-05-20 11:18:06 -07006644 }
6645 }
6646
Eric Laurent97ac8712018-07-27 18:59:02 -07006647 // Honor explicit routing requests only if no client using default routing is active on this
6648 // input: a specific app can not force routing for other apps by setting a preferred device.
6649 bool active;
François Gaffie11d30102018-11-02 16:09:09 +01006650 device = findPreferredDevice(inputDesc, AUDIO_SOURCE_DEFAULT, active, mAvailableInputDevices);
6651 if (device != nullptr) {
6652 return device;
Eric Laurent97ac8712018-07-27 18:59:02 -07006653 }
6654
Eric Laurentdc95a252018-04-12 12:46:56 -07006655 // If we are not in call and no client is active on this input, this methods returns
Andy Hungf024a9e2019-01-30 16:01:02 -08006656 // a null sp<>, causing the patch on the input stream to be released.
yuanjiahsu0735bf32021-03-18 08:12:54 +08006657 audio_attributes_t attributes;
6658 uid_t uid;
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02006659 audio_session_t session;
yuanjiahsu0735bf32021-03-18 08:12:54 +08006660 sp<RecordClientDescriptor> topClient = inputDesc->getHighestPriorityClient();
6661 if (topClient != nullptr) {
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01006662 attributes = topClient->attributes();
6663 uid = topClient->uid();
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02006664 session = topClient->session();
yuanjiahsu0735bf32021-03-18 08:12:54 +08006665 } else {
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01006666 attributes = { .source = AUDIO_SOURCE_DEFAULT };
6667 uid = 0;
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02006668 session = AUDIO_SESSION_NONE;
yuanjiahsu0735bf32021-03-18 08:12:54 +08006669 }
6670
Francois Gaffie716e1432019-01-14 16:58:59 +01006671 if (attributes.source == AUDIO_SOURCE_DEFAULT && isInCall()) {
6672 attributes.source = AUDIO_SOURCE_VOICE_COMMUNICATION;
Eric Laurentdc95a252018-04-12 12:46:56 -07006673 }
Francois Gaffie716e1432019-01-14 16:58:59 +01006674 if (attributes.source != AUDIO_SOURCE_DEFAULT) {
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02006675 device = mEngine->getInputDeviceForAttributes(attributes, uid, session);
Eric Laurentfb66dd92016-01-28 18:32:03 -08006676 }
Eric Laurent1c333e22014-05-20 10:48:17 -07006677
Eric Laurente552edb2014-03-10 17:42:56 -07006678 return device;
6679}
6680
Eric Laurent794fde22016-03-11 09:50:45 -08006681bool AudioPolicyManager::streamsMatchForvolume(audio_stream_type_t stream1,
6682 audio_stream_type_t stream2) {
Jean-Michel Trivi99bb2f92016-11-23 15:52:07 -08006683 return (stream1 == stream2);
Eric Laurent28d09f02016-03-08 10:43:05 -08006684}
6685
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08006686status_t AudioPolicyManager::getDevicesForAttributes(
Andy Hung6d23c0f2022-02-16 09:37:15 -08006687 const audio_attributes_t &attr, AudioDeviceTypeAddrVector *devices, bool forVolume) {
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08006688 if (devices == nullptr) {
6689 return BAD_VALUE;
6690 }
Andy Hung6d23c0f2022-02-16 09:37:15 -08006691
Andy Hung6d23c0f2022-02-16 09:37:15 -08006692 DeviceVector curDevices;
jiabinf1c73972022-04-14 16:28:52 -07006693 if (status_t status = getDevicesForAttributes(attr, curDevices, forVolume); status != OK) {
6694 return status;
Andy Hung6d23c0f2022-02-16 09:37:15 -08006695 }
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08006696 for (const auto& device : curDevices) {
6697 devices->push_back(device->getDeviceTypeAddr());
6698 }
6699 return NO_ERROR;
6700}
6701
Eric Laurente0720872014-03-11 09:30:41 -07006702void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07006703 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07006704 case AUDIO_STREAM_MUSIC:
François Gaffiec005e562018-11-06 15:04:49 +01006705 checkOutputForAttributes(attributes_initializer(AUDIO_USAGE_NOTIFICATION));
Eric Laurente552edb2014-03-10 17:42:56 -07006706 updateDevicesAndOutputs();
6707 break;
6708 default:
6709 break;
6710 }
6711}
6712
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006713uint32_t AudioPolicyManager::handleEventForBeacon(int event) {
Eric Laurent9459fb02015-08-12 18:36:32 -07006714
6715 // skip beacon mute management if a dedicated TTS output is available
6716 if (mTtsOutputAvailable) {
6717 return 0;
6718 }
6719
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006720 switch(event) {
6721 case STARTING_OUTPUT:
6722 mBeaconMuteRefCount++;
6723 break;
6724 case STOPPING_OUTPUT:
6725 if (mBeaconMuteRefCount > 0) {
6726 mBeaconMuteRefCount--;
6727 }
6728 break;
6729 case STARTING_BEACON:
6730 mBeaconPlayingRefCount++;
6731 break;
6732 case STOPPING_BEACON:
6733 if (mBeaconPlayingRefCount > 0) {
6734 mBeaconPlayingRefCount--;
6735 }
6736 break;
6737 }
6738
6739 if (mBeaconMuteRefCount > 0) {
6740 // any playback causes beacon to be muted
6741 return setBeaconMute(true);
6742 } else {
6743 // no other playback: unmute when beacon starts playing, mute when it stops
6744 return setBeaconMute(mBeaconPlayingRefCount == 0);
6745 }
6746}
6747
6748uint32_t AudioPolicyManager::setBeaconMute(bool mute) {
6749 ALOGV("setBeaconMute(%d) mBeaconMuteRefCount=%d mBeaconPlayingRefCount=%d",
6750 mute, mBeaconMuteRefCount, mBeaconPlayingRefCount);
6751 // keep track of muted state to avoid repeating mute/unmute operations
6752 if (mBeaconMuted != mute) {
6753 // mute/unmute AUDIO_STREAM_TTS on all outputs
6754 ALOGV("\t muting %d", mute);
6755 uint32_t maxLatency = 0;
Francois Gaffie4404ddb2021-02-04 17:03:38 +01006756 auto ttsVolumeSource = toVolumeSource(AUDIO_STREAM_TTS, false);
6757 if (ttsVolumeSource == VOLUME_SOURCE_NONE) {
6758 ALOGV("\t no tts volume source available");
6759 return 0;
6760 }
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006761 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07006762 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
jiabin9a3361e2019-10-01 09:38:30 -07006763 setVolumeSourceMute(ttsVolumeSource, mute/*on*/, desc, 0 /*delay*/, DeviceTypeSet());
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006764 const uint32_t latency = desc->latency() * 2;
Eric Laurentcdb2b352020-07-23 10:57:02 -07006765 if (desc->isActive(latency * 2) && latency > maxLatency) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006766 maxLatency = latency;
6767 }
6768 }
6769 mBeaconMuted = mute;
6770 return maxLatency;
6771 }
6772 return 0;
6773}
6774
Eric Laurente0720872014-03-11 09:30:41 -07006775void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07006776{
François Gaffiec005e562018-11-06 15:04:49 +01006777 mEngine->updateDeviceSelectionCache();
Eric Laurente552edb2014-03-10 17:42:56 -07006778 mPreviousOutputs = mOutputs;
6779}
6780
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07006781uint32_t AudioPolicyManager::checkDeviceMuteStrategies(const sp<AudioOutputDescriptor>& outputDesc,
François Gaffiec005e562018-11-06 15:04:49 +01006782 const DeviceVector &prevDevices,
Eric Laurente552edb2014-03-10 17:42:56 -07006783 uint32_t delayMs)
6784{
6785 // mute/unmute strategies using an incompatible device combination
6786 // if muting, wait for the audio in pcm buffer to be drained before proceeding
6787 // if unmuting, unmute only after the specified delay
6788 if (outputDesc->isDuplicated()) {
6789 return 0;
6790 }
6791
6792 uint32_t muteWaitMs = 0;
François Gaffiec005e562018-11-06 15:04:49 +01006793 DeviceVector devices = outputDesc->devices();
6794 bool shouldMute = outputDesc->isActive() && (devices.size() >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07006795
François Gaffiec005e562018-11-06 15:04:49 +01006796 auto productStrategies = mEngine->getOrderedProductStrategies();
6797 for (const auto &productStrategy : productStrategies) {
6798 auto attributes = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
6799 DeviceVector curDevices =
6800 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false/*fromCache*/);
6801 curDevices = curDevices.filter(outputDesc->supportedDevices());
6802 bool mute = shouldMute && curDevices.containsAtLeastOne(devices) && curDevices != devices;
Eric Laurente552edb2014-03-10 17:42:56 -07006803 bool doMute = false;
6804
François Gaffiec005e562018-11-06 15:04:49 +01006805 if (mute && !outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07006806 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01006807 outputDesc->setStrategyMutedByDevice(productStrategy, true);
6808 } else if (!mute && outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07006809 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01006810 outputDesc->setStrategyMutedByDevice(productStrategy, false);
Eric Laurente552edb2014-03-10 17:42:56 -07006811 }
Eric Laurent99401132014-05-07 19:48:15 -07006812 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07006813 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07006814 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07006815 // skip output if it does not share any device with current output
François Gaffie11d30102018-11-02 16:09:09 +01006816 if (!desc->supportedDevices().containsAtLeastOne(outputDesc->supportedDevices())) {
Eric Laurente552edb2014-03-10 17:42:56 -07006817 continue;
6818 }
François Gaffiec005e562018-11-06 15:04:49 +01006819 ALOGVV("%s() %s (curDevice %s)", __func__,
6820 mute ? "muting" : "unmuting", curDevices.toString().c_str());
6821 setStrategyMute(productStrategy, mute, desc, mute ? 0 : delayMs);
6822 if (desc->isStrategyActive(productStrategy)) {
Eric Laurent99401132014-05-07 19:48:15 -07006823 if (mute) {
6824 // FIXME: should not need to double latency if volume could be applied
6825 // immediately by the audioflinger mixer. We must account for the delay
6826 // between now and the next time the audioflinger thread for this output
6827 // will process a buffer (which corresponds to one buffer size,
6828 // usually 1/2 or 1/4 of the latency).
6829 if (muteWaitMs < desc->latency() * 2) {
6830 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07006831 }
6832 }
6833 }
6834 }
6835 }
6836 }
6837
Eric Laurent99401132014-05-07 19:48:15 -07006838 // temporary mute output if device selection changes to avoid volume bursts due to
6839 // different per device volumes
François Gaffiec005e562018-11-06 15:04:49 +01006840 if (outputDesc->isActive() && (devices != prevDevices)) {
Eric Laurentdc462862016-07-19 12:29:53 -07006841 uint32_t tempMuteWaitMs = outputDesc->latency() * 2;
Jasmine Chaf6074fe2021-08-17 13:44:31 +08006842
Eric Laurentdc462862016-07-19 12:29:53 -07006843 if (muteWaitMs < tempMuteWaitMs) {
6844 muteWaitMs = tempMuteWaitMs;
Eric Laurent99401132014-05-07 19:48:15 -07006845 }
Jasmine Chaf6074fe2021-08-17 13:44:31 +08006846
6847 // If recommended duration is defined, replace temporary mute duration to avoid
6848 // truncated notifications at beginning, which depends on duration of changing path in HAL.
6849 // Otherwise, temporary mute duration is conservatively set to 4 times the reported latency.
6850 uint32_t tempRecommendedMuteDuration = outputDesc->getRecommendedMuteDurationMs();
6851 uint32_t tempMuteDurationMs = tempRecommendedMuteDuration > 0 ?
6852 tempRecommendedMuteDuration : outputDesc->latency() * 4;
6853
François Gaffieaaac0fd2018-11-22 17:56:39 +01006854 for (const auto &activeVs : outputDesc->getActiveVolumeSources()) {
6855 // make sure that we do not start the temporary mute period too early in case of
6856 // delayed device change
6857 setVolumeSourceMute(activeVs, true, outputDesc, delayMs);
6858 setVolumeSourceMute(activeVs, false, outputDesc, delayMs + tempMuteDurationMs,
François Gaffiec005e562018-11-06 15:04:49 +01006859 devices.types());
Eric Laurent99401132014-05-07 19:48:15 -07006860 }
6861 }
6862
Eric Laurente552edb2014-03-10 17:42:56 -07006863 // wait for the PCM output buffers to empty before proceeding with the rest of the command
6864 if (muteWaitMs > delayMs) {
6865 muteWaitMs -= delayMs;
6866 usleep(muteWaitMs * 1000);
6867 return muteWaitMs;
6868 }
6869 return 0;
6870}
6871
François Gaffie11d30102018-11-02 16:09:09 +01006872uint32_t AudioPolicyManager::setOutputDevices(const sp<SwAudioOutputDescriptor>& outputDesc,
6873 const DeviceVector &devices,
6874 bool force,
6875 int delayMs,
6876 audio_patch_handle_t *patchHandle,
Francois Gaffie3523ab32021-06-22 13:24:34 +02006877 bool requiresMuteCheck, bool requiresVolumeCheck)
Eric Laurente552edb2014-03-10 17:42:56 -07006878{
François Gaffie11d30102018-11-02 16:09:09 +01006879 ALOGV("%s device %s delayMs %d", __func__, devices.toString().c_str(), delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07006880 uint32_t muteWaitMs;
6881
6882 if (outputDesc->isDuplicated()) {
François Gaffie11d30102018-11-02 16:09:09 +01006883 muteWaitMs = setOutputDevices(outputDesc->subOutput1(), devices, force, delayMs,
6884 nullptr /* patchHandle */, requiresMuteCheck);
6885 muteWaitMs += setOutputDevices(outputDesc->subOutput2(), devices, force, delayMs,
6886 nullptr /* patchHandle */, requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07006887 return muteWaitMs;
6888 }
Eric Laurente552edb2014-03-10 17:42:56 -07006889
6890 // filter devices according to output selected
Francois Gaffie716e1432019-01-14 16:58:59 +01006891 DeviceVector filteredDevices = outputDesc->filterSupportedDevices(devices);
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01006892 DeviceVector prevDevices = outputDesc->devices();
Francois Gaffie3523ab32021-06-22 13:24:34 +02006893 DeviceVector availPrevDevices = mAvailableOutputDevices.filter(prevDevices);
Eric Laurente552edb2014-03-10 17:42:56 -07006894
François Gaffie11d30102018-11-02 16:09:09 +01006895 ALOGV("setOutputDevices() prevDevice %s", prevDevices.toString().c_str());
6896
6897 if (!filteredDevices.isEmpty()) {
6898 outputDesc->setDevices(filteredDevices);
Eric Laurente552edb2014-03-10 17:42:56 -07006899 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00006900
6901 // if the outputs are not materially active, there is no need to mute.
6902 if (requiresMuteCheck) {
François Gaffiec005e562018-11-06 15:04:49 +01006903 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevices, delayMs);
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00006904 } else {
6905 ALOGV("%s: suppressing checkDeviceMuteStrategies", __func__);
6906 muteWaitMs = 0;
6907 }
Eric Laurente552edb2014-03-10 17:42:56 -07006908
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02006909 bool outputRouted = outputDesc->isRouted();
6910
Eric Laurent79ea9582020-06-11 18:49:24 -07006911 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
6912 // output profile or if new device is not supported AND previous device(s) is(are) still
6913 // available (otherwise reset device must be done on the output)
Francois Gaffie3523ab32021-06-22 13:24:34 +02006914 if (!devices.isEmpty() && filteredDevices.isEmpty() && !availPrevDevices.empty()) {
Eric Laurent79ea9582020-06-11 18:49:24 -07006915 ALOGV("%s: unsupported device %s for output", __func__, devices.toString().c_str());
6916 // restore previous device after evaluating strategy mute state
6917 outputDesc->setDevices(prevDevices);
6918 return muteWaitMs;
6919 }
6920
Eric Laurente552edb2014-03-10 17:42:56 -07006921 // Do not change the routing if:
Eric Laurentb80a2a82014-10-27 16:07:59 -07006922 // the requested device is AUDIO_DEVICE_NONE
6923 // OR the requested device is the same as current device
6924 // AND force is not specified
6925 // AND the output is connected by a valid audio patch.
François Gaffie11d30102018-11-02 16:09:09 +01006926 // Doing this check here allows the caller to call setOutputDevices() without conditions
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02006927 if ((filteredDevices.isEmpty() || filteredDevices == prevDevices) && !force && outputRouted) {
François Gaffie11d30102018-11-02 16:09:09 +01006928 ALOGV("%s setting same device %s or null device, force=%d, patch handle=%d", __func__,
6929 filteredDevices.toString().c_str(), force, outputDesc->getPatchHandle());
Francois Gaffie3523ab32021-06-22 13:24:34 +02006930 if (requiresVolumeCheck && !filteredDevices.isEmpty()) {
6931 ALOGV("%s setting same device on routed output, force apply volumes", __func__);
6932 applyStreamVolumes(outputDesc, filteredDevices.types(), delayMs, true /*force*/);
6933 }
Eric Laurente552edb2014-03-10 17:42:56 -07006934 return muteWaitMs;
6935 }
6936
François Gaffie11d30102018-11-02 16:09:09 +01006937 ALOGV("%s changing device to %s", __func__, filteredDevices.toString().c_str());
Eric Laurent1c333e22014-05-20 10:48:17 -07006938
Eric Laurente552edb2014-03-10 17:42:56 -07006939 // do the routing
Francois Gaffie3523ab32021-06-22 13:24:34 +02006940 if (filteredDevices.isEmpty() || mAvailableOutputDevices.filter(filteredDevices).empty()) {
Eric Laurentc75307b2015-03-17 15:29:32 -07006941 resetOutputDevice(outputDesc, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07006942 } else {
François Gaffie11d30102018-11-02 16:09:09 +01006943 PatchBuilder patchBuilder;
6944 patchBuilder.addSource(outputDesc);
6945 ALOG_ASSERT(filteredDevices.size() <= AUDIO_PATCH_PORTS_MAX, "Too many sink ports");
6946 for (const auto &filteredDevice : filteredDevices) {
6947 patchBuilder.addSink(filteredDevice);
Eric Laurentc40d9692016-04-13 19:14:13 -07006948 }
6949
Jasmine Cha7f82d1a2020-03-16 13:21:47 +08006950 // Add half reported latency to delayMs when muteWaitMs is null in order
6951 // to avoid disordered sequence of muting volume and changing devices.
6952 installPatch(__func__, patchHandle, outputDesc.get(), patchBuilder.patch(),
6953 muteWaitMs == 0 ? (delayMs + (outputDesc->latency() / 2)) : delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07006954 }
Eric Laurente552edb2014-03-10 17:42:56 -07006955
6956 // update stream volumes according to new device
François Gaffie11d30102018-11-02 16:09:09 +01006957 applyStreamVolumes(outputDesc, filteredDevices.types(), delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07006958
6959 return muteWaitMs;
6960}
6961
Eric Laurentc75307b2015-03-17 15:29:32 -07006962status_t AudioPolicyManager::resetOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurent6a94d692014-05-20 11:18:06 -07006963 int delayMs,
6964 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07006965{
Eric Laurent6a94d692014-05-20 11:18:06 -07006966 ssize_t index;
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02006967 if (patchHandle == nullptr && !outputDesc->isRouted()) {
6968 return INVALID_OPERATION;
6969 }
Eric Laurent6a94d692014-05-20 11:18:06 -07006970 if (patchHandle) {
6971 index = mAudioPatches.indexOfKey(*patchHandle);
6972 } else {
Jean-Michel Triviff155c62016-02-26 12:07:16 -08006973 index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07006974 }
6975 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07006976 return INVALID_OPERATION;
6977 }
Eric Laurent6a94d692014-05-20 11:18:06 -07006978 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006979 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07006980 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07006981 outputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
François Gaffieafd4cea2019-11-18 15:50:22 +01006982 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07006983 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07006984 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07006985 return status;
6986}
6987
6988status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
François Gaffie11d30102018-11-02 16:09:09 +01006989 const sp<DeviceDescriptor> &device,
Eric Laurent6a94d692014-05-20 11:18:06 -07006990 bool force,
6991 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07006992{
6993 status_t status = NO_ERROR;
6994
Eric Laurent1f2f2232014-06-02 12:01:23 -07006995 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
François Gaffie11d30102018-11-02 16:09:09 +01006996 if ((device != nullptr) && ((device != inputDesc->getDevice()) || force)) {
6997 inputDesc->setDevice(device);
Eric Laurent1c333e22014-05-20 10:48:17 -07006998
François Gaffie11d30102018-11-02 16:09:09 +01006999 if (mAvailableInputDevices.contains(device)) {
Mikhail Naganovdc769682018-05-04 15:34:08 -07007000 PatchBuilder patchBuilder;
7001 patchBuilder.addSink(inputDesc,
Eric Laurentdaf92cc2014-07-22 15:36:10 -07007002 // AUDIO_SOURCE_HOTWORD is for internal use only:
7003 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
Mikhail Naganovdc769682018-05-04 15:34:08 -07007004 [inputDesc](const PatchBuilder::mix_usecase_t& usecase) {
7005 auto result = usecase;
7006 if (result.source == AUDIO_SOURCE_HOTWORD && !inputDesc->isSoundTrigger()) {
7007 result.source = AUDIO_SOURCE_VOICE_RECOGNITION;
7008 }
7009 return result; }).
Eric Laurent1c333e22014-05-20 10:48:17 -07007010 //only one input device for now
François Gaffie11d30102018-11-02 16:09:09 +01007011 addSource(device);
Mikhail Naganovdc769682018-05-04 15:34:08 -07007012 status = installPatch(__func__, patchHandle, inputDesc.get(), patchBuilder.patch(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07007013 }
7014 }
7015 return status;
7016}
7017
Eric Laurent6a94d692014-05-20 11:18:06 -07007018status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
7019 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07007020{
Eric Laurent1f2f2232014-06-02 12:01:23 -07007021 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07007022 ssize_t index;
7023 if (patchHandle) {
7024 index = mAudioPatches.indexOfKey(*patchHandle);
7025 } else {
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08007026 index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007027 }
7028 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07007029 return INVALID_OPERATION;
7030 }
Eric Laurent6a94d692014-05-20 11:18:06 -07007031 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007032 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07007033 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07007034 inputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
François Gaffieafd4cea2019-11-18 15:50:22 +01007035 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007036 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07007037 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07007038 return status;
7039}
7040
François Gaffie11d30102018-11-02 16:09:09 +01007041sp<IOProfile> AudioPolicyManager::getInputProfile(const sp<DeviceDescriptor> &device,
François Gaffie53615e22015-03-19 09:24:12 +01007042 uint32_t& samplingRate,
Andy Hungf129b032015-04-07 13:45:50 -07007043 audio_format_t& format,
7044 audio_channel_mask_t& channelMask,
François Gaffie53615e22015-03-19 09:24:12 +01007045 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07007046{
7047 // Choose an input profile based on the requested capture parameters: select the first available
7048 // profile supporting all requested parameters.
jiabin2fd710d2022-05-02 23:20:22 +00007049 // The flags can be ignored if it doesn't contain a much match flag.
Andy Hungf129b032015-04-07 13:45:50 -07007050 //
7051 // TODO: perhaps isCompatibleProfile should return a "matching" score so we can return
7052 // the best matching profile, not the first one.
Eric Laurente552edb2014-03-10 17:42:56 -07007053
jiabin2fd710d2022-05-02 23:20:22 +00007054 const audio_input_flags_t mustMatchFlag = AUDIO_INPUT_FLAG_MMAP_NOIRQ;
7055 const audio_input_flags_t oriFlags = flags;
Glenn Kasten730b9262018-03-29 15:01:26 -07007056
jiabin2fd710d2022-05-02 23:20:22 +00007057 for (;;) {
7058 sp<IOProfile> firstInexact = nullptr;
7059 uint32_t updatedSamplingRate = 0;
7060 audio_format_t updatedFormat = AUDIO_FORMAT_INVALID;
7061 audio_channel_mask_t updatedChannelMask = AUDIO_CHANNEL_INVALID;
7062 for (const auto& hwModule : mHwModules) {
7063 for (const auto& profile : hwModule->getInputProfiles()) {
7064 // profile->log();
7065 //updatedFormat = format;
7066 if (profile->isCompatibleProfile(DeviceVector(device), samplingRate,
7067 &samplingRate /*updatedSamplingRate*/,
7068 format,
7069 &format, /*updatedFormat*/
7070 channelMask,
7071 &channelMask /*updatedChannelMask*/,
7072 // FIXME ugly cast
7073 (audio_output_flags_t) flags,
7074 true /*exactMatchRequiredForInputFlags*/)) {
7075 return profile;
7076 }
7077 if (firstInexact == nullptr && profile->isCompatibleProfile(DeviceVector(device),
7078 samplingRate,
7079 &updatedSamplingRate,
7080 format,
7081 &updatedFormat,
7082 channelMask,
7083 &updatedChannelMask,
7084 // FIXME ugly cast
7085 (audio_output_flags_t) flags,
7086 false /*exactMatchRequiredForInputFlags*/)) {
7087 firstInexact = profile;
7088 }
7089 }
7090 }
7091
7092 if (firstInexact != nullptr) {
7093 samplingRate = updatedSamplingRate;
7094 format = updatedFormat;
7095 channelMask = updatedChannelMask;
7096 return firstInexact;
7097 } else if (flags & AUDIO_INPUT_FLAG_RAW) {
7098 flags = (audio_input_flags_t) (flags & ~AUDIO_INPUT_FLAG_RAW); // retry
7099 } else if ((flags & mustMatchFlag) == AUDIO_INPUT_FLAG_NONE &&
7100 flags != AUDIO_INPUT_FLAG_NONE && audio_is_linear_pcm(format)) {
7101 flags = AUDIO_INPUT_FLAG_NONE;
7102 } else { // fail
7103 ALOGW("%s could not find profile for device %s, sampling rate %u, format %#x, "
7104 "channel mask 0x%X, flags %#x", __func__, device->toString().c_str(),
7105 samplingRate, format, channelMask, oriFlags);
7106 break;
Eric Laurente552edb2014-03-10 17:42:56 -07007107 }
7108 }
jiabin2fd710d2022-05-02 23:20:22 +00007109
7110 return nullptr;
Eric Laurente552edb2014-03-10 17:42:56 -07007111}
7112
François Gaffieaaac0fd2018-11-22 17:56:39 +01007113float AudioPolicyManager::computeVolume(IVolumeCurves &curves,
7114 VolumeSource volumeSource,
François Gaffied1ab2bd2015-12-02 18:20:06 +01007115 int index,
jiabin9a3361e2019-10-01 09:38:30 -07007116 const DeviceTypeSet& deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07007117{
jiabin9a3361e2019-10-01 09:38:30 -07007118 float volumeDb = curves.volIndexToDb(Volume::getDeviceCategory(deviceTypes), index);
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07007119
7120 // handle the case of accessibility active while a ringtone is playing: if the ringtone is much
7121 // louder than the accessibility prompt, the prompt cannot be heard, thus masking the touch
7122 // exploration of the dialer UI. In this situation, bring the accessibility volume closer to
7123 // the ringtone volume
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007124 const auto callVolumeSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL, false);
7125 const auto ringVolumeSrc = toVolumeSource(AUDIO_STREAM_RING, false);
7126 const auto musicVolumeSrc = toVolumeSource(AUDIO_STREAM_MUSIC, false);
7127 const auto alarmVolumeSrc = toVolumeSource(AUDIO_STREAM_ALARM, false);
7128 const auto a11yVolumeSrc = toVolumeSource(AUDIO_STREAM_ACCESSIBILITY, false);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007129
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07007130 if (volumeSource == a11yVolumeSrc
François Gaffieaaac0fd2018-11-22 17:56:39 +01007131 && (AUDIO_MODE_RINGTONE == mEngine->getPhoneState()) &&
7132 mOutputs.isActive(ringVolumeSrc, 0)) {
7133 auto &ringCurves = getVolumeCurves(AUDIO_STREAM_RING);
jiabin9a3361e2019-10-01 09:38:30 -07007134 const float ringVolumeDb = computeVolume(ringCurves, ringVolumeSrc, index, deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007135 return ringVolumeDb - 4 > volumeDb ? ringVolumeDb - 4 : volumeDb;
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07007136 }
7137
Eric Laurentdcd4ab12018-06-29 17:45:13 -07007138 // in-call: always cap volume by voice volume + some low headroom
François Gaffieaaac0fd2018-11-22 17:56:39 +01007139 if ((volumeSource != callVolumeSrc && (isInCall() ||
7140 mOutputs.isActiveLocally(callVolumeSrc))) &&
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007141 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM, false) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01007142 volumeSource == ringVolumeSrc || volumeSource == musicVolumeSrc ||
7143 volumeSource == alarmVolumeSrc ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007144 volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION, false) ||
7145 volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false) ||
7146 volumeSource == toVolumeSource(AUDIO_STREAM_DTMF, false) ||
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07007147 volumeSource == a11yVolumeSrc)) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007148 auto &voiceCurves = getVolumeCurves(callVolumeSrc);
jiabin9a3361e2019-10-01 09:38:30 -07007149 int voiceVolumeIndex = voiceCurves.getVolumeIndex(deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007150 const float maxVoiceVolDb =
jiabin9a3361e2019-10-01 09:38:30 -07007151 computeVolume(voiceCurves, callVolumeSrc, voiceVolumeIndex, deviceTypes)
Eric Laurent7731b5a2018-04-06 15:47:22 -07007152 + IN_CALL_EARPIECE_HEADROOM_DB;
Abhijith Shastry329ddab2019-04-23 11:53:26 -07007153 // FIXME: Workaround for call screening applications until a proper audio mode is defined
7154 // to support this scenario : Exempt the RING stream from the audio cap if the audio was
7155 // programmatically muted.
7156 // VOICE_CALL stream has minVolumeIndex > 0 : Users cannot set the volume of voice calls to
7157 // 0. We don't want to cap volume when the system has programmatically muted the voice call
7158 // stream. See setVolumeCurveIndex() for more information.
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07007159 bool exemptFromCapping =
7160 ((volumeSource == ringVolumeSrc) || (volumeSource == a11yVolumeSrc))
7161 && (voiceVolumeIndex == 0);
Abhijith Shastry329ddab2019-04-23 11:53:26 -07007162 ALOGV_IF(exemptFromCapping, "%s volume source %d at vol=%f not capped", __func__,
7163 volumeSource, volumeDb);
7164 if ((volumeDb > maxVoiceVolDb) && !exemptFromCapping) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007165 ALOGV("%s volume source %d at vol=%f overriden by volume group %d at vol=%f", __func__,
7166 volumeSource, volumeDb, callVolumeSrc, maxVoiceVolDb);
7167 volumeDb = maxVoiceVolDb;
Jean-Michel Trivi719a9872017-08-05 13:51:35 -07007168 }
7169 }
Eric Laurente552edb2014-03-10 17:42:56 -07007170 // if a headset is connected, apply the following rules to ring tones and notifications
7171 // to avoid sound level bursts in user's ears:
Eric Laurent6af1c1d2016-04-14 11:20:44 -07007172 // - always attenuate notifications volume by 6dB
7173 // - attenuate ring tones volume by 6dB unless music is not playing and
7174 // speaker is part of the select devices
Eric Laurente552edb2014-03-10 17:42:56 -07007175 // - if music is playing, always limit the volume to current music volume,
7176 // with a minimum threshold at -36dB so that notification is always perceived.
jiabin9a3361e2019-10-01 09:38:30 -07007177 if (!Intersection(deviceTypes,
7178 {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP, AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES,
7179 AUDIO_DEVICE_OUT_WIRED_HEADSET, AUDIO_DEVICE_OUT_WIRED_HEADPHONE,
Eric Laurentc42df452020-08-07 10:51:53 -07007180 AUDIO_DEVICE_OUT_USB_HEADSET, AUDIO_DEVICE_OUT_HEARING_AID,
7181 AUDIO_DEVICE_OUT_BLE_HEADSET}).empty() &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01007182 ((volumeSource == alarmVolumeSrc ||
7183 volumeSource == ringVolumeSrc) ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007184 (volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION, false)) ||
7185 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM, false)) ||
7186 ((volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false)) &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01007187 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) &&
7188 curves.canBeMuted()) {
7189
Eric Laurente552edb2014-03-10 17:42:56 -07007190 // when the phone is ringing we must consider that music could have been paused just before
7191 // by the music application and behave as if music was active if the last music track was
7192 // just stopped
Eric Laurent3b73df72014-03-11 09:06:29 -07007193 if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY) ||
Eric Laurente552edb2014-03-10 17:42:56 -07007194 mLimitRingtoneVolume) {
François Gaffie43c73442018-11-08 08:21:55 +01007195 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
jiabin9a3361e2019-10-01 09:38:30 -07007196 DeviceTypeSet musicDevice =
François Gaffiec005e562018-11-06 15:04:49 +01007197 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
7198 nullptr, true /*fromCache*/).types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01007199 auto &musicCurves = getVolumeCurves(AUDIO_STREAM_MUSIC);
jiabin9a3361e2019-10-01 09:38:30 -07007200 float musicVolDb = computeVolume(musicCurves,
7201 musicVolumeSrc,
7202 musicCurves.getVolumeIndex(musicDevice),
7203 musicDevice);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007204 float minVolDb = (musicVolDb > SONIFICATION_HEADSET_VOLUME_MIN_DB) ?
7205 musicVolDb : SONIFICATION_HEADSET_VOLUME_MIN_DB;
7206 if (volumeDb > minVolDb) {
7207 volumeDb = minVolDb;
7208 ALOGV("computeVolume limiting volume to %f musicVol %f", minVolDb, musicVolDb);
Eric Laurente552edb2014-03-10 17:42:56 -07007209 }
Eric Laurent7b6385c2021-05-12 17:55:36 +02007210 if (Volume::getDeviceForVolume(deviceTypes) != AUDIO_DEVICE_OUT_SPEAKER
7211 && !Intersection(deviceTypes, {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP,
7212 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES}).empty()) {
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07007213 // on A2DP, also ensure notification volume is not too low compared to media when
7214 // intended to be played
François Gaffie43c73442018-11-08 08:21:55 +01007215 if ((volumeDb > -96.0f) &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01007216 (musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB > volumeDb)) {
jiabin9a3361e2019-10-01 09:38:30 -07007217 ALOGV("%s increasing volume for volume source=%d device=%s from %f to %f",
7218 __func__, volumeSource, dumpDeviceTypes(deviceTypes).c_str(), volumeDb,
François Gaffieaaac0fd2018-11-22 17:56:39 +01007219 musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB);
7220 volumeDb = musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB;
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07007221 }
7222 }
jiabin9a3361e2019-10-01 09:38:30 -07007223 } else if ((Volume::getDeviceForVolume(deviceTypes) != AUDIO_DEVICE_OUT_SPEAKER) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01007224 (!(volumeSource == alarmVolumeSrc || volumeSource == ringVolumeSrc))) {
François Gaffie43c73442018-11-08 08:21:55 +01007225 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07007226 }
7227 }
7228
François Gaffie43c73442018-11-08 08:21:55 +01007229 return volumeDb;
Eric Laurente552edb2014-03-10 17:42:56 -07007230}
7231
Eric Laurent3839bc02018-07-10 18:33:34 -07007232int AudioPolicyManager::rescaleVolumeIndex(int srcIndex,
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01007233 VolumeSource fromVolumeSource,
7234 VolumeSource toVolumeSource)
Eric Laurent3839bc02018-07-10 18:33:34 -07007235{
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01007236 if (fromVolumeSource == toVolumeSource) {
Eric Laurent3839bc02018-07-10 18:33:34 -07007237 return srcIndex;
7238 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01007239 auto &srcCurves = getVolumeCurves(fromVolumeSource);
7240 auto &dstCurves = getVolumeCurves(toVolumeSource);
Eric Laurentf5aa58d2019-02-22 18:20:11 -08007241 float minSrc = (float)srcCurves.getVolumeIndexMin();
7242 float maxSrc = (float)srcCurves.getVolumeIndexMax();
7243 float minDst = (float)dstCurves.getVolumeIndexMin();
7244 float maxDst = (float)dstCurves.getVolumeIndexMax();
Eric Laurent3839bc02018-07-10 18:33:34 -07007245
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08007246 // preserve mute request or correct range
7247 if (srcIndex < minSrc) {
7248 if (srcIndex == 0) {
7249 return 0;
7250 }
7251 srcIndex = minSrc;
7252 } else if (srcIndex > maxSrc) {
7253 srcIndex = maxSrc;
7254 }
Eric Laurent3839bc02018-07-10 18:33:34 -07007255 return (int)(minDst + ((srcIndex - minSrc) * (maxDst - minDst)) / (maxSrc - minSrc));
7256}
7257
François Gaffieaaac0fd2018-11-22 17:56:39 +01007258status_t AudioPolicyManager::checkAndSetVolume(IVolumeCurves &curves,
7259 VolumeSource volumeSource,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08007260 int index,
7261 const sp<AudioOutputDescriptor>& outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07007262 DeviceTypeSet deviceTypes,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08007263 int delayMs,
7264 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07007265{
François Gaffieaaac0fd2018-11-22 17:56:39 +01007266 // do not change actual attributes volume if the attributes is muted
7267 if (outputDesc->isMuted(volumeSource)) {
7268 ALOGVV("%s: volume source %d muted count %d active=%d", __func__, volumeSource,
7269 outputDesc->getMuteCount(volumeSource), outputDesc->isActive(volumeSource));
Eric Laurente552edb2014-03-10 17:42:56 -07007270 return NO_ERROR;
7271 }
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007272 VolumeSource callVolSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL, false);
7273 VolumeSource btScoVolSrc = toVolumeSource(AUDIO_STREAM_BLUETOOTH_SCO, false);
7274 bool isVoiceVolSrc = (volumeSource != VOLUME_SOURCE_NONE) && (callVolSrc == volumeSource);
7275 bool isBtScoVolSrc = (volumeSource != VOLUME_SOURCE_NONE) && (btScoVolSrc == volumeSource);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007276
Eric Laurent2517af32020-11-25 15:31:27 +01007277 bool isScoRequested = isScoRequestedForComm();
Eric Laurent1a8b45f2022-04-13 16:01:47 +02007278 bool isHAUsed = isHearingAidUsedForComm();
7279
Eric Laurente552edb2014-03-10 17:42:56 -07007280 // do not change in call volume if bluetooth is connected and vice versa
François Gaffieaaac0fd2018-11-22 17:56:39 +01007281 // if sco and call follow same curves, bypass forceUseForComm
7282 if ((callVolSrc != btScoVolSrc) &&
Eric Laurent2517af32020-11-25 15:31:27 +01007283 ((isVoiceVolSrc && isScoRequested) ||
Eric Laurent1a8b45f2022-04-13 16:01:47 +02007284 (isBtScoVolSrc && !(isScoRequested || isHAUsed)))) {
Eric Laurent2517af32020-11-25 15:31:27 +01007285 ALOGV("%s cannot set volume group %d volume when is%srequested for comm", __func__,
Eric Laurent1a8b45f2022-04-13 16:01:47 +02007286 volumeSource, isScoRequested ? " " : " not ");
Eric Laurent571ef962020-07-24 11:43:48 -07007287 // Do not return an error here as AudioService will always set both voice call
7288 // and bluetooth SCO volumes due to stream aliasing.
7289 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07007290 }
jiabin9a3361e2019-10-01 09:38:30 -07007291 if (deviceTypes.empty()) {
7292 deviceTypes = outputDesc->devices().types();
Eric Laurentc75307b2015-03-17 15:29:32 -07007293 }
Eric Laurent275e8e92014-11-30 15:14:47 -08007294
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00007295 if (curves.getVolumeIndexMin() < 0 || curves.getVolumeIndexMax() < 0) {
7296 ALOGE("invalid volume index range");
7297 return BAD_VALUE;
7298 }
7299
jiabin9a3361e2019-10-01 09:38:30 -07007300 float volumeDb = computeVolume(curves, volumeSource, index, deviceTypes);
7301 if (outputDesc->isFixedVolume(deviceTypes) ||
Eric Laurent9698a4c2020-10-12 17:10:23 -07007302 // Force VoIP volume to max for bluetooth SCO device except if muted
7303 (index != 0 && (isVoiceVolSrc || isBtScoVolSrc) &&
jiabin9a3361e2019-10-01 09:38:30 -07007304 isSingleDeviceType(deviceTypes, audio_is_bluetooth_out_sco_device))) {
Eric Laurentffbc80f2015-03-18 18:30:19 -07007305 volumeDb = 0.0f;
Eric Laurent275e8e92014-11-30 15:14:47 -08007306 }
Francois Gaffie593634d2021-06-22 13:31:31 +02007307 const bool muted = (index == 0) && (volumeDb != 0.0f);
jiabin9a3361e2019-10-01 09:38:30 -07007308 outputDesc->setVolume(
Francois Gaffie593634d2021-06-22 13:31:31 +02007309 volumeDb, muted, volumeSource, curves.getStreamTypes(), deviceTypes, delayMs, force);
Eric Laurentc75307b2015-03-17 15:29:32 -07007310
Eric Laurente8f2c0f2021-08-17 11:17:19 +02007311 if (outputDesc == mPrimaryOutput && (isVoiceVolSrc || isBtScoVolSrc)) {
Eric Laurente552edb2014-03-10 17:42:56 -07007312 float voiceVolume;
Eric Laurentfad001d2019-06-11 19:17:57 -07007313 // 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 +01007314 if (isVoiceVolSrc) {
7315 voiceVolume = (float)index/(float)curves.getVolumeIndexMax();
Eric Laurente552edb2014-03-10 17:42:56 -07007316 } else {
Eric Laurentfad001d2019-06-11 19:17:57 -07007317 voiceVolume = index == 0 ? 0.0 : 1.0;
Eric Laurente552edb2014-03-10 17:42:56 -07007318 }
Eric Laurent18fba842016-03-31 14:41:26 -07007319 if (voiceVolume != mLastVoiceVolume) {
Eric Laurente552edb2014-03-10 17:42:56 -07007320 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
7321 mLastVoiceVolume = voiceVolume;
7322 }
7323 }
Eric Laurente552edb2014-03-10 17:42:56 -07007324 return NO_ERROR;
7325}
7326
Eric Laurentc75307b2015-03-17 15:29:32 -07007327void AudioPolicyManager::applyStreamVolumes(const sp<AudioOutputDescriptor>& outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07007328 const DeviceTypeSet& deviceTypes,
7329 int delayMs,
7330 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07007331{
jiabincd510522020-01-22 09:40:55 -08007332 ALOGVV("applyStreamVolumes() for device %s", dumpDeviceTypes(deviceTypes).c_str());
François Gaffieaaac0fd2018-11-22 17:56:39 +01007333 for (const auto &volumeGroup : mEngine->getVolumeGroups()) {
7334 auto &curves = getVolumeCurves(toVolumeSource(volumeGroup));
7335 checkAndSetVolume(curves, toVolumeSource(volumeGroup),
jiabin9a3361e2019-10-01 09:38:30 -07007336 curves.getVolumeIndex(deviceTypes),
7337 outputDesc, deviceTypes, delayMs, force);
Eric Laurente552edb2014-03-10 17:42:56 -07007338 }
7339}
7340
François Gaffiec005e562018-11-06 15:04:49 +01007341void AudioPolicyManager::setStrategyMute(product_strategy_t strategy,
7342 bool on,
7343 const sp<AudioOutputDescriptor>& outputDesc,
7344 int delayMs,
jiabin9a3361e2019-10-01 09:38:30 -07007345 DeviceTypeSet deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07007346{
François Gaffieaaac0fd2018-11-22 17:56:39 +01007347 std::vector<VolumeSource> sourcesToMute;
7348 for (auto attributes: mEngine->getAllAttributesForProductStrategy(strategy)) {
7349 ALOGVV("%s() attributes %s, mute %d, output ID %d", __func__,
7350 toString(attributes).c_str(), on, outputDesc->getId());
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007351 VolumeSource source = toVolumeSource(attributes, false);
7352 if ((source != VOLUME_SOURCE_NONE) &&
7353 (std::find(begin(sourcesToMute), end(sourcesToMute), source)
7354 == end(sourcesToMute))) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007355 sourcesToMute.push_back(source);
7356 }
Eric Laurente552edb2014-03-10 17:42:56 -07007357 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01007358 for (auto source : sourcesToMute) {
jiabin9a3361e2019-10-01 09:38:30 -07007359 setVolumeSourceMute(source, on, outputDesc, delayMs, deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007360 }
7361
Eric Laurente552edb2014-03-10 17:42:56 -07007362}
7363
François Gaffieaaac0fd2018-11-22 17:56:39 +01007364void AudioPolicyManager::setVolumeSourceMute(VolumeSource volumeSource,
7365 bool on,
7366 const sp<AudioOutputDescriptor>& outputDesc,
7367 int delayMs,
jiabin9a3361e2019-10-01 09:38:30 -07007368 DeviceTypeSet deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07007369{
jiabin9a3361e2019-10-01 09:38:30 -07007370 if (deviceTypes.empty()) {
7371 deviceTypes = outputDesc->devices().types();
Eric Laurente552edb2014-03-10 17:42:56 -07007372 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01007373 auto &curves = getVolumeCurves(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07007374 if (on) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007375 if (!outputDesc->isMuted(volumeSource)) {
Eric Laurentf5aa58d2019-02-22 18:20:11 -08007376 if (curves.canBeMuted() &&
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007377 (volumeSource != toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01007378 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) ==
7379 AUDIO_POLICY_FORCE_NONE))) {
jiabin9a3361e2019-10-01 09:38:30 -07007380 checkAndSetVolume(curves, volumeSource, 0, outputDesc, deviceTypes, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07007381 }
7382 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01007383 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not
7384 // ignored
7385 outputDesc->incMuteCount(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07007386 } else {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007387 if (!outputDesc->isMuted(volumeSource)) {
7388 ALOGV("%s unmuting non muted attributes!", __func__);
Eric Laurente552edb2014-03-10 17:42:56 -07007389 return;
7390 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01007391 if (outputDesc->decMuteCount(volumeSource) == 0) {
7392 checkAndSetVolume(curves, volumeSource,
jiabin9a3361e2019-10-01 09:38:30 -07007393 curves.getVolumeIndex(deviceTypes),
Eric Laurentc75307b2015-03-17 15:29:32 -07007394 outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07007395 deviceTypes,
Eric Laurente552edb2014-03-10 17:42:56 -07007396 delayMs);
7397 }
7398 }
7399}
7400
François Gaffie53615e22015-03-19 09:24:12 +01007401bool AudioPolicyManager::isValidAttributes(const audio_attributes_t *paa)
7402{
François Gaffiec005e562018-11-06 15:04:49 +01007403 // has flags that map to a stream type?
Eric Laurente83b55d2014-11-14 10:06:21 -08007404 if ((paa->flags & (AUDIO_FLAG_AUDIBILITY_ENFORCED | AUDIO_FLAG_SCO | AUDIO_FLAG_BEACON)) != 0) {
7405 return true;
7406 }
7407
7408 // has known usage?
7409 switch (paa->usage) {
7410 case AUDIO_USAGE_UNKNOWN:
7411 case AUDIO_USAGE_MEDIA:
7412 case AUDIO_USAGE_VOICE_COMMUNICATION:
7413 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
7414 case AUDIO_USAGE_ALARM:
7415 case AUDIO_USAGE_NOTIFICATION:
7416 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
7417 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
7418 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
7419 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
7420 case AUDIO_USAGE_NOTIFICATION_EVENT:
7421 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
7422 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
7423 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
7424 case AUDIO_USAGE_GAME:
Eric Laurent275e8e92014-11-30 15:14:47 -08007425 case AUDIO_USAGE_VIRTUAL_SOURCE:
Jean-Michel Trivi36867762016-12-29 12:03:28 -08007426 case AUDIO_USAGE_ASSISTANT:
Eric Laurent21777f82019-12-06 18:12:06 -08007427 case AUDIO_USAGE_CALL_ASSISTANT:
Hayden Gomes524159d2019-12-23 14:41:47 -08007428 case AUDIO_USAGE_EMERGENCY:
7429 case AUDIO_USAGE_SAFETY:
7430 case AUDIO_USAGE_VEHICLE_STATUS:
7431 case AUDIO_USAGE_ANNOUNCEMENT:
Eric Laurente83b55d2014-11-14 10:06:21 -08007432 break;
7433 default:
7434 return false;
7435 }
7436 return true;
7437}
7438
François Gaffie2110e042015-03-24 08:41:51 +01007439audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
7440{
7441 return mEngine->getForceUse(usage);
7442}
7443
Eric Laurent96d1dda2022-03-14 17:14:19 +01007444bool AudioPolicyManager::isInCall() const {
François Gaffie2110e042015-03-24 08:41:51 +01007445 return isStateInCall(mEngine->getPhoneState());
7446}
7447
Eric Laurent96d1dda2022-03-14 17:14:19 +01007448bool AudioPolicyManager::isStateInCall(int state) const {
François Gaffie2110e042015-03-24 08:41:51 +01007449 return is_state_in_call(state);
7450}
7451
Eric Laurent74b71512019-11-06 17:21:57 -08007452bool AudioPolicyManager::isCallAudioAccessible()
7453{
7454 audio_mode_t mode = mEngine->getPhoneState();
7455 return (mode == AUDIO_MODE_IN_CALL)
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01007456 || (mode == AUDIO_MODE_CALL_SCREEN)
7457 || (mode == AUDIO_MODE_CALL_REDIRECT);
Eric Laurent74b71512019-11-06 17:21:57 -08007458}
7459
Eric Laurentd60560a2015-04-10 11:31:20 -07007460void AudioPolicyManager::cleanUpForDevice(const sp<DeviceDescriptor>& deviceDesc)
7461{
7462 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07007463 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02007464 if (sourceDesc->isConnected() && (sourceDesc->srcDevice()->equals(deviceDesc) ||
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02007465 sourceDesc->sinkDevice()->equals(deviceDesc))
7466 && !isCallRxAudioSource(sourceDesc)) {
Francois Gaffiea0e5c992020-09-29 16:05:07 +02007467 disconnectAudioSource(sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07007468 }
7469 }
7470
7471 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
7472 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
7473 bool release = false;
7474 for (size_t j = 0; j < patchDesc->mPatch.num_sources && !release; j++) {
7475 const struct audio_port_config *source = &patchDesc->mPatch.sources[j];
7476 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
7477 source->ext.device.type == deviceDesc->type()) {
7478 release = true;
7479 }
7480 }
Francois Gaffiea0e5c992020-09-29 16:05:07 +02007481 const char *address = deviceDesc->address().c_str();
Eric Laurentd60560a2015-04-10 11:31:20 -07007482 for (size_t j = 0; j < patchDesc->mPatch.num_sinks && !release; j++) {
7483 const struct audio_port_config *sink = &patchDesc->mPatch.sinks[j];
7484 if (sink->type == AUDIO_PORT_TYPE_DEVICE &&
Francois Gaffiea0e5c992020-09-29 16:05:07 +02007485 sink->ext.device.type == deviceDesc->type() &&
7486 (strnlen(address, AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0
7487 || strncmp(sink->ext.device.address, address,
7488 AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0)) {
Eric Laurentd60560a2015-04-10 11:31:20 -07007489 release = true;
7490 }
7491 }
7492 if (release) {
François Gaffieafd4cea2019-11-18 15:50:22 +01007493 ALOGV("%s releasing patch %u", __FUNCTION__, patchDesc->getHandle());
7494 releaseAudioPatch(patchDesc->getHandle(), patchDesc->getUid());
Eric Laurentd60560a2015-04-10 11:31:20 -07007495 }
7496 }
Francois Gaffie716e1432019-01-14 16:58:59 +01007497
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01007498 mInputs.clearSessionRoutesForDevice(deviceDesc);
7499
Francois Gaffie716e1432019-01-14 16:58:59 +01007500 mHwModules.cleanUpForDevice(deviceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07007501}
7502
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007503void AudioPolicyManager::modifySurroundFormats(
7504 const sp<DeviceDescriptor>& devDesc, FormatVector *formatsPtr) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007505 std::unordered_set<audio_format_t> enforcedSurround(
7506 devDesc->encodedFormats().begin(), devDesc->encodedFormats().end());
Mikhail Naganov100f0122018-11-29 11:22:16 -08007507 std::unordered_set<audio_format_t> allSurround; // A flat set of all known surround formats
7508 for (const auto& pair : mConfig.getSurroundFormats()) {
7509 allSurround.insert(pair.first);
7510 for (const auto& subformat : pair.second) allSurround.insert(subformat);
7511 }
Phil Burk09bc4612016-02-24 15:58:15 -08007512
7513 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
7514 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Phil Burk0709b0a2016-03-31 12:54:57 -07007515 ALOGD("%s: forced use = %d", __FUNCTION__, forceUse);
Mikhail Naganov100f0122018-11-29 11:22:16 -08007516 // This is the resulting set of formats depending on the surround mode:
7517 // 'all surround' = allSurround
7518 // 'enforced surround' = enforcedSurround [may include IEC69137 which isn't raw surround fmt]
7519 // 'non-surround' = not in 'all surround' and not in 'enforced surround'
7520 // 'manual surround' = mManualSurroundFormats
7521 // AUTO: formats v 'enforced surround'
7522 // ALWAYS: formats v 'all surround' v 'enforced surround'
7523 // NEVER: formats ^ 'non-surround'
7524 // MANUAL: formats ^ ('non-surround' v 'manual surround' v (IEC69137 ^ 'enforced surround'))
Phil Burk09bc4612016-02-24 15:58:15 -08007525
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007526 std::unordered_set<audio_format_t> formatSet;
7527 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL
7528 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08007529 // formatSet is (formats ^ 'non-surround')
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007530 for (auto formatIter = formatsPtr->begin(); formatIter != formatsPtr->end(); ++formatIter) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08007531 if (allSurround.count(*formatIter) == 0 && enforcedSurround.count(*formatIter) == 0) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007532 formatSet.insert(*formatIter);
7533 }
7534 }
7535 } else {
7536 formatSet.insert(formatsPtr->begin(), formatsPtr->end());
7537 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08007538 formatsPtr->clear(); // Re-filled from the formatSet at the end.
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007539
jiabin81772902018-04-02 17:52:27 -07007540 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08007541 formatSet.insert(mManualSurroundFormats.begin(), mManualSurroundFormats.end());
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007542 // Enable IEC61937 when in MANUAL mode if it's enforced for this device.
7543 if (enforcedSurround.count(AUDIO_FORMAT_IEC61937) != 0) {
7544 formatSet.insert(AUDIO_FORMAT_IEC61937);
Phil Burk09bc4612016-02-24 15:58:15 -08007545 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08007546 } else if (forceUse != AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) { // AUTO or ALWAYS
7547 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS) {
7548 formatSet.insert(allSurround.begin(), allSurround.end());
Phil Burk07ac1142016-03-25 13:39:29 -07007549 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08007550 formatSet.insert(enforcedSurround.begin(), enforcedSurround.end());
Phil Burk09bc4612016-02-24 15:58:15 -08007551 }
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007552 for (const auto& format : formatSet) {
jiabin06e4bab2019-07-29 10:13:34 -07007553 formatsPtr->push_back(format);
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007554 }
Phil Burk0709b0a2016-03-31 12:54:57 -07007555}
7556
jiabin06e4bab2019-07-29 10:13:34 -07007557void AudioPolicyManager::modifySurroundChannelMasks(ChannelMaskSet *channelMasksPtr) {
7558 ChannelMaskSet &channelMasks = *channelMasksPtr;
Phil Burk0709b0a2016-03-31 12:54:57 -07007559 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
7560 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
7561
7562 // If NEVER, then remove support for channelMasks > stereo.
7563 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
jiabin06e4bab2019-07-29 10:13:34 -07007564 for (auto it = channelMasks.begin(); it != channelMasks.end();) {
7565 audio_channel_mask_t channelMask = *it;
Phil Burk0709b0a2016-03-31 12:54:57 -07007566 if (channelMask & ~AUDIO_CHANNEL_OUT_STEREO) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01007567 ALOGV("%s: force NEVER, so remove channelMask 0x%08x", __FUNCTION__, channelMask);
jiabin06e4bab2019-07-29 10:13:34 -07007568 it = channelMasks.erase(it);
Phil Burk0709b0a2016-03-31 12:54:57 -07007569 } else {
jiabin06e4bab2019-07-29 10:13:34 -07007570 ++it;
Phil Burk0709b0a2016-03-31 12:54:57 -07007571 }
7572 }
jiabin81772902018-04-02 17:52:27 -07007573 // If ALWAYS or MANUAL, then make sure we at least support 5.1
7574 } else if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS
7575 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Phil Burk0709b0a2016-03-31 12:54:57 -07007576 bool supports5dot1 = false;
7577 // Are there any channel masks that can be considered "surround"?
Mikhail Naganovcf84e592017-12-07 11:25:11 -08007578 for (audio_channel_mask_t channelMask : channelMasks) {
Phil Burk0709b0a2016-03-31 12:54:57 -07007579 if ((channelMask & AUDIO_CHANNEL_OUT_5POINT1) == AUDIO_CHANNEL_OUT_5POINT1) {
7580 supports5dot1 = true;
7581 break;
7582 }
7583 }
7584 // If not then add 5.1 support.
7585 if (!supports5dot1) {
jiabin06e4bab2019-07-29 10:13:34 -07007586 channelMasks.insert(AUDIO_CHANNEL_OUT_5POINT1);
Eric Laurentfecbceb2021-02-09 14:46:43 +01007587 ALOGV("%s: force MANUAL or ALWAYS, so adding channelMask for 5.1 surround", __func__);
Phil Burk0709b0a2016-03-31 12:54:57 -07007588 }
Phil Burk09bc4612016-02-24 15:58:15 -08007589 }
7590}
7591
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007592void AudioPolicyManager::updateAudioProfiles(const sp<DeviceDescriptor>& devDesc,
Phil Burk00eeb322016-03-31 12:41:00 -07007593 audio_io_handle_t ioHandle,
François Gaffie112b0af2015-11-19 16:13:25 +01007594 AudioProfileVector &profiles)
7595{
7596 String8 reply;
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007597 audio_devices_t device = devDesc->type();
Phil Burk0709b0a2016-03-31 12:54:57 -07007598
François Gaffie112b0af2015-11-19 16:13:25 +01007599 // Format MUST be checked first to update the list of AudioProfile
7600 if (profiles.hasDynamicFormat()) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07007601 reply = mpClientInterface->getParameters(
7602 ioHandle, String8(AudioParameter::keyStreamSupportedFormats));
jiabin81772902018-04-02 17:52:27 -07007603 ALOGV("%s: supported formats %d, %s", __FUNCTION__, ioHandle, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08007604 AudioParameter repliedParameters(reply);
7605 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07007606 String8(AudioParameter::keyStreamSupportedFormats), reply) != NO_ERROR) {
François Gaffie112b0af2015-11-19 16:13:25 +01007607 ALOGE("%s: failed to retrieve format, bailing out", __FUNCTION__);
7608 return;
7609 }
Phil Burk09bc4612016-02-24 15:58:15 -08007610 FormatVector formats = formatsFromString(reply.string());
Kriti Dangef6be8f2020-11-05 11:58:19 +01007611 mReportedFormatsMap[devDesc] = formats;
Mikhail Naganov100f0122018-11-29 11:22:16 -08007612 if (device == AUDIO_DEVICE_OUT_HDMI
7613 || isDeviceOfModule(devDesc, AUDIO_HARDWARE_MODULE_ID_MSD)) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007614 modifySurroundFormats(devDesc, &formats);
Phil Burk00eeb322016-03-31 12:41:00 -07007615 }
jiabin3e277cc2019-09-10 14:27:34 -07007616 addProfilesForFormats(profiles, formats);
François Gaffie112b0af2015-11-19 16:13:25 +01007617 }
François Gaffie112b0af2015-11-19 16:13:25 +01007618
Mikhail Naganovcf84e592017-12-07 11:25:11 -08007619 for (audio_format_t format : profiles.getSupportedFormats()) {
jiabin06e4bab2019-07-29 10:13:34 -07007620 ChannelMaskSet channelMasks;
7621 SampleRateSet samplingRates;
François Gaffie112b0af2015-11-19 16:13:25 +01007622 AudioParameter requestedParameters;
Mikhail Naganov388360c2016-10-17 17:09:41 -07007623 requestedParameters.addInt(String8(AudioParameter::keyFormat), format);
François Gaffie112b0af2015-11-19 16:13:25 +01007624
7625 if (profiles.hasDynamicRateFor(format)) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07007626 reply = mpClientInterface->getParameters(
7627 ioHandle,
7628 requestedParameters.toString() + ";" +
7629 AudioParameter::keyStreamSupportedSamplingRates);
François Gaffie112b0af2015-11-19 16:13:25 +01007630 ALOGV("%s: supported sampling rates %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08007631 AudioParameter repliedParameters(reply);
7632 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07007633 String8(AudioParameter::keyStreamSupportedSamplingRates), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08007634 samplingRates = samplingRatesFromString(reply.string());
François Gaffie112b0af2015-11-19 16:13:25 +01007635 }
7636 }
7637 if (profiles.hasDynamicChannelsFor(format)) {
7638 reply = mpClientInterface->getParameters(ioHandle,
7639 requestedParameters.toString() + ";" +
Mikhail Naganov388360c2016-10-17 17:09:41 -07007640 AudioParameter::keyStreamSupportedChannels);
François Gaffie112b0af2015-11-19 16:13:25 +01007641 ALOGV("%s: supported channel masks %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08007642 AudioParameter repliedParameters(reply);
7643 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07007644 String8(AudioParameter::keyStreamSupportedChannels), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08007645 channelMasks = channelMasksFromString(reply.string());
Mikhail Naganov100f0122018-11-29 11:22:16 -08007646 if (device == AUDIO_DEVICE_OUT_HDMI
7647 || isDeviceOfModule(devDesc, AUDIO_HARDWARE_MODULE_ID_MSD)) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007648 modifySurroundChannelMasks(&channelMasks);
Phil Burk0709b0a2016-03-31 12:54:57 -07007649 }
François Gaffie112b0af2015-11-19 16:13:25 +01007650 }
7651 }
jiabin3e277cc2019-09-10 14:27:34 -07007652 addDynamicAudioProfileAndSort(
7653 profiles, new AudioProfile(format, channelMasks, samplingRates));
François Gaffie112b0af2015-11-19 16:13:25 +01007654 }
7655}
Eric Laurentd60560a2015-04-10 11:31:20 -07007656
Mikhail Naganovdc769682018-05-04 15:34:08 -07007657status_t AudioPolicyManager::installPatch(const char *caller,
7658 audio_patch_handle_t *patchHandle,
7659 AudioIODescriptorInterface *ioDescriptor,
7660 const struct audio_patch *patch,
7661 int delayMs)
7662{
7663 ssize_t index = mAudioPatches.indexOfKey(
7664 patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE ?
7665 *patchHandle : ioDescriptor->getPatchHandle());
7666 sp<AudioPatch> patchDesc;
7667 status_t status = installPatch(
7668 caller, index, patchHandle, patch, delayMs, mUidCached, &patchDesc);
7669 if (status == NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01007670 ioDescriptor->setPatchHandle(patchDesc->getHandle());
Mikhail Naganovdc769682018-05-04 15:34:08 -07007671 }
7672 return status;
7673}
7674
7675status_t AudioPolicyManager::installPatch(const char *caller,
7676 ssize_t index,
7677 audio_patch_handle_t *patchHandle,
7678 const struct audio_patch *patch,
7679 int delayMs,
7680 uid_t uid,
7681 sp<AudioPatch> *patchDescPtr)
7682{
7683 sp<AudioPatch> patchDesc;
7684 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
7685 if (index >= 0) {
7686 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007687 afPatchHandle = patchDesc->getAfHandle();
Mikhail Naganovdc769682018-05-04 15:34:08 -07007688 }
7689
7690 status_t status = mpClientInterface->createAudioPatch(patch, &afPatchHandle, delayMs);
7691 ALOGV("%s() AF::createAudioPatch returned %d patchHandle %d num_sources %d num_sinks %d",
7692 caller, status, afPatchHandle, patch->num_sources, patch->num_sinks);
7693 if (status == NO_ERROR) {
7694 if (index < 0) {
7695 patchDesc = new AudioPatch(patch, uid);
François Gaffieafd4cea2019-11-18 15:50:22 +01007696 addAudioPatch(patchDesc->getHandle(), patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07007697 } else {
7698 patchDesc->mPatch = *patch;
7699 }
François Gaffieafd4cea2019-11-18 15:50:22 +01007700 patchDesc->setAfHandle(afPatchHandle);
Mikhail Naganovdc769682018-05-04 15:34:08 -07007701 if (patchHandle) {
François Gaffieafd4cea2019-11-18 15:50:22 +01007702 *patchHandle = patchDesc->getHandle();
Mikhail Naganovdc769682018-05-04 15:34:08 -07007703 }
7704 nextAudioPortGeneration();
7705 mpClientInterface->onAudioPatchListUpdate();
7706 }
7707 if (patchDescPtr) *patchDescPtr = patchDesc;
7708 return status;
7709}
7710
jiabinbce0c1d2020-10-05 11:20:18 -07007711bool AudioPolicyManager::areAllActiveTracksRerouted(const sp<SwAudioOutputDescriptor>& output)
7712{
7713 const TrackClientVector activeClients = output->getActiveClients();
7714 if (activeClients.empty()) {
7715 return true;
7716 }
7717 ssize_t index = mAudioPatches.indexOfKey(output->getPatchHandle());
7718 if (index < 0) {
7719 ALOGE("%s, no audio patch found while there are active clients on output %d",
7720 __func__, output->getId());
7721 return false;
7722 }
7723 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
7724 DeviceVector routedDevices;
7725 for (int i = 0; i < patchDesc->mPatch.num_sinks; ++i) {
7726 sp<DeviceDescriptor> device = mAvailableOutputDevices.getDeviceFromId(
7727 patchDesc->mPatch.sinks[i].id);
7728 if (device == nullptr) {
7729 ALOGE("%s, no audio device found with id(%d)",
7730 __func__, patchDesc->mPatch.sinks[i].id);
7731 return false;
7732 }
7733 routedDevices.add(device);
7734 }
7735 for (const auto& client : activeClients) {
jiabin49256852022-03-09 11:21:35 -08007736 if (client->isInvalid()) {
7737 // No need to take care about invalidated clients.
7738 continue;
7739 }
jiabinbce0c1d2020-10-05 11:20:18 -07007740 sp<DeviceDescriptor> preferredDevice =
7741 mAvailableOutputDevices.getDeviceFromId(client->preferredDeviceId());
7742 if (mEngine->getOutputDevicesForAttributes(
7743 client->attributes(), preferredDevice, false) == routedDevices) {
7744 return false;
7745 }
7746 }
7747 return true;
7748}
7749
7750sp<SwAudioOutputDescriptor> AudioPolicyManager::openOutputWithProfileAndDevice(
Eric Laurentb4f42a92022-01-17 17:37:31 +01007751 const sp<IOProfile>& profile, const DeviceVector& devices,
7752 const audio_config_base_t *mixerConfig)
jiabinbce0c1d2020-10-05 11:20:18 -07007753{
7754 for (const auto& device : devices) {
7755 // TODO: This should be checking if the profile supports the device combo.
7756 if (!profile->supportsDevice(device)) {
7757 return nullptr;
7758 }
7759 }
7760 sp<SwAudioOutputDescriptor> desc = new SwAudioOutputDescriptor(profile, mpClientInterface);
7761 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentb4f42a92022-01-17 17:37:31 +01007762 status_t status = desc->open(nullptr /* halConfig */, mixerConfig, devices,
jiabinbce0c1d2020-10-05 11:20:18 -07007763 AUDIO_STREAM_DEFAULT, AUDIO_OUTPUT_FLAG_NONE, &output);
7764 if (status != NO_ERROR) {
7765 return nullptr;
7766 }
7767
7768 // Here is where the out_set_parameters() for card & device gets called
7769 sp<DeviceDescriptor> device = devices.getDeviceForOpening();
7770 const audio_devices_t deviceType = device->type();
7771 const String8 &address = String8(device->address().c_str());
7772 if (!address.isEmpty()) {
7773 char *param = audio_device_address_to_parameter(deviceType, address.c_str());
7774 mpClientInterface->setParameters(output, String8(param));
7775 free(param);
7776 }
7777 updateAudioProfiles(device, output, profile->getAudioProfiles());
7778 if (!profile->hasValidAudioProfile()) {
7779 ALOGW("%s() missing param", __func__);
7780 desc->close();
7781 return nullptr;
7782 } else if (profile->hasDynamicAudioProfile()) {
7783 desc->close();
7784 output = AUDIO_IO_HANDLE_NONE;
7785 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
7786 profile->pickAudioProfile(
7787 config.sample_rate, config.channel_mask, config.format);
7788 config.offload_info.sample_rate = config.sample_rate;
7789 config.offload_info.channel_mask = config.channel_mask;
7790 config.offload_info.format = config.format;
7791
Eric Laurentb4f42a92022-01-17 17:37:31 +01007792 status = desc->open(&config, mixerConfig, devices,
jiabinbce0c1d2020-10-05 11:20:18 -07007793 AUDIO_STREAM_DEFAULT, AUDIO_OUTPUT_FLAG_NONE, &output);
7794 if (status != NO_ERROR) {
7795 return nullptr;
7796 }
7797 }
7798
7799 addOutput(output, desc);
Eric Laurentb4f42a92022-01-17 17:37:31 +01007800
baek.kim -61c20122022-07-27 10:05:32 +00007801 sp<DeviceDescriptor> speaker = mAvailableOutputDevices.getDevice(
7802 AUDIO_DEVICE_OUT_SPEAKER, String8(""), AUDIO_FORMAT_DEFAULT);
7803
jiabinbce0c1d2020-10-05 11:20:18 -07007804 if (audio_is_remote_submix_device(deviceType) && address != "0") {
7805 sp<AudioPolicyMix> policyMix;
7806 if (mPolicyMixes.getAudioPolicyMix(deviceType, address, policyMix) == NO_ERROR) {
7807 policyMix->setOutput(desc);
7808 desc->mPolicyMix = policyMix;
7809 } else {
7810 ALOGW("checkOutputsForDevice() cannot find policy for address %s",
7811 address.string());
7812 }
7813
baek.kim -61c20122022-07-27 10:05:32 +00007814 } else if (hasPrimaryOutput() && speaker != nullptr
7815 && mPrimaryOutput->supportsDevice(speaker) && !desc->supportsDevice(speaker)
Eric Laurentb4f42a92022-01-17 17:37:31 +01007816 && ((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0)) {
7817 // no duplicated output for:
7818 // - direct outputs
7819 // - outputs used by dynamic policy mixes
baek.kim -61c20122022-07-27 10:05:32 +00007820 // - outputs that supports SPEAKER while the primary output does not.
jiabinbce0c1d2020-10-05 11:20:18 -07007821 audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE;
7822
7823 //TODO: configure audio effect output stage here
7824
7825 // open a duplicating output thread for the new output and the primary output
7826 sp<SwAudioOutputDescriptor> dupOutputDesc =
7827 new SwAudioOutputDescriptor(nullptr, mpClientInterface);
7828 status = dupOutputDesc->openDuplicating(mPrimaryOutput, desc, &duplicatedOutput);
7829 if (status == NO_ERROR) {
7830 // add duplicated output descriptor
7831 addOutput(duplicatedOutput, dupOutputDesc);
7832 } else {
7833 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
7834 mPrimaryOutput->mIoHandle, output);
7835 desc->close();
7836 removeOutput(output);
7837 nextAudioPortGeneration();
7838 return nullptr;
7839 }
7840 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02007841 if (mPrimaryOutput == nullptr && profile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
7842 ALOGV("%s(): re-assigning mPrimaryOutput", __func__);
7843 mPrimaryOutput = desc;
7844 }
jiabinbce0c1d2020-10-05 11:20:18 -07007845 return desc;
7846}
7847
jiabinf1c73972022-04-14 16:28:52 -07007848status_t AudioPolicyManager::getDevicesForAttributes(
7849 const audio_attributes_t &attr, DeviceVector &devices, bool forVolume) {
7850 // Devices are determined in the following precedence:
7851 //
7852 // 1) Devices associated with a dynamic policy matching the attributes. This is often
7853 // a remote submix from MIX_ROUTE_FLAG_LOOP_BACK.
7854 //
7855 // If no such dynamic policy then
7856 // 2) Devices containing an active client using setPreferredDevice
7857 // with same strategy as the attributes.
7858 // (from the default Engine::getOutputDevicesForAttributes() implementation).
7859 //
7860 // If no corresponding active client with setPreferredDevice then
7861 // 3) Devices associated with the strategy determined by the attributes
7862 // (from the default Engine::getOutputDevicesForAttributes() implementation).
7863 //
7864 // See related getOutputForAttrInt().
7865
7866 // check dynamic policies but only for primary descriptors (secondary not used for audible
7867 // audio routing, only used for duplication for playback capture)
7868 sp<AudioPolicyMix> policyMix;
7869 status_t status = mPolicyMixes.getOutputForAttr(attr, AUDIO_CONFIG_BASE_INITIALIZER,
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007870 0 /*uid unknown here*/, AUDIO_SESSION_NONE, AUDIO_OUTPUT_FLAG_NONE, policyMix,
jiabinf1c73972022-04-14 16:28:52 -07007871 nullptr /* secondaryMixes */);
7872 if (status != OK) {
7873 return status;
7874 }
7875
7876 if (policyMix != nullptr && policyMix->getOutput() != nullptr &&
7877 // For volume control, skip LOOPBACK mixes which use AUDIO_DEVICE_OUT_REMOTE_SUBMIX
7878 // as they are unaffected by device/stream volume
7879 // (per SwAudioOutputDescriptor::isFixedVolume()).
7880 (!forVolume || policyMix->mDeviceType != AUDIO_DEVICE_OUT_REMOTE_SUBMIX)
7881 ) {
7882 sp<DeviceDescriptor> deviceDesc = mAvailableOutputDevices.getDevice(
7883 policyMix->mDeviceType, policyMix->mDeviceAddress, AUDIO_FORMAT_DEFAULT);
7884 devices.add(deviceDesc);
7885 } else {
7886 // The default Engine::getOutputDevicesForAttributes() uses findPreferredDevice()
7887 // which selects setPreferredDevice if active. This means forVolume call
7888 // will take an active setPreferredDevice, if such exists.
7889
7890 devices = mEngine->getOutputDevicesForAttributes(
7891 attr, nullptr /* preferredDevice */, false /* fromCache */);
7892 }
7893
7894 if (forVolume) {
7895 // We alias the device AUDIO_DEVICE_OUT_SPEAKER_SAFE to AUDIO_DEVICE_OUT_SPEAKER
7896 // for single volume control in AudioService (such relationship should exist if
7897 // SPEAKER_SAFE is present).
7898 //
7899 // (This is unrelated to a different device grouping as Volume::getDeviceCategory)
7900 DeviceVector speakerSafeDevices =
7901 devices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER_SAFE);
7902 if (!speakerSafeDevices.isEmpty()) {
7903 devices.merge(mAvailableOutputDevices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER));
7904 devices.remove(speakerSafeDevices);
7905 }
7906 }
7907
7908 return NO_ERROR;
7909}
7910
7911status_t AudioPolicyManager::getProfilesForDevices(const DeviceVector& devices,
7912 AudioProfileVector& audioProfiles,
7913 uint32_t flags,
7914 bool isInput) {
7915 for (const auto& hwModule : mHwModules) {
7916 // the MSD module checks for different conditions
7917 if (strcmp(hwModule->getName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0) {
7918 continue;
7919 }
7920 IOProfileCollection ioProfiles = isInput ? hwModule->getInputProfiles()
7921 : hwModule->getOutputProfiles();
7922 for (const auto& profile : ioProfiles) {
7923 if (!profile->areAllDevicesSupported(devices) ||
7924 !profile->isCompatibleProfileForFlags(
7925 flags, false /*exactMatchRequiredForInputFlags*/)) {
7926 continue;
7927 }
7928 audioProfiles.addAllValidProfiles(profile->asAudioPort()->getAudioProfiles());
7929 }
7930 }
7931
7932 if (!isInput) {
7933 // add the direct profiles from MSD if present and has audio patches to all the output(s)
7934 const auto &msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
7935 if (msdModule != nullptr) {
7936 if (msdHasPatchesToAllDevices(devices.toTypeAddrVector())) {
7937 ALOGV("%s: MSD audio patches set to all output devices.", __func__);
7938 for (const auto &profile: msdModule->getOutputProfiles()) {
7939 if (!profile->asAudioPort()->isDirectOutput()) {
7940 continue;
7941 }
7942 audioProfiles.addAllValidProfiles(profile->asAudioPort()->getAudioProfiles());
7943 }
7944 } else {
7945 ALOGV("%s: MSD audio patches NOT set to all output devices.", __func__);
7946 }
7947 }
7948 }
7949
7950 return NO_ERROR;
7951}
7952
Mikhail Naganov1b2a7942017-12-08 10:18:09 -08007953} // namespace android