blob: 83de3e2c9b028e5e3f88595e27e1e63726e1eb92 [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 Naganov0566bac2022-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 Laurentc2c94c32022-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,
1135 const audio_config_t *config,
1136 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 Wheatley23ecfe42022-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 };
1172 status = mPolicyMixes.getOutputForAttr(*resultAttr, clientConfig, uid, *flags, primaryMix,
1173 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 Wheatley23ecfe42022-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 Wheatley1bdf0f92022-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 Wheatley1bdf0f92022-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 Wheatley1bdf0f92022-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) {
1276 return INVALID_OPERATION;
1277 }
Paul McLeanaa981192015-03-21 09:55:15 -07001278
François Gaffiec005e562018-11-06 15:04:49 +01001279 *selectedDeviceId = getFirstDeviceId(outputDevices);
Michael Chan6fb34492020-12-08 15:44:49 +11001280 for (auto &outputDevice : outputDevices) {
1281 if (outputDevice->getId() == getConfig().getDefaultOutputDevice()->getId()) {
1282 *selectedDeviceId = outputDevice->getId();
1283 break;
1284 }
1285 }
Eric Laurent2ac76942017-06-22 17:17:09 -07001286
Eric Laurent8a1095a2019-11-08 14:44:16 -08001287 if (outputDevices.onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_TELEPHONY_TX)) {
1288 *outputType = API_OUTPUT_TELEPHONY_TX;
1289 } else {
1290 *outputType = API_OUTPUT_LEGACY;
1291 }
1292
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001293 ALOGV("%s returns output %d selectedDeviceId %d", __func__, *output, *selectedDeviceId);
1294
1295 return NO_ERROR;
1296}
1297
1298status_t AudioPolicyManager::getOutputForAttr(const audio_attributes_t *attr,
1299 audio_io_handle_t *output,
1300 audio_session_t session,
1301 audio_stream_type_t *stream,
Svet Ganov3e5f14f2021-05-13 22:51:08 +00001302 const AttributionSourceState& attributionSource,
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001303 const audio_config_t *config,
1304 audio_output_flags_t *flags,
1305 audio_port_handle_t *selectedDeviceId,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001306 audio_port_handle_t *portId,
Eric Laurent8a1095a2019-11-08 14:44:16 -08001307 std::vector<audio_io_handle_t> *secondaryOutputs,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001308 output_type_t *outputType,
1309 bool *isSpatialized)
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001310{
1311 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
1312 if (*portId != AUDIO_PORT_HANDLE_NONE) {
1313 return INVALID_OPERATION;
1314 }
Philip P. Moltmannbda45752020-07-17 16:41:18 -07001315 const uid_t uid = VALUE_OR_RETURN_STATUS(
Svet Ganov3e5f14f2021-05-13 22:51:08 +00001316 aidl2legacy_int32_t_uid_t(attributionSource.uid));
Francois Gaffie716e1432019-01-14 16:58:59 +01001317 const audio_port_handle_t requestedPortId = *selectedDeviceId;
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001318 audio_attributes_t resultAttr;
François Gaffief579db52018-11-13 11:25:16 +01001319 bool isRequestedDeviceForExclusiveUse = false;
Eric Laurentc529cf62020-04-17 18:19:10 -07001320 std::vector<sp<AudioPolicyMix>> secondaryMixes;
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001321 const sp<DeviceDescriptor> requestedDevice =
1322 mAvailableOutputDevices.getDeviceFromId(requestedPortId);
1323
1324 // Prevent from storing invalid requested device id in clients
1325 const audio_port_handle_t sanitizedRequestedPortId =
1326 requestedDevice != nullptr ? requestedPortId : AUDIO_PORT_HANDLE_NONE;
1327 *selectedDeviceId = sanitizedRequestedPortId;
1328
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001329 status_t status = getOutputForAttrInt(&resultAttr, output, session, attr, stream, uid,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001330 config, flags, selectedDeviceId, &isRequestedDeviceForExclusiveUse,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001331 secondaryOutputs != nullptr ? &secondaryMixes : nullptr, outputType, isSpatialized);
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001332 if (status != NO_ERROR) {
1333 return status;
1334 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001335 std::vector<wp<SwAudioOutputDescriptor>> weakSecondaryOutputDescs;
Eric Laurentc529cf62020-04-17 18:19:10 -07001336 if (secondaryOutputs != nullptr) {
1337 for (auto &secondaryMix : secondaryMixes) {
1338 sp<SwAudioOutputDescriptor> outputDesc = secondaryMix->getOutput();
1339 if (outputDesc != nullptr &&
1340 outputDesc->mIoHandle != AUDIO_IO_HANDLE_NONE) {
1341 secondaryOutputs->push_back(outputDesc->mIoHandle);
1342 weakSecondaryOutputDescs.push_back(outputDesc);
1343 }
1344 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001345 }
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001346
Eric Laurent8fc147b2018-07-22 19:13:55 -07001347 audio_config_base_t clientConfig = {.sample_rate = config->sample_rate,
Nick Desaulniersa30e3202019-10-18 13:38:23 -07001348 .channel_mask = config->channel_mask,
Eric Laurent8fc147b2018-07-22 19:13:55 -07001349 .format = config->format,
Nick Desaulniersa30e3202019-10-18 13:38:23 -07001350 };
jiabin4ef93452019-09-10 14:29:54 -07001351 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurent8f42ea12018-08-08 09:08:25 -07001352
Eric Laurentc209fe42020-06-05 18:11:23 -07001353 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(*output);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001354 sp<TrackClientDescriptor> clientDesc =
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001355 new TrackClientDescriptor(*portId, uid, session, resultAttr, clientConfig,
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001356 sanitizedRequestedPortId, *stream,
François Gaffiec005e562018-11-06 15:04:49 +01001357 mEngine->getProductStrategyForAttributes(resultAttr),
François Gaffieaaac0fd2018-11-22 17:56:39 +01001358 toVolumeSource(resultAttr),
Kevin Rocard153f92d2018-12-18 18:33:28 -08001359 *flags, isRequestedDeviceForExclusiveUse,
Eric Laurentc209fe42020-06-05 18:11:23 -07001360 std::move(weakSecondaryOutputDescs),
1361 outputDesc->mPolicyMix);
Andy Hung39efb7a2018-09-26 15:39:28 -07001362 outputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001363
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001364 ALOGV("%s() returns output %d requestedPortId %d selectedDeviceId %d for port ID %d", __func__,
1365 *output, requestedPortId, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07001366
Eric Laurente83b55d2014-11-14 10:06:21 -08001367 return NO_ERROR;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001368}
1369
Eric Laurentc529cf62020-04-17 18:19:10 -07001370status_t AudioPolicyManager::openDirectOutput(audio_stream_type_t stream,
1371 audio_session_t session,
1372 const audio_config_t *config,
1373 audio_output_flags_t flags,
1374 const DeviceVector &devices,
1375 audio_io_handle_t *output) {
1376
1377 *output = AUDIO_IO_HANDLE_NONE;
1378
1379 // skip direct output selection if the request can obviously be attached to a mixed output
1380 // and not explicitly requested
1381 if (((flags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
1382 audio_is_linear_pcm(config->format) && config->sample_rate <= SAMPLE_RATE_HZ_MAX &&
1383 audio_channel_count_from_out_mask(config->channel_mask) <= 2) {
1384 return NAME_NOT_FOUND;
1385 }
1386
1387 // Do not allow offloading if one non offloadable effect is enabled or MasterMono is enabled.
1388 // This prevents creating an offloaded track and tearing it down immediately after start
1389 // when audioflinger detects there is an active non offloadable effect.
1390 // FIXME: We should check the audio session here but we do not have it in this context.
1391 // This may prevent offloading in rare situations where effects are left active by apps
1392 // in the background.
1393 sp<IOProfile> profile;
1394 if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) ||
1395 !(mEffects.isNonOffloadableEffectEnabled() || mMasterMono)) {
1396 profile = getProfileForOutput(
1397 devices, config->sample_rate, config->format, config->channel_mask,
1398 flags, true /* directOnly */);
1399 }
1400
1401 if (profile == nullptr) {
1402 return NAME_NOT_FOUND;
1403 }
1404
1405 // exclusive outputs for MMAP and Offload are enforced by different session ids.
1406 for (size_t i = 0; i < mOutputs.size(); i++) {
1407 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
1408 if (!desc->isDuplicated() && (profile == desc->mProfile)) {
1409 // reuse direct output if currently open by the same client
1410 // and configured with same parameters
1411 if ((config->sample_rate == desc->getSamplingRate()) &&
1412 (config->format == desc->getFormat()) &&
1413 (config->channel_mask == desc->getChannelMask()) &&
1414 (session == desc->mDirectClientSession)) {
1415 desc->mDirectOpenCount++;
Eric Laurentfecbceb2021-02-09 14:46:43 +01001416 ALOGV("%s reusing direct output %d for session %d", __func__,
Eric Laurentc529cf62020-04-17 18:19:10 -07001417 mOutputs.keyAt(i), session);
1418 *output = mOutputs.keyAt(i);
1419 return NO_ERROR;
1420 }
1421 }
1422 }
1423
1424 if (!profile->canOpenNewIo()) {
1425 return NAME_NOT_FOUND;
1426 }
1427
1428 sp<SwAudioOutputDescriptor> outputDesc =
1429 new SwAudioOutputDescriptor(profile, mpClientInterface);
1430
Michael Chan6fb34492020-12-08 15:44:49 +11001431 // An MSD patch may be using the only output stream that can service this request. Release
1432 // all MSD patches to prioritize this request over any active output on MSD.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001433 releaseMsdOutputPatches(devices);
Eric Laurentc529cf62020-04-17 18:19:10 -07001434
Eric Laurentf1f22e72021-07-13 14:04:14 +02001435 status_t status =
1436 outputDesc->open(config, nullptr /* mixerConfig */, devices, stream, flags, output);
Eric Laurentc529cf62020-04-17 18:19:10 -07001437
1438 // only accept an output with the requested parameters
1439 if (status != NO_ERROR ||
1440 (config->sample_rate != 0 && config->sample_rate != outputDesc->getSamplingRate()) ||
1441 (config->format != AUDIO_FORMAT_DEFAULT && config->format != outputDesc->getFormat()) ||
1442 (config->channel_mask != 0 && config->channel_mask != outputDesc->getChannelMask())) {
1443 ALOGV("%s failed opening direct output: output %d sample rate %d %d,"
1444 "format %d %d, channel mask %04x %04x", __func__, *output, config->sample_rate,
1445 outputDesc->getSamplingRate(), config->format, outputDesc->getFormat(),
1446 config->channel_mask, outputDesc->getChannelMask());
1447 if (*output != AUDIO_IO_HANDLE_NONE) {
1448 outputDesc->close();
1449 }
1450 // fall back to mixer output if possible when the direct output could not be open
1451 if (audio_is_linear_pcm(config->format) &&
1452 config->sample_rate <= SAMPLE_RATE_HZ_MAX) {
1453 return NAME_NOT_FOUND;
1454 }
1455 *output = AUDIO_IO_HANDLE_NONE;
1456 return BAD_VALUE;
1457 }
1458 outputDesc->mDirectOpenCount = 1;
1459 outputDesc->mDirectClientSession = session;
1460
1461 addOutput(*output, outputDesc);
1462 mPreviousOutputs = mOutputs;
1463 ALOGV("%s returns new direct output %d", __func__, *output);
1464 mpClientInterface->onAudioPortListUpdate();
1465 return NO_ERROR;
1466}
1467
François Gaffie11d30102018-11-02 16:09:09 +01001468audio_io_handle_t AudioPolicyManager::getOutputForDevices(
1469 const DeviceVector &devices,
Kevin Rocard169753c2017-03-06 14:18:23 -08001470 audio_session_t session,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001471 const audio_attributes_t *attr,
Eric Laurentfe231122017-11-17 17:48:06 -08001472 const audio_config_t *config,
jiabine375d412019-02-26 12:54:53 -08001473 audio_output_flags_t *flags,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001474 bool *isSpatialized,
jiabine375d412019-02-26 12:54:53 -08001475 bool forceMutingHaptic)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001476{
Andy Hungc88b0642018-04-27 15:42:35 -07001477 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001478
jiabine375d412019-02-26 12:54:53 -08001479 // Discard haptic channel mask when forcing muting haptic channels.
1480 audio_channel_mask_t channelMask = forceMutingHaptic
Mikhail Naganov55773032020-10-01 15:08:13 -07001481 ? static_cast<audio_channel_mask_t>(config->channel_mask & ~AUDIO_CHANNEL_HAPTIC_ALL)
1482 : config->channel_mask;
jiabine375d412019-02-26 12:54:53 -08001483
Eric Laurente552edb2014-03-10 17:42:56 -07001484 // open a direct output if required by specified parameters
1485 //force direct flag if offload flag is set: offloading implies a direct output stream
1486 // and all common behaviors are driven by checking only the direct flag
1487 // this should normally be set appropriately in the policy configuration file
Nadav Bar766fb022018-01-07 12:18:03 +02001488 if ((*flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1489 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurente552edb2014-03-10 17:42:56 -07001490 }
Nadav Bar766fb022018-01-07 12:18:03 +02001491 if ((*flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
1492 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent93c3d412014-08-01 14:48:35 -07001493 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001494
1495 audio_stream_type_t stream = mEngine->getStreamTypeForAttributes(*attr);
1496
Eric Laurente83b55d2014-11-14 10:06:21 -08001497 // only allow deep buffering for music stream type
1498 if (stream != AUDIO_STREAM_MUSIC) {
Nadav Bar766fb022018-01-07 12:18:03 +02001499 *flags = (audio_output_flags_t)(*flags &~AUDIO_OUTPUT_FLAG_DEEP_BUFFER);
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -07001500 } else if (/* stream == AUDIO_STREAM_MUSIC && */
Nadav Bar766fb022018-01-07 12:18:03 +02001501 *flags == AUDIO_OUTPUT_FLAG_NONE &&
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -07001502 property_get_bool("audio.deep_buffer.media", false /* default_value */)) {
1503 // use DEEP_BUFFER as default output for music stream type
Nadav Bar766fb022018-01-07 12:18:03 +02001504 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
Eric Laurente83b55d2014-11-14 10:06:21 -08001505 }
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -07001506 if (stream == AUDIO_STREAM_TTS) {
Nadav Bar766fb022018-01-07 12:18:03 +02001507 *flags = AUDIO_OUTPUT_FLAG_TTS;
Haynes Mathew George84c621e2017-04-25 11:41:50 -07001508 } else if (stream == AUDIO_STREAM_VOICE_CALL &&
Nadav Bar20919492018-11-20 10:20:51 +02001509 audio_is_linear_pcm(config->format) &&
1510 (*flags & AUDIO_OUTPUT_FLAG_INCALL_MUSIC) == 0) {
Nadav Bar766fb022018-01-07 12:18:03 +02001511 *flags = (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_VOIP_RX |
Haynes Mathew George84c621e2017-04-25 11:41:50 -07001512 AUDIO_OUTPUT_FLAG_DIRECT);
1513 ALOGV("Set VoIP and Direct output flags for PCM format");
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -07001514 }
Eric Laurente552edb2014-03-10 17:42:56 -07001515
Carter Hsua3abb402021-10-26 11:11:20 +08001516 // Attach the Ultrasound flag for the AUDIO_CONTENT_TYPE_ULTRASOUND
1517 if (attr->content_type == AUDIO_CONTENT_TYPE_ULTRASOUND) {
1518 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_ULTRASOUND);
1519 }
1520
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001521 *isSpatialized = false;
Eric Laurentfa0f6742021-08-17 18:39:44 +02001522 if (mSpatializerOutput != nullptr
Andy Hung9dd1a5b2022-05-10 15:39:39 -07001523 && canBeSpatializedInt(attr, config, devices.toTypeAddrVector())) {
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001524 *isSpatialized = true;
Eric Laurentfa0f6742021-08-17 18:39:44 +02001525 return mSpatializerOutput->mIoHandle;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001526 }
1527
Eric Laurentc529cf62020-04-17 18:19:10 -07001528 audio_config_t directConfig = *config;
1529 directConfig.channel_mask = channelMask;
1530 status_t status = openDirectOutput(stream, session, &directConfig, *flags, devices, &output);
1531 if (status != NAME_NOT_FOUND) {
Eric Laurente552edb2014-03-10 17:42:56 -07001532 return output;
1533 }
1534
Eric Laurent14cbfca2016-03-17 09:42:16 -07001535 // A request for HW A/V sync cannot fallback to a mixed output because time
1536 // stamps are embedded in audio data
Phil Burk2d059932018-02-15 15:55:11 -08001537 if ((*flags & (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ)) != 0) {
Eric Laurent14cbfca2016-03-17 09:42:16 -07001538 return AUDIO_IO_HANDLE_NONE;
1539 }
1540
Eric Laurente552edb2014-03-10 17:42:56 -07001541 // ignoring channel mask due to downmix capability in mixer
1542
1543 // open a non direct output
1544
1545 // for non direct outputs, only PCM is supported
Eric Laurentfe231122017-11-17 17:48:06 -08001546 if (audio_is_linear_pcm(config->format)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001547 // get which output is suitable for the specified stream. The actual
1548 // routing change will happen when startOutput() will be called
François Gaffie11d30102018-11-02 16:09:09 +01001549 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07001550
Eric Laurent8838a382014-09-08 16:44:28 -07001551 // at this stage we should ignore the DIRECT flag as no direct output could be found earlier
Nadav Bar766fb022018-01-07 12:18:03 +02001552 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
jiabinebb6af42020-06-09 17:31:17 -07001553 output = selectOutput(
1554 outputs, *flags, config->format, channelMask, config->sample_rate, session);
Eric Laurente552edb2014-03-10 17:42:56 -07001555 }
François Gaffie11d30102018-11-02 16:09:09 +01001556 ALOGW_IF((output == 0), "getOutputForDevices() could not find output for stream %d, "
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001557 "sampling rate %d, format %#x, channels %#x, flags %#x",
jiabine375d412019-02-26 12:54:53 -08001558 stream, config->sample_rate, config->format, channelMask, *flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001559
Eric Laurente552edb2014-03-10 17:42:56 -07001560 return output;
1561}
1562
Mikhail Naganovf02f3672018-11-09 12:44:16 -08001563sp<DeviceDescriptor> AudioPolicyManager::getMsdAudioInDevice() const {
François Gaffie11d30102018-11-02 16:09:09 +01001564 auto msdInDevices = mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1565 mAvailableInputDevices);
1566 return msdInDevices.isEmpty()? nullptr : msdInDevices.itemAt(0);
1567}
1568
1569DeviceVector AudioPolicyManager::getMsdAudioOutDevices() const {
1570 return mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1571 mAvailableOutputDevices);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001572}
1573
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001574const AudioPatchCollection AudioPolicyManager::getMsdOutputPatches() const {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001575 AudioPatchCollection msdPatches;
Mikhail Naganov86112352018-10-04 09:02:49 -07001576 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1577 if (msdModule != 0) {
1578 for (size_t i = 0; i < mAudioPatches.size(); ++i) {
1579 sp<AudioPatch> patch = mAudioPatches.valueAt(i);
1580 for (size_t j = 0; j < patch->mPatch.num_sources; ++j) {
1581 const struct audio_port_config *source = &patch->mPatch.sources[j];
1582 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
1583 source->ext.device.hw_module == msdModule->getHandle()) {
François Gaffieafd4cea2019-11-18 15:50:22 +01001584 msdPatches.addAudioPatch(patch->getHandle(), patch);
Mikhail Naganov86112352018-10-04 09:02:49 -07001585 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001586 }
1587 }
1588 }
1589 return msdPatches;
1590}
1591
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02001592bool AudioPolicyManager::isMsdPatch(const audio_patch_handle_t &handle) const {
1593 ssize_t index = mAudioPatches.indexOfKey(handle);
1594 if (index < 0) {
1595 return false;
1596 }
1597 const sp<AudioPatch> patch = mAudioPatches.valueAt(index);
1598 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1599 if (msdModule == nullptr) {
1600 return false;
1601 }
1602 const struct audio_port_config *sink = &patch->mPatch.sinks[0];
1603 if (getMsdAudioOutDevices().contains(mAvailableOutputDevices.getDeviceFromId(sink->id))) {
1604 return true;
1605 }
1606 index = getMsdOutputPatches().indexOfKey(handle);
1607 if (index < 0) {
1608 return false;
1609 }
1610 return true;
1611}
1612
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001613status_t AudioPolicyManager::getMsdProfiles(bool hwAvSync,
1614 const InputProfileCollection &inputProfiles,
1615 const OutputProfileCollection &outputProfiles,
1616 const sp<DeviceDescriptor> &sourceDevice,
1617 const sp<DeviceDescriptor> &sinkDevice,
1618 AudioProfileVector& sourceProfiles,
1619 AudioProfileVector& sinkProfiles) const {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001620 if (inputProfiles.isEmpty()) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001621 ALOGE("%s() no input profiles for source module", __func__);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001622 return NO_INIT;
1623 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001624 if (outputProfiles.isEmpty()) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001625 ALOGE("%s() no output profiles for sink module", __func__);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001626 return NO_INIT;
1627 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001628 for (const auto &inProfile : inputProfiles) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001629 if (hwAvSync == ((inProfile->getFlags() & AUDIO_INPUT_FLAG_HW_AV_SYNC) != 0) &&
1630 inProfile->supportsDevice(sourceDevice)) {
1631 appendAudioProfiles(sourceProfiles, inProfile->getAudioProfiles());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001632 }
1633 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001634 for (const auto &outProfile : outputProfiles) {
Michael Chan6fb34492020-12-08 15:44:49 +11001635 if (hwAvSync == ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) &&
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001636 outProfile->supportsDevice(sinkDevice)) {
1637 appendAudioProfiles(sinkProfiles, outProfile->getAudioProfiles());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001638 }
1639 }
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001640 return NO_ERROR;
1641}
1642
1643status_t AudioPolicyManager::getBestMsdConfig(bool hwAvSync,
1644 const AudioProfileVector &sourceProfiles, const AudioProfileVector &sinkProfiles,
1645 audio_port_config *sourceConfig, audio_port_config *sinkConfig) const
1646{
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001647 struct audio_config_base bestSinkConfig;
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001648 status_t result = findBestMatchingOutputConfig(sourceProfiles, sinkProfiles,
1649 msdCompressedFormatsOrder, msdSurroundChannelMasksOrder,
1650 true /*preferHigherSamplingRates*/, bestSinkConfig);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001651 if (result != NO_ERROR) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001652 ALOGD("%s() no matching config found for sink, hwAvSync: %d",
1653 __func__, hwAvSync);
Greg Kaiser83289652018-07-30 06:13:57 -07001654 return result;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001655 }
1656 sinkConfig->sample_rate = bestSinkConfig.sample_rate;
1657 sinkConfig->channel_mask = bestSinkConfig.channel_mask;
1658 sinkConfig->format = bestSinkConfig.format;
1659 // For encoded streams force direct flag to prevent downstream mixing.
1660 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1661 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_DIRECT);
Dean Wheatley5c9f0832019-11-21 13:39:31 +11001662 if (audio_is_iec61937_compatible(sinkConfig->format)) {
1663 // For formats compatible with IEC61937 encapsulation, assume that
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001664 // the input is IEC61937 framed (for proportional buffer sizing).
Dean Wheatley5c9f0832019-11-21 13:39:31 +11001665 // Add the AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO flag so downstream HAL can distinguish between
1666 // raw and IEC61937 framed streams.
1667 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1668 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO);
1669 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001670 sourceConfig->sample_rate = bestSinkConfig.sample_rate;
1671 // Specify exact channel mask to prevent guessing by bit count in PatchPanel.
1672 sourceConfig->channel_mask = audio_channel_mask_out_to_in(bestSinkConfig.channel_mask);
1673 sourceConfig->format = bestSinkConfig.format;
1674 // Copy input stream directly without any processing (e.g. resampling).
1675 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1676 sourceConfig->flags.input | AUDIO_INPUT_FLAG_DIRECT);
1677 if (hwAvSync) {
1678 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1679 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
1680 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1681 sourceConfig->flags.input | AUDIO_INPUT_FLAG_HW_AV_SYNC);
1682 }
1683 const unsigned int config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE |
1684 AUDIO_PORT_CONFIG_CHANNEL_MASK | AUDIO_PORT_CONFIG_FORMAT | AUDIO_PORT_CONFIG_FLAGS;
1685 sinkConfig->config_mask |= config_mask;
1686 sourceConfig->config_mask |= config_mask;
1687 return NO_ERROR;
1688}
1689
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001690PatchBuilder AudioPolicyManager::buildMsdPatch(bool msdIsSource,
1691 const sp<DeviceDescriptor> &device) const
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001692{
1693 PatchBuilder patchBuilder;
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001694 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1695 ALOG_ASSERT(msdModule != nullptr, "MSD module not available");
1696 sp<HwModule> deviceModule = mHwModules.getModuleForDevice(device, AUDIO_FORMAT_DEFAULT);
1697 if (deviceModule == nullptr) {
1698 ALOGE("%s() unable to get module for %s", __func__, device->toString().c_str());
1699 return patchBuilder;
1700 }
1701 const InputProfileCollection inputProfiles = msdIsSource ?
1702 msdModule->getInputProfiles() : deviceModule->getInputProfiles();
1703 const OutputProfileCollection outputProfiles = msdIsSource ?
1704 deviceModule->getOutputProfiles() : msdModule->getOutputProfiles();
1705
1706 const sp<DeviceDescriptor> sourceDevice = msdIsSource ? getMsdAudioInDevice() : device;
1707 const sp<DeviceDescriptor> sinkDevice = msdIsSource ?
1708 device : getMsdAudioOutDevices().itemAt(0);
1709 patchBuilder.addSource(sourceDevice).addSink(sinkDevice);
1710
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001711 audio_port_config sourceConfig = patchBuilder.patch()->sources[0];
1712 audio_port_config sinkConfig = patchBuilder.patch()->sinks[0];
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001713 AudioProfileVector sourceProfiles;
1714 AudioProfileVector sinkProfiles;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001715 // TODO: Figure out whether MSD module has HW_AV_SYNC flag set in the AP config file.
1716 // For now, we just forcefully try with HwAvSync first.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001717 for (auto hwAvSync : { true, false }) {
1718 if (getMsdProfiles(hwAvSync, inputProfiles, outputProfiles, sourceDevice, sinkDevice,
1719 sourceProfiles, sinkProfiles) != NO_ERROR) {
1720 continue;
1721 }
1722 if (getBestMsdConfig(hwAvSync, sourceProfiles, sinkProfiles, &sourceConfig,
1723 &sinkConfig) == NO_ERROR) {
1724 // Found a matching config. Re-create PatchBuilder with this config.
1725 return (PatchBuilder()).addSource(sourceConfig).addSink(sinkConfig);
1726 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001727 }
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001728 ALOGV("%s() no matching config found. Fall through to default PCM patch"
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001729 " supporting PCM format conversion.", __func__);
1730 return patchBuilder;
1731}
1732
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001733status_t AudioPolicyManager::setMsdOutputPatches(const DeviceVector *outputDevices) {
Michael Chan6fb34492020-12-08 15:44:49 +11001734 DeviceVector devices;
1735 if (outputDevices != nullptr && outputDevices->size() > 0) {
1736 devices.add(*outputDevices);
1737 } else {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001738 // Use media strategy for unspecified output device. This should only
1739 // occur on checkForDeviceAndOutputChanges(). Device connection events may
1740 // therefore invalidate explicit routing requests.
Michael Chan6fb34492020-12-08 15:44:49 +11001741 devices = mEngine->getOutputDevicesForAttributes(
François Gaffiec005e562018-11-06 15:04:49 +01001742 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
Michael Chan6fb34492020-12-08 15:44:49 +11001743 LOG_ALWAYS_FATAL_IF(devices.isEmpty(), "no output device to set MSD patch");
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001744 }
Michael Chan6fb34492020-12-08 15:44:49 +11001745 std::vector<PatchBuilder> patchesToCreate;
1746 for (auto i = 0u; i < devices.size(); ++i) {
1747 ALOGV("%s() for device %s", __func__, devices[i]->toString().c_str());
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001748 patchesToCreate.push_back(buildMsdPatch(true /*msdIsSource*/, devices[i]));
Michael Chan6fb34492020-12-08 15:44:49 +11001749 }
1750 // Retain only the MSD patches associated with outputDevices request.
1751 // Tear down the others, and create new ones as needed.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001752 AudioPatchCollection patchesToRemove = getMsdOutputPatches();
Michael Chan6fb34492020-12-08 15:44:49 +11001753 for (auto it = patchesToCreate.begin(); it != patchesToCreate.end(); ) {
1754 auto retainedPatch = false;
1755 for (auto i = 0u; i < patchesToRemove.size(); ++i) {
1756 if (audio_patches_are_equal(it->patch(), &patchesToRemove[i]->mPatch)) {
1757 patchesToRemove.removeItemsAt(i);
1758 retainedPatch = true;
1759 break;
1760 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001761 }
Michael Chan6fb34492020-12-08 15:44:49 +11001762 if (retainedPatch) {
1763 it = patchesToCreate.erase(it);
1764 continue;
1765 }
1766 ++it;
1767 }
1768 if (patchesToCreate.size() == 0 && patchesToRemove.size() == 0) {
1769 return NO_ERROR;
1770 }
1771 for (auto i = 0u; i < patchesToRemove.size(); ++i) {
1772 auto &currentPatch = patchesToRemove.valueAt(i);
François Gaffieafd4cea2019-11-18 15:50:22 +01001773 releaseAudioPatch(currentPatch->getHandle(), mUidCached);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001774 }
Michael Chan6fb34492020-12-08 15:44:49 +11001775 status_t status = NO_ERROR;
1776 for (const auto &p : patchesToCreate) {
1777 auto currStatus = installPatch(__func__, -1 /*index*/, nullptr /*patchHandle*/,
1778 p.patch(), 0 /*delayMs*/, mUidCached, nullptr /*patchDescPtr*/);
1779 char message[256];
1780 snprintf(message, sizeof(message), "%s() %s: creating MSD patch from device:IN_BUS to "
1781 "device:%#x (format:%#x channels:%#x samplerate:%d)", __func__,
1782 currStatus == NO_ERROR ? "Success" : "Error",
1783 p.patch()->sinks[0].ext.device.type, p.patch()->sources[0].format,
1784 p.patch()->sources[0].channel_mask, p.patch()->sources[0].sample_rate);
1785 if (currStatus == NO_ERROR) {
1786 ALOGD("%s", message);
1787 } else {
1788 ALOGE("%s", message);
1789 if (status == NO_ERROR) {
1790 status = currStatus;
1791 }
1792 }
1793 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001794 return status;
1795}
1796
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001797void AudioPolicyManager::releaseMsdOutputPatches(const DeviceVector& devices) {
1798 AudioPatchCollection msdPatches = getMsdOutputPatches();
Michael Chan6fb34492020-12-08 15:44:49 +11001799 for (size_t i = 0; i < msdPatches.size(); i++) {
1800 const auto& patch = msdPatches[i];
1801 for (size_t j = 0; j < patch->mPatch.num_sinks; ++j) {
1802 const struct audio_port_config *sink = &patch->mPatch.sinks[j];
1803 if (sink->type == AUDIO_PORT_TYPE_DEVICE && devices.getDevice(sink->ext.device.type,
1804 String8(sink->ext.device.address), AUDIO_FORMAT_DEFAULT) != nullptr) {
1805 releaseAudioPatch(patch->getHandle(), mUidCached);
1806 break;
1807 }
1808 }
1809 }
1810}
1811
Dorin Drimus94d94412022-02-02 09:05:02 +01001812bool AudioPolicyManager::msdHasPatchesToAllDevices(const AudioDeviceTypeAddrVector& devices) {
1813 DeviceVector devicesToCheck = mOutputDevicesAll.getDevicesFromDeviceTypeAddrVec(devices);
1814 AudioPatchCollection msdPatches = getMsdOutputPatches();
1815 for (size_t i = 0; i < msdPatches.size(); i++) {
1816 const auto& patch = msdPatches[i];
1817 for (size_t j = 0; j < patch->mPatch.num_sinks; ++j) {
1818 const struct audio_port_config *sink = &patch->mPatch.sinks[j];
1819 if (sink->type == AUDIO_PORT_TYPE_DEVICE) {
1820 const auto& foundDevice = devicesToCheck.getDevice(
1821 sink->ext.device.type, String8(sink->ext.device.address), AUDIO_FORMAT_DEFAULT);
1822 if (foundDevice != nullptr) {
1823 devicesToCheck.remove(foundDevice);
1824 if (devicesToCheck.isEmpty()) {
1825 return true;
1826 }
1827 }
1828 }
1829 }
1830 }
1831 return false;
1832}
1833
Eric Laurente0720872014-03-11 09:30:41 -07001834audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
jiabinebb6af42020-06-09 17:31:17 -07001835 audio_output_flags_t flags,
1836 audio_format_t format,
1837 audio_channel_mask_t channelMask,
1838 uint32_t samplingRate,
1839 audio_session_t sessionId)
Eric Laurente552edb2014-03-10 17:42:56 -07001840{
Eric Laurent16c66dd2019-05-01 17:54:10 -07001841 LOG_ALWAYS_FATAL_IF(!(format == AUDIO_FORMAT_INVALID || audio_is_linear_pcm(format)),
1842 "%s called with format %#x", __func__, format);
1843
jiabinebb6af42020-06-09 17:31:17 -07001844 // Return the output that haptic-generating attached to when 1) session id is specified,
1845 // 2) haptic-generating effect exists for given session id and 3) the output that
1846 // haptic-generating effect attached to is in given outputs.
1847 if (sessionId != AUDIO_SESSION_NONE) {
1848 audio_io_handle_t hapticGeneratingOutput = mEffects.getIoForSession(
1849 sessionId, FX_IID_HAPTICGENERATOR);
1850 if (outputs.indexOf(hapticGeneratingOutput) >= 0) {
1851 return hapticGeneratingOutput;
1852 }
1853 }
1854
Eric Laurent16c66dd2019-05-01 17:54:10 -07001855 // Flags disqualifying an output: the match must happen before calling selectOutput()
1856 static const audio_output_flags_t kExcludedFlags = (audio_output_flags_t)
1857 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ | AUDIO_OUTPUT_FLAG_DIRECT);
1858
1859 // Flags expressing a functional request: must be honored in priority over
1860 // other criteria
1861 static const audio_output_flags_t kFunctionalFlags = (audio_output_flags_t)
1862 (AUDIO_OUTPUT_FLAG_VOIP_RX | AUDIO_OUTPUT_FLAG_INCALL_MUSIC |
Eric Laurente28c66d2022-01-21 13:40:41 +01001863 AUDIO_OUTPUT_FLAG_TTS | AUDIO_OUTPUT_FLAG_DIRECT_PCM | AUDIO_OUTPUT_FLAG_ULTRASOUND |
1864 AUDIO_OUTPUT_FLAG_SPATIALIZER);
Eric Laurent16c66dd2019-05-01 17:54:10 -07001865 // Flags expressing a performance request: have lower priority than serving
1866 // requested sampling rate or channel mask
1867 static const audio_output_flags_t kPerformanceFlags = (audio_output_flags_t)
1868 (AUDIO_OUTPUT_FLAG_FAST | AUDIO_OUTPUT_FLAG_DEEP_BUFFER |
1869 AUDIO_OUTPUT_FLAG_RAW | AUDIO_OUTPUT_FLAG_SYNC);
1870
1871 const audio_output_flags_t functionalFlags =
1872 (audio_output_flags_t)(flags & kFunctionalFlags);
1873 const audio_output_flags_t performanceFlags =
1874 (audio_output_flags_t)(flags & kPerformanceFlags);
1875
1876 audio_io_handle_t bestOutput = (outputs.size() == 0) ? AUDIO_IO_HANDLE_NONE : outputs[0];
1877
Eric Laurente552edb2014-03-10 17:42:56 -07001878 // select one output among several that provide a path to a particular device or set of
François Gaffie11d30102018-11-02 16:09:09 +01001879 // devices (the list was previously build by getOutputsForDevices()).
Eric Laurente552edb2014-03-10 17:42:56 -07001880 // The priority is as follows:
jiabin40573322018-11-08 12:08:02 -08001881 // 1: the output supporting haptic playback when requesting haptic playback
Eric Laurent16c66dd2019-05-01 17:54:10 -07001882 // 2: the output with the highest number of requested functional flags
Carter Hsu199f1892021-10-15 15:47:29 +08001883 // with tiebreak preferring the minimum number of extra functional flags
1884 // (see b/200293124, the incorrect selection of AUDIO_OUTPUT_FLAG_VOIP_RX).
Eric Laurent16c66dd2019-05-01 17:54:10 -07001885 // 3: the output supporting the exact channel mask
1886 // 4: the output with a higher channel count than requested
1887 // 5: the output with a higher sampling rate than requested
1888 // 6: the output with the highest number of requested performance flags
1889 // 7: the output with the bit depth the closest to the requested one
1890 // 8: the primary output
1891 // 9: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07001892
Eric Laurent16c66dd2019-05-01 17:54:10 -07001893 // matching criteria values in priority order for best matching output so far
1894 std::vector<uint32_t> bestMatchCriteria(8, 0);
Eric Laurente552edb2014-03-10 17:42:56 -07001895
Eric Laurent16c66dd2019-05-01 17:54:10 -07001896 const uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
1897 const uint32_t hapticChannelCount = audio_channel_count_from_out_mask(
1898 channelMask & AUDIO_CHANNEL_HAPTIC_ALL);
Eric Laurente78b6762018-12-19 16:29:01 -08001899
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001900 for (audio_io_handle_t output : outputs) {
1901 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent16c66dd2019-05-01 17:54:10 -07001902 // matching criteria values in priority order for current output
1903 std::vector<uint32_t> currentMatchCriteria(8, 0);
jiabin40573322018-11-08 12:08:02 -08001904
Eric Laurent16c66dd2019-05-01 17:54:10 -07001905 if (outputDesc->isDuplicated()) {
1906 continue;
1907 }
1908 if ((kExcludedFlags & outputDesc->mFlags) != 0) {
1909 continue;
1910 }
Eric Laurent8838a382014-09-08 16:44:28 -07001911
Eric Laurent16c66dd2019-05-01 17:54:10 -07001912 // If haptic channel is specified, use the haptic output if present.
1913 // When using haptic output, same audio format and sample rate are required.
1914 const uint32_t outputHapticChannelCount = audio_channel_count_from_out_mask(
jiabin5740f082019-08-19 15:08:30 -07001915 outputDesc->getChannelMask() & AUDIO_CHANNEL_HAPTIC_ALL);
Eric Laurent16c66dd2019-05-01 17:54:10 -07001916 if ((hapticChannelCount == 0) != (outputHapticChannelCount == 0)) {
1917 continue;
1918 }
1919 if (outputHapticChannelCount >= hapticChannelCount
jiabin5740f082019-08-19 15:08:30 -07001920 && format == outputDesc->getFormat()
1921 && samplingRate == outputDesc->getSamplingRate()) {
Eric Laurent16c66dd2019-05-01 17:54:10 -07001922 currentMatchCriteria[0] = outputHapticChannelCount;
1923 }
1924
1925 // functional flags match
Carter Hsu199f1892021-10-15 15:47:29 +08001926 const int matchingFunctionalFlags =
1927 __builtin_popcount(outputDesc->mFlags & functionalFlags);
1928 const int totalFunctionalFlags =
1929 __builtin_popcount(outputDesc->mFlags & kFunctionalFlags);
1930 // Prefer matching functional flags, but subtract unnecessary functional flags.
1931 currentMatchCriteria[1] = 100 * (matchingFunctionalFlags + 1) - totalFunctionalFlags;
Eric Laurent16c66dd2019-05-01 17:54:10 -07001932
1933 // channel mask and channel count match
jiabin5740f082019-08-19 15:08:30 -07001934 uint32_t outputChannelCount = audio_channel_count_from_out_mask(
1935 outputDesc->getChannelMask());
Eric Laurent16c66dd2019-05-01 17:54:10 -07001936 if (channelMask != AUDIO_CHANNEL_NONE && channelCount > 2 &&
1937 channelCount <= outputChannelCount) {
1938 if ((audio_channel_mask_get_representation(channelMask) ==
jiabin5740f082019-08-19 15:08:30 -07001939 audio_channel_mask_get_representation(outputDesc->getChannelMask())) &&
1940 ((channelMask & outputDesc->getChannelMask()) == channelMask)) {
Eric Laurent16c66dd2019-05-01 17:54:10 -07001941 currentMatchCriteria[2] = outputChannelCount;
Eric Laurente552edb2014-03-10 17:42:56 -07001942 }
Eric Laurent16c66dd2019-05-01 17:54:10 -07001943 currentMatchCriteria[3] = outputChannelCount;
1944 }
1945
1946 // sampling rate match
1947 if (samplingRate > SAMPLE_RATE_HZ_DEFAULT &&
jiabin5740f082019-08-19 15:08:30 -07001948 samplingRate <= outputDesc->getSamplingRate()) {
1949 currentMatchCriteria[4] = outputDesc->getSamplingRate();
Eric Laurent16c66dd2019-05-01 17:54:10 -07001950 }
1951
1952 // performance flags match
1953 currentMatchCriteria[5] = popcount(outputDesc->mFlags & performanceFlags);
1954
1955 // format match
1956 if (format != AUDIO_FORMAT_INVALID) {
1957 currentMatchCriteria[6] =
jiabin4ef93452019-09-10 14:29:54 -07001958 PolicyAudioPort::kFormatDistanceMax -
1959 PolicyAudioPort::formatDistance(format, outputDesc->getFormat());
Eric Laurent16c66dd2019-05-01 17:54:10 -07001960 }
1961
1962 // primary output match
1963 currentMatchCriteria[7] = outputDesc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY;
1964
1965 // compare match criteria by priority then value
1966 if (std::lexicographical_compare(bestMatchCriteria.begin(), bestMatchCriteria.end(),
1967 currentMatchCriteria.begin(), currentMatchCriteria.end())) {
1968 bestMatchCriteria = currentMatchCriteria;
1969 bestOutput = output;
1970
1971 std::stringstream result;
1972 std::copy(bestMatchCriteria.begin(), bestMatchCriteria.end(),
1973 std::ostream_iterator<int>(result, " "));
1974 ALOGV("%s new bestOutput %d criteria %s",
1975 __func__, bestOutput, result.str().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07001976 }
1977 }
1978
Eric Laurent16c66dd2019-05-01 17:54:10 -07001979 return bestOutput;
Eric Laurente552edb2014-03-10 17:42:56 -07001980}
1981
Eric Laurent8fc147b2018-07-22 19:13:55 -07001982status_t AudioPolicyManager::startOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07001983{
Eric Laurent8fc147b2018-07-22 19:13:55 -07001984 ALOGV("%s portId %d", __FUNCTION__, portId);
1985
1986 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
1987 if (outputDesc == 0) {
1988 ALOGW("startOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001989 return BAD_VALUE;
1990 }
Andy Hung39efb7a2018-09-26 15:39:28 -07001991 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001992
Eric Laurent8fc147b2018-07-22 19:13:55 -07001993 ALOGV("startOutput() output %d, stream %d, session %d",
Eric Laurent97ac8712018-07-27 18:59:02 -07001994 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurentc75307b2015-03-17 15:29:32 -07001995
Eric Laurent733ce942017-12-07 12:18:25 -08001996 status_t status = outputDesc->start();
1997 if (status != NO_ERROR) {
1998 return status;
Eric Laurent3974e3b2017-12-07 17:58:43 -08001999 }
2000
Eric Laurent97ac8712018-07-27 18:59:02 -07002001 uint32_t delayMs;
2002 status = startSource(outputDesc, client, &delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07002003
2004 if (status != NO_ERROR) {
Eric Laurent733ce942017-12-07 12:18:25 -08002005 outputDesc->stop();
Eric Laurent8c7e6da2015-04-21 17:37:00 -07002006 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07002007 }
Eric Laurentc75307b2015-03-17 15:29:32 -07002008 if (delayMs != 0) {
2009 usleep(delayMs * 1000);
2010 }
2011
2012 return status;
2013}
2014
Eric Laurent96d1dda2022-03-14 17:14:19 +01002015bool AudioPolicyManager::isLeUnicastActive() const {
2016 if (isInCall()) {
2017 return true;
2018 }
2019 return isAnyDeviceTypeActive(getAudioDeviceOutLeAudioUnicastSet());
2020}
2021
2022bool AudioPolicyManager::isAnyDeviceTypeActive(const DeviceTypeSet& deviceTypes) const {
2023 if (mAvailableOutputDevices.getDevicesFromTypes(deviceTypes).isEmpty()) {
2024 return false;
2025 }
2026 bool active = mOutputs.isAnyDeviceTypeActive(deviceTypes);
2027 ALOGV("%s active %d", __func__, active);
2028 return active;
2029}
2030
Eric Laurent97ac8712018-07-27 18:59:02 -07002031status_t AudioPolicyManager::startSource(const sp<SwAudioOutputDescriptor>& outputDesc,
2032 const sp<TrackClientDescriptor>& client,
2033 uint32_t *delayMs)
Eric Laurentc75307b2015-03-17 15:29:32 -07002034{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002035 // cannot start playback of STREAM_TTS if any other output is being used
2036 uint32_t beaconMuteLatency = 0;
Eric Laurentc75307b2015-03-17 15:29:32 -07002037
2038 *delayMs = 0;
Eric Laurent97ac8712018-07-27 18:59:02 -07002039 audio_stream_type_t stream = client->stream();
François Gaffie1c878552018-11-22 16:53:21 +01002040 auto clientVolSrc = client->volumeSource();
François Gaffiec005e562018-11-06 15:04:49 +01002041 auto clientStrategy = client->strategy();
2042 auto clientAttr = client->attributes();
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002043 if (stream == AUDIO_STREAM_TTS) {
2044 ALOGV("\t found BEACON stream");
François Gaffie1c878552018-11-22 16:53:21 +01002045 if (!mTtsOutputAvailable && mOutputs.isAnyOutputActive(
Francois Gaffie4404ddb2021-02-04 17:03:38 +01002046 toVolumeSource(AUDIO_STREAM_TTS, false) /*sourceToIgnore*/)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002047 return INVALID_OPERATION;
2048 } else {
2049 beaconMuteLatency = handleEventForBeacon(STARTING_BEACON);
2050 }
2051 } else {
2052 // some playback other than beacon starts
2053 beaconMuteLatency = handleEventForBeacon(STARTING_OUTPUT);
2054 }
2055
Eric Laurent77305a62016-07-25 16:39:22 -07002056 // force device change if the output is inactive and no audio patch is already present.
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002057 // check active before incrementing usage count
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02002058 bool force = !outputDesc->isActive() && !outputDesc->isRouted();
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002059
François Gaffie11d30102018-11-02 16:09:09 +01002060 DeviceVector devices;
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002061 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
Eric Laurent97ac8712018-07-27 18:59:02 -07002062 const char *address = NULL;
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002063 if (policyMix != nullptr) {
François Gaffie11d30102018-11-02 16:09:09 +01002064 audio_devices_t newDeviceType;
Eric Laurent97ac8712018-07-27 18:59:02 -07002065 address = policyMix->mDeviceAddress.string();
Kevin Rocard153f92d2018-12-18 18:33:28 -08002066 if ((policyMix->mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie11d30102018-11-02 16:09:09 +01002067 newDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Kevin Rocard153f92d2018-12-18 18:33:28 -08002068 } else {
2069 newDeviceType = policyMix->mDeviceType;
Eric Laurent97ac8712018-07-27 18:59:02 -07002070 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08002071 sp device = mAvailableOutputDevices.getDevice(newDeviceType, String8(address),
2072 AUDIO_FORMAT_DEFAULT);
2073 ALOG_ASSERT(device, "%s: no device found t=%u, a=%s", __func__, newDeviceType, address);
2074 devices.add(device);
Eric Laurent97ac8712018-07-27 18:59:02 -07002075 }
2076
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002077 // requiresMuteCheck is false when we can bypass mute strategy.
2078 // It covers a common case when there is no materially active audio
2079 // and muting would result in unnecessary delay and dropped audio.
2080 const uint32_t outputLatencyMs = outputDesc->latency();
2081 bool requiresMuteCheck = outputDesc->isActive(outputLatencyMs * 2); // account for drain
Eric Laurent96d1dda2022-03-14 17:14:19 +01002082 bool wasLeUnicastActive = isLeUnicastActive();
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002083
Eric Laurente552edb2014-03-10 17:42:56 -07002084 // increment usage count for this stream on the requested output:
2085 // NOTE that the usage count is the same for duplicated output and hardware output which is
2086 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
Eric Laurent592dd7b2018-08-05 18:58:48 -07002087 outputDesc->setClientActive(client, true);
Eric Laurent97ac8712018-07-27 18:59:02 -07002088
2089 if (client->hasPreferredDevice(true)) {
François Gaffief96e5432019-04-09 17:13:56 +02002090 if (outputDesc->clientsList(true /*activeOnly*/).size() == 1 &&
2091 client->isPreferredDeviceForExclusiveUse()) {
2092 // Preferred device may be exclusive, use only if no other active clients on this output
2093 devices = DeviceVector(
2094 mAvailableOutputDevices.getDeviceFromId(client->preferredDeviceId()));
2095 } else {
2096 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
2097 }
François Gaffie11d30102018-11-02 16:09:09 +01002098 if (devices != outputDesc->devices()) {
François Gaffiec005e562018-11-06 15:04:49 +01002099 checkStrategyRoute(clientStrategy, outputDesc->mIoHandle);
Eric Laurent97ac8712018-07-27 18:59:02 -07002100 }
2101 }
Eric Laurente552edb2014-03-10 17:42:56 -07002102
François Gaffiec005e562018-11-06 15:04:49 +01002103 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07002104 selectOutputForMusicEffects();
2105 }
2106
François Gaffie1c878552018-11-22 16:53:21 +01002107 if (outputDesc->getActivityCount(clientVolSrc) == 1 || !devices.isEmpty()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08002108 // starting an output being rerouted?
François Gaffie11d30102018-11-02 16:09:09 +01002109 if (devices.isEmpty()) {
2110 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Eric Laurent275e8e92014-11-30 15:14:47 -08002111 }
François Gaffiec005e562018-11-06 15:04:49 +01002112 bool shouldWait =
2113 (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM)) ||
2114 followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_NOTIFICATION)) ||
2115 (beaconMuteLatency > 0));
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002116 uint32_t waitMs = beaconMuteLatency;
Eric Laurente552edb2014-03-10 17:42:56 -07002117 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01002118 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07002119 if (desc != outputDesc) {
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002120 // An output has a shared device if
2121 // - managed by the same hw module
2122 // - supports the currently selected device
2123 const bool sharedDevice = outputDesc->sharesHwModuleWith(desc)
François Gaffie11d30102018-11-02 16:09:09 +01002124 && (!desc->filterSupportedDevices(devices).isEmpty());
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002125
Eric Laurent77305a62016-07-25 16:39:22 -07002126 // force a device change if any other output is:
2127 // - managed by the same hw module
Jean-Michel Trivi4a5b4812018-02-08 17:22:32 +00002128 // - supports currently selected device
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002129 // - has a current device selection that differs from selected device.
Eric Laurent77305a62016-07-25 16:39:22 -07002130 // - has an active audio patch
Eric Laurente552edb2014-03-10 17:42:56 -07002131 // In this case, the audio HAL must receive the new device selection so that it can
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002132 // change the device currently selected by the other output.
2133 if (sharedDevice &&
François Gaffie11d30102018-11-02 16:09:09 +01002134 desc->devices() != devices &&
Eric Laurent77305a62016-07-25 16:39:22 -07002135 desc->getPatchHandle() != AUDIO_PATCH_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07002136 force = true;
2137 }
2138 // wait for audio on other active outputs to be presented when starting
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002139 // a notification so that audio focus effect can propagate, or that a mute/unmute
2140 // event occurred for beacon
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002141 const uint32_t latencyMs = desc->latency();
2142 const bool isActive = desc->isActive(latencyMs * 2); // account for drain
2143
2144 if (shouldWait && isActive && (waitMs < latencyMs)) {
2145 waitMs = latencyMs;
Eric Laurente552edb2014-03-10 17:42:56 -07002146 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002147
2148 // Require mute check if another output is on a shared device
2149 // and currently active to have proper drain and avoid pops.
2150 // Note restoring AudioTracks onto this output needs to invoke
2151 // a volume ramp if there is no mute.
2152 requiresMuteCheck |= sharedDevice && isActive;
Eric Laurente552edb2014-03-10 17:42:56 -07002153 }
2154 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002155
2156 const uint32_t muteWaitMs =
François Gaffie11d30102018-11-02 16:09:09 +01002157 setOutputDevices(outputDesc, devices, force, 0, NULL, requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07002158
Eric Laurente552edb2014-03-10 17:42:56 -07002159 // apply volume rules for current stream and device if necessary
François Gaffieaaac0fd2018-11-22 17:56:39 +01002160 auto &curves = getVolumeCurves(client->attributes());
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00002161 if (NO_ERROR != checkAndSetVolume(curves, client->volumeSource(),
François Gaffieaaac0fd2018-11-22 17:56:39 +01002162 curves.getVolumeIndex(outputDesc->devices().types()),
Eric Laurentc75307b2015-03-17 15:29:32 -07002163 outputDesc,
Francois Gaffied11442b2020-04-27 11:51:09 +02002164 outputDesc->devices().types(), 0 /*delay*/,
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00002165 outputDesc->useHwGain() /*force*/)) {
2166 // request AudioService to reinitialize the volume curves asynchronously
2167 ALOGE("checkAndSetVolume failed, requesting volume range init");
2168 mpClientInterface->onVolumeRangeInitRequest();
2169 };
Eric Laurente552edb2014-03-10 17:42:56 -07002170
2171 // update the outputs if starting an output with a stream that can affect notification
2172 // routing
2173 handleNotificationRoutingForStream(stream);
Eric Laurentc722f302014-12-10 11:21:49 -08002174
Eric Laurent2cbe89a2014-12-19 11:49:08 -08002175 // force reevaluating accessibility routing when ringtone or alarm starts
François Gaffiec005e562018-11-06 15:04:49 +01002176 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM))) {
Eric Laurent2cbe89a2014-12-19 11:49:08 -08002177 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
2178 }
Eric Laurentdc462862016-07-19 12:29:53 -07002179
2180 if (waitMs > muteWaitMs) {
2181 *delayMs = waitMs - muteWaitMs;
2182 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002183
2184 // FIXME: A device change (muteWaitMs > 0) likely introduces a volume change.
2185 // A volume change enacted by APM with 0 delay is not synchronous, as it goes
2186 // via AudioCommandThread to AudioFlinger. Hence it is possible that the volume
2187 // change occurs after the MixerThread starts and causes a stream volume
2188 // glitch.
2189 //
2190 // We do not introduce additional delay here.
Eric Laurente552edb2014-03-10 17:42:56 -07002191 }
Eric Laurentdc462862016-07-19 12:29:53 -07002192
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002193 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
jiabin9a3361e2019-10-01 09:38:30 -07002194 mEngine->getForceUse(
2195 AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
François Gaffiec005e562018-11-06 15:04:49 +01002196 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), true, outputDesc);
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002197 }
2198
Eric Laurent97ac8712018-07-27 18:59:02 -07002199 // Automatically enable the remote submix input when output is started on a re routing mix
2200 // of type MIX_TYPE_RECORDERS
jiabin9a3361e2019-10-01 09:38:30 -07002201 if (isSingleDeviceType(devices.types(), &audio_is_remote_submix_device) &&
2202 policyMix != NULL && policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002203 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2204 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2205 address,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002206 "remote-submix",
2207 AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07002208 }
2209
Eric Laurent96d1dda2022-03-14 17:14:19 +01002210 checkLeBroadcastRoutes(wasLeUnicastActive, outputDesc, *delayMs);
2211
Eric Laurente552edb2014-03-10 17:42:56 -07002212 return NO_ERROR;
2213}
2214
Eric Laurent96d1dda2022-03-14 17:14:19 +01002215void AudioPolicyManager::checkLeBroadcastRoutes(bool wasUnicastActive,
2216 sp<SwAudioOutputDescriptor> ignoredOutput, uint32_t delayMs) {
2217 bool isUnicastActive = isLeUnicastActive();
2218
2219 if (wasUnicastActive != isUnicastActive) {
2220 //reroute all outputs routed to LE broadcast if LE unicast activy changed on any output
2221 for (size_t i = 0; i < mOutputs.size(); i++) {
2222 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
2223 if (desc != ignoredOutput && desc->isActive()
2224 && ((isUnicastActive &&
2225 !desc->devices().
2226 getDevicesFromType(AUDIO_DEVICE_OUT_BLE_BROADCAST).isEmpty())
2227 || (wasUnicastActive &&
2228 !desc->devices().getDevicesFromTypes(
2229 getAudioDeviceOutLeAudioUnicastSet()).isEmpty()))) {
2230 DeviceVector newDevices = getNewOutputDevices(desc, false /*fromCache*/);
2231 bool force = desc->devices() != newDevices;
2232 setOutputDevices(desc, newDevices, force, delayMs);
2233 // re-apply device specific volume if not done by setOutputDevice()
2234 if (!force) {
2235 applyStreamVolumes(desc, newDevices.types(), delayMs);
2236 }
2237 }
2238 }
2239 }
2240}
2241
Eric Laurent8fc147b2018-07-22 19:13:55 -07002242status_t AudioPolicyManager::stopOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002243{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002244 ALOGV("%s portId %d", __FUNCTION__, portId);
2245
2246 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2247 if (outputDesc == 0) {
2248 ALOGW("stopOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002249 return BAD_VALUE;
2250 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002251 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002252
Eric Laurent97ac8712018-07-27 18:59:02 -07002253 ALOGV("stopOutput() output %d, stream %d, session %d",
2254 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurente552edb2014-03-10 17:42:56 -07002255
Eric Laurent97ac8712018-07-27 18:59:02 -07002256 status_t status = stopSource(outputDesc, client);
Eric Laurent3974e3b2017-12-07 17:58:43 -08002257
Eric Laurent733ce942017-12-07 12:18:25 -08002258 if (status == NO_ERROR ) {
2259 outputDesc->stop();
Eric Laurent3974e3b2017-12-07 17:58:43 -08002260 }
2261 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07002262}
2263
Eric Laurent97ac8712018-07-27 18:59:02 -07002264status_t AudioPolicyManager::stopSource(const sp<SwAudioOutputDescriptor>& outputDesc,
2265 const sp<TrackClientDescriptor>& client)
Eric Laurentc75307b2015-03-17 15:29:32 -07002266{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002267 // always handle stream stop, check which stream type is stopping
Eric Laurent97ac8712018-07-27 18:59:02 -07002268 audio_stream_type_t stream = client->stream();
François Gaffie1c878552018-11-22 16:53:21 +01002269 auto clientVolSrc = client->volumeSource();
Eric Laurent96d1dda2022-03-14 17:14:19 +01002270 bool wasLeUnicastActive = isLeUnicastActive();
Eric Laurent97ac8712018-07-27 18:59:02 -07002271
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002272 handleEventForBeacon(stream == AUDIO_STREAM_TTS ? STOPPING_BEACON : STOPPING_OUTPUT);
2273
François Gaffie1c878552018-11-22 16:53:21 +01002274 if (outputDesc->getActivityCount(clientVolSrc) > 0) {
2275 if (outputDesc->getActivityCount(clientVolSrc) == 1) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002276 // Automatically disable the remote submix input when output is stopped on a
2277 // re routing mix of type MIX_TYPE_RECORDERS
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002278 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
jiabin9a3361e2019-10-01 09:38:30 -07002279 if (isSingleDeviceType(
2280 outputDesc->devices().types(), &audio_is_remote_submix_device) &&
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002281 policyMix != nullptr &&
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002282 policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002283 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2284 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002285 policyMix->mDeviceAddress,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002286 "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07002287 }
2288 }
2289 bool forceDeviceUpdate = false;
2290 if (client->hasPreferredDevice(true)) {
François Gaffiec005e562018-11-06 15:04:49 +01002291 checkStrategyRoute(client->strategy(), AUDIO_IO_HANDLE_NONE);
Eric Laurent97ac8712018-07-27 18:59:02 -07002292 forceDeviceUpdate = true;
2293 }
2294
Eric Laurente552edb2014-03-10 17:42:56 -07002295 // decrement usage count of this stream on the output
Eric Laurent592dd7b2018-08-05 18:58:48 -07002296 outputDesc->setClientActive(client, false);
Paul McLeanaa981192015-03-21 09:55:15 -07002297
Eric Laurente552edb2014-03-10 17:42:56 -07002298 // store time at which the stream was stopped - see isStreamActive()
François Gaffie1c878552018-11-22 16:53:21 +01002299 if (outputDesc->getActivityCount(clientVolSrc) == 0 || forceDeviceUpdate) {
François Gaffiec005e562018-11-06 15:04:49 +01002300 outputDesc->setStopTime(client, systemTime());
François Gaffie11d30102018-11-02 16:09:09 +01002301 DeviceVector newDevices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Francois Gaffie3523ab32021-06-22 13:24:34 +02002302
2303 // If the routing does not change, if an output is routed on a device using HwGain
2304 // (aka setAudioPortConfig) and there are still active clients following different
2305 // volume group(s), force reapply volume
2306 bool requiresVolumeCheck = outputDesc->getActivityCount(clientVolSrc) == 0 &&
2307 outputDesc->useHwGain() && outputDesc->isAnyActive(VOLUME_SOURCE_NONE);
2308
Eric Laurente552edb2014-03-10 17:42:56 -07002309 // delay the device switch by twice the latency because stopOutput() is executed when
2310 // the track stop() command is received and at that time the audio track buffer can
2311 // still contain data that needs to be drained. The latency only covers the audio HAL
2312 // and kernel buffers. Also the latency does not always include additional delay in the
2313 // audio path (audio DSP, CODEC ...)
Francois Gaffie3523ab32021-06-22 13:24:34 +02002314 setOutputDevices(outputDesc, newDevices, false, outputDesc->latency()*2,
2315 nullptr, true /*requiresMuteCheck*/, requiresVolumeCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07002316
2317 // force restoring the device selection on other active outputs if it differs from the
2318 // one being selected for this output
Eric Laurent57de36c2016-09-28 16:59:11 -07002319 uint32_t delayMs = outputDesc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -07002320 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01002321 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07002322 if (desc != outputDesc &&
Eric Laurente552edb2014-03-10 17:42:56 -07002323 desc->isActive() &&
2324 outputDesc->sharesHwModuleWith(desc) &&
François Gaffie11d30102018-11-02 16:09:09 +01002325 (newDevices != desc->devices())) {
2326 DeviceVector newDevices2 = getNewOutputDevices(desc, false /*fromCache*/);
2327 bool force = desc->devices() != newDevices2;
Eric Laurentf3a5a602018-05-22 18:42:55 -07002328
François Gaffie11d30102018-11-02 16:09:09 +01002329 setOutputDevices(desc, newDevices2, force, delayMs);
2330
Eric Laurent57de36c2016-09-28 16:59:11 -07002331 // re-apply device specific volume if not done by setOutputDevice()
2332 if (!force) {
François Gaffie11d30102018-11-02 16:09:09 +01002333 applyStreamVolumes(desc, newDevices2.types(), delayMs);
Eric Laurent57de36c2016-09-28 16:59:11 -07002334 }
Eric Laurente552edb2014-03-10 17:42:56 -07002335 }
2336 }
2337 // update the outputs if stopping one with a stream that can affect notification routing
2338 handleNotificationRoutingForStream(stream);
2339 }
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002340
2341 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
2342 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Jean-Michel Trivi74e01fa2019-02-25 12:18:09 -08002343 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), false, outputDesc);
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002344 }
2345
François Gaffiec005e562018-11-06 15:04:49 +01002346 if (followsSameRouting(client->attributes(), attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07002347 selectOutputForMusicEffects();
2348 }
Eric Laurent96d1dda2022-03-14 17:14:19 +01002349
2350 checkLeBroadcastRoutes(wasLeUnicastActive, outputDesc, outputDesc->latency()*2);
2351
Eric Laurente552edb2014-03-10 17:42:56 -07002352 return NO_ERROR;
2353 } else {
Eric Laurentc75307b2015-03-17 15:29:32 -07002354 ALOGW("stopOutput() refcount is already 0");
Eric Laurente552edb2014-03-10 17:42:56 -07002355 return INVALID_OPERATION;
2356 }
2357}
2358
jiabinbce0c1d2020-10-05 11:20:18 -07002359bool AudioPolicyManager::releaseOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002360{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002361 ALOGV("%s portId %d", __FUNCTION__, portId);
2362
2363 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2364 if (outputDesc == 0) {
Andy Hung39efb7a2018-09-26 15:39:28 -07002365 // If an output descriptor is closed due to a device routing change,
2366 // then there are race conditions with releaseOutput from tracks
2367 // that may be destroyed (with no PlaybackThread) or a PlaybackThread
2368 // destroyed shortly thereafter.
2369 //
2370 // Here we just log a warning, instead of a fatal error.
Eric Laurent8fc147b2018-07-22 19:13:55 -07002371 ALOGW("releaseOutput() no output for client %d", portId);
jiabinbce0c1d2020-10-05 11:20:18 -07002372 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002373 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002374
2375 ALOGV("releaseOutput() %d", outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -07002376
Jaideep Sharma7bf382e2020-11-26 17:07:29 +05302377 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
2378 if (outputDesc->isClientActive(client)) {
2379 ALOGW("releaseOutput() inactivates portId %d in good faith", portId);
2380 stopOutput(portId);
2381 }
2382
Eric Laurent8fc147b2018-07-22 19:13:55 -07002383 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
2384 if (outputDesc->mDirectOpenCount <= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07002385 ALOGW("releaseOutput() invalid open count %d for output %d",
Eric Laurent8fc147b2018-07-22 19:13:55 -07002386 outputDesc->mDirectOpenCount, outputDesc->mIoHandle);
jiabinbce0c1d2020-10-05 11:20:18 -07002387 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002388 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002389 if (--outputDesc->mDirectOpenCount == 0) {
2390 closeOutput(outputDesc->mIoHandle);
Eric Laurentb52c1522014-05-20 11:27:36 -07002391 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07002392 }
2393 }
Jaideep Sharma7bf382e2020-11-26 17:07:29 +05302394
Andy Hung39efb7a2018-09-26 15:39:28 -07002395 outputDesc->removeClient(portId);
jiabinbce0c1d2020-10-05 11:20:18 -07002396 if (outputDesc->mPendingReopenToQueryProfiles && outputDesc->getClientCount() == 0) {
2397 // The output is pending reopened to query dynamic profiles and
2398 // there is no active clients
2399 closeOutput(outputDesc->mIoHandle);
2400 sp<SwAudioOutputDescriptor> newOutputDesc = openOutputWithProfileAndDevice(
2401 outputDesc->mProfile, mEngine->getActiveMediaDevices(mAvailableOutputDevices));
2402 if (newOutputDesc == nullptr) {
2403 ALOGE("%s failed to open output", __func__);
2404 }
2405 return true;
2406 }
2407 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002408}
2409
Eric Laurentcaf7f482014-11-25 17:50:47 -08002410status_t AudioPolicyManager::getInputForAttr(const audio_attributes_t *attr,
2411 audio_io_handle_t *input,
Mikhail Naganov2996f672019-04-18 12:29:59 -07002412 audio_unique_id_t riid,
Eric Laurentcaf7f482014-11-25 17:50:47 -08002413 audio_session_t session,
Svet Ganov3e5f14f2021-05-13 22:51:08 +00002414 const AttributionSourceState& attributionSource,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002415 const audio_config_base_t *config,
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002416 audio_input_flags_t flags,
Eric Laurent2ac76942017-06-22 17:17:09 -07002417 audio_port_handle_t *selectedDeviceId,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002418 input_type_t *inputType,
2419 audio_port_handle_t *portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002420{
François Gaffiec005e562018-11-06 15:04:49 +01002421 ALOGV("%s() source %d, sampling rate %d, format %#x, channel mask %#x, session %d, "
Eric Laurent2f2c1982021-06-02 14:03:11 +02002422 "flags %#x attributes=%s requested device ID %d",
2423 __func__, attr->source, config->sample_rate, config->format, config->channel_mask,
2424 session, flags, toString(*attr).c_str(), *selectedDeviceId);
Eric Laurente552edb2014-03-10 17:42:56 -07002425
Eric Laurentad2e7b92017-09-14 20:06:42 -07002426 status_t status = NO_ERROR;
Francois Gaffie716e1432019-01-14 16:58:59 +01002427 audio_attributes_t attributes = *attr;
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002428 sp<AudioPolicyMix> policyMix;
François Gaffie11d30102018-11-02 16:09:09 +01002429 sp<DeviceDescriptor> device;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002430 sp<AudioInputDescriptor> inputDesc;
2431 sp<RecordClientDescriptor> clientDesc;
2432 audio_port_handle_t requestedDeviceId = *selectedDeviceId;
Svet Ganov3e5f14f2021-05-13 22:51:08 +00002433 uid_t uid = VALUE_OR_RETURN_STATUS(aidl2legacy_int32_t_uid_t(attributionSource.uid));
Eric Laurent8f42ea12018-08-08 09:08:25 -07002434 bool isSoundTrigger;
Eric Laurent8f42ea12018-08-08 09:08:25 -07002435
2436 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
2437 if (*portId != AUDIO_PORT_HANDLE_NONE) {
2438 return INVALID_OPERATION;
2439 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08002440
Francois Gaffie716e1432019-01-14 16:58:59 +01002441 if (attr->source == AUDIO_SOURCE_DEFAULT) {
2442 attributes.source = AUDIO_SOURCE_MIC;
Eric Laurentfe231122017-11-17 17:48:06 -08002443 }
2444
Paul McLean466dc8e2015-04-17 13:15:36 -06002445 // Explicit routing?
Pattydd807582021-11-04 21:01:03 +08002446 sp<DeviceDescriptor> explicitRoutingDevice =
François Gaffie11d30102018-11-02 16:09:09 +01002447 mAvailableInputDevices.getDeviceFromId(*selectedDeviceId);
Paul McLean466dc8e2015-04-17 13:15:36 -06002448
Eric Laurentad2e7b92017-09-14 20:06:42 -07002449 // special case for mmap capture: if an input IO handle is specified, we reuse this input if
2450 // possible
2451 if ((flags & AUDIO_INPUT_FLAG_MMAP_NOIRQ) == AUDIO_INPUT_FLAG_MMAP_NOIRQ &&
2452 *input != AUDIO_IO_HANDLE_NONE) {
2453 ssize_t index = mInputs.indexOfKey(*input);
2454 if (index < 0) {
2455 ALOGW("getInputForAttr() unknown MMAP input %d", *input);
2456 status = BAD_VALUE;
2457 goto error;
2458 }
2459 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002460 RecordClientVector clients = inputDesc->getClientsForSession(session);
2461 if (clients.size() == 0) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07002462 ALOGW("getInputForAttr() unknown session %d on input %d", session, *input);
2463 status = BAD_VALUE;
2464 goto error;
2465 }
2466 // For MMAP mode, the first call to getInputForAttr() is made on behalf of audioflinger.
2467 // The second call is for the first active client and sets the UID. Any further call
Eric Laurent331679c2018-04-16 17:03:16 -07002468 // corresponds to a new client and is only permitted from the same UID.
2469 // If the first UID is silenced, allow a new UID connection and replace with new UID
Eric Laurent8f42ea12018-08-08 09:08:25 -07002470 if (clients.size() > 1) {
2471 for (const auto& client : clients) {
2472 // The client map is ordered by key values (portId) and portIds are allocated
2473 // incrementaly. So the first client in this list is the one opened by audio flinger
2474 // when the mmap stream is created and should be ignored as it does not correspond
2475 // to an actual client
2476 if (client == *clients.cbegin()) {
2477 continue;
2478 }
2479 if (uid != client->uid() && !client->isSilenced()) {
2480 ALOGW("getInputForAttr() bad uid %d for client %d uid %d",
2481 uid, client->portId(), client->uid());
2482 status = INVALID_OPERATION;
2483 goto error;
2484 }
Eric Laurent331679c2018-04-16 17:03:16 -07002485 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002486 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002487 *inputType = API_INPUT_LEGACY;
François Gaffie11d30102018-11-02 16:09:09 +01002488 device = inputDesc->getDevice();
Eric Laurentad2e7b92017-09-14 20:06:42 -07002489
Eric Laurentfecbceb2021-02-09 14:46:43 +01002490 ALOGV("%s reusing MMAP input %d for session %d", __FUNCTION__, *input, session);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002491 goto exit;
Eric Laurentad2e7b92017-09-14 20:06:42 -07002492 }
2493
2494 *input = AUDIO_IO_HANDLE_NONE;
2495 *inputType = API_INPUT_INVALID;
2496
Francois Gaffie716e1432019-01-14 16:58:59 +01002497 if (attributes.source == AUDIO_SOURCE_REMOTE_SUBMIX &&
2498 strncmp(attributes.tags, "addr=", strlen("addr=")) == 0) {
2499 status = mPolicyMixes.getInputMixForAttr(attributes, &policyMix);
Eric Laurentad2e7b92017-09-14 20:06:42 -07002500 if (status != NO_ERROR) {
jiabinc1de2df2019-05-07 14:26:40 -07002501 ALOGW("%s could not find input mix for attr %s",
2502 __func__, toString(attributes).c_str());
Eric Laurentad2e7b92017-09-14 20:06:42 -07002503 goto error;
François Gaffie036e1e92015-03-19 10:16:24 +01002504 }
jiabinc1de2df2019-05-07 14:26:40 -07002505 device = mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2506 String8(attr->tags + strlen("addr=")),
2507 AUDIO_FORMAT_DEFAULT);
2508 if (device == nullptr) {
Kevin Rocard04ed0462019-05-02 17:53:24 -07002509 ALOGW("%s could not find in Remote Submix device for source %d, tags %s",
jiabinc1de2df2019-05-07 14:26:40 -07002510 __func__, attributes.source, attributes.tags);
2511 status = BAD_VALUE;
2512 goto error;
2513 }
2514
Kevin Rocard25f9b052019-02-27 15:08:54 -08002515 if (is_mix_loopback_render(policyMix->mRouteFlags)) {
2516 *inputType = API_INPUT_MIX_PUBLIC_CAPTURE_PLAYBACK;
2517 } else {
2518 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
2519 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002520 } else {
François Gaffie11d30102018-11-02 16:09:09 +01002521 if (explicitRoutingDevice != nullptr) {
2522 device = explicitRoutingDevice;
Eric Laurent97ac8712018-07-27 18:59:02 -07002523 } else {
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01002524 // Prevent from storing invalid requested device id in clients
2525 requestedDeviceId = AUDIO_PORT_HANDLE_NONE;
yuanjiahsu0735bf32021-03-18 08:12:54 +08002526 device = mEngine->getInputDeviceForAttributes(attributes, uid, &policyMix);
yuanjiahsu4069d5d2021-04-19 07:54:27 +08002527 ALOGV_IF(device != nullptr, "%s found device type is 0x%X",
2528 __FUNCTION__, device->type());
Eric Laurent97ac8712018-07-27 18:59:02 -07002529 }
François Gaffie11d30102018-11-02 16:09:09 +01002530 if (device == nullptr) {
Francois Gaffie716e1432019-01-14 16:58:59 +01002531 ALOGW("getInputForAttr() could not find device for source %d", attributes.source);
Eric Laurentad2e7b92017-09-14 20:06:42 -07002532 status = BAD_VALUE;
2533 goto error;
Eric Laurent275e8e92014-11-30 15:14:47 -08002534 }
Alden DSouzab7d20782021-02-08 08:51:42 -08002535 if (device->type() == AUDIO_DEVICE_IN_ECHO_REFERENCE) {
2536 *inputType = API_INPUT_MIX_CAPTURE;
2537 } else if (policyMix) {
François Gaffie11d30102018-11-02 16:09:09 +01002538 ALOG_ASSERT(policyMix->mMixType == MIX_TYPE_RECORDERS, "Invalid Mix Type");
2539 // there is an external policy, but this input is attached to a mix of recorders,
2540 // meaning it receives audio injected into the framework, so the recorder doesn't
2541 // know about it and is therefore considered "legacy"
2542 *inputType = API_INPUT_LEGACY;
2543 } else if (audio_is_remote_submix_device(device->type())) {
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002544 *inputType = API_INPUT_MIX_CAPTURE;
François Gaffie11d30102018-11-02 16:09:09 +01002545 } else if (device->type() == AUDIO_DEVICE_IN_TELEPHONY_RX) {
Eric Laurent82db2692015-08-07 13:59:42 -07002546 *inputType = API_INPUT_TELEPHONY_RX;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002547 } else {
2548 *inputType = API_INPUT_LEGACY;
Eric Laurentc722f302014-12-10 11:21:49 -08002549 }
Ravi Kumar Alamandab367f5b2015-08-25 08:21:37 -07002550
Eric Laurent599c7582015-12-07 18:05:55 -08002551 }
2552
François Gaffiec005e562018-11-06 15:04:49 +01002553 *input = getInputForDevice(device, session, attributes, config, flags, policyMix);
Eric Laurent599c7582015-12-07 18:05:55 -08002554 if (*input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07002555 status = INVALID_OPERATION;
2556 goto error;
Eric Laurent599c7582015-12-07 18:05:55 -08002557 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08002558
Eric Laurent8f42ea12018-08-08 09:08:25 -07002559exit:
2560
François Gaffiec005e562018-11-06 15:04:49 +01002561 *selectedDeviceId = mAvailableInputDevices.contains(device) ?
2562 device->getId() : AUDIO_PORT_HANDLE_NONE;
Eric Laurent2ac76942017-06-22 17:17:09 -07002563
Francois Gaffie716e1432019-01-14 16:58:59 +01002564 isSoundTrigger = attributes.source == AUDIO_SOURCE_HOTWORD &&
Carter Hsud0cce2e2019-05-03 17:36:28 +08002565 mSoundTriggerSessions.indexOfKey(session) >= 0;
jiabin4ef93452019-09-10 14:29:54 -07002566 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002567
Mikhail Naganov2996f672019-04-18 12:29:59 -07002568 clientDesc = new RecordClientDescriptor(*portId, riid, uid, session, attributes, *config,
Francois Gaffie716e1432019-01-14 16:58:59 +01002569 requestedDeviceId, attributes.source, flags,
2570 isSoundTrigger);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002571 inputDesc = mInputs.valueFor(*input);
Andy Hung39efb7a2018-09-26 15:39:28 -07002572 inputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002573
2574 ALOGV("getInputForAttr() returns input %d type %d selectedDeviceId %d for port ID %d",
2575 *input, *inputType, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07002576
Eric Laurent599c7582015-12-07 18:05:55 -08002577 return NO_ERROR;
Eric Laurentad2e7b92017-09-14 20:06:42 -07002578
2579error:
Eric Laurentad2e7b92017-09-14 20:06:42 -07002580 return status;
Eric Laurent599c7582015-12-07 18:05:55 -08002581}
2582
2583
François Gaffie11d30102018-11-02 16:09:09 +01002584audio_io_handle_t AudioPolicyManager::getInputForDevice(const sp<DeviceDescriptor> &device,
Eric Laurent599c7582015-12-07 18:05:55 -08002585 audio_session_t session,
François Gaffiec005e562018-11-06 15:04:49 +01002586 const audio_attributes_t &attributes,
Eric Laurentfe231122017-11-17 17:48:06 -08002587 const audio_config_base_t *config,
Eric Laurent599c7582015-12-07 18:05:55 -08002588 audio_input_flags_t flags,
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002589 const sp<AudioPolicyMix> &policyMix)
Eric Laurent599c7582015-12-07 18:05:55 -08002590{
2591 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
François Gaffiec005e562018-11-06 15:04:49 +01002592 audio_source_t halInputSource = attributes.source;
Eric Laurent599c7582015-12-07 18:05:55 -08002593 bool isSoundTrigger = false;
2594
François Gaffiec005e562018-11-06 15:04:49 +01002595 if (attributes.source == AUDIO_SOURCE_HOTWORD) {
Eric Laurent599c7582015-12-07 18:05:55 -08002596 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
2597 if (index >= 0) {
2598 input = mSoundTriggerSessions.valueFor(session);
2599 isSoundTrigger = true;
2600 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_HW_HOTWORD);
2601 ALOGV("SoundTrigger capture on session %d input %d", session, input);
2602 } else {
2603 halInputSource = AUDIO_SOURCE_VOICE_RECOGNITION;
Eric Laurent5dbe4712014-09-19 19:04:57 -07002604 }
François Gaffiec005e562018-11-06 15:04:49 +01002605 } else if (attributes.source == AUDIO_SOURCE_VOICE_COMMUNICATION &&
Eric Laurentfe231122017-11-17 17:48:06 -08002606 audio_is_linear_pcm(config->format)) {
Haynes Mathew George851d3ff2017-06-19 20:01:57 -07002607 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_VOIP_TX);
Eric Laurent5dbe4712014-09-19 19:04:57 -07002608 }
2609
Carter Hsua3abb402021-10-26 11:11:20 +08002610 if (attributes.source == AUDIO_SOURCE_ULTRASOUND) {
2611 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_ULTRASOUND);
2612 }
2613
Andy Hungf129b032015-04-07 13:45:50 -07002614 // find a compatible input profile (not necessarily identical in parameters)
2615 sp<IOProfile> profile;
Eric Laurentfe231122017-11-17 17:48:06 -08002616 // sampling rate and flags may be updated by getInputProfile
2617 uint32_t profileSamplingRate = (config->sample_rate == 0) ?
2618 SAMPLE_RATE_HZ_DEFAULT : config->sample_rate;
Glenn Kasten730b9262018-03-29 15:01:26 -07002619 audio_format_t profileFormat;
Eric Laurentfe231122017-11-17 17:48:06 -08002620 audio_channel_mask_t profileChannelMask = config->channel_mask;
Andy Hungf129b032015-04-07 13:45:50 -07002621 audio_input_flags_t profileFlags = flags;
2622 for (;;) {
Glenn Kasten730b9262018-03-29 15:01:26 -07002623 profileFormat = config->format; // reset each time through loop, in case it is updated
François Gaffie11d30102018-11-02 16:09:09 +01002624 profile = getInputProfile(device, profileSamplingRate, profileFormat, profileChannelMask,
Andy Hungf129b032015-04-07 13:45:50 -07002625 profileFlags);
2626 if (profile != 0) {
2627 break; // success
Eric Laurent05067782016-06-01 18:27:28 -07002628 } else if (profileFlags & AUDIO_INPUT_FLAG_RAW) {
2629 profileFlags = (audio_input_flags_t) (profileFlags & ~AUDIO_INPUT_FLAG_RAW); // retry
Atneya Nair497fff12022-01-18 16:23:04 -05002630 } else if (profileFlags != AUDIO_INPUT_FLAG_NONE && audio_is_linear_pcm(config->format)) {
Andy Hungf129b032015-04-07 13:45:50 -07002631 profileFlags = AUDIO_INPUT_FLAG_NONE; // retry
2632 } else { // fail
François Gaffie11d30102018-11-02 16:09:09 +01002633 ALOGW("%s could not find profile for device %s, sampling rate %u, format %#x, "
Pattydd807582021-11-04 21:01:03 +08002634 "channel mask 0x%X, flags %#x", __func__, device->toString().c_str(),
François Gaffie11d30102018-11-02 16:09:09 +01002635 config->sample_rate, config->format, config->channel_mask, flags);
Eric Laurent599c7582015-12-07 18:05:55 -08002636 return input;
Eric Laurent5dbe4712014-09-19 19:04:57 -07002637 }
Eric Laurente552edb2014-03-10 17:42:56 -07002638 }
Glenn Kasten05ddca52016-02-11 08:17:12 -08002639 // Pick input sampling rate if not specified by client
Eric Laurentfe231122017-11-17 17:48:06 -08002640 uint32_t samplingRate = config->sample_rate;
Glenn Kasten05ddca52016-02-11 08:17:12 -08002641 if (samplingRate == 0) {
2642 samplingRate = profileSamplingRate;
2643 }
Eric Laurente552edb2014-03-10 17:42:56 -07002644
Eric Laurent322b4d22015-04-03 15:57:54 -07002645 if (profile->getModuleHandle() == 0) {
2646 ALOGE("getInputForAttr(): HW module %s not opened", profile->getModuleName());
Eric Laurent599c7582015-12-07 18:05:55 -08002647 return input;
Eric Laurentcf2c0212014-07-25 16:20:43 -07002648 }
2649
Eric Laurentec376dc2021-04-08 20:41:22 +02002650 // Reuse an already opened input if a client with the same session ID already exists
2651 // on that input
2652 for (size_t i = 0; i < mInputs.size(); i++) {
2653 sp <AudioInputDescriptor> desc = mInputs.valueAt(i);
2654 if (desc->mProfile != profile) {
2655 continue;
2656 }
2657 RecordClientVector clients = desc->clientsList();
2658 for (const auto &client : clients) {
2659 if (session == client->session()) {
2660 return desc->mIoHandle;
2661 }
2662 }
2663 }
2664
Eric Laurent3974e3b2017-12-07 17:58:43 -08002665 if (!profile->canOpenNewIo()) {
Eric Laurent4eb58f12018-12-07 16:41:02 -08002666 for (size_t i = 0; i < mInputs.size(); ) {
Eric Laurentc529cf62020-04-17 18:19:10 -07002667 sp<AudioInputDescriptor> desc = mInputs.valueAt(i);
Eric Laurent4eb58f12018-12-07 16:41:02 -08002668 if (desc->mProfile != profile) {
Carter Hsu9a645a92019-05-15 12:15:32 +08002669 i++;
Eric Laurent4eb58f12018-12-07 16:41:02 -08002670 continue;
2671 }
2672 // if sound trigger, reuse input if used by other sound trigger on same session
2673 // else
2674 // reuse input if active client app is not in IDLE state
2675 //
2676 RecordClientVector clients = desc->clientsList();
2677 bool doClose = false;
2678 for (const auto& client : clients) {
2679 if (isSoundTrigger != client->isSoundTrigger()) {
2680 continue;
2681 }
2682 if (client->isSoundTrigger()) {
2683 if (session == client->session()) {
2684 return desc->mIoHandle;
2685 }
2686 continue;
2687 }
2688 if (client->active() && client->appState() != APP_STATE_IDLE) {
2689 return desc->mIoHandle;
2690 }
2691 doClose = true;
2692 }
2693 if (doClose) {
2694 closeInput(desc->mIoHandle);
2695 } else {
2696 i++;
2697 }
2698 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002699 }
2700
Eric Laurentfe231122017-11-17 17:48:06 -08002701 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07002702
Eric Laurentfe231122017-11-17 17:48:06 -08002703 audio_config_t lConfig = AUDIO_CONFIG_INITIALIZER;
2704 lConfig.sample_rate = profileSamplingRate;
2705 lConfig.channel_mask = profileChannelMask;
2706 lConfig.format = profileFormat;
Eric Laurente3014102017-05-03 11:15:43 -07002707
François Gaffie11d30102018-11-02 16:09:09 +01002708 status_t status = inputDesc->open(&lConfig, device, halInputSource, profileFlags, &input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07002709
2710 // only accept input with the exact requested set of parameters
Eric Laurent599c7582015-12-07 18:05:55 -08002711 if (status != NO_ERROR || input == AUDIO_IO_HANDLE_NONE ||
Eric Laurentfe231122017-11-17 17:48:06 -08002712 (profileSamplingRate != lConfig.sample_rate) ||
2713 !audio_formats_match(profileFormat, lConfig.format) ||
2714 (profileChannelMask != lConfig.channel_mask)) {
2715 ALOGW("getInputForAttr() failed opening input: sampling rate %d"
Glenn Kasten49f36ba2017-12-06 13:02:02 -08002716 ", format %#x, channel mask %#x",
Eric Laurentfe231122017-11-17 17:48:06 -08002717 profileSamplingRate, profileFormat, profileChannelMask);
Eric Laurent599c7582015-12-07 18:05:55 -08002718 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfe231122017-11-17 17:48:06 -08002719 inputDesc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07002720 }
Eric Laurent599c7582015-12-07 18:05:55 -08002721 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07002722 }
2723
Eric Laurentc722f302014-12-10 11:21:49 -08002724 inputDesc->mPolicyMix = policyMix;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002725
Eric Laurent599c7582015-12-07 18:05:55 -08002726 addInput(input, inputDesc);
Eric Laurentb52c1522014-05-20 11:27:36 -07002727 mpClientInterface->onAudioPortListUpdate();
Paul McLean466dc8e2015-04-17 13:15:36 -06002728
Eric Laurent599c7582015-12-07 18:05:55 -08002729 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07002730}
2731
Eric Laurent4eb58f12018-12-07 16:41:02 -08002732status_t AudioPolicyManager::startInput(audio_port_handle_t portId)
Eric Laurentbb948092017-01-23 18:33:30 -08002733{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002734 ALOGV("%s portId %d", __FUNCTION__, portId);
2735
2736 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2737 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002738 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurentd52a28c2020-08-21 17:10:39 -07002739 return DEAD_OBJECT;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002740 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002741 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07002742 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002743 if (client->active()) {
2744 ALOGW("%s input %d client %d already started", __FUNCTION__, input, client->portId());
2745 return INVALID_OPERATION;
Eric Laurent4dc68062014-07-28 17:26:49 -07002746 }
2747
Eric Laurent8f42ea12018-08-08 09:08:25 -07002748 audio_session_t session = client->session();
2749
Eric Laurent4eb58f12018-12-07 16:41:02 -08002750 ALOGV("%s input:%d, session:%d)", __FUNCTION__, input, session);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002751
Eric Laurent4eb58f12018-12-07 16:41:02 -08002752 Vector<sp<AudioInputDescriptor>> activeInputs = mInputs.getActiveInputs();
Eric Laurent74708e72017-04-07 17:13:42 -07002753
Eric Laurent4eb58f12018-12-07 16:41:02 -08002754 status_t status = inputDesc->start();
2755 if (status != NO_ERROR) {
2756 return status;
Eric Laurent74708e72017-04-07 17:13:42 -07002757 }
Eric Laurente552edb2014-03-10 17:42:56 -07002758
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002759 // increment activity count before calling getNewInputDevice() below as only active sessions
Eric Laurent313d1e72016-01-29 09:56:57 -08002760 // are considered for device selection
Eric Laurent8f42ea12018-08-08 09:08:25 -07002761 inputDesc->setClientActive(client, true);
Eric Laurent313d1e72016-01-29 09:56:57 -08002762
Eric Laurent8f42ea12018-08-08 09:08:25 -07002763 // indicate active capture to sound trigger service if starting capture from a mic on
2764 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01002765 sp<DeviceDescriptor> device = getNewInputDevice(inputDesc);
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002766 if (device != nullptr) {
2767 status = setInputDevice(input, device, true /* force */);
2768 } else {
2769 ALOGW("%s no new input device can be found for descriptor %d",
2770 __FUNCTION__, inputDesc->getId());
2771 status = BAD_VALUE;
2772 }
Eric Laurente552edb2014-03-10 17:42:56 -07002773
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002774 if (status == NO_ERROR && inputDesc->activeCount() == 1) {
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002775 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002776 // if input maps to a dynamic policy with an activity listener, notify of state change
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002777 if ((policyMix != nullptr)
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002778 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
2779 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
Eric Laurent8f42ea12018-08-08 09:08:25 -07002780 MIX_STATE_MIXING);
Eric Laurent733ce942017-12-07 12:18:25 -08002781 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002782
François Gaffie11d30102018-11-02 16:09:09 +01002783 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
2784 if (primaryInputDevices.contains(device) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07002785 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 1) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07002786 mpClientInterface->setSoundTriggerCaptureState(true);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002787 }
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002788
Eric Laurent8f42ea12018-08-08 09:08:25 -07002789 // automatically enable the remote submix output when input is started if not
2790 // used by a policy mix of type MIX_TYPE_RECORDERS
2791 // For remote submix (a virtual device), we open only one input per capture request.
François Gaffie11d30102018-11-02 16:09:09 +01002792 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002793 String8 address = String8("");
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002794 if (policyMix == nullptr) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002795 address = String8("0");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002796 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
2797 address = policyMix->mDeviceAddress;
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002798 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07002799 if (address != "") {
2800 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2801 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002802 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurentc722f302014-12-10 11:21:49 -08002803 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07002804 }
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002805 } else if (status != NO_ERROR) {
2806 // Restore client activity state.
2807 inputDesc->setClientActive(client, false);
2808 inputDesc->stop();
Eric Laurente552edb2014-03-10 17:42:56 -07002809 }
2810
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002811 ALOGV("%s input %d source = %d status = %d exit",
2812 __FUNCTION__, input, client->source(), status);
Eric Laurente552edb2014-03-10 17:42:56 -07002813
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002814 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07002815}
2816
Eric Laurent8fc147b2018-07-22 19:13:55 -07002817status_t AudioPolicyManager::stopInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002818{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002819 ALOGV("%s portId %d", __FUNCTION__, portId);
2820
2821 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2822 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002823 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002824 return BAD_VALUE;
2825 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002826 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07002827 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002828 if (!client->active()) {
2829 ALOGW("%s input %d client %d already stopped", __FUNCTION__, input, client->portId());
Eric Laurente552edb2014-03-10 17:42:56 -07002830 return INVALID_OPERATION;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002831 }
Carter Hsue6139d52021-07-08 10:30:20 +08002832 auto old_source = inputDesc->source();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002833 inputDesc->setClientActive(client, false);
Paul McLean466dc8e2015-04-17 13:15:36 -06002834
Eric Laurent8f42ea12018-08-08 09:08:25 -07002835 inputDesc->stop();
2836 if (inputDesc->isActive()) {
Carter Hsue6139d52021-07-08 10:30:20 +08002837 auto current_source = inputDesc->source();
2838 setInputDevice(input, getNewInputDevice(inputDesc),
2839 old_source != current_source /* force */);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002840 } else {
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002841 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002842 // if input maps to a dynamic policy with an activity listener, notify of state change
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002843 if ((policyMix != nullptr)
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002844 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
2845 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
Eric Laurent8f42ea12018-08-08 09:08:25 -07002846 MIX_STATE_IDLE);
Eric Laurent84332aa2016-01-28 22:19:18 +00002847 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07002848
2849 // automatically disable the remote submix output when input is stopped if not
2850 // used by a policy mix of type MIX_TYPE_RECORDERS
François Gaffie11d30102018-11-02 16:09:09 +01002851 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002852 String8 address = String8("");
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002853 if (policyMix == nullptr) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002854 address = String8("0");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002855 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
2856 address = policyMix->mDeviceAddress;
Eric Laurent8f42ea12018-08-08 09:08:25 -07002857 }
2858 if (address != "") {
2859 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2860 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002861 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002862 }
2863 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07002864 resetInputDevice(input);
2865
2866 // indicate inactive capture to sound trigger service if stopping capture from a mic on
2867 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01002868 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
2869 if (primaryInputDevices.contains(inputDesc->getDevice()) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07002870 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07002871 mpClientInterface->setSoundTriggerCaptureState(false);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002872 }
2873 inputDesc->clearPreemptedSessions();
Eric Laurente552edb2014-03-10 17:42:56 -07002874 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002875 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07002876}
2877
Eric Laurent8fc147b2018-07-22 19:13:55 -07002878void AudioPolicyManager::releaseInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002879{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002880 ALOGV("%s portId %d", __FUNCTION__, portId);
2881
2882 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2883 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002884 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002885 return;
2886 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002887 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002888 audio_io_handle_t input = inputDesc->mIoHandle;
2889
Eric Laurent8f42ea12018-08-08 09:08:25 -07002890 ALOGV("%s %d", __FUNCTION__, input);
Paul McLean466dc8e2015-04-17 13:15:36 -06002891
Andy Hung39efb7a2018-09-26 15:39:28 -07002892 inputDesc->removeClient(portId);
Eric Laurent599c7582015-12-07 18:05:55 -08002893
Andy Hung39efb7a2018-09-26 15:39:28 -07002894 if (inputDesc->getClientCount() > 0) {
2895 ALOGV("%s(%d) %zu clients remaining", __func__, portId, inputDesc->getClientCount());
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002896 return;
2897 }
2898
Eric Laurent05b90f82014-08-27 15:32:29 -07002899 closeInput(input);
Eric Laurentb52c1522014-05-20 11:27:36 -07002900 mpClientInterface->onAudioPortListUpdate();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002901 ALOGV("%s exit", __FUNCTION__);
Eric Laurente552edb2014-03-10 17:42:56 -07002902}
2903
Eric Laurent8f42ea12018-08-08 09:08:25 -07002904void AudioPolicyManager::closeActiveClients(const sp<AudioInputDescriptor>& input)
Eric Laurent8fc147b2018-07-22 19:13:55 -07002905{
Eric Laurent8f42ea12018-08-08 09:08:25 -07002906 RecordClientVector clients = input->clientsList(true);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002907
2908 for (const auto& client : clients) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002909 closeClient(client->portId());
Eric Laurent8fc147b2018-07-22 19:13:55 -07002910 }
2911}
2912
Eric Laurent8f42ea12018-08-08 09:08:25 -07002913void AudioPolicyManager::closeClient(audio_port_handle_t portId)
2914{
2915 stopInput(portId);
2916 releaseInput(portId);
2917}
Eric Laurent8fc147b2018-07-22 19:13:55 -07002918
Eric Laurent0dd51852019-04-19 18:18:58 -07002919void AudioPolicyManager::checkCloseInputs() {
2920 // After connecting or disconnecting an input device, close input if:
2921 // - it has no client (was just opened to check profile) OR
2922 // - none of its supported devices are connected anymore OR
2923 // - one of its clients cannot be routed to one of its supported
2924 // devices anymore. Otherwise update device selection
2925 std::vector<audio_io_handle_t> inputsToClose;
2926 for (size_t i = 0; i < mInputs.size(); i++) {
2927 const sp<AudioInputDescriptor> input = mInputs.valueAt(i);
2928 if (input->clientsList().size() == 0
Eric Laurent85732f42020-03-19 11:31:10 -07002929 || !mAvailableInputDevices.containsAtLeastOne(input->supportedDevices())) {
Eric Laurent0dd51852019-04-19 18:18:58 -07002930 inputsToClose.push_back(mInputs.keyAt(i));
2931 } else {
2932 bool close = false;
2933 for (const auto& client : input->clientsList()) {
2934 sp<DeviceDescriptor> device =
yuanjiahsu0735bf32021-03-18 08:12:54 +08002935 mEngine->getInputDeviceForAttributes(client->attributes(), client->uid());
Eric Laurent0dd51852019-04-19 18:18:58 -07002936 if (!input->supportedDevices().contains(device)) {
2937 close = true;
2938 break;
2939 }
2940 }
2941 if (close) {
2942 inputsToClose.push_back(mInputs.keyAt(i));
2943 } else {
2944 setInputDevice(input->mIoHandle, getNewInputDevice(input));
2945 }
2946 }
2947 }
2948
2949 for (const audio_io_handle_t handle : inputsToClose) {
2950 ALOGV("%s closing input %d", __func__, handle);
2951 closeInput(handle);
Eric Laurent05b90f82014-08-27 15:32:29 -07002952 }
Eric Laurentd4692962014-05-05 18:13:44 -07002953}
2954
François Gaffie251c7f02018-11-07 10:41:08 +01002955void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream, int indexMin, int indexMax)
Eric Laurente552edb2014-03-10 17:42:56 -07002956{
2957 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08002958 if (indexMin < 0 || indexMax < 0) {
2959 ALOGE("%s for stream %d: invalid min %d or max %d", __func__, stream , indexMin, indexMax);
2960 return;
2961 }
Eric Laurentf5aa58d2019-02-22 18:20:11 -08002962 getVolumeCurves(stream).initVolume(indexMin, indexMax);
Eric Laurent28d09f02016-03-08 10:43:05 -08002963
2964 // initialize other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08002965 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
2966 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002967 continue;
2968 }
Eric Laurentf5aa58d2019-02-22 18:20:11 -08002969 getVolumeCurves((audio_stream_type_t)curStream).initVolume(indexMin, indexMax);
Eric Laurent223fd5c2014-11-11 13:43:36 -08002970 }
Eric Laurente552edb2014-03-10 17:42:56 -07002971}
2972
Eric Laurente0720872014-03-11 09:30:41 -07002973status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
François Gaffie53615e22015-03-19 09:24:12 +01002974 int index,
2975 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07002976{
François Gaffieaaac0fd2018-11-22 17:56:39 +01002977 auto attributes = mEngine->getAttributesForStreamType(stream);
Eric Laurent242a9f82020-03-23 15:57:04 -07002978 if (attributes == AUDIO_ATTRIBUTES_INITIALIZER) {
2979 ALOGW("%s: no group for stream %s, bailing out", __func__, toString(stream).c_str());
2980 return NO_ERROR;
2981 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01002982 ALOGV("%s: stream %s attributes=%s", __func__,
2983 toString(stream).c_str(), toString(attributes).c_str());
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002984 return setVolumeIndexForAttributes(attributes, index, device);
Eric Laurente552edb2014-03-10 17:42:56 -07002985}
2986
Eric Laurente0720872014-03-11 09:30:41 -07002987status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
François Gaffieaaac0fd2018-11-22 17:56:39 +01002988 int *index,
2989 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07002990{
François Gaffiec005e562018-11-06 15:04:49 +01002991 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
2992 // stream by the engine.
jiabin9a3361e2019-10-01 09:38:30 -07002993 DeviceTypeSet deviceTypes = {device};
Eric Laurent5a2b6292016-04-14 18:05:57 -07002994 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
jiabin9a3361e2019-10-01 09:38:30 -07002995 deviceTypes = mEngine->getOutputDevicesForStream(
2996 stream, true /*fromCache*/).types();
Eric Laurente552edb2014-03-10 17:42:56 -07002997 }
jiabin9a3361e2019-10-01 09:38:30 -07002998 return getVolumeIndex(getVolumeCurves(stream), *index, deviceTypes);
Eric Laurente552edb2014-03-10 17:42:56 -07002999}
3000
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003001status_t AudioPolicyManager::setVolumeIndexForAttributes(const audio_attributes_t &attributes,
François Gaffiecfe17322018-11-07 13:41:29 +01003002 int index,
3003 audio_devices_t device)
3004{
3005 // Get Volume group matching the Audio Attributes
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003006 auto group = mEngine->getVolumeGroupForAttributes(attributes);
3007 if (group == VOLUME_GROUP_NONE) {
3008 ALOGD("%s: no group matching with %s", __FUNCTION__, toString(attributes).c_str());
François Gaffiecfe17322018-11-07 13:41:29 +01003009 return BAD_VALUE;
3010 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003011 ALOGV("%s: group %d matching with %s", __FUNCTION__, group, toString(attributes).c_str());
François Gaffiecfe17322018-11-07 13:41:29 +01003012 status_t status = NO_ERROR;
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003013 IVolumeCurves &curves = getVolumeCurves(attributes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01003014 VolumeSource vs = toVolumeSource(group);
3015 product_strategy_t strategy = mEngine->getProductStrategyForAttributes(attributes);
3016
3017 status = setVolumeCurveIndex(index, device, curves);
3018 if (status != NO_ERROR) {
3019 ALOGE("%s failed to set curve index for group %d device 0x%X", __func__, group, device);
3020 return status;
3021 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003022
jiabin9a3361e2019-10-01 09:38:30 -07003023 DeviceTypeSet curSrcDevices;
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003024 auto curCurvAttrs = curves.getAttributes();
3025 if (!curCurvAttrs.empty() && curCurvAttrs.front() != defaultAttr) {
3026 auto attr = curCurvAttrs.front();
jiabin9a3361e2019-10-01 09:38:30 -07003027 curSrcDevices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false).types();
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003028 } else if (!curves.getStreamTypes().empty()) {
3029 auto stream = curves.getStreamTypes().front();
jiabin9a3361e2019-10-01 09:38:30 -07003030 curSrcDevices = mEngine->getOutputDevicesForStream(stream, false).types();
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003031 } else {
3032 ALOGE("%s: Invalid src %d: no valid attributes nor stream",__func__, vs);
3033 return BAD_VALUE;
3034 }
jiabin9a3361e2019-10-01 09:38:30 -07003035 audio_devices_t curSrcDevice = Volume::getDeviceForVolume(curSrcDevices);
3036 resetDeviceTypes(curSrcDevices, curSrcDevice);
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003037
François Gaffiecfe17322018-11-07 13:41:29 +01003038 // update volume on all outputs and streams matching the following:
3039 // - The requested stream (or a stream matching for volume control) is active on the output
3040 // - The device (or devices) selected by the engine for this stream includes
3041 // the requested device
3042 // - For non default requested device, currently selected device on the output is either the
3043 // requested device or one of the devices selected by the engine for this stream
3044 // - For default requested device (AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME), apply volume only if
3045 // no specific device volume value exists for currently selected device.
François Gaffieaaac0fd2018-11-22 17:56:39 +01003046 for (size_t i = 0; i < mOutputs.size(); i++) {
3047 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
jiabin9a3361e2019-10-01 09:38:30 -07003048 DeviceTypeSet curDevices = desc->devices().types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01003049
jiabin9a3361e2019-10-01 09:38:30 -07003050 if (curDevices.erase(AUDIO_DEVICE_OUT_SPEAKER_SAFE)) {
3051 curDevices.insert(AUDIO_DEVICE_OUT_SPEAKER);
Robert Lee5e66e792019-04-03 18:37:15 +08003052 }
François Gaffieed91f582020-01-31 10:35:37 +01003053 if (!(desc->isActive(vs) || isInCall())) {
3054 continue;
3055 }
3056 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME &&
3057 curDevices.find(device) == curDevices.end()) {
3058 continue;
3059 }
3060 bool applyVolume = false;
3061 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
3062 curSrcDevices.insert(device);
3063 applyVolume = (curSrcDevices.find(
3064 Volume::getDeviceForVolume(curDevices)) != curSrcDevices.end());
3065 } else {
3066 applyVolume = !curves.hasVolumeIndexForDevice(curSrcDevice);
3067 }
3068 if (!applyVolume) {
3069 continue; // next output
3070 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01003071 // Inter / intra volume group priority management: Loop on strategies arranged by priority
3072 // If a higher priority strategy is active, and the output is routed to a device with a
3073 // HW Gain management, do not change the volume
François Gaffieaaac0fd2018-11-22 17:56:39 +01003074 if (desc->useHwGain()) {
François Gaffieed91f582020-01-31 10:35:37 +01003075 applyVolume = false;
Francois Gaffie593634d2021-06-22 13:31:31 +02003076 // If the volume source is active with higher priority source, ensure at least Sw Muted
3077 desc->setSwMute((index == 0), vs, curves.getStreamTypes(), curDevices, 0 /*delayMs*/);
François Gaffieaaac0fd2018-11-22 17:56:39 +01003078 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
3079 auto activeClients = desc->clientsList(true /*activeOnly*/, productStrategy,
3080 false /*preferredDevice*/);
3081 if (activeClients.empty()) {
3082 continue;
3083 }
3084 bool isPreempted = false;
3085 bool isHigherPriority = productStrategy < strategy;
3086 for (const auto &client : activeClients) {
3087 if (isHigherPriority && (client->volumeSource() != vs)) {
3088 ALOGV("%s: Strategy=%d (\nrequester:\n"
3089 " group %d, volumeGroup=%d attributes=%s)\n"
3090 " higher priority source active:\n"
3091 " volumeGroup=%d attributes=%s) \n"
3092 " on output %zu, bailing out", __func__, productStrategy,
3093 group, group, toString(attributes).c_str(),
3094 client->volumeSource(), toString(client->attributes()).c_str(), i);
3095 applyVolume = false;
3096 isPreempted = true;
3097 break;
3098 }
3099 // However, continue for loop to ensure no higher prio clients running on output
3100 if (client->volumeSource() == vs) {
3101 applyVolume = true;
3102 }
3103 }
3104 if (isPreempted || applyVolume) {
3105 break;
3106 }
3107 }
3108 if (!applyVolume) {
3109 continue; // next output
3110 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01003111 }
François Gaffieed91f582020-01-31 10:35:37 +01003112 //FIXME: workaround for truncated touch sounds
3113 // delayed volume change for system stream to be removed when the problem is
3114 // handled by system UI
3115 status_t volStatus = checkAndSetVolume(
3116 curves, vs, index, desc, curDevices,
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003117 ((vs == toVolumeSource(AUDIO_STREAM_SYSTEM, false))?
François Gaffieed91f582020-01-31 10:35:37 +01003118 TOUCH_SOUND_FIXED_DELAY_MS : 0));
3119 if (volStatus != NO_ERROR) {
3120 status = volStatus;
François Gaffieaaac0fd2018-11-22 17:56:39 +01003121 }
3122 }
François Gaffiecfe17322018-11-07 13:41:29 +01003123 mpClientInterface->onAudioVolumeGroupChanged(group, 0 /*flags*/);
3124 return status;
3125}
3126
François Gaffieaaac0fd2018-11-22 17:56:39 +01003127status_t AudioPolicyManager::setVolumeCurveIndex(int index,
François Gaffiecfe17322018-11-07 13:41:29 +01003128 audio_devices_t device,
3129 IVolumeCurves &volumeCurves)
3130{
3131 // VOICE_CALL stream has minVolumeIndex > 0 but can be muted directly by an
3132 // app that has MODIFY_PHONE_STATE permission.
François Gaffieaaac0fd2018-11-22 17:56:39 +01003133 bool hasVoice = hasVoiceStream(volumeCurves.getStreamTypes());
3134 if (((index < volumeCurves.getVolumeIndexMin()) && !(hasVoice && index == 0)) ||
François Gaffiecfe17322018-11-07 13:41:29 +01003135 (index > volumeCurves.getVolumeIndexMax())) {
3136 ALOGD("%s: wrong index %d min=%d max=%d", __FUNCTION__, index,
3137 volumeCurves.getVolumeIndexMin(), volumeCurves.getVolumeIndexMax());
3138 return BAD_VALUE;
3139 }
3140 if (!audio_is_output_device(device)) {
3141 return BAD_VALUE;
3142 }
3143
3144 // Force max volume if stream cannot be muted
3145 if (!volumeCurves.canBeMuted()) index = volumeCurves.getVolumeIndexMax();
3146
François Gaffieaaac0fd2018-11-22 17:56:39 +01003147 ALOGV("%s device %08x, index %d", __FUNCTION__ , device, index);
François Gaffiecfe17322018-11-07 13:41:29 +01003148 volumeCurves.addCurrentVolumeIndex(device, index);
3149 return NO_ERROR;
3150}
3151
3152status_t AudioPolicyManager::getVolumeIndexForAttributes(const audio_attributes_t &attr,
3153 int &index,
3154 audio_devices_t device)
3155{
3156 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
3157 // stream by the engine.
jiabin9a3361e2019-10-01 09:38:30 -07003158 DeviceTypeSet deviceTypes = {device};
François Gaffiecfe17322018-11-07 13:41:29 +01003159 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
Mikhail Naganovbb990f22022-06-15 00:46:43 +00003160 deviceTypes = mEngine->getOutputDevicesForAttributes(
jiabin9a3361e2019-10-01 09:38:30 -07003161 attr, nullptr, true /*fromCache*/).types();
François Gaffiecfe17322018-11-07 13:41:29 +01003162 }
jiabin9a3361e2019-10-01 09:38:30 -07003163 return getVolumeIndex(getVolumeCurves(attr), index, deviceTypes);
François Gaffiecfe17322018-11-07 13:41:29 +01003164}
3165
3166status_t AudioPolicyManager::getVolumeIndex(const IVolumeCurves &curves,
3167 int &index,
jiabin9a3361e2019-10-01 09:38:30 -07003168 const DeviceTypeSet& deviceTypes) const
François Gaffiecfe17322018-11-07 13:41:29 +01003169{
Mikhail Naganovbb990f22022-06-15 00:46:43 +00003170 if (!isSingleDeviceType(deviceTypes, audio_is_output_device)) {
François Gaffiecfe17322018-11-07 13:41:29 +01003171 return BAD_VALUE;
3172 }
jiabin9a3361e2019-10-01 09:38:30 -07003173 index = curves.getVolumeIndex(deviceTypes);
3174 ALOGV("%s: device %s index %d", __FUNCTION__, dumpDeviceTypes(deviceTypes).c_str(), index);
François Gaffiecfe17322018-11-07 13:41:29 +01003175 return NO_ERROR;
3176}
3177
3178status_t AudioPolicyManager::getMinVolumeIndexForAttributes(const audio_attributes_t &attr,
3179 int &index)
3180{
3181 index = getVolumeCurves(attr).getVolumeIndexMin();
3182 return NO_ERROR;
3183}
3184
3185status_t AudioPolicyManager::getMaxVolumeIndexForAttributes(const audio_attributes_t &attr,
3186 int &index)
3187{
3188 index = getVolumeCurves(attr).getVolumeIndexMax();
3189 return NO_ERROR;
3190}
3191
Eric Laurent36829f92017-04-07 19:04:42 -07003192audio_io_handle_t AudioPolicyManager::selectOutputForMusicEffects()
Eric Laurente552edb2014-03-10 17:42:56 -07003193{
3194 // select one output among several suitable for global effects.
3195 // The priority is as follows:
3196 // 1: An offloaded output. If the effect ends up not being offloadable,
3197 // AudioFlinger will invalidate the track and the offloaded output
3198 // will be closed causing the effect to be moved to a PCM output.
3199 // 2: A deep buffer output
Eric Laurent36829f92017-04-07 19:04:42 -07003200 // 3: The primary output
3201 // 4: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07003202
François Gaffiec005e562018-11-06 15:04:49 +01003203 DeviceVector devices = mEngine->getOutputDevicesForAttributes(
3204 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
François Gaffie11d30102018-11-02 16:09:09 +01003205 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07003206
Eric Laurent36829f92017-04-07 19:04:42 -07003207 if (outputs.size() == 0) {
3208 return AUDIO_IO_HANDLE_NONE;
3209 }
Eric Laurente552edb2014-03-10 17:42:56 -07003210
Eric Laurent36829f92017-04-07 19:04:42 -07003211 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
3212 bool activeOnly = true;
3213
3214 while (output == AUDIO_IO_HANDLE_NONE) {
3215 audio_io_handle_t outputOffloaded = AUDIO_IO_HANDLE_NONE;
3216 audio_io_handle_t outputDeepBuffer = AUDIO_IO_HANDLE_NONE;
3217 audio_io_handle_t outputPrimary = AUDIO_IO_HANDLE_NONE;
3218
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003219 for (audio_io_handle_t output : outputs) {
3220 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
Eric Laurent83d17c22019-04-02 17:10:01 -07003221 if (activeOnly && !desc->isActive(toVolumeSource(AUDIO_STREAM_MUSIC))) {
Eric Laurent36829f92017-04-07 19:04:42 -07003222 continue;
3223 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003224 ALOGV("selectOutputForMusicEffects activeOnly %d output %d flags 0x%08x",
3225 activeOnly, output, desc->mFlags);
Eric Laurent36829f92017-04-07 19:04:42 -07003226 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003227 outputOffloaded = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003228 }
3229 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003230 outputDeepBuffer = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003231 }
3232 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003233 outputPrimary = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003234 }
3235 }
3236 if (outputOffloaded != AUDIO_IO_HANDLE_NONE) {
3237 output = outputOffloaded;
3238 } else if (outputDeepBuffer != AUDIO_IO_HANDLE_NONE) {
3239 output = outputDeepBuffer;
3240 } else if (outputPrimary != AUDIO_IO_HANDLE_NONE) {
3241 output = outputPrimary;
3242 } else {
3243 output = outputs[0];
3244 }
3245 activeOnly = false;
3246 }
3247
3248 if (output != mMusicEffectOutput) {
Eric Laurent6c796322019-04-09 14:13:17 -07003249 mEffects.moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output);
Eric Laurent36829f92017-04-07 19:04:42 -07003250 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output);
3251 mMusicEffectOutput = output;
3252 }
3253
3254 ALOGV("selectOutputForMusicEffects selected output %d", output);
Eric Laurente552edb2014-03-10 17:42:56 -07003255 return output;
3256}
3257
Eric Laurent36829f92017-04-07 19:04:42 -07003258audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc __unused)
3259{
3260 return selectOutputForMusicEffects();
3261}
3262
Eric Laurente0720872014-03-11 09:30:41 -07003263status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07003264 audio_io_handle_t io,
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08003265 product_strategy_t strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07003266 int session,
3267 int id)
3268{
Eric Laurentb82e6b72019-11-22 17:25:04 -08003269 if (session != AUDIO_SESSION_DEVICE) {
3270 ssize_t index = mOutputs.indexOfKey(io);
Eric Laurente552edb2014-03-10 17:42:56 -07003271 if (index < 0) {
Eric Laurentb82e6b72019-11-22 17:25:04 -08003272 index = mInputs.indexOfKey(io);
3273 if (index < 0) {
3274 ALOGW("registerEffect() unknown io %d", io);
3275 return INVALID_OPERATION;
3276 }
Eric Laurente552edb2014-03-10 17:42:56 -07003277 }
3278 }
Eric Laurentbf8f69f2022-03-25 17:48:38 +01003279 bool isMusicEffect = (session != AUDIO_SESSION_OUTPUT_STAGE)
3280 && ((strategy == streamToStrategy(AUDIO_STREAM_MUSIC)
3281 || strategy == PRODUCT_STRATEGY_NONE));
3282 return mEffects.registerEffect(desc, io, session, id, isMusicEffect);
Eric Laurente552edb2014-03-10 17:42:56 -07003283}
3284
Eric Laurentc241b0d2018-11-28 09:08:49 -08003285status_t AudioPolicyManager::unregisterEffect(int id)
3286{
3287 if (mEffects.getEffect(id) == nullptr) {
3288 return INVALID_OPERATION;
3289 }
Eric Laurentc241b0d2018-11-28 09:08:49 -08003290 if (mEffects.isEffectEnabled(id)) {
3291 ALOGW("%s effect %d enabled", __FUNCTION__, id);
3292 setEffectEnabled(id, false);
3293 }
3294 return mEffects.unregisterEffect(id);
3295}
3296
3297status_t AudioPolicyManager::setEffectEnabled(int id, bool enabled)
3298{
3299 sp<EffectDescriptor> effect = mEffects.getEffect(id);
3300 if (effect == nullptr) {
3301 return INVALID_OPERATION;
3302 }
3303
3304 status_t status = mEffects.setEffectEnabled(id, enabled);
3305 if (status == NO_ERROR) {
3306 mInputs.trackEffectEnabled(effect, enabled);
3307 }
3308 return status;
3309}
3310
Eric Laurent6c796322019-04-09 14:13:17 -07003311
3312status_t AudioPolicyManager::moveEffectsToIo(const std::vector<int>& ids, audio_io_handle_t io)
3313{
3314 mEffects.moveEffects(ids, io);
3315 return NO_ERROR;
3316}
3317
Eric Laurentc75307b2015-03-17 15:29:32 -07003318bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
3319{
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003320 auto vs = toVolumeSource(stream, false);
3321 return vs != VOLUME_SOURCE_NONE ? mOutputs.isActive(vs, inPastMs) : false;
Eric Laurentc75307b2015-03-17 15:29:32 -07003322}
3323
3324bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream, uint32_t inPastMs) const
3325{
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003326 auto vs = toVolumeSource(stream, false);
3327 return vs != VOLUME_SOURCE_NONE ? mOutputs.isActiveRemotely(vs, inPastMs) : false;
Eric Laurentc75307b2015-03-17 15:29:32 -07003328}
3329
Eric Laurente0720872014-03-11 09:30:41 -07003330bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07003331{
3332 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003333 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08003334 if (inputDescriptor->isSourceActive(source)) {
Eric Laurente552edb2014-03-10 17:42:56 -07003335 return true;
3336 }
3337 }
3338 return false;
3339}
3340
Eric Laurent275e8e92014-11-30 15:14:47 -08003341// Register a list of custom mixes with their attributes and format.
3342// When a mix is registered, corresponding input and output profiles are
3343// added to the remote submix hw module. The profile contains only the
3344// parameters (sampling rate, format...) specified by the mix.
3345// The corresponding input remote submix device is also connected.
3346//
3347// When a remote submix device is connected, the address is checked to select the
3348// appropriate profile and the corresponding input or output stream is opened.
3349//
3350// When capture starts, getInputForAttr() will:
3351// - 1 look for a mix matching the address passed in attribtutes tags if any
3352// - 2 if none found, getDeviceForInputSource() will:
3353// - 2.1 look for a mix matching the attributes source
3354// - 2.2 if none found, default to device selection by policy rules
3355// At this time, the corresponding output remote submix device is also connected
3356// and active playback use cases can be transferred to this mix if needed when reconnecting
3357// after AudioTracks are invalidated
3358//
3359// When playback starts, getOutputForAttr() will:
3360// - 1 look for a mix matching the address passed in attribtutes tags if any
3361// - 2 if none found, look for a mix matching the attributes usage
3362// - 3 if none found, default to device and output selection by policy rules.
3363
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003364status_t AudioPolicyManager::registerPolicyMixes(const Vector<AudioMix>& mixes)
Eric Laurent275e8e92014-11-30 15:14:47 -08003365{
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003366 ALOGV("registerPolicyMixes() %zu mix(es)", mixes.size());
3367 status_t res = NO_ERROR;
Eric Laurentc209fe42020-06-05 18:11:23 -07003368 bool checkOutputs = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003369 sp<HwModule> rSubmixModule;
3370 // examine each mix's route type
3371 for (size_t i = 0; i < mixes.size(); i++) {
Eric Laurent97ac8712018-07-27 18:59:02 -07003372 AudioMix mix = mixes[i];
Kevin Rocard153f92d2018-12-18 18:33:28 -08003373 // Only capture of playback is allowed in LOOP_BACK & RENDER mode
3374 if (is_mix_loopback_render(mix.mRouteFlags) && mix.mMixType != MIX_TYPE_PLAYERS) {
3375 ALOGE("Unsupported Policy Mix %zu of %zu: "
3376 "Only capture of playback is allowed in LOOP_BACK & RENDER mode",
3377 i, mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003378 res = INVALID_OPERATION;
Eric Laurent275e8e92014-11-30 15:14:47 -08003379 break;
3380 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08003381 // LOOP_BACK and LOOP_BACK | RENDER have the same remote submix backend and are handled
3382 // in the same way.
Eric Laurent97ac8712018-07-27 18:59:02 -07003383 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003384 ALOGV("registerPolicyMixes() mix %zu of %zu is LOOP_BACK %d", i, mixes.size(),
3385 mix.mRouteFlags);
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003386 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003387 rSubmixModule = mHwModules.getModuleFromName(
3388 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
3389 if (rSubmixModule == 0) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003390 ALOGE("Unable to find audio module for submix, aborting mix %zu registration",
Mikhail Naganovd4120142017-12-06 15:49:22 -08003391 i);
3392 res = INVALID_OPERATION;
3393 break;
3394 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003395 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003396
Eric Laurent97ac8712018-07-27 18:59:02 -07003397 String8 address = mix.mDeviceAddress;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003398 audio_devices_t deviceTypeToMakeAvailable;
Eric Laurent97ac8712018-07-27 18:59:02 -07003399 if (mix.mMixType == MIX_TYPE_PLAYERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07003400 mix.mDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003401 deviceTypeToMakeAvailable = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
3402 } else {
3403 mix.mDeviceType = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
3404 deviceTypeToMakeAvailable = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Eric Laurent97ac8712018-07-27 18:59:02 -07003405 }
François Gaffie036e1e92015-03-19 10:16:24 +01003406
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003407 if (mPolicyMixes.registerMix(mix, 0 /*output desc*/) != NO_ERROR) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003408 ALOGE("Error registering mix %zu for address %s", i, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003409 res = INVALID_OPERATION;
3410 break;
3411 }
Eric Laurent97ac8712018-07-27 18:59:02 -07003412 audio_config_t outputConfig = mix.mFormat;
3413 audio_config_t inputConfig = mix.mFormat;
Eric Laurentc529cf62020-04-17 18:19:10 -07003414 // NOTE: audio flinger mixer does not support mono output: configure remote submix HAL
3415 // in stereo and let audio flinger do the channel conversion if needed.
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003416 outputConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
3417 inputConfig.channel_mask = AUDIO_CHANNEL_IN_STEREO;
jiabin5740f082019-08-19 15:08:30 -07003418 rSubmixModule->addOutputProfile(address.c_str(), &outputConfig,
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003419 AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address);
jiabin5740f082019-08-19 15:08:30 -07003420 rSubmixModule->addInputProfile(address.c_str(), &inputConfig,
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003421 AUDIO_DEVICE_IN_REMOTE_SUBMIX, address);
François Gaffie036e1e92015-03-19 10:16:24 +01003422
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003423 if ((res = setDeviceConnectionStateInt(deviceTypeToMakeAvailable,
jiabinc1de2df2019-05-07 14:26:40 -07003424 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
3425 address.string(), "remote-submix", AUDIO_FORMAT_DEFAULT)) != NO_ERROR) {
3426 ALOGE("Failed to set remote submix device available, type %u, address %s",
3427 mix.mDeviceType, address.string());
3428 break;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003429 }
Eric Laurent97ac8712018-07-27 18:59:02 -07003430 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
3431 String8 address = mix.mDeviceAddress;
Eric Laurent2c80be02019-01-23 18:06:37 -08003432 audio_devices_t type = mix.mDeviceType;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003433 ALOGV(" registerPolicyMixes() mix %zu of %zu is RENDER, dev=0x%X addr=%s",
Eric Laurent2c80be02019-01-23 18:06:37 -08003434 i, mixes.size(), type, address.string());
3435
3436 sp<DeviceDescriptor> device = mHwModules.getDeviceDescriptor(
3437 mix.mDeviceType, mix.mDeviceAddress,
3438 String8(), AUDIO_FORMAT_DEFAULT);
3439 if (device == nullptr) {
3440 res = INVALID_OPERATION;
3441 break;
3442 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003443
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003444 bool foundOutput = false;
Eric Laurentc529cf62020-04-17 18:19:10 -07003445 // First try to find an already opened output supporting the device
3446 for (size_t j = 0 ; j < mOutputs.size() && !foundOutput && res == NO_ERROR; j++) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003447 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurent2c80be02019-01-23 18:06:37 -08003448
Eric Laurentc529cf62020-04-17 18:19:10 -07003449 if (!desc->isDuplicated() && desc->supportedDevices().contains(device)) {
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003450 if (mPolicyMixes.registerMix(mix, desc) != NO_ERROR) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003451 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
3452 address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003453 res = INVALID_OPERATION;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003454 } else {
3455 foundOutput = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003456 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003457 }
3458 }
Eric Laurentc529cf62020-04-17 18:19:10 -07003459 // If no output found, try to find a direct output profile supporting the device
3460 for (size_t i = 0; i < mHwModules.size() && !foundOutput && res == NO_ERROR; i++) {
3461 sp<HwModule> module = mHwModules[i];
3462 for (size_t j = 0;
3463 j < module->getOutputProfiles().size() && !foundOutput && res == NO_ERROR;
3464 j++) {
3465 sp<IOProfile> profile = module->getOutputProfiles()[j];
3466 if (profile->isDirectOutput() && profile->supportsDevice(device)) {
3467 if (mPolicyMixes.registerMix(mix, nullptr) != NO_ERROR) {
3468 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
3469 address.string());
3470 res = INVALID_OPERATION;
3471 } else {
3472 foundOutput = true;
3473 }
3474 }
3475 }
3476 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003477 if (res != NO_ERROR) {
3478 ALOGE(" Error registering mix %zu for device 0x%X addr %s",
Eric Laurent2c80be02019-01-23 18:06:37 -08003479 i, type, address.string());
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003480 res = INVALID_OPERATION;
3481 break;
3482 } else if (!foundOutput) {
3483 ALOGE(" Output not found for mix %zu for device 0x%X addr %s",
Eric Laurent2c80be02019-01-23 18:06:37 -08003484 i, type, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003485 res = INVALID_OPERATION;
3486 break;
Eric Laurentc209fe42020-06-05 18:11:23 -07003487 } else {
3488 checkOutputs = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003489 }
Eric Laurentc722f302014-12-10 11:21:49 -08003490 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003491 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003492 if (res != NO_ERROR) {
3493 unregisterPolicyMixes(mixes);
Eric Laurentc209fe42020-06-05 18:11:23 -07003494 } else if (checkOutputs) {
3495 checkForDeviceAndOutputChanges();
3496 updateCallAndOutputRouting();
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003497 }
3498 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08003499}
3500
3501status_t AudioPolicyManager::unregisterPolicyMixes(Vector<AudioMix> mixes)
3502{
Eric Laurent7b279bb2015-12-14 10:18:23 -08003503 ALOGV("unregisterPolicyMixes() num mixes %zu", mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003504 status_t res = NO_ERROR;
Eric Laurentc209fe42020-06-05 18:11:23 -07003505 bool checkOutputs = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003506 sp<HwModule> rSubmixModule;
3507 // examine each mix's route type
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003508 for (const auto& mix : mixes) {
3509 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie036e1e92015-03-19 10:16:24 +01003510
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003511 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003512 rSubmixModule = mHwModules.getModuleFromName(
3513 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
3514 if (rSubmixModule == 0) {
3515 res = INVALID_OPERATION;
3516 continue;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003517 }
3518 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003519
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003520 String8 address = mix.mDeviceAddress;
Eric Laurent275e8e92014-11-30 15:14:47 -08003521
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003522 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003523 res = INVALID_OPERATION;
3524 continue;
3525 }
3526
Kevin Rocard04ed0462019-05-02 17:53:24 -07003527 for (auto device : {AUDIO_DEVICE_IN_REMOTE_SUBMIX, AUDIO_DEVICE_OUT_REMOTE_SUBMIX}) {
3528 if (getDeviceConnectionState(device, address.string()) ==
3529 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
3530 res = setDeviceConnectionStateInt(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
3531 address.string(), "remote-submix",
3532 AUDIO_FORMAT_DEFAULT);
3533 if (res != OK) {
3534 ALOGE("Error making RemoteSubmix device unavailable for mix "
3535 "with type %d, address %s", device, address.string());
3536 }
3537 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003538 }
jiabin5740f082019-08-19 15:08:30 -07003539 rSubmixModule->removeOutputProfile(address.c_str());
3540 rSubmixModule->removeInputProfile(address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003541
Kevin Rocard153f92d2018-12-18 18:33:28 -08003542 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003543 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003544 res = INVALID_OPERATION;
3545 continue;
Eric Laurentc209fe42020-06-05 18:11:23 -07003546 } else {
3547 checkOutputs = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003548 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003549 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003550 }
Eric Laurentc209fe42020-06-05 18:11:23 -07003551 if (res == NO_ERROR && checkOutputs) {
3552 checkForDeviceAndOutputChanges();
3553 updateCallAndOutputRouting();
3554 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003555 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08003556}
3557
Mikhail Naganov100f0122018-11-29 11:22:16 -08003558void AudioPolicyManager::dumpManualSurroundFormats(String8 *dst) const
3559{
3560 size_t i = 0;
3561 constexpr size_t audioFormatPrefixLen = sizeof("AUDIO_FORMAT_");
3562 for (const auto& fmt : mManualSurroundFormats) {
3563 if (i++ != 0) dst->append(", ");
3564 std::string sfmt;
3565 FormatConverter::toString(fmt, sfmt);
3566 dst->append(sfmt.size() >= audioFormatPrefixLen ?
3567 sfmt.c_str() + audioFormatPrefixLen - 1 : sfmt.c_str());
3568 }
3569}
3570
Eric Laurentc529cf62020-04-17 18:19:10 -07003571// Returns true if all devices types match the predicate and are supported by one HW module
3572bool AudioPolicyManager::areAllDevicesSupported(
jiabin6a02d532020-08-07 11:56:38 -07003573 const AudioDeviceTypeAddrVector& devices,
Eric Laurentc529cf62020-04-17 18:19:10 -07003574 std::function<bool(audio_devices_t)> predicate,
3575 const char *context) {
3576 for (size_t i = 0; i < devices.size(); i++) {
3577 sp<DeviceDescriptor> devDesc = mHwModules.getDeviceDescriptor(
jiabin0a488932020-08-07 17:32:40 -07003578 devices[i].mType, devices[i].getAddress(), String8(),
Eric Laurent0e26e3f2020-04-29 14:24:16 -07003579 AUDIO_FORMAT_DEFAULT, false /*allowToCreate*/, true /*matchAddress*/);
Eric Laurentc529cf62020-04-17 18:19:10 -07003580 if (devDesc == nullptr || (predicate != nullptr && !predicate(devices[i].mType))) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003581 ALOGE("%s: device type %#x address %s not supported or not match predicate",
jiabin0a488932020-08-07 17:32:40 -07003582 context, devices[i].mType, devices[i].getAddress());
Eric Laurentc529cf62020-04-17 18:19:10 -07003583 return false;
3584 }
3585 }
3586 return true;
3587}
3588
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003589status_t AudioPolicyManager::setUidDeviceAffinities(uid_t uid,
jiabin6a02d532020-08-07 11:56:38 -07003590 const AudioDeviceTypeAddrVector& devices) {
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003591 ALOGV("%s() uid=%d num devices %zu", __FUNCTION__, uid, devices.size());
Eric Laurentc529cf62020-04-17 18:19:10 -07003592 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
3593 return BAD_VALUE;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003594 }
3595 status_t res = mPolicyMixes.setUidDeviceAffinities(uid, devices);
Eric Laurentc529cf62020-04-17 18:19:10 -07003596 if (res != NO_ERROR) {
3597 ALOGE("%s() Could not set all device affinities for uid = %d", __FUNCTION__, uid);
3598 return res;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003599 }
Eric Laurentc529cf62020-04-17 18:19:10 -07003600
3601 checkForDeviceAndOutputChanges();
3602 updateCallAndOutputRouting();
3603
3604 return NO_ERROR;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003605}
3606
3607status_t AudioPolicyManager::removeUidDeviceAffinities(uid_t uid) {
3608 ALOGV("%s() uid=%d", __FUNCTION__, uid);
Oscar Azucena4b2a8212019-04-26 23:48:59 -07003609 status_t res = mPolicyMixes.removeUidDeviceAffinities(uid);
3610 if (res != NO_ERROR) {
Eric Laurentc529cf62020-04-17 18:19:10 -07003611 ALOGE("%s() Could not remove all device affinities for uid = %d",
Oscar Azucena4b2a8212019-04-26 23:48:59 -07003612 __FUNCTION__, uid);
3613 return INVALID_OPERATION;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003614 }
3615
Eric Laurentc529cf62020-04-17 18:19:10 -07003616 checkForDeviceAndOutputChanges();
3617 updateCallAndOutputRouting();
3618
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003619 return res;
3620}
3621
Eric Laurent2517af32020-11-25 15:31:27 +01003622
jiabin0a488932020-08-07 17:32:40 -07003623status_t AudioPolicyManager::setDevicesRoleForStrategy(product_strategy_t strategy,
3624 device_role_t role,
3625 const AudioDeviceTypeAddrVector &devices) {
3626 ALOGV("%s() strategy=%d role=%d %s", __func__, strategy, role,
3627 dumpAudioDeviceTypeAddrVector(devices).c_str());
Eric Laurentc529cf62020-04-17 18:19:10 -07003628
Eric Laurentc529cf62020-04-17 18:19:10 -07003629 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003630 return BAD_VALUE;
3631 }
jiabin0a488932020-08-07 17:32:40 -07003632 status_t status = mEngine->setDevicesRoleForStrategy(strategy, role, devices);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003633 if (status != NO_ERROR) {
jiabin0a488932020-08-07 17:32:40 -07003634 ALOGW("Engine could not set preferred devices %s for strategy %d role %d",
3635 dumpAudioDeviceTypeAddrVector(devices).c_str(), strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003636 return status;
3637 }
3638
3639 checkForDeviceAndOutputChanges();
Eric Laurent2517af32020-11-25 15:31:27 +01003640
3641 bool forceVolumeReeval = false;
3642 // FIXME: workaround for truncated touch sounds
3643 // to be removed when the problem is handled by system UI
3644 uint32_t delayMs = 0;
3645 if (strategy == mCommunnicationStrategy) {
3646 forceVolumeReeval = true;
3647 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
3648 updateInputRouting();
3649 }
3650 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003651
3652 return NO_ERROR;
3653}
3654
3655void AudioPolicyManager::updateCallAndOutputRouting(bool forceVolumeReeval, uint32_t delayMs)
3656{
3657 uint32_t waitMs = 0;
Eric Laurent96d1dda2022-03-14 17:14:19 +01003658 bool wasLeUnicastActive = isLeUnicastActive();
Francois Gaffie19fd6c52021-02-04 17:02:59 +01003659 if (updateCallRouting(true /*fromCache*/, delayMs, &waitMs) == NO_ERROR) {
Eric Laurentb36b4ac2020-08-21 12:50:41 -07003660 // Only apply special touch sound delay once
3661 delayMs = 0;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003662 }
3663 for (size_t i = 0; i < mOutputs.size(); i++) {
3664 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
3665 DeviceVector newDevices = getNewOutputDevices(outputDesc, true /*fromCache*/);
Francois Gaffie601801d2021-06-22 13:27:39 +02003666 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) ||
3667 (outputDesc != mPrimaryOutput && !isTelephonyRxOrTx(outputDesc))) {
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003668 // As done in setDeviceConnectionState, we could also fix default device issue by
3669 // preventing the force re-routing in case of default dev that distinguishes on address.
3670 // Let's give back to engine full device choice decision however.
Francois Gaffie601801d2021-06-22 13:27:39 +02003671 bool forceRouting = !newDevices.isEmpty();
3672 waitMs = setOutputDevices(outputDesc, newDevices, forceRouting, delayMs, nullptr,
3673 true /*requiresMuteCheck*/,
3674 !forceRouting /*requiresVolumeCheck*/);
Eric Laurentb36b4ac2020-08-21 12:50:41 -07003675 // Only apply special touch sound delay once
3676 delayMs = 0;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003677 }
3678 if (forceVolumeReeval && !newDevices.isEmpty()) {
3679 applyStreamVolumes(outputDesc, newDevices.types(), waitMs, true);
3680 }
3681 }
Eric Laurent96d1dda2022-03-14 17:14:19 +01003682 checkLeBroadcastRoutes(wasLeUnicastActive, nullptr, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003683}
3684
Eric Laurent2517af32020-11-25 15:31:27 +01003685void AudioPolicyManager::updateInputRouting() {
3686 for (const auto& activeDesc : mInputs.getActiveInputs()) {
Jaideep Sharma408349a2020-11-27 14:47:17 +05303687 // Skip for hotword recording as the input device switch
3688 // is handled within sound trigger HAL
3689 if (activeDesc->isSoundTrigger() && activeDesc->source() == AUDIO_SOURCE_HOTWORD) {
3690 continue;
3691 }
Eric Laurent2517af32020-11-25 15:31:27 +01003692 auto newDevice = getNewInputDevice(activeDesc);
3693 // Force new input selection if the new device can not be reached via current input
3694 if (activeDesc->mProfile->getSupportedDevices().contains(newDevice)) {
3695 setInputDevice(activeDesc->mIoHandle, newDevice);
3696 } else {
3697 closeInput(activeDesc->mIoHandle);
3698 }
3699 }
3700}
3701
jiabin0a488932020-08-07 17:32:40 -07003702status_t AudioPolicyManager::removeDevicesRoleForStrategy(product_strategy_t strategy,
3703 device_role_t role)
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003704{
Eric Laurentfecbceb2021-02-09 14:46:43 +01003705 ALOGV("%s() strategy=%d role=%d", __func__, strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003706
jiabin0a488932020-08-07 17:32:40 -07003707 status_t status = mEngine->removeDevicesRoleForStrategy(strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003708 if (status != NO_ERROR) {
Eric Laurent2517af32020-11-25 15:31:27 +01003709 ALOGV("Engine could not remove preferred device for strategy %d status %d",
3710 strategy, status);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003711 return status;
3712 }
3713
3714 checkForDeviceAndOutputChanges();
Eric Laurent2517af32020-11-25 15:31:27 +01003715
3716 bool forceVolumeReeval = false;
3717 // FIXME: workaround for truncated touch sounds
3718 // to be removed when the problem is handled by system UI
3719 uint32_t delayMs = 0;
3720 if (strategy == mCommunnicationStrategy) {
3721 forceVolumeReeval = true;
3722 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
3723 updateInputRouting();
3724 }
3725 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003726
3727 return NO_ERROR;
3728}
3729
jiabin0a488932020-08-07 17:32:40 -07003730status_t AudioPolicyManager::getDevicesForRoleAndStrategy(product_strategy_t strategy,
3731 device_role_t role,
3732 AudioDeviceTypeAddrVector &devices) {
3733 return mEngine->getDevicesForRoleAndStrategy(strategy, role, devices);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003734}
3735
Jiabin Huang3b98d322020-09-03 17:54:16 +00003736status_t AudioPolicyManager::setDevicesRoleForCapturePreset(
3737 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices) {
3738 ALOGV("%s() audioSource=%d role=%d %s", __func__, audioSource, role,
3739 dumpAudioDeviceTypeAddrVector(devices).c_str());
3740
Mikhail Naganov55773032020-10-01 15:08:13 -07003741 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003742 return BAD_VALUE;
3743 }
3744 status_t status = mEngine->setDevicesRoleForCapturePreset(audioSource, role, devices);
3745 ALOGW_IF(status != NO_ERROR,
3746 "Engine could not set preferred devices %s for audio source %d role %d",
3747 dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
3748
3749 return status;
3750}
3751
3752status_t AudioPolicyManager::addDevicesRoleForCapturePreset(
3753 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices) {
3754 ALOGV("%s() audioSource=%d role=%d %s", __func__, audioSource, role,
3755 dumpAudioDeviceTypeAddrVector(devices).c_str());
3756
Mikhail Naganov55773032020-10-01 15:08:13 -07003757 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003758 return BAD_VALUE;
3759 }
3760 status_t status = mEngine->addDevicesRoleForCapturePreset(audioSource, role, devices);
3761 ALOGW_IF(status != NO_ERROR,
3762 "Engine could not add preferred devices %s for audio source %d role %d",
3763 dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
3764
Eric Laurent2517af32020-11-25 15:31:27 +01003765 updateInputRouting();
Jiabin Huang3b98d322020-09-03 17:54:16 +00003766 return status;
3767}
3768
3769status_t AudioPolicyManager::removeDevicesRoleForCapturePreset(
3770 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector& devices)
3771{
3772 ALOGV("%s() audioSource=%d role=%d devices=%s", __func__, audioSource, role,
3773 dumpAudioDeviceTypeAddrVector(devices).c_str());
3774
Mikhail Naganov55773032020-10-01 15:08:13 -07003775 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003776 return BAD_VALUE;
3777 }
3778
3779 status_t status = mEngine->removeDevicesRoleForCapturePreset(
3780 audioSource, role, devices);
3781 ALOGW_IF(status != NO_ERROR,
3782 "Engine could not remove devices role (%d) for capture preset %d", role, audioSource);
3783
Eric Laurent2517af32020-11-25 15:31:27 +01003784 updateInputRouting();
Jiabin Huang3b98d322020-09-03 17:54:16 +00003785 return status;
3786}
3787
3788status_t AudioPolicyManager::clearDevicesRoleForCapturePreset(audio_source_t audioSource,
3789 device_role_t role) {
3790 ALOGV("%s() audioSource=%d role=%d", __func__, audioSource, role);
3791
3792 status_t status = mEngine->clearDevicesRoleForCapturePreset(audioSource, role);
3793 ALOGW_IF(status != NO_ERROR,
3794 "Engine could not clear devices role (%d) for capture preset %d", role, audioSource);
3795
Eric Laurent2517af32020-11-25 15:31:27 +01003796 updateInputRouting();
Jiabin Huang3b98d322020-09-03 17:54:16 +00003797 return status;
3798}
3799
3800status_t AudioPolicyManager::getDevicesForRoleAndCapturePreset(
3801 audio_source_t audioSource, device_role_t role, AudioDeviceTypeAddrVector &devices) {
3802 return mEngine->getDevicesForRoleAndCapturePreset(audioSource, role, devices);
3803}
3804
Oscar Azucena90e77632019-11-27 17:12:28 -08003805status_t AudioPolicyManager::setUserIdDeviceAffinities(int userId,
jiabin6a02d532020-08-07 11:56:38 -07003806 const AudioDeviceTypeAddrVector& devices) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01003807 ALOGV("%s() userId=%d num devices %zu", __func__, userId, devices.size());
Eric Laurentc529cf62020-04-17 18:19:10 -07003808 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
3809 return BAD_VALUE;
Oscar Azucena90e77632019-11-27 17:12:28 -08003810 }
Oscar Azucena90e77632019-11-27 17:12:28 -08003811 status_t status = mPolicyMixes.setUserIdDeviceAffinities(userId, devices);
3812 if (status != NO_ERROR) {
3813 ALOGE("%s() could not set device affinity for userId %d",
3814 __FUNCTION__, userId);
3815 return status;
3816 }
3817
3818 // reevaluate outputs for all devices
3819 checkForDeviceAndOutputChanges();
3820 updateCallAndOutputRouting();
3821
3822 return NO_ERROR;
3823}
3824
3825status_t AudioPolicyManager::removeUserIdDeviceAffinities(int userId) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01003826 ALOGV("%s() userId=%d", __FUNCTION__, userId);
Oscar Azucena90e77632019-11-27 17:12:28 -08003827 status_t status = mPolicyMixes.removeUserIdDeviceAffinities(userId);
3828 if (status != NO_ERROR) {
3829 ALOGE("%s() Could not remove all device affinities fo userId = %d",
3830 __FUNCTION__, userId);
3831 return status;
3832 }
3833
3834 // reevaluate outputs for all devices
3835 checkForDeviceAndOutputChanges();
3836 updateCallAndOutputRouting();
3837
3838 return NO_ERROR;
3839}
3840
Andy Hungc29d82b2018-10-05 12:23:17 -07003841void AudioPolicyManager::dump(String8 *dst) const
Eric Laurente552edb2014-03-10 17:42:56 -07003842{
Andy Hungc29d82b2018-10-05 12:23:17 -07003843 dst->appendFormat("\nAudioPolicyManager Dump: %p\n", this);
Mikhail Naganov0dbe87b2021-12-01 02:03:31 +00003844 dst->appendFormat(" Primary Output I/O handle: %d\n",
Eric Laurent87ffa392015-05-22 10:32:38 -07003845 hasPrimaryOutput() ? mPrimaryOutput->mIoHandle : AUDIO_IO_HANDLE_NONE);
Mikhail Naganov0d6a0332016-04-19 17:12:38 -07003846 std::string stateLiteral;
3847 AudioModeConverter::toString(mEngine->getPhoneState(), stateLiteral);
Andy Hungc29d82b2018-10-05 12:23:17 -07003848 dst->appendFormat(" Phone state: %s\n", stateLiteral.c_str());
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07003849 const char* forceUses[AUDIO_POLICY_FORCE_USE_CNT] = {
3850 "communications", "media", "record", "dock", "system",
3851 "HDMI system audio", "encoded surround output", "vibrate ringing" };
3852 for (audio_policy_force_use_t i = AUDIO_POLICY_FORCE_FOR_COMMUNICATION;
3853 i < AUDIO_POLICY_FORCE_USE_CNT; i = (audio_policy_force_use_t)((int)i + 1)) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08003854 audio_policy_forced_cfg_t forceUseValue = mEngine->getForceUse(i);
3855 dst->appendFormat(" Force use for %s: %d", forceUses[i], forceUseValue);
3856 if (i == AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND &&
3857 forceUseValue == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
3858 dst->append(" (MANUAL: ");
3859 dumpManualSurroundFormats(dst);
3860 dst->append(")");
3861 }
3862 dst->append("\n");
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07003863 }
Andy Hungc29d82b2018-10-05 12:23:17 -07003864 dst->appendFormat(" TTS output %savailable\n", mTtsOutputAvailable ? "" : "not ");
3865 dst->appendFormat(" Master mono: %s\n", mMasterMono ? "on" : "off");
Mikhail Naganovb3bcb4f2022-02-23 23:46:56 +00003866 dst->appendFormat(" Communication Strategy id: %d\n", mCommunnicationStrategy);
Andy Hungc29d82b2018-10-05 12:23:17 -07003867 dst->appendFormat(" Config source: %s\n", mConfig.getSource().c_str()); // getConfig not const
Eric Laurent2517af32020-11-25 15:31:27 +01003868
Mikhail Naganov0f413b22021-12-02 05:29:27 +00003869 dst->append("\n");
3870 mAvailableOutputDevices.dump(dst, String8("Available output"), 1);
3871 dst->append("\n");
3872 mAvailableInputDevices.dump(dst, String8("Available input"), 1);
Andy Hungc29d82b2018-10-05 12:23:17 -07003873 mHwModulesAll.dump(dst);
3874 mOutputs.dump(dst);
3875 mInputs.dump(dst);
Mikhail Naganov0f413b22021-12-02 05:29:27 +00003876 mEffects.dump(dst, 1);
Andy Hungc29d82b2018-10-05 12:23:17 -07003877 mAudioPatches.dump(dst);
3878 mPolicyMixes.dump(dst);
3879 mAudioSources.dump(dst);
François Gaffiec005e562018-11-06 15:04:49 +01003880
Kevin Rocardb99cc752019-03-21 20:52:24 -07003881 dst->appendFormat(" AllowedCapturePolicies:\n");
3882 for (auto& policy : mAllowedCapturePolicies) {
3883 dst->appendFormat(" - uid=%d flag_mask=%#x\n", policy.first, policy.second);
3884 }
3885
François Gaffiec005e562018-11-06 15:04:49 +01003886 dst->appendFormat("\nPolicy Engine dump:\n");
3887 mEngine->dump(dst);
Andy Hungc29d82b2018-10-05 12:23:17 -07003888}
3889
3890status_t AudioPolicyManager::dump(int fd)
3891{
3892 String8 result;
3893 dump(&result);
Andy Hungbb54e202018-10-05 11:42:02 -07003894 write(fd, result.string(), result.size());
Eric Laurente552edb2014-03-10 17:42:56 -07003895 return NO_ERROR;
3896}
3897
Kevin Rocardb99cc752019-03-21 20:52:24 -07003898status_t AudioPolicyManager::setAllowedCapturePolicy(uid_t uid, audio_flags_mask_t capturePolicy)
3899{
3900 mAllowedCapturePolicies[uid] = capturePolicy;
3901 return NO_ERROR;
3902}
3903
Eric Laurente552edb2014-03-10 17:42:56 -07003904// This function checks for the parameters which can be offloaded.
3905// This can be enhanced depending on the capability of the DSP and policy
3906// of the system.
Eric Laurent90fe31c2020-11-26 20:06:35 +01003907audio_offload_mode_t AudioPolicyManager::getOffloadSupport(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07003908{
Eric Laurent90fe31c2020-11-26 20:06:35 +01003909 ALOGV("%s: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07003910 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurent90fe31c2020-11-26 20:06:35 +01003911 __func__, offloadInfo.sample_rate, offloadInfo.channel_mask,
Eric Laurente552edb2014-03-10 17:42:56 -07003912 offloadInfo.format,
3913 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
3914 offloadInfo.has_video);
3915
jiabin2b9d5a12021-12-10 01:06:29 +00003916 if (!isOffloadPossible(offloadInfo)) {
Eric Laurent90fe31c2020-11-26 20:06:35 +01003917 return AUDIO_OFFLOAD_NOT_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07003918 }
3919
3920 // See if there is a profile to support this.
3921 // AUDIO_DEVICE_NONE
François Gaffie11d30102018-11-02 16:09:09 +01003922 sp<IOProfile> profile = getProfileForOutput(DeviceVector() /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07003923 offloadInfo.sample_rate,
3924 offloadInfo.format,
3925 offloadInfo.channel_mask,
Michael Chana94fbb22018-04-24 14:31:19 +10003926 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD,
3927 true /* directOnly */);
Eric Laurent94365442021-01-08 18:36:05 +01003928 ALOGV("%s: profile %sfound%s", __func__, profile != nullptr ? "" : "NOT ",
3929 (profile != nullptr && (profile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD) != 0)
3930 ? ", supports gapless" : "");
Eric Laurent90fe31c2020-11-26 20:06:35 +01003931 if (profile == nullptr) {
3932 return AUDIO_OFFLOAD_NOT_SUPPORTED;
3933 }
3934 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD) != 0) {
3935 return AUDIO_OFFLOAD_GAPLESS_SUPPORTED;
3936 }
3937 return AUDIO_OFFLOAD_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07003938}
3939
Michael Chana94fbb22018-04-24 14:31:19 +10003940bool AudioPolicyManager::isDirectOutputSupported(const audio_config_base_t& config,
3941 const audio_attributes_t& attributes) {
3942 audio_output_flags_t output_flags = AUDIO_OUTPUT_FLAG_NONE;
François Gaffie58d4be52018-11-06 15:30:12 +01003943 audio_flags_to_audio_output_flags(attributes.flags, &output_flags);
Dorin Drimus9901eb02022-01-14 11:36:51 +00003944 DeviceVector outputDevices = mEngine->getOutputDevicesForAttributes(attributes);
3945 sp<IOProfile> profile = getProfileForOutput(outputDevices,
Michael Chana94fbb22018-04-24 14:31:19 +10003946 config.sample_rate,
3947 config.format,
3948 config.channel_mask,
3949 output_flags,
3950 true /* directOnly */);
3951 ALOGV("%s() profile %sfound with name: %s, "
3952 "sample rate: %u, format: 0x%x, channel_mask: 0x%x, output flags: 0x%x",
3953 __FUNCTION__, profile != 0 ? "" : "NOT ",
jiabin5740f082019-08-19 15:08:30 -07003954 (profile != 0 ? profile->getTagName().c_str() : "null"),
Michael Chana94fbb22018-04-24 14:31:19 +10003955 config.sample_rate, config.format, config.channel_mask, output_flags);
Dorin Drimusecc9f422022-03-09 17:57:40 +01003956
3957 // also try the MSD module if compatible profile not found
3958 if (profile == nullptr) {
3959 profile = getMsdProfileForOutput(outputDevices,
3960 config.sample_rate,
3961 config.format,
3962 config.channel_mask,
3963 output_flags,
3964 true /* directOnly */);
3965 ALOGV("%s() MSD profile %sfound with name: %s, "
3966 "sample rate: %u, format: 0x%x, channel_mask: 0x%x, output flags: 0x%x",
3967 __FUNCTION__, profile != 0 ? "" : "NOT ",
3968 (profile != 0 ? profile->getTagName().c_str() : "null"),
3969 config.sample_rate, config.format, config.channel_mask, output_flags);
3970 }
3971 return (profile != nullptr);
Michael Chana94fbb22018-04-24 14:31:19 +10003972}
3973
jiabin2b9d5a12021-12-10 01:06:29 +00003974bool AudioPolicyManager::isOffloadPossible(const audio_offload_info_t &offloadInfo,
3975 bool durationIgnored) {
3976 if (mMasterMono) {
3977 return false; // no offloading if mono is set.
3978 }
3979
3980 // Check if offload has been disabled
3981 if (property_get_bool("audio.offload.disable", false /* default_value */)) {
3982 ALOGV("%s: offload disabled by audio.offload.disable", __func__);
3983 return false;
3984 }
3985
3986 // Check if stream type is music, then only allow offload as of now.
3987 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
3988 {
3989 ALOGV("%s: stream_type != MUSIC, returning false", __func__);
3990 return false;
3991 }
3992
3993 //TODO: enable audio offloading with video when ready
3994 const bool allowOffloadWithVideo =
3995 property_get_bool("audio.offload.video", false /* default_value */);
3996 if (offloadInfo.has_video && !allowOffloadWithVideo) {
3997 ALOGV("%s: has_video == true, returning false", __func__);
3998 return false;
3999 }
4000
4001 //If duration is less than minimum value defined in property, return false
4002 const int min_duration_secs = property_get_int32(
4003 "audio.offload.min.duration.secs", -1 /* default_value */);
4004 if (!durationIgnored) {
4005 if (min_duration_secs >= 0) {
4006 if (offloadInfo.duration_us < min_duration_secs * 1000000LL) {
4007 ALOGV("%s: Offload denied by duration < audio.offload.min.duration.secs(=%d)",
4008 __func__, min_duration_secs);
4009 return false;
4010 }
4011 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
4012 ALOGV("%s: Offload denied by duration < default min(=%u)",
4013 __func__, OFFLOAD_DEFAULT_MIN_DURATION_SECS);
4014 return false;
4015 }
4016 }
4017
4018 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
4019 // creating an offloaded track and tearing it down immediately after start when audioflinger
4020 // detects there is an active non offloadable effect.
4021 // FIXME: We should check the audio session here but we do not have it in this context.
4022 // This may prevent offloading in rare situations where effects are left active by apps
4023 // in the background.
4024 if (mEffects.isNonOffloadableEffectEnabled()) {
4025 return false;
4026 }
4027
4028 return true;
4029}
4030
4031audio_direct_mode_t AudioPolicyManager::getDirectPlaybackSupport(const audio_attributes_t *attr,
4032 const audio_config_t *config) {
4033 audio_offload_info_t offloadInfo = AUDIO_INFO_INITIALIZER;
4034 offloadInfo.format = config->format;
4035 offloadInfo.sample_rate = config->sample_rate;
4036 offloadInfo.channel_mask = config->channel_mask;
4037 offloadInfo.stream_type = mEngine->getStreamTypeForAttributes(*attr);
4038 offloadInfo.has_video = false;
4039 offloadInfo.is_streaming = false;
4040 const bool offloadPossible = isOffloadPossible(offloadInfo, true /*durationIgnored*/);
4041
4042 audio_direct_mode_t directMode = AUDIO_DIRECT_NOT_SUPPORTED;
4043 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
4044 audio_flags_to_audio_output_flags(attr->flags, &flags);
4045 // only retain flags that will drive compressed offload or passthrough
4046 uint32_t relevantFlags = AUDIO_OUTPUT_FLAG_HW_AV_SYNC;
4047 if (offloadPossible) {
4048 relevantFlags |= AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD;
4049 }
4050 flags = (audio_output_flags_t)((flags & relevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
4051
Dorin Drimusfae3c642022-03-17 18:36:30 +01004052 DeviceVector engineOutputDevices = mEngine->getOutputDevicesForAttributes(*attr);
jiabin2b9d5a12021-12-10 01:06:29 +00004053 for (const auto& hwModule : mHwModules) {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004054 DeviceVector outputDevices = engineOutputDevices;
4055 // the MSD module checks for different conditions and output devices
4056 if (strcmp(hwModule->getName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0) {
4057 if (!msdHasPatchesToAllDevices(engineOutputDevices.toTypeAddrVector())) {
4058 continue;
4059 }
4060 outputDevices = getMsdAudioOutDevices();
4061 }
jiabin2b9d5a12021-12-10 01:06:29 +00004062 for (const auto& curProfile : hwModule->getOutputProfiles()) {
jiabinc8f7dfc2022-01-06 18:42:08 +00004063 if (!curProfile->isCompatibleProfile(outputDevices,
jiabin2b9d5a12021-12-10 01:06:29 +00004064 config->sample_rate, nullptr /*updatedSamplingRate*/,
4065 config->format, nullptr /*updatedFormat*/,
4066 config->channel_mask, nullptr /*updatedChannelMask*/,
4067 flags)) {
4068 continue;
4069 }
4070 // reject profiles not corresponding to a device currently available
4071 if (!mAvailableOutputDevices.containsAtLeastOne(curProfile->getSupportedDevices())) {
4072 continue;
4073 }
4074 if ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)
4075 != AUDIO_OUTPUT_FLAG_NONE) {
jiabinc6132d62022-01-01 07:36:31 +00004076 if ((directMode & AUDIO_DIRECT_OFFLOAD_GAPLESS_SUPPORTED)
jiabin2b9d5a12021-12-10 01:06:29 +00004077 != AUDIO_DIRECT_NOT_SUPPORTED) {
4078 // Already reports offload gapless supported. No need to report offload support.
4079 continue;
4080 }
4081 if ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD)
4082 != AUDIO_OUTPUT_FLAG_NONE) {
4083 // If offload gapless is reported, no need to report offload support.
4084 directMode = (audio_direct_mode_t) ((directMode &
4085 ~AUDIO_DIRECT_OFFLOAD_SUPPORTED) |
4086 AUDIO_DIRECT_OFFLOAD_GAPLESS_SUPPORTED);
4087 } else {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004088 directMode = (audio_direct_mode_t)(directMode | AUDIO_DIRECT_OFFLOAD_SUPPORTED);
jiabin2b9d5a12021-12-10 01:06:29 +00004089 }
4090 } else {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004091 directMode = (audio_direct_mode_t) (directMode | AUDIO_DIRECT_BITSTREAM_SUPPORTED);
jiabin2b9d5a12021-12-10 01:06:29 +00004092 }
4093 }
4094 }
4095 return directMode;
4096}
4097
Dorin Drimusf2196d82022-01-03 12:11:18 +01004098status_t AudioPolicyManager::getDirectProfilesForAttributes(const audio_attributes_t* attr,
4099 AudioProfileVector& audioProfilesVector) {
4100 AudioDeviceTypeAddrVector devices;
Andy Hung6d23c0f2022-02-16 09:37:15 -08004101 status_t status = getDevicesForAttributes(*attr, &devices, false /* forVolume */);
Dorin Drimusf2196d82022-01-03 12:11:18 +01004102 if (status != OK) {
4103 return status;
4104 }
4105 ALOGV("%s: found %zu output devices for attributes.", __func__, devices.size());
4106 if (devices.empty()) {
4107 return OK; // no output devices for the attributes
4108 }
4109
4110 for (const auto& hwModule : mHwModules) {
Dorin Drimus94d94412022-02-02 09:05:02 +01004111 // the MSD module checks for different conditions
4112 if (strcmp(hwModule->getName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0) {
4113 continue;
4114 }
4115 for (const auto& outputProfile : hwModule->getOutputProfiles()) {
4116 if (!outputProfile->asAudioPort()->isDirectOutput()) {
Dorin Drimusf2196d82022-01-03 12:11:18 +01004117 continue;
4118 }
Dorin Drimus94d94412022-02-02 09:05:02 +01004119 // allow only profiles that support all the available and routed devices
4120 if (outputProfile->getSupportedDevices().getDevicesFromDeviceTypeAddrVec(devices).size()
Dorin Drimusf2196d82022-01-03 12:11:18 +01004121 != devices.size()) {
4122 continue;
4123 }
Dorin Drimus94d94412022-02-02 09:05:02 +01004124 audioProfilesVector.addAllValidProfiles(
4125 outputProfile->asAudioPort()->getAudioProfiles());
Dorin Drimusf2196d82022-01-03 12:11:18 +01004126 }
4127 }
Dorin Drimus94d94412022-02-02 09:05:02 +01004128
4129 // add the direct profiles from MSD if present and has audio patches to all the output(s)
4130 const auto& msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
4131 if (msdModule != nullptr) {
4132 if (msdHasPatchesToAllDevices(devices)) {
4133 ALOGV("%s: MSD audio patches set to all output devices.", __func__);
4134 for (const auto& outputProfile : msdModule->getOutputProfiles()) {
4135 if (!outputProfile->asAudioPort()->isDirectOutput()) {
4136 continue;
4137 }
4138 audioProfilesVector.addAllValidProfiles(
4139 outputProfile->asAudioPort()->getAudioProfiles());
4140 }
4141 } else {
4142 ALOGV("%s: MSD audio patches NOT set to all output devices.", __func__);
4143 }
4144 }
4145
Dorin Drimusf2196d82022-01-03 12:11:18 +01004146 return NO_ERROR;
4147}
4148
Eric Laurent6a94d692014-05-20 11:18:06 -07004149status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
4150 audio_port_type_t type,
4151 unsigned int *num_ports,
jiabin19cdba52020-11-24 11:28:58 -08004152 struct audio_port_v7 *ports,
Eric Laurent6a94d692014-05-20 11:18:06 -07004153 unsigned int *generation)
4154{
jiabin19cdba52020-11-24 11:28:58 -08004155 if (num_ports == nullptr || (*num_ports != 0 && ports == nullptr) ||
4156 generation == nullptr) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004157 return BAD_VALUE;
4158 }
4159 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
jiabin19cdba52020-11-24 11:28:58 -08004160 if (ports == nullptr) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004161 *num_ports = 0;
4162 }
4163
4164 size_t portsWritten = 0;
4165 size_t portsMax = *num_ports;
4166 *num_ports = 0;
4167 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07004168 // do not report devices with type AUDIO_DEVICE_IN_STUB or AUDIO_DEVICE_OUT_STUB
4169 // as they are used by stub HALs by convention
Eric Laurent6a94d692014-05-20 11:18:06 -07004170 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004171 for (const auto& dev : mAvailableOutputDevices) {
4172 if (dev->type() == AUDIO_DEVICE_OUT_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07004173 continue;
4174 }
4175 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004176 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07004177 }
4178 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07004179 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004180 }
4181 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004182 for (const auto& dev : mAvailableInputDevices) {
4183 if (dev->type() == AUDIO_DEVICE_IN_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07004184 continue;
4185 }
4186 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004187 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07004188 }
4189 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07004190 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004191 }
4192 }
4193 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
4194 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
4195 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
4196 mInputs[i]->toAudioPort(&ports[portsWritten++]);
4197 }
4198 *num_ports += mInputs.size();
4199 }
4200 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent84c70242014-06-23 08:46:27 -07004201 size_t numOutputs = 0;
4202 for (size_t i = 0; i < mOutputs.size(); i++) {
4203 if (!mOutputs[i]->isDuplicated()) {
4204 numOutputs++;
4205 if (portsWritten < portsMax) {
4206 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
4207 }
4208 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004209 }
Eric Laurent84c70242014-06-23 08:46:27 -07004210 *num_ports += numOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07004211 }
4212 }
4213 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07004214 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
Eric Laurent6a94d692014-05-20 11:18:06 -07004215 return NO_ERROR;
4216}
4217
jiabin19cdba52020-11-24 11:28:58 -08004218status_t AudioPolicyManager::getAudioPort(struct audio_port_v7 *port)
Eric Laurent6a94d692014-05-20 11:18:06 -07004219{
Eric Laurent99fcae42018-05-17 16:59:18 -07004220 if (port == nullptr || port->id == AUDIO_PORT_HANDLE_NONE) {
4221 return BAD_VALUE;
4222 }
4223 sp<DeviceDescriptor> dev = mAvailableOutputDevices.getDeviceFromId(port->id);
4224 if (dev != 0) {
4225 dev->toAudioPort(port);
4226 return NO_ERROR;
4227 }
4228 dev = mAvailableInputDevices.getDeviceFromId(port->id);
4229 if (dev != 0) {
4230 dev->toAudioPort(port);
4231 return NO_ERROR;
4232 }
4233 sp<SwAudioOutputDescriptor> out = mOutputs.getOutputFromId(port->id);
4234 if (out != 0) {
4235 out->toAudioPort(port);
4236 return NO_ERROR;
4237 }
4238 sp<AudioInputDescriptor> in = mInputs.getInputFromId(port->id);
4239 if (in != 0) {
4240 in->toAudioPort(port);
4241 return NO_ERROR;
4242 }
4243 return BAD_VALUE;
Eric Laurent6a94d692014-05-20 11:18:06 -07004244}
4245
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004246status_t AudioPolicyManager::createAudioPatch(const struct audio_patch *patch,
4247 audio_patch_handle_t *handle,
4248 uid_t uid)
Eric Laurent6a94d692014-05-20 11:18:06 -07004249{
François Gaffieafd4cea2019-11-18 15:50:22 +01004250 ALOGV("%s", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004251 if (handle == NULL || patch == NULL) {
4252 return BAD_VALUE;
4253 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004254 ALOGV("%s num sources %d num sinks %d", __func__, patch->num_sources, patch->num_sinks);
Mikhail Naganovac9858b2018-06-15 13:12:37 -07004255 if (!audio_patch_is_valid(patch)) {
Eric Laurent874c42872014-08-08 15:13:39 -07004256 return BAD_VALUE;
4257 }
4258 // only one source per audio patch supported for now
4259 if (patch->num_sources > 1) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004260 return INVALID_OPERATION;
4261 }
Eric Laurent874c42872014-08-08 15:13:39 -07004262 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004263 return INVALID_OPERATION;
4264 }
Eric Laurent874c42872014-08-08 15:13:39 -07004265 for (size_t i = 0; i < patch->num_sinks; i++) {
4266 if (patch->sinks[i].role != AUDIO_PORT_ROLE_SINK) {
4267 return INVALID_OPERATION;
4268 }
4269 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004270
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004271 sp<DeviceDescriptor> srcDevice = mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
4272 sp<DeviceDescriptor> sinkDevice = mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id);
4273 if (srcDevice == nullptr || sinkDevice == nullptr) {
4274 ALOGW("%s could not create patch, invalid sink and/or source device(s)", __func__);
4275 return BAD_VALUE;
4276 }
4277 ALOGV("%s between source %s and sink %s", __func__,
4278 srcDevice->toString().c_str(), sinkDevice->toString().c_str());
4279 audio_port_handle_t portId = PolicyAudioPort::getNextUniqueId();
4280 // Default attributes, default volume priority, not to infer with non raw audio patches.
4281 audio_attributes_t attributes = attributes_initializer(AUDIO_USAGE_MEDIA);
4282 const struct audio_port_config *source = &patch->sources[0];
4283 sp<SourceClientDescriptor> sourceDesc =
4284 new InternalSourceClientDescriptor(
4285 portId, uid, attributes, *source, srcDevice, sinkDevice,
4286 mEngine->getProductStrategyForAttributes(attributes), toVolumeSource(attributes));
4287
4288 status_t status =
4289 connectAudioSourceToSink(sourceDesc, sinkDevice, patch, *handle, uid, 0 /* delayMs */);
4290
4291 if (status != NO_ERROR) {
4292 return INVALID_OPERATION;
4293 }
4294 mAudioSources.add(portId, sourceDesc);
4295 return NO_ERROR;
4296}
4297
4298status_t AudioPolicyManager::connectAudioSourceToSink(
4299 const sp<SourceClientDescriptor>& sourceDesc, const sp<DeviceDescriptor> &sinkDevice,
4300 const struct audio_patch *patch,
4301 audio_patch_handle_t &handle,
4302 uid_t uid, uint32_t delayMs)
4303{
4304 status_t status = createAudioPatchInternal(patch, &handle, uid, delayMs, sourceDesc);
4305 if (status != NO_ERROR || mAudioPatches.indexOfKey(handle) < 0) {
4306 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
4307 return INVALID_OPERATION;
4308 }
4309 sourceDesc->connect(handle, sinkDevice);
4310 if (isMsdPatch(handle)) {
4311 return NO_ERROR;
4312 }
4313 // SW Bridge? (@todo: HW bridge, keep track of HwOutput for device selection "reconsideration")
4314 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
4315 ALOG_ASSERT(swOutput != nullptr, "%s: a swOutput shall always be associated", __func__);
4316 if (swOutput->getClient(sourceDesc->portId()) != nullptr) {
4317 ALOGW("%s source portId has already been attached to outputDesc", __func__);
4318 goto FailurePatchAdded;
4319 }
4320 status = swOutput->start();
4321 if (status != NO_ERROR) {
4322 goto FailureSourceAdded;
4323 }
4324 swOutput->addClient(sourceDesc);
4325 status = startSource(swOutput, sourceDesc, &delayMs);
4326 if (status != NO_ERROR) {
4327 ALOGW("%s failed to start source, error %d", __FUNCTION__, status);
4328 goto FailureSourceActive;
4329 }
4330 if (delayMs != 0) {
4331 usleep(delayMs * 1000);
4332 }
4333 return NO_ERROR;
4334
4335FailureSourceActive:
4336 swOutput->stop();
4337 releaseOutput(sourceDesc->portId());
4338FailureSourceAdded:
4339 sourceDesc->setSwOutput(nullptr);
4340FailurePatchAdded:
4341 releaseAudioPatchInternal(handle);
4342 return INVALID_OPERATION;
4343}
4344
4345status_t AudioPolicyManager::createAudioPatchInternal(const struct audio_patch *patch,
4346 audio_patch_handle_t *handle,
4347 uid_t uid, uint32_t delayMs,
4348 const sp<SourceClientDescriptor>& sourceDesc)
4349{
4350 ALOGV("%s num sources %d num sinks %d", __func__, patch->num_sources, patch->num_sinks);
Eric Laurent6a94d692014-05-20 11:18:06 -07004351 sp<AudioPatch> patchDesc;
4352 ssize_t index = mAudioPatches.indexOfKey(*handle);
4353
François Gaffieafd4cea2019-11-18 15:50:22 +01004354 ALOGV("%s source id %d role %d type %d", __func__, patch->sources[0].id,
4355 patch->sources[0].role,
4356 patch->sources[0].type);
Eric Laurent874c42872014-08-08 15:13:39 -07004357#if LOG_NDEBUG == 0
4358 for (size_t i = 0; i < patch->num_sinks; i++) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004359 ALOGV("%s sink %zu: id %d role %d type %d", __func__ ,i, patch->sinks[i].id,
4360 patch->sinks[i].role,
4361 patch->sinks[i].type);
Eric Laurent874c42872014-08-08 15:13:39 -07004362 }
4363#endif
Eric Laurent6a94d692014-05-20 11:18:06 -07004364
4365 if (index >= 0) {
4366 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01004367 ALOGV("%s mUidCached %d patchDesc->mUid %d uid %d",
4368 __func__, mUidCached, patchDesc->getUid(), uid);
4369 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004370 return INVALID_OPERATION;
4371 }
4372 } else {
Glenn Kastena13cde92016-03-28 15:26:02 -07004373 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07004374 }
4375
4376 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004377 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004378 if (outputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004379 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004380 return BAD_VALUE;
4381 }
Eric Laurent84c70242014-06-23 08:46:27 -07004382 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
4383 outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004384 if (patchDesc != 0) {
4385 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004386 ALOGV("%s source id differs for patch current id %d new id %d",
4387 __func__, patchDesc->mPatch.sources[0].id, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004388 return BAD_VALUE;
4389 }
4390 }
Eric Laurent874c42872014-08-08 15:13:39 -07004391 DeviceVector devices;
4392 for (size_t i = 0; i < patch->num_sinks; i++) {
4393 // Only support mix to devices connection
4394 // TODO add support for mix to mix connection
4395 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004396 ALOGV("%s source mix but sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07004397 return INVALID_OPERATION;
4398 }
4399 sp<DeviceDescriptor> devDesc =
4400 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
4401 if (devDesc == 0) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004402 ALOGV("%s out device not found for id %d", __func__, patch->sinks[i].id);
Eric Laurent874c42872014-08-08 15:13:39 -07004403 return BAD_VALUE;
4404 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004405
François Gaffie11d30102018-11-02 16:09:09 +01004406 if (!outputDesc->mProfile->isCompatibleProfile(DeviceVector(devDesc),
Eric Laurent874c42872014-08-08 15:13:39 -07004407 patch->sources[0].sample_rate,
François Gaffie53615e22015-03-19 09:24:12 +01004408 NULL, // updatedSamplingRate
4409 patch->sources[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07004410 NULL, // updatedFormat
François Gaffie53615e22015-03-19 09:24:12 +01004411 patch->sources[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07004412 NULL, // updatedChannelMask
François Gaffie53615e22015-03-19 09:24:12 +01004413 AUDIO_OUTPUT_FLAG_NONE /*FIXME*/)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004414 ALOGV("%s profile not supported for device %08x", __func__, devDesc->type());
Eric Laurent874c42872014-08-08 15:13:39 -07004415 return INVALID_OPERATION;
4416 }
4417 devices.add(devDesc);
4418 }
4419 if (devices.size() == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004420 return INVALID_OPERATION;
4421 }
Eric Laurent874c42872014-08-08 15:13:39 -07004422
Eric Laurent6a94d692014-05-20 11:18:06 -07004423 // TODO: reconfigure output format and channels here
François Gaffieafd4cea2019-11-18 15:50:22 +01004424 ALOGV("%s setting device %s on output %d",
4425 __func__, dumpDeviceTypes(devices.types()).c_str(), outputDesc->mIoHandle);
François Gaffie11d30102018-11-02 16:09:09 +01004426 setOutputDevices(outputDesc, devices, true, 0, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004427 index = mAudioPatches.indexOfKey(*handle);
4428 if (index >= 0) {
4429 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004430 ALOGW("%s setOutputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004431 }
4432 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01004433 patchDesc->setUid(uid);
4434 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004435 } else {
François Gaffieafd4cea2019-11-18 15:50:22 +01004436 ALOGW("%s setOutputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004437 return INVALID_OPERATION;
4438 }
4439 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
4440 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
4441 // input device to input mix connection
Eric Laurent874c42872014-08-08 15:13:39 -07004442 // only one sink supported when connecting an input device to a mix
4443 if (patch->num_sinks > 1) {
4444 return INVALID_OPERATION;
4445 }
François Gaffie53615e22015-03-19 09:24:12 +01004446 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004447 if (inputDesc == NULL) {
4448 return BAD_VALUE;
4449 }
4450 if (patchDesc != 0) {
4451 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
4452 return BAD_VALUE;
4453 }
4454 }
François Gaffie11d30102018-11-02 16:09:09 +01004455 sp<DeviceDescriptor> device =
Eric Laurent6a94d692014-05-20 11:18:06 -07004456 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01004457 if (device == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004458 return BAD_VALUE;
4459 }
4460
François Gaffie11d30102018-11-02 16:09:09 +01004461 if (!inputDesc->mProfile->isCompatibleProfile(DeviceVector(device),
Eric Laurent275e8e92014-11-30 15:14:47 -08004462 patch->sinks[0].sample_rate,
4463 NULL, /*updatedSampleRate*/
4464 patch->sinks[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07004465 NULL, /*updatedFormat*/
Eric Laurent275e8e92014-11-30 15:14:47 -08004466 patch->sinks[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07004467 NULL, /*updatedChannelMask*/
Eric Laurent275e8e92014-11-30 15:14:47 -08004468 // FIXME for the parameter type,
4469 // and the NONE
4470 (audio_output_flags_t)
Glenn Kasten6a8ab052014-07-24 14:08:35 -07004471 AUDIO_INPUT_FLAG_NONE)) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004472 return INVALID_OPERATION;
4473 }
4474 // TODO: reconfigure output format and channels here
François Gaffieafd4cea2019-11-18 15:50:22 +01004475 ALOGV("%s setting device %s on output %d", __func__,
François Gaffie11d30102018-11-02 16:09:09 +01004476 device->toString().c_str(), inputDesc->mIoHandle);
4477 setInputDevice(inputDesc->mIoHandle, device, true, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004478 index = mAudioPatches.indexOfKey(*handle);
4479 if (index >= 0) {
4480 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004481 ALOGW("%s setInputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004482 }
4483 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01004484 patchDesc->setUid(uid);
4485 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004486 } else {
François Gaffieafd4cea2019-11-18 15:50:22 +01004487 ALOGW("%s setInputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004488 return INVALID_OPERATION;
4489 }
4490 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
4491 // device to device connection
4492 if (patchDesc != 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07004493 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004494 return BAD_VALUE;
4495 }
4496 }
François Gaffie11d30102018-11-02 16:09:09 +01004497 sp<DeviceDescriptor> srcDevice =
Eric Laurent6a94d692014-05-20 11:18:06 -07004498 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01004499 if (srcDevice == 0) {
Eric Laurent58f8eb72014-09-12 16:19:41 -07004500 return BAD_VALUE;
4501 }
Eric Laurent874c42872014-08-08 15:13:39 -07004502
Eric Laurent6a94d692014-05-20 11:18:06 -07004503 //update source and sink with our own data as the data passed in the patch may
4504 // be incomplete.
François Gaffieafd4cea2019-11-18 15:50:22 +01004505 PatchBuilder patchBuilder;
4506 audio_port_config sourcePortConfig = {};
Dean Wheatley8bee85a2021-02-10 16:02:23 +11004507
4508 // if first sink is to MSD, establish single MSD patch
4509 if (getMsdAudioOutDevices().contains(
4510 mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id))) {
4511 ALOGV("%s patching to MSD", __FUNCTION__);
4512 patchBuilder = buildMsdPatch(false /*msdIsSource*/, srcDevice);
4513 goto installPatch;
4514 }
4515
François Gaffieafd4cea2019-11-18 15:50:22 +01004516 srcDevice->toAudioPortConfig(&sourcePortConfig, &patch->sources[0]);
4517 patchBuilder.addSource(sourcePortConfig);
Eric Laurent6a94d692014-05-20 11:18:06 -07004518
Eric Laurent874c42872014-08-08 15:13:39 -07004519 for (size_t i = 0; i < patch->num_sinks; i++) {
4520 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004521 ALOGV("%s source device but one sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07004522 return INVALID_OPERATION;
4523 }
François Gaffie11d30102018-11-02 16:09:09 +01004524 sp<DeviceDescriptor> sinkDevice =
Eric Laurent874c42872014-08-08 15:13:39 -07004525 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
François Gaffie11d30102018-11-02 16:09:09 +01004526 if (sinkDevice == 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07004527 return BAD_VALUE;
4528 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004529 audio_port_config sinkPortConfig = {};
4530 sinkDevice->toAudioPortConfig(&sinkPortConfig, &patch->sinks[i]);
4531 patchBuilder.addSink(sinkPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07004532
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004533 // Whatever Sw or Hw bridge, we do attach an SwOutput to an Audio Source for
4534 // volume management purpose (tracking activity)
4535 // In case of Hw bridge, it is a Work Around. The mixPort used is the one declared
4536 // in config XML to reach the sink so that is can be declared as available.
4537 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
4538 sp<SwAudioOutputDescriptor> outputDesc = nullptr;
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004539 if (!sourceDesc->isInternal()) {
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004540 // take care of dynamic routing for SwOutput selection,
4541 audio_attributes_t attributes = sourceDesc->attributes();
4542 audio_stream_type_t stream = sourceDesc->stream();
4543 audio_attributes_t resultAttr;
4544 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
4545 config.sample_rate = sourceDesc->config().sample_rate;
4546 config.channel_mask = sourceDesc->config().channel_mask;
4547 config.format = sourceDesc->config().format;
4548 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
4549 audio_port_handle_t selectedDeviceId = AUDIO_PORT_HANDLE_NONE;
4550 bool isRequestedDeviceForExclusiveUse = false;
4551 output_type_t outputType;
Eric Laurentb0a7bc92022-04-05 15:06:08 +02004552 bool isSpatialized;
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004553 getOutputForAttrInt(&resultAttr, &output, AUDIO_SESSION_NONE, &attributes,
4554 &stream, sourceDesc->uid(), &config, &flags,
4555 &selectedDeviceId, &isRequestedDeviceForExclusiveUse,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02004556 nullptr, &outputType, &isSpatialized);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004557 if (output == AUDIO_IO_HANDLE_NONE) {
4558 ALOGV("%s no output for device %s",
4559 __FUNCTION__, sinkDevice->toString().c_str());
4560 return INVALID_OPERATION;
4561 }
4562 outputDesc = mOutputs.valueFor(output);
4563 if (outputDesc->isDuplicated()) {
4564 ALOGE("%s output is duplicated", __func__);
4565 return INVALID_OPERATION;
4566 }
4567 sourceDesc->setSwOutput(outputDesc);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004568 } else {
4569 // Same for "raw patches" aka created from createAudioPatch API
4570 SortedVector<audio_io_handle_t> outputs =
4571 getOutputsForDevices(DeviceVector(sinkDevice), mOutputs);
4572 // if the sink device is reachable via an opened output stream, request to
4573 // go via this output stream by adding a second source to the patch
4574 // description
4575 output = selectOutput(outputs);
4576 if (output == AUDIO_IO_HANDLE_NONE) {
4577 ALOGE("%s no output available for internal patch sink", __func__);
4578 return INVALID_OPERATION;
4579 }
4580 outputDesc = mOutputs.valueFor(output);
4581 if (outputDesc->isDuplicated()) {
4582 ALOGV("%s output for device %s is duplicated",
4583 __func__, sinkDevice->toString().c_str());
4584 return INVALID_OPERATION;
4585 }
4586 sourceDesc->setSwOutput(outputDesc);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004587 }
Eric Laurent3bcf8592015-04-03 12:13:24 -07004588 // create a software bridge in PatchPanel if:
Scott Randolphf3172402018-01-23 17:06:53 -08004589 // - source and sink devices are on different HW modules OR
Eric Laurent3bcf8592015-04-03 12:13:24 -07004590 // - audio HAL version is < 3.0
Francois Gaffie99896da2018-04-09 11:05:33 +02004591 // - audio HAL version is >= 3.0 but no route has been declared between devices
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004592 // - called from startAudioSource (aka sourceDesc is not internal) and source device
4593 // does not have a gain controller
François Gaffie11d30102018-11-02 16:09:09 +01004594 if (!srcDevice->hasSameHwModuleAs(sinkDevice) ||
4595 (srcDevice->getModuleVersionMajor() < 3) ||
François Gaffieafd4cea2019-11-18 15:50:22 +01004596 !srcDevice->getModule()->supportsPatch(srcDevice, sinkDevice) ||
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004597 (!sourceDesc->isInternal() &&
François Gaffieafd4cea2019-11-18 15:50:22 +01004598 srcDevice->getAudioPort()->getGains().size() == 0)) {
Eric Laurent3bcf8592015-04-03 12:13:24 -07004599 // support only one sink device for now to simplify output selection logic
Eric Laurent874c42872014-08-08 15:13:39 -07004600 if (patch->num_sinks > 1) {
Eric Laurent83b88082014-06-20 18:31:16 -07004601 return INVALID_OPERATION;
4602 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004603 sourceDesc->setUseSwBridge();
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004604 if (outputDesc != nullptr) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004605 audio_port_config srcMixPortConfig = {};
Ytai Ben-Tsvic9d2a912021-11-22 16:43:09 -08004606 outputDesc->toAudioPortConfig(&srcMixPortConfig, nullptr);
François Gaffieafd4cea2019-11-18 15:50:22 +01004607 // for volume control, we may need a valid stream
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004608 srcMixPortConfig.ext.mix.usecase.stream = !sourceDesc->isInternal() ?
4609 mEngine->getStreamTypeForAttributes(sourceDesc->attributes()) :
4610 AUDIO_STREAM_PATCH;
François Gaffieafd4cea2019-11-18 15:50:22 +01004611 patchBuilder.addSource(srcMixPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07004612 }
Eric Laurent83b88082014-06-20 18:31:16 -07004613 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004614 }
4615 // TODO: check from routing capabilities in config file and other conflicting patches
4616
Dean Wheatley8bee85a2021-02-10 16:02:23 +11004617installPatch:
François Gaffieafd4cea2019-11-18 15:50:22 +01004618 status_t status = installPatch(
4619 __func__, index, handle, patchBuilder.patch(), delayMs, uid, &patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07004620 if (status != NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004621 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
Eric Laurent6a94d692014-05-20 11:18:06 -07004622 return INVALID_OPERATION;
4623 }
4624 } else {
4625 return BAD_VALUE;
4626 }
4627 } else {
4628 return BAD_VALUE;
4629 }
4630 return NO_ERROR;
4631}
4632
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004633status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle, uid_t uid)
Eric Laurent6a94d692014-05-20 11:18:06 -07004634{
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004635 ALOGV("%s patch %d", __func__, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004636 ssize_t index = mAudioPatches.indexOfKey(handle);
4637
4638 if (index < 0) {
4639 return BAD_VALUE;
4640 }
4641 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01004642 ALOGV("%s() mUidCached %d patchDesc->mUid %d uid %d",
4643 __func__, mUidCached, patchDesc->getUid(), uid);
4644 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004645 return INVALID_OPERATION;
4646 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004647 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
4648 for (size_t i = 0; i < mAudioSources.size(); i++) {
4649 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
4650 if (sourceDesc != nullptr && sourceDesc->getPatchHandle() == handle) {
4651 portId = sourceDesc->portId();
4652 break;
4653 }
4654 }
4655 return portId != AUDIO_PORT_HANDLE_NONE ?
4656 stopAudioSource(portId) : releaseAudioPatchInternal(handle);
François Gaffieafd4cea2019-11-18 15:50:22 +01004657}
Eric Laurent6a94d692014-05-20 11:18:06 -07004658
François Gaffieafd4cea2019-11-18 15:50:22 +01004659status_t AudioPolicyManager::releaseAudioPatchInternal(audio_patch_handle_t handle,
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004660 uint32_t delayMs,
4661 const sp<SourceClientDescriptor>& sourceDesc)
François Gaffieafd4cea2019-11-18 15:50:22 +01004662{
4663 ALOGV("%s patch %d", __func__, handle);
4664 if (mAudioPatches.indexOfKey(handle) < 0) {
4665 ALOGE("%s: no patch found with handle=%d", __func__, handle);
4666 return BAD_VALUE;
4667 }
4668 sp<AudioPatch> patchDesc = mAudioPatches.valueFor(handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004669 struct audio_patch *patch = &patchDesc->mPatch;
François Gaffieafd4cea2019-11-18 15:50:22 +01004670 patchDesc->setUid(mUidCached);
Eric Laurent6a94d692014-05-20 11:18:06 -07004671 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004672 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004673 if (outputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004674 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004675 return BAD_VALUE;
4676 }
4677
François Gaffie11d30102018-11-02 16:09:09 +01004678 setOutputDevices(outputDesc,
4679 getNewOutputDevices(outputDesc, true /*fromCache*/),
4680 true,
4681 0,
4682 NULL);
Eric Laurent6a94d692014-05-20 11:18:06 -07004683 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
4684 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
François Gaffie53615e22015-03-19 09:24:12 +01004685 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004686 if (inputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004687 ALOGV("%s input not found for id %d", __func__, patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004688 return BAD_VALUE;
4689 }
4690 setInputDevice(inputDesc->mIoHandle,
Eric Laurentfb66dd92016-01-28 18:32:03 -08004691 getNewInputDevice(inputDesc),
Eric Laurent6a94d692014-05-20 11:18:06 -07004692 true,
4693 NULL);
4694 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004695 status_t status =
4696 mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
4697 ALOGV("%s patch panel returned %d patchHandle %d",
4698 __func__, status, patchDesc->getAfHandle());
4699 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004700 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004701 mpClientInterface->onAudioPatchListUpdate();
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004702 // SW or HW Bridge
4703 sp<SwAudioOutputDescriptor> outputDesc = nullptr;
4704 audio_patch_handle_t patchHandle = AUDIO_PATCH_HANDLE_NONE;
Francois Gaffie7feb8542020-04-06 17:39:47 +02004705 if (patch->num_sources > 1 && patch->sources[1].type == AUDIO_PORT_TYPE_MIX) {
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004706 outputDesc = mOutputs.getOutputFromId(patch->sources[1].id);
4707 } else if (patch->num_sources == 1 && sourceDesc != nullptr) {
4708 outputDesc = sourceDesc->swOutput().promote();
4709 }
4710 if (outputDesc == nullptr) {
4711 ALOGW("%s no output for id %d", __func__, patch->sources[0].id);
4712 // releaseOutput has already called closeOutput in case of direct output
4713 return NO_ERROR;
4714 }
4715 if (!outputDesc->isActive() && !sourceDesc->useSwBridge()) {
4716 resetOutputDevice(outputDesc);
4717 } else {
4718 // Reuse patch handle if still valid / do not force rerouting if still routed
4719 patchHandle = outputDesc->getPatchHandle();
Francois Gaffie7feb8542020-04-06 17:39:47 +02004720 setOutputDevices(outputDesc,
4721 getNewOutputDevices(outputDesc, true /*fromCache*/),
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004722 patchHandle == AUDIO_PATCH_HANDLE_NONE, /*force*/
Francois Gaffie7feb8542020-04-06 17:39:47 +02004723 0,
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004724 patchHandle == AUDIO_PATCH_HANDLE_NONE ? nullptr : &patchHandle);
Francois Gaffie7feb8542020-04-06 17:39:47 +02004725 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004726 } else {
4727 return BAD_VALUE;
4728 }
4729 } else {
4730 return BAD_VALUE;
4731 }
4732 return NO_ERROR;
4733}
4734
4735status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
4736 struct audio_patch *patches,
4737 unsigned int *generation)
4738{
François Gaffie53615e22015-03-19 09:24:12 +01004739 if (generation == NULL) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004740 return BAD_VALUE;
4741 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004742 *generation = curAudioPortGeneration();
François Gaffie53615e22015-03-19 09:24:12 +01004743 return mAudioPatches.listAudioPatches(num_patches, patches);
Eric Laurent6a94d692014-05-20 11:18:06 -07004744}
4745
Eric Laurente1715a42014-05-20 11:30:42 -07004746status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07004747{
Eric Laurente1715a42014-05-20 11:30:42 -07004748 ALOGV("setAudioPortConfig()");
4749
4750 if (config == NULL) {
4751 return BAD_VALUE;
4752 }
4753 ALOGV("setAudioPortConfig() on port handle %d", config->id);
4754 // Only support gain configuration for now
Eric Laurenta121f902014-06-03 13:32:54 -07004755 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
4756 return INVALID_OPERATION;
Eric Laurente1715a42014-05-20 11:30:42 -07004757 }
4758
Eric Laurenta121f902014-06-03 13:32:54 -07004759 sp<AudioPortConfig> audioPortConfig;
Eric Laurente1715a42014-05-20 11:30:42 -07004760 if (config->type == AUDIO_PORT_TYPE_MIX) {
4761 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004762 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07004763 if (outputDesc == NULL) {
4764 return BAD_VALUE;
4765 }
Eric Laurent84c70242014-06-23 08:46:27 -07004766 ALOG_ASSERT(!outputDesc->isDuplicated(),
4767 "setAudioPortConfig() called on duplicated output %d",
4768 outputDesc->mIoHandle);
Eric Laurenta121f902014-06-03 13:32:54 -07004769 audioPortConfig = outputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07004770 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
François Gaffie53615e22015-03-19 09:24:12 +01004771 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07004772 if (inputDesc == NULL) {
4773 return BAD_VALUE;
4774 }
Eric Laurenta121f902014-06-03 13:32:54 -07004775 audioPortConfig = inputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07004776 } else {
4777 return BAD_VALUE;
4778 }
4779 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
4780 sp<DeviceDescriptor> deviceDesc;
4781 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
4782 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
4783 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
4784 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
4785 } else {
4786 return BAD_VALUE;
4787 }
4788 if (deviceDesc == NULL) {
4789 return BAD_VALUE;
4790 }
Eric Laurenta121f902014-06-03 13:32:54 -07004791 audioPortConfig = deviceDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07004792 } else {
4793 return BAD_VALUE;
4794 }
4795
Mikhail Naganov7be71d22018-05-23 16:51:46 -07004796 struct audio_port_config backupConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07004797 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
4798 if (status == NO_ERROR) {
Mikhail Naganov7be71d22018-05-23 16:51:46 -07004799 struct audio_port_config newConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07004800 audioPortConfig->toAudioPortConfig(&newConfig, config);
4801 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
Eric Laurente1715a42014-05-20 11:30:42 -07004802 }
Eric Laurenta121f902014-06-03 13:32:54 -07004803 if (status != NO_ERROR) {
4804 audioPortConfig->applyAudioPortConfig(&backupConfig);
Eric Laurente1715a42014-05-20 11:30:42 -07004805 }
Eric Laurente1715a42014-05-20 11:30:42 -07004806
4807 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07004808}
4809
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004810void AudioPolicyManager::releaseResourcesForUid(uid_t uid)
4811{
Eric Laurentd60560a2015-04-10 11:31:20 -07004812 clearAudioSources(uid);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004813 clearAudioPatches(uid);
4814 clearSessionRoutes(uid);
4815}
4816
Eric Laurent6a94d692014-05-20 11:18:06 -07004817void AudioPolicyManager::clearAudioPatches(uid_t uid)
4818{
Eric Laurent0add0fd2014-12-04 18:58:14 -08004819 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004820 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
François Gaffieafd4cea2019-11-18 15:50:22 +01004821 if (patchDesc->getUid() == uid) {
Eric Laurent0add0fd2014-12-04 18:58:14 -08004822 releaseAudioPatch(mAudioPatches.keyAt(i), uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07004823 }
4824 }
4825}
4826
François Gaffiec005e562018-11-06 15:04:49 +01004827void AudioPolicyManager::checkStrategyRoute(product_strategy_t ps, audio_io_handle_t ouptutToSkip)
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004828{
François Gaffiec005e562018-11-06 15:04:49 +01004829 // Take the first attributes following the product strategy as it is used to retrieve the routed
4830 // device. All attributes wihin a strategy follows the same "routing strategy"
4831 auto attributes = mEngine->getAllAttributesForProductStrategy(ps).front();
4832 DeviceVector devices = mEngine->getOutputDevicesForAttributes(attributes, nullptr, false);
François Gaffie11d30102018-11-02 16:09:09 +01004833 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004834 for (size_t j = 0; j < mOutputs.size(); j++) {
4835 if (mOutputs.keyAt(j) == ouptutToSkip) {
4836 continue;
4837 }
4838 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(j);
François Gaffiec005e562018-11-06 15:04:49 +01004839 if (!outputDesc->isStrategyActive(ps)) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004840 continue;
4841 }
4842 // If the default device for this strategy is on another output mix,
4843 // invalidate all tracks in this strategy to force re connection.
4844 // Otherwise select new device on the output mix.
4845 if (outputs.indexOf(mOutputs.keyAt(j)) < 0) {
François Gaffiec005e562018-11-06 15:04:49 +01004846 for (auto stream : mEngine->getStreamTypesForProductStrategy(ps)) {
4847 mpClientInterface->invalidateStream(stream);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004848 }
4849 } else {
François Gaffie11d30102018-11-02 16:09:09 +01004850 setOutputDevices(
4851 outputDesc, getNewOutputDevices(outputDesc, false /*fromCache*/), false);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004852 }
4853 }
4854}
4855
4856void AudioPolicyManager::clearSessionRoutes(uid_t uid)
4857{
4858 // remove output routes associated with this uid
François Gaffiec005e562018-11-06 15:04:49 +01004859 std::vector<product_strategy_t> affectedStrategies;
Eric Laurent97ac8712018-07-27 18:59:02 -07004860 for (size_t i = 0; i < mOutputs.size(); i++) {
4861 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07004862 for (const auto& client : outputDesc->getClientIterable()) {
4863 if (client->hasPreferredDevice() && client->uid() == uid) {
4864 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
François Gaffiec005e562018-11-06 15:04:49 +01004865 auto clientStrategy = client->strategy();
4866 if (std::find(begin(affectedStrategies), end(affectedStrategies), clientStrategy) !=
4867 end(affectedStrategies)) {
4868 continue;
4869 }
4870 affectedStrategies.push_back(client->strategy());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004871 }
4872 }
4873 }
4874 // reroute outputs if necessary
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004875 for (const auto& strategy : affectedStrategies) {
4876 checkStrategyRoute(strategy, AUDIO_IO_HANDLE_NONE);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004877 }
4878
4879 // remove input routes associated with this uid
4880 SortedVector<audio_source_t> affectedSources;
Eric Laurent97ac8712018-07-27 18:59:02 -07004881 for (size_t i = 0; i < mInputs.size(); i++) {
4882 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07004883 for (const auto& client : inputDesc->getClientIterable()) {
4884 if (client->hasPreferredDevice() && client->uid() == uid) {
4885 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
4886 affectedSources.add(client->source());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004887 }
4888 }
4889 }
4890 // reroute inputs if necessary
4891 SortedVector<audio_io_handle_t> inputsToClose;
4892 for (size_t i = 0; i < mInputs.size(); i++) {
4893 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Eric Laurent4eb58f12018-12-07 16:41:02 -08004894 if (affectedSources.indexOf(inputDesc->source()) >= 0) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004895 inputsToClose.add(inputDesc->mIoHandle);
4896 }
4897 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004898 for (const auto& input : inputsToClose) {
4899 closeInput(input);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004900 }
4901}
4902
Eric Laurentd60560a2015-04-10 11:31:20 -07004903void AudioPolicyManager::clearAudioSources(uid_t uid)
4904{
4905 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004906 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
4907 if (sourceDesc->uid() == uid) {
Eric Laurentd60560a2015-04-10 11:31:20 -07004908 stopAudioSource(mAudioSources.keyAt(i));
4909 }
4910 }
4911}
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004912
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07004913status_t AudioPolicyManager::acquireSoundTriggerSession(audio_session_t *session,
4914 audio_io_handle_t *ioHandle,
4915 audio_devices_t *device)
4916{
Glenn Kastenf0c6d7d2016-02-26 10:44:04 -08004917 *session = (audio_session_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
4918 *ioHandle = (audio_io_handle_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
Francois Gaffie716e1432019-01-14 16:58:59 +01004919 audio_attributes_t attr = { .source = AUDIO_SOURCE_HOTWORD };
François Gaffiec005e562018-11-06 15:04:49 +01004920 *device = mEngine->getInputDeviceForAttributes(attr)->type();
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07004921
François Gaffiedf372692015-03-19 10:43:27 +01004922 return mSoundTriggerSessions.acquireSession(*session, *ioHandle);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07004923}
4924
Eric Laurentd60560a2015-04-10 11:31:20 -07004925status_t AudioPolicyManager::startAudioSource(const struct audio_port_config *source,
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004926 const audio_attributes_t *attributes,
4927 audio_port_handle_t *portId,
4928 uid_t uid)
Eric Laurent554a2772015-04-10 11:29:24 -07004929{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004930 ALOGV("%s", __FUNCTION__);
4931 *portId = AUDIO_PORT_HANDLE_NONE;
4932
4933 if (source == NULL || attributes == NULL || portId == NULL) {
4934 ALOGW("%s invalid argument: source %p attributes %p handle %p",
4935 __FUNCTION__, source, attributes, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07004936 return BAD_VALUE;
4937 }
4938
Eric Laurentd60560a2015-04-10 11:31:20 -07004939 if (source->role != AUDIO_PORT_ROLE_SOURCE ||
4940 source->type != AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004941 ALOGW("%s INVALID_OPERATION source->role %d source->type %d",
4942 __FUNCTION__, source->role, source->type);
Eric Laurentd60560a2015-04-10 11:31:20 -07004943 return INVALID_OPERATION;
4944 }
4945
François Gaffie11d30102018-11-02 16:09:09 +01004946 sp<DeviceDescriptor> srcDevice =
Eric Laurentd60560a2015-04-10 11:31:20 -07004947 mAvailableInputDevices.getDevice(source->ext.device.type,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08004948 String8(source->ext.device.address),
4949 AUDIO_FORMAT_DEFAULT);
François Gaffie11d30102018-11-02 16:09:09 +01004950 if (srcDevice == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004951 ALOGW("%s source->ext.device.type %08x not found", __FUNCTION__, source->ext.device.type);
Eric Laurentd60560a2015-04-10 11:31:20 -07004952 return BAD_VALUE;
4953 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004954
jiabin4ef93452019-09-10 14:29:54 -07004955 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurentd60560a2015-04-10 11:31:20 -07004956
François Gaffieaaac0fd2018-11-22 17:56:39 +01004957 sp<SourceClientDescriptor> sourceDesc =
François Gaffieafd4cea2019-11-18 15:50:22 +01004958 new SourceClientDescriptor(*portId, uid, *attributes, *source, srcDevice,
François Gaffieaaac0fd2018-11-22 17:56:39 +01004959 mEngine->getStreamTypeForAttributes(*attributes),
4960 mEngine->getProductStrategyForAttributes(*attributes),
4961 toVolumeSource(*attributes));
Eric Laurentd60560a2015-04-10 11:31:20 -07004962
4963 status_t status = connectAudioSource(sourceDesc);
4964 if (status == NO_ERROR) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004965 mAudioSources.add(*portId, sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07004966 }
4967 return status;
4968}
4969
Francois Gaffie601801d2021-06-22 13:27:39 +02004970sp<SourceClientDescriptor> AudioPolicyManager::startAudioSourceInternal(
4971 const struct audio_port_config *source, const audio_attributes_t *attributes, uid_t uid)
4972{
4973 ALOGV("%s", __FUNCTION__);
4974 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
4975
4976 status_t status = startAudioSource(source, attributes, &portId, uid);
4977 ALOGE_IF(status != OK, "%s: failed to start audio source (%d)", __func__, status);
4978 return mAudioSources.valueFor(portId);
4979}
4980
4981
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004982status_t AudioPolicyManager::connectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07004983{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004984 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->portId());
Eric Laurentd60560a2015-04-10 11:31:20 -07004985
4986 // make sure we only have one patch per source.
4987 disconnectAudioSource(sourceDesc);
4988
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004989 audio_attributes_t attributes = sourceDesc->attributes();
Francois Gaffiea0e5c992020-09-29 16:05:07 +02004990 // May the device (dynamic) have been disconnected/reconnected, id has changed.
4991 sp<DeviceDescriptor> srcDevice = mAvailableInputDevices.getDevice(
4992 sourceDesc->srcDevice()->type(),
4993 String8(sourceDesc->srcDevice()->address().c_str()),
4994 AUDIO_FORMAT_DEFAULT);
François Gaffiec005e562018-11-06 15:04:49 +01004995 DeviceVector sinkDevices =
Francois Gaffieff1eb522020-05-06 18:37:04 +02004996 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false /*fromCache*/);
François Gaffiec005e562018-11-06 15:04:49 +01004997 ALOG_ASSERT(!sinkDevices.isEmpty(), "connectAudioSource(): no device found for attributes");
François Gaffie11d30102018-11-02 16:09:09 +01004998 sp<DeviceDescriptor> sinkDevice = sinkDevices.itemAt(0);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02004999 if (!mAvailableOutputDevices.contains(sinkDevice)) {
5000 ALOGE("%s Device %s not available", __func__, sinkDevice->toString().c_str());
5001 return INVALID_OPERATION;
5002 }
François Gaffieafd4cea2019-11-18 15:50:22 +01005003 PatchBuilder patchBuilder;
5004 patchBuilder.addSink(sinkDevice).addSource(srcDevice);
5005 audio_patch_handle_t handle = AUDIO_PATCH_HANDLE_NONE;
François Gaffieafd4cea2019-11-18 15:50:22 +01005006
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005007 return connectAudioSourceToSink(
5008 sourceDesc, sinkDevice, patchBuilder.patch(), handle, mUidCached, 0 /*delayMs*/);
Eric Laurent554a2772015-04-10 11:29:24 -07005009}
5010
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005011status_t AudioPolicyManager::stopAudioSource(audio_port_handle_t portId)
Eric Laurent554a2772015-04-10 11:29:24 -07005012{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005013 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueFor(portId);
5014 ALOGV("%s port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005015 if (sourceDesc == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005016 ALOGW("%s unknown source for port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005017 return BAD_VALUE;
5018 }
5019 status_t status = disconnectAudioSource(sourceDesc);
5020
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005021 mAudioSources.removeItem(portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005022 return status;
5023}
5024
Andy Hung2ddee192015-12-18 17:34:44 -08005025status_t AudioPolicyManager::setMasterMono(bool mono)
5026{
5027 if (mMasterMono == mono) {
5028 return NO_ERROR;
5029 }
5030 mMasterMono = mono;
5031 // if enabling mono we close all offloaded devices, which will invalidate the
5032 // corresponding AudioTrack. The AudioTrack client/MediaPlayer is responsible
5033 // for recreating the new AudioTrack as non-offloaded PCM.
5034 //
5035 // If disabling mono, we leave all tracks as is: we don't know which clients
5036 // and tracks are able to be recreated as offloaded. The next "song" should
5037 // play back offloaded.
5038 if (mMasterMono) {
5039 Vector<audio_io_handle_t> offloaded;
5040 for (size_t i = 0; i < mOutputs.size(); ++i) {
5041 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
5042 if (desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
5043 offloaded.push(desc->mIoHandle);
5044 }
5045 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005046 for (const auto& handle : offloaded) {
5047 closeOutput(handle);
Andy Hung2ddee192015-12-18 17:34:44 -08005048 }
5049 }
5050 // update master mono for all remaining outputs
5051 for (size_t i = 0; i < mOutputs.size(); ++i) {
5052 updateMono(mOutputs.keyAt(i));
5053 }
5054 return NO_ERROR;
5055}
5056
5057status_t AudioPolicyManager::getMasterMono(bool *mono)
5058{
5059 *mono = mMasterMono;
5060 return NO_ERROR;
5061}
5062
Eric Laurentac9cef52017-06-09 15:46:26 -07005063float AudioPolicyManager::getStreamVolumeDB(
5064 audio_stream_type_t stream, int index, audio_devices_t device)
5065{
jiabin9a3361e2019-10-01 09:38:30 -07005066 return computeVolume(getVolumeCurves(stream), toVolumeSource(stream), index, {device});
Eric Laurentac9cef52017-06-09 15:46:26 -07005067}
5068
jiabin81772902018-04-02 17:52:27 -07005069status_t AudioPolicyManager::getSurroundFormats(unsigned int *numSurroundFormats,
5070 audio_format_t *surroundFormats,
Kriti Dang6537def2021-03-02 13:46:59 +01005071 bool *surroundFormatsEnabled)
jiabin81772902018-04-02 17:52:27 -07005072{
Kriti Dang6537def2021-03-02 13:46:59 +01005073 if (numSurroundFormats == nullptr || (*numSurroundFormats != 0 &&
5074 (surroundFormats == nullptr || surroundFormatsEnabled == nullptr))) {
jiabin81772902018-04-02 17:52:27 -07005075 return BAD_VALUE;
5076 }
Kriti Dang6537def2021-03-02 13:46:59 +01005077 ALOGV("%s() numSurroundFormats %d surroundFormats %p surroundFormatsEnabled %p",
5078 __func__, *numSurroundFormats, surroundFormats, surroundFormatsEnabled);
jiabin81772902018-04-02 17:52:27 -07005079
5080 size_t formatsWritten = 0;
5081 size_t formatsMax = *numSurroundFormats;
Kriti Dangef6be8f2020-11-05 11:58:19 +01005082
Kriti Dang6537def2021-03-02 13:46:59 +01005083 *numSurroundFormats = mConfig.getSurroundFormats().size();
Mikhail Naganov100f0122018-11-29 11:22:16 -08005084 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
5085 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Kriti Dang6537def2021-03-02 13:46:59 +01005086 for (const auto& format: mConfig.getSurroundFormats()) {
jiabin81772902018-04-02 17:52:27 -07005087 if (formatsWritten < formatsMax) {
Kriti Dang6537def2021-03-02 13:46:59 +01005088 surroundFormats[formatsWritten] = format.first;
Mikhail Naganov100f0122018-11-29 11:22:16 -08005089 bool formatEnabled = true;
5090 switch (forceUse) {
5091 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL:
Kriti Dang6537def2021-03-02 13:46:59 +01005092 formatEnabled = mManualSurroundFormats.count(format.first) != 0;
Mikhail Naganov100f0122018-11-29 11:22:16 -08005093 break;
5094 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER:
5095 formatEnabled = false;
5096 break;
5097 default: // AUTO or ALWAYS => true
5098 break;
jiabin81772902018-04-02 17:52:27 -07005099 }
5100 surroundFormatsEnabled[formatsWritten++] = formatEnabled;
5101 }
jiabin81772902018-04-02 17:52:27 -07005102 }
5103 return NO_ERROR;
5104}
5105
Kriti Dang6537def2021-03-02 13:46:59 +01005106status_t AudioPolicyManager::getReportedSurroundFormats(unsigned int *numSurroundFormats,
5107 audio_format_t *surroundFormats) {
5108 if (numSurroundFormats == nullptr || (*numSurroundFormats != 0 && surroundFormats == nullptr)) {
5109 return BAD_VALUE;
5110 }
5111 ALOGV("%s() numSurroundFormats %d surroundFormats %p",
5112 __func__, *numSurroundFormats, surroundFormats);
5113
5114 size_t formatsWritten = 0;
5115 size_t formatsMax = *numSurroundFormats;
5116 std::unordered_set<audio_format_t> formats; // Uses primary surround formats only
5117
5118 // Return formats from all device profiles that have already been resolved by
5119 // checkOutputsForDevice().
5120 for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
5121 sp<DeviceDescriptor> device = mAvailableOutputDevices[i];
5122 audio_devices_t deviceType = device->type();
5123 // Enabling/disabling formats are applied to only HDMI devices. So, this function
5124 // returns formats reported by HDMI devices.
5125 if (deviceType != AUDIO_DEVICE_OUT_HDMI) {
5126 continue;
5127 }
5128 // Formats reported by sink devices
5129 std::unordered_set<audio_format_t> formatset;
5130 if (auto it = mReportedFormatsMap.find(device); it != mReportedFormatsMap.end()) {
5131 formatset.insert(it->second.begin(), it->second.end());
5132 }
5133
5134 // Formats hard-coded in the in policy configuration file (if any).
5135 FormatVector encodedFormats = device->encodedFormats();
5136 formatset.insert(encodedFormats.begin(), encodedFormats.end());
5137 // Filter the formats which are supported by the vendor hardware.
5138 for (auto it = formatset.begin(); it != formatset.end(); ++it) {
5139 if (mConfig.getSurroundFormats().count(*it) != 0) {
5140 formats.insert(*it);
5141 } else {
5142 for (const auto& pair : mConfig.getSurroundFormats()) {
5143 if (pair.second.count(*it) != 0) {
5144 formats.insert(pair.first);
5145 break;
5146 }
5147 }
5148 }
5149 }
5150 }
5151 *numSurroundFormats = formats.size();
5152 for (const auto& format: formats) {
5153 if (formatsWritten < formatsMax) {
5154 surroundFormats[formatsWritten++] = format;
5155 }
5156 }
5157 return NO_ERROR;
5158}
5159
jiabin81772902018-04-02 17:52:27 -07005160status_t AudioPolicyManager::setSurroundFormatEnabled(audio_format_t audioFormat, bool enabled)
5161{
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005162 ALOGV("%s() format 0x%X enabled %d", __func__, audioFormat, enabled);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07005163 const auto& formatIter = mConfig.getSurroundFormats().find(audioFormat);
5164 if (formatIter == mConfig.getSurroundFormats().end()) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005165 ALOGW("%s() format 0x%X is not a known surround format", __func__, audioFormat);
jiabin81772902018-04-02 17:52:27 -07005166 return BAD_VALUE;
5167 }
5168
Mikhail Naganov100f0122018-11-29 11:22:16 -08005169 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND) !=
5170 AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005171 ALOGW("%s() not in manual mode for surround sound format selection", __func__);
jiabin81772902018-04-02 17:52:27 -07005172 return INVALID_OPERATION;
5173 }
5174
Mikhail Naganov100f0122018-11-29 11:22:16 -08005175 if ((mManualSurroundFormats.count(audioFormat) != 0) == enabled) {
jiabin81772902018-04-02 17:52:27 -07005176 return NO_ERROR;
5177 }
5178
Mikhail Naganov100f0122018-11-29 11:22:16 -08005179 std::unordered_set<audio_format_t> surroundFormatsBackup(mManualSurroundFormats);
jiabin81772902018-04-02 17:52:27 -07005180 if (enabled) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005181 mManualSurroundFormats.insert(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07005182 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005183 mManualSurroundFormats.insert(subFormat);
jiabin81772902018-04-02 17:52:27 -07005184 }
5185 } else {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005186 mManualSurroundFormats.erase(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07005187 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005188 mManualSurroundFormats.erase(subFormat);
jiabin81772902018-04-02 17:52:27 -07005189 }
5190 }
5191
5192 sp<SwAudioOutputDescriptor> outputDesc;
5193 bool profileUpdated = false;
jiabin9a3361e2019-10-01 09:38:30 -07005194 DeviceVector hdmiOutputDevices = mAvailableOutputDevices.getDevicesFromType(
5195 AUDIO_DEVICE_OUT_HDMI);
jiabin81772902018-04-02 17:52:27 -07005196 for (size_t i = 0; i < hdmiOutputDevices.size(); i++) {
5197 // Simulate reconnection to update enabled surround sound formats.
jiabince9f20e2019-09-12 16:29:15 -07005198 String8 address = String8(hdmiOutputDevices[i]->address().c_str());
jiabin5740f082019-08-19 15:08:30 -07005199 std::string name = hdmiOutputDevices[i]->getName();
jiabin81772902018-04-02 17:52:27 -07005200 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
5201 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
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 if (status != NO_ERROR) {
5206 continue;
5207 }
5208 status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
5209 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
5210 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005211 name.c_str(),
5212 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005213 profileUpdated |= (status == NO_ERROR);
5214 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08005215 // FIXME: Why doing this for input HDMI devices if we don't augment their reported formats?
jiabin9a3361e2019-10-01 09:38:30 -07005216 DeviceVector hdmiInputDevices = mAvailableInputDevices.getDevicesFromType(
jiabin81772902018-04-02 17:52:27 -07005217 AUDIO_DEVICE_IN_HDMI);
5218 for (size_t i = 0; i < hdmiInputDevices.size(); i++) {
5219 // Simulate reconnection to update enabled surround sound formats.
jiabince9f20e2019-09-12 16:29:15 -07005220 String8 address = String8(hdmiInputDevices[i]->address().c_str());
jiabin5740f082019-08-19 15:08:30 -07005221 std::string name = hdmiInputDevices[i]->getName();
jiabin81772902018-04-02 17:52:27 -07005222 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
5223 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
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 if (status != NO_ERROR) {
5228 continue;
5229 }
5230 status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
5231 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
5232 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005233 name.c_str(),
5234 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005235 profileUpdated |= (status == NO_ERROR);
5236 }
5237
jiabin81772902018-04-02 17:52:27 -07005238 if (!profileUpdated) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005239 ALOGW("%s() no audio profiles updated, undoing surround formats change", __func__);
Mikhail Naganov100f0122018-11-29 11:22:16 -08005240 mManualSurroundFormats = std::move(surroundFormatsBackup);
jiabin81772902018-04-02 17:52:27 -07005241 }
5242
5243 return profileUpdated ? NO_ERROR : INVALID_OPERATION;
5244}
5245
Eric Laurent5ada82e2019-08-29 17:53:54 -07005246void AudioPolicyManager::setAppState(audio_port_handle_t portId, app_state_t state)
Svet Ganovf4ddfef2018-01-16 07:37:58 -08005247{
Eric Laurent5ada82e2019-08-29 17:53:54 -07005248 ALOGV("%s(portId:%d, state:%d)", __func__, portId, state);
Eric Laurenta9f86652018-11-28 17:23:11 -08005249 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent5ada82e2019-08-29 17:53:54 -07005250 mInputs.valueAt(i)->setAppState(portId, state);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08005251 }
5252}
5253
jiabin6012f912018-11-02 17:06:30 -07005254bool AudioPolicyManager::isHapticPlaybackSupported()
5255{
5256 for (const auto& hwModule : mHwModules) {
5257 const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
5258 for (const auto &outProfile : outputProfiles) {
5259 struct audio_port audioPort;
5260 outProfile->toAudioPort(&audioPort);
5261 for (size_t i = 0; i < audioPort.num_channel_masks; i++) {
5262 if (audioPort.channel_masks[i] & AUDIO_CHANNEL_HAPTIC_ALL) {
5263 return true;
5264 }
5265 }
5266 }
5267 }
5268 return false;
5269}
5270
Carter Hsu325a8eb2022-01-19 19:56:51 +08005271bool AudioPolicyManager::isUltrasoundSupported()
5272{
5273 bool hasUltrasoundOutput = false;
5274 bool hasUltrasoundInput = false;
5275 for (const auto& hwModule : mHwModules) {
5276 const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
5277 if (!hasUltrasoundOutput) {
5278 for (const auto &outProfile : outputProfiles) {
5279 if (outProfile->getFlags() & AUDIO_OUTPUT_FLAG_ULTRASOUND) {
5280 hasUltrasoundOutput = true;
5281 break;
5282 }
5283 }
5284 }
5285
5286 const InputProfileCollection &inputProfiles = hwModule->getInputProfiles();
5287 if (!hasUltrasoundInput) {
5288 for (const auto &inputProfile : inputProfiles) {
5289 if (inputProfile->getFlags() & AUDIO_INPUT_FLAG_ULTRASOUND) {
5290 hasUltrasoundInput = true;
5291 break;
5292 }
5293 }
5294 }
5295
5296 if (hasUltrasoundOutput && hasUltrasoundInput)
5297 return true;
5298 }
5299 return false;
5300}
5301
Eric Laurent8340e672019-11-06 11:01:08 -08005302bool AudioPolicyManager::isCallScreenModeSupported()
5303{
5304 return getConfig().isCallScreenModeSupported();
5305}
5306
5307
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005308status_t AudioPolicyManager::disconnectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07005309{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005310 ALOGV("%s port Id %d", __FUNCTION__, sourceDesc->portId());
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005311 if (!sourceDesc->isConnected()) {
5312 ALOGV("%s port Id %d already disconnected", __FUNCTION__, sourceDesc->portId());
5313 return NO_ERROR;
5314 }
François Gaffieafd4cea2019-11-18 15:50:22 +01005315 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
5316 if (swOutput != 0) {
5317 status_t status = stopSource(swOutput, sourceDesc);
Eric Laurent733ce942017-12-07 12:18:25 -08005318 if (status == NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005319 swOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08005320 }
jiabinbce0c1d2020-10-05 11:20:18 -07005321 if (releaseOutput(sourceDesc->portId())) {
5322 // The output descriptor is reopened to query dynamic profiles. In that case, there is
5323 // no need to release audio patch here but just return NO_ERROR.
5324 return NO_ERROR;
5325 }
Eric Laurentd60560a2015-04-10 11:31:20 -07005326 } else {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005327 sp<HwAudioOutputDescriptor> hwOutputDesc = sourceDesc->hwOutput().promote();
Eric Laurentd60560a2015-04-10 11:31:20 -07005328 if (hwOutputDesc != 0) {
Eric Laurentd60560a2015-04-10 11:31:20 -07005329 // close Hwoutput and remove from mHwOutputs
5330 } else {
5331 ALOGW("%s source has neither SW nor HW output", __FUNCTION__);
5332 }
5333 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005334 status_t status = releaseAudioPatchInternal(sourceDesc->getPatchHandle(), 0, sourceDesc);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005335 sourceDesc->disconnect();
5336 return status;
Eric Laurentd60560a2015-04-10 11:31:20 -07005337}
5338
François Gaffiec005e562018-11-06 15:04:49 +01005339sp<SourceClientDescriptor> AudioPolicyManager::getSourceForAttributesOnOutput(
5340 audio_io_handle_t output, const audio_attributes_t &attr)
Eric Laurentd60560a2015-04-10 11:31:20 -07005341{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005342 sp<SourceClientDescriptor> source;
Eric Laurentd60560a2015-04-10 11:31:20 -07005343 for (size_t i = 0; i < mAudioSources.size(); i++) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005344 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005345 sp<SwAudioOutputDescriptor> outputDesc = sourceDesc->swOutput().promote();
François Gaffiec005e562018-11-06 15:04:49 +01005346 if (followsSameRouting(attr, sourceDesc->attributes()) &&
5347 outputDesc != 0 && outputDesc->mIoHandle == output) {
Eric Laurentd60560a2015-04-10 11:31:20 -07005348 source = sourceDesc;
5349 break;
5350 }
5351 }
5352 return source;
Eric Laurent554a2772015-04-10 11:29:24 -07005353}
5354
Eric Laurentb4f42a92022-01-17 17:37:31 +01005355bool AudioPolicyManager::canBeSpatializedInt(const audio_attributes_t *attr,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005356 const audio_config_t *config,
Andy Hung9dd1a5b2022-05-10 15:39:39 -07005357 const AudioDeviceTypeAddrVector &devices) const
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005358{
5359 // The caller can have the audio attributes criteria ignored by either passing a null ptr or
5360 // the AUDIO_ATTRIBUTES_INITIALIZER value.
Eric Laurentfa0f6742021-08-17 18:39:44 +02005361 // If attributes are specified, current policy is to only allow spatialization for media
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005362 // and game usages.
Eric Laurent39095982021-08-24 18:29:27 +02005363 if (attr != nullptr && *attr != AUDIO_ATTRIBUTES_INITIALIZER) {
5364 if (attr->usage != AUDIO_USAGE_MEDIA && attr->usage != AUDIO_USAGE_GAME) {
5365 return false;
5366 }
5367 if ((attr->flags & (AUDIO_FLAG_CONTENT_SPATIALIZED | AUDIO_FLAG_NEVER_SPATIALIZE)) != 0) {
5368 return false;
5369 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005370 }
5371
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005372 sp<IOProfile> profile =
Eric Laurent39095982021-08-24 18:29:27 +02005373 getSpatializerOutputProfile(config, devices);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005374 if (profile == nullptr) {
5375 return false;
5376 }
5377
5378 // The caller can have the audio config criteria ignored by either passing a null ptr or
5379 // the AUDIO_CONFIG_INITIALIZER value.
Eric Laurentfa0f6742021-08-17 18:39:44 +02005380 // If an audio config is specified, current policy is to only allow spatialization for
Eric Laurent39095982021-08-24 18:29:27 +02005381 // some positional channel masks.
Eric Laurent39095982021-08-24 18:29:27 +02005382
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005383 if (config != nullptr && *config != AUDIO_CONFIG_INITIALIZER) {
Andy Hung9dd1a5b2022-05-10 15:39:39 -07005384 if (!audio_is_channel_mask_spatialized(config->channel_mask)) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005385 return false;
5386 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005387 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005388 return true;
5389}
5390
5391void AudioPolicyManager::checkVirtualizerClientRoutes() {
5392 std::set<audio_stream_type_t> streamsToInvalidate;
5393 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent39095982021-08-24 18:29:27 +02005394 const sp<SwAudioOutputDescriptor>& desc = mOutputs[i];
5395 for (const sp<TrackClientDescriptor>& client : desc->getClientIterable()) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005396 audio_attributes_t attr = client->attributes();
5397 DeviceVector devices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false);
5398 AudioDeviceTypeAddrVector devicesTypeAddress = devices.toTypeAddrVector();
5399 audio_config_base_t clientConfig = client->config();
5400 audio_config_t config = audio_config_initializer(&clientConfig);
Eric Laurent39095982021-08-24 18:29:27 +02005401 if (desc != mSpatializerOutput
Andy Hung9dd1a5b2022-05-10 15:39:39 -07005402 && canBeSpatializedInt(&attr, &config, devicesTypeAddress)) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005403 streamsToInvalidate.insert(client->stream());
5404 }
5405 }
5406 }
5407
5408 for (audio_stream_type_t stream : streamsToInvalidate) {
5409 mpClientInterface->invalidateStream(stream);
5410 }
5411}
5412
Eric Laurente191d1b2022-04-15 11:59:25 +02005413
5414bool AudioPolicyManager::isOutputOnlyAvailableRouteToSomeDevice(
5415 const sp<SwAudioOutputDescriptor>& outputDesc) {
5416 if (outputDesc->isDuplicated()) {
5417 return false;
5418 }
5419 DeviceVector devices = outputDesc->supportedDevices();
5420 for (size_t i = 0; i < mOutputs.size(); i++) {
5421 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
5422 if (desc == outputDesc || desc->isDuplicated()) {
5423 continue;
5424 }
5425 DeviceVector sharedDevices = desc->filterSupportedDevices(devices);
5426 if (!sharedDevices.isEmpty()
5427 && (desc->devicesSupportEncodedFormats(sharedDevices.types())
5428 == outputDesc->devicesSupportEncodedFormats(sharedDevices.types()))) {
5429 return false;
5430 }
5431 }
5432 return true;
5433}
5434
5435
Eric Laurentfa0f6742021-08-17 18:39:44 +02005436status_t AudioPolicyManager::getSpatializerOutput(const audio_config_base_t *mixerConfig,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005437 const audio_attributes_t *attr,
5438 audio_io_handle_t *output) {
5439 *output = AUDIO_IO_HANDLE_NONE;
5440
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005441 DeviceVector devices = mEngine->getOutputDevicesForAttributes(*attr, nullptr, false);
5442 AudioDeviceTypeAddrVector devicesTypeAddress = devices.toTypeAddrVector();
5443 audio_config_t *configPtr = nullptr;
5444 audio_config_t config;
5445 if (mixerConfig != nullptr) {
5446 config = audio_config_initializer(mixerConfig);
5447 configPtr = &config;
5448 }
Andy Hung9dd1a5b2022-05-10 15:39:39 -07005449 if (!canBeSpatializedInt(attr, configPtr, devicesTypeAddress)) {
Eric Laurente191d1b2022-04-15 11:59:25 +02005450 ALOGV("%s provided attributes or mixer config cannot be spatialized", __func__);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005451 return BAD_VALUE;
5452 }
5453
5454 sp<IOProfile> profile =
Eric Laurent39095982021-08-24 18:29:27 +02005455 getSpatializerOutputProfile(configPtr, devicesTypeAddress);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005456 if (profile == nullptr) {
Eric Laurente191d1b2022-04-15 11:59:25 +02005457 ALOGV("%s no suitable output profile for provided attributes or mixer config", __func__);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005458 return BAD_VALUE;
5459 }
5460
Eric Laurente191d1b2022-04-15 11:59:25 +02005461 std::vector<sp<SwAudioOutputDescriptor>> spatializerOutputs;
Eric Laurent39095982021-08-24 18:29:27 +02005462 for (size_t i = 0; i < mOutputs.size(); i++) {
5463 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente191d1b2022-04-15 11:59:25 +02005464 if (!desc->isDuplicated()
5465 && (desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0) {
5466 spatializerOutputs.push_back(desc);
5467 ALOGV("%s adding opened spatializer Output %d", __func__, desc->mIoHandle);
Eric Laurent39095982021-08-24 18:29:27 +02005468 }
5469 }
Eric Laurente191d1b2022-04-15 11:59:25 +02005470 mSpatializerOutput.clear();
5471 bool outputsChanged = false;
5472 for (const auto& desc : spatializerOutputs) {
5473 if (desc->mProfile == profile
5474 && (configPtr == nullptr
5475 || configPtr->channel_mask == desc->mMixerChannelMask)) {
5476 mSpatializerOutput = desc;
5477 ALOGV("%s reusing current spatializer output %d", __func__, desc->mIoHandle);
5478 } else {
5479 ALOGV("%s closing spatializerOutput output %d to match channel mask %#x"
5480 " and devices %s", __func__, desc->mIoHandle,
5481 configPtr != nullptr ? configPtr->channel_mask : 0,
5482 devices.toString().c_str());
5483 closeOutput(desc->mIoHandle);
5484 outputsChanged = true;
5485 }
Eric Laurent39095982021-08-24 18:29:27 +02005486 }
5487
Eric Laurente191d1b2022-04-15 11:59:25 +02005488 if (mSpatializerOutput == nullptr) {
Eric Laurentb4f42a92022-01-17 17:37:31 +01005489 sp<SwAudioOutputDescriptor> desc =
5490 openOutputWithProfileAndDevice(profile, devices, mixerConfig);
Eric Laurente191d1b2022-04-15 11:59:25 +02005491 if (desc != nullptr) {
5492 mSpatializerOutput = desc;
5493 outputsChanged = true;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005494 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005495 }
5496
5497 checkVirtualizerClientRoutes();
5498
Eric Laurente191d1b2022-04-15 11:59:25 +02005499 if (outputsChanged) {
5500 mPreviousOutputs = mOutputs;
5501 mpClientInterface->onAudioPortListUpdate();
5502 }
5503
5504 if (mSpatializerOutput == nullptr) {
5505 ALOGV("%s could not open spatializer output with requested config", __func__);
5506 return BAD_VALUE;
5507 }
Eric Laurent39095982021-08-24 18:29:27 +02005508 *output = mSpatializerOutput->mIoHandle;
Eric Laurente191d1b2022-04-15 11:59:25 +02005509 ALOGV("%s returning new spatializer output %d", __func__, *output);
5510 return OK;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005511}
5512
Eric Laurentfa0f6742021-08-17 18:39:44 +02005513status_t AudioPolicyManager::releaseSpatializerOutput(audio_io_handle_t output) {
5514 if (mSpatializerOutput == nullptr) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005515 return INVALID_OPERATION;
5516 }
Eric Laurentfa0f6742021-08-17 18:39:44 +02005517 if (mSpatializerOutput->mIoHandle != output) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005518 return BAD_VALUE;
5519 }
Eric Laurent39095982021-08-24 18:29:27 +02005520
Eric Laurente191d1b2022-04-15 11:59:25 +02005521 if (!isOutputOnlyAvailableRouteToSomeDevice(mSpatializerOutput)) {
5522 ALOGV("%s closing spatializer output %d", __func__, mSpatializerOutput->mIoHandle);
5523 closeOutput(mSpatializerOutput->mIoHandle);
5524 //from now on mSpatializerOutput is null
5525 checkVirtualizerClientRoutes();
5526 }
Eric Laurent39095982021-08-24 18:29:27 +02005527
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005528 return NO_ERROR;
5529}
5530
Eric Laurente552edb2014-03-10 17:42:56 -07005531// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07005532// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07005533// ----------------------------------------------------------------------------
Eric Laurent6a94d692014-05-20 11:18:06 -07005534uint32_t AudioPolicyManager::nextAudioPortGeneration()
5535{
Mikhail Naganov2773dd72017-12-08 10:12:11 -08005536 return mAudioPortGeneration++;
Eric Laurent6a94d692014-05-20 11:18:06 -07005537}
5538
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09005539static status_t deserializeAudioPolicyXmlConfig(AudioPolicyConfig &config) {
Mikhail Naganov946c0032020-10-21 13:04:58 -07005540 if (std::string audioPolicyXmlConfigFile = audio_get_audio_policy_config_file();
5541 !audioPolicyXmlConfigFile.empty()) {
5542 status_t ret = deserializeAudioPolicyFile(audioPolicyXmlConfigFile.c_str(), &config);
5543 if (ret == NO_ERROR) {
5544 config.setSource(audioPolicyXmlConfigFile);
Cheney Ni6851adb2018-11-01 06:30:37 +08005545 }
Mikhail Naganov946c0032020-10-21 13:04:58 -07005546 return ret;
Petri Gyntherf497f292018-04-17 18:46:10 -07005547 }
Mikhail Naganov946c0032020-10-21 13:04:58 -07005548 return BAD_VALUE;
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09005549}
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09005550
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005551AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface,
5552 bool /*forTesting*/)
Eric Laurente552edb2014-03-10 17:42:56 -07005553 :
Andy Hung4ef19fa2018-05-15 19:35:29 -07005554 mUidCached(AID_AUDIOSERVER), // no need to call getuid(), there's only one of us running.
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005555 mpClientInterface(clientInterface),
Eric Laurente552edb2014-03-10 17:42:56 -07005556 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
Eric Laurent3a4311c2014-03-17 12:00:47 -07005557 mA2dpSuspended(false),
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005558 mConfig(mHwModulesAll, mOutputDevicesAll, mInputDevicesAll, mDefaultOutputDevice),
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005559 mAudioPortGeneration(1),
5560 mBeaconMuteRefCount(0),
5561 mBeaconPlayingRefCount(0),
Eric Laurent9459fb02015-08-12 18:36:32 -07005562 mBeaconMuted(false),
Andy Hung2ddee192015-12-18 17:34:44 -08005563 mTtsOutputAvailable(false),
Eric Laurent36829f92017-04-07 19:04:42 -07005564 mMasterMono(false),
Eric Laurent4eb58f12018-12-07 16:41:02 -08005565 mMusicEffectOutput(AUDIO_IO_HANDLE_NONE)
Eric Laurente552edb2014-03-10 17:42:56 -07005566{
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005567}
François Gaffied1ab2bd2015-12-02 18:20:06 +01005568
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005569AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface)
5570 : AudioPolicyManager(clientInterface, false /*forTesting*/)
5571{
5572 loadConfig();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005573}
François Gaffied1ab2bd2015-12-02 18:20:06 +01005574
Kevin Rocarddfa1e8a2018-10-26 16:42:07 -07005575void AudioPolicyManager::loadConfig() {
5576 if (deserializeAudioPolicyXmlConfig(getConfig()) != NO_ERROR) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01005577 ALOGE("could not load audio policy configuration file, setting defaults");
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005578 getConfig().setDefault();
François Gaffied1ab2bd2015-12-02 18:20:06 +01005579 }
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005580}
5581
5582status_t AudioPolicyManager::initialize() {
Mikhail Naganov47835552019-05-14 10:32:51 -07005583 {
5584 auto engLib = EngineLibrary::load(
5585 "libaudiopolicyengine" + getConfig().getEngineLibraryNameSuffix() + ".so");
5586 if (!engLib) {
5587 ALOGE("%s: Failed to load the engine library", __FUNCTION__);
5588 return NO_INIT;
5589 }
5590 mEngine = engLib->createEngine();
5591 if (mEngine == nullptr) {
5592 ALOGE("%s: Failed to instantiate the APM engine", __FUNCTION__);
5593 return NO_INIT;
5594 }
François Gaffie2110e042015-03-24 08:41:51 +01005595 }
5596 mEngine->setObserver(this);
5597 status_t status = mEngine->initCheck();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005598 if (status != NO_ERROR) {
5599 LOG_FATAL("Policy engine not initialized(err=%d)", status);
5600 return status;
5601 }
François Gaffie2110e042015-03-24 08:41:51 +01005602
Eric Laurent1a8b45f2022-04-13 16:01:47 +02005603 mEngine->updateDeviceSelectionCache();
Eric Laurent1d69c872021-01-11 18:53:01 +01005604 mCommunnicationStrategy = mEngine->getProductStrategyForAttributes(
5605 mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL));
5606
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005607 // after parsing the config, mOutputDevicesAll and mInputDevicesAll contain all known devices;
Eric Laurente552edb2014-03-10 17:42:56 -07005608 // open all output streams needed to access attached devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07005609 onNewAudioModulesAvailableInt(nullptr /*newDevices*/);
François Gaffie11d30102018-11-02 16:09:09 +01005610
Eric Laurent3a4311c2014-03-17 12:00:47 -07005611 // make sure default device is reachable
François Gaffie11d30102018-11-02 16:09:09 +01005612 if (mDefaultOutputDevice == 0 || !mAvailableOutputDevices.contains(mDefaultOutputDevice)) {
5613 ALOGE_IF(mDefaultOutputDevice != 0, "Default device %s is unreachable",
5614 mDefaultOutputDevice->toString().c_str());
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005615 status = NO_INIT;
Eric Laurent3a4311c2014-03-17 12:00:47 -07005616 }
jiabin9ff780e2018-03-19 18:19:52 -07005617 // If microphones address is empty, set it according to device type
Eric Laurent736a1022019-03-27 18:28:46 -07005618 for (size_t i = 0; i < mAvailableInputDevices.size(); i++) {
jiabince9f20e2019-09-12 16:29:15 -07005619 if (mAvailableInputDevices[i]->address().empty()) {
jiabin9ff780e2018-03-19 18:19:52 -07005620 if (mAvailableInputDevices[i]->type() == AUDIO_DEVICE_IN_BUILTIN_MIC) {
jiabince9f20e2019-09-12 16:29:15 -07005621 mAvailableInputDevices[i]->setAddress(AUDIO_BOTTOM_MICROPHONE_ADDRESS);
jiabin9ff780e2018-03-19 18:19:52 -07005622 } else if (mAvailableInputDevices[i]->type() == AUDIO_DEVICE_IN_BACK_MIC) {
jiabince9f20e2019-09-12 16:29:15 -07005623 mAvailableInputDevices[i]->setAddress(AUDIO_BACK_MICROPHONE_ADDRESS);
jiabin9ff780e2018-03-19 18:19:52 -07005624 }
5625 }
5626 }
Eric Laurente552edb2014-03-10 17:42:56 -07005627
Francois Gaffiebce7cd42020-10-14 16:13:20 +02005628 ALOGW_IF(mPrimaryOutput == nullptr, "The policy configuration does not declare a primary output");
Eric Laurente552edb2014-03-10 17:42:56 -07005629
Tomoharu Kasahara71c90912018-10-31 09:10:12 +09005630 // Silence ALOGV statements
5631 property_set("log.tag." LOG_TAG, "D");
5632
Eric Laurente552edb2014-03-10 17:42:56 -07005633 updateDevicesAndOutputs();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005634 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07005635}
5636
Eric Laurente0720872014-03-11 09:30:41 -07005637AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07005638{
Eric Laurente552edb2014-03-10 17:42:56 -07005639 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08005640 mOutputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07005641 }
5642 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08005643 mInputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07005644 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07005645 mAvailableOutputDevices.clear();
5646 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07005647 mOutputs.clear();
5648 mInputs.clear();
5649 mHwModules.clear();
Mikhail Naganovd4120142017-12-06 15:49:22 -08005650 mHwModulesAll.clear();
Mikhail Naganov100f0122018-11-29 11:22:16 -08005651 mManualSurroundFormats.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07005652}
5653
Eric Laurente0720872014-03-11 09:30:41 -07005654status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07005655{
Eric Laurent87ffa392015-05-22 10:32:38 -07005656 return hasPrimaryOutput() ? NO_ERROR : NO_INIT;
Eric Laurente552edb2014-03-10 17:42:56 -07005657}
5658
Eric Laurente552edb2014-03-10 17:42:56 -07005659// ---
5660
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005661void AudioPolicyManager::onNewAudioModulesAvailable()
5662{
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07005663 DeviceVector newDevices;
5664 onNewAudioModulesAvailableInt(&newDevices);
5665 if (!newDevices.empty()) {
5666 nextAudioPortGeneration();
5667 mpClientInterface->onAudioPortListUpdate();
5668 }
5669}
5670
5671void AudioPolicyManager::onNewAudioModulesAvailableInt(DeviceVector *newDevices)
5672{
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005673 for (const auto& hwModule : mHwModulesAll) {
5674 if (std::find(mHwModules.begin(), mHwModules.end(), hwModule) != mHwModules.end()) {
5675 continue;
5676 }
5677 hwModule->setHandle(mpClientInterface->loadHwModule(hwModule->getName()));
5678 if (hwModule->getHandle() == AUDIO_MODULE_HANDLE_NONE) {
5679 ALOGW("could not open HW module %s", hwModule->getName());
5680 continue;
5681 }
5682 mHwModules.push_back(hwModule);
Dean Wheatley12a87132021-04-16 10:08:49 +10005683 // open all output streams needed to access attached devices.
5684 // direct outputs are closed immediately after checking the availability of attached devices
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005685 // This also validates mAvailableOutputDevices list
5686 for (const auto& outProfile : hwModule->getOutputProfiles()) {
5687 if (!outProfile->canOpenNewIo()) {
5688 ALOGE("Invalid Output profile max open count %u for profile %s",
5689 outProfile->maxOpenCount, outProfile->getTagName().c_str());
5690 continue;
5691 }
5692 if (!outProfile->hasSupportedDevices()) {
5693 ALOGW("Output profile contains no device on module %s", hwModule->getName());
5694 continue;
5695 }
Carter Hsu1a3364a2022-01-21 15:32:56 +08005696 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_TTS) != 0 ||
5697 (outProfile->getFlags() & AUDIO_OUTPUT_FLAG_ULTRASOUND) != 0) {
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005698 mTtsOutputAvailable = true;
5699 }
5700
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005701 const DeviceVector &supportedDevices = outProfile->getSupportedDevices();
5702 DeviceVector availProfileDevices = supportedDevices.filter(mOutputDevicesAll);
5703 sp<DeviceDescriptor> supportedDevice = 0;
5704 if (supportedDevices.contains(mDefaultOutputDevice)) {
5705 supportedDevice = mDefaultOutputDevice;
5706 } else {
5707 // choose first device present in profile's SupportedDevices also part of
5708 // mAvailableOutputDevices.
5709 if (availProfileDevices.isEmpty()) {
5710 continue;
5711 }
5712 supportedDevice = availProfileDevices.itemAt(0);
5713 }
5714 if (!mOutputDevicesAll.contains(supportedDevice)) {
5715 continue;
5716 }
5717 sp<SwAudioOutputDescriptor> outputDesc = new SwAudioOutputDescriptor(outProfile,
5718 mpClientInterface);
5719 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentf1f22e72021-07-13 14:04:14 +02005720 status_t status = outputDesc->open(nullptr /* halConfig */, nullptr /* mixerConfig */,
5721 DeviceVector(supportedDevice),
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005722 AUDIO_STREAM_DEFAULT,
5723 AUDIO_OUTPUT_FLAG_NONE, &output);
5724 if (status != NO_ERROR) {
5725 ALOGW("Cannot open output stream for devices %s on hw module %s",
5726 supportedDevice->toString().c_str(), hwModule->getName());
5727 continue;
5728 }
5729 for (const auto &device : availProfileDevices) {
5730 // give a valid ID to an attached device once confirmed it is reachable
5731 if (!device->isAttached()) {
5732 device->attach(hwModule);
5733 mAvailableOutputDevices.add(device);
jiabin1c4794b2020-05-05 10:08:05 -07005734 device->setEncapsulationInfoFromHal(mpClientInterface);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07005735 if (newDevices) newDevices->add(device);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005736 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
5737 }
5738 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02005739 if (mPrimaryOutput == nullptr &&
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005740 outProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
5741 mPrimaryOutput = outputDesc;
5742 }
Eric Laurent39095982021-08-24 18:29:27 +02005743 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
Eric Laurentc529cf62020-04-17 18:19:10 -07005744 outputDesc->close();
5745 } else {
5746 addOutput(output, outputDesc);
5747 setOutputDevices(outputDesc,
5748 DeviceVector(supportedDevice),
5749 true,
5750 0,
5751 NULL);
5752 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005753 }
5754 // open input streams needed to access attached devices to validate
5755 // mAvailableInputDevices list
5756 for (const auto& inProfile : hwModule->getInputProfiles()) {
5757 if (!inProfile->canOpenNewIo()) {
5758 ALOGE("Invalid Input profile max open count %u for profile %s",
5759 inProfile->maxOpenCount, inProfile->getTagName().c_str());
5760 continue;
5761 }
5762 if (!inProfile->hasSupportedDevices()) {
5763 ALOGW("Input profile contains no device on module %s", hwModule->getName());
5764 continue;
5765 }
5766 // chose first device present in profile's SupportedDevices also part of
5767 // available input devices
5768 const DeviceVector &supportedDevices = inProfile->getSupportedDevices();
5769 DeviceVector availProfileDevices = supportedDevices.filter(mInputDevicesAll);
5770 if (availProfileDevices.isEmpty()) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01005771 ALOGV("%s: Input device list is empty! for profile %s",
5772 __func__, inProfile->getTagName().c_str());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005773 continue;
5774 }
5775 sp<AudioInputDescriptor> inputDesc =
5776 new AudioInputDescriptor(inProfile, mpClientInterface);
5777
5778 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
5779 status_t status = inputDesc->open(nullptr,
5780 availProfileDevices.itemAt(0),
5781 AUDIO_SOURCE_MIC,
5782 AUDIO_INPUT_FLAG_NONE,
5783 &input);
5784 if (status != NO_ERROR) {
5785 ALOGW("Cannot open input stream for device %s on hw module %s",
5786 availProfileDevices.toString().c_str(),
5787 hwModule->getName());
5788 continue;
5789 }
5790 for (const auto &device : availProfileDevices) {
5791 // give a valid ID to an attached device once confirmed it is reachable
5792 if (!device->isAttached()) {
5793 device->attach(hwModule);
5794 device->importAudioPortAndPickAudioProfile(inProfile, true);
5795 mAvailableInputDevices.add(device);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07005796 if (newDevices) newDevices->add(device);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005797 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
5798 }
5799 }
5800 inputDesc->close();
5801 }
5802 }
Eric Laurente191d1b2022-04-15 11:59:25 +02005803
5804 // Check if spatializer outputs can be closed until used.
5805 // mOutputs vector never contains duplicated outputs at this point.
5806 std::vector<audio_io_handle_t> outputsClosed;
5807 for (size_t i = 0; i < mOutputs.size(); i++) {
5808 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
5809 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0
5810 && !isOutputOnlyAvailableRouteToSomeDevice(desc)) {
5811 outputsClosed.push_back(desc->mIoHandle);
5812 desc->close();
5813 }
5814 }
5815 for (auto output : outputsClosed) {
5816 removeOutput(output);
5817 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005818}
5819
Eric Laurent98e38192018-02-15 18:31:53 -08005820void AudioPolicyManager::addOutput(audio_io_handle_t output,
5821 const sp<SwAudioOutputDescriptor>& outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07005822{
Eric Laurent1c333e22014-05-20 10:48:17 -07005823 mOutputs.add(output, outputDesc);
jiabin9a3361e2019-10-01 09:38:30 -07005824 applyStreamVolumes(outputDesc, DeviceTypeSet(), 0 /* delayMs */, true /* force */);
Andy Hung2ddee192015-12-18 17:34:44 -08005825 updateMono(output); // update mono status when adding to output list
Eric Laurent36829f92017-04-07 19:04:42 -07005826 selectOutputForMusicEffects();
Eric Laurent6a94d692014-05-20 11:18:06 -07005827 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07005828}
5829
François Gaffie53615e22015-03-19 09:24:12 +01005830void AudioPolicyManager::removeOutput(audio_io_handle_t output)
5831{
Francois Gaffiebce7cd42020-10-14 16:13:20 +02005832 if (mPrimaryOutput != 0 && mPrimaryOutput == mOutputs.valueFor(output)) {
5833 ALOGV("%s: removing primary output", __func__);
5834 mPrimaryOutput = nullptr;
5835 }
François Gaffie53615e22015-03-19 09:24:12 +01005836 mOutputs.removeItem(output);
Eric Laurent36829f92017-04-07 19:04:42 -07005837 selectOutputForMusicEffects();
François Gaffie53615e22015-03-19 09:24:12 +01005838}
5839
Eric Laurent98e38192018-02-15 18:31:53 -08005840void AudioPolicyManager::addInput(audio_io_handle_t input,
5841 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07005842{
Eric Laurent1c333e22014-05-20 10:48:17 -07005843 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07005844 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07005845}
Eric Laurente552edb2014-03-10 17:42:56 -07005846
François Gaffie11d30102018-11-02 16:09:09 +01005847status_t AudioPolicyManager::checkOutputsForDevice(const sp<DeviceDescriptor>& device,
François Gaffie53615e22015-03-19 09:24:12 +01005848 audio_policy_dev_state_t state,
François Gaffie11d30102018-11-02 16:09:09 +01005849 SortedVector<audio_io_handle_t>& outputs)
Eric Laurente552edb2014-03-10 17:42:56 -07005850{
François Gaffie11d30102018-11-02 16:09:09 +01005851 audio_devices_t deviceType = device->type();
jiabince9f20e2019-09-12 16:29:15 -07005852 const String8 &address = String8(device->address().c_str());
Eric Laurentc75307b2015-03-17 15:29:32 -07005853 sp<SwAudioOutputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07005854
François Gaffie11d30102018-11-02 16:09:09 +01005855 if (audio_device_is_digital(deviceType)) {
Eric Laurentcc750d32015-06-25 11:48:20 -07005856 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01005857 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07005858 }
Eric Laurente552edb2014-03-10 17:42:56 -07005859
Eric Laurent3b73df72014-03-11 09:06:29 -07005860 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
jiabinb4fed192020-09-22 14:45:40 -07005861 // first call getAudioPort to get the supported attributes from the HAL
5862 struct audio_port_v7 port = {};
5863 device->toAudioPort(&port);
5864 status_t status = mpClientInterface->getAudioPort(&port);
5865 if (status == NO_ERROR) {
5866 device->importAudioPort(port);
5867 }
5868
5869 // then list already open outputs that can be routed to this device
Eric Laurente552edb2014-03-10 17:42:56 -07005870 for (size_t i = 0; i < mOutputs.size(); i++) {
5871 desc = mOutputs.valueAt(i);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005872 if (!desc->isDuplicated() && desc->supportsDevice(device)
jiabin9a3361e2019-10-01 09:38:30 -07005873 && desc->devicesSupportEncodedFormats({deviceType})) {
François Gaffie11d30102018-11-02 16:09:09 +01005874 ALOGV("checkOutputsForDevice(): adding opened output %d on device %s",
5875 mOutputs.keyAt(i), device->toString().c_str());
5876 outputs.add(mOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07005877 }
5878 }
5879 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07005880 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08005881 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005882 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
5883 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
François Gaffie11d30102018-11-02 16:09:09 +01005884 if (profile->supportsDevice(device)) {
5885 profiles.add(profile);
5886 ALOGV("checkOutputsForDevice(): adding profile %zu from module %s",
5887 j, hwModule->getName());
Eric Laurente552edb2014-03-10 17:42:56 -07005888 }
5889 }
5890 }
5891
Eric Laurent7b279bb2015-12-14 10:18:23 -08005892 ALOGV(" found %zu profiles, %zu outputs", profiles.size(), outputs.size());
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005893
Eric Laurente552edb2014-03-10 17:42:56 -07005894 if (profiles.isEmpty() && outputs.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01005895 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07005896 return BAD_VALUE;
5897 }
5898
5899 // open outputs for matching profiles if needed. Direct outputs are also opened to
5900 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
5901 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07005902 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07005903
5904 // nothing to do if one output is already opened for this profile
5905 size_t j;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005906 for (j = 0; j < outputs.size(); j++) {
5907 desc = mOutputs.valueFor(outputs.itemAt(j));
Eric Laurente552edb2014-03-10 17:42:56 -07005908 if (!desc->isDuplicated() && desc->mProfile == profile) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07005909 // matching profile: save the sample rates, format and channel masks supported
5910 // by the profile in our device descriptor
François Gaffie11d30102018-11-02 16:09:09 +01005911 if (audio_device_is_digital(deviceType)) {
jiabin4ef93452019-09-10 14:29:54 -07005912 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07005913 }
Eric Laurente552edb2014-03-10 17:42:56 -07005914 break;
5915 }
5916 }
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005917 if (j != outputs.size()) {
Eric Laurente552edb2014-03-10 17:42:56 -07005918 continue;
5919 }
5920
Eric Laurent3974e3b2017-12-07 17:58:43 -08005921 if (!profile->canOpenNewIo()) {
5922 ALOGW("Max Output number %u already opened for this profile %s",
5923 profile->maxOpenCount, profile->getTagName().c_str());
5924 continue;
5925 }
5926
Eric Laurent83efe1c2017-07-09 16:51:08 -07005927 ALOGV("opening output for device %08x with params %s profile %p name %s",
jiabin5740f082019-08-19 15:08:30 -07005928 deviceType, address.string(), profile.get(), profile->getName().c_str());
jiabinbce0c1d2020-10-05 11:20:18 -07005929 desc = openOutputWithProfileAndDevice(profile, DeviceVector(device));
5930 audio_io_handle_t output = desc == nullptr ? AUDIO_IO_HANDLE_NONE : desc->mIoHandle;
Eric Laurentcf2c0212014-07-25 16:20:43 -07005931 if (output == AUDIO_IO_HANDLE_NONE) {
François Gaffie11d30102018-11-02 16:09:09 +01005932 ALOGW("checkOutputsForDevice() could not open output for device %x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07005933 profiles.removeAt(profile_index);
5934 profile_index--;
5935 } else {
5936 outputs.add(output);
Paul McLean9080a4c2015-06-18 08:24:02 -07005937 // Load digital format info only for digital devices
François Gaffie11d30102018-11-02 16:09:09 +01005938 if (audio_device_is_digital(deviceType)) {
jiabinbce0c1d2020-10-05 11:20:18 -07005939 // TODO: when getAudioPort is ready, it may not be needed to import the audio
5940 // port but just pick audio profile
jiabin4ef93452019-09-10 14:29:54 -07005941 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07005942 }
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07005943
François Gaffie11d30102018-11-02 16:09:09 +01005944 if (device_distinguishes_on_address(deviceType)) {
5945 ALOGV("checkOutputsForDevice(): setOutputDevices %s",
5946 device->toString().c_str());
5947 setOutputDevices(desc, DeviceVector(device), true/*force*/, 0/*delay*/,
5948 NULL/*patch handle*/);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005949 }
Eric Laurente552edb2014-03-10 17:42:56 -07005950 ALOGV("checkOutputsForDevice(): adding output %d", output);
5951 }
5952 }
5953
5954 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01005955 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07005956 return BAD_VALUE;
5957 }
Eric Laurentd4692962014-05-05 18:13:44 -07005958 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07005959 // check if one opened output is not needed any more after disconnecting one device
5960 for (size_t i = 0; i < mOutputs.size(); i++) {
5961 desc = mOutputs.valueAt(i);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005962 if (!desc->isDuplicated()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08005963 // exact match on device
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005964 if (device_distinguishes_on_address(deviceType) && desc->supportsDevice(device)
Francois Gaffiec7d4c222021-12-02 11:12:52 +01005965 && desc->containsSingleDeviceSupportingEncodedFormats(device)) {
François Gaffie11d30102018-11-02 16:09:09 +01005966 outputs.add(mOutputs.keyAt(i));
Francois Gaffie716e1432019-01-14 16:58:59 +01005967 } else if (!mAvailableOutputDevices.containsAtLeastOne(desc->supportedDevices())) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005968 ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
5969 mOutputs.keyAt(i));
5970 outputs.add(mOutputs.keyAt(i));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005971 }
Eric Laurente552edb2014-03-10 17:42:56 -07005972 }
5973 }
Eric Laurentd4692962014-05-05 18:13:44 -07005974 // Clear any profiles associated with the disconnected device.
Mikhail Naganov7e22e942017-12-07 10:04:29 -08005975 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005976 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
5977 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
jiabinbce0c1d2020-10-05 11:20:18 -07005978 if (!profile->supportsDevice(device)) {
5979 continue;
5980 }
5981 ALOGV("checkOutputsForDevice(): "
5982 "clearing direct output profile %zu on module %s",
5983 j, hwModule->getName());
5984 profile->clearAudioProfiles();
5985 if (!profile->hasDynamicAudioProfile()) {
5986 continue;
5987 }
5988 // When a device is disconnected, if there is an IOProfile that contains dynamic
5989 // profiles and supports the disconnected device, call getAudioPort to repopulate
5990 // the capabilities of the devices that is supported by the IOProfile.
5991 for (const auto& supportedDevice : profile->getSupportedDevices()) {
5992 if (supportedDevice == device ||
5993 !mAvailableOutputDevices.contains(supportedDevice)) {
5994 continue;
5995 }
5996 struct audio_port_v7 port;
5997 supportedDevice->toAudioPort(&port);
5998 status_t status = mpClientInterface->getAudioPort(&port);
5999 if (status == NO_ERROR) {
6000 supportedDevice->importAudioPort(port);
6001 }
Eric Laurente552edb2014-03-10 17:42:56 -07006002 }
6003 }
6004 }
6005 }
6006 return NO_ERROR;
6007}
6008
François Gaffie11d30102018-11-02 16:09:09 +01006009status_t AudioPolicyManager::checkInputsForDevice(const sp<DeviceDescriptor>& device,
Eric Laurent0dd51852019-04-19 18:18:58 -07006010 audio_policy_dev_state_t state)
Eric Laurentd4692962014-05-05 18:13:44 -07006011{
Eric Laurent1f2f2232014-06-02 12:01:23 -07006012 sp<AudioInputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07006013
François Gaffie11d30102018-11-02 16:09:09 +01006014 if (audio_device_is_digital(device->type())) {
Eric Laurentcc750d32015-06-25 11:48:20 -07006015 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01006016 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07006017 }
6018
Eric Laurentd4692962014-05-05 18:13:44 -07006019 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
Eric Laurent0dd51852019-04-19 18:18:58 -07006020 // look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07006021 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006022 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07006023 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006024 profile_index < hwModule->getInputProfiles().size();
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006025 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006026 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Eric Laurent275e8e92014-11-30 15:14:47 -08006027
François Gaffie11d30102018-11-02 16:09:09 +01006028 if (profile->supportsDevice(device)) {
6029 profiles.add(profile);
6030 ALOGV("checkInputsForDevice(): adding profile %zu from module %s",
6031 profile_index, hwModule->getName());
Eric Laurentd4692962014-05-05 18:13:44 -07006032 }
6033 }
6034 }
6035
Eric Laurent0dd51852019-04-19 18:18:58 -07006036 if (profiles.isEmpty()) {
6037 ALOGW("%s: No input profile available for device %s",
6038 __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07006039 return BAD_VALUE;
6040 }
6041
6042 // open inputs for matching profiles if needed. Direct inputs are also opened to
6043 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
6044 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
6045
Eric Laurent1c333e22014-05-20 10:48:17 -07006046 sp<IOProfile> profile = profiles[profile_index];
Eric Laurent3974e3b2017-12-07 17:58:43 -08006047
Eric Laurentd4692962014-05-05 18:13:44 -07006048 // nothing to do if one input is already opened for this profile
6049 size_t input_index;
6050 for (input_index = 0; input_index < mInputs.size(); input_index++) {
6051 desc = mInputs.valueAt(input_index);
6052 if (desc->mProfile == profile) {
François Gaffie11d30102018-11-02 16:09:09 +01006053 if (audio_device_is_digital(device->type())) {
jiabin4ef93452019-09-10 14:29:54 -07006054 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006055 }
Eric Laurentd4692962014-05-05 18:13:44 -07006056 break;
6057 }
6058 }
6059 if (input_index != mInputs.size()) {
6060 continue;
6061 }
6062
Eric Laurent3974e3b2017-12-07 17:58:43 -08006063 if (!profile->canOpenNewIo()) {
6064 ALOGW("Max Input number %u already opened for this profile %s",
6065 profile->maxOpenCount, profile->getTagName().c_str());
6066 continue;
6067 }
6068
Eric Laurentfe231122017-11-17 17:48:06 -08006069 desc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentcf2c0212014-07-25 16:20:43 -07006070 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08006071 status_t status = desc->open(nullptr,
6072 device,
Eric Laurentfe231122017-11-17 17:48:06 -08006073 AUDIO_SOURCE_MIC,
6074 AUDIO_INPUT_FLAG_NONE,
6075 &input);
Eric Laurentd4692962014-05-05 18:13:44 -07006076
Eric Laurentcf2c0212014-07-25 16:20:43 -07006077 if (status == NO_ERROR) {
jiabince9f20e2019-09-12 16:29:15 -07006078 const String8& address = String8(device->address().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07006079 if (!address.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006080 char *param = audio_device_address_to_parameter(device->type(), address);
Eric Laurentcf2c0212014-07-25 16:20:43 -07006081 mpClientInterface->setParameters(input, String8(param));
6082 free(param);
Eric Laurentd4692962014-05-05 18:13:44 -07006083 }
François Gaffie11d30102018-11-02 16:09:09 +01006084 updateAudioProfiles(device, input, profile->getAudioProfiles());
François Gaffie112b0af2015-11-19 16:13:25 +01006085 if (!profile->hasValidAudioProfile()) {
Eric Laurentd4692962014-05-05 18:13:44 -07006086 ALOGW("checkInputsForDevice() direct input missing param");
Eric Laurentfe231122017-11-17 17:48:06 -08006087 desc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07006088 input = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07006089 }
6090
Eric Laurent0dd51852019-04-19 18:18:58 -07006091 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07006092 addInput(input, desc);
6093 }
6094 } // endif input != 0
6095
Eric Laurentcf2c0212014-07-25 16:20:43 -07006096 if (input == AUDIO_IO_HANDLE_NONE) {
Pattydd807582021-11-04 21:01:03 +08006097 ALOGW("%s could not open input for device %s", __func__,
François Gaffie11d30102018-11-02 16:09:09 +01006098 device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07006099 profiles.removeAt(profile_index);
6100 profile_index--;
6101 } else {
François Gaffie11d30102018-11-02 16:09:09 +01006102 if (audio_device_is_digital(device->type())) {
jiabin4ef93452019-09-10 14:29:54 -07006103 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006104 }
Eric Laurentd4692962014-05-05 18:13:44 -07006105 ALOGV("checkInputsForDevice(): adding input %d", input);
6106 }
6107 } // end scan profiles
6108
6109 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006110 ALOGW("%s: No input available for device %s", __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07006111 return BAD_VALUE;
6112 }
6113 } else {
6114 // Disconnect
Eric Laurentd4692962014-05-05 18:13:44 -07006115 // Clear any profiles associated with the disconnected device.
Mikhail Naganovd4120142017-12-06 15:49:22 -08006116 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07006117 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006118 profile_index < hwModule->getInputProfiles().size();
Eric Laurentd4692962014-05-05 18:13:44 -07006119 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006120 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Francois Gaffie716e1432019-01-14 16:58:59 +01006121 if (profile->supportsDevice(device)) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08006122 ALOGV("checkInputsForDevice(): clearing direct input profile %zu on module %s",
6123 profile_index, hwModule->getName());
François Gaffie112b0af2015-11-19 16:13:25 +01006124 profile->clearAudioProfiles();
Eric Laurentd4692962014-05-05 18:13:44 -07006125 }
6126 }
6127 }
6128 } // end disconnect
6129
6130 return NO_ERROR;
6131}
6132
6133
Eric Laurente0720872014-03-11 09:30:41 -07006134void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07006135{
6136 ALOGV("closeOutput(%d)", output);
6137
François Gaffie1c878552018-11-22 16:53:21 +01006138 sp<SwAudioOutputDescriptor> closingOutput = mOutputs.valueFor(output);
6139 if (closingOutput == NULL) {
Eric Laurente552edb2014-03-10 17:42:56 -07006140 ALOGW("closeOutput() unknown output %d", output);
6141 return;
6142 }
Mikhail Naganov32ebca32019-03-22 15:42:52 -07006143 const bool closingOutputWasActive = closingOutput->isActive();
François Gaffie1c878552018-11-22 16:53:21 +01006144 mPolicyMixes.closeOutput(closingOutput);
Eric Laurent275e8e92014-11-30 15:14:47 -08006145
Eric Laurente552edb2014-03-10 17:42:56 -07006146 // look for duplicated outputs connected to the output being removed.
6147 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie1c878552018-11-22 16:53:21 +01006148 sp<SwAudioOutputDescriptor> dupOutput = mOutputs.valueAt(i);
6149 if (dupOutput->isDuplicated() &&
6150 (dupOutput->mOutput1 == closingOutput || dupOutput->mOutput2 == closingOutput)) {
6151 sp<SwAudioOutputDescriptor> remainingOutput =
6152 dupOutput->mOutput1 == closingOutput ? dupOutput->mOutput2 : dupOutput->mOutput1;
Eric Laurente552edb2014-03-10 17:42:56 -07006153 // As all active tracks on duplicated output will be deleted,
6154 // and as they were also referenced on the other output, the reference
6155 // count for their stream type must be adjusted accordingly on
6156 // the other output.
François Gaffie1c878552018-11-22 16:53:21 +01006157 const bool wasActive = remainingOutput->isActive();
6158 // Note: no-op on the closing output where all clients has already been set inactive
6159 dupOutput->setAllClientsInactive();
Eric Laurent733ce942017-12-07 12:18:25 -08006160 // stop() will be a no op if the output is still active but is needed in case all
6161 // active streams refcounts where cleared above
6162 if (wasActive) {
François Gaffie1c878552018-11-22 16:53:21 +01006163 remainingOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08006164 }
Eric Laurente552edb2014-03-10 17:42:56 -07006165 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
6166 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
6167
6168 mpClientInterface->closeOutput(duplicatedOutput);
François Gaffie53615e22015-03-19 09:24:12 +01006169 removeOutput(duplicatedOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07006170 }
6171 }
6172
Eric Laurent05b90f82014-08-27 15:32:29 -07006173 nextAudioPortGeneration();
6174
François Gaffie1c878552018-11-22 16:53:21 +01006175 ssize_t index = mAudioPatches.indexOfKey(closingOutput->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07006176 if (index >= 0) {
6177 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006178 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
6179 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07006180 mAudioPatches.removeItemsAt(index);
6181 mpClientInterface->onAudioPatchListUpdate();
6182 }
6183
Mikhail Naganov32ebca32019-03-22 15:42:52 -07006184 if (closingOutputWasActive) {
6185 closingOutput->stop();
6186 }
François Gaffie1c878552018-11-22 16:53:21 +01006187 closingOutput->close();
Eric Laurente552edb2014-03-10 17:42:56 -07006188
François Gaffie53615e22015-03-19 09:24:12 +01006189 removeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07006190 mPreviousOutputs = mOutputs;
Eric Laurentb4f42a92022-01-17 17:37:31 +01006191 if (closingOutput == mSpatializerOutput) {
6192 mSpatializerOutput.clear();
6193 }
Dean Wheatley3023b382018-08-09 07:42:40 +10006194
6195 // MSD patches may have been released to support a non-MSD direct output. Reset MSD patch if
6196 // no direct outputs are open.
François Gaffie11d30102018-11-02 16:09:09 +01006197 if (!getMsdAudioOutDevices().isEmpty()) {
Dean Wheatley3023b382018-08-09 07:42:40 +10006198 bool directOutputOpen = false;
6199 for (size_t i = 0; i < mOutputs.size(); i++) {
6200 if (mOutputs[i]->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
6201 directOutputOpen = true;
6202 break;
6203 }
6204 }
6205 if (!directOutputOpen) {
Michael Chan6fb34492020-12-08 15:44:49 +11006206 ALOGV("no direct outputs open, reset MSD patches");
6207 // TODO: The MSD patches to be established here may differ to current MSD patches due to
6208 // how output devices for patching are resolved. Avoid by caching and reusing the
6209 // arguments to mEngine->getOutputDevicesForAttributes() when resolving which output
6210 // devices to patch to. This may be complicated by the fact that devices may become
6211 // unavailable.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11006212 setMsdOutputPatches();
Dean Wheatley3023b382018-08-09 07:42:40 +10006213 }
6214 }
Eric Laurent05b90f82014-08-27 15:32:29 -07006215}
6216
6217void AudioPolicyManager::closeInput(audio_io_handle_t input)
6218{
6219 ALOGV("closeInput(%d)", input);
6220
6221 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
6222 if (inputDesc == NULL) {
6223 ALOGW("closeInput() unknown input %d", input);
6224 return;
6225 }
6226
Eric Laurent6a94d692014-05-20 11:18:06 -07006227 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07006228
François Gaffie11d30102018-11-02 16:09:09 +01006229 sp<DeviceDescriptor> device = inputDesc->getDevice();
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08006230 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07006231 if (index >= 0) {
6232 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006233 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
6234 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07006235 mAudioPatches.removeItemsAt(index);
6236 mpClientInterface->onAudioPatchListUpdate();
6237 }
6238
Eric Laurentfe231122017-11-17 17:48:06 -08006239 inputDesc->close();
Eric Laurent05b90f82014-08-27 15:32:29 -07006240 mInputs.removeItem(input);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07006241
François Gaffie11d30102018-11-02 16:09:09 +01006242 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
6243 if (primaryInputDevices.contains(device) &&
Haynes Mathew George1d539d92018-03-16 11:40:49 -07006244 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07006245 mpClientInterface->setSoundTriggerCaptureState(false);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07006246 }
Eric Laurente552edb2014-03-10 17:42:56 -07006247}
6248
François Gaffie11d30102018-11-02 16:09:09 +01006249SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevices(
6250 const DeviceVector &devices,
6251 const SwAudioOutputCollection& openOutputs)
Eric Laurente552edb2014-03-10 17:42:56 -07006252{
6253 SortedVector<audio_io_handle_t> outputs;
6254
François Gaffie11d30102018-11-02 16:09:09 +01006255 ALOGVV("%s() devices %s", __func__, devices.toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07006256 for (size_t i = 0; i < openOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01006257 ALOGVV("output %zu isDuplicated=%d device=%s",
Eric Laurent8c7e6da2015-04-21 17:37:00 -07006258 i, openOutputs.valueAt(i)->isDuplicated(),
François Gaffie11d30102018-11-02 16:09:09 +01006259 openOutputs.valueAt(i)->supportedDevices().toString().c_str());
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006260 if (openOutputs.valueAt(i)->supportsAllDevices(devices)
jiabin9a3361e2019-10-01 09:38:30 -07006261 && openOutputs.valueAt(i)->devicesSupportEncodedFormats(devices.types())) {
François Gaffie11d30102018-11-02 16:09:09 +01006262 ALOGVV("%s() found output %d", __func__, openOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07006263 outputs.add(openOutputs.keyAt(i));
6264 }
6265 }
6266 return outputs;
6267}
6268
Mikhail Naganov37977152018-07-11 15:54:44 -07006269void AudioPolicyManager::checkForDeviceAndOutputChanges(std::function<bool()> onOutputsChecked)
6270{
6271 // checkA2dpSuspend must run before checkOutputForAllStrategies so that A2DP
6272 // output is suspended before any tracks are moved to it
6273 checkA2dpSuspend();
6274 checkOutputForAllStrategies();
Kevin Rocard153f92d2018-12-18 18:33:28 -08006275 checkSecondaryOutputs();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11006276 if (onOutputsChecked != nullptr && onOutputsChecked()) checkA2dpSuspend();
Mikhail Naganov37977152018-07-11 15:54:44 -07006277 updateDevicesAndOutputs();
Mikhail Naganov7bd9b8d2018-11-15 02:09:03 +00006278 if (mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD) != 0) {
Michael Chan6fb34492020-12-08 15:44:49 +11006279 // TODO: The MSD patches to be established here may differ to current MSD patches due to how
6280 // output devices for patching are resolved. Nevertheless, AudioTracks affected by device
6281 // configuration changes will ultimately be rerouted correctly. We can still avoid
6282 // unnecessary rerouting by caching and reusing the arguments to
6283 // mEngine->getOutputDevicesForAttributes() when resolving which output devices to patch to.
6284 // This may be complicated by the fact that devices may become unavailable.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11006285 setMsdOutputPatches();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11006286 }
Jean-Michel Trivi9a6b9ad2020-10-22 16:46:43 -07006287 // an event that changed routing likely occurred, inform upper layers
6288 mpClientInterface->onRoutingUpdated();
Mikhail Naganov37977152018-07-11 15:54:44 -07006289}
6290
François Gaffiec005e562018-11-06 15:04:49 +01006291bool AudioPolicyManager::followsSameRouting(const audio_attributes_t &lAttr,
6292 const audio_attributes_t &rAttr) const
Eric Laurente552edb2014-03-10 17:42:56 -07006293{
François Gaffiec005e562018-11-06 15:04:49 +01006294 return mEngine->getProductStrategyForAttributes(lAttr) ==
6295 mEngine->getProductStrategyForAttributes(rAttr);
6296}
6297
Francois Gaffieff1eb522020-05-06 18:37:04 +02006298void AudioPolicyManager::checkAudioSourceForAttributes(const audio_attributes_t &attr)
6299{
6300 for (size_t i = 0; i < mAudioSources.size(); i++) {
6301 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
6302 if (sourceDesc != nullptr && followsSameRouting(attr, sourceDesc->attributes())
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02006303 && sourceDesc->getPatchHandle() == AUDIO_PATCH_HANDLE_NONE
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02006304 && !isCallRxAudioSource(sourceDesc) && !sourceDesc->isInternal()) {
Francois Gaffieff1eb522020-05-06 18:37:04 +02006305 connectAudioSource(sourceDesc);
6306 }
6307 }
6308}
6309
6310void AudioPolicyManager::clearAudioSourcesForOutput(audio_io_handle_t output)
6311{
6312 for (size_t i = 0; i < mAudioSources.size(); i++) {
6313 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
6314 if (sourceDesc != nullptr && sourceDesc->swOutput().promote() != nullptr
6315 && sourceDesc->swOutput().promote()->mIoHandle == output) {
6316 disconnectAudioSource(sourceDesc);
6317 }
6318 }
6319}
6320
François Gaffiec005e562018-11-06 15:04:49 +01006321void AudioPolicyManager::checkOutputForAttributes(const audio_attributes_t &attr)
6322{
6323 auto psId = mEngine->getProductStrategyForAttributes(attr);
6324
6325 DeviceVector oldDevices = mEngine->getOutputDevicesForAttributes(attr, 0, true /*fromCache*/);
6326 DeviceVector newDevices = mEngine->getOutputDevicesForAttributes(attr, 0, false /*fromCache*/);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07006327
François Gaffie11d30102018-11-02 16:09:09 +01006328 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevices(oldDevices, mPreviousOutputs);
6329 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevices(newDevices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07006330
Eric Laurentc209fe42020-06-05 18:11:23 -07006331 uint32_t maxLatency = 0;
6332 bool invalidate = false;
6333 // take into account dynamic audio policies related changes: if a client is now associated
6334 // to a different policy mix than at creation time, invalidate corresponding stream
6335 for (size_t i = 0; i < mPreviousOutputs.size() && !invalidate; i++) {
6336 const sp<SwAudioOutputDescriptor>& desc = mPreviousOutputs.valueAt(i);
6337 if (desc->isDuplicated()) {
6338 continue;
Jean-Michel Trivife472e22014-12-16 14:23:13 -08006339 }
Eric Laurentc209fe42020-06-05 18:11:23 -07006340 for (const sp<TrackClientDescriptor>& client : desc->getClientIterable()) {
6341 if (mEngine->getProductStrategyForAttributes(client->attributes()) != psId) {
6342 continue;
6343 }
6344 sp<AudioPolicyMix> primaryMix;
Dean Wheatley23ecfe42022-02-04 11:10:48 +11006345 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->config(),
6346 client->uid(), client->flags(), primaryMix, nullptr);
Eric Laurentc209fe42020-06-05 18:11:23 -07006347 if (status != OK) {
6348 continue;
6349 }
yucliuf4de36d2020-09-14 14:57:56 -07006350 if (client->getPrimaryMix() != primaryMix || client->hasLostPrimaryMix()) {
Eric Laurentc209fe42020-06-05 18:11:23 -07006351 invalidate = true;
6352 if (desc->isStrategyActive(psId)) {
6353 maxLatency = desc->latency();
6354 }
6355 break;
6356 }
Jean-Michel Trivife472e22014-12-16 14:23:13 -08006357 }
6358 }
6359
Eric Laurentc209fe42020-06-05 18:11:23 -07006360 if (srcOutputs != dstOutputs || invalidate) {
Eric Laurentac3a6902018-05-11 16:39:10 -07006361 // get maximum latency of all source outputs to determine the minimum mute time guaranteeing
6362 // audio from invalidated tracks will be rendered when unmuting
Eric Laurentac3a6902018-05-11 16:39:10 -07006363 for (audio_io_handle_t srcOut : srcOutputs) {
6364 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
Eric Laurentaa02db82019-09-05 17:31:49 -07006365 if (desc == nullptr) continue;
6366
6367 if (desc->isStrategyActive(psId) && maxLatency < desc->latency()) {
Eric Laurentac3a6902018-05-11 16:39:10 -07006368 maxLatency = desc->latency();
6369 }
Eric Laurentaa02db82019-09-05 17:31:49 -07006370
6371 if (invalidate) continue;
6372
6373 for (auto client : desc->clientsList(false /*activeOnly*/)) {
Eric Laurent78aade82019-09-13 18:55:08 -07006374 if (desc->isDuplicated() || !desc->mProfile->isDirectOutput()) {
Eric Laurentaa02db82019-09-05 17:31:49 -07006375 // a client on a non direct outputs has necessarily a linear PCM format
6376 // so we can call selectOutput() safely
6377 const audio_io_handle_t newOutput = selectOutput(dstOutputs,
6378 client->flags(),
6379 client->config().format,
6380 client->config().channel_mask,
jiabinebb6af42020-06-09 17:31:17 -07006381 client->config().sample_rate,
6382 client->session());
Eric Laurentaa02db82019-09-05 17:31:49 -07006383 if (newOutput != srcOut) {
6384 invalidate = true;
6385 break;
6386 }
6387 } else {
6388 sp<IOProfile> profile = getProfileForOutput(newDevices,
6389 client->config().sample_rate,
6390 client->config().format,
6391 client->config().channel_mask,
6392 client->flags(),
6393 true /* directOnly */);
6394 if (profile != desc->mProfile) {
6395 invalidate = true;
6396 break;
6397 }
6398 }
6399 }
Eric Laurentac3a6902018-05-11 16:39:10 -07006400 }
Eric Laurentaa02db82019-09-05 17:31:49 -07006401
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006402 ALOGV_IF(!(srcOutputs.isEmpty() || dstOutputs.isEmpty()),
François Gaffiec005e562018-11-06 15:04:49 +01006403 "%s: strategy %d, moving from output %s to output %s", __func__, psId,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006404 std::to_string(srcOutputs[0]).c_str(),
6405 std::to_string(dstOutputs[0]).c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07006406 // mute strategy while moving tracks from one output to another
Mikhail Naganovcf84e592017-12-07 11:25:11 -08006407 for (audio_io_handle_t srcOut : srcOutputs) {
Eric Laurentac3a6902018-05-11 16:39:10 -07006408 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
Eric Laurentaa02db82019-09-05 17:31:49 -07006409 if (desc == nullptr) continue;
6410
6411 if (desc->isStrategyActive(psId)) {
François Gaffiec005e562018-11-06 15:04:49 +01006412 setStrategyMute(psId, true, desc);
6413 setStrategyMute(psId, false, desc, maxLatency * LATENCY_MUTE_FACTOR,
François Gaffie11d30102018-11-02 16:09:09 +01006414 newDevices.types());
Eric Laurente552edb2014-03-10 17:42:56 -07006415 }
François Gaffiec005e562018-11-06 15:04:49 +01006416 sp<SourceClientDescriptor> source = getSourceForAttributesOnOutput(srcOut, attr);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02006417 if (source != nullptr && !isCallRxAudioSource(source) && !source->isInternal()) {
Eric Laurentd60560a2015-04-10 11:31:20 -07006418 connectAudioSource(source);
6419 }
Eric Laurente552edb2014-03-10 17:42:56 -07006420 }
6421
François Gaffiec005e562018-11-06 15:04:49 +01006422 // Move effects associated to this stream from previous output to new output
6423 if (followsSameRouting(attr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07006424 selectOutputForMusicEffects();
Eric Laurente552edb2014-03-10 17:42:56 -07006425 }
François Gaffiec005e562018-11-06 15:04:49 +01006426 // Move tracks associated to this stream (and linked) from previous output to new output
Eric Laurentaa02db82019-09-05 17:31:49 -07006427 if (invalidate) {
6428 for (auto stream : mEngine->getStreamTypesForProductStrategy(psId)) {
6429 mpClientInterface->invalidateStream(stream);
6430 }
jiabin49256852022-03-09 11:21:35 -08006431 for (audio_io_handle_t srcOut : srcOutputs) {
6432 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
6433 if (desc == nullptr) continue;
6434
6435 desc->setTracksInvalidatedStatusByStrategy(psId);
6436 }
Eric Laurente552edb2014-03-10 17:42:56 -07006437 }
6438 }
6439}
6440
Eric Laurente0720872014-03-11 09:30:41 -07006441void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07006442{
François Gaffiec005e562018-11-06 15:04:49 +01006443 for (const auto &strategy : mEngine->getOrderedProductStrategies()) {
6444 auto attributes = mEngine->getAllAttributesForProductStrategy(strategy).front();
6445 checkOutputForAttributes(attributes);
Francois Gaffieff1eb522020-05-06 18:37:04 +02006446 checkAudioSourceForAttributes(attributes);
François Gaffiec005e562018-11-06 15:04:49 +01006447 }
Eric Laurente552edb2014-03-10 17:42:56 -07006448}
6449
Kevin Rocard153f92d2018-12-18 18:33:28 -08006450void AudioPolicyManager::checkSecondaryOutputs() {
6451 std::set<audio_stream_type_t> streamsToInvalidate;
jiabin10a03f12021-05-07 23:46:28 +00006452 TrackSecondaryOutputsMap trackSecondaryOutputs;
Kevin Rocard153f92d2018-12-18 18:33:28 -08006453 for (size_t i = 0; i < mOutputs.size(); i++) {
6454 const sp<SwAudioOutputDescriptor>& outputDescriptor = mOutputs[i];
6455 for (const sp<TrackClientDescriptor>& client : outputDescriptor->getClientIterable()) {
Eric Laurentc529cf62020-04-17 18:19:10 -07006456 sp<AudioPolicyMix> primaryMix;
6457 std::vector<sp<AudioPolicyMix>> secondaryMixes;
Dean Wheatley23ecfe42022-02-04 11:10:48 +11006458 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->config(),
6459 client->uid(), client->flags(), primaryMix, &secondaryMixes);
Eric Laurentc529cf62020-04-17 18:19:10 -07006460 std::vector<sp<SwAudioOutputDescriptor>> secondaryDescs;
6461 for (auto &secondaryMix : secondaryMixes) {
6462 sp<SwAudioOutputDescriptor> outputDesc = secondaryMix->getOutput();
6463 if (outputDesc != nullptr &&
6464 outputDesc->mIoHandle != AUDIO_IO_HANDLE_NONE) {
6465 secondaryDescs.push_back(outputDesc);
6466 }
6467 }
6468
jiabin10a03f12021-05-07 23:46:28 +00006469 if (status != OK) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08006470 streamsToInvalidate.insert(client->stream());
jiabin10a03f12021-05-07 23:46:28 +00006471 } else if (!std::equal(
6472 client->getSecondaryOutputs().begin(),
6473 client->getSecondaryOutputs().end(),
6474 secondaryDescs.begin(), secondaryDescs.end())) {
jiabina5281062021-11-23 00:10:23 +00006475 if (!audio_is_linear_pcm(client->config().format)) {
6476 // If the format is not PCM, the tracks should be invalidated to get correct
6477 // behavior when the secondary output is changed.
6478 streamsToInvalidate.insert(client->stream());
6479 } else {
6480 std::vector<wp<SwAudioOutputDescriptor>> weakSecondaryDescs;
6481 std::vector<audio_io_handle_t> secondaryOutputIds;
6482 for (const auto &secondaryDesc: secondaryDescs) {
6483 secondaryOutputIds.push_back(secondaryDesc->mIoHandle);
6484 weakSecondaryDescs.push_back(secondaryDesc);
6485 }
6486 trackSecondaryOutputs.emplace(client->portId(), secondaryOutputIds);
6487 client->setSecondaryOutputs(std::move(weakSecondaryDescs));
jiabin10a03f12021-05-07 23:46:28 +00006488 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08006489 }
6490 }
6491 }
jiabin10a03f12021-05-07 23:46:28 +00006492 if (!trackSecondaryOutputs.empty()) {
6493 mpClientInterface->updateSecondaryOutputs(trackSecondaryOutputs);
6494 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08006495 for (audio_stream_type_t stream : streamsToInvalidate) {
jiabin10a03f12021-05-07 23:46:28 +00006496 ALOGD("%s Invalidate stream %d due to fail getting output for attr", __func__, stream);
Kevin Rocard153f92d2018-12-18 18:33:28 -08006497 mpClientInterface->invalidateStream(stream);
6498 }
6499}
6500
Eric Laurent2517af32020-11-25 15:31:27 +01006501bool AudioPolicyManager::isScoRequestedForComm() const {
6502 AudioDeviceTypeAddrVector devices;
6503 mEngine->getDevicesForRoleAndStrategy(mCommunnicationStrategy, DEVICE_ROLE_PREFERRED, devices);
6504 for (const auto &device : devices) {
6505 if (audio_is_bluetooth_out_sco_device(device.mType)) {
6506 return true;
6507 }
6508 }
6509 return false;
6510}
6511
Eric Laurent1a8b45f2022-04-13 16:01:47 +02006512bool AudioPolicyManager::isHearingAidUsedForComm() const {
6513 DeviceVector devices = mEngine->getOutputDevicesForStream(AUDIO_STREAM_VOICE_CALL,
6514 true /*fromCache*/);
6515 for (const auto &device : devices) {
6516 if (device->type() == AUDIO_DEVICE_OUT_HEARING_AID) {
6517 return true;
6518 }
6519 }
6520 return false;
6521}
6522
6523
Eric Laurente0720872014-03-11 09:30:41 -07006524void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07006525{
François Gaffie53615e22015-03-19 09:24:12 +01006526 audio_io_handle_t a2dpOutput = mOutputs.getA2dpOutput();
Aniket Kumar Lataa8ee9962018-01-31 20:24:23 -08006527 if (a2dpOutput == 0 || mOutputs.isA2dpOffloadedOnPrimary()) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07006528 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07006529 return;
6530 }
6531
Eric Laurent3a4311c2014-03-17 12:00:47 -07006532 bool isScoConnected =
jiabin9a3361e2019-10-01 09:38:30 -07006533 (mAvailableInputDevices.types().count(AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) != 0 ||
6534 !Intersection(mAvailableOutputDevices.types(), getAudioDeviceOutAllScoSet()).empty());
Eric Laurent2517af32020-11-25 15:31:27 +01006535 bool isScoRequested = isScoRequestedForComm();
Eric Laurentf732e072016-08-03 19:30:28 -07006536
6537 // if suspended, restore A2DP output if:
6538 // ((SCO device is NOT connected) ||
Eric Laurent2517af32020-11-25 15:31:27 +01006539 // ((SCO is not requested) &&
Eric Laurentf732e072016-08-03 19:30:28 -07006540 // (phone state is NOT in call) && (phone state is NOT ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07006541 //
Eric Laurentf732e072016-08-03 19:30:28 -07006542 // if not suspended, suspend A2DP output if:
6543 // (SCO device is connected) &&
Eric Laurent2517af32020-11-25 15:31:27 +01006544 // ((SCO is requested) ||
Eric Laurentf732e072016-08-03 19:30:28 -07006545 // ((phone state is in call) || (phone state is ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07006546 //
6547 if (mA2dpSuspended) {
Eric Laurentf732e072016-08-03 19:30:28 -07006548 if (!isScoConnected ||
Eric Laurent2517af32020-11-25 15:31:27 +01006549 (!isScoRequested &&
Eric Laurentf732e072016-08-03 19:30:28 -07006550 (mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) &&
François Gaffie2110e042015-03-24 08:41:51 +01006551 (mEngine->getPhoneState() != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07006552
6553 mpClientInterface->restoreOutput(a2dpOutput);
6554 mA2dpSuspended = false;
6555 }
6556 } else {
Eric Laurentf732e072016-08-03 19:30:28 -07006557 if (isScoConnected &&
Eric Laurent2517af32020-11-25 15:31:27 +01006558 (isScoRequested ||
Eric Laurentf732e072016-08-03 19:30:28 -07006559 (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) ||
François Gaffie2110e042015-03-24 08:41:51 +01006560 (mEngine->getPhoneState() == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07006561
6562 mpClientInterface->suspendOutput(a2dpOutput);
6563 mA2dpSuspended = true;
6564 }
6565 }
6566}
6567
François Gaffie11d30102018-11-02 16:09:09 +01006568DeviceVector AudioPolicyManager::getNewOutputDevices(const sp<SwAudioOutputDescriptor>& outputDesc,
6569 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07006570{
François Gaffie11d30102018-11-02 16:09:09 +01006571 DeviceVector devices;
6572
Jean-Michel Triviff155c62016-02-26 12:07:16 -08006573 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07006574 if (index >= 0) {
6575 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006576 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01006577 ALOGV("%s device %s forced by patch %d", __func__,
6578 outputDesc->devices().toString().c_str(), outputDesc->getPatchHandle());
6579 return outputDesc->devices();
Eric Laurent6a94d692014-05-20 11:18:06 -07006580 }
6581 }
6582
Dean Wheatley514b4312020-06-17 21:45:00 +10006583 // Do not retrieve engine device for outputs through MSD
6584 // TODO: support explicit routing requests by resetting MSD patch to engine device.
6585 if (outputDesc->devices() == getMsdAudioOutDevices()) {
6586 return outputDesc->devices();
6587 }
6588
Eric Laurent97ac8712018-07-27 18:59:02 -07006589 // Honor explicit routing requests only if no client using default routing is active on this
6590 // input: a specific app can not force routing for other apps by setting a preferred device.
6591 bool active; // unused
François Gaffie11d30102018-11-02 16:09:09 +01006592 sp<DeviceDescriptor> device =
François Gaffiec005e562018-11-06 15:04:49 +01006593 findPreferredDevice(outputDesc, PRODUCT_STRATEGY_NONE, active, mAvailableOutputDevices);
François Gaffie11d30102018-11-02 16:09:09 +01006594 if (device != nullptr) {
6595 return DeviceVector(device);
Eric Laurentf3a5a602018-05-22 18:42:55 -07006596 }
6597
François Gaffiea807ef92018-11-05 10:44:33 +01006598 // Legacy Engine cannot take care of bus devices and mix, so we need to handle the conflict
6599 // of setForceUse / Default Bus device here
6600 device = mPolicyMixes.getDeviceAndMixForOutput(outputDesc, mAvailableOutputDevices);
6601 if (device != nullptr) {
6602 return DeviceVector(device);
6603 }
6604
François Gaffiec005e562018-11-06 15:04:49 +01006605 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
6606 StreamTypeVector streams = mEngine->getStreamTypesForProductStrategy(productStrategy);
6607 auto attr = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05306608 auto hasStreamActive = [&](auto stream) {
6609 return hasStream(streams, stream) && isStreamActive(stream, 0);
6610 };
Eric Laurent484e9272018-06-07 17:29:23 -07006611
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05306612 auto doGetOutputDevicesForVoice = [&]() {
6613 return hasVoiceStream(streams) && (outputDesc == mPrimaryOutput ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01006614 outputDesc->isActive(toVolumeSource(AUDIO_STREAM_VOICE_CALL, false))) &&
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05306615 (isInCall() ||
Henrik Backlund07c654a2021-10-14 15:57:10 +02006616 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc)) &&
6617 !isStreamActive(AUDIO_STREAM_ENFORCED_AUDIBLE, 0);
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05306618 };
6619
6620 // With low-latency playing on speaker, music on WFD, when the first low-latency
6621 // output is stopped, getNewOutputDevices checks for a product strategy
6622 // from the list, as STRATEGY_SONIFICATION comes prior to STRATEGY_MEDIA.
Carter Hsucc58a6b2021-07-20 08:44:50 +00006623 // If an ALARM or ENFORCED_AUDIBLE stream is supported by the product strategy,
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05306624 // devices are returned for STRATEGY_SONIFICATION without checking whether the
6625 // stream is associated to the output descriptor.
6626 if (doGetOutputDevicesForVoice() || outputDesc->isStrategyActive(productStrategy) ||
6627 ((hasStreamActive(AUDIO_STREAM_ALARM) ||
6628 hasStreamActive(AUDIO_STREAM_ENFORCED_AUDIBLE)) &&
6629 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc))) {
François Gaffiec005e562018-11-06 15:04:49 +01006630 // Retrieval of devices for voice DL is done on primary output profile, cannot
6631 // check the route (would force modifying configuration file for this profile)
6632 devices = mEngine->getOutputDevicesForAttributes(attr, nullptr, fromCache);
6633 break;
6634 }
Eric Laurente552edb2014-03-10 17:42:56 -07006635 }
François Gaffiec005e562018-11-06 15:04:49 +01006636 ALOGV("%s selected devices %s", __func__, devices.toString().c_str());
François Gaffie11d30102018-11-02 16:09:09 +01006637 return devices;
Eric Laurent1c333e22014-05-20 10:48:17 -07006638}
6639
François Gaffie11d30102018-11-02 16:09:09 +01006640sp<DeviceDescriptor> AudioPolicyManager::getNewInputDevice(
6641 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurent1c333e22014-05-20 10:48:17 -07006642{
François Gaffie11d30102018-11-02 16:09:09 +01006643 sp<DeviceDescriptor> device;
Eric Laurent6a94d692014-05-20 11:18:06 -07006644
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08006645 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07006646 if (index >= 0) {
6647 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006648 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01006649 ALOGV("getNewInputDevice() device %s forced by patch %d",
6650 inputDesc->getDevice()->toString().c_str(), inputDesc->getPatchHandle());
6651 return inputDesc->getDevice();
Eric Laurent6a94d692014-05-20 11:18:06 -07006652 }
6653 }
6654
Eric Laurent97ac8712018-07-27 18:59:02 -07006655 // Honor explicit routing requests only if no client using default routing is active on this
6656 // input: a specific app can not force routing for other apps by setting a preferred device.
6657 bool active;
François Gaffie11d30102018-11-02 16:09:09 +01006658 device = findPreferredDevice(inputDesc, AUDIO_SOURCE_DEFAULT, active, mAvailableInputDevices);
6659 if (device != nullptr) {
6660 return device;
Eric Laurent97ac8712018-07-27 18:59:02 -07006661 }
6662
Eric Laurentdc95a252018-04-12 12:46:56 -07006663 // If we are not in call and no client is active on this input, this methods returns
Andy Hungf024a9e2019-01-30 16:01:02 -08006664 // a null sp<>, causing the patch on the input stream to be released.
yuanjiahsu0735bf32021-03-18 08:12:54 +08006665 audio_attributes_t attributes;
6666 uid_t uid;
6667 sp<RecordClientDescriptor> topClient = inputDesc->getHighestPriorityClient();
6668 if (topClient != nullptr) {
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01006669 attributes = topClient->attributes();
6670 uid = topClient->uid();
yuanjiahsu0735bf32021-03-18 08:12:54 +08006671 } else {
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01006672 attributes = { .source = AUDIO_SOURCE_DEFAULT };
6673 uid = 0;
yuanjiahsu0735bf32021-03-18 08:12:54 +08006674 }
6675
Francois Gaffie716e1432019-01-14 16:58:59 +01006676 if (attributes.source == AUDIO_SOURCE_DEFAULT && isInCall()) {
6677 attributes.source = AUDIO_SOURCE_VOICE_COMMUNICATION;
Eric Laurentdc95a252018-04-12 12:46:56 -07006678 }
Francois Gaffie716e1432019-01-14 16:58:59 +01006679 if (attributes.source != AUDIO_SOURCE_DEFAULT) {
yuanjiahsu0735bf32021-03-18 08:12:54 +08006680 device = mEngine->getInputDeviceForAttributes(attributes, uid);
Eric Laurentfb66dd92016-01-28 18:32:03 -08006681 }
Eric Laurent1c333e22014-05-20 10:48:17 -07006682
Eric Laurente552edb2014-03-10 17:42:56 -07006683 return device;
6684}
6685
Eric Laurent794fde22016-03-11 09:50:45 -08006686bool AudioPolicyManager::streamsMatchForvolume(audio_stream_type_t stream1,
6687 audio_stream_type_t stream2) {
Jean-Michel Trivi99bb2f92016-11-23 15:52:07 -08006688 return (stream1 == stream2);
Eric Laurent28d09f02016-03-08 10:43:05 -08006689}
6690
Dorin Drimusf2196d82022-01-03 12:11:18 +01006691// TODO - consider MSD routes b/214971780
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08006692status_t AudioPolicyManager::getDevicesForAttributes(
Andy Hung6d23c0f2022-02-16 09:37:15 -08006693 const audio_attributes_t &attr, AudioDeviceTypeAddrVector *devices, bool forVolume) {
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08006694 if (devices == nullptr) {
6695 return BAD_VALUE;
6696 }
Andy Hung6d23c0f2022-02-16 09:37:15 -08006697
6698 // Devices are determined in the following precedence:
6699 //
6700 // 1) Devices associated with a dynamic policy matching the attributes. This is often
6701 // a remote submix from MIX_ROUTE_FLAG_LOOP_BACK.
6702 //
6703 // If no such dynamic policy then
6704 // 2) Devices containing an active client using setPreferredDevice
6705 // with same strategy as the attributes.
6706 // (from the default Engine::getOutputDevicesForAttributes() implementation).
6707 //
6708 // If no corresponding active client with setPreferredDevice then
6709 // 3) Devices associated with the strategy determined by the attributes
6710 // (from the default Engine::getOutputDevicesForAttributes() implementation).
6711 //
6712 // See related getOutputForAttrInt().
6713
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08006714 // check dynamic policies but only for primary descriptors (secondary not used for audible
6715 // audio routing, only used for duplication for playback capture)
Eric Laurentc529cf62020-04-17 18:19:10 -07006716 sp<AudioPolicyMix> policyMix;
Dean Wheatley23ecfe42022-02-04 11:10:48 +11006717 status_t status = mPolicyMixes.getOutputForAttr(attr, AUDIO_CONFIG_BASE_INITIALIZER,
6718 0 /*uid unknown here*/, AUDIO_OUTPUT_FLAG_NONE, policyMix, nullptr);
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08006719 if (status != OK) {
6720 return status;
6721 }
Andy Hung6d23c0f2022-02-16 09:37:15 -08006722
6723 DeviceVector curDevices;
6724 if (policyMix != nullptr && policyMix->getOutput() != nullptr &&
6725 // For volume control, skip LOOPBACK mixes which use AUDIO_DEVICE_OUT_REMOTE_SUBMIX
6726 // as they are unaffected by device/stream volume
6727 // (per SwAudioOutputDescriptor::isFixedVolume()).
6728 (!forVolume || policyMix->mDeviceType != AUDIO_DEVICE_OUT_REMOTE_SUBMIX)
6729 ) {
6730 sp<DeviceDescriptor> deviceDesc = mAvailableOutputDevices.getDevice(
6731 policyMix->mDeviceType, policyMix->mDeviceAddress, AUDIO_FORMAT_DEFAULT);
6732 curDevices.add(deviceDesc);
6733 } else {
6734 // The default Engine::getOutputDevicesForAttributes() uses findPreferredDevice()
6735 // which selects setPreferredDevice if active. This means forVolume call
6736 // will take an active setPreferredDevice, if such exists.
6737
6738 curDevices = mEngine->getOutputDevicesForAttributes(
6739 attr, nullptr /* preferredDevice */, false /* fromCache */);
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08006740 }
Andy Hung6d23c0f2022-02-16 09:37:15 -08006741
6742 if (forVolume) {
6743 // We alias the device AUDIO_DEVICE_OUT_SPEAKER_SAFE to AUDIO_DEVICE_OUT_SPEAKER
6744 // for single volume control in AudioService (such relationship should exist if
6745 // SPEAKER_SAFE is present).
6746 //
6747 // (This is unrelated to a different device grouping as Volume::getDeviceCategory)
6748 DeviceVector speakerSafeDevices =
6749 curDevices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER_SAFE);
6750 if (!speakerSafeDevices.isEmpty()) {
6751 curDevices.merge(
6752 mAvailableOutputDevices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER));
6753 curDevices.remove(speakerSafeDevices);
6754 }
6755 }
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08006756 for (const auto& device : curDevices) {
6757 devices->push_back(device->getDeviceTypeAddr());
6758 }
6759 return NO_ERROR;
6760}
6761
Eric Laurente0720872014-03-11 09:30:41 -07006762void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07006763 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07006764 case AUDIO_STREAM_MUSIC:
François Gaffiec005e562018-11-06 15:04:49 +01006765 checkOutputForAttributes(attributes_initializer(AUDIO_USAGE_NOTIFICATION));
Eric Laurente552edb2014-03-10 17:42:56 -07006766 updateDevicesAndOutputs();
6767 break;
6768 default:
6769 break;
6770 }
6771}
6772
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006773uint32_t AudioPolicyManager::handleEventForBeacon(int event) {
Eric Laurent9459fb02015-08-12 18:36:32 -07006774
6775 // skip beacon mute management if a dedicated TTS output is available
6776 if (mTtsOutputAvailable) {
6777 return 0;
6778 }
6779
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006780 switch(event) {
6781 case STARTING_OUTPUT:
6782 mBeaconMuteRefCount++;
6783 break;
6784 case STOPPING_OUTPUT:
6785 if (mBeaconMuteRefCount > 0) {
6786 mBeaconMuteRefCount--;
6787 }
6788 break;
6789 case STARTING_BEACON:
6790 mBeaconPlayingRefCount++;
6791 break;
6792 case STOPPING_BEACON:
6793 if (mBeaconPlayingRefCount > 0) {
6794 mBeaconPlayingRefCount--;
6795 }
6796 break;
6797 }
6798
6799 if (mBeaconMuteRefCount > 0) {
6800 // any playback causes beacon to be muted
6801 return setBeaconMute(true);
6802 } else {
6803 // no other playback: unmute when beacon starts playing, mute when it stops
6804 return setBeaconMute(mBeaconPlayingRefCount == 0);
6805 }
6806}
6807
6808uint32_t AudioPolicyManager::setBeaconMute(bool mute) {
6809 ALOGV("setBeaconMute(%d) mBeaconMuteRefCount=%d mBeaconPlayingRefCount=%d",
6810 mute, mBeaconMuteRefCount, mBeaconPlayingRefCount);
6811 // keep track of muted state to avoid repeating mute/unmute operations
6812 if (mBeaconMuted != mute) {
6813 // mute/unmute AUDIO_STREAM_TTS on all outputs
6814 ALOGV("\t muting %d", mute);
6815 uint32_t maxLatency = 0;
Francois Gaffie4404ddb2021-02-04 17:03:38 +01006816 auto ttsVolumeSource = toVolumeSource(AUDIO_STREAM_TTS, false);
6817 if (ttsVolumeSource == VOLUME_SOURCE_NONE) {
6818 ALOGV("\t no tts volume source available");
6819 return 0;
6820 }
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006821 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07006822 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
jiabin9a3361e2019-10-01 09:38:30 -07006823 setVolumeSourceMute(ttsVolumeSource, mute/*on*/, desc, 0 /*delay*/, DeviceTypeSet());
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006824 const uint32_t latency = desc->latency() * 2;
Eric Laurentcdb2b352020-07-23 10:57:02 -07006825 if (desc->isActive(latency * 2) && latency > maxLatency) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006826 maxLatency = latency;
6827 }
6828 }
6829 mBeaconMuted = mute;
6830 return maxLatency;
6831 }
6832 return 0;
6833}
6834
Eric Laurente0720872014-03-11 09:30:41 -07006835void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07006836{
François Gaffiec005e562018-11-06 15:04:49 +01006837 mEngine->updateDeviceSelectionCache();
Eric Laurente552edb2014-03-10 17:42:56 -07006838 mPreviousOutputs = mOutputs;
6839}
6840
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07006841uint32_t AudioPolicyManager::checkDeviceMuteStrategies(const sp<AudioOutputDescriptor>& outputDesc,
François Gaffiec005e562018-11-06 15:04:49 +01006842 const DeviceVector &prevDevices,
Eric Laurente552edb2014-03-10 17:42:56 -07006843 uint32_t delayMs)
6844{
6845 // mute/unmute strategies using an incompatible device combination
6846 // if muting, wait for the audio in pcm buffer to be drained before proceeding
6847 // if unmuting, unmute only after the specified delay
6848 if (outputDesc->isDuplicated()) {
6849 return 0;
6850 }
6851
6852 uint32_t muteWaitMs = 0;
François Gaffiec005e562018-11-06 15:04:49 +01006853 DeviceVector devices = outputDesc->devices();
6854 bool shouldMute = outputDesc->isActive() && (devices.size() >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07006855
François Gaffiec005e562018-11-06 15:04:49 +01006856 auto productStrategies = mEngine->getOrderedProductStrategies();
6857 for (const auto &productStrategy : productStrategies) {
6858 auto attributes = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
6859 DeviceVector curDevices =
6860 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false/*fromCache*/);
6861 curDevices = curDevices.filter(outputDesc->supportedDevices());
6862 bool mute = shouldMute && curDevices.containsAtLeastOne(devices) && curDevices != devices;
Eric Laurente552edb2014-03-10 17:42:56 -07006863 bool doMute = false;
6864
François Gaffiec005e562018-11-06 15:04:49 +01006865 if (mute && !outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07006866 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01006867 outputDesc->setStrategyMutedByDevice(productStrategy, true);
6868 } else if (!mute && outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07006869 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01006870 outputDesc->setStrategyMutedByDevice(productStrategy, false);
Eric Laurente552edb2014-03-10 17:42:56 -07006871 }
Eric Laurent99401132014-05-07 19:48:15 -07006872 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07006873 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07006874 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07006875 // skip output if it does not share any device with current output
François Gaffie11d30102018-11-02 16:09:09 +01006876 if (!desc->supportedDevices().containsAtLeastOne(outputDesc->supportedDevices())) {
Eric Laurente552edb2014-03-10 17:42:56 -07006877 continue;
6878 }
François Gaffiec005e562018-11-06 15:04:49 +01006879 ALOGVV("%s() %s (curDevice %s)", __func__,
6880 mute ? "muting" : "unmuting", curDevices.toString().c_str());
6881 setStrategyMute(productStrategy, mute, desc, mute ? 0 : delayMs);
6882 if (desc->isStrategyActive(productStrategy)) {
Eric Laurent99401132014-05-07 19:48:15 -07006883 if (mute) {
6884 // FIXME: should not need to double latency if volume could be applied
6885 // immediately by the audioflinger mixer. We must account for the delay
6886 // between now and the next time the audioflinger thread for this output
6887 // will process a buffer (which corresponds to one buffer size,
6888 // usually 1/2 or 1/4 of the latency).
6889 if (muteWaitMs < desc->latency() * 2) {
6890 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07006891 }
6892 }
6893 }
6894 }
6895 }
6896 }
6897
Eric Laurent99401132014-05-07 19:48:15 -07006898 // temporary mute output if device selection changes to avoid volume bursts due to
6899 // different per device volumes
François Gaffiec005e562018-11-06 15:04:49 +01006900 if (outputDesc->isActive() && (devices != prevDevices)) {
Eric Laurentdc462862016-07-19 12:29:53 -07006901 uint32_t tempMuteWaitMs = outputDesc->latency() * 2;
Jasmine Chaf6074fe2021-08-17 13:44:31 +08006902
Eric Laurentdc462862016-07-19 12:29:53 -07006903 if (muteWaitMs < tempMuteWaitMs) {
6904 muteWaitMs = tempMuteWaitMs;
Eric Laurent99401132014-05-07 19:48:15 -07006905 }
Jasmine Chaf6074fe2021-08-17 13:44:31 +08006906
6907 // If recommended duration is defined, replace temporary mute duration to avoid
6908 // truncated notifications at beginning, which depends on duration of changing path in HAL.
6909 // Otherwise, temporary mute duration is conservatively set to 4 times the reported latency.
6910 uint32_t tempRecommendedMuteDuration = outputDesc->getRecommendedMuteDurationMs();
6911 uint32_t tempMuteDurationMs = tempRecommendedMuteDuration > 0 ?
6912 tempRecommendedMuteDuration : outputDesc->latency() * 4;
6913
François Gaffieaaac0fd2018-11-22 17:56:39 +01006914 for (const auto &activeVs : outputDesc->getActiveVolumeSources()) {
6915 // make sure that we do not start the temporary mute period too early in case of
6916 // delayed device change
6917 setVolumeSourceMute(activeVs, true, outputDesc, delayMs);
6918 setVolumeSourceMute(activeVs, false, outputDesc, delayMs + tempMuteDurationMs,
François Gaffiec005e562018-11-06 15:04:49 +01006919 devices.types());
Eric Laurent99401132014-05-07 19:48:15 -07006920 }
6921 }
6922
Eric Laurente552edb2014-03-10 17:42:56 -07006923 // wait for the PCM output buffers to empty before proceeding with the rest of the command
6924 if (muteWaitMs > delayMs) {
6925 muteWaitMs -= delayMs;
6926 usleep(muteWaitMs * 1000);
6927 return muteWaitMs;
6928 }
6929 return 0;
6930}
6931
François Gaffie11d30102018-11-02 16:09:09 +01006932uint32_t AudioPolicyManager::setOutputDevices(const sp<SwAudioOutputDescriptor>& outputDesc,
6933 const DeviceVector &devices,
6934 bool force,
6935 int delayMs,
6936 audio_patch_handle_t *patchHandle,
Francois Gaffie3523ab32021-06-22 13:24:34 +02006937 bool requiresMuteCheck, bool requiresVolumeCheck)
Eric Laurente552edb2014-03-10 17:42:56 -07006938{
François Gaffie11d30102018-11-02 16:09:09 +01006939 ALOGV("%s device %s delayMs %d", __func__, devices.toString().c_str(), delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07006940 uint32_t muteWaitMs;
6941
6942 if (outputDesc->isDuplicated()) {
François Gaffie11d30102018-11-02 16:09:09 +01006943 muteWaitMs = setOutputDevices(outputDesc->subOutput1(), devices, force, delayMs,
6944 nullptr /* patchHandle */, requiresMuteCheck);
6945 muteWaitMs += setOutputDevices(outputDesc->subOutput2(), devices, force, delayMs,
6946 nullptr /* patchHandle */, requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07006947 return muteWaitMs;
6948 }
Eric Laurente552edb2014-03-10 17:42:56 -07006949
6950 // filter devices according to output selected
Francois Gaffie716e1432019-01-14 16:58:59 +01006951 DeviceVector filteredDevices = outputDesc->filterSupportedDevices(devices);
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01006952 DeviceVector prevDevices = outputDesc->devices();
Francois Gaffie3523ab32021-06-22 13:24:34 +02006953 DeviceVector availPrevDevices = mAvailableOutputDevices.filter(prevDevices);
Eric Laurente552edb2014-03-10 17:42:56 -07006954
François Gaffie11d30102018-11-02 16:09:09 +01006955 ALOGV("setOutputDevices() prevDevice %s", prevDevices.toString().c_str());
6956
6957 if (!filteredDevices.isEmpty()) {
6958 outputDesc->setDevices(filteredDevices);
Eric Laurente552edb2014-03-10 17:42:56 -07006959 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00006960
6961 // if the outputs are not materially active, there is no need to mute.
6962 if (requiresMuteCheck) {
François Gaffiec005e562018-11-06 15:04:49 +01006963 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevices, delayMs);
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00006964 } else {
6965 ALOGV("%s: suppressing checkDeviceMuteStrategies", __func__);
6966 muteWaitMs = 0;
6967 }
Eric Laurente552edb2014-03-10 17:42:56 -07006968
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02006969 bool outputRouted = outputDesc->isRouted();
6970
Eric Laurent79ea9582020-06-11 18:49:24 -07006971 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
6972 // output profile or if new device is not supported AND previous device(s) is(are) still
6973 // available (otherwise reset device must be done on the output)
Francois Gaffie3523ab32021-06-22 13:24:34 +02006974 if (!devices.isEmpty() && filteredDevices.isEmpty() && !availPrevDevices.empty()) {
Eric Laurent79ea9582020-06-11 18:49:24 -07006975 ALOGV("%s: unsupported device %s for output", __func__, devices.toString().c_str());
6976 // restore previous device after evaluating strategy mute state
6977 outputDesc->setDevices(prevDevices);
6978 return muteWaitMs;
6979 }
6980
Eric Laurente552edb2014-03-10 17:42:56 -07006981 // Do not change the routing if:
Eric Laurentb80a2a82014-10-27 16:07:59 -07006982 // the requested device is AUDIO_DEVICE_NONE
6983 // OR the requested device is the same as current device
6984 // AND force is not specified
6985 // AND the output is connected by a valid audio patch.
François Gaffie11d30102018-11-02 16:09:09 +01006986 // Doing this check here allows the caller to call setOutputDevices() without conditions
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02006987 if ((filteredDevices.isEmpty() || filteredDevices == prevDevices) && !force && outputRouted) {
François Gaffie11d30102018-11-02 16:09:09 +01006988 ALOGV("%s setting same device %s or null device, force=%d, patch handle=%d", __func__,
6989 filteredDevices.toString().c_str(), force, outputDesc->getPatchHandle());
Francois Gaffie3523ab32021-06-22 13:24:34 +02006990 if (requiresVolumeCheck && !filteredDevices.isEmpty()) {
6991 ALOGV("%s setting same device on routed output, force apply volumes", __func__);
6992 applyStreamVolumes(outputDesc, filteredDevices.types(), delayMs, true /*force*/);
6993 }
Eric Laurente552edb2014-03-10 17:42:56 -07006994 return muteWaitMs;
6995 }
6996
François Gaffie11d30102018-11-02 16:09:09 +01006997 ALOGV("%s changing device to %s", __func__, filteredDevices.toString().c_str());
Eric Laurent1c333e22014-05-20 10:48:17 -07006998
Eric Laurente552edb2014-03-10 17:42:56 -07006999 // do the routing
Francois Gaffie3523ab32021-06-22 13:24:34 +02007000 if (filteredDevices.isEmpty() || mAvailableOutputDevices.filter(filteredDevices).empty()) {
Eric Laurentc75307b2015-03-17 15:29:32 -07007001 resetOutputDevice(outputDesc, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07007002 } else {
François Gaffie11d30102018-11-02 16:09:09 +01007003 PatchBuilder patchBuilder;
7004 patchBuilder.addSource(outputDesc);
7005 ALOG_ASSERT(filteredDevices.size() <= AUDIO_PATCH_PORTS_MAX, "Too many sink ports");
7006 for (const auto &filteredDevice : filteredDevices) {
7007 patchBuilder.addSink(filteredDevice);
Eric Laurentc40d9692016-04-13 19:14:13 -07007008 }
7009
Jasmine Cha7f82d1a2020-03-16 13:21:47 +08007010 // Add half reported latency to delayMs when muteWaitMs is null in order
7011 // to avoid disordered sequence of muting volume and changing devices.
7012 installPatch(__func__, patchHandle, outputDesc.get(), patchBuilder.patch(),
7013 muteWaitMs == 0 ? (delayMs + (outputDesc->latency() / 2)) : delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07007014 }
Eric Laurente552edb2014-03-10 17:42:56 -07007015
7016 // update stream volumes according to new device
François Gaffie11d30102018-11-02 16:09:09 +01007017 applyStreamVolumes(outputDesc, filteredDevices.types(), delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07007018
7019 return muteWaitMs;
7020}
7021
Eric Laurentc75307b2015-03-17 15:29:32 -07007022status_t AudioPolicyManager::resetOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurent6a94d692014-05-20 11:18:06 -07007023 int delayMs,
7024 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07007025{
Eric Laurent6a94d692014-05-20 11:18:06 -07007026 ssize_t index;
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02007027 if (patchHandle == nullptr && !outputDesc->isRouted()) {
7028 return INVALID_OPERATION;
7029 }
Eric Laurent6a94d692014-05-20 11:18:06 -07007030 if (patchHandle) {
7031 index = mAudioPatches.indexOfKey(*patchHandle);
7032 } else {
Jean-Michel Triviff155c62016-02-26 12:07:16 -08007033 index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007034 }
7035 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07007036 return INVALID_OPERATION;
7037 }
Eric Laurent6a94d692014-05-20 11:18:06 -07007038 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007039 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07007040 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07007041 outputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
François Gaffieafd4cea2019-11-18 15:50:22 +01007042 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007043 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07007044 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07007045 return status;
7046}
7047
7048status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
François Gaffie11d30102018-11-02 16:09:09 +01007049 const sp<DeviceDescriptor> &device,
Eric Laurent6a94d692014-05-20 11:18:06 -07007050 bool force,
7051 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07007052{
7053 status_t status = NO_ERROR;
7054
Eric Laurent1f2f2232014-06-02 12:01:23 -07007055 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
François Gaffie11d30102018-11-02 16:09:09 +01007056 if ((device != nullptr) && ((device != inputDesc->getDevice()) || force)) {
7057 inputDesc->setDevice(device);
Eric Laurent1c333e22014-05-20 10:48:17 -07007058
François Gaffie11d30102018-11-02 16:09:09 +01007059 if (mAvailableInputDevices.contains(device)) {
Mikhail Naganovdc769682018-05-04 15:34:08 -07007060 PatchBuilder patchBuilder;
7061 patchBuilder.addSink(inputDesc,
Eric Laurentdaf92cc2014-07-22 15:36:10 -07007062 // AUDIO_SOURCE_HOTWORD is for internal use only:
7063 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
Mikhail Naganovdc769682018-05-04 15:34:08 -07007064 [inputDesc](const PatchBuilder::mix_usecase_t& usecase) {
7065 auto result = usecase;
7066 if (result.source == AUDIO_SOURCE_HOTWORD && !inputDesc->isSoundTrigger()) {
7067 result.source = AUDIO_SOURCE_VOICE_RECOGNITION;
7068 }
7069 return result; }).
Eric Laurent1c333e22014-05-20 10:48:17 -07007070 //only one input device for now
François Gaffie11d30102018-11-02 16:09:09 +01007071 addSource(device);
Mikhail Naganovdc769682018-05-04 15:34:08 -07007072 status = installPatch(__func__, patchHandle, inputDesc.get(), patchBuilder.patch(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07007073 }
7074 }
7075 return status;
7076}
7077
Eric Laurent6a94d692014-05-20 11:18:06 -07007078status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
7079 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07007080{
Eric Laurent1f2f2232014-06-02 12:01:23 -07007081 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07007082 ssize_t index;
7083 if (patchHandle) {
7084 index = mAudioPatches.indexOfKey(*patchHandle);
7085 } else {
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08007086 index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007087 }
7088 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07007089 return INVALID_OPERATION;
7090 }
Eric Laurent6a94d692014-05-20 11:18:06 -07007091 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007092 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07007093 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07007094 inputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
François Gaffieafd4cea2019-11-18 15:50:22 +01007095 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007096 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07007097 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07007098 return status;
7099}
7100
François Gaffie11d30102018-11-02 16:09:09 +01007101sp<IOProfile> AudioPolicyManager::getInputProfile(const sp<DeviceDescriptor> &device,
François Gaffie53615e22015-03-19 09:24:12 +01007102 uint32_t& samplingRate,
Andy Hungf129b032015-04-07 13:45:50 -07007103 audio_format_t& format,
7104 audio_channel_mask_t& channelMask,
François Gaffie53615e22015-03-19 09:24:12 +01007105 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07007106{
7107 // Choose an input profile based on the requested capture parameters: select the first available
7108 // profile supporting all requested parameters.
Andy Hungf129b032015-04-07 13:45:50 -07007109 //
7110 // TODO: perhaps isCompatibleProfile should return a "matching" score so we can return
7111 // the best matching profile, not the first one.
Eric Laurente552edb2014-03-10 17:42:56 -07007112
Glenn Kasten730b9262018-03-29 15:01:26 -07007113 sp<IOProfile> firstInexact;
7114 uint32_t updatedSamplingRate = 0;
7115 audio_format_t updatedFormat = AUDIO_FORMAT_INVALID;
7116 audio_channel_mask_t updatedChannelMask = AUDIO_CHANNEL_INVALID;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08007117 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08007118 for (const auto& profile : hwModule->getInputProfiles()) {
Eric Laurentd4692962014-05-05 18:13:44 -07007119 // profile->log();
Glenn Kasten730b9262018-03-29 15:01:26 -07007120 //updatedFormat = format;
François Gaffie11d30102018-11-02 16:09:09 +01007121 if (profile->isCompatibleProfile(DeviceVector(device), samplingRate,
Glenn Kasten730b9262018-03-29 15:01:26 -07007122 &samplingRate /*updatedSamplingRate*/,
Andy Hungf129b032015-04-07 13:45:50 -07007123 format,
Glenn Kasten730b9262018-03-29 15:01:26 -07007124 &format, /*updatedFormat*/
Andy Hungf129b032015-04-07 13:45:50 -07007125 channelMask,
Glenn Kasten730b9262018-03-29 15:01:26 -07007126 &channelMask /*updatedChannelMask*/,
7127 // FIXME ugly cast
7128 (audio_output_flags_t) flags,
7129 true /*exactMatchRequiredForInputFlags*/)) {
Eric Laurente552edb2014-03-10 17:42:56 -07007130 return profile;
7131 }
François Gaffie11d30102018-11-02 16:09:09 +01007132 if (firstInexact == nullptr && profile->isCompatibleProfile(DeviceVector(device),
Glenn Kasten730b9262018-03-29 15:01:26 -07007133 samplingRate,
7134 &updatedSamplingRate,
7135 format,
7136 &updatedFormat,
7137 channelMask,
7138 &updatedChannelMask,
7139 // FIXME ugly cast
7140 (audio_output_flags_t) flags,
7141 false /*exactMatchRequiredForInputFlags*/)) {
7142 firstInexact = profile;
7143 }
7144
Eric Laurente552edb2014-03-10 17:42:56 -07007145 }
7146 }
Glenn Kasten730b9262018-03-29 15:01:26 -07007147 if (firstInexact != nullptr) {
7148 samplingRate = updatedSamplingRate;
7149 format = updatedFormat;
7150 channelMask = updatedChannelMask;
7151 return firstInexact;
7152 }
Eric Laurente552edb2014-03-10 17:42:56 -07007153 return NULL;
7154}
7155
François Gaffieaaac0fd2018-11-22 17:56:39 +01007156float AudioPolicyManager::computeVolume(IVolumeCurves &curves,
7157 VolumeSource volumeSource,
François Gaffied1ab2bd2015-12-02 18:20:06 +01007158 int index,
jiabin9a3361e2019-10-01 09:38:30 -07007159 const DeviceTypeSet& deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07007160{
jiabin9a3361e2019-10-01 09:38:30 -07007161 float volumeDb = curves.volIndexToDb(Volume::getDeviceCategory(deviceTypes), index);
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07007162
7163 // handle the case of accessibility active while a ringtone is playing: if the ringtone is much
7164 // louder than the accessibility prompt, the prompt cannot be heard, thus masking the touch
7165 // exploration of the dialer UI. In this situation, bring the accessibility volume closer to
7166 // the ringtone volume
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007167 const auto callVolumeSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL, false);
7168 const auto ringVolumeSrc = toVolumeSource(AUDIO_STREAM_RING, false);
7169 const auto musicVolumeSrc = toVolumeSource(AUDIO_STREAM_MUSIC, false);
7170 const auto alarmVolumeSrc = toVolumeSource(AUDIO_STREAM_ALARM, false);
7171 const auto a11yVolumeSrc = toVolumeSource(AUDIO_STREAM_ACCESSIBILITY, false);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007172
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07007173 if (volumeSource == a11yVolumeSrc
François Gaffieaaac0fd2018-11-22 17:56:39 +01007174 && (AUDIO_MODE_RINGTONE == mEngine->getPhoneState()) &&
7175 mOutputs.isActive(ringVolumeSrc, 0)) {
7176 auto &ringCurves = getVolumeCurves(AUDIO_STREAM_RING);
jiabin9a3361e2019-10-01 09:38:30 -07007177 const float ringVolumeDb = computeVolume(ringCurves, ringVolumeSrc, index, deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007178 return ringVolumeDb - 4 > volumeDb ? ringVolumeDb - 4 : volumeDb;
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07007179 }
7180
Eric Laurentdcd4ab12018-06-29 17:45:13 -07007181 // in-call: always cap volume by voice volume + some low headroom
François Gaffieaaac0fd2018-11-22 17:56:39 +01007182 if ((volumeSource != callVolumeSrc && (isInCall() ||
7183 mOutputs.isActiveLocally(callVolumeSrc))) &&
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007184 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM, false) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01007185 volumeSource == ringVolumeSrc || volumeSource == musicVolumeSrc ||
7186 volumeSource == alarmVolumeSrc ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007187 volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION, false) ||
7188 volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false) ||
7189 volumeSource == toVolumeSource(AUDIO_STREAM_DTMF, false) ||
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07007190 volumeSource == a11yVolumeSrc)) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007191 auto &voiceCurves = getVolumeCurves(callVolumeSrc);
jiabin9a3361e2019-10-01 09:38:30 -07007192 int voiceVolumeIndex = voiceCurves.getVolumeIndex(deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007193 const float maxVoiceVolDb =
jiabin9a3361e2019-10-01 09:38:30 -07007194 computeVolume(voiceCurves, callVolumeSrc, voiceVolumeIndex, deviceTypes)
Eric Laurent7731b5a2018-04-06 15:47:22 -07007195 + IN_CALL_EARPIECE_HEADROOM_DB;
Abhijith Shastry329ddab2019-04-23 11:53:26 -07007196 // FIXME: Workaround for call screening applications until a proper audio mode is defined
7197 // to support this scenario : Exempt the RING stream from the audio cap if the audio was
7198 // programmatically muted.
7199 // VOICE_CALL stream has minVolumeIndex > 0 : Users cannot set the volume of voice calls to
7200 // 0. We don't want to cap volume when the system has programmatically muted the voice call
7201 // stream. See setVolumeCurveIndex() for more information.
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07007202 bool exemptFromCapping =
7203 ((volumeSource == ringVolumeSrc) || (volumeSource == a11yVolumeSrc))
7204 && (voiceVolumeIndex == 0);
Abhijith Shastry329ddab2019-04-23 11:53:26 -07007205 ALOGV_IF(exemptFromCapping, "%s volume source %d at vol=%f not capped", __func__,
7206 volumeSource, volumeDb);
7207 if ((volumeDb > maxVoiceVolDb) && !exemptFromCapping) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007208 ALOGV("%s volume source %d at vol=%f overriden by volume group %d at vol=%f", __func__,
7209 volumeSource, volumeDb, callVolumeSrc, maxVoiceVolDb);
7210 volumeDb = maxVoiceVolDb;
Jean-Michel Trivi719a9872017-08-05 13:51:35 -07007211 }
7212 }
Eric Laurente552edb2014-03-10 17:42:56 -07007213 // if a headset is connected, apply the following rules to ring tones and notifications
7214 // to avoid sound level bursts in user's ears:
Eric Laurent6af1c1d2016-04-14 11:20:44 -07007215 // - always attenuate notifications volume by 6dB
7216 // - attenuate ring tones volume by 6dB unless music is not playing and
7217 // speaker is part of the select devices
Eric Laurente552edb2014-03-10 17:42:56 -07007218 // - if music is playing, always limit the volume to current music volume,
7219 // with a minimum threshold at -36dB so that notification is always perceived.
jiabin9a3361e2019-10-01 09:38:30 -07007220 if (!Intersection(deviceTypes,
7221 {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP, AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES,
7222 AUDIO_DEVICE_OUT_WIRED_HEADSET, AUDIO_DEVICE_OUT_WIRED_HEADPHONE,
Eric Laurentc42df452020-08-07 10:51:53 -07007223 AUDIO_DEVICE_OUT_USB_HEADSET, AUDIO_DEVICE_OUT_HEARING_AID,
7224 AUDIO_DEVICE_OUT_BLE_HEADSET}).empty() &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01007225 ((volumeSource == alarmVolumeSrc ||
7226 volumeSource == ringVolumeSrc) ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007227 (volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION, false)) ||
7228 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM, false)) ||
7229 ((volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false)) &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01007230 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) &&
7231 curves.canBeMuted()) {
7232
Eric Laurente552edb2014-03-10 17:42:56 -07007233 // when the phone is ringing we must consider that music could have been paused just before
7234 // by the music application and behave as if music was active if the last music track was
7235 // just stopped
Eric Laurent3b73df72014-03-11 09:06:29 -07007236 if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY) ||
Eric Laurente552edb2014-03-10 17:42:56 -07007237 mLimitRingtoneVolume) {
François Gaffie43c73442018-11-08 08:21:55 +01007238 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
jiabin9a3361e2019-10-01 09:38:30 -07007239 DeviceTypeSet musicDevice =
François Gaffiec005e562018-11-06 15:04:49 +01007240 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
7241 nullptr, true /*fromCache*/).types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01007242 auto &musicCurves = getVolumeCurves(AUDIO_STREAM_MUSIC);
jiabin9a3361e2019-10-01 09:38:30 -07007243 float musicVolDb = computeVolume(musicCurves,
7244 musicVolumeSrc,
7245 musicCurves.getVolumeIndex(musicDevice),
7246 musicDevice);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007247 float minVolDb = (musicVolDb > SONIFICATION_HEADSET_VOLUME_MIN_DB) ?
7248 musicVolDb : SONIFICATION_HEADSET_VOLUME_MIN_DB;
7249 if (volumeDb > minVolDb) {
7250 volumeDb = minVolDb;
7251 ALOGV("computeVolume limiting volume to %f musicVol %f", minVolDb, musicVolDb);
Eric Laurente552edb2014-03-10 17:42:56 -07007252 }
Eric Laurent7b6385c2021-05-12 17:55:36 +02007253 if (Volume::getDeviceForVolume(deviceTypes) != AUDIO_DEVICE_OUT_SPEAKER
7254 && !Intersection(deviceTypes, {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP,
7255 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES}).empty()) {
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07007256 // on A2DP, also ensure notification volume is not too low compared to media when
7257 // intended to be played
François Gaffie43c73442018-11-08 08:21:55 +01007258 if ((volumeDb > -96.0f) &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01007259 (musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB > volumeDb)) {
jiabin9a3361e2019-10-01 09:38:30 -07007260 ALOGV("%s increasing volume for volume source=%d device=%s from %f to %f",
7261 __func__, volumeSource, dumpDeviceTypes(deviceTypes).c_str(), volumeDb,
François Gaffieaaac0fd2018-11-22 17:56:39 +01007262 musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB);
7263 volumeDb = musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB;
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07007264 }
7265 }
jiabin9a3361e2019-10-01 09:38:30 -07007266 } else if ((Volume::getDeviceForVolume(deviceTypes) != AUDIO_DEVICE_OUT_SPEAKER) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01007267 (!(volumeSource == alarmVolumeSrc || volumeSource == ringVolumeSrc))) {
François Gaffie43c73442018-11-08 08:21:55 +01007268 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07007269 }
7270 }
7271
François Gaffie43c73442018-11-08 08:21:55 +01007272 return volumeDb;
Eric Laurente552edb2014-03-10 17:42:56 -07007273}
7274
Eric Laurent3839bc02018-07-10 18:33:34 -07007275int AudioPolicyManager::rescaleVolumeIndex(int srcIndex,
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01007276 VolumeSource fromVolumeSource,
7277 VolumeSource toVolumeSource)
Eric Laurent3839bc02018-07-10 18:33:34 -07007278{
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01007279 if (fromVolumeSource == toVolumeSource) {
Eric Laurent3839bc02018-07-10 18:33:34 -07007280 return srcIndex;
7281 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01007282 auto &srcCurves = getVolumeCurves(fromVolumeSource);
7283 auto &dstCurves = getVolumeCurves(toVolumeSource);
Eric Laurentf5aa58d2019-02-22 18:20:11 -08007284 float minSrc = (float)srcCurves.getVolumeIndexMin();
7285 float maxSrc = (float)srcCurves.getVolumeIndexMax();
7286 float minDst = (float)dstCurves.getVolumeIndexMin();
7287 float maxDst = (float)dstCurves.getVolumeIndexMax();
Eric Laurent3839bc02018-07-10 18:33:34 -07007288
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08007289 // preserve mute request or correct range
7290 if (srcIndex < minSrc) {
7291 if (srcIndex == 0) {
7292 return 0;
7293 }
7294 srcIndex = minSrc;
7295 } else if (srcIndex > maxSrc) {
7296 srcIndex = maxSrc;
7297 }
Eric Laurent3839bc02018-07-10 18:33:34 -07007298 return (int)(minDst + ((srcIndex - minSrc) * (maxDst - minDst)) / (maxSrc - minSrc));
7299}
7300
François Gaffieaaac0fd2018-11-22 17:56:39 +01007301status_t AudioPolicyManager::checkAndSetVolume(IVolumeCurves &curves,
7302 VolumeSource volumeSource,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08007303 int index,
7304 const sp<AudioOutputDescriptor>& outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07007305 DeviceTypeSet deviceTypes,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08007306 int delayMs,
7307 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07007308{
François Gaffieaaac0fd2018-11-22 17:56:39 +01007309 // do not change actual attributes volume if the attributes is muted
7310 if (outputDesc->isMuted(volumeSource)) {
7311 ALOGVV("%s: volume source %d muted count %d active=%d", __func__, volumeSource,
7312 outputDesc->getMuteCount(volumeSource), outputDesc->isActive(volumeSource));
Eric Laurente552edb2014-03-10 17:42:56 -07007313 return NO_ERROR;
7314 }
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007315 VolumeSource callVolSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL, false);
7316 VolumeSource btScoVolSrc = toVolumeSource(AUDIO_STREAM_BLUETOOTH_SCO, false);
7317 bool isVoiceVolSrc = (volumeSource != VOLUME_SOURCE_NONE) && (callVolSrc == volumeSource);
7318 bool isBtScoVolSrc = (volumeSource != VOLUME_SOURCE_NONE) && (btScoVolSrc == volumeSource);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007319
Eric Laurent2517af32020-11-25 15:31:27 +01007320 bool isScoRequested = isScoRequestedForComm();
Eric Laurent1a8b45f2022-04-13 16:01:47 +02007321 bool isHAUsed = isHearingAidUsedForComm();
7322
Eric Laurente552edb2014-03-10 17:42:56 -07007323 // do not change in call volume if bluetooth is connected and vice versa
François Gaffieaaac0fd2018-11-22 17:56:39 +01007324 // if sco and call follow same curves, bypass forceUseForComm
7325 if ((callVolSrc != btScoVolSrc) &&
Eric Laurent2517af32020-11-25 15:31:27 +01007326 ((isVoiceVolSrc && isScoRequested) ||
Eric Laurent1a8b45f2022-04-13 16:01:47 +02007327 (isBtScoVolSrc && !(isScoRequested || isHAUsed)))) {
Eric Laurent2517af32020-11-25 15:31:27 +01007328 ALOGV("%s cannot set volume group %d volume when is%srequested for comm", __func__,
Eric Laurent1a8b45f2022-04-13 16:01:47 +02007329 volumeSource, isScoRequested ? " " : " not ");
Eric Laurent571ef962020-07-24 11:43:48 -07007330 // Do not return an error here as AudioService will always set both voice call
7331 // and bluetooth SCO volumes due to stream aliasing.
7332 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07007333 }
jiabin9a3361e2019-10-01 09:38:30 -07007334 if (deviceTypes.empty()) {
7335 deviceTypes = outputDesc->devices().types();
Eric Laurentc75307b2015-03-17 15:29:32 -07007336 }
Eric Laurent275e8e92014-11-30 15:14:47 -08007337
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00007338 if (curves.getVolumeIndexMin() < 0 || curves.getVolumeIndexMax() < 0) {
7339 ALOGE("invalid volume index range");
7340 return BAD_VALUE;
7341 }
7342
jiabin9a3361e2019-10-01 09:38:30 -07007343 float volumeDb = computeVolume(curves, volumeSource, index, deviceTypes);
7344 if (outputDesc->isFixedVolume(deviceTypes) ||
Eric Laurent9698a4c2020-10-12 17:10:23 -07007345 // Force VoIP volume to max for bluetooth SCO device except if muted
7346 (index != 0 && (isVoiceVolSrc || isBtScoVolSrc) &&
jiabin9a3361e2019-10-01 09:38:30 -07007347 isSingleDeviceType(deviceTypes, audio_is_bluetooth_out_sco_device))) {
Eric Laurentffbc80f2015-03-18 18:30:19 -07007348 volumeDb = 0.0f;
Eric Laurent275e8e92014-11-30 15:14:47 -08007349 }
Francois Gaffie593634d2021-06-22 13:31:31 +02007350 const bool muted = (index == 0) && (volumeDb != 0.0f);
jiabin9a3361e2019-10-01 09:38:30 -07007351 outputDesc->setVolume(
Francois Gaffie593634d2021-06-22 13:31:31 +02007352 volumeDb, muted, volumeSource, curves.getStreamTypes(), deviceTypes, delayMs, force);
Eric Laurentc75307b2015-03-17 15:29:32 -07007353
Eric Laurente8f2c0f2021-08-17 11:17:19 +02007354 if (outputDesc == mPrimaryOutput && (isVoiceVolSrc || isBtScoVolSrc)) {
Eric Laurente552edb2014-03-10 17:42:56 -07007355 float voiceVolume;
Eric Laurentfad001d2019-06-11 19:17:57 -07007356 // 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 +01007357 if (isVoiceVolSrc) {
7358 voiceVolume = (float)index/(float)curves.getVolumeIndexMax();
Eric Laurente552edb2014-03-10 17:42:56 -07007359 } else {
Eric Laurentfad001d2019-06-11 19:17:57 -07007360 voiceVolume = index == 0 ? 0.0 : 1.0;
Eric Laurente552edb2014-03-10 17:42:56 -07007361 }
Eric Laurent18fba842016-03-31 14:41:26 -07007362 if (voiceVolume != mLastVoiceVolume) {
Eric Laurente552edb2014-03-10 17:42:56 -07007363 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
7364 mLastVoiceVolume = voiceVolume;
7365 }
7366 }
Eric Laurente552edb2014-03-10 17:42:56 -07007367 return NO_ERROR;
7368}
7369
Eric Laurentc75307b2015-03-17 15:29:32 -07007370void AudioPolicyManager::applyStreamVolumes(const sp<AudioOutputDescriptor>& outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07007371 const DeviceTypeSet& deviceTypes,
7372 int delayMs,
7373 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07007374{
jiabincd510522020-01-22 09:40:55 -08007375 ALOGVV("applyStreamVolumes() for device %s", dumpDeviceTypes(deviceTypes).c_str());
François Gaffieaaac0fd2018-11-22 17:56:39 +01007376 for (const auto &volumeGroup : mEngine->getVolumeGroups()) {
7377 auto &curves = getVolumeCurves(toVolumeSource(volumeGroup));
7378 checkAndSetVolume(curves, toVolumeSource(volumeGroup),
jiabin9a3361e2019-10-01 09:38:30 -07007379 curves.getVolumeIndex(deviceTypes),
7380 outputDesc, deviceTypes, delayMs, force);
Eric Laurente552edb2014-03-10 17:42:56 -07007381 }
7382}
7383
François Gaffiec005e562018-11-06 15:04:49 +01007384void AudioPolicyManager::setStrategyMute(product_strategy_t strategy,
7385 bool on,
7386 const sp<AudioOutputDescriptor>& outputDesc,
7387 int delayMs,
jiabin9a3361e2019-10-01 09:38:30 -07007388 DeviceTypeSet deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07007389{
François Gaffieaaac0fd2018-11-22 17:56:39 +01007390 std::vector<VolumeSource> sourcesToMute;
7391 for (auto attributes: mEngine->getAllAttributesForProductStrategy(strategy)) {
7392 ALOGVV("%s() attributes %s, mute %d, output ID %d", __func__,
7393 toString(attributes).c_str(), on, outputDesc->getId());
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007394 VolumeSource source = toVolumeSource(attributes, false);
7395 if ((source != VOLUME_SOURCE_NONE) &&
7396 (std::find(begin(sourcesToMute), end(sourcesToMute), source)
7397 == end(sourcesToMute))) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007398 sourcesToMute.push_back(source);
7399 }
Eric Laurente552edb2014-03-10 17:42:56 -07007400 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01007401 for (auto source : sourcesToMute) {
jiabin9a3361e2019-10-01 09:38:30 -07007402 setVolumeSourceMute(source, on, outputDesc, delayMs, deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007403 }
7404
Eric Laurente552edb2014-03-10 17:42:56 -07007405}
7406
François Gaffieaaac0fd2018-11-22 17:56:39 +01007407void AudioPolicyManager::setVolumeSourceMute(VolumeSource volumeSource,
7408 bool on,
7409 const sp<AudioOutputDescriptor>& outputDesc,
7410 int delayMs,
jiabin9a3361e2019-10-01 09:38:30 -07007411 DeviceTypeSet deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07007412{
jiabin9a3361e2019-10-01 09:38:30 -07007413 if (deviceTypes.empty()) {
7414 deviceTypes = outputDesc->devices().types();
Eric Laurente552edb2014-03-10 17:42:56 -07007415 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01007416 auto &curves = getVolumeCurves(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07007417 if (on) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007418 if (!outputDesc->isMuted(volumeSource)) {
Eric Laurentf5aa58d2019-02-22 18:20:11 -08007419 if (curves.canBeMuted() &&
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007420 (volumeSource != toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01007421 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) ==
7422 AUDIO_POLICY_FORCE_NONE))) {
jiabin9a3361e2019-10-01 09:38:30 -07007423 checkAndSetVolume(curves, volumeSource, 0, outputDesc, deviceTypes, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07007424 }
7425 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01007426 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not
7427 // ignored
7428 outputDesc->incMuteCount(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07007429 } else {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007430 if (!outputDesc->isMuted(volumeSource)) {
7431 ALOGV("%s unmuting non muted attributes!", __func__);
Eric Laurente552edb2014-03-10 17:42:56 -07007432 return;
7433 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01007434 if (outputDesc->decMuteCount(volumeSource) == 0) {
7435 checkAndSetVolume(curves, volumeSource,
jiabin9a3361e2019-10-01 09:38:30 -07007436 curves.getVolumeIndex(deviceTypes),
Eric Laurentc75307b2015-03-17 15:29:32 -07007437 outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07007438 deviceTypes,
Eric Laurente552edb2014-03-10 17:42:56 -07007439 delayMs);
7440 }
7441 }
7442}
7443
François Gaffie53615e22015-03-19 09:24:12 +01007444bool AudioPolicyManager::isValidAttributes(const audio_attributes_t *paa)
7445{
François Gaffiec005e562018-11-06 15:04:49 +01007446 // has flags that map to a stream type?
Eric Laurente83b55d2014-11-14 10:06:21 -08007447 if ((paa->flags & (AUDIO_FLAG_AUDIBILITY_ENFORCED | AUDIO_FLAG_SCO | AUDIO_FLAG_BEACON)) != 0) {
7448 return true;
7449 }
7450
7451 // has known usage?
7452 switch (paa->usage) {
7453 case AUDIO_USAGE_UNKNOWN:
7454 case AUDIO_USAGE_MEDIA:
7455 case AUDIO_USAGE_VOICE_COMMUNICATION:
7456 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
7457 case AUDIO_USAGE_ALARM:
7458 case AUDIO_USAGE_NOTIFICATION:
7459 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
7460 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
7461 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
7462 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
7463 case AUDIO_USAGE_NOTIFICATION_EVENT:
7464 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
7465 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
7466 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
7467 case AUDIO_USAGE_GAME:
Eric Laurent275e8e92014-11-30 15:14:47 -08007468 case AUDIO_USAGE_VIRTUAL_SOURCE:
Jean-Michel Trivi36867762016-12-29 12:03:28 -08007469 case AUDIO_USAGE_ASSISTANT:
Eric Laurent21777f82019-12-06 18:12:06 -08007470 case AUDIO_USAGE_CALL_ASSISTANT:
Hayden Gomes524159d2019-12-23 14:41:47 -08007471 case AUDIO_USAGE_EMERGENCY:
7472 case AUDIO_USAGE_SAFETY:
7473 case AUDIO_USAGE_VEHICLE_STATUS:
7474 case AUDIO_USAGE_ANNOUNCEMENT:
Eric Laurente83b55d2014-11-14 10:06:21 -08007475 break;
7476 default:
7477 return false;
7478 }
7479 return true;
7480}
7481
François Gaffie2110e042015-03-24 08:41:51 +01007482audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
7483{
7484 return mEngine->getForceUse(usage);
7485}
7486
Eric Laurent96d1dda2022-03-14 17:14:19 +01007487bool AudioPolicyManager::isInCall() const {
François Gaffie2110e042015-03-24 08:41:51 +01007488 return isStateInCall(mEngine->getPhoneState());
7489}
7490
Eric Laurent96d1dda2022-03-14 17:14:19 +01007491bool AudioPolicyManager::isStateInCall(int state) const {
François Gaffie2110e042015-03-24 08:41:51 +01007492 return is_state_in_call(state);
7493}
7494
Eric Laurent74b71512019-11-06 17:21:57 -08007495bool AudioPolicyManager::isCallAudioAccessible()
7496{
7497 audio_mode_t mode = mEngine->getPhoneState();
7498 return (mode == AUDIO_MODE_IN_CALL)
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01007499 || (mode == AUDIO_MODE_CALL_SCREEN)
7500 || (mode == AUDIO_MODE_CALL_REDIRECT);
Eric Laurent74b71512019-11-06 17:21:57 -08007501}
7502
Eric Laurentd60560a2015-04-10 11:31:20 -07007503void AudioPolicyManager::cleanUpForDevice(const sp<DeviceDescriptor>& deviceDesc)
7504{
7505 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07007506 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02007507 if (sourceDesc->isConnected() && (sourceDesc->srcDevice()->equals(deviceDesc) ||
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02007508 sourceDesc->sinkDevice()->equals(deviceDesc))
7509 && !isCallRxAudioSource(sourceDesc)) {
Francois Gaffiea0e5c992020-09-29 16:05:07 +02007510 disconnectAudioSource(sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07007511 }
7512 }
7513
7514 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
7515 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
7516 bool release = false;
7517 for (size_t j = 0; j < patchDesc->mPatch.num_sources && !release; j++) {
7518 const struct audio_port_config *source = &patchDesc->mPatch.sources[j];
7519 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
7520 source->ext.device.type == deviceDesc->type()) {
7521 release = true;
7522 }
7523 }
Francois Gaffiea0e5c992020-09-29 16:05:07 +02007524 const char *address = deviceDesc->address().c_str();
Eric Laurentd60560a2015-04-10 11:31:20 -07007525 for (size_t j = 0; j < patchDesc->mPatch.num_sinks && !release; j++) {
7526 const struct audio_port_config *sink = &patchDesc->mPatch.sinks[j];
7527 if (sink->type == AUDIO_PORT_TYPE_DEVICE &&
Francois Gaffiea0e5c992020-09-29 16:05:07 +02007528 sink->ext.device.type == deviceDesc->type() &&
7529 (strnlen(address, AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0
7530 || strncmp(sink->ext.device.address, address,
7531 AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0)) {
Eric Laurentd60560a2015-04-10 11:31:20 -07007532 release = true;
7533 }
7534 }
7535 if (release) {
François Gaffieafd4cea2019-11-18 15:50:22 +01007536 ALOGV("%s releasing patch %u", __FUNCTION__, patchDesc->getHandle());
7537 releaseAudioPatch(patchDesc->getHandle(), patchDesc->getUid());
Eric Laurentd60560a2015-04-10 11:31:20 -07007538 }
7539 }
Francois Gaffie716e1432019-01-14 16:58:59 +01007540
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01007541 mInputs.clearSessionRoutesForDevice(deviceDesc);
7542
Francois Gaffie716e1432019-01-14 16:58:59 +01007543 mHwModules.cleanUpForDevice(deviceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07007544}
7545
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007546void AudioPolicyManager::modifySurroundFormats(
7547 const sp<DeviceDescriptor>& devDesc, FormatVector *formatsPtr) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007548 std::unordered_set<audio_format_t> enforcedSurround(
7549 devDesc->encodedFormats().begin(), devDesc->encodedFormats().end());
Mikhail Naganov100f0122018-11-29 11:22:16 -08007550 std::unordered_set<audio_format_t> allSurround; // A flat set of all known surround formats
7551 for (const auto& pair : mConfig.getSurroundFormats()) {
7552 allSurround.insert(pair.first);
7553 for (const auto& subformat : pair.second) allSurround.insert(subformat);
7554 }
Phil Burk09bc4612016-02-24 15:58:15 -08007555
7556 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
7557 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Phil Burk0709b0a2016-03-31 12:54:57 -07007558 ALOGD("%s: forced use = %d", __FUNCTION__, forceUse);
Mikhail Naganov100f0122018-11-29 11:22:16 -08007559 // This is the resulting set of formats depending on the surround mode:
7560 // 'all surround' = allSurround
7561 // 'enforced surround' = enforcedSurround [may include IEC69137 which isn't raw surround fmt]
7562 // 'non-surround' = not in 'all surround' and not in 'enforced surround'
7563 // 'manual surround' = mManualSurroundFormats
7564 // AUTO: formats v 'enforced surround'
7565 // ALWAYS: formats v 'all surround' v 'enforced surround'
7566 // NEVER: formats ^ 'non-surround'
7567 // MANUAL: formats ^ ('non-surround' v 'manual surround' v (IEC69137 ^ 'enforced surround'))
Phil Burk09bc4612016-02-24 15:58:15 -08007568
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007569 std::unordered_set<audio_format_t> formatSet;
7570 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL
7571 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08007572 // formatSet is (formats ^ 'non-surround')
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007573 for (auto formatIter = formatsPtr->begin(); formatIter != formatsPtr->end(); ++formatIter) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08007574 if (allSurround.count(*formatIter) == 0 && enforcedSurround.count(*formatIter) == 0) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007575 formatSet.insert(*formatIter);
7576 }
7577 }
7578 } else {
7579 formatSet.insert(formatsPtr->begin(), formatsPtr->end());
7580 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08007581 formatsPtr->clear(); // Re-filled from the formatSet at the end.
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007582
jiabin81772902018-04-02 17:52:27 -07007583 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08007584 formatSet.insert(mManualSurroundFormats.begin(), mManualSurroundFormats.end());
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007585 // Enable IEC61937 when in MANUAL mode if it's enforced for this device.
7586 if (enforcedSurround.count(AUDIO_FORMAT_IEC61937) != 0) {
7587 formatSet.insert(AUDIO_FORMAT_IEC61937);
Phil Burk09bc4612016-02-24 15:58:15 -08007588 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08007589 } else if (forceUse != AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) { // AUTO or ALWAYS
7590 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS) {
7591 formatSet.insert(allSurround.begin(), allSurround.end());
Phil Burk07ac1142016-03-25 13:39:29 -07007592 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08007593 formatSet.insert(enforcedSurround.begin(), enforcedSurround.end());
Phil Burk09bc4612016-02-24 15:58:15 -08007594 }
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007595 for (const auto& format : formatSet) {
jiabin06e4bab2019-07-29 10:13:34 -07007596 formatsPtr->push_back(format);
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007597 }
Phil Burk0709b0a2016-03-31 12:54:57 -07007598}
7599
jiabin06e4bab2019-07-29 10:13:34 -07007600void AudioPolicyManager::modifySurroundChannelMasks(ChannelMaskSet *channelMasksPtr) {
7601 ChannelMaskSet &channelMasks = *channelMasksPtr;
Phil Burk0709b0a2016-03-31 12:54:57 -07007602 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
7603 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
7604
7605 // If NEVER, then remove support for channelMasks > stereo.
7606 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
jiabin06e4bab2019-07-29 10:13:34 -07007607 for (auto it = channelMasks.begin(); it != channelMasks.end();) {
7608 audio_channel_mask_t channelMask = *it;
Phil Burk0709b0a2016-03-31 12:54:57 -07007609 if (channelMask & ~AUDIO_CHANNEL_OUT_STEREO) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01007610 ALOGV("%s: force NEVER, so remove channelMask 0x%08x", __FUNCTION__, channelMask);
jiabin06e4bab2019-07-29 10:13:34 -07007611 it = channelMasks.erase(it);
Phil Burk0709b0a2016-03-31 12:54:57 -07007612 } else {
jiabin06e4bab2019-07-29 10:13:34 -07007613 ++it;
Phil Burk0709b0a2016-03-31 12:54:57 -07007614 }
7615 }
jiabin81772902018-04-02 17:52:27 -07007616 // If ALWAYS or MANUAL, then make sure we at least support 5.1
7617 } else if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS
7618 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Phil Burk0709b0a2016-03-31 12:54:57 -07007619 bool supports5dot1 = false;
7620 // Are there any channel masks that can be considered "surround"?
Mikhail Naganovcf84e592017-12-07 11:25:11 -08007621 for (audio_channel_mask_t channelMask : channelMasks) {
Phil Burk0709b0a2016-03-31 12:54:57 -07007622 if ((channelMask & AUDIO_CHANNEL_OUT_5POINT1) == AUDIO_CHANNEL_OUT_5POINT1) {
7623 supports5dot1 = true;
7624 break;
7625 }
7626 }
7627 // If not then add 5.1 support.
7628 if (!supports5dot1) {
jiabin06e4bab2019-07-29 10:13:34 -07007629 channelMasks.insert(AUDIO_CHANNEL_OUT_5POINT1);
Eric Laurentfecbceb2021-02-09 14:46:43 +01007630 ALOGV("%s: force MANUAL or ALWAYS, so adding channelMask for 5.1 surround", __func__);
Phil Burk0709b0a2016-03-31 12:54:57 -07007631 }
Phil Burk09bc4612016-02-24 15:58:15 -08007632 }
7633}
7634
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007635void AudioPolicyManager::updateAudioProfiles(const sp<DeviceDescriptor>& devDesc,
Phil Burk00eeb322016-03-31 12:41:00 -07007636 audio_io_handle_t ioHandle,
François Gaffie112b0af2015-11-19 16:13:25 +01007637 AudioProfileVector &profiles)
7638{
7639 String8 reply;
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007640 audio_devices_t device = devDesc->type();
Phil Burk0709b0a2016-03-31 12:54:57 -07007641
François Gaffie112b0af2015-11-19 16:13:25 +01007642 // Format MUST be checked first to update the list of AudioProfile
7643 if (profiles.hasDynamicFormat()) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07007644 reply = mpClientInterface->getParameters(
7645 ioHandle, String8(AudioParameter::keyStreamSupportedFormats));
jiabin81772902018-04-02 17:52:27 -07007646 ALOGV("%s: supported formats %d, %s", __FUNCTION__, ioHandle, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08007647 AudioParameter repliedParameters(reply);
7648 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07007649 String8(AudioParameter::keyStreamSupportedFormats), reply) != NO_ERROR) {
François Gaffie112b0af2015-11-19 16:13:25 +01007650 ALOGE("%s: failed to retrieve format, bailing out", __FUNCTION__);
7651 return;
7652 }
Phil Burk09bc4612016-02-24 15:58:15 -08007653 FormatVector formats = formatsFromString(reply.string());
Kriti Dangef6be8f2020-11-05 11:58:19 +01007654 mReportedFormatsMap[devDesc] = formats;
Mikhail Naganov100f0122018-11-29 11:22:16 -08007655 if (device == AUDIO_DEVICE_OUT_HDMI
7656 || isDeviceOfModule(devDesc, AUDIO_HARDWARE_MODULE_ID_MSD)) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007657 modifySurroundFormats(devDesc, &formats);
Phil Burk00eeb322016-03-31 12:41:00 -07007658 }
jiabin3e277cc2019-09-10 14:27:34 -07007659 addProfilesForFormats(profiles, formats);
François Gaffie112b0af2015-11-19 16:13:25 +01007660 }
François Gaffie112b0af2015-11-19 16:13:25 +01007661
Mikhail Naganovcf84e592017-12-07 11:25:11 -08007662 for (audio_format_t format : profiles.getSupportedFormats()) {
jiabin06e4bab2019-07-29 10:13:34 -07007663 ChannelMaskSet channelMasks;
7664 SampleRateSet samplingRates;
François Gaffie112b0af2015-11-19 16:13:25 +01007665 AudioParameter requestedParameters;
Mikhail Naganov388360c2016-10-17 17:09:41 -07007666 requestedParameters.addInt(String8(AudioParameter::keyFormat), format);
François Gaffie112b0af2015-11-19 16:13:25 +01007667
7668 if (profiles.hasDynamicRateFor(format)) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07007669 reply = mpClientInterface->getParameters(
7670 ioHandle,
7671 requestedParameters.toString() + ";" +
7672 AudioParameter::keyStreamSupportedSamplingRates);
François Gaffie112b0af2015-11-19 16:13:25 +01007673 ALOGV("%s: supported sampling rates %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08007674 AudioParameter repliedParameters(reply);
7675 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07007676 String8(AudioParameter::keyStreamSupportedSamplingRates), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08007677 samplingRates = samplingRatesFromString(reply.string());
François Gaffie112b0af2015-11-19 16:13:25 +01007678 }
7679 }
7680 if (profiles.hasDynamicChannelsFor(format)) {
7681 reply = mpClientInterface->getParameters(ioHandle,
7682 requestedParameters.toString() + ";" +
Mikhail Naganov388360c2016-10-17 17:09:41 -07007683 AudioParameter::keyStreamSupportedChannels);
François Gaffie112b0af2015-11-19 16:13:25 +01007684 ALOGV("%s: supported channel masks %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08007685 AudioParameter repliedParameters(reply);
7686 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07007687 String8(AudioParameter::keyStreamSupportedChannels), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08007688 channelMasks = channelMasksFromString(reply.string());
Mikhail Naganov100f0122018-11-29 11:22:16 -08007689 if (device == AUDIO_DEVICE_OUT_HDMI
7690 || isDeviceOfModule(devDesc, AUDIO_HARDWARE_MODULE_ID_MSD)) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007691 modifySurroundChannelMasks(&channelMasks);
Phil Burk0709b0a2016-03-31 12:54:57 -07007692 }
François Gaffie112b0af2015-11-19 16:13:25 +01007693 }
7694 }
jiabin3e277cc2019-09-10 14:27:34 -07007695 addDynamicAudioProfileAndSort(
7696 profiles, new AudioProfile(format, channelMasks, samplingRates));
François Gaffie112b0af2015-11-19 16:13:25 +01007697 }
7698}
Eric Laurentd60560a2015-04-10 11:31:20 -07007699
Mikhail Naganovdc769682018-05-04 15:34:08 -07007700status_t AudioPolicyManager::installPatch(const char *caller,
7701 audio_patch_handle_t *patchHandle,
7702 AudioIODescriptorInterface *ioDescriptor,
7703 const struct audio_patch *patch,
7704 int delayMs)
7705{
7706 ssize_t index = mAudioPatches.indexOfKey(
7707 patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE ?
7708 *patchHandle : ioDescriptor->getPatchHandle());
7709 sp<AudioPatch> patchDesc;
7710 status_t status = installPatch(
7711 caller, index, patchHandle, patch, delayMs, mUidCached, &patchDesc);
7712 if (status == NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01007713 ioDescriptor->setPatchHandle(patchDesc->getHandle());
Mikhail Naganovdc769682018-05-04 15:34:08 -07007714 }
7715 return status;
7716}
7717
7718status_t AudioPolicyManager::installPatch(const char *caller,
7719 ssize_t index,
7720 audio_patch_handle_t *patchHandle,
7721 const struct audio_patch *patch,
7722 int delayMs,
7723 uid_t uid,
7724 sp<AudioPatch> *patchDescPtr)
7725{
7726 sp<AudioPatch> patchDesc;
7727 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
7728 if (index >= 0) {
7729 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007730 afPatchHandle = patchDesc->getAfHandle();
Mikhail Naganovdc769682018-05-04 15:34:08 -07007731 }
7732
7733 status_t status = mpClientInterface->createAudioPatch(patch, &afPatchHandle, delayMs);
7734 ALOGV("%s() AF::createAudioPatch returned %d patchHandle %d num_sources %d num_sinks %d",
7735 caller, status, afPatchHandle, patch->num_sources, patch->num_sinks);
7736 if (status == NO_ERROR) {
7737 if (index < 0) {
7738 patchDesc = new AudioPatch(patch, uid);
François Gaffieafd4cea2019-11-18 15:50:22 +01007739 addAudioPatch(patchDesc->getHandle(), patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07007740 } else {
7741 patchDesc->mPatch = *patch;
7742 }
François Gaffieafd4cea2019-11-18 15:50:22 +01007743 patchDesc->setAfHandle(afPatchHandle);
Mikhail Naganovdc769682018-05-04 15:34:08 -07007744 if (patchHandle) {
François Gaffieafd4cea2019-11-18 15:50:22 +01007745 *patchHandle = patchDesc->getHandle();
Mikhail Naganovdc769682018-05-04 15:34:08 -07007746 }
7747 nextAudioPortGeneration();
7748 mpClientInterface->onAudioPatchListUpdate();
7749 }
7750 if (patchDescPtr) *patchDescPtr = patchDesc;
7751 return status;
7752}
7753
jiabinbce0c1d2020-10-05 11:20:18 -07007754bool AudioPolicyManager::areAllActiveTracksRerouted(const sp<SwAudioOutputDescriptor>& output)
7755{
7756 const TrackClientVector activeClients = output->getActiveClients();
7757 if (activeClients.empty()) {
7758 return true;
7759 }
7760 ssize_t index = mAudioPatches.indexOfKey(output->getPatchHandle());
7761 if (index < 0) {
7762 ALOGE("%s, no audio patch found while there are active clients on output %d",
7763 __func__, output->getId());
7764 return false;
7765 }
7766 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
7767 DeviceVector routedDevices;
7768 for (int i = 0; i < patchDesc->mPatch.num_sinks; ++i) {
7769 sp<DeviceDescriptor> device = mAvailableOutputDevices.getDeviceFromId(
7770 patchDesc->mPatch.sinks[i].id);
7771 if (device == nullptr) {
7772 ALOGE("%s, no audio device found with id(%d)",
7773 __func__, patchDesc->mPatch.sinks[i].id);
7774 return false;
7775 }
7776 routedDevices.add(device);
7777 }
7778 for (const auto& client : activeClients) {
jiabin49256852022-03-09 11:21:35 -08007779 if (client->isInvalid()) {
7780 // No need to take care about invalidated clients.
7781 continue;
7782 }
jiabinbce0c1d2020-10-05 11:20:18 -07007783 sp<DeviceDescriptor> preferredDevice =
7784 mAvailableOutputDevices.getDeviceFromId(client->preferredDeviceId());
7785 if (mEngine->getOutputDevicesForAttributes(
7786 client->attributes(), preferredDevice, false) == routedDevices) {
7787 return false;
7788 }
7789 }
7790 return true;
7791}
7792
7793sp<SwAudioOutputDescriptor> AudioPolicyManager::openOutputWithProfileAndDevice(
Eric Laurentb4f42a92022-01-17 17:37:31 +01007794 const sp<IOProfile>& profile, const DeviceVector& devices,
7795 const audio_config_base_t *mixerConfig)
jiabinbce0c1d2020-10-05 11:20:18 -07007796{
7797 for (const auto& device : devices) {
7798 // TODO: This should be checking if the profile supports the device combo.
7799 if (!profile->supportsDevice(device)) {
7800 return nullptr;
7801 }
7802 }
7803 sp<SwAudioOutputDescriptor> desc = new SwAudioOutputDescriptor(profile, mpClientInterface);
7804 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentb4f42a92022-01-17 17:37:31 +01007805 status_t status = desc->open(nullptr /* halConfig */, mixerConfig, devices,
jiabinbce0c1d2020-10-05 11:20:18 -07007806 AUDIO_STREAM_DEFAULT, AUDIO_OUTPUT_FLAG_NONE, &output);
7807 if (status != NO_ERROR) {
7808 return nullptr;
7809 }
7810
7811 // Here is where the out_set_parameters() for card & device gets called
7812 sp<DeviceDescriptor> device = devices.getDeviceForOpening();
7813 const audio_devices_t deviceType = device->type();
7814 const String8 &address = String8(device->address().c_str());
7815 if (!address.isEmpty()) {
7816 char *param = audio_device_address_to_parameter(deviceType, address.c_str());
7817 mpClientInterface->setParameters(output, String8(param));
7818 free(param);
7819 }
7820 updateAudioProfiles(device, output, profile->getAudioProfiles());
7821 if (!profile->hasValidAudioProfile()) {
7822 ALOGW("%s() missing param", __func__);
7823 desc->close();
7824 return nullptr;
7825 } else if (profile->hasDynamicAudioProfile()) {
7826 desc->close();
7827 output = AUDIO_IO_HANDLE_NONE;
7828 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
7829 profile->pickAudioProfile(
7830 config.sample_rate, config.channel_mask, config.format);
7831 config.offload_info.sample_rate = config.sample_rate;
7832 config.offload_info.channel_mask = config.channel_mask;
7833 config.offload_info.format = config.format;
7834
Eric Laurentb4f42a92022-01-17 17:37:31 +01007835 status = desc->open(&config, mixerConfig, devices,
jiabinbce0c1d2020-10-05 11:20:18 -07007836 AUDIO_STREAM_DEFAULT, AUDIO_OUTPUT_FLAG_NONE, &output);
7837 if (status != NO_ERROR) {
7838 return nullptr;
7839 }
7840 }
7841
7842 addOutput(output, desc);
Eric Laurentb4f42a92022-01-17 17:37:31 +01007843
baek.kim -61c20122022-07-27 10:05:32 +00007844 sp<DeviceDescriptor> speaker = mAvailableOutputDevices.getDevice(
7845 AUDIO_DEVICE_OUT_SPEAKER, String8(""), AUDIO_FORMAT_DEFAULT);
7846
jiabinbce0c1d2020-10-05 11:20:18 -07007847 if (audio_is_remote_submix_device(deviceType) && address != "0") {
7848 sp<AudioPolicyMix> policyMix;
7849 if (mPolicyMixes.getAudioPolicyMix(deviceType, address, policyMix) == NO_ERROR) {
7850 policyMix->setOutput(desc);
7851 desc->mPolicyMix = policyMix;
7852 } else {
7853 ALOGW("checkOutputsForDevice() cannot find policy for address %s",
7854 address.string());
7855 }
7856
baek.kim -61c20122022-07-27 10:05:32 +00007857 } else if (hasPrimaryOutput() && speaker != nullptr
7858 && mPrimaryOutput->supportsDevice(speaker) && !desc->supportsDevice(speaker)
Eric Laurentb4f42a92022-01-17 17:37:31 +01007859 && ((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0)) {
7860 // no duplicated output for:
7861 // - direct outputs
7862 // - outputs used by dynamic policy mixes
baek.kim -61c20122022-07-27 10:05:32 +00007863 // - outputs that supports SPEAKER while the primary output does not.
jiabinbce0c1d2020-10-05 11:20:18 -07007864 audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE;
7865
7866 //TODO: configure audio effect output stage here
7867
7868 // open a duplicating output thread for the new output and the primary output
7869 sp<SwAudioOutputDescriptor> dupOutputDesc =
7870 new SwAudioOutputDescriptor(nullptr, mpClientInterface);
7871 status = dupOutputDesc->openDuplicating(mPrimaryOutput, desc, &duplicatedOutput);
7872 if (status == NO_ERROR) {
7873 // add duplicated output descriptor
7874 addOutput(duplicatedOutput, dupOutputDesc);
7875 } else {
7876 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
7877 mPrimaryOutput->mIoHandle, output);
7878 desc->close();
7879 removeOutput(output);
7880 nextAudioPortGeneration();
7881 return nullptr;
7882 }
7883 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02007884 if (mPrimaryOutput == nullptr && profile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
7885 ALOGV("%s(): re-assigning mPrimaryOutput", __func__);
7886 mPrimaryOutput = desc;
7887 }
jiabinbce0c1d2020-10-05 11:20:18 -07007888 return desc;
7889}
7890
Mikhail Naganov1b2a7942017-12-08 10:18:09 -08007891} // namespace android