blob: 795406a57ac9e48e30f65df83f0cf6646f829083 [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
Jan Sebechlebsky0af8e872023-08-11 14:45:08 +020017#include "utils/Errors.h"
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -070018#define LOG_TAG "APM_AudioPolicyManager"
Tomoharu Kasahara71c90912018-10-31 09:10:12 +090019
20// Need to keep the log statements even in production builds
21// to enable VERBOSE logging dynamically.
22// You can enable VERBOSE logging as follows:
23// adb shell setprop log.tag.APM_AudioPolicyManager V
24#define LOG_NDEBUG 0
Eric Laurente552edb2014-03-10 17:42:56 -070025
26//#define VERY_VERBOSE_LOGGING
27#ifdef VERY_VERBOSE_LOGGING
28#define ALOGVV ALOGV
29#else
30#define ALOGVV(a...) do { } while(0)
31#endif
32
Eric Laurent16c66dd2019-05-01 17:54:10 -070033#include <algorithm>
Eric Laurentd4692962014-05-05 18:13:44 -070034#include <inttypes.h>
jiabin10a03f12021-05-07 23:46:28 +000035#include <map>
Eric Laurente552edb2014-03-10 17:42:56 -070036#include <math.h>
Kevin Rocard153f92d2018-12-18 18:33:28 -080037#include <set>
Atneya Nair0f0a8032022-12-12 16:20:12 -080038#include <type_traits>
Mikhail Naganovd5e18052018-11-30 14:55:45 -080039#include <unordered_set>
Mikhail Naganov15be9d22017-11-08 14:18:13 +110040#include <vector>
Mikhail Naganov946c0032020-10-21 13:04:58 -070041
42#include <Serializer.h>
Nathalie Le Clair88fa2752021-11-23 13:03:41 +010043#include <android/media/audio/common/AudioPort.h>
Glenn Kasten76a13442020-07-01 12:10:59 -070044#include <cutils/bitops.h>
Eric Laurente552edb2014-03-10 17:42:56 -070045#include <cutils/properties.h>
Eric Laurent3b73df72014-03-11 09:06:29 -070046#include <media/AudioParameter.h>
Mikhail Naganov946c0032020-10-21 13:04:58 -070047#include <policy.h>
Andy Hung4ef19fa2018-05-15 19:35:29 -070048#include <private/android_filesystem_config.h>
Mikhail Naganovcbc8f612016-10-11 18:05:13 -070049#include <system/audio.h>
Mikhail Naganov27cf37c2020-04-14 14:47:01 -070050#include <system/audio_config.h>
jiabinebb6af42020-06-09 17:31:17 -070051#include <system/audio_effects/effect_hapticgenerator.h>
Mikhail Naganov946c0032020-10-21 13:04:58 -070052#include <utils/Log.h>
53
Eric Laurentd4692962014-05-05 18:13:44 -070054#include "AudioPolicyManager.h"
François Gaffiea8ecc2c2015-11-09 16:10:40 +010055#include "TypeConverter.h"
Eric Laurente552edb2014-03-10 17:42:56 -070056
Eric Laurent3b73df72014-03-11 09:06:29 -070057namespace android {
Eric Laurente552edb2014-03-10 17:42:56 -070058
Nathalie Le Clair88fa2752021-11-23 13:03:41 +010059using android::media::audio::common::AudioDevice;
60using android::media::audio::common::AudioDeviceAddress;
61using android::media::audio::common::AudioPortDeviceExt;
62using android::media::audio::common::AudioPortExt;
Svet Ganov3e5f14f2021-05-13 22:51:08 +000063using content::AttributionSourceState;
Philip P. Moltmannbda45752020-07-17 16:41:18 -070064
Eric Laurentdc462862016-07-19 12:29:53 -070065//FIXME: workaround for truncated touch sounds
66// to be removed when the problem is handled by system UI
67#define TOUCH_SOUND_FIXED_DELAY_MS 100
Jean-Michel Trivi719a9872017-08-05 13:51:35 -070068
69// Largest difference in dB on earpiece in call between the voice volume and another
70// media / notification / system volume.
71constexpr float IN_CALL_EARPIECE_HEADROOM_DB = 3.f;
72
jiabin06e4bab2019-07-29 10:13:34 -070073template <typename T>
74bool operator== (const SortedVector<T> &left, const SortedVector<T> &right)
75{
76 if (left.size() != right.size()) {
77 return false;
78 }
79 for (size_t index = 0; index < right.size(); index++) {
80 if (left[index] != right[index]) {
81 return false;
82 }
83 }
84 return true;
85}
86
87template <typename T>
88bool operator!= (const SortedVector<T> &left, const SortedVector<T> &right)
89{
90 return !(left == right);
91}
92
Eric Laurente552edb2014-03-10 17:42:56 -070093// ----------------------------------------------------------------------------
94// AudioPolicyInterface implementation
95// ----------------------------------------------------------------------------
96
Nathalie Le Clair88fa2752021-11-23 13:03:41 +010097status_t AudioPolicyManager::setDeviceConnectionState(audio_policy_dev_state_t state,
98 const android::media::audio::common::AudioPort& port, audio_format_t encodedFormat) {
99 status_t status = setDeviceConnectionStateInt(state, port, encodedFormat);
jiabina7b43792018-02-15 16:04:46 -0800100 nextAudioPortGeneration();
101 return status;
Eric Laurentc73ca6e2014-12-12 14:34:22 -0800102}
103
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100104status_t AudioPolicyManager::setDeviceConnectionState(audio_devices_t device,
105 audio_policy_dev_state_t state,
106 const char* device_address,
107 const char* device_name,
108 audio_format_t encodedFormat) {
Atneya Nair638a6e42022-12-18 16:45:15 -0800109 media::AudioPortFw aidlPort;
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100110 if (status_t status = deviceToAudioPort(device, device_address, device_name, &aidlPort);
111 status == OK) {
112 return setDeviceConnectionState(state, aidlPort.hal, encodedFormat);
113 } else {
114 ALOGE("Failed to convert to AudioPort Parcelable: %s", statusToString(status).c_str());
115 return status;
116 }
117}
118
François Gaffie11d30102018-11-02 16:09:09 +0100119void AudioPolicyManager::broadcastDeviceConnectionState(const sp<DeviceDescriptor> &device,
jiabinc0048632023-04-27 22:04:31 +0000120 media::DeviceConnectedState state)
François Gaffie44481e72016-04-20 07:49:57 +0200121{
Mikhail Naganov516d3982022-02-01 23:53:59 +0000122 audio_port_v7 devicePort;
123 device->toAudioPort(&devicePort);
jiabinc0048632023-04-27 22:04:31 +0000124 if (status_t status = mpClientInterface->setDeviceConnectedState(&devicePort, state);
Mikhail Naganov516d3982022-02-01 23:53:59 +0000125 status != OK) {
jiabinc0048632023-04-27 22:04:31 +0000126 ALOGE("Error %d while setting connected state for device %s", state,
Mikhail Naganov516d3982022-02-01 23:53:59 +0000127 device->getDeviceTypeAddr().toString(false).c_str());
128 }
François Gaffie44481e72016-04-20 07:49:57 +0200129}
130
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100131status_t AudioPolicyManager::setDeviceConnectionStateInt(
132 audio_policy_dev_state_t state, const android::media::audio::common::AudioPort& port,
133 audio_format_t encodedFormat) {
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100134 if (port.ext.getTag() != AudioPortExt::device) {
135 return BAD_VALUE;
136 }
137 audio_devices_t device_type;
138 std::string device_address;
139 if (status_t status = aidl2legacy_AudioDevice_audio_device(
140 port.ext.get<AudioPortExt::device>().device, &device_type, &device_address);
141 status != OK) {
142 return status;
143 };
144 const char* device_name = port.name.c_str();
145 // connect/disconnect only 1 device at a time
146 if (!audio_is_output_device(device_type) && !audio_is_input_device(device_type))
147 return BAD_VALUE;
148
149 sp<DeviceDescriptor> device = mHwModules.getDeviceDescriptor(
150 device_type, device_address.c_str(), device_name, encodedFormat,
151 state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
Mikhail Naganovddc5f312022-06-11 00:47:52 +0000152 if (device == nullptr) {
153 return INVALID_OPERATION;
154 }
155 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
156 device->setExtraAudioDescriptors(port.extraAudioDescriptors);
157 }
158 return setDeviceConnectionStateInt(device, state);
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100159}
160
François Gaffie11d30102018-11-02 16:09:09 +0100161status_t AudioPolicyManager::setDeviceConnectionStateInt(audio_devices_t deviceType,
Eric Laurenta1d525f2015-01-29 13:36:45 -0800162 audio_policy_dev_state_t state,
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100163 const char* device_address,
164 const char* device_name,
165 audio_format_t encodedFormat) {
Atneya Nair638a6e42022-12-18 16:45:15 -0800166 media::AudioPortFw aidlPort;
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100167 if (status_t status = deviceToAudioPort(deviceType, device_address, device_name, &aidlPort);
168 status == OK) {
169 return setDeviceConnectionStateInt(state, aidlPort.hal, encodedFormat);
170 } else {
171 ALOGE("Failed to convert to AudioPort Parcelable: %s", statusToString(status).c_str());
172 return status;
173 }
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700174}
Paul McLeane743a472015-01-28 11:07:31 -0800175
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700176status_t AudioPolicyManager::setDeviceConnectionStateInt(const sp<DeviceDescriptor> &device,
177 audio_policy_dev_state_t state)
178{
Eric Laurente552edb2014-03-10 17:42:56 -0700179 // handle output devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700180 if (audio_is_output_device(device->type())) {
Eric Laurentd4692962014-05-05 18:13:44 -0700181 SortedVector <audio_io_handle_t> outputs;
182
François Gaffie11d30102018-11-02 16:09:09 +0100183 ssize_t index = mAvailableOutputDevices.indexOf(device);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700184
Eric Laurente552edb2014-03-10 17:42:56 -0700185 // save a copy of the opened output descriptors before any output is opened or closed
186 // by checkOutputsForDevice(). This will be needed by checkOutputForAllStrategies()
187 mPreviousOutputs = mOutputs;
Eric Laurent96d1dda2022-03-14 17:14:19 +0100188
189 bool wasLeUnicastActive = isLeUnicastActive();
190
Eric Laurente552edb2014-03-10 17:42:56 -0700191 switch (state)
192 {
193 // handle output device connection
Eric Laurent3ae5f312015-02-03 17:12:08 -0800194 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700195 if (index >= 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100196 ALOGW("%s() device already connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700197 return INVALID_OPERATION;
198 }
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800199 ALOGV("%s() connecting device %s format %x",
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700200 __func__, device->toString().c_str(), device->getEncodedFormat());
Eric Laurente552edb2014-03-10 17:42:56 -0700201
Eric Laurente552edb2014-03-10 17:42:56 -0700202 // register new device as available
Francois Gaffie993f3902019-04-10 15:39:27 +0200203 if (mAvailableOutputDevices.add(device) < 0) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700204 return NO_MEMORY;
Eric Laurente552edb2014-03-10 17:42:56 -0700205 }
206
François Gaffie44481e72016-04-20 07:49:57 +0200207 // Before checking outputs, broadcast connect event to allow HAL to retrieve dynamic
208 // parameters on newly connected devices (instead of opening the outputs...)
jiabinc0048632023-04-27 22:04:31 +0000209 broadcastDeviceConnectionState(device, media::DeviceConnectedState::CONNECTED);
François Gaffie44481e72016-04-20 07:49:57 +0200210
François Gaffie11d30102018-11-02 16:09:09 +0100211 if (checkOutputsForDevice(device, state, outputs) != NO_ERROR) {
212 mAvailableOutputDevices.remove(device);
François Gaffie44481e72016-04-20 07:49:57 +0200213
Francois Gaffie716e1432019-01-14 16:58:59 +0100214 mHwModules.cleanUpForDevice(device);
215
jiabinc0048632023-04-27 22:04:31 +0000216 broadcastDeviceConnectionState(device, media::DeviceConnectedState::DISCONNECTED);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700217 return INVALID_OPERATION;
218 }
François Gaffie2110e042015-03-24 08:41:51 +0100219
jiabin1c4794b2020-05-05 10:08:05 -0700220 // Populate encapsulation information when a output device is connected.
221 device->setEncapsulationInfoFromHal(mpClientInterface);
222
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700223 // outputs should never be empty here
224 ALOG_ASSERT(outputs.size() != 0, "setDeviceConnectionState():"
225 "checkOutputsForDevice() returned no outputs but status OK");
François Gaffie11d30102018-11-02 16:09:09 +0100226 ALOGV("%s() checkOutputsForDevice() returned %zu outputs", __func__, outputs.size());
Eric Laurent3ae5f312015-02-03 17:12:08 -0800227
Eric Laurent3ae5f312015-02-03 17:12:08 -0800228 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700229 // handle output device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700230 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700231 if (index < 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100232 ALOGW("%s() device not connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700233 return INVALID_OPERATION;
234 }
235
François Gaffie11d30102018-11-02 16:09:09 +0100236 ALOGV("%s() disconnecting output device %s", __func__, device->toString().c_str());
Paul McLean5c477aa2014-08-20 16:47:57 -0700237
jiabinc0048632023-04-27 22:04:31 +0000238 // Notify the HAL to prepare to disconnect device
239 broadcastDeviceConnectionState(
240 device, media::DeviceConnectedState::PREPARE_TO_DISCONNECT);
Paul McLean5c477aa2014-08-20 16:47:57 -0700241
Eric Laurente552edb2014-03-10 17:42:56 -0700242 // remove device from available output devices
François Gaffie11d30102018-11-02 16:09:09 +0100243 mAvailableOutputDevices.remove(device);
Eric Laurente552edb2014-03-10 17:42:56 -0700244
Francois Gaffieba2cf0f2018-12-12 16:40:25 +0100245 mOutputs.clearSessionRoutesForDevice(device);
246
François Gaffie11d30102018-11-02 16:09:09 +0100247 checkOutputsForDevice(device, state, outputs);
François Gaffie2110e042015-03-24 08:41:51 +0100248
jiabinc0048632023-04-27 22:04:31 +0000249 // Send Disconnect to HALs
250 broadcastDeviceConnectionState(device, media::DeviceConnectedState::DISCONNECTED);
251
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800252 // Reset active device codec
253 device->setEncodedFormat(AUDIO_FORMAT_DEFAULT);
254
Kriti Dangef6be8f2020-11-05 11:58:19 +0100255 // remove device from mReportedFormatsMap cache
256 mReportedFormatsMap.erase(device);
257
jiabina84c3d32022-12-02 18:59:55 +0000258 // remove preferred mixer configurations
259 mPreferredMixerAttrInfos.erase(device->getId());
260
Eric Laurente552edb2014-03-10 17:42:56 -0700261 } break;
262
263 default:
François Gaffie11d30102018-11-02 16:09:09 +0100264 ALOGE("%s() invalid state: %x", __func__, state);
Eric Laurente552edb2014-03-10 17:42:56 -0700265 return BAD_VALUE;
266 }
267
Eric Laurent736a1022019-03-27 18:28:46 -0700268 // Propagate device availability to Engine
269 setEngineDeviceConnectionState(device, state);
270
Eric Laurentae970022019-01-29 14:25:04 -0800271 // No need to evaluate playback routing when connecting a remote submix
272 // output device used by a dynamic policy of type recorder as no
273 // playback use case is affected.
274 bool doCheckForDeviceAndOutputChanges = true;
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700275 if (device->type() == AUDIO_DEVICE_OUT_REMOTE_SUBMIX && device->address() != "0") {
Eric Laurentae970022019-01-29 14:25:04 -0800276 for (audio_io_handle_t output : outputs) {
277 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
Mikhail Naganovbfac5832019-03-05 16:55:28 -0800278 sp<AudioPolicyMix> policyMix = desc->mPolicyMix.promote();
279 if (policyMix != nullptr
280 && policyMix->mMixType == MIX_TYPE_RECORDERS
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +0000281 && device->address() == policyMix->mDeviceAddress.c_str()) {
Eric Laurentae970022019-01-29 14:25:04 -0800282 doCheckForDeviceAndOutputChanges = false;
283 break;
284 }
285 }
286 }
287
288 auto checkCloseOutputs = [&]() {
Mikhail Naganov37977152018-07-11 15:54:44 -0700289 // outputs must be closed after checkOutputForAllStrategies() is executed
290 if (!outputs.isEmpty()) {
291 for (audio_io_handle_t output : outputs) {
292 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
François Gaffie11d30102018-11-02 16:09:09 +0100293 // close unused outputs after device disconnection or direct outputs that have
294 // been opened by checkOutputsForDevice() to query dynamic parameters
Eric Laurente191d1b2022-04-15 11:59:25 +0200295 // "outputs" vector never contains duplicated outputs
Eric Laurentcad6c0d2021-07-13 15:12:39 +0200296 if ((state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE)
297 || (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != 0) &&
Eric Laurente191d1b2022-04-15 11:59:25 +0200298 (desc->mDirectOpenCount == 0))
299 || (((desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0) &&
300 !isOutputOnlyAvailableRouteToSomeDevice(desc))) {
Francois Gaffieff1eb522020-05-06 18:37:04 +0200301 clearAudioSourcesForOutput(output);
Mikhail Naganov37977152018-07-11 15:54:44 -0700302 closeOutput(output);
303 }
Eric Laurente552edb2014-03-10 17:42:56 -0700304 }
Mikhail Naganov37977152018-07-11 15:54:44 -0700305 // check A2DP again after closing A2DP output to reset mA2dpSuspended if needed
306 return true;
Eric Laurente552edb2014-03-10 17:42:56 -0700307 }
Mikhail Naganov37977152018-07-11 15:54:44 -0700308 return false;
Eric Laurentae970022019-01-29 14:25:04 -0800309 };
310
311 if (doCheckForDeviceAndOutputChanges) {
312 checkForDeviceAndOutputChanges(checkCloseOutputs);
313 } else {
314 checkCloseOutputs();
315 }
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100316 (void)updateCallRouting(false /*fromCache*/);
François Gaffie11d30102018-11-02 16:09:09 +0100317 const DeviceVector msdOutDevices = getMsdAudioOutDevices();
jiabinbce0c1d2020-10-05 11:20:18 -0700318 const DeviceVector activeMediaDevices =
319 mEngine->getActiveMediaDevices(mAvailableOutputDevices);
jiabin3ff8d7d2022-12-13 06:27:44 +0000320 std::map<audio_io_handle_t, DeviceVector> outputsToReopenWithDevices;
Eric Laurente552edb2014-03-10 17:42:56 -0700321 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700322 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Jaideep Sharma89b5b852020-11-23 16:41:33 +0530323 if (desc->isActive() && ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) ||
324 (desc != mPrimaryOutput))) {
François Gaffie11d30102018-11-02 16:09:09 +0100325 DeviceVector newDevices = getNewOutputDevices(desc, true /*fromCache*/);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700326 // do not force device change on duplicated output because if device is 0, it will
327 // also force a device 0 for the two outputs it is duplicated to which may override
328 // a valid device selection on those outputs.
François Gaffie11d30102018-11-02 16:09:09 +0100329 bool force = (msdOutDevices.isEmpty() || msdOutDevices != desc->devices())
Mikhail Naganov15be9d22017-11-08 14:18:13 +1100330 && !desc->isDuplicated()
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700331 && (!device_distinguishes_on_address(device->type())
Eric Laurentc2730ba2014-07-20 15:47:07 -0700332 // always force when disconnecting (a non-duplicated device)
333 || (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE));
jiabin3ff8d7d2022-12-13 06:27:44 +0000334 if (desc->mUsePreferredMixerAttributes && newDevices != desc->devices()) {
335 // If the device is using preferred mixer attributes, the output need to reopen
336 // with default configuration when the new selected devices are different from
337 // current routing devices
338 outputsToReopenWithDevices.emplace(mOutputs.keyAt(i), newDevices);
339 continue;
340 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +0530341 setOutputDevices(__func__, desc, newDevices, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700342 }
jiabinbce0c1d2020-10-05 11:20:18 -0700343 if (!desc->isDuplicated() && desc->mProfile->hasDynamicAudioProfile() &&
jiabin498d2152021-04-02 00:26:46 +0000344 !activeMediaDevices.empty() && desc->devices() != activeMediaDevices &&
jiabinbce0c1d2020-10-05 11:20:18 -0700345 desc->supportsDevicesForPlayback(activeMediaDevices)) {
346 // Reopen the output to query the dynamic profiles when there is not active
347 // clients or all active clients will be rerouted. Otherwise, set the flag
348 // `mPendingReopenToQueryProfiles` in the SwOutputDescriptor so that the output
349 // can be reopened to query dynamic profiles when all clients are inactive.
350 if (areAllActiveTracksRerouted(desc)) {
jiabin3ff8d7d2022-12-13 06:27:44 +0000351 outputsToReopenWithDevices.emplace(mOutputs.keyAt(i), activeMediaDevices);
jiabinbce0c1d2020-10-05 11:20:18 -0700352 } else {
353 desc->mPendingReopenToQueryProfiles = true;
354 }
355 }
356 if (!desc->supportsDevicesForPlayback(activeMediaDevices)) {
357 // Clear the flag that previously set for re-querying profiles.
358 desc->mPendingReopenToQueryProfiles = false;
359 }
360 }
jiabin3ff8d7d2022-12-13 06:27:44 +0000361 reopenOutputsWithDevices(outputsToReopenWithDevices);
Eric Laurente552edb2014-03-10 17:42:56 -0700362
Eric Laurentd60560a2015-04-10 11:31:20 -0700363 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
François Gaffie11d30102018-11-02 16:09:09 +0100364 cleanUpForDevice(device);
Eric Laurentd60560a2015-04-10 11:31:20 -0700365 }
366
Eric Laurent96d1dda2022-03-14 17:14:19 +0100367 checkLeBroadcastRoutes(wasLeUnicastActive, nullptr, 0);
368
Eric Laurent72aa32f2014-05-30 18:51:48 -0700369 mpClientInterface->onAudioPortListUpdate();
Eric Laurentb71e58b2014-05-29 16:08:11 -0700370 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700371 } // end if is output device
372
Eric Laurente552edb2014-03-10 17:42:56 -0700373 // handle input devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700374 if (audio_is_input_device(device->type())) {
François Gaffie11d30102018-11-02 16:09:09 +0100375 ssize_t index = mAvailableInputDevices.indexOf(device);
Eric Laurente552edb2014-03-10 17:42:56 -0700376 switch (state)
377 {
378 // handle input device connection
Eric Laurent3b73df72014-03-11 09:06:29 -0700379 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700380 if (index >= 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100381 ALOGW("%s() device already connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700382 return INVALID_OPERATION;
383 }
Eric Laurent0dd51852019-04-19 18:18:58 -0700384
385 if (mAvailableInputDevices.add(device) < 0) {
386 return NO_MEMORY;
387 }
388
François Gaffie44481e72016-04-20 07:49:57 +0200389 // Before checking intputs, broadcast connect event to allow HAL to retrieve dynamic
390 // parameters on newly connected devices (instead of opening the inputs...)
jiabinc0048632023-04-27 22:04:31 +0000391 broadcastDeviceConnectionState(device, media::DeviceConnectedState::CONNECTED);
François Gaffie44481e72016-04-20 07:49:57 +0200392
Eric Laurent0dd51852019-04-19 18:18:58 -0700393 if (checkInputsForDevice(device, state) != NO_ERROR) {
394 mAvailableInputDevices.remove(device);
395
jiabinc0048632023-04-27 22:04:31 +0000396 broadcastDeviceConnectionState(device, media::DeviceConnectedState::DISCONNECTED);
Francois Gaffie716e1432019-01-14 16:58:59 +0100397
398 mHwModules.cleanUpForDevice(device);
399
Eric Laurentd4692962014-05-05 18:13:44 -0700400 return INVALID_OPERATION;
401 }
402
Eric Laurentd4692962014-05-05 18:13:44 -0700403 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700404
405 // handle input device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700406 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700407 if (index < 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100408 ALOGW("%s() device not connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700409 return INVALID_OPERATION;
410 }
Paul McLean5c477aa2014-08-20 16:47:57 -0700411
François Gaffie11d30102018-11-02 16:09:09 +0100412 ALOGV("%s() disconnecting input device %s", __func__, device->toString().c_str());
Paul McLean5c477aa2014-08-20 16:47:57 -0700413
jiabinc0048632023-04-27 22:04:31 +0000414 // Notify the HAL to prepare to disconnect device
415 broadcastDeviceConnectionState(
416 device, media::DeviceConnectedState::PREPARE_TO_DISCONNECT);
Paul McLean5c477aa2014-08-20 16:47:57 -0700417
François Gaffie11d30102018-11-02 16:09:09 +0100418 mAvailableInputDevices.remove(device);
Eric Laurent0dd51852019-04-19 18:18:58 -0700419
420 checkInputsForDevice(device, state);
Kriti Dangef6be8f2020-11-05 11:58:19 +0100421
jiabinc0048632023-04-27 22:04:31 +0000422 // Set Disconnect to HALs
423 broadcastDeviceConnectionState(device, media::DeviceConnectedState::DISCONNECTED);
424
Kriti Dangef6be8f2020-11-05 11:58:19 +0100425 // remove device from mReportedFormatsMap cache
426 mReportedFormatsMap.erase(device);
Eric Laurentd4692962014-05-05 18:13:44 -0700427 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700428
429 default:
François Gaffie11d30102018-11-02 16:09:09 +0100430 ALOGE("%s() invalid state: %x", __func__, state);
Eric Laurente552edb2014-03-10 17:42:56 -0700431 return BAD_VALUE;
432 }
433
Eric Laurent736a1022019-03-27 18:28:46 -0700434 // Propagate device availability to Engine
435 setEngineDeviceConnectionState(device, state);
436
Eric Laurent0dd51852019-04-19 18:18:58 -0700437 checkCloseInputs();
Eric Laurent5f5fca52016-08-04 11:48:57 -0700438 // As the input device list can impact the output device selection, update
439 // getDeviceForStrategy() cache
440 updateDevicesAndOutputs();
Eric Laurente552edb2014-03-10 17:42:56 -0700441
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100442 (void)updateCallRouting(false /*fromCache*/);
Francois Gaffiea0e5c992020-09-29 16:05:07 +0200443 // Reconnect Audio Source
444 for (const auto &strategy : mEngine->getOrderedProductStrategies()) {
445 auto attributes = mEngine->getAllAttributesForProductStrategy(strategy).front();
446 checkAudioSourceForAttributes(attributes);
447 }
Eric Laurentd60560a2015-04-10 11:31:20 -0700448 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
François Gaffie11d30102018-11-02 16:09:09 +0100449 cleanUpForDevice(device);
Eric Laurentd60560a2015-04-10 11:31:20 -0700450 }
451
Eric Laurentb52c1522014-05-20 11:27:36 -0700452 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -0700453 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700454 } // end if is input device
Eric Laurente552edb2014-03-10 17:42:56 -0700455
François Gaffie11d30102018-11-02 16:09:09 +0100456 ALOGW("%s() invalid device: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700457 return BAD_VALUE;
458}
459
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100460status_t AudioPolicyManager::deviceToAudioPort(audio_devices_t device, const char* device_address,
461 const char* device_name,
Atneya Nair638a6e42022-12-18 16:45:15 -0800462 media::AudioPortFw* aidlPort) {
Andy Hung5b9a6112023-08-09 19:56:57 -0700463 const auto devDescr = sp<DeviceDescriptorBase>::make(device, device_address);
464 devDescr->setName(device_name);
465 return devDescr->writeToParcelable(aidlPort);
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100466}
467
Eric Laurent736a1022019-03-27 18:28:46 -0700468void AudioPolicyManager::setEngineDeviceConnectionState(const sp<DeviceDescriptor> device,
469 audio_policy_dev_state_t state) {
470
471 // the Engine does not have to know about remote submix devices used by dynamic audio policies
472 if (audio_is_remote_submix_device(device->type()) && device->address() != "0") {
473 return;
474 }
475 mEngine->setDeviceConnectionState(device, state);
476}
477
478
Eric Laurente0720872014-03-11 09:30:41 -0700479audio_policy_dev_state_t AudioPolicyManager::getDeviceConnectionState(audio_devices_t device,
François Gaffie53615e22015-03-19 09:24:12 +0100480 const char *device_address)
Eric Laurente552edb2014-03-10 17:42:56 -0700481{
Eric Laurent634b7142016-04-20 13:48:02 -0700482 sp<DeviceDescriptor> devDesc =
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800483 mHwModules.getDeviceDescriptor(device, device_address, "", AUDIO_FORMAT_DEFAULT,
484 false /* allowToCreate */,
Eric Laurent634b7142016-04-20 13:48:02 -0700485 (strlen(device_address) != 0)/*matchAddress*/);
486
487 if (devDesc == 0) {
François Gaffie251c7f02018-11-07 10:41:08 +0100488 ALOGV("getDeviceConnectionState() undeclared device, type %08x, address: %s",
Eric Laurent634b7142016-04-20 13:48:02 -0700489 device, device_address);
490 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
491 }
François Gaffie53615e22015-03-19 09:24:12 +0100492
Eric Laurent3a4311c2014-03-17 12:00:47 -0700493 DeviceVector *deviceVector;
494
Eric Laurente552edb2014-03-10 17:42:56 -0700495 if (audio_is_output_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700496 deviceVector = &mAvailableOutputDevices;
Eric Laurente552edb2014-03-10 17:42:56 -0700497 } else if (audio_is_input_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700498 deviceVector = &mAvailableInputDevices;
499 } else {
François Gaffie11d30102018-11-02 16:09:09 +0100500 ALOGW("%s() invalid device type %08x", __func__, device);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700501 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurente552edb2014-03-10 17:42:56 -0700502 }
Eric Laurent634b7142016-04-20 13:48:02 -0700503
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800504 return (deviceVector->getDevice(
505 device, String8(device_address), AUDIO_FORMAT_DEFAULT) != 0) ?
Eric Laurent634b7142016-04-20 13:48:02 -0700506 AUDIO_POLICY_DEVICE_STATE_AVAILABLE : AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurenta1d525f2015-01-29 13:36:45 -0800507}
508
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800509status_t AudioPolicyManager::handleDeviceConfigChange(audio_devices_t device,
510 const char *device_address,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800511 const char *device_name,
512 audio_format_t encodedFormat)
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800513{
514 status_t status;
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700515 String8 reply;
516 AudioParameter param;
517 int isReconfigA2dpSupported = 0;
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800518
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800519 ALOGV("handleDeviceConfigChange(() device: 0x%X, address %s name %s encodedFormat: 0x%X",
520 device, device_address, device_name, encodedFormat);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800521
Pavlin Radoslavovc694ff42017-01-09 23:27:29 -0800522 // connect/disconnect only 1 device at a time
523 if (!audio_is_output_device(device) && !audio_is_input_device(device)) return BAD_VALUE;
524
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800525 // Check if the device is currently connected
jiabin9a3361e2019-10-01 09:38:30 -0700526 DeviceVector deviceList = mAvailableOutputDevices.getDevicesFromType(device);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800527 if (deviceList.empty()) {
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800528 // Nothing to do: device is not connected
529 return NO_ERROR;
530 }
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800531 sp<DeviceDescriptor> devDesc = deviceList.itemAt(0);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800532
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700533 // For offloaded A2DP, Hw modules may have the capability to
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800534 // configure codecs.
535 // Handle two specific cases by sending a set parameter to
536 // configure A2DP codecs. No need to toggle device state.
537 // Case 1: A2DP active device switches from primary to primary
538 // module
539 // Case 2: A2DP device config changes on primary module.
Francois Gaffiebce7cd42020-10-14 16:13:20 +0200540 if (audio_is_a2dp_out_device(device) && hasPrimaryOutput()) {
jiabin9a3361e2019-10-01 09:38:30 -0700541 sp<HwModule> module = mHwModules.getModuleForDeviceType(device, encodedFormat);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800542 audio_module_handle_t primaryHandle = mPrimaryOutput->getModuleHandle();
543 if (availablePrimaryOutputDevices().contains(devDesc) &&
544 (module != 0 && module->getHandle() == primaryHandle)) {
545 reply = mpClientInterface->getParameters(
546 AUDIO_IO_HANDLE_NONE,
547 String8(AudioParameter::keyReconfigA2dpSupported));
548 AudioParameter repliedParameters(reply);
549 repliedParameters.getInt(
550 String8(AudioParameter::keyReconfigA2dpSupported), isReconfigA2dpSupported);
551 if (isReconfigA2dpSupported) {
552 const String8 key(AudioParameter::keyReconfigA2dp);
553 param.add(key, String8("true"));
554 mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString());
555 devDesc->setEncodedFormat(encodedFormat);
556 return NO_ERROR;
557 }
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700558 }
559 }
cnx421bd2dcc42020-07-11 14:58:44 +0800560 auto musicStrategy = streamToStrategy(AUDIO_STREAM_MUSIC);
561 for (size_t i = 0; i < mOutputs.size(); i++) {
562 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
563 // mute media strategies and delay device switch by the largest
564 // This avoid sending the music tail into the earpiece or headset.
565 setStrategyMute(musicStrategy, true, desc);
566 setStrategyMute(musicStrategy, false, desc, MUTE_TIME_MS,
567 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
568 nullptr, true /*fromCache*/).types());
569 }
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800570 // Toggle the device state: UNAVAILABLE -> AVAILABLE
571 // This will force reading again the device configuration
572 status = setDeviceConnectionState(device,
573 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800574 device_address, device_name,
575 devDesc->getEncodedFormat());
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800576 if (status != NO_ERROR) {
577 ALOGW("handleDeviceConfigChange() error disabling connection state: %d",
578 status);
579 return status;
580 }
581
582 status = setDeviceConnectionState(device,
583 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800584 device_address, device_name, encodedFormat);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800585 if (status != NO_ERROR) {
586 ALOGW("handleDeviceConfigChange() error enabling connection state: %d",
587 status);
588 return status;
589 }
590
591 return NO_ERROR;
592}
593
Pattydd807582021-11-04 21:01:03 +0800594status_t AudioPolicyManager::getHwOffloadFormatsSupportedForBluetoothMedia(
595 audio_devices_t device, std::vector<audio_format_t> *formats)
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800596{
Pattydd807582021-11-04 21:01:03 +0800597 ALOGV("getHwOffloadFormatsSupportedForBluetoothMedia()");
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800598 status_t status = NO_ERROR;
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800599 std::unordered_set<audio_format_t> formatSet;
600 sp<HwModule> primaryModule =
601 mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_PRIMARY);
Aniket Kumar Latafedb5982019-07-03 11:20:36 -0700602 if (primaryModule == nullptr) {
603 ALOGE("%s() unable to get primary module", __func__);
604 return NO_INIT;
605 }
Pattydd807582021-11-04 21:01:03 +0800606
607 DeviceTypeSet audioDeviceSet;
608
609 switch(device) {
610 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP:
611 audioDeviceSet = getAudioDeviceOutAllA2dpSet();
612 break;
613 case AUDIO_DEVICE_OUT_BLE_HEADSET:
Patty Huang36028df2022-07-06 00:14:12 +0800614 audioDeviceSet = getAudioDeviceOutLeAudioUnicastSet();
615 break;
616 case AUDIO_DEVICE_OUT_BLE_BROADCAST:
617 audioDeviceSet = getAudioDeviceOutLeAudioBroadcastSet();
Pattydd807582021-11-04 21:01:03 +0800618 break;
619 default:
620 ALOGE("%s() device type 0x%08x not supported", __func__, device);
621 return BAD_VALUE;
622 }
623
jiabin9a3361e2019-10-01 09:38:30 -0700624 DeviceVector declaredDevices = primaryModule->getDeclaredDevices().getDevicesFromTypes(
Pattydd807582021-11-04 21:01:03 +0800625 audioDeviceSet);
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800626 for (const auto& device : declaredDevices) {
627 formatSet.insert(device->encodedFormats().begin(), device->encodedFormats().end());
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800628 }
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800629 formats->assign(formatSet.begin(), formatSet.end());
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800630 return status;
631}
632
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100633DeviceVector AudioPolicyManager::selectBestRxSinkDevicesForCall(bool fromCache)
634{
635 DeviceVector rxSinkdevices{};
636 rxSinkdevices = mEngine->getOutputDevicesForAttributes(
637 attributes_initializer(AUDIO_USAGE_VOICE_COMMUNICATION), nullptr, fromCache);
638 if (!rxSinkdevices.isEmpty() && mAvailableOutputDevices.contains(rxSinkdevices.itemAt(0))) {
639 auto rxSinkDevice = rxSinkdevices.itemAt(0);
640 auto telephonyRxModule = mHwModules.getModuleForDeviceType(
641 AUDIO_DEVICE_IN_TELEPHONY_RX, AUDIO_FORMAT_DEFAULT);
642 // retrieve Rx Source device descriptor
643 sp<DeviceDescriptor> rxSourceDevice = mAvailableInputDevices.getDevice(
644 AUDIO_DEVICE_IN_TELEPHONY_RX, String8(), AUDIO_FORMAT_DEFAULT);
645
646 // RX Telephony and Rx sink devices are declared by Primary Audio HAL
647 if (isPrimaryModule(telephonyRxModule) && (telephonyRxModule->getHalVersionMajor() >= 3) &&
648 telephonyRxModule->supportsPatch(rxSourceDevice, rxSinkDevice)) {
649 ALOGW("%s() device %s using HW Bridge", __func__, rxSinkDevice->toString().c_str());
650 return DeviceVector(rxSinkDevice);
651 }
652 }
653 // Note that despite the fact that getNewOutputDevices() is called on the primary output,
654 // the device returned is not necessarily reachable via this output
655 // (filter later by setOutputDevices())
656 return getNewOutputDevices(mPrimaryOutput, fromCache);
657}
658
659status_t AudioPolicyManager::updateCallRouting(bool fromCache, uint32_t delayMs, uint32_t *waitMs)
660{
François Gaffiedb1755b2023-09-01 11:50:35 +0200661 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) {
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100662 DeviceVector rxDevices = selectBestRxSinkDevicesForCall(fromCache);
663 return updateCallRoutingInternal(rxDevices, delayMs, waitMs);
664 }
665 return INVALID_OPERATION;
666}
667
668status_t AudioPolicyManager::updateCallRoutingInternal(
669 const DeviceVector &rxDevices, uint32_t delayMs, uint32_t *waitMs)
Eric Laurentc2730ba2014-07-20 15:47:07 -0700670{
671 bool createTxPatch = false;
François Gaffie9eb18552018-11-05 10:33:26 +0100672 bool createRxPatch = false;
Eric Laurentdc462862016-07-19 12:29:53 -0700673 uint32_t muteWaitMs = 0;
François Gaffiedb1755b2023-09-01 11:50:35 +0200674 if (hasPrimaryOutput() &&
jiabin9a3361e2019-10-01 09:38:30 -0700675 mPrimaryOutput->devices().onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_STUB)) {
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100676 return INVALID_OPERATION;
Eric Laurent87ffa392015-05-22 10:32:38 -0700677 }
François Gaffie11d30102018-11-02 16:09:09 +0100678
Francois Gaffie716e1432019-01-14 16:58:59 +0100679 audio_attributes_t attr = { .source = AUDIO_SOURCE_VOICE_COMMUNICATION };
François Gaffiec005e562018-11-06 15:04:49 +0100680 auto txSourceDevice = mEngine->getInputDeviceForAttributes(attr);
François Gaffiedb1755b2023-09-01 11:50:35 +0200681
682 disconnectTelephonyAudioSource(mCallRxSourceClient);
683 disconnectTelephonyAudioSource(mCallTxSourceClient);
684
685 if (rxDevices.isEmpty()) {
686 ALOGW("%s() no selected output device", __func__);
687 return INVALID_OPERATION;
688 }
Eric Laurentcedd5b52023-03-22 00:03:31 +0000689 if (txSourceDevice == nullptr) {
690 ALOGE("%s() selected input device not available", __func__);
691 return INVALID_OPERATION;
692 }
François Gaffiec005e562018-11-06 15:04:49 +0100693
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100694 ALOGV("%s device rxDevice %s txDevice %s", __func__,
François Gaffie9eb18552018-11-05 10:33:26 +0100695 rxDevices.itemAt(0)->toString().c_str(), txSourceDevice->toString().c_str());
Eric Laurentc2730ba2014-07-20 15:47:07 -0700696
François Gaffie9eb18552018-11-05 10:33:26 +0100697 auto telephonyRxModule =
jiabin9a3361e2019-10-01 09:38:30 -0700698 mHwModules.getModuleForDeviceType(AUDIO_DEVICE_IN_TELEPHONY_RX, AUDIO_FORMAT_DEFAULT);
François Gaffie9eb18552018-11-05 10:33:26 +0100699 auto telephonyTxModule =
jiabin9a3361e2019-10-01 09:38:30 -0700700 mHwModules.getModuleForDeviceType(AUDIO_DEVICE_OUT_TELEPHONY_TX, AUDIO_FORMAT_DEFAULT);
François Gaffie9eb18552018-11-05 10:33:26 +0100701 // retrieve Rx Source and Tx Sink device descriptors
702 sp<DeviceDescriptor> rxSourceDevice =
703 mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_TELEPHONY_RX,
704 String8(),
705 AUDIO_FORMAT_DEFAULT);
706 sp<DeviceDescriptor> txSinkDevice =
707 mAvailableOutputDevices.getDevice(AUDIO_DEVICE_OUT_TELEPHONY_TX,
708 String8(),
709 AUDIO_FORMAT_DEFAULT);
710
711 // RX and TX Telephony device are declared by Primary Audio HAL
712 if (isPrimaryModule(telephonyRxModule) && isPrimaryModule(telephonyTxModule) &&
713 (telephonyRxModule->getHalVersionMajor() >= 3)) {
714 if (rxSourceDevice == 0 || txSinkDevice == 0) {
715 // RX / TX Telephony device(s) is(are) not currently available
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100716 ALOGE("%s() no telephony Tx and/or RX device", __func__);
717 return INVALID_OPERATION;
François Gaffie9eb18552018-11-05 10:33:26 +0100718 }
François Gaffieafd4cea2019-11-18 15:50:22 +0100719 // createAudioPatchInternal now supports both HW / SW bridging
720 createRxPatch = true;
721 createTxPatch = true;
François Gaffie9eb18552018-11-05 10:33:26 +0100722 } else {
723 // If the RX device is on the primary HW module, then use legacy routing method for
724 // voice calls via setOutputDevice() on primary output.
725 // Otherwise, create two audio patches for TX and RX path.
726 createRxPatch = !(availablePrimaryOutputDevices().contains(rxDevices.itemAt(0))) &&
727 (rxSourceDevice != 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700728 // If the TX device is also on the primary HW module, setOutputDevice() will take care
729 // of it due to legacy implementation. If not, create a patch.
François Gaffie9eb18552018-11-05 10:33:26 +0100730 createTxPatch = !(availablePrimaryModuleInputDevices().contains(txSourceDevice)) &&
731 (txSinkDevice != 0);
732 }
733 // Use legacy routing method for voice calls via setOutputDevice() on primary output.
734 // Otherwise, create two audio patches for TX and RX path.
735 if (!createRxPatch) {
François Gaffiedb1755b2023-09-01 11:50:35 +0200736 if (!hasPrimaryOutput()) {
737 ALOGW("%s() no primary output available", __func__);
738 return INVALID_OPERATION;
739 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +0530740 muteWaitMs = setOutputDevices(__func__, mPrimaryOutput, rxDevices, true, delayMs);
Eric Laurent8ae73122016-04-12 10:13:29 -0700741 } else { // create RX path audio patch
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200742 connectTelephonyRxAudioSource();
juyuchen2224c5a2019-01-21 12:00:58 +0800743 // If the TX device is on the primary HW module but RX device is
744 // on other HW module, SinkMetaData of telephony input should handle it
745 // assuming the device uses audio HAL V5.0 and above
Eric Laurentc2730ba2014-07-20 15:47:07 -0700746 }
Eric Laurent8ae73122016-04-12 10:13:29 -0700747 if (createTxPatch) { // create TX path audio patch
François Gaffieafd4cea2019-11-18 15:50:22 +0100748 // terminate active capture if on the same HW module as the call TX source device
749 // FIXME: would be better to refine to only inputs whose profile connects to the
750 // call TX device but this information is not in the audio patch and logic here must be
751 // symmetric to the one in startInput()
752 for (const auto& activeDesc : mInputs.getActiveInputs()) {
753 if (activeDesc->hasSameHwModuleAs(txSourceDevice)) {
754 closeActiveClients(activeDesc);
755 }
756 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200757 connectTelephonyTxAudioSource(txSourceDevice, txSinkDevice, delayMs);
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800758 }
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100759 if (waitMs != nullptr) {
760 *waitMs = muteWaitMs;
761 }
762 return NO_ERROR;
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800763}
Eric Laurentc2730ba2014-07-20 15:47:07 -0700764
Mikhail Naganov100f0122018-11-29 11:22:16 -0800765bool AudioPolicyManager::isDeviceOfModule(
766 const sp<DeviceDescriptor>& devDesc, const char *moduleId) const {
767 sp<HwModule> module = mHwModules.getModuleFromName(moduleId);
768 if (module != 0) {
769 return mAvailableOutputDevices.getDevicesFromHwModule(module->getHandle())
770 .indexOf(devDesc) != NAME_NOT_FOUND
771 || mAvailableInputDevices.getDevicesFromHwModule(module->getHandle())
772 .indexOf(devDesc) != NAME_NOT_FOUND;
773 }
774 return false;
775}
776
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200777void AudioPolicyManager::connectTelephonyRxAudioSource()
778{
Francois Gaffie601801d2021-06-22 13:27:39 +0200779 disconnectTelephonyAudioSource(mCallRxSourceClient);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200780 const struct audio_port_config source = {
781 .role = AUDIO_PORT_ROLE_SOURCE, .type = AUDIO_PORT_TYPE_DEVICE,
782 .ext.device.type = AUDIO_DEVICE_IN_TELEPHONY_RX, .ext.device.address = ""
783 };
784 const auto aa = mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL);
Francois Gaffie601801d2021-06-22 13:27:39 +0200785 mCallRxSourceClient = startAudioSourceInternal(&source, &aa, 0/*uid*/);
786 ALOGE_IF(mCallRxSourceClient == nullptr,
787 "%s failed to start Telephony Rx AudioSource", __func__);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200788}
789
Francois Gaffie601801d2021-06-22 13:27:39 +0200790void AudioPolicyManager::disconnectTelephonyAudioSource(sp<SourceClientDescriptor> &clientDesc)
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200791{
Francois Gaffie601801d2021-06-22 13:27:39 +0200792 if (clientDesc == nullptr) {
793 return;
794 }
795 ALOGW_IF(stopAudioSource(clientDesc->portId()) != NO_ERROR,
796 "%s error stopping audio source", __func__);
797 clientDesc.clear();
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200798}
799
800void AudioPolicyManager::connectTelephonyTxAudioSource(
801 const sp<DeviceDescriptor> &srcDevice, const sp<DeviceDescriptor> &sinkDevice,
802 uint32_t delayMs)
803{
Francois Gaffie601801d2021-06-22 13:27:39 +0200804 disconnectTelephonyAudioSource(mCallTxSourceClient);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200805 if (srcDevice == nullptr || sinkDevice == nullptr) {
806 ALOGW("%s could not create patch, invalid sink and/or source device(s)", __func__);
807 return;
808 }
809 PatchBuilder patchBuilder;
810 patchBuilder.addSource(srcDevice).addSink(sinkDevice);
811 ALOGV("%s between source %s and sink %s", __func__,
812 srcDevice->toString().c_str(), sinkDevice->toString().c_str());
Francois Gaffie601801d2021-06-22 13:27:39 +0200813 auto callTxSourceClientPortId = PolicyAudioPort::getNextUniqueId();
Eric Laurent78b07302022-10-07 16:20:34 +0200814 const auto aa = mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL);
815
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200816 struct audio_port_config source = {};
817 srcDevice->toAudioPortConfig(&source);
Francois Gaffie601801d2021-06-22 13:27:39 +0200818 mCallTxSourceClient = new InternalSourceClientDescriptor(
819 callTxSourceClientPortId, mUidCached, aa, source, srcDevice, sinkDevice,
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200820 mCommunnicationStrategy, toVolumeSource(aa));
821 audio_patch_handle_t patchHandle = AUDIO_PATCH_HANDLE_NONE;
822 status_t status = connectAudioSourceToSink(
Francois Gaffie601801d2021-06-22 13:27:39 +0200823 mCallTxSourceClient, sinkDevice, patchBuilder.patch(), patchHandle, mUidCached,
824 delayMs);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200825 ALOGE_IF(status != NO_ERROR, "%s() error %d creating TX audio patch", __func__, status);
826 if (status == NO_ERROR) {
Francois Gaffie601801d2021-06-22 13:27:39 +0200827 mAudioSources.add(callTxSourceClientPortId, mCallTxSourceClient);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200828 }
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200829}
830
Eric Laurente0720872014-03-11 09:30:41 -0700831void AudioPolicyManager::setPhoneState(audio_mode_t state)
Eric Laurente552edb2014-03-10 17:42:56 -0700832{
833 ALOGV("setPhoneState() state %d", state);
François Gaffie2110e042015-03-24 08:41:51 +0100834 // store previous phone state for management of sonification strategy below
835 int oldState = mEngine->getPhoneState();
Eric Laurent96d1dda2022-03-14 17:14:19 +0100836 bool wasLeUnicastActive = isLeUnicastActive();
François Gaffie2110e042015-03-24 08:41:51 +0100837
838 if (mEngine->setPhoneState(state) != NO_ERROR) {
839 ALOGW("setPhoneState() invalid or same state %d", state);
Eric Laurente552edb2014-03-10 17:42:56 -0700840 return;
841 }
François Gaffie2110e042015-03-24 08:41:51 +0100842 /// Opens: can these line be executed after the switch of volume curves???
Eric Laurent63dea1d2015-07-02 17:10:28 -0700843 if (isStateInCall(oldState)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700844 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent63dea1d2015-07-02 17:10:28 -0700845 // force reevaluating accessibility routing when call stops
jiabinc44b3462022-12-08 12:52:31 -0800846 invalidateStreams({AUDIO_STREAM_ACCESSIBILITY});
Eric Laurente552edb2014-03-10 17:42:56 -0700847 }
848
François Gaffie2110e042015-03-24 08:41:51 +0100849 /**
850 * Switching to or from incall state or switching between telephony and VoIP lead to force
851 * routing command.
852 */
Eric Laurent74b71512019-11-06 17:21:57 -0800853 bool force = ((isStateInCall(oldState) != isStateInCall(state))
854 || (isStateInCall(state) && (state != oldState)));
Eric Laurente552edb2014-03-10 17:42:56 -0700855
856 // check for device and output changes triggered by new phone state
Mikhail Naganov37977152018-07-11 15:54:44 -0700857 checkForDeviceAndOutputChanges();
Eric Laurente552edb2014-03-10 17:42:56 -0700858
Eric Laurente552edb2014-03-10 17:42:56 -0700859 int delayMs = 0;
860 if (isStateInCall(state)) {
861 nsecs_t sysTime = systemTime();
François Gaffiec005e562018-11-06 15:04:49 +0100862 auto musicStrategy = streamToStrategy(AUDIO_STREAM_MUSIC);
863 auto sonificationStrategy = streamToStrategy(AUDIO_STREAM_ALARM);
Eric Laurente552edb2014-03-10 17:42:56 -0700864 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700865 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700866 // mute media and sonification strategies and delay device switch by the largest
867 // latency of any output where either strategy is active.
868 // This avoid sending the ring tone or music tail into the earpiece or headset.
François Gaffiec005e562018-11-06 15:04:49 +0100869 if ((desc->isStrategyActive(musicStrategy, SONIFICATION_HEADSET_MUSIC_DELAY, sysTime) ||
870 desc->isStrategyActive(sonificationStrategy, SONIFICATION_HEADSET_MUSIC_DELAY,
871 sysTime)) &&
Eric Laurentc75307b2015-03-17 15:29:32 -0700872 (delayMs < (int)desc->latency()*2)) {
873 delayMs = desc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -0700874 }
François Gaffiec005e562018-11-06 15:04:49 +0100875 setStrategyMute(musicStrategy, true, desc);
876 setStrategyMute(musicStrategy, false, desc, MUTE_TIME_MS,
877 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
878 nullptr, true /*fromCache*/).types());
879 setStrategyMute(sonificationStrategy, true, desc);
880 setStrategyMute(sonificationStrategy, false, desc, MUTE_TIME_MS,
881 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_ALARM),
882 nullptr, true /*fromCache*/).types());
Eric Laurente552edb2014-03-10 17:42:56 -0700883 }
884 }
885
François Gaffiedb1755b2023-09-01 11:50:35 +0200886 if (state == AUDIO_MODE_IN_CALL) {
887 (void)updateCallRouting(false /*fromCache*/, delayMs);
888 } else {
889 if (oldState == AUDIO_MODE_IN_CALL) {
890 disconnectTelephonyAudioSource(mCallRxSourceClient);
891 disconnectTelephonyAudioSource(mCallTxSourceClient);
892 }
893 if (hasPrimaryOutput()) {
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100894 DeviceVector rxDevices = getNewOutputDevices(mPrimaryOutput, false /*fromCache*/);
895 // force routing command to audio hardware when ending call
896 // even if no device change is needed
897 if (isStateInCall(oldState) && rxDevices.isEmpty()) {
898 rxDevices = mPrimaryOutput->devices();
899 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +0530900 setOutputDevices(__func__, mPrimaryOutput, rxDevices, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700901 }
Eric Laurentc2730ba2014-07-20 15:47:07 -0700902 }
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700903
jiabin3ff8d7d2022-12-13 06:27:44 +0000904 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700905 // reevaluate routing on all outputs in case tracks have been started during the call
906 for (size_t i = 0; i < mOutputs.size(); i++) {
907 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
François Gaffie11d30102018-11-02 16:09:09 +0100908 DeviceVector newDevices = getNewOutputDevices(desc, true /*fromCache*/);
Francois Gaffie601801d2021-06-22 13:27:39 +0200909 if (state != AUDIO_MODE_IN_CALL || (desc != mPrimaryOutput && !isTelephonyRxOrTx(desc))) {
910 bool forceRouting = !newDevices.isEmpty();
jiabin3ff8d7d2022-12-13 06:27:44 +0000911 if (desc->mUsePreferredMixerAttributes && newDevices != desc->devices()) {
912 // If the device is using preferred mixer attributes, the output need to reopen
913 // with default configuration when the new selected devices are different from
914 // current routing devices.
915 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices);
916 continue;
917 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +0530918 setOutputDevices(__func__, desc, newDevices, forceRouting, 0 /*delayMs*/, nullptr,
Francois Gaffie601801d2021-06-22 13:27:39 +0200919 true /*requiresMuteCheck*/, !forceRouting /*requiresVolumeCheck*/);
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700920 }
921 }
jiabin3ff8d7d2022-12-13 06:27:44 +0000922 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700923
Eric Laurent96d1dda2022-03-14 17:14:19 +0100924 checkLeBroadcastRoutes(wasLeUnicastActive, nullptr, delayMs);
925
Eric Laurente552edb2014-03-10 17:42:56 -0700926 if (isStateInCall(state)) {
927 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent63dea1d2015-07-02 17:10:28 -0700928 // force reevaluating accessibility routing when call starts
jiabinc44b3462022-12-08 12:52:31 -0800929 invalidateStreams({AUDIO_STREAM_ACCESSIBILITY});
Eric Laurente552edb2014-03-10 17:42:56 -0700930 }
931
932 // Flag that ringtone volume must be limited to music volume until we exit MODE_RINGTONE
François Gaffiec005e562018-11-06 15:04:49 +0100933 mLimitRingtoneVolume = (state == AUDIO_MODE_RINGTONE &&
934 isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY));
Eric Laurente552edb2014-03-10 17:42:56 -0700935}
936
Jean-Michel Trivi887a9ed2015-03-31 18:02:24 -0700937audio_mode_t AudioPolicyManager::getPhoneState() {
938 return mEngine->getPhoneState();
939}
940
Eric Laurente0720872014-03-11 09:30:41 -0700941void AudioPolicyManager::setForceUse(audio_policy_force_use_t usage,
François Gaffie11d30102018-11-02 16:09:09 +0100942 audio_policy_forced_cfg_t config)
Eric Laurente552edb2014-03-10 17:42:56 -0700943{
François Gaffie2110e042015-03-24 08:41:51 +0100944 ALOGV("setForceUse() usage %d, config %d, mPhoneState %d", usage, config, mEngine->getPhoneState());
Eric Laurent8dc87a62017-05-16 19:00:40 -0700945 if (config == mEngine->getForceUse(usage)) {
946 return;
947 }
Eric Laurente552edb2014-03-10 17:42:56 -0700948
François Gaffie2110e042015-03-24 08:41:51 +0100949 if (mEngine->setForceUse(usage, config) != NO_ERROR) {
950 ALOGW("setForceUse() could not set force cfg %d for usage %d", config, usage);
951 return;
Eric Laurente552edb2014-03-10 17:42:56 -0700952 }
François Gaffie2110e042015-03-24 08:41:51 +0100953 bool forceVolumeReeval = (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) ||
954 (usage == AUDIO_POLICY_FORCE_FOR_DOCK) ||
955 (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM);
Eric Laurente552edb2014-03-10 17:42:56 -0700956
957 // check for device and output changes triggered by new force usage
Mikhail Naganov37977152018-07-11 15:54:44 -0700958 checkForDeviceAndOutputChanges();
Phil Burk09bc4612016-02-24 15:58:15 -0800959
Eric Laurent22fcda22019-05-17 16:28:47 -0700960 // force client reconnection to reevaluate flag AUDIO_FLAG_AUDIBILITY_ENFORCED
961 if (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM) {
jiabinc44b3462022-12-08 12:52:31 -0800962 invalidateStreams({AUDIO_STREAM_SYSTEM, AUDIO_STREAM_ENFORCED_AUDIBLE});
Eric Laurent22fcda22019-05-17 16:28:47 -0700963 }
964
Eric Laurentdc462862016-07-19 12:29:53 -0700965 //FIXME: workaround for truncated touch sounds
966 // to be removed when the problem is handled by system UI
967 uint32_t delayMs = 0;
Eric Laurentdc462862016-07-19 12:29:53 -0700968 if (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) {
969 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
970 }
Jean-Michel Trivi30857152019-11-01 11:04:15 -0700971
972 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Eric Laurent2517af32020-11-25 15:31:27 +0100973 updateInputRouting();
Eric Laurente552edb2014-03-10 17:42:56 -0700974}
975
Eric Laurente0720872014-03-11 09:30:41 -0700976void AudioPolicyManager::setSystemProperty(const char* property, const char* value)
Eric Laurente552edb2014-03-10 17:42:56 -0700977{
978 ALOGV("setSystemProperty() property %s, value %s", property, value);
979}
980
Dorin Drimusecc9f422022-03-09 17:57:40 +0100981// Find an MSD output profile compatible with the parameters passed.
982// When "directOnly" is set, restrict search to profiles for direct outputs.
983sp<IOProfile> AudioPolicyManager::getMsdProfileForOutput(
984 const DeviceVector& devices,
985 uint32_t samplingRate,
986 audio_format_t format,
987 audio_channel_mask_t channelMask,
988 audio_output_flags_t flags,
989 bool directOnly)
990{
991 flags = getRelevantFlags(flags, directOnly);
992
993 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
994 if (msdModule != nullptr) {
995 // for the msd module check if there are patches to the output devices
996 if (msdHasPatchesToAllDevices(devices.toTypeAddrVector())) {
997 HwModuleCollection modules;
998 modules.add(msdModule);
999 return searchCompatibleProfileHwModules(
1000 modules, getMsdAudioOutDevices(), samplingRate, format, channelMask,
1001 flags, directOnly);
1002 }
1003 }
1004 return nullptr;
1005}
1006
Michael Chana94fbb22018-04-24 14:31:19 +10001007// Find an output profile compatible with the parameters passed. When "directOnly" is set, restrict
1008// search to profiles for direct outputs.
1009sp<IOProfile> AudioPolicyManager::getProfileForOutput(
François Gaffie11d30102018-11-02 16:09:09 +01001010 const DeviceVector& devices,
Michael Chana94fbb22018-04-24 14:31:19 +10001011 uint32_t samplingRate,
1012 audio_format_t format,
1013 audio_channel_mask_t channelMask,
1014 audio_output_flags_t flags,
1015 bool directOnly)
Eric Laurente552edb2014-03-10 17:42:56 -07001016{
Dorin Drimusecc9f422022-03-09 17:57:40 +01001017 flags = getRelevantFlags(flags, directOnly);
1018
1019 return searchCompatibleProfileHwModules(
1020 mHwModules, devices, samplingRate, format, channelMask, flags, directOnly);
1021}
1022
1023audio_output_flags_t AudioPolicyManager::getRelevantFlags (
1024 audio_output_flags_t flags, bool directOnly) {
Michael Chana94fbb22018-04-24 14:31:19 +10001025 if (directOnly) {
Dorin Drimusecc9f422022-03-09 17:57:40 +01001026 // only retain flags that will drive the direct output profile selection
1027 // if explicitly requested
1028 static const uint32_t kRelevantFlags =
Michael Chana94fbb22018-04-24 14:31:19 +10001029 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD |
Dorin Drimusecc9f422022-03-09 17:57:40 +01001030 AUDIO_OUTPUT_FLAG_VOIP_RX | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ);
1031 flags = (audio_output_flags_t)((flags & kRelevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
Michael Chana94fbb22018-04-24 14:31:19 +10001032 }
Dorin Drimusecc9f422022-03-09 17:57:40 +01001033 return flags;
1034}
Eric Laurent861a6282015-05-18 15:40:16 -07001035
Dorin Drimusecc9f422022-03-09 17:57:40 +01001036sp<IOProfile> AudioPolicyManager::searchCompatibleProfileHwModules (
1037 const HwModuleCollection& hwModules,
1038 const DeviceVector& devices,
1039 uint32_t samplingRate,
1040 audio_format_t format,
1041 audio_channel_mask_t channelMask,
1042 audio_output_flags_t flags,
1043 bool directOnly) {
Eric Laurent861a6282015-05-18 15:40:16 -07001044 sp<IOProfile> profile;
Dorin Drimusecc9f422022-03-09 17:57:40 +01001045 for (const auto& hwModule : hwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08001046 for (const auto& curProfile : hwModule->getOutputProfiles()) {
Dorin Drimusecc9f422022-03-09 17:57:40 +01001047 if (!curProfile->isCompatibleProfile(devices,
1048 samplingRate, NULL /*updatedSamplingRate*/,
1049 format, NULL /*updatedFormat*/,
1050 channelMask, NULL /*updatedChannelMask*/,
1051 flags)) {
1052 continue;
1053 }
1054 // reject profiles not corresponding to a device currently available
1055 if (!mAvailableOutputDevices.containsAtLeastOne(curProfile->getSupportedDevices())) {
1056 continue;
1057 }
1058 // reject profiles if connected device does not support codec
1059 if (!curProfile->devicesSupportEncodedFormats(devices.types())) {
1060 continue;
1061 }
1062 if (!directOnly) {
1063 return curProfile;
1064 }
1065
1066 // when searching for direct outputs, if several profiles are compatible, give priority
1067 // to one with offload capability
Patty Huang36028df2022-07-06 00:14:12 +08001068 if (profile != 0 &&
Dorin Drimusecc9f422022-03-09 17:57:40 +01001069 ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0)) {
Eric Laurent861a6282015-05-18 15:40:16 -07001070 continue;
Dorin Drimusecc9f422022-03-09 17:57:40 +01001071 }
1072 profile = curProfile;
1073 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1074 break;
1075 }
Eric Laurente552edb2014-03-10 17:42:56 -07001076 }
1077 }
Eric Laurent861a6282015-05-18 15:40:16 -07001078 return profile;
Eric Laurente552edb2014-03-10 17:42:56 -07001079}
1080
Eric Laurentfa0f6742021-08-17 18:39:44 +02001081sp<IOProfile> AudioPolicyManager::getSpatializerOutputProfile(
Eric Laurent39095982021-08-24 18:29:27 +02001082 const audio_config_t *config __unused, const AudioDeviceTypeAddrVector &devices) const
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001083{
1084 for (const auto& hwModule : mHwModules) {
1085 for (const auto& curProfile : hwModule->getOutputProfiles()) {
Eric Laurent1c5e2e32021-08-18 18:50:28 +02001086 if (curProfile->getFlags() != AUDIO_OUTPUT_FLAG_SPATIALIZER) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001087 continue;
1088 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001089 if (!devices.empty()) {
Eric Laurent0c8f7cc2022-06-24 14:32:36 +02001090 // reject profiles not corresponding to a device currently available
1091 DeviceVector supportedDevices = curProfile->getSupportedDevices();
1092 if (!mAvailableOutputDevices.containsAtLeastOne(supportedDevices)) {
1093 continue;
1094 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001095 if (supportedDevices.getDevicesFromDeviceTypeAddrVec(devices).size()
1096 != devices.size()) {
1097 continue;
1098 }
1099 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001100 ALOGV("%s found profile %s", __func__, curProfile->getName().c_str());
1101 return curProfile;
1102 }
1103 }
1104 return nullptr;
1105}
1106
Eric Laurentf4e63452017-11-06 19:31:46 +00001107audio_io_handle_t AudioPolicyManager::getOutput(audio_stream_type_t stream)
Eric Laurente552edb2014-03-10 17:42:56 -07001108{
François Gaffiec005e562018-11-06 15:04:49 +01001109 DeviceVector devices = mEngine->getOutputDevicesForStream(stream, false /*fromCache*/);
Andy Hungc9901522017-11-10 20:07:54 -08001110
1111 // Note that related method getOutputForAttr() uses getOutputForDevice() not selectOutput().
1112 // We use selectOutput() here since we don't have the desired AudioTrack sample rate,
1113 // format, flags, etc. This may result in some discrepancy for functions that utilize
1114 // getOutput() solely on audio_stream_type such as AudioSystem::getOutputFrameCount()
1115 // and AudioSystem::getOutputSamplingRate().
1116
François Gaffie11d30102018-11-02 16:09:09 +01001117 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Mingyu Shih75563d32023-05-24 04:47:40 +08001118 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
1119 if (stream == AUDIO_STREAM_MUSIC &&
1120 property_get_bool("audio.deep_buffer.media", false /* default_value */)) {
1121 flags = AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
1122 }
1123 const audio_io_handle_t output = selectOutput(outputs, flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001124
François Gaffie11d30102018-11-02 16:09:09 +01001125 ALOGV("getOutput() stream %d selected devices %s, output %d", stream,
1126 devices.toString().c_str(), output);
Eric Laurentf4e63452017-11-06 19:31:46 +00001127 return output;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001128}
1129
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001130status_t AudioPolicyManager::getAudioAttributes(audio_attributes_t *dstAttr,
1131 const audio_attributes_t *srcAttr,
1132 audio_stream_type_t srcStream)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001133{
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001134 if (srcAttr != NULL) {
1135 if (!isValidAttributes(srcAttr)) {
1136 ALOGE("%s invalid attributes: usage=%d content=%d flags=0x%x tags=[%s]",
1137 __func__,
1138 srcAttr->usage, srcAttr->content_type, srcAttr->flags,
1139 srcAttr->tags);
1140 return BAD_VALUE;
1141 }
1142 *dstAttr = *srcAttr;
1143 } else {
1144 if (srcStream < AUDIO_STREAM_MIN || srcStream >= AUDIO_STREAM_PUBLIC_CNT) {
1145 ALOGE("%s: invalid stream type", __func__);
1146 return BAD_VALUE;
1147 }
François Gaffiec005e562018-11-06 15:04:49 +01001148 *dstAttr = mEngine->getAttributesForStreamType(srcStream);
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001149 }
Eric Laurent22fcda22019-05-17 16:28:47 -07001150
1151 // Only honor audibility enforced when required. The client will be
1152 // forced to reconnect if the forced usage changes.
1153 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Mikhail Naganov55773032020-10-01 15:08:13 -07001154 dstAttr->flags = static_cast<audio_flags_mask_t>(
1155 dstAttr->flags & ~AUDIO_FLAG_AUDIBILITY_ENFORCED);
Eric Laurent22fcda22019-05-17 16:28:47 -07001156 }
1157
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001158 return NO_ERROR;
1159}
1160
Kevin Rocard153f92d2018-12-18 18:33:28 -08001161status_t AudioPolicyManager::getOutputForAttrInt(
1162 audio_attributes_t *resultAttr,
1163 audio_io_handle_t *output,
1164 audio_session_t session,
1165 const audio_attributes_t *attr,
1166 audio_stream_type_t *stream,
1167 uid_t uid,
jiabinf1c73972022-04-14 16:28:52 -07001168 audio_config_t *config,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001169 audio_output_flags_t *flags,
1170 audio_port_handle_t *selectedDeviceId,
1171 bool *isRequestedDeviceForExclusiveUse,
Eric Laurentc529cf62020-04-17 18:19:10 -07001172 std::vector<sp<AudioPolicyMix>> *secondaryMixes,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001173 output_type_t *outputType,
jiabinc658e452022-10-21 20:52:21 +00001174 bool *isSpatialized,
1175 bool *isBitPerfect)
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001176{
François Gaffiec005e562018-11-06 15:04:49 +01001177 DeviceVector outputDevices;
Francois Gaffie716e1432019-01-14 16:58:59 +01001178 const audio_port_handle_t requestedPortId = *selectedDeviceId;
François Gaffie11d30102018-11-02 16:09:09 +01001179 DeviceVector msdDevices = getMsdAudioOutDevices();
François Gaffiec005e562018-11-06 15:04:49 +01001180 const sp<DeviceDescriptor> requestedDevice =
1181 mAvailableOutputDevices.getDeviceFromId(requestedPortId);
1182
Eric Laurent8a1095a2019-11-08 14:44:16 -08001183 *outputType = API_OUTPUT_INVALID;
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001184 *isSpatialized = false;
1185
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001186 status_t status = getAudioAttributes(resultAttr, attr, *stream);
1187 if (status != NO_ERROR) {
1188 return status;
Eric Laurent8f42ea12018-08-08 09:08:25 -07001189 }
Kevin Rocardb99cc752019-03-21 20:52:24 -07001190 if (auto it = mAllowedCapturePolicies.find(uid); it != end(mAllowedCapturePolicies)) {
Mikhail Naganov55773032020-10-01 15:08:13 -07001191 resultAttr->flags = static_cast<audio_flags_mask_t>(resultAttr->flags | it->second);
Kevin Rocardb99cc752019-03-21 20:52:24 -07001192 }
François Gaffiec005e562018-11-06 15:04:49 +01001193 *stream = mEngine->getStreamTypeForAttributes(*resultAttr);
Eric Laurent8f42ea12018-08-08 09:08:25 -07001194
François Gaffiec005e562018-11-06 15:04:49 +01001195 ALOGV("%s() attributes=%s stream=%s session %d selectedDeviceId %d", __func__,
1196 toString(*resultAttr).c_str(), toString(*stream).c_str(), session, requestedPortId);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001197
Oscar Azucena873d10f2023-01-12 18:34:42 -08001198 bool usePrimaryOutputFromPolicyMixes = false;
1199
Kevin Rocard153f92d2018-12-18 18:33:28 -08001200 // The primary output is the explicit routing (eg. setPreferredDevice) if specified,
1201 // otherwise, fallback to the dynamic policies, if none match, query the engine.
1202 // Secondary outputs are always found by dynamic policies as the engine do not support them
Eric Laurentc529cf62020-04-17 18:19:10 -07001203 sp<AudioPolicyMix> primaryMix;
Dean Wheatleyd082f472022-02-04 11:10:48 +11001204 const audio_config_base_t clientConfig = {.sample_rate = config->sample_rate,
1205 .channel_mask = config->channel_mask,
1206 .format = config->format,
1207 };
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02001208 status = mPolicyMixes.getOutputForAttr(*resultAttr, clientConfig, uid, session, *flags,
Oscar Azucena873d10f2023-01-12 18:34:42 -08001209 mAvailableOutputDevices, requestedDevice, primaryMix,
1210 secondaryMixes, usePrimaryOutputFromPolicyMixes);
Kevin Rocard94114a22019-04-01 19:38:23 -07001211 if (status != OK) {
1212 return status;
Kevin Rocard153f92d2018-12-18 18:33:28 -08001213 }
Kevin Rocard94114a22019-04-01 19:38:23 -07001214
Kevin Rocard153f92d2018-12-18 18:33:28 -08001215 // FIXME: in case of RENDER policy, the output capabilities should be checked
Dean Wheatleyd082f472022-02-04 11:10:48 +11001216 if ((secondaryMixes != nullptr && !secondaryMixes->empty())
1217 && !audio_is_linear_pcm(config->format)) {
1218 ALOGD("%s: rejecting request as secondary mixes only support pcm", __func__);
Kevin Rocard153f92d2018-12-18 18:33:28 -08001219 return BAD_VALUE;
1220 }
1221 if (usePrimaryOutputFromPolicyMixes) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001222 sp<DeviceDescriptor> deviceDesc =
1223 mAvailableOutputDevices.getDevice(primaryMix->mDeviceType,
1224 primaryMix->mDeviceAddress,
1225 AUDIO_FORMAT_DEFAULT);
1226 sp<SwAudioOutputDescriptor> policyDesc = primaryMix->getOutput();
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001227 bool tryDirectForFlags = policyDesc == nullptr ||
1228 (policyDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT);
1229 // if a direct output can be opened to deliver the track's multi-channel content to the
1230 // output rather than being downmixed by the primary output, then use this direct
1231 // output by by-passing the primary mix if possible, otherwise fall-through to primary
1232 // mix.
1233 bool tryDirectForChannelMask = policyDesc != nullptr
1234 && (audio_channel_count_from_out_mask(policyDesc->getConfig().channel_mask) <
1235 audio_channel_count_from_out_mask(config->channel_mask));
1236 if (deviceDesc != nullptr && (tryDirectForFlags || tryDirectForChannelMask)) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001237 audio_io_handle_t newOutput;
1238 status = openDirectOutput(
1239 *stream, session, config,
1240 (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT),
1241 DeviceVector(deviceDesc), &newOutput);
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001242 if (status == NO_ERROR) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001243 policyDesc = mOutputs.valueFor(newOutput);
1244 primaryMix->setOutput(policyDesc);
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001245 } else if (tryDirectForFlags) {
1246 policyDesc = nullptr;
1247 } // otherwise use primary if available.
Eric Laurentc529cf62020-04-17 18:19:10 -07001248 }
1249 if (policyDesc != nullptr) {
1250 policyDesc->mPolicyMix = primaryMix;
1251 *output = policyDesc->mIoHandle;
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08001252 *selectedDeviceId = deviceDesc != 0 ? deviceDesc->getId() : AUDIO_PORT_HANDLE_NONE;
Eric Laurent8a1095a2019-11-08 14:44:16 -08001253
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08001254 ALOGV("getOutputForAttr() returns output %d", *output);
1255 if (resultAttr->usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
1256 *outputType = API_OUT_MIX_PLAYBACK;
1257 } else {
1258 *outputType = API_OUTPUT_LEGACY;
1259 }
1260 return NO_ERROR;
Eric Laurent8a1095a2019-11-08 14:44:16 -08001261 }
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001262 }
François Gaffiec005e562018-11-06 15:04:49 +01001263 // Virtual sources must always be dynamicaly or explicitly routed
1264 if (resultAttr->usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
1265 ALOGW("getOutputForAttr() no policy mix found for usage AUDIO_USAGE_VIRTUAL_SOURCE");
1266 return BAD_VALUE;
1267 }
1268 // explicit routing managed by getDeviceForStrategy in APM is now handled by engine
1269 // in order to let the choice of the order to future vendor engine
1270 outputDevices = mEngine->getOutputDevicesForAttributes(*resultAttr, requestedDevice, false);
Scott Randolph7b1fd232018-06-18 15:33:03 -07001271
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001272 if ((resultAttr->flags & AUDIO_FLAG_HW_AV_SYNC) != 0) {
Nadav Bar766fb022018-01-07 12:18:03 +02001273 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
Eric Laurent93c3d412014-08-01 14:48:35 -07001274 }
1275
Nadav Barb2f18162018-07-18 13:01:53 +03001276 // Set incall music only if device was explicitly set, and fallback to the device which is
1277 // chosen by the engine if not.
1278 // FIXME: provide a more generic approach which is not device specific and move this back
1279 // to getOutputForDevice.
Nadav Bar20919492018-11-20 10:20:51 +02001280 // TODO: Remove check of AUDIO_STREAM_MUSIC once migration is completed on the app side.
jiabin9a3361e2019-10-01 09:38:30 -07001281 if (outputDevices.onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_TELEPHONY_TX) &&
François Gaffiec005e562018-11-06 15:04:49 +01001282 (*stream == AUDIO_STREAM_MUSIC || resultAttr->usage == AUDIO_USAGE_VOICE_COMMUNICATION) &&
Nadav Barb2f18162018-07-18 13:01:53 +03001283 audio_is_linear_pcm(config->format) &&
Eric Laurent74b71512019-11-06 17:21:57 -08001284 isCallAudioAccessible()) {
Francois Gaffie716e1432019-01-14 16:58:59 +01001285 if (requestedPortId != AUDIO_PORT_HANDLE_NONE) {
Nadav Barb2f18162018-07-18 13:01:53 +03001286 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_INCALL_MUSIC;
François Gaffief579db52018-11-13 11:25:16 +01001287 *isRequestedDeviceForExclusiveUse = true;
Nadav Barb2f18162018-07-18 13:01:53 +03001288 }
1289 }
1290
François Gaffiec005e562018-11-06 15:04:49 +01001291 ALOGV("%s() device %s, sampling rate %d, format %#x, channel mask %#x, flags %#x stream %s",
1292 __func__, outputDevices.toString().c_str(), config->sample_rate, config->format,
1293 config->channel_mask, *flags, toString(*stream).c_str());
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001294
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001295 *output = AUDIO_IO_HANDLE_NONE;
François Gaffie11d30102018-11-02 16:09:09 +01001296 if (!msdDevices.isEmpty()) {
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001297 *output = getOutputForDevices(msdDevices, session, resultAttr, config, flags, isSpatialized);
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001298 if (*output != AUDIO_IO_HANDLE_NONE && setMsdOutputPatches(&outputDevices) == NO_ERROR) {
François Gaffiec005e562018-11-06 15:04:49 +01001299 ALOGV("%s() Using MSD devices %s instead of devices %s",
1300 __func__, msdDevices.toString().c_str(), outputDevices.toString().c_str());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001301 } else {
1302 *output = AUDIO_IO_HANDLE_NONE;
1303 }
1304 }
1305 if (*output == AUDIO_IO_HANDLE_NONE) {
jiabina84c3d32022-12-02 18:59:55 +00001306 sp<PreferredMixerAttributesInfo> info = nullptr;
1307 if (outputDevices.size() == 1) {
1308 info = getPreferredMixerAttributesInfo(
1309 outputDevices.itemAt(0)->getId(),
jiabind9a58d32023-06-01 17:57:30 +00001310 mEngine->getProductStrategyForAttributes(*resultAttr),
1311 true /*activeBitPerfectPreferred*/);
jiabin5eaf0962022-12-20 20:11:38 +00001312 // Only use preferred mixer if the uid matches or the preferred mixer is bit-perfect
1313 // and it is currently active.
1314 if (info != nullptr && info->getUid() != uid &&
1315 ((info->getFlags() & AUDIO_OUTPUT_FLAG_BIT_PERFECT) == AUDIO_OUTPUT_FLAG_NONE ||
1316 info->getActiveClientCount() == 0)) {
jiabina84c3d32022-12-02 18:59:55 +00001317 info = nullptr;
1318 }
1319 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001320 *output = getOutputForDevices(outputDevices, session, resultAttr, config,
jiabina84c3d32022-12-02 18:59:55 +00001321 flags, isSpatialized, info, resultAttr->flags & AUDIO_FLAG_MUTE_HAPTIC);
jiabin5eaf0962022-12-20 20:11:38 +00001322 // The client will be active if the client is currently preferred mixer owner and the
1323 // requested configuration matches the preferred mixer configuration.
jiabinc658e452022-10-21 20:52:21 +00001324 *isBitPerfect = (info != nullptr
1325 && (info->getFlags() & AUDIO_OUTPUT_FLAG_BIT_PERFECT) != AUDIO_OUTPUT_FLAG_NONE
jiabin5eaf0962022-12-20 20:11:38 +00001326 && info->getUid() == uid
1327 && *output != AUDIO_IO_HANDLE_NONE
1328 // When bit-perfect output is selected for the preferred mixer attributes owner,
1329 // only need to consider the config matches.
1330 && mOutputs.valueFor(*output)->isConfigurationMatched(
1331 clientConfig, AUDIO_OUTPUT_FLAG_NONE));
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001332 }
Eric Laurente83b55d2014-11-14 10:06:21 -08001333 if (*output == AUDIO_IO_HANDLE_NONE) {
jiabinf1c73972022-04-14 16:28:52 -07001334 AudioProfileVector profiles;
1335 status_t ret = getProfilesForDevices(outputDevices, profiles, *flags, false /*isInput*/);
1336 if (ret == NO_ERROR && !profiles.empty()) {
Robert Wub98ff1b2023-06-15 22:53:58 +00001337 const auto channels = profiles[0]->getChannels();
1338 if (!channels.empty() && (channels.find(config->channel_mask) == channels.end())) {
1339 config->channel_mask = *channels.begin();
1340 }
1341 const auto sampleRates = profiles[0]->getSampleRates();
1342 if (!sampleRates.empty() &&
1343 (sampleRates.find(config->sample_rate) == sampleRates.end())) {
1344 config->sample_rate = *sampleRates.begin();
1345 }
jiabinf1c73972022-04-14 16:28:52 -07001346 config->format = profiles[0]->getFormat();
1347 }
Eric Laurente83b55d2014-11-14 10:06:21 -08001348 return INVALID_OPERATION;
1349 }
Paul McLeanaa981192015-03-21 09:55:15 -07001350
François Gaffiec005e562018-11-06 15:04:49 +01001351 *selectedDeviceId = getFirstDeviceId(outputDevices);
Michael Chan6fb34492020-12-08 15:44:49 +11001352 for (auto &outputDevice : outputDevices) {
Mikhail Naganov68e3f642023-04-28 13:06:32 -07001353 if (outputDevice->getId() == mConfig->getDefaultOutputDevice()->getId()) {
Michael Chan6fb34492020-12-08 15:44:49 +11001354 *selectedDeviceId = outputDevice->getId();
1355 break;
1356 }
1357 }
Eric Laurent2ac76942017-06-22 17:17:09 -07001358
Eric Laurent8a1095a2019-11-08 14:44:16 -08001359 if (outputDevices.onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_TELEPHONY_TX)) {
1360 *outputType = API_OUTPUT_TELEPHONY_TX;
1361 } else {
1362 *outputType = API_OUTPUT_LEGACY;
1363 }
1364
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001365 ALOGV("%s returns output %d selectedDeviceId %d", __func__, *output, *selectedDeviceId);
1366
1367 return NO_ERROR;
1368}
1369
1370status_t AudioPolicyManager::getOutputForAttr(const audio_attributes_t *attr,
1371 audio_io_handle_t *output,
1372 audio_session_t session,
1373 audio_stream_type_t *stream,
Svet Ganov3e5f14f2021-05-13 22:51:08 +00001374 const AttributionSourceState& attributionSource,
jiabinf1c73972022-04-14 16:28:52 -07001375 audio_config_t *config,
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001376 audio_output_flags_t *flags,
1377 audio_port_handle_t *selectedDeviceId,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001378 audio_port_handle_t *portId,
Eric Laurent8a1095a2019-11-08 14:44:16 -08001379 std::vector<audio_io_handle_t> *secondaryOutputs,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001380 output_type_t *outputType,
jiabinc658e452022-10-21 20:52:21 +00001381 bool *isSpatialized,
1382 bool *isBitPerfect)
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001383{
1384 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
1385 if (*portId != AUDIO_PORT_HANDLE_NONE) {
1386 return INVALID_OPERATION;
1387 }
Philip P. Moltmannbda45752020-07-17 16:41:18 -07001388 const uid_t uid = VALUE_OR_RETURN_STATUS(
Svet Ganov3e5f14f2021-05-13 22:51:08 +00001389 aidl2legacy_int32_t_uid_t(attributionSource.uid));
Francois Gaffie716e1432019-01-14 16:58:59 +01001390 const audio_port_handle_t requestedPortId = *selectedDeviceId;
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001391 audio_attributes_t resultAttr;
François Gaffief579db52018-11-13 11:25:16 +01001392 bool isRequestedDeviceForExclusiveUse = false;
Eric Laurentc529cf62020-04-17 18:19:10 -07001393 std::vector<sp<AudioPolicyMix>> secondaryMixes;
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001394 const sp<DeviceDescriptor> requestedDevice =
1395 mAvailableOutputDevices.getDeviceFromId(requestedPortId);
1396
1397 // Prevent from storing invalid requested device id in clients
1398 const audio_port_handle_t sanitizedRequestedPortId =
1399 requestedDevice != nullptr ? requestedPortId : AUDIO_PORT_HANDLE_NONE;
1400 *selectedDeviceId = sanitizedRequestedPortId;
1401
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001402 status_t status = getOutputForAttrInt(&resultAttr, output, session, attr, stream, uid,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001403 config, flags, selectedDeviceId, &isRequestedDeviceForExclusiveUse,
jiabinc658e452022-10-21 20:52:21 +00001404 secondaryOutputs != nullptr ? &secondaryMixes : nullptr, outputType, isSpatialized,
1405 isBitPerfect);
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001406 if (status != NO_ERROR) {
1407 return status;
1408 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001409 std::vector<wp<SwAudioOutputDescriptor>> weakSecondaryOutputDescs;
Eric Laurentc529cf62020-04-17 18:19:10 -07001410 if (secondaryOutputs != nullptr) {
1411 for (auto &secondaryMix : secondaryMixes) {
1412 sp<SwAudioOutputDescriptor> outputDesc = secondaryMix->getOutput();
1413 if (outputDesc != nullptr &&
1414 outputDesc->mIoHandle != AUDIO_IO_HANDLE_NONE) {
1415 secondaryOutputs->push_back(outputDesc->mIoHandle);
1416 weakSecondaryOutputDescs.push_back(outputDesc);
1417 }
1418 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001419 }
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001420
Eric Laurent8fc147b2018-07-22 19:13:55 -07001421 audio_config_base_t clientConfig = {.sample_rate = config->sample_rate,
Nick Desaulniersa30e3202019-10-18 13:38:23 -07001422 .channel_mask = config->channel_mask,
Eric Laurent8fc147b2018-07-22 19:13:55 -07001423 .format = config->format,
Nick Desaulniersa30e3202019-10-18 13:38:23 -07001424 };
jiabin4ef93452019-09-10 14:29:54 -07001425 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurent8f42ea12018-08-08 09:08:25 -07001426
Eric Laurentc209fe42020-06-05 18:11:23 -07001427 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(*output);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001428 sp<TrackClientDescriptor> clientDesc =
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001429 new TrackClientDescriptor(*portId, uid, session, resultAttr, clientConfig,
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001430 sanitizedRequestedPortId, *stream,
François Gaffiec005e562018-11-06 15:04:49 +01001431 mEngine->getProductStrategyForAttributes(resultAttr),
François Gaffieaaac0fd2018-11-22 17:56:39 +01001432 toVolumeSource(resultAttr),
Kevin Rocard153f92d2018-12-18 18:33:28 -08001433 *flags, isRequestedDeviceForExclusiveUse,
Eric Laurentc209fe42020-06-05 18:11:23 -07001434 std::move(weakSecondaryOutputDescs),
1435 outputDesc->mPolicyMix);
Andy Hung39efb7a2018-09-26 15:39:28 -07001436 outputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001437
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001438 ALOGV("%s() returns output %d requestedPortId %d selectedDeviceId %d for port ID %d", __func__,
1439 *output, requestedPortId, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07001440
Eric Laurente83b55d2014-11-14 10:06:21 -08001441 return NO_ERROR;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001442}
1443
Eric Laurentc529cf62020-04-17 18:19:10 -07001444status_t AudioPolicyManager::openDirectOutput(audio_stream_type_t stream,
1445 audio_session_t session,
1446 const audio_config_t *config,
1447 audio_output_flags_t flags,
1448 const DeviceVector &devices,
1449 audio_io_handle_t *output) {
1450
1451 *output = AUDIO_IO_HANDLE_NONE;
1452
1453 // skip direct output selection if the request can obviously be attached to a mixed output
1454 // and not explicitly requested
1455 if (((flags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
1456 audio_is_linear_pcm(config->format) && config->sample_rate <= SAMPLE_RATE_HZ_MAX &&
1457 audio_channel_count_from_out_mask(config->channel_mask) <= 2) {
1458 return NAME_NOT_FOUND;
1459 }
1460
1461 // Do not allow offloading if one non offloadable effect is enabled or MasterMono is enabled.
1462 // This prevents creating an offloaded track and tearing it down immediately after start
1463 // when audioflinger detects there is an active non offloadable effect.
1464 // FIXME: We should check the audio session here but we do not have it in this context.
1465 // This may prevent offloading in rare situations where effects are left active by apps
1466 // in the background.
1467 sp<IOProfile> profile;
1468 if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) ||
1469 !(mEffects.isNonOffloadableEffectEnabled() || mMasterMono)) {
1470 profile = getProfileForOutput(
1471 devices, config->sample_rate, config->format, config->channel_mask,
1472 flags, true /* directOnly */);
1473 }
1474
1475 if (profile == nullptr) {
1476 return NAME_NOT_FOUND;
1477 }
1478
1479 // exclusive outputs for MMAP and Offload are enforced by different session ids.
1480 for (size_t i = 0; i < mOutputs.size(); i++) {
1481 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
1482 if (!desc->isDuplicated() && (profile == desc->mProfile)) {
1483 // reuse direct output if currently open by the same client
1484 // and configured with same parameters
1485 if ((config->sample_rate == desc->getSamplingRate()) &&
1486 (config->format == desc->getFormat()) &&
1487 (config->channel_mask == desc->getChannelMask()) &&
1488 (session == desc->mDirectClientSession)) {
1489 desc->mDirectOpenCount++;
Eric Laurentfecbceb2021-02-09 14:46:43 +01001490 ALOGV("%s reusing direct output %d for session %d", __func__,
Eric Laurentc529cf62020-04-17 18:19:10 -07001491 mOutputs.keyAt(i), session);
1492 *output = mOutputs.keyAt(i);
1493 return NO_ERROR;
1494 }
1495 }
1496 }
1497
1498 if (!profile->canOpenNewIo()) {
1499 return NAME_NOT_FOUND;
1500 }
1501
1502 sp<SwAudioOutputDescriptor> outputDesc =
1503 new SwAudioOutputDescriptor(profile, mpClientInterface);
1504
Michael Chan6fb34492020-12-08 15:44:49 +11001505 // An MSD patch may be using the only output stream that can service this request. Release
1506 // all MSD patches to prioritize this request over any active output on MSD.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001507 releaseMsdOutputPatches(devices);
Eric Laurentc529cf62020-04-17 18:19:10 -07001508
Eric Laurentf1f22e72021-07-13 14:04:14 +02001509 status_t status =
1510 outputDesc->open(config, nullptr /* mixerConfig */, devices, stream, flags, output);
Eric Laurentc529cf62020-04-17 18:19:10 -07001511
1512 // only accept an output with the requested parameters
1513 if (status != NO_ERROR ||
1514 (config->sample_rate != 0 && config->sample_rate != outputDesc->getSamplingRate()) ||
1515 (config->format != AUDIO_FORMAT_DEFAULT && config->format != outputDesc->getFormat()) ||
1516 (config->channel_mask != 0 && config->channel_mask != outputDesc->getChannelMask())) {
1517 ALOGV("%s failed opening direct output: output %d sample rate %d %d,"
1518 "format %d %d, channel mask %04x %04x", __func__, *output, config->sample_rate,
1519 outputDesc->getSamplingRate(), config->format, outputDesc->getFormat(),
1520 config->channel_mask, outputDesc->getChannelMask());
1521 if (*output != AUDIO_IO_HANDLE_NONE) {
1522 outputDesc->close();
1523 }
1524 // fall back to mixer output if possible when the direct output could not be open
1525 if (audio_is_linear_pcm(config->format) &&
1526 config->sample_rate <= SAMPLE_RATE_HZ_MAX) {
1527 return NAME_NOT_FOUND;
1528 }
1529 *output = AUDIO_IO_HANDLE_NONE;
1530 return BAD_VALUE;
1531 }
1532 outputDesc->mDirectOpenCount = 1;
1533 outputDesc->mDirectClientSession = session;
1534
1535 addOutput(*output, outputDesc);
1536 mPreviousOutputs = mOutputs;
1537 ALOGV("%s returns new direct output %d", __func__, *output);
1538 mpClientInterface->onAudioPortListUpdate();
1539 return NO_ERROR;
1540}
1541
François Gaffie11d30102018-11-02 16:09:09 +01001542audio_io_handle_t AudioPolicyManager::getOutputForDevices(
1543 const DeviceVector &devices,
Kevin Rocard169753c2017-03-06 14:18:23 -08001544 audio_session_t session,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001545 const audio_attributes_t *attr,
Eric Laurentfe231122017-11-17 17:48:06 -08001546 const audio_config_t *config,
jiabine375d412019-02-26 12:54:53 -08001547 audio_output_flags_t *flags,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001548 bool *isSpatialized,
jiabina84c3d32022-12-02 18:59:55 +00001549 sp<PreferredMixerAttributesInfo> prefMixerConfigInfo,
jiabine375d412019-02-26 12:54:53 -08001550 bool forceMutingHaptic)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001551{
Andy Hungc88b0642018-04-27 15:42:35 -07001552 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001553
jiabine375d412019-02-26 12:54:53 -08001554 // Discard haptic channel mask when forcing muting haptic channels.
1555 audio_channel_mask_t channelMask = forceMutingHaptic
Mikhail Naganov55773032020-10-01 15:08:13 -07001556 ? static_cast<audio_channel_mask_t>(config->channel_mask & ~AUDIO_CHANNEL_HAPTIC_ALL)
1557 : config->channel_mask;
jiabine375d412019-02-26 12:54:53 -08001558
Eric Laurente552edb2014-03-10 17:42:56 -07001559 // open a direct output if required by specified parameters
1560 //force direct flag if offload flag is set: offloading implies a direct output stream
1561 // and all common behaviors are driven by checking only the direct flag
1562 // this should normally be set appropriately in the policy configuration file
Nadav Bar766fb022018-01-07 12:18:03 +02001563 if ((*flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1564 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurente552edb2014-03-10 17:42:56 -07001565 }
Nadav Bar766fb022018-01-07 12:18:03 +02001566 if ((*flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
1567 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent93c3d412014-08-01 14:48:35 -07001568 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001569
1570 audio_stream_type_t stream = mEngine->getStreamTypeForAttributes(*attr);
1571
Eric Laurente83b55d2014-11-14 10:06:21 -08001572 // only allow deep buffering for music stream type
1573 if (stream != AUDIO_STREAM_MUSIC) {
Nadav Bar766fb022018-01-07 12:18:03 +02001574 *flags = (audio_output_flags_t)(*flags &~AUDIO_OUTPUT_FLAG_DEEP_BUFFER);
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -07001575 } else if (/* stream == AUDIO_STREAM_MUSIC && */
Nadav Bar766fb022018-01-07 12:18:03 +02001576 *flags == AUDIO_OUTPUT_FLAG_NONE &&
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -07001577 property_get_bool("audio.deep_buffer.media", false /* default_value */)) {
1578 // use DEEP_BUFFER as default output for music stream type
Nadav Bar766fb022018-01-07 12:18:03 +02001579 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
Eric Laurente83b55d2014-11-14 10:06:21 -08001580 }
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -07001581 if (stream == AUDIO_STREAM_TTS) {
Nadav Bar766fb022018-01-07 12:18:03 +02001582 *flags = AUDIO_OUTPUT_FLAG_TTS;
Haynes Mathew George84c621e2017-04-25 11:41:50 -07001583 } else if (stream == AUDIO_STREAM_VOICE_CALL &&
Nadav Bar20919492018-11-20 10:20:51 +02001584 audio_is_linear_pcm(config->format) &&
1585 (*flags & AUDIO_OUTPUT_FLAG_INCALL_MUSIC) == 0) {
Nadav Bar766fb022018-01-07 12:18:03 +02001586 *flags = (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_VOIP_RX |
Haynes Mathew George84c621e2017-04-25 11:41:50 -07001587 AUDIO_OUTPUT_FLAG_DIRECT);
1588 ALOGV("Set VoIP and Direct output flags for PCM format");
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -07001589 }
Eric Laurente552edb2014-03-10 17:42:56 -07001590
Carter Hsua3abb402021-10-26 11:11:20 +08001591 // Attach the Ultrasound flag for the AUDIO_CONTENT_TYPE_ULTRASOUND
1592 if (attr->content_type == AUDIO_CONTENT_TYPE_ULTRASOUND) {
1593 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_ULTRASOUND);
1594 }
1595
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001596 *isSpatialized = false;
Eric Laurentfa0f6742021-08-17 18:39:44 +02001597 if (mSpatializerOutput != nullptr
Andy Hung9dd1a5b2022-05-10 15:39:39 -07001598 && canBeSpatializedInt(attr, config, devices.toTypeAddrVector())) {
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001599 *isSpatialized = true;
Eric Laurentfa0f6742021-08-17 18:39:44 +02001600 return mSpatializerOutput->mIoHandle;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001601 }
1602
Eric Laurentc529cf62020-04-17 18:19:10 -07001603 audio_config_t directConfig = *config;
1604 directConfig.channel_mask = channelMask;
1605 status_t status = openDirectOutput(stream, session, &directConfig, *flags, devices, &output);
1606 if (status != NAME_NOT_FOUND) {
Eric Laurente552edb2014-03-10 17:42:56 -07001607 return output;
1608 }
1609
Eric Laurent14cbfca2016-03-17 09:42:16 -07001610 // A request for HW A/V sync cannot fallback to a mixed output because time
1611 // stamps are embedded in audio data
Phil Burk2d059932018-02-15 15:55:11 -08001612 if ((*flags & (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ)) != 0) {
Eric Laurent14cbfca2016-03-17 09:42:16 -07001613 return AUDIO_IO_HANDLE_NONE;
1614 }
Pierre Couillaude73496b2023-03-06 16:19:05 +00001615 // A request for Tuner cannot fallback to a mixed output
1616 if ((directConfig.offload_info.content_id || directConfig.offload_info.sync_id)) {
1617 return AUDIO_IO_HANDLE_NONE;
1618 }
Eric Laurent14cbfca2016-03-17 09:42:16 -07001619
Eric Laurente552edb2014-03-10 17:42:56 -07001620 // ignoring channel mask due to downmix capability in mixer
1621
1622 // open a non direct output
1623
1624 // for non direct outputs, only PCM is supported
Eric Laurentfe231122017-11-17 17:48:06 -08001625 if (audio_is_linear_pcm(config->format)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001626 // get which output is suitable for the specified stream. The actual
1627 // routing change will happen when startOutput() will be called
François Gaffie11d30102018-11-02 16:09:09 +01001628 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
jiabina84c3d32022-12-02 18:59:55 +00001629 if (prefMixerConfigInfo != nullptr) {
1630 for (audio_io_handle_t outputHandle : outputs) {
1631 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(outputHandle);
1632 if (outputDesc->mProfile == prefMixerConfigInfo->getProfile()) {
1633 output = outputHandle;
1634 break;
1635 }
1636 }
1637 if (output == AUDIO_IO_HANDLE_NONE) {
1638 // No output open with the preferred profile. Open a new one.
1639 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
1640 config.channel_mask = prefMixerConfigInfo->getConfigBase().channel_mask;
1641 config.sample_rate = prefMixerConfigInfo->getConfigBase().sample_rate;
1642 config.format = prefMixerConfigInfo->getConfigBase().format;
1643 sp<SwAudioOutputDescriptor> preferredOutput = openOutputWithProfileAndDevice(
1644 prefMixerConfigInfo->getProfile(), devices, nullptr /*mixerConfig*/,
1645 &config, prefMixerConfigInfo->getFlags());
1646 if (preferredOutput == nullptr) {
1647 ALOGE("%s failed to open output with preferred mixer config", __func__);
1648 } else {
1649 output = preferredOutput->mIoHandle;
1650 }
1651 }
1652 } else {
1653 // at this stage we should ignore the DIRECT flag as no direct output could be
1654 // found earlier
1655 *flags = (audio_output_flags_t) (*flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
1656 output = selectOutput(
1657 outputs, *flags, config->format, channelMask, config->sample_rate, session);
1658 }
Eric Laurente552edb2014-03-10 17:42:56 -07001659 }
François Gaffie11d30102018-11-02 16:09:09 +01001660 ALOGW_IF((output == 0), "getOutputForDevices() could not find output for stream %d, "
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001661 "sampling rate %d, format %#x, channels %#x, flags %#x",
jiabine375d412019-02-26 12:54:53 -08001662 stream, config->sample_rate, config->format, channelMask, *flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001663
Eric Laurente552edb2014-03-10 17:42:56 -07001664 return output;
1665}
1666
Mikhail Naganovf02f3672018-11-09 12:44:16 -08001667sp<DeviceDescriptor> AudioPolicyManager::getMsdAudioInDevice() const {
François Gaffie11d30102018-11-02 16:09:09 +01001668 auto msdInDevices = mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1669 mAvailableInputDevices);
1670 return msdInDevices.isEmpty()? nullptr : msdInDevices.itemAt(0);
1671}
1672
1673DeviceVector AudioPolicyManager::getMsdAudioOutDevices() const {
1674 return mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1675 mAvailableOutputDevices);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001676}
1677
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001678const AudioPatchCollection AudioPolicyManager::getMsdOutputPatches() const {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001679 AudioPatchCollection msdPatches;
Mikhail Naganov86112352018-10-04 09:02:49 -07001680 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1681 if (msdModule != 0) {
1682 for (size_t i = 0; i < mAudioPatches.size(); ++i) {
1683 sp<AudioPatch> patch = mAudioPatches.valueAt(i);
1684 for (size_t j = 0; j < patch->mPatch.num_sources; ++j) {
1685 const struct audio_port_config *source = &patch->mPatch.sources[j];
1686 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
1687 source->ext.device.hw_module == msdModule->getHandle()) {
François Gaffieafd4cea2019-11-18 15:50:22 +01001688 msdPatches.addAudioPatch(patch->getHandle(), patch);
Mikhail Naganov86112352018-10-04 09:02:49 -07001689 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001690 }
1691 }
1692 }
1693 return msdPatches;
1694}
1695
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02001696bool AudioPolicyManager::isMsdPatch(const audio_patch_handle_t &handle) const {
1697 ssize_t index = mAudioPatches.indexOfKey(handle);
1698 if (index < 0) {
1699 return false;
1700 }
1701 const sp<AudioPatch> patch = mAudioPatches.valueAt(index);
1702 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1703 if (msdModule == nullptr) {
1704 return false;
1705 }
1706 const struct audio_port_config *sink = &patch->mPatch.sinks[0];
1707 if (getMsdAudioOutDevices().contains(mAvailableOutputDevices.getDeviceFromId(sink->id))) {
1708 return true;
1709 }
1710 index = getMsdOutputPatches().indexOfKey(handle);
1711 if (index < 0) {
1712 return false;
1713 }
1714 return true;
1715}
1716
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001717status_t AudioPolicyManager::getMsdProfiles(bool hwAvSync,
1718 const InputProfileCollection &inputProfiles,
1719 const OutputProfileCollection &outputProfiles,
1720 const sp<DeviceDescriptor> &sourceDevice,
1721 const sp<DeviceDescriptor> &sinkDevice,
1722 AudioProfileVector& sourceProfiles,
1723 AudioProfileVector& sinkProfiles) const {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001724 if (inputProfiles.isEmpty()) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001725 ALOGE("%s() no input profiles for source module", __func__);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001726 return NO_INIT;
1727 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001728 if (outputProfiles.isEmpty()) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001729 ALOGE("%s() no output profiles for sink module", __func__);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001730 return NO_INIT;
1731 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001732 for (const auto &inProfile : inputProfiles) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001733 if (hwAvSync == ((inProfile->getFlags() & AUDIO_INPUT_FLAG_HW_AV_SYNC) != 0) &&
1734 inProfile->supportsDevice(sourceDevice)) {
1735 appendAudioProfiles(sourceProfiles, inProfile->getAudioProfiles());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001736 }
1737 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001738 for (const auto &outProfile : outputProfiles) {
Michael Chan6fb34492020-12-08 15:44:49 +11001739 if (hwAvSync == ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) &&
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001740 outProfile->supportsDevice(sinkDevice)) {
1741 appendAudioProfiles(sinkProfiles, outProfile->getAudioProfiles());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001742 }
1743 }
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001744 return NO_ERROR;
1745}
1746
1747status_t AudioPolicyManager::getBestMsdConfig(bool hwAvSync,
1748 const AudioProfileVector &sourceProfiles, const AudioProfileVector &sinkProfiles,
1749 audio_port_config *sourceConfig, audio_port_config *sinkConfig) const
1750{
Dean Wheatley16809da2022-12-09 14:55:46 +11001751 // Compressed formats for MSD module, ordered from most preferred to least preferred.
1752 static const std::vector<audio_format_t> formatsOrder = {{
1753 AUDIO_FORMAT_IEC60958, AUDIO_FORMAT_MAT_2_1, AUDIO_FORMAT_MAT_2_0, AUDIO_FORMAT_E_AC3,
1754 AUDIO_FORMAT_AC3, AUDIO_FORMAT_PCM_16_BIT }};
1755 static const std::vector<audio_channel_mask_t> channelMasksOrder = [](){
1756 // Channel position masks for MSD module, 3D > 2D > 1D ordering (most preferred to least
1757 // preferred).
1758 std::vector<audio_channel_mask_t> masks = {{
1759 AUDIO_CHANNEL_OUT_3POINT1POINT2, AUDIO_CHANNEL_OUT_3POINT0POINT2,
1760 AUDIO_CHANNEL_OUT_2POINT1POINT2, AUDIO_CHANNEL_OUT_2POINT0POINT2,
1761 AUDIO_CHANNEL_OUT_5POINT1, AUDIO_CHANNEL_OUT_STEREO }};
1762 // insert index masks (higher counts most preferred) as preferred over position masks
1763 for (int i = 1; i <= AUDIO_CHANNEL_COUNT_MAX; i++) {
1764 masks.insert(
1765 masks.begin(), audio_channel_mask_for_index_assignment_from_count(i));
1766 }
1767 return masks;
1768 }();
1769
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001770 struct audio_config_base bestSinkConfig;
Dean Wheatley16809da2022-12-09 14:55:46 +11001771 status_t result = findBestMatchingOutputConfig(sourceProfiles, sinkProfiles, formatsOrder,
1772 channelMasksOrder, true /*preferHigherSamplingRates*/, bestSinkConfig);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001773 if (result != NO_ERROR) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001774 ALOGD("%s() no matching config found for sink, hwAvSync: %d",
1775 __func__, hwAvSync);
Greg Kaiser83289652018-07-30 06:13:57 -07001776 return result;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001777 }
1778 sinkConfig->sample_rate = bestSinkConfig.sample_rate;
1779 sinkConfig->channel_mask = bestSinkConfig.channel_mask;
1780 sinkConfig->format = bestSinkConfig.format;
1781 // For encoded streams force direct flag to prevent downstream mixing.
1782 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1783 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_DIRECT);
Dean Wheatley5c9f0832019-11-21 13:39:31 +11001784 if (audio_is_iec61937_compatible(sinkConfig->format)) {
1785 // For formats compatible with IEC61937 encapsulation, assume that
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001786 // the input is IEC61937 framed (for proportional buffer sizing).
Dean Wheatley5c9f0832019-11-21 13:39:31 +11001787 // Add the AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO flag so downstream HAL can distinguish between
1788 // raw and IEC61937 framed streams.
1789 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1790 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO);
1791 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001792 sourceConfig->sample_rate = bestSinkConfig.sample_rate;
1793 // Specify exact channel mask to prevent guessing by bit count in PatchPanel.
Dean Wheatley16809da2022-12-09 14:55:46 +11001794 sourceConfig->channel_mask =
1795 audio_channel_mask_get_representation(bestSinkConfig.channel_mask)
1796 == AUDIO_CHANNEL_REPRESENTATION_INDEX ?
1797 bestSinkConfig.channel_mask : audio_channel_mask_out_to_in(bestSinkConfig.channel_mask);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001798 sourceConfig->format = bestSinkConfig.format;
1799 // Copy input stream directly without any processing (e.g. resampling).
1800 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1801 sourceConfig->flags.input | AUDIO_INPUT_FLAG_DIRECT);
1802 if (hwAvSync) {
1803 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1804 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
1805 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1806 sourceConfig->flags.input | AUDIO_INPUT_FLAG_HW_AV_SYNC);
1807 }
1808 const unsigned int config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE |
1809 AUDIO_PORT_CONFIG_CHANNEL_MASK | AUDIO_PORT_CONFIG_FORMAT | AUDIO_PORT_CONFIG_FLAGS;
1810 sinkConfig->config_mask |= config_mask;
1811 sourceConfig->config_mask |= config_mask;
1812 return NO_ERROR;
1813}
1814
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001815PatchBuilder AudioPolicyManager::buildMsdPatch(bool msdIsSource,
1816 const sp<DeviceDescriptor> &device) const
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001817{
1818 PatchBuilder patchBuilder;
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001819 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1820 ALOG_ASSERT(msdModule != nullptr, "MSD module not available");
1821 sp<HwModule> deviceModule = mHwModules.getModuleForDevice(device, AUDIO_FORMAT_DEFAULT);
1822 if (deviceModule == nullptr) {
1823 ALOGE("%s() unable to get module for %s", __func__, device->toString().c_str());
1824 return patchBuilder;
1825 }
1826 const InputProfileCollection inputProfiles = msdIsSource ?
1827 msdModule->getInputProfiles() : deviceModule->getInputProfiles();
1828 const OutputProfileCollection outputProfiles = msdIsSource ?
1829 deviceModule->getOutputProfiles() : msdModule->getOutputProfiles();
1830
1831 const sp<DeviceDescriptor> sourceDevice = msdIsSource ? getMsdAudioInDevice() : device;
1832 const sp<DeviceDescriptor> sinkDevice = msdIsSource ?
1833 device : getMsdAudioOutDevices().itemAt(0);
1834 patchBuilder.addSource(sourceDevice).addSink(sinkDevice);
1835
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001836 audio_port_config sourceConfig = patchBuilder.patch()->sources[0];
1837 audio_port_config sinkConfig = patchBuilder.patch()->sinks[0];
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001838 AudioProfileVector sourceProfiles;
1839 AudioProfileVector sinkProfiles;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001840 // TODO: Figure out whether MSD module has HW_AV_SYNC flag set in the AP config file.
1841 // For now, we just forcefully try with HwAvSync first.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001842 for (auto hwAvSync : { true, false }) {
1843 if (getMsdProfiles(hwAvSync, inputProfiles, outputProfiles, sourceDevice, sinkDevice,
1844 sourceProfiles, sinkProfiles) != NO_ERROR) {
1845 continue;
1846 }
1847 if (getBestMsdConfig(hwAvSync, sourceProfiles, sinkProfiles, &sourceConfig,
1848 &sinkConfig) == NO_ERROR) {
1849 // Found a matching config. Re-create PatchBuilder with this config.
1850 return (PatchBuilder()).addSource(sourceConfig).addSink(sinkConfig);
1851 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001852 }
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001853 ALOGV("%s() no matching config found. Fall through to default PCM patch"
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001854 " supporting PCM format conversion.", __func__);
1855 return patchBuilder;
1856}
1857
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001858status_t AudioPolicyManager::setMsdOutputPatches(const DeviceVector *outputDevices) {
Michael Chan6fb34492020-12-08 15:44:49 +11001859 DeviceVector devices;
1860 if (outputDevices != nullptr && outputDevices->size() > 0) {
1861 devices.add(*outputDevices);
1862 } else {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001863 // Use media strategy for unspecified output device. This should only
1864 // occur on checkForDeviceAndOutputChanges(). Device connection events may
1865 // therefore invalidate explicit routing requests.
Michael Chan6fb34492020-12-08 15:44:49 +11001866 devices = mEngine->getOutputDevicesForAttributes(
François Gaffiec005e562018-11-06 15:04:49 +01001867 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
Michael Chan6fb34492020-12-08 15:44:49 +11001868 LOG_ALWAYS_FATAL_IF(devices.isEmpty(), "no output device to set MSD patch");
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001869 }
Michael Chan6fb34492020-12-08 15:44:49 +11001870 std::vector<PatchBuilder> patchesToCreate;
1871 for (auto i = 0u; i < devices.size(); ++i) {
1872 ALOGV("%s() for device %s", __func__, devices[i]->toString().c_str());
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001873 patchesToCreate.push_back(buildMsdPatch(true /*msdIsSource*/, devices[i]));
Michael Chan6fb34492020-12-08 15:44:49 +11001874 }
1875 // Retain only the MSD patches associated with outputDevices request.
1876 // Tear down the others, and create new ones as needed.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001877 AudioPatchCollection patchesToRemove = getMsdOutputPatches();
Michael Chan6fb34492020-12-08 15:44:49 +11001878 for (auto it = patchesToCreate.begin(); it != patchesToCreate.end(); ) {
1879 auto retainedPatch = false;
1880 for (auto i = 0u; i < patchesToRemove.size(); ++i) {
1881 if (audio_patches_are_equal(it->patch(), &patchesToRemove[i]->mPatch)) {
1882 patchesToRemove.removeItemsAt(i);
1883 retainedPatch = true;
1884 break;
1885 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001886 }
Michael Chan6fb34492020-12-08 15:44:49 +11001887 if (retainedPatch) {
1888 it = patchesToCreate.erase(it);
1889 continue;
1890 }
1891 ++it;
1892 }
1893 if (patchesToCreate.size() == 0 && patchesToRemove.size() == 0) {
1894 return NO_ERROR;
1895 }
1896 for (auto i = 0u; i < patchesToRemove.size(); ++i) {
1897 auto &currentPatch = patchesToRemove.valueAt(i);
François Gaffieafd4cea2019-11-18 15:50:22 +01001898 releaseAudioPatch(currentPatch->getHandle(), mUidCached);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001899 }
Michael Chan6fb34492020-12-08 15:44:49 +11001900 status_t status = NO_ERROR;
1901 for (const auto &p : patchesToCreate) {
1902 auto currStatus = installPatch(__func__, -1 /*index*/, nullptr /*patchHandle*/,
1903 p.patch(), 0 /*delayMs*/, mUidCached, nullptr /*patchDescPtr*/);
1904 char message[256];
1905 snprintf(message, sizeof(message), "%s() %s: creating MSD patch from device:IN_BUS to "
1906 "device:%#x (format:%#x channels:%#x samplerate:%d)", __func__,
1907 currStatus == NO_ERROR ? "Success" : "Error",
1908 p.patch()->sinks[0].ext.device.type, p.patch()->sources[0].format,
1909 p.patch()->sources[0].channel_mask, p.patch()->sources[0].sample_rate);
1910 if (currStatus == NO_ERROR) {
1911 ALOGD("%s", message);
1912 } else {
1913 ALOGE("%s", message);
1914 if (status == NO_ERROR) {
1915 status = currStatus;
1916 }
1917 }
1918 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001919 return status;
1920}
1921
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001922void AudioPolicyManager::releaseMsdOutputPatches(const DeviceVector& devices) {
1923 AudioPatchCollection msdPatches = getMsdOutputPatches();
Michael Chan6fb34492020-12-08 15:44:49 +11001924 for (size_t i = 0; i < msdPatches.size(); i++) {
1925 const auto& patch = msdPatches[i];
1926 for (size_t j = 0; j < patch->mPatch.num_sinks; ++j) {
1927 const struct audio_port_config *sink = &patch->mPatch.sinks[j];
1928 if (sink->type == AUDIO_PORT_TYPE_DEVICE && devices.getDevice(sink->ext.device.type,
1929 String8(sink->ext.device.address), AUDIO_FORMAT_DEFAULT) != nullptr) {
1930 releaseAudioPatch(patch->getHandle(), mUidCached);
1931 break;
1932 }
1933 }
1934 }
1935}
1936
Dorin Drimus94d94412022-02-02 09:05:02 +01001937bool AudioPolicyManager::msdHasPatchesToAllDevices(const AudioDeviceTypeAddrVector& devices) {
Mikhail Naganov68e3f642023-04-28 13:06:32 -07001938 DeviceVector devicesToCheck =
1939 mConfig->getOutputDevices().getDevicesFromDeviceTypeAddrVec(devices);
Dorin Drimus94d94412022-02-02 09:05:02 +01001940 AudioPatchCollection msdPatches = getMsdOutputPatches();
1941 for (size_t i = 0; i < msdPatches.size(); i++) {
1942 const auto& patch = msdPatches[i];
1943 for (size_t j = 0; j < patch->mPatch.num_sinks; ++j) {
1944 const struct audio_port_config *sink = &patch->mPatch.sinks[j];
1945 if (sink->type == AUDIO_PORT_TYPE_DEVICE) {
1946 const auto& foundDevice = devicesToCheck.getDevice(
1947 sink->ext.device.type, String8(sink->ext.device.address), AUDIO_FORMAT_DEFAULT);
1948 if (foundDevice != nullptr) {
1949 devicesToCheck.remove(foundDevice);
1950 if (devicesToCheck.isEmpty()) {
1951 return true;
1952 }
1953 }
1954 }
1955 }
1956 }
1957 return false;
1958}
1959
Eric Laurente0720872014-03-11 09:30:41 -07001960audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
jiabinebb6af42020-06-09 17:31:17 -07001961 audio_output_flags_t flags,
1962 audio_format_t format,
1963 audio_channel_mask_t channelMask,
1964 uint32_t samplingRate,
1965 audio_session_t sessionId)
Eric Laurente552edb2014-03-10 17:42:56 -07001966{
Eric Laurent16c66dd2019-05-01 17:54:10 -07001967 LOG_ALWAYS_FATAL_IF(!(format == AUDIO_FORMAT_INVALID || audio_is_linear_pcm(format)),
1968 "%s called with format %#x", __func__, format);
1969
jiabinebb6af42020-06-09 17:31:17 -07001970 // Return the output that haptic-generating attached to when 1) session id is specified,
1971 // 2) haptic-generating effect exists for given session id and 3) the output that
1972 // haptic-generating effect attached to is in given outputs.
1973 if (sessionId != AUDIO_SESSION_NONE) {
1974 audio_io_handle_t hapticGeneratingOutput = mEffects.getIoForSession(
1975 sessionId, FX_IID_HAPTICGENERATOR);
1976 if (outputs.indexOf(hapticGeneratingOutput) >= 0) {
1977 return hapticGeneratingOutput;
1978 }
1979 }
1980
Eric Laurent16c66dd2019-05-01 17:54:10 -07001981 // Flags disqualifying an output: the match must happen before calling selectOutput()
1982 static const audio_output_flags_t kExcludedFlags = (audio_output_flags_t)
1983 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ | AUDIO_OUTPUT_FLAG_DIRECT);
1984
1985 // Flags expressing a functional request: must be honored in priority over
1986 // other criteria
1987 static const audio_output_flags_t kFunctionalFlags = (audio_output_flags_t)
1988 (AUDIO_OUTPUT_FLAG_VOIP_RX | AUDIO_OUTPUT_FLAG_INCALL_MUSIC |
Eric Laurente28c66d2022-01-21 13:40:41 +01001989 AUDIO_OUTPUT_FLAG_TTS | AUDIO_OUTPUT_FLAG_DIRECT_PCM | AUDIO_OUTPUT_FLAG_ULTRASOUND |
1990 AUDIO_OUTPUT_FLAG_SPATIALIZER);
Eric Laurent16c66dd2019-05-01 17:54:10 -07001991 // Flags expressing a performance request: have lower priority than serving
1992 // requested sampling rate or channel mask
1993 static const audio_output_flags_t kPerformanceFlags = (audio_output_flags_t)
1994 (AUDIO_OUTPUT_FLAG_FAST | AUDIO_OUTPUT_FLAG_DEEP_BUFFER |
1995 AUDIO_OUTPUT_FLAG_RAW | AUDIO_OUTPUT_FLAG_SYNC);
1996
1997 const audio_output_flags_t functionalFlags =
1998 (audio_output_flags_t)(flags & kFunctionalFlags);
1999 const audio_output_flags_t performanceFlags =
2000 (audio_output_flags_t)(flags & kPerformanceFlags);
2001
2002 audio_io_handle_t bestOutput = (outputs.size() == 0) ? AUDIO_IO_HANDLE_NONE : outputs[0];
2003
Eric Laurente552edb2014-03-10 17:42:56 -07002004 // select one output among several that provide a path to a particular device or set of
François Gaffie11d30102018-11-02 16:09:09 +01002005 // devices (the list was previously build by getOutputsForDevices()).
Eric Laurente552edb2014-03-10 17:42:56 -07002006 // The priority is as follows:
jiabin40573322018-11-08 12:08:02 -08002007 // 1: the output supporting haptic playback when requesting haptic playback
Eric Laurent16c66dd2019-05-01 17:54:10 -07002008 // 2: the output with the highest number of requested functional flags
Carter Hsu199f1892021-10-15 15:47:29 +08002009 // with tiebreak preferring the minimum number of extra functional flags
2010 // (see b/200293124, the incorrect selection of AUDIO_OUTPUT_FLAG_VOIP_RX).
Eric Laurent16c66dd2019-05-01 17:54:10 -07002011 // 3: the output supporting the exact channel mask
2012 // 4: the output with a higher channel count than requested
jiabinb12a6da2022-06-03 20:48:18 +00002013 // 5: the output with the highest sampling rate if the requested sample rate is
2014 // greater than default sampling rate
Eric Laurent16c66dd2019-05-01 17:54:10 -07002015 // 6: the output with the highest number of requested performance flags
2016 // 7: the output with the bit depth the closest to the requested one
2017 // 8: the primary output
2018 // 9: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07002019
Eric Laurent16c66dd2019-05-01 17:54:10 -07002020 // matching criteria values in priority order for best matching output so far
2021 std::vector<uint32_t> bestMatchCriteria(8, 0);
Eric Laurente552edb2014-03-10 17:42:56 -07002022
Eric Laurent16c66dd2019-05-01 17:54:10 -07002023 const uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
2024 const uint32_t hapticChannelCount = audio_channel_count_from_out_mask(
2025 channelMask & AUDIO_CHANNEL_HAPTIC_ALL);
Eric Laurente78b6762018-12-19 16:29:01 -08002026
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002027 for (audio_io_handle_t output : outputs) {
2028 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent16c66dd2019-05-01 17:54:10 -07002029 // matching criteria values in priority order for current output
2030 std::vector<uint32_t> currentMatchCriteria(8, 0);
jiabin40573322018-11-08 12:08:02 -08002031
Eric Laurent16c66dd2019-05-01 17:54:10 -07002032 if (outputDesc->isDuplicated()) {
2033 continue;
2034 }
2035 if ((kExcludedFlags & outputDesc->mFlags) != 0) {
2036 continue;
2037 }
Eric Laurent8838a382014-09-08 16:44:28 -07002038
Eric Laurent16c66dd2019-05-01 17:54:10 -07002039 // If haptic channel is specified, use the haptic output if present.
2040 // When using haptic output, same audio format and sample rate are required.
2041 const uint32_t outputHapticChannelCount = audio_channel_count_from_out_mask(
jiabin5740f082019-08-19 15:08:30 -07002042 outputDesc->getChannelMask() & AUDIO_CHANNEL_HAPTIC_ALL);
Eric Laurent16c66dd2019-05-01 17:54:10 -07002043 if ((hapticChannelCount == 0) != (outputHapticChannelCount == 0)) {
2044 continue;
2045 }
2046 if (outputHapticChannelCount >= hapticChannelCount
jiabin5740f082019-08-19 15:08:30 -07002047 && format == outputDesc->getFormat()
2048 && samplingRate == outputDesc->getSamplingRate()) {
Eric Laurent16c66dd2019-05-01 17:54:10 -07002049 currentMatchCriteria[0] = outputHapticChannelCount;
2050 }
2051
2052 // functional flags match
Carter Hsu199f1892021-10-15 15:47:29 +08002053 const int matchingFunctionalFlags =
2054 __builtin_popcount(outputDesc->mFlags & functionalFlags);
2055 const int totalFunctionalFlags =
2056 __builtin_popcount(outputDesc->mFlags & kFunctionalFlags);
2057 // Prefer matching functional flags, but subtract unnecessary functional flags.
2058 currentMatchCriteria[1] = 100 * (matchingFunctionalFlags + 1) - totalFunctionalFlags;
Eric Laurent16c66dd2019-05-01 17:54:10 -07002059
2060 // channel mask and channel count match
jiabin5740f082019-08-19 15:08:30 -07002061 uint32_t outputChannelCount = audio_channel_count_from_out_mask(
2062 outputDesc->getChannelMask());
Eric Laurent16c66dd2019-05-01 17:54:10 -07002063 if (channelMask != AUDIO_CHANNEL_NONE && channelCount > 2 &&
2064 channelCount <= outputChannelCount) {
2065 if ((audio_channel_mask_get_representation(channelMask) ==
jiabin5740f082019-08-19 15:08:30 -07002066 audio_channel_mask_get_representation(outputDesc->getChannelMask())) &&
2067 ((channelMask & outputDesc->getChannelMask()) == channelMask)) {
Eric Laurent16c66dd2019-05-01 17:54:10 -07002068 currentMatchCriteria[2] = outputChannelCount;
Eric Laurente552edb2014-03-10 17:42:56 -07002069 }
Eric Laurent16c66dd2019-05-01 17:54:10 -07002070 currentMatchCriteria[3] = outputChannelCount;
2071 }
2072
2073 // sampling rate match
jiabinb12a6da2022-06-03 20:48:18 +00002074 if (samplingRate > SAMPLE_RATE_HZ_DEFAULT) {
jiabin5740f082019-08-19 15:08:30 -07002075 currentMatchCriteria[4] = outputDesc->getSamplingRate();
Eric Laurent16c66dd2019-05-01 17:54:10 -07002076 }
2077
2078 // performance flags match
2079 currentMatchCriteria[5] = popcount(outputDesc->mFlags & performanceFlags);
2080
2081 // format match
2082 if (format != AUDIO_FORMAT_INVALID) {
2083 currentMatchCriteria[6] =
jiabin4ef93452019-09-10 14:29:54 -07002084 PolicyAudioPort::kFormatDistanceMax -
2085 PolicyAudioPort::formatDistance(format, outputDesc->getFormat());
Eric Laurent16c66dd2019-05-01 17:54:10 -07002086 }
2087
2088 // primary output match
2089 currentMatchCriteria[7] = outputDesc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY;
2090
2091 // compare match criteria by priority then value
2092 if (std::lexicographical_compare(bestMatchCriteria.begin(), bestMatchCriteria.end(),
2093 currentMatchCriteria.begin(), currentMatchCriteria.end())) {
2094 bestMatchCriteria = currentMatchCriteria;
2095 bestOutput = output;
2096
2097 std::stringstream result;
2098 std::copy(bestMatchCriteria.begin(), bestMatchCriteria.end(),
2099 std::ostream_iterator<int>(result, " "));
2100 ALOGV("%s new bestOutput %d criteria %s",
2101 __func__, bestOutput, result.str().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07002102 }
2103 }
2104
Eric Laurent16c66dd2019-05-01 17:54:10 -07002105 return bestOutput;
Eric Laurente552edb2014-03-10 17:42:56 -07002106}
2107
Eric Laurent8fc147b2018-07-22 19:13:55 -07002108status_t AudioPolicyManager::startOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002109{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002110 ALOGV("%s portId %d", __FUNCTION__, portId);
2111
2112 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2113 if (outputDesc == 0) {
2114 ALOGW("startOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002115 return BAD_VALUE;
2116 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002117 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002118
Eric Laurent8fc147b2018-07-22 19:13:55 -07002119 ALOGV("startOutput() output %d, stream %d, session %d",
Eric Laurent97ac8712018-07-27 18:59:02 -07002120 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurentc75307b2015-03-17 15:29:32 -07002121
Eric Laurent733ce942017-12-07 12:18:25 -08002122 status_t status = outputDesc->start();
2123 if (status != NO_ERROR) {
2124 return status;
Eric Laurent3974e3b2017-12-07 17:58:43 -08002125 }
2126
Eric Laurent97ac8712018-07-27 18:59:02 -07002127 uint32_t delayMs;
2128 status = startSource(outputDesc, client, &delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07002129
2130 if (status != NO_ERROR) {
Eric Laurent733ce942017-12-07 12:18:25 -08002131 outputDesc->stop();
jiabin3ff8d7d2022-12-13 06:27:44 +00002132 if (status == DEAD_OBJECT) {
2133 sp<SwAudioOutputDescriptor> desc =
2134 reopenOutput(outputDesc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
2135 if (desc == nullptr) {
2136 // This is not common, it may indicate something wrong with the HAL.
2137 ALOGE("%s unable to open output with default config", __func__);
2138 return status;
2139 }
2140 desc->mUsePreferredMixerAttributes = true;
2141 }
Eric Laurent8c7e6da2015-04-21 17:37:00 -07002142 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07002143 }
jiabina84c3d32022-12-02 18:59:55 +00002144
2145 // If the client is the first one active on preferred mixer parameters, reopen the output
2146 // if the current mixer parameters doesn't match the preferred one.
2147 if (outputDesc->devices().size() == 1) {
2148 sp<PreferredMixerAttributesInfo> info = getPreferredMixerAttributesInfo(
2149 outputDesc->devices()[0]->getId(), client->strategy());
2150 if (info != nullptr && info->getUid() == client->uid()) {
2151 if (info->getActiveClientCount() == 0 && !outputDesc->isConfigurationMatched(
2152 info->getConfigBase(), info->getFlags())) {
2153 stopSource(outputDesc, client);
2154 outputDesc->stop();
2155 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
2156 config.channel_mask = info->getConfigBase().channel_mask;
2157 config.sample_rate = info->getConfigBase().sample_rate;
2158 config.format = info->getConfigBase().format;
jiabin3ff8d7d2022-12-13 06:27:44 +00002159 sp<SwAudioOutputDescriptor> desc =
2160 reopenOutput(outputDesc, &config, info->getFlags(), __func__);
2161 if (desc == nullptr) {
2162 return BAD_VALUE;
jiabina84c3d32022-12-02 18:59:55 +00002163 }
jiabin3ff8d7d2022-12-13 06:27:44 +00002164 desc->mUsePreferredMixerAttributes = true;
jiabina84c3d32022-12-02 18:59:55 +00002165 // Intentionally return error to let the client side resending request for
2166 // creating and starting.
2167 return DEAD_OBJECT;
2168 }
2169 info->increaseActiveClient();
jiabine3d1f552023-06-14 17:42:17 +00002170 if (info->getActiveClientCount() == 1 &&
2171 (info->getFlags() & AUDIO_OUTPUT_FLAG_BIT_PERFECT) != AUDIO_OUTPUT_FLAG_NONE) {
2172 // If it is first bit-perfect client, reroute all clients that will be routed to
2173 // the bit-perfect sink so that it is guaranteed only bit-perfect stream is active.
2174 PortHandleVector clientsToInvalidate;
2175 for (size_t i = 0; i < mOutputs.size(); i++) {
2176 if (mOutputs[i] == outputDesc ||
jiabin98c519c2023-07-05 17:34:21 +00002177 mOutputs[i]->devices().filter(outputDesc->devices()).isEmpty()) {
jiabine3d1f552023-06-14 17:42:17 +00002178 continue;
2179 }
2180 for (const auto& c : mOutputs[i]->getClientIterable()) {
2181 clientsToInvalidate.push_back(c->portId());
2182 }
2183 }
2184 if (!clientsToInvalidate.empty()) {
2185 ALOGD("%s Invalidate clients due to first bit-perfect client started",
2186 __func__);
2187 mpClientInterface->invalidateTracks(clientsToInvalidate);
2188 }
2189 }
jiabina84c3d32022-12-02 18:59:55 +00002190 }
2191 }
2192
Jean-Michel Trivib1f6e642023-02-07 20:49:04 +00002193 if (client->hasPreferredDevice()) {
2194 // playback activity with preferred device impacts routing occurred, inform upper layers
2195 mpClientInterface->onRoutingUpdated();
2196 }
Eric Laurentc75307b2015-03-17 15:29:32 -07002197 if (delayMs != 0) {
2198 usleep(delayMs * 1000);
2199 }
2200
2201 return status;
2202}
2203
Eric Laurent96d1dda2022-03-14 17:14:19 +01002204bool AudioPolicyManager::isLeUnicastActive() const {
2205 if (isInCall()) {
2206 return true;
2207 }
2208 return isAnyDeviceTypeActive(getAudioDeviceOutLeAudioUnicastSet());
2209}
2210
2211bool AudioPolicyManager::isAnyDeviceTypeActive(const DeviceTypeSet& deviceTypes) const {
2212 if (mAvailableOutputDevices.getDevicesFromTypes(deviceTypes).isEmpty()) {
2213 return false;
2214 }
2215 bool active = mOutputs.isAnyDeviceTypeActive(deviceTypes);
2216 ALOGV("%s active %d", __func__, active);
2217 return active;
2218}
2219
Eric Laurent97ac8712018-07-27 18:59:02 -07002220status_t AudioPolicyManager::startSource(const sp<SwAudioOutputDescriptor>& outputDesc,
2221 const sp<TrackClientDescriptor>& client,
2222 uint32_t *delayMs)
Eric Laurentc75307b2015-03-17 15:29:32 -07002223{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002224 // cannot start playback of STREAM_TTS if any other output is being used
2225 uint32_t beaconMuteLatency = 0;
Eric Laurentc75307b2015-03-17 15:29:32 -07002226
2227 *delayMs = 0;
Eric Laurent97ac8712018-07-27 18:59:02 -07002228 audio_stream_type_t stream = client->stream();
François Gaffie1c878552018-11-22 16:53:21 +01002229 auto clientVolSrc = client->volumeSource();
François Gaffiec005e562018-11-06 15:04:49 +01002230 auto clientStrategy = client->strategy();
2231 auto clientAttr = client->attributes();
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002232 if (stream == AUDIO_STREAM_TTS) {
2233 ALOGV("\t found BEACON stream");
François Gaffie1c878552018-11-22 16:53:21 +01002234 if (!mTtsOutputAvailable && mOutputs.isAnyOutputActive(
Francois Gaffie4404ddb2021-02-04 17:03:38 +01002235 toVolumeSource(AUDIO_STREAM_TTS, false) /*sourceToIgnore*/)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002236 return INVALID_OPERATION;
2237 } else {
2238 beaconMuteLatency = handleEventForBeacon(STARTING_BEACON);
2239 }
2240 } else {
2241 // some playback other than beacon starts
2242 beaconMuteLatency = handleEventForBeacon(STARTING_OUTPUT);
2243 }
2244
Eric Laurent77305a62016-07-25 16:39:22 -07002245 // force device change if the output is inactive and no audio patch is already present.
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002246 // check active before incrementing usage count
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02002247 bool force = !outputDesc->isActive() && !outputDesc->isRouted();
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002248
François Gaffie11d30102018-11-02 16:09:09 +01002249 DeviceVector devices;
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002250 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
Eric Laurent97ac8712018-07-27 18:59:02 -07002251 const char *address = NULL;
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002252 if (policyMix != nullptr) {
François Gaffie11d30102018-11-02 16:09:09 +01002253 audio_devices_t newDeviceType;
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00002254 address = policyMix->mDeviceAddress.c_str();
Kevin Rocard153f92d2018-12-18 18:33:28 -08002255 if ((policyMix->mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie11d30102018-11-02 16:09:09 +01002256 newDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Kevin Rocard153f92d2018-12-18 18:33:28 -08002257 } else {
2258 newDeviceType = policyMix->mDeviceType;
Eric Laurent97ac8712018-07-27 18:59:02 -07002259 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08002260 sp device = mAvailableOutputDevices.getDevice(newDeviceType, String8(address),
2261 AUDIO_FORMAT_DEFAULT);
2262 ALOG_ASSERT(device, "%s: no device found t=%u, a=%s", __func__, newDeviceType, address);
2263 devices.add(device);
Eric Laurent97ac8712018-07-27 18:59:02 -07002264 }
2265
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002266 // requiresMuteCheck is false when we can bypass mute strategy.
2267 // It covers a common case when there is no materially active audio
2268 // and muting would result in unnecessary delay and dropped audio.
2269 const uint32_t outputLatencyMs = outputDesc->latency();
2270 bool requiresMuteCheck = outputDesc->isActive(outputLatencyMs * 2); // account for drain
Eric Laurent96d1dda2022-03-14 17:14:19 +01002271 bool wasLeUnicastActive = isLeUnicastActive();
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002272
Eric Laurente552edb2014-03-10 17:42:56 -07002273 // increment usage count for this stream on the requested output:
2274 // NOTE that the usage count is the same for duplicated output and hardware output which is
2275 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
Eric Laurent592dd7b2018-08-05 18:58:48 -07002276 outputDesc->setClientActive(client, true);
Eric Laurent97ac8712018-07-27 18:59:02 -07002277
2278 if (client->hasPreferredDevice(true)) {
Eric Laurent72af8012023-03-15 17:36:22 +01002279 if (outputDesc->sameExclusivePreferredDevicesCount() > 0) {
François Gaffief96e5432019-04-09 17:13:56 +02002280 // Preferred device may be exclusive, use only if no other active clients on this output
2281 devices = DeviceVector(
2282 mAvailableOutputDevices.getDeviceFromId(client->preferredDeviceId()));
2283 } else {
2284 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
2285 }
François Gaffie11d30102018-11-02 16:09:09 +01002286 if (devices != outputDesc->devices()) {
François Gaffiec005e562018-11-06 15:04:49 +01002287 checkStrategyRoute(clientStrategy, outputDesc->mIoHandle);
Eric Laurent97ac8712018-07-27 18:59:02 -07002288 }
2289 }
Eric Laurente552edb2014-03-10 17:42:56 -07002290
François Gaffiec005e562018-11-06 15:04:49 +01002291 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07002292 selectOutputForMusicEffects();
2293 }
2294
François Gaffie1c878552018-11-22 16:53:21 +01002295 if (outputDesc->getActivityCount(clientVolSrc) == 1 || !devices.isEmpty()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08002296 // starting an output being rerouted?
François Gaffie11d30102018-11-02 16:09:09 +01002297 if (devices.isEmpty()) {
2298 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Eric Laurent275e8e92014-11-30 15:14:47 -08002299 }
François Gaffiec005e562018-11-06 15:04:49 +01002300 bool shouldWait =
2301 (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM)) ||
2302 followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_NOTIFICATION)) ||
2303 (beaconMuteLatency > 0));
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002304 uint32_t waitMs = beaconMuteLatency;
Eric Laurente552edb2014-03-10 17:42:56 -07002305 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01002306 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07002307 if (desc != outputDesc) {
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002308 // An output has a shared device if
2309 // - managed by the same hw module
2310 // - supports the currently selected device
2311 const bool sharedDevice = outputDesc->sharesHwModuleWith(desc)
François Gaffie11d30102018-11-02 16:09:09 +01002312 && (!desc->filterSupportedDevices(devices).isEmpty());
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002313
Eric Laurent77305a62016-07-25 16:39:22 -07002314 // force a device change if any other output is:
2315 // - managed by the same hw module
Jean-Michel Trivi4a5b4812018-02-08 17:22:32 +00002316 // - supports currently selected device
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002317 // - has a current device selection that differs from selected device.
Eric Laurent77305a62016-07-25 16:39:22 -07002318 // - has an active audio patch
Eric Laurente552edb2014-03-10 17:42:56 -07002319 // In this case, the audio HAL must receive the new device selection so that it can
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002320 // change the device currently selected by the other output.
2321 if (sharedDevice &&
François Gaffie11d30102018-11-02 16:09:09 +01002322 desc->devices() != devices &&
Eric Laurent77305a62016-07-25 16:39:22 -07002323 desc->getPatchHandle() != AUDIO_PATCH_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07002324 force = true;
2325 }
2326 // wait for audio on other active outputs to be presented when starting
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002327 // a notification so that audio focus effect can propagate, or that a mute/unmute
2328 // event occurred for beacon
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002329 const uint32_t latencyMs = desc->latency();
2330 const bool isActive = desc->isActive(latencyMs * 2); // account for drain
2331
2332 if (shouldWait && isActive && (waitMs < latencyMs)) {
2333 waitMs = latencyMs;
Eric Laurente552edb2014-03-10 17:42:56 -07002334 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002335
2336 // Require mute check if another output is on a shared device
2337 // and currently active to have proper drain and avoid pops.
2338 // Note restoring AudioTracks onto this output needs to invoke
2339 // a volume ramp if there is no mute.
2340 requiresMuteCheck |= sharedDevice && isActive;
Eric Laurente552edb2014-03-10 17:42:56 -07002341 }
2342 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002343
jiabin3ff8d7d2022-12-13 06:27:44 +00002344 if (outputDesc->mUsePreferredMixerAttributes && devices != outputDesc->devices()) {
2345 // If the output is open with preferred mixer attributes, but the routed device is
2346 // changed when calling this function, returning DEAD_OBJECT to indicate routing
2347 // changed.
2348 return DEAD_OBJECT;
2349 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002350 const uint32_t muteWaitMs =
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05302351 setOutputDevices(__func__, outputDesc, devices, force, 0, nullptr,
2352 requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07002353
Eric Laurente552edb2014-03-10 17:42:56 -07002354 // apply volume rules for current stream and device if necessary
François Gaffieaaac0fd2018-11-22 17:56:39 +01002355 auto &curves = getVolumeCurves(client->attributes());
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00002356 if (NO_ERROR != checkAndSetVolume(curves, client->volumeSource(),
François Gaffieaaac0fd2018-11-22 17:56:39 +01002357 curves.getVolumeIndex(outputDesc->devices().types()),
Eric Laurentc75307b2015-03-17 15:29:32 -07002358 outputDesc,
Francois Gaffied11442b2020-04-27 11:51:09 +02002359 outputDesc->devices().types(), 0 /*delay*/,
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00002360 outputDesc->useHwGain() /*force*/)) {
2361 // request AudioService to reinitialize the volume curves asynchronously
2362 ALOGE("checkAndSetVolume failed, requesting volume range init");
2363 mpClientInterface->onVolumeRangeInitRequest();
2364 };
Eric Laurente552edb2014-03-10 17:42:56 -07002365
2366 // update the outputs if starting an output with a stream that can affect notification
2367 // routing
2368 handleNotificationRoutingForStream(stream);
Eric Laurentc722f302014-12-10 11:21:49 -08002369
Eric Laurent2cbe89a2014-12-19 11:49:08 -08002370 // force reevaluating accessibility routing when ringtone or alarm starts
François Gaffiec005e562018-11-06 15:04:49 +01002371 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM))) {
jiabinc44b3462022-12-08 12:52:31 -08002372 invalidateStreams({AUDIO_STREAM_ACCESSIBILITY});
Eric Laurent2cbe89a2014-12-19 11:49:08 -08002373 }
Eric Laurentdc462862016-07-19 12:29:53 -07002374
2375 if (waitMs > muteWaitMs) {
2376 *delayMs = waitMs - muteWaitMs;
2377 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002378
2379 // FIXME: A device change (muteWaitMs > 0) likely introduces a volume change.
2380 // A volume change enacted by APM with 0 delay is not synchronous, as it goes
2381 // via AudioCommandThread to AudioFlinger. Hence it is possible that the volume
2382 // change occurs after the MixerThread starts and causes a stream volume
2383 // glitch.
2384 //
2385 // We do not introduce additional delay here.
Eric Laurente552edb2014-03-10 17:42:56 -07002386 }
Eric Laurentdc462862016-07-19 12:29:53 -07002387
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002388 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
jiabin9a3361e2019-10-01 09:38:30 -07002389 mEngine->getForceUse(
2390 AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
François Gaffiec005e562018-11-06 15:04:49 +01002391 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), true, outputDesc);
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002392 }
2393
Eric Laurent97ac8712018-07-27 18:59:02 -07002394 // Automatically enable the remote submix input when output is started on a re routing mix
2395 // of type MIX_TYPE_RECORDERS
jiabin9a3361e2019-10-01 09:38:30 -07002396 if (isSingleDeviceType(devices.types(), &audio_is_remote_submix_device) &&
2397 policyMix != NULL && policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002398 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2399 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2400 address,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002401 "remote-submix",
2402 AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07002403 }
2404
Eric Laurent96d1dda2022-03-14 17:14:19 +01002405 checkLeBroadcastRoutes(wasLeUnicastActive, outputDesc, *delayMs);
2406
Eric Laurente552edb2014-03-10 17:42:56 -07002407 return NO_ERROR;
2408}
2409
Eric Laurent96d1dda2022-03-14 17:14:19 +01002410void AudioPolicyManager::checkLeBroadcastRoutes(bool wasUnicastActive,
2411 sp<SwAudioOutputDescriptor> ignoredOutput, uint32_t delayMs) {
2412 bool isUnicastActive = isLeUnicastActive();
2413
2414 if (wasUnicastActive != isUnicastActive) {
jiabin3ff8d7d2022-12-13 06:27:44 +00002415 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent96d1dda2022-03-14 17:14:19 +01002416 //reroute all outputs routed to LE broadcast if LE unicast activy changed on any output
2417 for (size_t i = 0; i < mOutputs.size(); i++) {
2418 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
2419 if (desc != ignoredOutput && desc->isActive()
2420 && ((isUnicastActive &&
2421 !desc->devices().
2422 getDevicesFromType(AUDIO_DEVICE_OUT_BLE_BROADCAST).isEmpty())
2423 || (wasUnicastActive &&
2424 !desc->devices().getDevicesFromTypes(
2425 getAudioDeviceOutLeAudioUnicastSet()).isEmpty()))) {
2426 DeviceVector newDevices = getNewOutputDevices(desc, false /*fromCache*/);
2427 bool force = desc->devices() != newDevices;
jiabin3ff8d7d2022-12-13 06:27:44 +00002428 if (desc->mUsePreferredMixerAttributes && force) {
2429 // If the device is using preferred mixer attributes, the output need to reopen
2430 // with default configuration when the new selected devices are different from
2431 // current routing devices.
2432 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices);
2433 continue;
2434 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05302435 setOutputDevices(__func__, desc, newDevices, force, delayMs);
Eric Laurent96d1dda2022-03-14 17:14:19 +01002436 // re-apply device specific volume if not done by setOutputDevice()
2437 if (!force) {
2438 applyStreamVolumes(desc, newDevices.types(), delayMs);
2439 }
2440 }
2441 }
jiabin3ff8d7d2022-12-13 06:27:44 +00002442 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent96d1dda2022-03-14 17:14:19 +01002443 }
2444}
2445
Eric Laurent8fc147b2018-07-22 19:13:55 -07002446status_t AudioPolicyManager::stopOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002447{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002448 ALOGV("%s portId %d", __FUNCTION__, portId);
2449
2450 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2451 if (outputDesc == 0) {
2452 ALOGW("stopOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002453 return BAD_VALUE;
2454 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002455 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002456
Jean-Michel Trivib1f6e642023-02-07 20:49:04 +00002457 if (client->hasPreferredDevice(true)) {
2458 // playback activity with preferred device impacts routing occurred, inform upper layers
2459 mpClientInterface->onRoutingUpdated();
2460 }
2461
Eric Laurent97ac8712018-07-27 18:59:02 -07002462 ALOGV("stopOutput() output %d, stream %d, session %d",
2463 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurente552edb2014-03-10 17:42:56 -07002464
Eric Laurent97ac8712018-07-27 18:59:02 -07002465 status_t status = stopSource(outputDesc, client);
Eric Laurent3974e3b2017-12-07 17:58:43 -08002466
Eric Laurent733ce942017-12-07 12:18:25 -08002467 if (status == NO_ERROR ) {
2468 outputDesc->stop();
jiabina84c3d32022-12-02 18:59:55 +00002469 } else {
2470 return status;
2471 }
2472
2473 if (outputDesc->devices().size() == 1) {
2474 sp<PreferredMixerAttributesInfo> info = getPreferredMixerAttributesInfo(
2475 outputDesc->devices()[0]->getId(), client->strategy());
2476 if (info != nullptr && info->getUid() == client->uid()) {
2477 info->decreaseActiveClient();
2478 if (info->getActiveClientCount() == 0) {
2479 reopenOutput(outputDesc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
2480 }
2481 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002482 }
2483 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07002484}
2485
Eric Laurent97ac8712018-07-27 18:59:02 -07002486status_t AudioPolicyManager::stopSource(const sp<SwAudioOutputDescriptor>& outputDesc,
2487 const sp<TrackClientDescriptor>& client)
Eric Laurentc75307b2015-03-17 15:29:32 -07002488{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002489 // always handle stream stop, check which stream type is stopping
Eric Laurent97ac8712018-07-27 18:59:02 -07002490 audio_stream_type_t stream = client->stream();
François Gaffie1c878552018-11-22 16:53:21 +01002491 auto clientVolSrc = client->volumeSource();
Eric Laurent96d1dda2022-03-14 17:14:19 +01002492 bool wasLeUnicastActive = isLeUnicastActive();
Eric Laurent97ac8712018-07-27 18:59:02 -07002493
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002494 handleEventForBeacon(stream == AUDIO_STREAM_TTS ? STOPPING_BEACON : STOPPING_OUTPUT);
2495
François Gaffie1c878552018-11-22 16:53:21 +01002496 if (outputDesc->getActivityCount(clientVolSrc) > 0) {
2497 if (outputDesc->getActivityCount(clientVolSrc) == 1) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002498 // Automatically disable the remote submix input when output is stopped on a
2499 // re routing mix of type MIX_TYPE_RECORDERS
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002500 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
jiabin9a3361e2019-10-01 09:38:30 -07002501 if (isSingleDeviceType(
2502 outputDesc->devices().types(), &audio_is_remote_submix_device) &&
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002503 policyMix != nullptr &&
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002504 policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002505 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2506 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002507 policyMix->mDeviceAddress,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002508 "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07002509 }
2510 }
2511 bool forceDeviceUpdate = false;
Eric Laurent72af8012023-03-15 17:36:22 +01002512 if (client->hasPreferredDevice(true) &&
2513 outputDesc->sameExclusivePreferredDevicesCount() < 2) {
François Gaffiec005e562018-11-06 15:04:49 +01002514 checkStrategyRoute(client->strategy(), AUDIO_IO_HANDLE_NONE);
Eric Laurent97ac8712018-07-27 18:59:02 -07002515 forceDeviceUpdate = true;
2516 }
2517
Eric Laurente552edb2014-03-10 17:42:56 -07002518 // decrement usage count of this stream on the output
Eric Laurent592dd7b2018-08-05 18:58:48 -07002519 outputDesc->setClientActive(client, false);
Paul McLeanaa981192015-03-21 09:55:15 -07002520
Eric Laurente552edb2014-03-10 17:42:56 -07002521 // store time at which the stream was stopped - see isStreamActive()
François Gaffie1c878552018-11-22 16:53:21 +01002522 if (outputDesc->getActivityCount(clientVolSrc) == 0 || forceDeviceUpdate) {
François Gaffiec005e562018-11-06 15:04:49 +01002523 outputDesc->setStopTime(client, systemTime());
François Gaffie11d30102018-11-02 16:09:09 +01002524 DeviceVector newDevices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Francois Gaffie3523ab32021-06-22 13:24:34 +02002525
2526 // If the routing does not change, if an output is routed on a device using HwGain
2527 // (aka setAudioPortConfig) and there are still active clients following different
2528 // volume group(s), force reapply volume
2529 bool requiresVolumeCheck = outputDesc->getActivityCount(clientVolSrc) == 0 &&
2530 outputDesc->useHwGain() && outputDesc->isAnyActive(VOLUME_SOURCE_NONE);
2531
Eric Laurente552edb2014-03-10 17:42:56 -07002532 // delay the device switch by twice the latency because stopOutput() is executed when
2533 // the track stop() command is received and at that time the audio track buffer can
2534 // still contain data that needs to be drained. The latency only covers the audio HAL
2535 // and kernel buffers. Also the latency does not always include additional delay in the
2536 // audio path (audio DSP, CODEC ...)
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05302537 setOutputDevices(__func__, outputDesc, newDevices, false, outputDesc->latency()*2,
Francois Gaffie3523ab32021-06-22 13:24:34 +02002538 nullptr, true /*requiresMuteCheck*/, requiresVolumeCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07002539
2540 // force restoring the device selection on other active outputs if it differs from the
2541 // one being selected for this output
jiabin3ff8d7d2022-12-13 06:27:44 +00002542 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent57de36c2016-09-28 16:59:11 -07002543 uint32_t delayMs = outputDesc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -07002544 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01002545 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07002546 if (desc != outputDesc &&
Eric Laurente552edb2014-03-10 17:42:56 -07002547 desc->isActive() &&
2548 outputDesc->sharesHwModuleWith(desc) &&
François Gaffie11d30102018-11-02 16:09:09 +01002549 (newDevices != desc->devices())) {
2550 DeviceVector newDevices2 = getNewOutputDevices(desc, false /*fromCache*/);
2551 bool force = desc->devices() != newDevices2;
Eric Laurentf3a5a602018-05-22 18:42:55 -07002552
jiabin3ff8d7d2022-12-13 06:27:44 +00002553 if (desc->mUsePreferredMixerAttributes && force) {
2554 // If the device is using preferred mixer attributes, the output need to
2555 // reopen with default configuration when the new selected devices are
2556 // different from current routing devices.
2557 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices2);
2558 continue;
2559 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05302560 setOutputDevices(__func__, desc, newDevices2, force, delayMs);
François Gaffie11d30102018-11-02 16:09:09 +01002561
Eric Laurent57de36c2016-09-28 16:59:11 -07002562 // re-apply device specific volume if not done by setOutputDevice()
2563 if (!force) {
François Gaffie11d30102018-11-02 16:09:09 +01002564 applyStreamVolumes(desc, newDevices2.types(), delayMs);
Eric Laurent57de36c2016-09-28 16:59:11 -07002565 }
Eric Laurente552edb2014-03-10 17:42:56 -07002566 }
2567 }
jiabin3ff8d7d2022-12-13 06:27:44 +00002568 reopenOutputsWithDevices(outputsToReopen);
Eric Laurente552edb2014-03-10 17:42:56 -07002569 // update the outputs if stopping one with a stream that can affect notification routing
2570 handleNotificationRoutingForStream(stream);
2571 }
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002572
2573 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
2574 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Jean-Michel Trivi74e01fa2019-02-25 12:18:09 -08002575 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), false, outputDesc);
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002576 }
2577
François Gaffiec005e562018-11-06 15:04:49 +01002578 if (followsSameRouting(client->attributes(), attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07002579 selectOutputForMusicEffects();
2580 }
Eric Laurent96d1dda2022-03-14 17:14:19 +01002581
2582 checkLeBroadcastRoutes(wasLeUnicastActive, outputDesc, outputDesc->latency()*2);
2583
Eric Laurente552edb2014-03-10 17:42:56 -07002584 return NO_ERROR;
2585 } else {
Eric Laurentc75307b2015-03-17 15:29:32 -07002586 ALOGW("stopOutput() refcount is already 0");
Eric Laurente552edb2014-03-10 17:42:56 -07002587 return INVALID_OPERATION;
2588 }
2589}
2590
jiabinbce0c1d2020-10-05 11:20:18 -07002591bool AudioPolicyManager::releaseOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002592{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002593 ALOGV("%s portId %d", __FUNCTION__, portId);
2594
2595 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2596 if (outputDesc == 0) {
Andy Hung39efb7a2018-09-26 15:39:28 -07002597 // If an output descriptor is closed due to a device routing change,
2598 // then there are race conditions with releaseOutput from tracks
2599 // that may be destroyed (with no PlaybackThread) or a PlaybackThread
2600 // destroyed shortly thereafter.
2601 //
2602 // Here we just log a warning, instead of a fatal error.
Eric Laurent8fc147b2018-07-22 19:13:55 -07002603 ALOGW("releaseOutput() no output for client %d", portId);
jiabinbce0c1d2020-10-05 11:20:18 -07002604 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002605 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002606
2607 ALOGV("releaseOutput() %d", outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -07002608
Jaideep Sharma7bf382e2020-11-26 17:07:29 +05302609 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
2610 if (outputDesc->isClientActive(client)) {
2611 ALOGW("releaseOutput() inactivates portId %d in good faith", portId);
2612 stopOutput(portId);
2613 }
2614
Eric Laurent8fc147b2018-07-22 19:13:55 -07002615 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
2616 if (outputDesc->mDirectOpenCount <= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07002617 ALOGW("releaseOutput() invalid open count %d for output %d",
Eric Laurent8fc147b2018-07-22 19:13:55 -07002618 outputDesc->mDirectOpenCount, outputDesc->mIoHandle);
jiabinbce0c1d2020-10-05 11:20:18 -07002619 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002620 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002621 if (--outputDesc->mDirectOpenCount == 0) {
2622 closeOutput(outputDesc->mIoHandle);
Eric Laurentb52c1522014-05-20 11:27:36 -07002623 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07002624 }
2625 }
Jaideep Sharma7bf382e2020-11-26 17:07:29 +05302626
Andy Hung39efb7a2018-09-26 15:39:28 -07002627 outputDesc->removeClient(portId);
jiabinbce0c1d2020-10-05 11:20:18 -07002628 if (outputDesc->mPendingReopenToQueryProfiles && outputDesc->getClientCount() == 0) {
2629 // The output is pending reopened to query dynamic profiles and
2630 // there is no active clients
2631 closeOutput(outputDesc->mIoHandle);
2632 sp<SwAudioOutputDescriptor> newOutputDesc = openOutputWithProfileAndDevice(
2633 outputDesc->mProfile, mEngine->getActiveMediaDevices(mAvailableOutputDevices));
2634 if (newOutputDesc == nullptr) {
2635 ALOGE("%s failed to open output", __func__);
2636 }
2637 return true;
2638 }
2639 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002640}
2641
Eric Laurentcaf7f482014-11-25 17:50:47 -08002642status_t AudioPolicyManager::getInputForAttr(const audio_attributes_t *attr,
2643 audio_io_handle_t *input,
Mikhail Naganov2996f672019-04-18 12:29:59 -07002644 audio_unique_id_t riid,
Eric Laurentcaf7f482014-11-25 17:50:47 -08002645 audio_session_t session,
Svet Ganov3e5f14f2021-05-13 22:51:08 +00002646 const AttributionSourceState& attributionSource,
jiabinf1c73972022-04-14 16:28:52 -07002647 audio_config_base_t *config,
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002648 audio_input_flags_t flags,
Eric Laurent2ac76942017-06-22 17:17:09 -07002649 audio_port_handle_t *selectedDeviceId,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002650 input_type_t *inputType,
2651 audio_port_handle_t *portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002652{
François Gaffiec005e562018-11-06 15:04:49 +01002653 ALOGV("%s() source %d, sampling rate %d, format %#x, channel mask %#x, session %d, "
Eric Laurent2f2c1982021-06-02 14:03:11 +02002654 "flags %#x attributes=%s requested device ID %d",
2655 __func__, attr->source, config->sample_rate, config->format, config->channel_mask,
2656 session, flags, toString(*attr).c_str(), *selectedDeviceId);
Eric Laurente552edb2014-03-10 17:42:56 -07002657
Eric Laurentad2e7b92017-09-14 20:06:42 -07002658 status_t status = NO_ERROR;
Francois Gaffie716e1432019-01-14 16:58:59 +01002659 audio_attributes_t attributes = *attr;
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002660 sp<AudioPolicyMix> policyMix;
François Gaffie11d30102018-11-02 16:09:09 +01002661 sp<DeviceDescriptor> device;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002662 sp<AudioInputDescriptor> inputDesc;
François Gaffie1b4753e2023-02-06 10:36:33 +01002663 sp<AudioInputDescriptor> previousInputDesc;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002664 sp<RecordClientDescriptor> clientDesc;
2665 audio_port_handle_t requestedDeviceId = *selectedDeviceId;
Svet Ganov3e5f14f2021-05-13 22:51:08 +00002666 uid_t uid = VALUE_OR_RETURN_STATUS(aidl2legacy_int32_t_uid_t(attributionSource.uid));
Eric Laurent8f42ea12018-08-08 09:08:25 -07002667 bool isSoundTrigger;
Eric Laurent8f42ea12018-08-08 09:08:25 -07002668
2669 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
2670 if (*portId != AUDIO_PORT_HANDLE_NONE) {
2671 return INVALID_OPERATION;
2672 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08002673
Francois Gaffie716e1432019-01-14 16:58:59 +01002674 if (attr->source == AUDIO_SOURCE_DEFAULT) {
2675 attributes.source = AUDIO_SOURCE_MIC;
Eric Laurentfe231122017-11-17 17:48:06 -08002676 }
2677
Paul McLean466dc8e2015-04-17 13:15:36 -06002678 // Explicit routing?
Pattydd807582021-11-04 21:01:03 +08002679 sp<DeviceDescriptor> explicitRoutingDevice =
François Gaffie11d30102018-11-02 16:09:09 +01002680 mAvailableInputDevices.getDeviceFromId(*selectedDeviceId);
Paul McLean466dc8e2015-04-17 13:15:36 -06002681
Eric Laurentad2e7b92017-09-14 20:06:42 -07002682 // special case for mmap capture: if an input IO handle is specified, we reuse this input if
2683 // possible
2684 if ((flags & AUDIO_INPUT_FLAG_MMAP_NOIRQ) == AUDIO_INPUT_FLAG_MMAP_NOIRQ &&
2685 *input != AUDIO_IO_HANDLE_NONE) {
2686 ssize_t index = mInputs.indexOfKey(*input);
2687 if (index < 0) {
2688 ALOGW("getInputForAttr() unknown MMAP input %d", *input);
2689 status = BAD_VALUE;
2690 goto error;
2691 }
2692 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002693 RecordClientVector clients = inputDesc->getClientsForSession(session);
2694 if (clients.size() == 0) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07002695 ALOGW("getInputForAttr() unknown session %d on input %d", session, *input);
2696 status = BAD_VALUE;
2697 goto error;
2698 }
2699 // For MMAP mode, the first call to getInputForAttr() is made on behalf of audioflinger.
2700 // The second call is for the first active client and sets the UID. Any further call
Eric Laurent331679c2018-04-16 17:03:16 -07002701 // corresponds to a new client and is only permitted from the same UID.
2702 // If the first UID is silenced, allow a new UID connection and replace with new UID
Eric Laurent8f42ea12018-08-08 09:08:25 -07002703 if (clients.size() > 1) {
2704 for (const auto& client : clients) {
2705 // The client map is ordered by key values (portId) and portIds are allocated
2706 // incrementaly. So the first client in this list is the one opened by audio flinger
2707 // when the mmap stream is created and should be ignored as it does not correspond
2708 // to an actual client
2709 if (client == *clients.cbegin()) {
2710 continue;
2711 }
2712 if (uid != client->uid() && !client->isSilenced()) {
2713 ALOGW("getInputForAttr() bad uid %d for client %d uid %d",
2714 uid, client->portId(), client->uid());
2715 status = INVALID_OPERATION;
2716 goto error;
2717 }
Eric Laurent331679c2018-04-16 17:03:16 -07002718 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002719 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002720 *inputType = API_INPUT_LEGACY;
François Gaffie11d30102018-11-02 16:09:09 +01002721 device = inputDesc->getDevice();
Eric Laurentad2e7b92017-09-14 20:06:42 -07002722
Eric Laurentfecbceb2021-02-09 14:46:43 +01002723 ALOGV("%s reusing MMAP input %d for session %d", __FUNCTION__, *input, session);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002724 goto exit;
Eric Laurentad2e7b92017-09-14 20:06:42 -07002725 }
2726
2727 *input = AUDIO_IO_HANDLE_NONE;
2728 *inputType = API_INPUT_INVALID;
2729
Francois Gaffie716e1432019-01-14 16:58:59 +01002730 if (attributes.source == AUDIO_SOURCE_REMOTE_SUBMIX &&
Jan Sebechlebskybc56bcd2022-09-26 13:15:19 +02002731 extractAddressFromAudioAttributes(attributes).has_value()) {
Francois Gaffie716e1432019-01-14 16:58:59 +01002732 status = mPolicyMixes.getInputMixForAttr(attributes, &policyMix);
Eric Laurentad2e7b92017-09-14 20:06:42 -07002733 if (status != NO_ERROR) {
jiabinc1de2df2019-05-07 14:26:40 -07002734 ALOGW("%s could not find input mix for attr %s",
2735 __func__, toString(attributes).c_str());
Eric Laurentad2e7b92017-09-14 20:06:42 -07002736 goto error;
François Gaffie036e1e92015-03-19 10:16:24 +01002737 }
jiabinc1de2df2019-05-07 14:26:40 -07002738 device = mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2739 String8(attr->tags + strlen("addr=")),
2740 AUDIO_FORMAT_DEFAULT);
2741 if (device == nullptr) {
Kevin Rocard04ed0462019-05-02 17:53:24 -07002742 ALOGW("%s could not find in Remote Submix device for source %d, tags %s",
jiabinc1de2df2019-05-07 14:26:40 -07002743 __func__, attributes.source, attributes.tags);
2744 status = BAD_VALUE;
2745 goto error;
2746 }
2747
Kevin Rocard25f9b052019-02-27 15:08:54 -08002748 if (is_mix_loopback_render(policyMix->mRouteFlags)) {
2749 *inputType = API_INPUT_MIX_PUBLIC_CAPTURE_PLAYBACK;
2750 } else {
2751 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
2752 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002753 } else {
François Gaffie11d30102018-11-02 16:09:09 +01002754 if (explicitRoutingDevice != nullptr) {
2755 device = explicitRoutingDevice;
Eric Laurent97ac8712018-07-27 18:59:02 -07002756 } else {
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01002757 // Prevent from storing invalid requested device id in clients
2758 requestedDeviceId = AUDIO_PORT_HANDLE_NONE;
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02002759 device = mEngine->getInputDeviceForAttributes(attributes, uid, session, &policyMix);
yuanjiahsu4069d5d2021-04-19 07:54:27 +08002760 ALOGV_IF(device != nullptr, "%s found device type is 0x%X",
2761 __FUNCTION__, device->type());
Eric Laurent97ac8712018-07-27 18:59:02 -07002762 }
François Gaffie11d30102018-11-02 16:09:09 +01002763 if (device == nullptr) {
Francois Gaffie716e1432019-01-14 16:58:59 +01002764 ALOGW("getInputForAttr() could not find device for source %d", attributes.source);
Eric Laurentad2e7b92017-09-14 20:06:42 -07002765 status = BAD_VALUE;
2766 goto error;
Eric Laurent275e8e92014-11-30 15:14:47 -08002767 }
Alden DSouzab7d20782021-02-08 08:51:42 -08002768 if (device->type() == AUDIO_DEVICE_IN_ECHO_REFERENCE) {
2769 *inputType = API_INPUT_MIX_CAPTURE;
2770 } else if (policyMix) {
François Gaffie11d30102018-11-02 16:09:09 +01002771 ALOG_ASSERT(policyMix->mMixType == MIX_TYPE_RECORDERS, "Invalid Mix Type");
2772 // there is an external policy, but this input is attached to a mix of recorders,
2773 // meaning it receives audio injected into the framework, so the recorder doesn't
2774 // know about it and is therefore considered "legacy"
2775 *inputType = API_INPUT_LEGACY;
2776 } else if (audio_is_remote_submix_device(device->type())) {
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002777 *inputType = API_INPUT_MIX_CAPTURE;
François Gaffie11d30102018-11-02 16:09:09 +01002778 } else if (device->type() == AUDIO_DEVICE_IN_TELEPHONY_RX) {
Eric Laurent82db2692015-08-07 13:59:42 -07002779 *inputType = API_INPUT_TELEPHONY_RX;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002780 } else {
2781 *inputType = API_INPUT_LEGACY;
Eric Laurentc722f302014-12-10 11:21:49 -08002782 }
Ravi Kumar Alamandab367f5b2015-08-25 08:21:37 -07002783
Eric Laurent599c7582015-12-07 18:05:55 -08002784 }
2785
François Gaffiec005e562018-11-06 15:04:49 +01002786 *input = getInputForDevice(device, session, attributes, config, flags, policyMix);
Eric Laurent599c7582015-12-07 18:05:55 -08002787 if (*input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07002788 status = INVALID_OPERATION;
jiabinf1c73972022-04-14 16:28:52 -07002789 AudioProfileVector profiles;
2790 status_t ret = getProfilesForDevices(
2791 DeviceVector(device), profiles, flags, true /*isInput*/);
2792 if (ret == NO_ERROR && !profiles.empty()) {
Robert Wub98ff1b2023-06-15 22:53:58 +00002793 const auto channels = profiles[0]->getChannels();
2794 if (!channels.empty() && (channels.find(config->channel_mask) == channels.end())) {
2795 config->channel_mask = *channels.begin();
2796 }
2797 const auto sampleRates = profiles[0]->getSampleRates();
2798 if (!sampleRates.empty() &&
2799 (sampleRates.find(config->sample_rate) == sampleRates.end())) {
2800 config->sample_rate = *sampleRates.begin();
2801 }
jiabinf1c73972022-04-14 16:28:52 -07002802 config->format = profiles[0]->getFormat();
2803 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002804 goto error;
Eric Laurent599c7582015-12-07 18:05:55 -08002805 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08002806
Eric Laurent8f42ea12018-08-08 09:08:25 -07002807exit:
2808
François Gaffiec005e562018-11-06 15:04:49 +01002809 *selectedDeviceId = mAvailableInputDevices.contains(device) ?
2810 device->getId() : AUDIO_PORT_HANDLE_NONE;
Eric Laurent2ac76942017-06-22 17:17:09 -07002811
Francois Gaffie716e1432019-01-14 16:58:59 +01002812 isSoundTrigger = attributes.source == AUDIO_SOURCE_HOTWORD &&
Carter Hsud0cce2e2019-05-03 17:36:28 +08002813 mSoundTriggerSessions.indexOfKey(session) >= 0;
jiabin4ef93452019-09-10 14:29:54 -07002814 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002815
Mikhail Naganov2996f672019-04-18 12:29:59 -07002816 clientDesc = new RecordClientDescriptor(*portId, riid, uid, session, attributes, *config,
Francois Gaffie716e1432019-01-14 16:58:59 +01002817 requestedDeviceId, attributes.source, flags,
2818 isSoundTrigger);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002819 inputDesc = mInputs.valueFor(*input);
François Gaffie1b4753e2023-02-06 10:36:33 +01002820 // Move (if found) effect for the client session to its input
2821 mEffects.moveEffectsForIo(session, *input, &mInputs, mpClientInterface);
Andy Hung39efb7a2018-09-26 15:39:28 -07002822 inputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002823
2824 ALOGV("getInputForAttr() returns input %d type %d selectedDeviceId %d for port ID %d",
2825 *input, *inputType, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07002826
Eric Laurent599c7582015-12-07 18:05:55 -08002827 return NO_ERROR;
Eric Laurentad2e7b92017-09-14 20:06:42 -07002828
2829error:
Eric Laurentad2e7b92017-09-14 20:06:42 -07002830 return status;
Eric Laurent599c7582015-12-07 18:05:55 -08002831}
2832
2833
François Gaffie11d30102018-11-02 16:09:09 +01002834audio_io_handle_t AudioPolicyManager::getInputForDevice(const sp<DeviceDescriptor> &device,
Eric Laurent599c7582015-12-07 18:05:55 -08002835 audio_session_t session,
François Gaffiec005e562018-11-06 15:04:49 +01002836 const audio_attributes_t &attributes,
jiabinf1c73972022-04-14 16:28:52 -07002837 audio_config_base_t *config,
Eric Laurent599c7582015-12-07 18:05:55 -08002838 audio_input_flags_t flags,
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002839 const sp<AudioPolicyMix> &policyMix)
Eric Laurent599c7582015-12-07 18:05:55 -08002840{
2841 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
François Gaffiec005e562018-11-06 15:04:49 +01002842 audio_source_t halInputSource = attributes.source;
Eric Laurent599c7582015-12-07 18:05:55 -08002843 bool isSoundTrigger = false;
2844
François Gaffiec005e562018-11-06 15:04:49 +01002845 if (attributes.source == AUDIO_SOURCE_HOTWORD) {
Eric Laurent599c7582015-12-07 18:05:55 -08002846 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
2847 if (index >= 0) {
2848 input = mSoundTriggerSessions.valueFor(session);
2849 isSoundTrigger = true;
2850 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_HW_HOTWORD);
2851 ALOGV("SoundTrigger capture on session %d input %d", session, input);
2852 } else {
2853 halInputSource = AUDIO_SOURCE_VOICE_RECOGNITION;
Eric Laurent5dbe4712014-09-19 19:04:57 -07002854 }
François Gaffiec005e562018-11-06 15:04:49 +01002855 } else if (attributes.source == AUDIO_SOURCE_VOICE_COMMUNICATION &&
Eric Laurentfe231122017-11-17 17:48:06 -08002856 audio_is_linear_pcm(config->format)) {
Haynes Mathew George851d3ff2017-06-19 20:01:57 -07002857 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_VOIP_TX);
Eric Laurent5dbe4712014-09-19 19:04:57 -07002858 }
2859
Carter Hsua3abb402021-10-26 11:11:20 +08002860 if (attributes.source == AUDIO_SOURCE_ULTRASOUND) {
2861 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_ULTRASOUND);
2862 }
2863
Eric Laurentfe231122017-11-17 17:48:06 -08002864 // sampling rate and flags may be updated by getInputProfile
2865 uint32_t profileSamplingRate = (config->sample_rate == 0) ?
2866 SAMPLE_RATE_HZ_DEFAULT : config->sample_rate;
jiabin2fd710d2022-05-02 23:20:22 +00002867 audio_format_t profileFormat = config->format;
Eric Laurentfe231122017-11-17 17:48:06 -08002868 audio_channel_mask_t profileChannelMask = config->channel_mask;
Andy Hungf129b032015-04-07 13:45:50 -07002869 audio_input_flags_t profileFlags = flags;
jiabin2fd710d2022-05-02 23:20:22 +00002870 // find a compatible input profile (not necessarily identical in parameters)
2871 sp<IOProfile> profile = getInputProfile(
2872 device, profileSamplingRate, profileFormat, profileChannelMask, profileFlags);
2873 if (profile == nullptr) {
2874 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07002875 }
jiabin2fd710d2022-05-02 23:20:22 +00002876
Glenn Kasten05ddca52016-02-11 08:17:12 -08002877 // Pick input sampling rate if not specified by client
Eric Laurentfe231122017-11-17 17:48:06 -08002878 uint32_t samplingRate = config->sample_rate;
Glenn Kasten05ddca52016-02-11 08:17:12 -08002879 if (samplingRate == 0) {
2880 samplingRate = profileSamplingRate;
2881 }
Eric Laurente552edb2014-03-10 17:42:56 -07002882
Eric Laurent322b4d22015-04-03 15:57:54 -07002883 if (profile->getModuleHandle() == 0) {
2884 ALOGE("getInputForAttr(): HW module %s not opened", profile->getModuleName());
Eric Laurent599c7582015-12-07 18:05:55 -08002885 return input;
Eric Laurentcf2c0212014-07-25 16:20:43 -07002886 }
2887
Eric Laurentec376dc2021-04-08 20:41:22 +02002888 // Reuse an already opened input if a client with the same session ID already exists
2889 // on that input
2890 for (size_t i = 0; i < mInputs.size(); i++) {
2891 sp <AudioInputDescriptor> desc = mInputs.valueAt(i);
2892 if (desc->mProfile != profile) {
2893 continue;
2894 }
2895 RecordClientVector clients = desc->clientsList();
2896 for (const auto &client : clients) {
2897 if (session == client->session()) {
2898 return desc->mIoHandle;
2899 }
2900 }
2901 }
2902
Eric Laurent3974e3b2017-12-07 17:58:43 -08002903 if (!profile->canOpenNewIo()) {
Eric Laurent4eb58f12018-12-07 16:41:02 -08002904 for (size_t i = 0; i < mInputs.size(); ) {
Eric Laurentc529cf62020-04-17 18:19:10 -07002905 sp<AudioInputDescriptor> desc = mInputs.valueAt(i);
Eric Laurent4eb58f12018-12-07 16:41:02 -08002906 if (desc->mProfile != profile) {
Carter Hsu9a645a92019-05-15 12:15:32 +08002907 i++;
Eric Laurent4eb58f12018-12-07 16:41:02 -08002908 continue;
2909 }
2910 // if sound trigger, reuse input if used by other sound trigger on same session
2911 // else
2912 // reuse input if active client app is not in IDLE state
2913 //
2914 RecordClientVector clients = desc->clientsList();
2915 bool doClose = false;
2916 for (const auto& client : clients) {
2917 if (isSoundTrigger != client->isSoundTrigger()) {
2918 continue;
2919 }
2920 if (client->isSoundTrigger()) {
2921 if (session == client->session()) {
2922 return desc->mIoHandle;
2923 }
2924 continue;
2925 }
2926 if (client->active() && client->appState() != APP_STATE_IDLE) {
2927 return desc->mIoHandle;
2928 }
2929 doClose = true;
2930 }
2931 if (doClose) {
2932 closeInput(desc->mIoHandle);
2933 } else {
2934 i++;
2935 }
2936 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002937 }
2938
Eric Laurentfe231122017-11-17 17:48:06 -08002939 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07002940
Eric Laurentfe231122017-11-17 17:48:06 -08002941 audio_config_t lConfig = AUDIO_CONFIG_INITIALIZER;
2942 lConfig.sample_rate = profileSamplingRate;
2943 lConfig.channel_mask = profileChannelMask;
2944 lConfig.format = profileFormat;
Eric Laurente3014102017-05-03 11:15:43 -07002945
François Gaffie11d30102018-11-02 16:09:09 +01002946 status_t status = inputDesc->open(&lConfig, device, halInputSource, profileFlags, &input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07002947
2948 // only accept input with the exact requested set of parameters
Eric Laurent599c7582015-12-07 18:05:55 -08002949 if (status != NO_ERROR || input == AUDIO_IO_HANDLE_NONE ||
Eric Laurentfe231122017-11-17 17:48:06 -08002950 (profileSamplingRate != lConfig.sample_rate) ||
2951 !audio_formats_match(profileFormat, lConfig.format) ||
2952 (profileChannelMask != lConfig.channel_mask)) {
2953 ALOGW("getInputForAttr() failed opening input: sampling rate %d"
Glenn Kasten49f36ba2017-12-06 13:02:02 -08002954 ", format %#x, channel mask %#x",
Eric Laurentfe231122017-11-17 17:48:06 -08002955 profileSamplingRate, profileFormat, profileChannelMask);
Eric Laurent599c7582015-12-07 18:05:55 -08002956 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfe231122017-11-17 17:48:06 -08002957 inputDesc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07002958 }
Eric Laurent599c7582015-12-07 18:05:55 -08002959 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07002960 }
2961
Eric Laurentc722f302014-12-10 11:21:49 -08002962 inputDesc->mPolicyMix = policyMix;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002963
Eric Laurent599c7582015-12-07 18:05:55 -08002964 addInput(input, inputDesc);
Eric Laurentb52c1522014-05-20 11:27:36 -07002965 mpClientInterface->onAudioPortListUpdate();
Paul McLean466dc8e2015-04-17 13:15:36 -06002966
Eric Laurent599c7582015-12-07 18:05:55 -08002967 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07002968}
2969
Eric Laurent4eb58f12018-12-07 16:41:02 -08002970status_t AudioPolicyManager::startInput(audio_port_handle_t portId)
Eric Laurentbb948092017-01-23 18:33:30 -08002971{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002972 ALOGV("%s portId %d", __FUNCTION__, portId);
2973
2974 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2975 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002976 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurentd52a28c2020-08-21 17:10:39 -07002977 return DEAD_OBJECT;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002978 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002979 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07002980 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002981 if (client->active()) {
2982 ALOGW("%s input %d client %d already started", __FUNCTION__, input, client->portId());
2983 return INVALID_OPERATION;
Eric Laurent4dc68062014-07-28 17:26:49 -07002984 }
2985
Eric Laurent8f42ea12018-08-08 09:08:25 -07002986 audio_session_t session = client->session();
2987
Eric Laurent4eb58f12018-12-07 16:41:02 -08002988 ALOGV("%s input:%d, session:%d)", __FUNCTION__, input, session);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002989
Eric Laurent4eb58f12018-12-07 16:41:02 -08002990 Vector<sp<AudioInputDescriptor>> activeInputs = mInputs.getActiveInputs();
Eric Laurent74708e72017-04-07 17:13:42 -07002991
Eric Laurent4eb58f12018-12-07 16:41:02 -08002992 status_t status = inputDesc->start();
2993 if (status != NO_ERROR) {
2994 return status;
Eric Laurent74708e72017-04-07 17:13:42 -07002995 }
Eric Laurente552edb2014-03-10 17:42:56 -07002996
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002997 // increment activity count before calling getNewInputDevice() below as only active sessions
Eric Laurent313d1e72016-01-29 09:56:57 -08002998 // are considered for device selection
Eric Laurent8f42ea12018-08-08 09:08:25 -07002999 inputDesc->setClientActive(client, true);
Eric Laurent313d1e72016-01-29 09:56:57 -08003000
Eric Laurent8f42ea12018-08-08 09:08:25 -07003001 // indicate active capture to sound trigger service if starting capture from a mic on
3002 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01003003 sp<DeviceDescriptor> device = getNewInputDevice(inputDesc);
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003004 if (device != nullptr) {
3005 status = setInputDevice(input, device, true /* force */);
3006 } else {
3007 ALOGW("%s no new input device can be found for descriptor %d",
3008 __FUNCTION__, inputDesc->getId());
3009 status = BAD_VALUE;
3010 }
Eric Laurente552edb2014-03-10 17:42:56 -07003011
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003012 if (status == NO_ERROR && inputDesc->activeCount() == 1) {
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003013 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003014 // if input maps to a dynamic policy with an activity listener, notify of state change
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003015 if ((policyMix != nullptr)
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003016 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
3017 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
Eric Laurent8f42ea12018-08-08 09:08:25 -07003018 MIX_STATE_MIXING);
Eric Laurent733ce942017-12-07 12:18:25 -08003019 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08003020
François Gaffie11d30102018-11-02 16:09:09 +01003021 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
3022 if (primaryInputDevices.contains(device) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07003023 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 1) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07003024 mpClientInterface->setSoundTriggerCaptureState(true);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003025 }
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07003026
Eric Laurent8f42ea12018-08-08 09:08:25 -07003027 // automatically enable the remote submix output when input is started if not
3028 // used by a policy mix of type MIX_TYPE_RECORDERS
3029 // For remote submix (a virtual device), we open only one input per capture request.
François Gaffie11d30102018-11-02 16:09:09 +01003030 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003031 String8 address = String8("");
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003032 if (policyMix == nullptr) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003033 address = String8("0");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003034 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
3035 address = policyMix->mDeviceAddress;
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07003036 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07003037 if (address != "") {
3038 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
3039 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08003040 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurentc722f302014-12-10 11:21:49 -08003041 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07003042 }
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003043 } else if (status != NO_ERROR) {
3044 // Restore client activity state.
3045 inputDesc->setClientActive(client, false);
3046 inputDesc->stop();
Eric Laurente552edb2014-03-10 17:42:56 -07003047 }
3048
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003049 ALOGV("%s input %d source = %d status = %d exit",
3050 __FUNCTION__, input, client->source(), status);
Eric Laurente552edb2014-03-10 17:42:56 -07003051
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003052 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07003053}
3054
Eric Laurent8fc147b2018-07-22 19:13:55 -07003055status_t AudioPolicyManager::stopInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07003056{
Eric Laurent8fc147b2018-07-22 19:13:55 -07003057 ALOGV("%s portId %d", __FUNCTION__, portId);
3058
3059 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
3060 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003061 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07003062 return BAD_VALUE;
3063 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07003064 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07003065 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003066 if (!client->active()) {
3067 ALOGW("%s input %d client %d already stopped", __FUNCTION__, input, client->portId());
Eric Laurente552edb2014-03-10 17:42:56 -07003068 return INVALID_OPERATION;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003069 }
Carter Hsue6139d52021-07-08 10:30:20 +08003070 auto old_source = inputDesc->source();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003071 inputDesc->setClientActive(client, false);
Paul McLean466dc8e2015-04-17 13:15:36 -06003072
Eric Laurent8f42ea12018-08-08 09:08:25 -07003073 inputDesc->stop();
3074 if (inputDesc->isActive()) {
Carter Hsue6139d52021-07-08 10:30:20 +08003075 auto current_source = inputDesc->source();
3076 setInputDevice(input, getNewInputDevice(inputDesc),
3077 old_source != current_source /* force */);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003078 } else {
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003079 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003080 // if input maps to a dynamic policy with an activity listener, notify of state change
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003081 if ((policyMix != nullptr)
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003082 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
3083 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
Eric Laurent8f42ea12018-08-08 09:08:25 -07003084 MIX_STATE_IDLE);
Eric Laurent84332aa2016-01-28 22:19:18 +00003085 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07003086
3087 // automatically disable the remote submix output when input is stopped if not
3088 // used by a policy mix of type MIX_TYPE_RECORDERS
François Gaffie11d30102018-11-02 16:09:09 +01003089 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003090 String8 address = String8("");
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003091 if (policyMix == nullptr) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003092 address = String8("0");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003093 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
3094 address = policyMix->mDeviceAddress;
Eric Laurent8f42ea12018-08-08 09:08:25 -07003095 }
3096 if (address != "") {
3097 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
3098 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08003099 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003100 }
3101 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07003102 resetInputDevice(input);
3103
3104 // indicate inactive capture to sound trigger service if stopping capture from a mic on
3105 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01003106 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
3107 if (primaryInputDevices.contains(inputDesc->getDevice()) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07003108 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07003109 mpClientInterface->setSoundTriggerCaptureState(false);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003110 }
3111 inputDesc->clearPreemptedSessions();
Eric Laurente552edb2014-03-10 17:42:56 -07003112 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003113 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07003114}
3115
Eric Laurent8fc147b2018-07-22 19:13:55 -07003116void AudioPolicyManager::releaseInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07003117{
Eric Laurent8fc147b2018-07-22 19:13:55 -07003118 ALOGV("%s portId %d", __FUNCTION__, portId);
3119
3120 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
3121 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003122 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07003123 return;
3124 }
Andy Hung39efb7a2018-09-26 15:39:28 -07003125 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8fc147b2018-07-22 19:13:55 -07003126 audio_io_handle_t input = inputDesc->mIoHandle;
3127
Eric Laurent8f42ea12018-08-08 09:08:25 -07003128 ALOGV("%s %d", __FUNCTION__, input);
Paul McLean466dc8e2015-04-17 13:15:36 -06003129
Andy Hung39efb7a2018-09-26 15:39:28 -07003130 inputDesc->removeClient(portId);
François Gaffie1b4753e2023-02-06 10:36:33 +01003131 mEffects.putOrphanEffects(client->session(), input, &mInputs, mpClientInterface);
Andy Hung39efb7a2018-09-26 15:39:28 -07003132 if (inputDesc->getClientCount() > 0) {
3133 ALOGV("%s(%d) %zu clients remaining", __func__, portId, inputDesc->getClientCount());
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003134 return;
3135 }
3136
Eric Laurent05b90f82014-08-27 15:32:29 -07003137 closeInput(input);
Eric Laurentb52c1522014-05-20 11:27:36 -07003138 mpClientInterface->onAudioPortListUpdate();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003139 ALOGV("%s exit", __FUNCTION__);
Eric Laurente552edb2014-03-10 17:42:56 -07003140}
3141
Eric Laurent8f42ea12018-08-08 09:08:25 -07003142void AudioPolicyManager::closeActiveClients(const sp<AudioInputDescriptor>& input)
Eric Laurent8fc147b2018-07-22 19:13:55 -07003143{
Eric Laurent8f42ea12018-08-08 09:08:25 -07003144 RecordClientVector clients = input->clientsList(true);
Eric Laurent8fc147b2018-07-22 19:13:55 -07003145
3146 for (const auto& client : clients) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003147 closeClient(client->portId());
Eric Laurent8fc147b2018-07-22 19:13:55 -07003148 }
3149}
3150
Eric Laurent8f42ea12018-08-08 09:08:25 -07003151void AudioPolicyManager::closeClient(audio_port_handle_t portId)
3152{
3153 stopInput(portId);
3154 releaseInput(portId);
3155}
Eric Laurent8fc147b2018-07-22 19:13:55 -07003156
Eric Laurent0dd51852019-04-19 18:18:58 -07003157void AudioPolicyManager::checkCloseInputs() {
3158 // After connecting or disconnecting an input device, close input if:
3159 // - it has no client (was just opened to check profile) OR
3160 // - none of its supported devices are connected anymore OR
3161 // - one of its clients cannot be routed to one of its supported
3162 // devices anymore. Otherwise update device selection
3163 std::vector<audio_io_handle_t> inputsToClose;
3164 for (size_t i = 0; i < mInputs.size(); i++) {
3165 const sp<AudioInputDescriptor> input = mInputs.valueAt(i);
3166 if (input->clientsList().size() == 0
Eric Laurent85732f42020-03-19 11:31:10 -07003167 || !mAvailableInputDevices.containsAtLeastOne(input->supportedDevices())) {
Eric Laurent0dd51852019-04-19 18:18:58 -07003168 inputsToClose.push_back(mInputs.keyAt(i));
3169 } else {
3170 bool close = false;
3171 for (const auto& client : input->clientsList()) {
3172 sp<DeviceDescriptor> device =
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02003173 mEngine->getInputDeviceForAttributes(client->attributes(), client->uid(),
3174 client->session());
Eric Laurent0dd51852019-04-19 18:18:58 -07003175 if (!input->supportedDevices().contains(device)) {
3176 close = true;
3177 break;
3178 }
3179 }
3180 if (close) {
3181 inputsToClose.push_back(mInputs.keyAt(i));
3182 } else {
3183 setInputDevice(input->mIoHandle, getNewInputDevice(input));
3184 }
3185 }
3186 }
3187
3188 for (const audio_io_handle_t handle : inputsToClose) {
3189 ALOGV("%s closing input %d", __func__, handle);
3190 closeInput(handle);
Eric Laurent05b90f82014-08-27 15:32:29 -07003191 }
Eric Laurentd4692962014-05-05 18:13:44 -07003192}
3193
François Gaffie251c7f02018-11-07 10:41:08 +01003194void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream, int indexMin, int indexMax)
Eric Laurente552edb2014-03-10 17:42:56 -07003195{
3196 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08003197 if (indexMin < 0 || indexMax < 0) {
3198 ALOGE("%s for stream %d: invalid min %d or max %d", __func__, stream , indexMin, indexMax);
3199 return;
3200 }
Eric Laurentf5aa58d2019-02-22 18:20:11 -08003201 getVolumeCurves(stream).initVolume(indexMin, indexMax);
Eric Laurent28d09f02016-03-08 10:43:05 -08003202
3203 // initialize other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08003204 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
3205 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08003206 continue;
3207 }
Eric Laurentf5aa58d2019-02-22 18:20:11 -08003208 getVolumeCurves((audio_stream_type_t)curStream).initVolume(indexMin, indexMax);
Eric Laurent223fd5c2014-11-11 13:43:36 -08003209 }
Eric Laurente552edb2014-03-10 17:42:56 -07003210}
3211
Eric Laurente0720872014-03-11 09:30:41 -07003212status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
François Gaffie53615e22015-03-19 09:24:12 +01003213 int index,
3214 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07003215{
François Gaffieaaac0fd2018-11-22 17:56:39 +01003216 auto attributes = mEngine->getAttributesForStreamType(stream);
Eric Laurent242a9f82020-03-23 15:57:04 -07003217 if (attributes == AUDIO_ATTRIBUTES_INITIALIZER) {
3218 ALOGW("%s: no group for stream %s, bailing out", __func__, toString(stream).c_str());
3219 return NO_ERROR;
3220 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01003221 ALOGV("%s: stream %s attributes=%s", __func__,
3222 toString(stream).c_str(), toString(attributes).c_str());
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003223 return setVolumeIndexForAttributes(attributes, index, device);
Eric Laurente552edb2014-03-10 17:42:56 -07003224}
3225
Eric Laurente0720872014-03-11 09:30:41 -07003226status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
François Gaffieaaac0fd2018-11-22 17:56:39 +01003227 int *index,
3228 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07003229{
François Gaffiec005e562018-11-06 15:04:49 +01003230 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
3231 // stream by the engine.
jiabin9a3361e2019-10-01 09:38:30 -07003232 DeviceTypeSet deviceTypes = {device};
Eric Laurent5a2b6292016-04-14 18:05:57 -07003233 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
jiabin9a3361e2019-10-01 09:38:30 -07003234 deviceTypes = mEngine->getOutputDevicesForStream(
3235 stream, true /*fromCache*/).types();
Eric Laurente552edb2014-03-10 17:42:56 -07003236 }
jiabin9a3361e2019-10-01 09:38:30 -07003237 return getVolumeIndex(getVolumeCurves(stream), *index, deviceTypes);
Eric Laurente552edb2014-03-10 17:42:56 -07003238}
3239
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003240status_t AudioPolicyManager::setVolumeIndexForAttributes(const audio_attributes_t &attributes,
François Gaffiecfe17322018-11-07 13:41:29 +01003241 int index,
3242 audio_devices_t device)
3243{
3244 // Get Volume group matching the Audio Attributes
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003245 auto group = mEngine->getVolumeGroupForAttributes(attributes);
3246 if (group == VOLUME_GROUP_NONE) {
3247 ALOGD("%s: no group matching with %s", __FUNCTION__, toString(attributes).c_str());
François Gaffiecfe17322018-11-07 13:41:29 +01003248 return BAD_VALUE;
3249 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003250 ALOGV("%s: group %d matching with %s", __FUNCTION__, group, toString(attributes).c_str());
François Gaffiecfe17322018-11-07 13:41:29 +01003251 status_t status = NO_ERROR;
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003252 IVolumeCurves &curves = getVolumeCurves(attributes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01003253 VolumeSource vs = toVolumeSource(group);
Eric Laurentf9cccec2022-11-16 19:12:00 +01003254 // AUDIO_STREAM_BLUETOOTH_SCO is only used for volume control so we remap
3255 // to AUDIO_STREAM_VOICE_CALL to match with relevant playback activity
3256 VolumeSource activityVs = (vs == toVolumeSource(AUDIO_STREAM_BLUETOOTH_SCO, false)) ?
3257 toVolumeSource(AUDIO_STREAM_VOICE_CALL, false) : vs;
François Gaffieaaac0fd2018-11-22 17:56:39 +01003258 product_strategy_t strategy = mEngine->getProductStrategyForAttributes(attributes);
3259
3260 status = setVolumeCurveIndex(index, device, curves);
3261 if (status != NO_ERROR) {
3262 ALOGE("%s failed to set curve index for group %d device 0x%X", __func__, group, device);
3263 return status;
3264 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003265
jiabin9a3361e2019-10-01 09:38:30 -07003266 DeviceTypeSet curSrcDevices;
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003267 auto curCurvAttrs = curves.getAttributes();
3268 if (!curCurvAttrs.empty() && curCurvAttrs.front() != defaultAttr) {
3269 auto attr = curCurvAttrs.front();
jiabin9a3361e2019-10-01 09:38:30 -07003270 curSrcDevices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false).types();
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003271 } else if (!curves.getStreamTypes().empty()) {
3272 auto stream = curves.getStreamTypes().front();
jiabin9a3361e2019-10-01 09:38:30 -07003273 curSrcDevices = mEngine->getOutputDevicesForStream(stream, false).types();
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003274 } else {
3275 ALOGE("%s: Invalid src %d: no valid attributes nor stream",__func__, vs);
3276 return BAD_VALUE;
3277 }
jiabin9a3361e2019-10-01 09:38:30 -07003278 audio_devices_t curSrcDevice = Volume::getDeviceForVolume(curSrcDevices);
3279 resetDeviceTypes(curSrcDevices, curSrcDevice);
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003280
François Gaffiecfe17322018-11-07 13:41:29 +01003281 // update volume on all outputs and streams matching the following:
3282 // - The requested stream (or a stream matching for volume control) is active on the output
3283 // - The device (or devices) selected by the engine for this stream includes
3284 // the requested device
3285 // - For non default requested device, currently selected device on the output is either the
3286 // requested device or one of the devices selected by the engine for this stream
3287 // - For default requested device (AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME), apply volume only if
3288 // no specific device volume value exists for currently selected device.
François Gaffieaaac0fd2018-11-22 17:56:39 +01003289 for (size_t i = 0; i < mOutputs.size(); i++) {
3290 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
jiabin9a3361e2019-10-01 09:38:30 -07003291 DeviceTypeSet curDevices = desc->devices().types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01003292
jiabin9a3361e2019-10-01 09:38:30 -07003293 if (curDevices.erase(AUDIO_DEVICE_OUT_SPEAKER_SAFE)) {
3294 curDevices.insert(AUDIO_DEVICE_OUT_SPEAKER);
Robert Lee5e66e792019-04-03 18:37:15 +08003295 }
Eric Laurentf9cccec2022-11-16 19:12:00 +01003296
3297 if (!(desc->isActive(activityVs) || isInCallOrScreening())) {
François Gaffieed91f582020-01-31 10:35:37 +01003298 continue;
3299 }
3300 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME &&
3301 curDevices.find(device) == curDevices.end()) {
3302 continue;
3303 }
3304 bool applyVolume = false;
3305 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
3306 curSrcDevices.insert(device);
3307 applyVolume = (curSrcDevices.find(
3308 Volume::getDeviceForVolume(curDevices)) != curSrcDevices.end());
3309 } else {
3310 applyVolume = !curves.hasVolumeIndexForDevice(curSrcDevice);
3311 }
3312 if (!applyVolume) {
3313 continue; // next output
3314 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01003315 // Inter / intra volume group priority management: Loop on strategies arranged by priority
3316 // If a higher priority strategy is active, and the output is routed to a device with a
3317 // HW Gain management, do not change the volume
François Gaffieaaac0fd2018-11-22 17:56:39 +01003318 if (desc->useHwGain()) {
François Gaffieed91f582020-01-31 10:35:37 +01003319 applyVolume = false;
Francois Gaffie593634d2021-06-22 13:31:31 +02003320 // If the volume source is active with higher priority source, ensure at least Sw Muted
3321 desc->setSwMute((index == 0), vs, curves.getStreamTypes(), curDevices, 0 /*delayMs*/);
François Gaffieaaac0fd2018-11-22 17:56:39 +01003322 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
3323 auto activeClients = desc->clientsList(true /*activeOnly*/, productStrategy,
3324 false /*preferredDevice*/);
3325 if (activeClients.empty()) {
3326 continue;
3327 }
3328 bool isPreempted = false;
3329 bool isHigherPriority = productStrategy < strategy;
3330 for (const auto &client : activeClients) {
Eric Laurentf9cccec2022-11-16 19:12:00 +01003331 if (isHigherPriority && (client->volumeSource() != activityVs)) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01003332 ALOGV("%s: Strategy=%d (\nrequester:\n"
3333 " group %d, volumeGroup=%d attributes=%s)\n"
3334 " higher priority source active:\n"
3335 " volumeGroup=%d attributes=%s) \n"
3336 " on output %zu, bailing out", __func__, productStrategy,
3337 group, group, toString(attributes).c_str(),
3338 client->volumeSource(), toString(client->attributes()).c_str(), i);
3339 applyVolume = false;
3340 isPreempted = true;
3341 break;
3342 }
3343 // However, continue for loop to ensure no higher prio clients running on output
Eric Laurentf9cccec2022-11-16 19:12:00 +01003344 if (client->volumeSource() == activityVs) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01003345 applyVolume = true;
3346 }
3347 }
3348 if (isPreempted || applyVolume) {
3349 break;
3350 }
3351 }
3352 if (!applyVolume) {
3353 continue; // next output
3354 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01003355 }
François Gaffieed91f582020-01-31 10:35:37 +01003356 //FIXME: workaround for truncated touch sounds
3357 // delayed volume change for system stream to be removed when the problem is
3358 // handled by system UI
3359 status_t volStatus = checkAndSetVolume(
3360 curves, vs, index, desc, curDevices,
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003361 ((vs == toVolumeSource(AUDIO_STREAM_SYSTEM, false))?
François Gaffieed91f582020-01-31 10:35:37 +01003362 TOUCH_SOUND_FIXED_DELAY_MS : 0));
3363 if (volStatus != NO_ERROR) {
3364 status = volStatus;
François Gaffieaaac0fd2018-11-22 17:56:39 +01003365 }
3366 }
François Gaffiecfe17322018-11-07 13:41:29 +01003367 mpClientInterface->onAudioVolumeGroupChanged(group, 0 /*flags*/);
3368 return status;
3369}
3370
François Gaffieaaac0fd2018-11-22 17:56:39 +01003371status_t AudioPolicyManager::setVolumeCurveIndex(int index,
François Gaffiecfe17322018-11-07 13:41:29 +01003372 audio_devices_t device,
3373 IVolumeCurves &volumeCurves)
3374{
3375 // VOICE_CALL stream has minVolumeIndex > 0 but can be muted directly by an
3376 // app that has MODIFY_PHONE_STATE permission.
François Gaffieaaac0fd2018-11-22 17:56:39 +01003377 bool hasVoice = hasVoiceStream(volumeCurves.getStreamTypes());
3378 if (((index < volumeCurves.getVolumeIndexMin()) && !(hasVoice && index == 0)) ||
François Gaffiecfe17322018-11-07 13:41:29 +01003379 (index > volumeCurves.getVolumeIndexMax())) {
3380 ALOGD("%s: wrong index %d min=%d max=%d", __FUNCTION__, index,
3381 volumeCurves.getVolumeIndexMin(), volumeCurves.getVolumeIndexMax());
3382 return BAD_VALUE;
3383 }
3384 if (!audio_is_output_device(device)) {
3385 return BAD_VALUE;
3386 }
3387
3388 // Force max volume if stream cannot be muted
3389 if (!volumeCurves.canBeMuted()) index = volumeCurves.getVolumeIndexMax();
3390
François Gaffieaaac0fd2018-11-22 17:56:39 +01003391 ALOGV("%s device %08x, index %d", __FUNCTION__ , device, index);
François Gaffiecfe17322018-11-07 13:41:29 +01003392 volumeCurves.addCurrentVolumeIndex(device, index);
3393 return NO_ERROR;
3394}
3395
3396status_t AudioPolicyManager::getVolumeIndexForAttributes(const audio_attributes_t &attr,
3397 int &index,
3398 audio_devices_t device)
3399{
3400 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
3401 // stream by the engine.
jiabin9a3361e2019-10-01 09:38:30 -07003402 DeviceTypeSet deviceTypes = {device};
François Gaffiecfe17322018-11-07 13:41:29 +01003403 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
Mikhail Naganovbb990f22022-06-15 00:46:43 +00003404 deviceTypes = mEngine->getOutputDevicesForAttributes(
jiabin9a3361e2019-10-01 09:38:30 -07003405 attr, nullptr, true /*fromCache*/).types();
François Gaffiecfe17322018-11-07 13:41:29 +01003406 }
jiabin9a3361e2019-10-01 09:38:30 -07003407 return getVolumeIndex(getVolumeCurves(attr), index, deviceTypes);
François Gaffiecfe17322018-11-07 13:41:29 +01003408}
3409
3410status_t AudioPolicyManager::getVolumeIndex(const IVolumeCurves &curves,
3411 int &index,
jiabin9a3361e2019-10-01 09:38:30 -07003412 const DeviceTypeSet& deviceTypes) const
François Gaffiecfe17322018-11-07 13:41:29 +01003413{
Mikhail Naganovbb990f22022-06-15 00:46:43 +00003414 if (!isSingleDeviceType(deviceTypes, audio_is_output_device)) {
François Gaffiecfe17322018-11-07 13:41:29 +01003415 return BAD_VALUE;
3416 }
jiabin9a3361e2019-10-01 09:38:30 -07003417 index = curves.getVolumeIndex(deviceTypes);
3418 ALOGV("%s: device %s index %d", __FUNCTION__, dumpDeviceTypes(deviceTypes).c_str(), index);
François Gaffiecfe17322018-11-07 13:41:29 +01003419 return NO_ERROR;
3420}
3421
3422status_t AudioPolicyManager::getMinVolumeIndexForAttributes(const audio_attributes_t &attr,
3423 int &index)
3424{
3425 index = getVolumeCurves(attr).getVolumeIndexMin();
3426 return NO_ERROR;
3427}
3428
3429status_t AudioPolicyManager::getMaxVolumeIndexForAttributes(const audio_attributes_t &attr,
3430 int &index)
3431{
3432 index = getVolumeCurves(attr).getVolumeIndexMax();
3433 return NO_ERROR;
3434}
3435
Eric Laurent36829f92017-04-07 19:04:42 -07003436audio_io_handle_t AudioPolicyManager::selectOutputForMusicEffects()
Eric Laurente552edb2014-03-10 17:42:56 -07003437{
3438 // select one output among several suitable for global effects.
3439 // The priority is as follows:
3440 // 1: An offloaded output. If the effect ends up not being offloadable,
3441 // AudioFlinger will invalidate the track and the offloaded output
3442 // will be closed causing the effect to be moved to a PCM output.
3443 // 2: A deep buffer output
Eric Laurent36829f92017-04-07 19:04:42 -07003444 // 3: The primary output
3445 // 4: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07003446
François Gaffiec005e562018-11-06 15:04:49 +01003447 DeviceVector devices = mEngine->getOutputDevicesForAttributes(
3448 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
François Gaffie11d30102018-11-02 16:09:09 +01003449 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07003450
Eric Laurent36829f92017-04-07 19:04:42 -07003451 if (outputs.size() == 0) {
3452 return AUDIO_IO_HANDLE_NONE;
3453 }
Eric Laurente552edb2014-03-10 17:42:56 -07003454
Eric Laurent36829f92017-04-07 19:04:42 -07003455 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
3456 bool activeOnly = true;
3457
3458 while (output == AUDIO_IO_HANDLE_NONE) {
3459 audio_io_handle_t outputOffloaded = AUDIO_IO_HANDLE_NONE;
3460 audio_io_handle_t outputDeepBuffer = AUDIO_IO_HANDLE_NONE;
3461 audio_io_handle_t outputPrimary = AUDIO_IO_HANDLE_NONE;
3462
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003463 for (audio_io_handle_t output : outputs) {
3464 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
Eric Laurent83d17c22019-04-02 17:10:01 -07003465 if (activeOnly && !desc->isActive(toVolumeSource(AUDIO_STREAM_MUSIC))) {
Eric Laurent36829f92017-04-07 19:04:42 -07003466 continue;
3467 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003468 ALOGV("selectOutputForMusicEffects activeOnly %d output %d flags 0x%08x",
3469 activeOnly, output, desc->mFlags);
Eric Laurent36829f92017-04-07 19:04:42 -07003470 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003471 outputOffloaded = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003472 }
3473 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003474 outputDeepBuffer = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003475 }
3476 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003477 outputPrimary = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003478 }
3479 }
3480 if (outputOffloaded != AUDIO_IO_HANDLE_NONE) {
3481 output = outputOffloaded;
3482 } else if (outputDeepBuffer != AUDIO_IO_HANDLE_NONE) {
3483 output = outputDeepBuffer;
3484 } else if (outputPrimary != AUDIO_IO_HANDLE_NONE) {
3485 output = outputPrimary;
3486 } else {
3487 output = outputs[0];
3488 }
3489 activeOnly = false;
3490 }
3491
3492 if (output != mMusicEffectOutput) {
François Gaffie1b4753e2023-02-06 10:36:33 +01003493 mEffects.moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output,
3494 mpClientInterface);
Eric Laurent36829f92017-04-07 19:04:42 -07003495 mMusicEffectOutput = output;
3496 }
3497
3498 ALOGV("selectOutputForMusicEffects selected output %d", output);
Eric Laurente552edb2014-03-10 17:42:56 -07003499 return output;
3500}
3501
Eric Laurent36829f92017-04-07 19:04:42 -07003502audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc __unused)
3503{
3504 return selectOutputForMusicEffects();
3505}
3506
Eric Laurente0720872014-03-11 09:30:41 -07003507status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07003508 audio_io_handle_t io,
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08003509 product_strategy_t strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07003510 int session,
3511 int id)
3512{
Eric Laurentb82e6b72019-11-22 17:25:04 -08003513 if (session != AUDIO_SESSION_DEVICE) {
3514 ssize_t index = mOutputs.indexOfKey(io);
Eric Laurente552edb2014-03-10 17:42:56 -07003515 if (index < 0) {
Eric Laurentb82e6b72019-11-22 17:25:04 -08003516 index = mInputs.indexOfKey(io);
3517 if (index < 0) {
3518 ALOGW("registerEffect() unknown io %d", io);
3519 return INVALID_OPERATION;
3520 }
Eric Laurente552edb2014-03-10 17:42:56 -07003521 }
3522 }
Eric Laurentbf8f69f2022-03-25 17:48:38 +01003523 bool isMusicEffect = (session != AUDIO_SESSION_OUTPUT_STAGE)
3524 && ((strategy == streamToStrategy(AUDIO_STREAM_MUSIC)
3525 || strategy == PRODUCT_STRATEGY_NONE));
3526 return mEffects.registerEffect(desc, io, session, id, isMusicEffect);
Eric Laurente552edb2014-03-10 17:42:56 -07003527}
3528
Eric Laurentc241b0d2018-11-28 09:08:49 -08003529status_t AudioPolicyManager::unregisterEffect(int id)
3530{
3531 if (mEffects.getEffect(id) == nullptr) {
3532 return INVALID_OPERATION;
3533 }
Eric Laurentc241b0d2018-11-28 09:08:49 -08003534 if (mEffects.isEffectEnabled(id)) {
3535 ALOGW("%s effect %d enabled", __FUNCTION__, id);
3536 setEffectEnabled(id, false);
3537 }
3538 return mEffects.unregisterEffect(id);
3539}
3540
3541status_t AudioPolicyManager::setEffectEnabled(int id, bool enabled)
3542{
3543 sp<EffectDescriptor> effect = mEffects.getEffect(id);
3544 if (effect == nullptr) {
3545 return INVALID_OPERATION;
3546 }
3547
3548 status_t status = mEffects.setEffectEnabled(id, enabled);
3549 if (status == NO_ERROR) {
3550 mInputs.trackEffectEnabled(effect, enabled);
3551 }
3552 return status;
3553}
3554
Eric Laurent6c796322019-04-09 14:13:17 -07003555
3556status_t AudioPolicyManager::moveEffectsToIo(const std::vector<int>& ids, audio_io_handle_t io)
3557{
3558 mEffects.moveEffects(ids, io);
3559 return NO_ERROR;
3560}
3561
Eric Laurentc75307b2015-03-17 15:29:32 -07003562bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
3563{
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003564 auto vs = toVolumeSource(stream, false);
3565 return vs != VOLUME_SOURCE_NONE ? mOutputs.isActive(vs, inPastMs) : false;
Eric Laurentc75307b2015-03-17 15:29:32 -07003566}
3567
3568bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream, uint32_t inPastMs) const
3569{
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003570 auto vs = toVolumeSource(stream, false);
3571 return vs != VOLUME_SOURCE_NONE ? mOutputs.isActiveRemotely(vs, inPastMs) : false;
Eric Laurentc75307b2015-03-17 15:29:32 -07003572}
3573
Eric Laurente0720872014-03-11 09:30:41 -07003574bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07003575{
3576 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003577 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08003578 if (inputDescriptor->isSourceActive(source)) {
Eric Laurente552edb2014-03-10 17:42:56 -07003579 return true;
3580 }
3581 }
3582 return false;
3583}
3584
Eric Laurent275e8e92014-11-30 15:14:47 -08003585// Register a list of custom mixes with their attributes and format.
3586// When a mix is registered, corresponding input and output profiles are
3587// added to the remote submix hw module. The profile contains only the
3588// parameters (sampling rate, format...) specified by the mix.
3589// The corresponding input remote submix device is also connected.
3590//
3591// When a remote submix device is connected, the address is checked to select the
3592// appropriate profile and the corresponding input or output stream is opened.
3593//
3594// When capture starts, getInputForAttr() will:
3595// - 1 look for a mix matching the address passed in attribtutes tags if any
3596// - 2 if none found, getDeviceForInputSource() will:
3597// - 2.1 look for a mix matching the attributes source
3598// - 2.2 if none found, default to device selection by policy rules
3599// At this time, the corresponding output remote submix device is also connected
3600// and active playback use cases can be transferred to this mix if needed when reconnecting
3601// after AudioTracks are invalidated
3602//
3603// When playback starts, getOutputForAttr() will:
3604// - 1 look for a mix matching the address passed in attribtutes tags if any
3605// - 2 if none found, look for a mix matching the attributes usage
3606// - 3 if none found, default to device and output selection by policy rules.
3607
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003608status_t AudioPolicyManager::registerPolicyMixes(const Vector<AudioMix>& mixes)
Eric Laurent275e8e92014-11-30 15:14:47 -08003609{
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003610 ALOGV("registerPolicyMixes() %zu mix(es)", mixes.size());
3611 status_t res = NO_ERROR;
Eric Laurentc209fe42020-06-05 18:11:23 -07003612 bool checkOutputs = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003613 sp<HwModule> rSubmixModule;
3614 // examine each mix's route type
3615 for (size_t i = 0; i < mixes.size(); i++) {
Eric Laurent97ac8712018-07-27 18:59:02 -07003616 AudioMix mix = mixes[i];
Kevin Rocard153f92d2018-12-18 18:33:28 -08003617 // Only capture of playback is allowed in LOOP_BACK & RENDER mode
3618 if (is_mix_loopback_render(mix.mRouteFlags) && mix.mMixType != MIX_TYPE_PLAYERS) {
3619 ALOGE("Unsupported Policy Mix %zu of %zu: "
3620 "Only capture of playback is allowed in LOOP_BACK & RENDER mode",
3621 i, mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003622 res = INVALID_OPERATION;
Eric Laurent275e8e92014-11-30 15:14:47 -08003623 break;
3624 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08003625 // LOOP_BACK and LOOP_BACK | RENDER have the same remote submix backend and are handled
3626 // in the same way.
Eric Laurent97ac8712018-07-27 18:59:02 -07003627 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003628 ALOGV("registerPolicyMixes() mix %zu of %zu is LOOP_BACK %d", i, mixes.size(),
3629 mix.mRouteFlags);
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003630 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003631 rSubmixModule = mHwModules.getModuleFromName(
3632 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
3633 if (rSubmixModule == 0) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003634 ALOGE("Unable to find audio module for submix, aborting mix %zu registration",
Mikhail Naganovd4120142017-12-06 15:49:22 -08003635 i);
3636 res = INVALID_OPERATION;
3637 break;
3638 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003639 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003640
Eric Laurent97ac8712018-07-27 18:59:02 -07003641 String8 address = mix.mDeviceAddress;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003642 audio_devices_t deviceTypeToMakeAvailable;
Eric Laurent97ac8712018-07-27 18:59:02 -07003643 if (mix.mMixType == MIX_TYPE_PLAYERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07003644 mix.mDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003645 deviceTypeToMakeAvailable = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
3646 } else {
3647 mix.mDeviceType = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
3648 deviceTypeToMakeAvailable = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Eric Laurent97ac8712018-07-27 18:59:02 -07003649 }
François Gaffie036e1e92015-03-19 10:16:24 +01003650
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003651 if (mPolicyMixes.registerMix(mix, 0 /*output desc*/) != NO_ERROR) {
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003652 ALOGE("Error registering mix %zu for address %s", i, address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003653 res = INVALID_OPERATION;
3654 break;
3655 }
Eric Laurent97ac8712018-07-27 18:59:02 -07003656 audio_config_t outputConfig = mix.mFormat;
3657 audio_config_t inputConfig = mix.mFormat;
Eric Laurentc529cf62020-04-17 18:19:10 -07003658 // NOTE: audio flinger mixer does not support mono output: configure remote submix HAL
3659 // in stereo and let audio flinger do the channel conversion if needed.
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003660 outputConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
3661 inputConfig.channel_mask = AUDIO_CHANNEL_IN_STEREO;
jiabin5740f082019-08-19 15:08:30 -07003662 rSubmixModule->addOutputProfile(address.c_str(), &outputConfig,
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003663 AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address);
jiabin5740f082019-08-19 15:08:30 -07003664 rSubmixModule->addInputProfile(address.c_str(), &inputConfig,
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003665 AUDIO_DEVICE_IN_REMOTE_SUBMIX, address);
François Gaffie036e1e92015-03-19 10:16:24 +01003666
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003667 if ((res = setDeviceConnectionStateInt(deviceTypeToMakeAvailable,
jiabinc1de2df2019-05-07 14:26:40 -07003668 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003669 address.c_str(), "remote-submix", AUDIO_FORMAT_DEFAULT)) != NO_ERROR) {
jiabinc1de2df2019-05-07 14:26:40 -07003670 ALOGE("Failed to set remote submix device available, type %u, address %s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003671 mix.mDeviceType, address.c_str());
jiabinc1de2df2019-05-07 14:26:40 -07003672 break;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003673 }
Eric Laurent97ac8712018-07-27 18:59:02 -07003674 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
3675 String8 address = mix.mDeviceAddress;
Eric Laurent2c80be02019-01-23 18:06:37 -08003676 audio_devices_t type = mix.mDeviceType;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003677 ALOGV(" registerPolicyMixes() mix %zu of %zu is RENDER, dev=0x%X addr=%s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003678 i, mixes.size(), type, address.c_str());
Eric Laurent2c80be02019-01-23 18:06:37 -08003679
3680 sp<DeviceDescriptor> device = mHwModules.getDeviceDescriptor(
3681 mix.mDeviceType, mix.mDeviceAddress,
3682 String8(), AUDIO_FORMAT_DEFAULT);
3683 if (device == nullptr) {
3684 res = INVALID_OPERATION;
3685 break;
3686 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003687
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003688 bool foundOutput = false;
Eric Laurentc529cf62020-04-17 18:19:10 -07003689 // First try to find an already opened output supporting the device
3690 for (size_t j = 0 ; j < mOutputs.size() && !foundOutput && res == NO_ERROR; j++) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003691 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurent2c80be02019-01-23 18:06:37 -08003692
Eric Laurentc529cf62020-04-17 18:19:10 -07003693 if (!desc->isDuplicated() && desc->supportedDevices().contains(device)) {
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003694 if (mPolicyMixes.registerMix(mix, desc) != NO_ERROR) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003695 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003696 address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003697 res = INVALID_OPERATION;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003698 } else {
3699 foundOutput = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003700 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003701 }
3702 }
Eric Laurentc529cf62020-04-17 18:19:10 -07003703 // If no output found, try to find a direct output profile supporting the device
3704 for (size_t i = 0; i < mHwModules.size() && !foundOutput && res == NO_ERROR; i++) {
3705 sp<HwModule> module = mHwModules[i];
3706 for (size_t j = 0;
3707 j < module->getOutputProfiles().size() && !foundOutput && res == NO_ERROR;
3708 j++) {
3709 sp<IOProfile> profile = module->getOutputProfiles()[j];
3710 if (profile->isDirectOutput() && profile->supportsDevice(device)) {
3711 if (mPolicyMixes.registerMix(mix, nullptr) != NO_ERROR) {
3712 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003713 address.c_str());
Eric Laurentc529cf62020-04-17 18:19:10 -07003714 res = INVALID_OPERATION;
3715 } else {
3716 foundOutput = true;
3717 }
3718 }
3719 }
3720 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003721 if (res != NO_ERROR) {
3722 ALOGE(" Error registering mix %zu for device 0x%X addr %s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003723 i, type, address.c_str());
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003724 res = INVALID_OPERATION;
3725 break;
3726 } else if (!foundOutput) {
3727 ALOGE(" Output not found for mix %zu for device 0x%X addr %s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003728 i, type, address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003729 res = INVALID_OPERATION;
3730 break;
Eric Laurentc209fe42020-06-05 18:11:23 -07003731 } else {
3732 checkOutputs = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003733 }
Eric Laurentc722f302014-12-10 11:21:49 -08003734 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003735 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003736 if (res != NO_ERROR) {
3737 unregisterPolicyMixes(mixes);
Eric Laurentc209fe42020-06-05 18:11:23 -07003738 } else if (checkOutputs) {
3739 checkForDeviceAndOutputChanges();
3740 updateCallAndOutputRouting();
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003741 }
3742 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08003743}
3744
3745status_t AudioPolicyManager::unregisterPolicyMixes(Vector<AudioMix> mixes)
3746{
Eric Laurent7b279bb2015-12-14 10:18:23 -08003747 ALOGV("unregisterPolicyMixes() num mixes %zu", mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003748 status_t res = NO_ERROR;
Eric Laurentc209fe42020-06-05 18:11:23 -07003749 bool checkOutputs = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003750 sp<HwModule> rSubmixModule;
3751 // examine each mix's route type
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003752 for (const auto& mix : mixes) {
3753 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie036e1e92015-03-19 10:16:24 +01003754
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003755 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003756 rSubmixModule = mHwModules.getModuleFromName(
3757 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
3758 if (rSubmixModule == 0) {
3759 res = INVALID_OPERATION;
3760 continue;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003761 }
3762 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003763
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003764 String8 address = mix.mDeviceAddress;
Eric Laurent275e8e92014-11-30 15:14:47 -08003765
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003766 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003767 res = INVALID_OPERATION;
3768 continue;
3769 }
3770
Kevin Rocard04ed0462019-05-02 17:53:24 -07003771 for (auto device : {AUDIO_DEVICE_IN_REMOTE_SUBMIX, AUDIO_DEVICE_OUT_REMOTE_SUBMIX}) {
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003772 if (getDeviceConnectionState(device, address.c_str()) ==
Kevin Rocard04ed0462019-05-02 17:53:24 -07003773 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
3774 res = setDeviceConnectionStateInt(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003775 address.c_str(), "remote-submix",
Kevin Rocard04ed0462019-05-02 17:53:24 -07003776 AUDIO_FORMAT_DEFAULT);
3777 if (res != OK) {
3778 ALOGE("Error making RemoteSubmix device unavailable for mix "
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003779 "with type %d, address %s", device, address.c_str());
Kevin Rocard04ed0462019-05-02 17:53:24 -07003780 }
3781 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003782 }
jiabin5740f082019-08-19 15:08:30 -07003783 rSubmixModule->removeOutputProfile(address.c_str());
3784 rSubmixModule->removeInputProfile(address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003785
Kevin Rocard153f92d2018-12-18 18:33:28 -08003786 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003787 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003788 res = INVALID_OPERATION;
3789 continue;
Eric Laurentc209fe42020-06-05 18:11:23 -07003790 } else {
3791 checkOutputs = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003792 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003793 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003794 }
Eric Laurentc209fe42020-06-05 18:11:23 -07003795 if (res == NO_ERROR && checkOutputs) {
3796 checkForDeviceAndOutputChanges();
3797 updateCallAndOutputRouting();
3798 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003799 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08003800}
3801
Jan Sebechlebsky0af8e872023-08-11 14:45:08 +02003802status_t AudioPolicyManager::updatePolicyMix(
3803 const AudioMix& mix,
3804 const std::vector<AudioMixMatchCriterion>& updatedCriteria) {
3805 status_t res = mPolicyMixes.updateMix(mix, updatedCriteria);
3806 if (res == NO_ERROR) {
3807 checkForDeviceAndOutputChanges();
3808 updateCallAndOutputRouting();
3809 }
3810 return res;
3811}
3812
Mikhail Naganov100f0122018-11-29 11:22:16 -08003813void AudioPolicyManager::dumpManualSurroundFormats(String8 *dst) const
3814{
3815 size_t i = 0;
3816 constexpr size_t audioFormatPrefixLen = sizeof("AUDIO_FORMAT_");
3817 for (const auto& fmt : mManualSurroundFormats) {
3818 if (i++ != 0) dst->append(", ");
3819 std::string sfmt;
3820 FormatConverter::toString(fmt, sfmt);
3821 dst->append(sfmt.size() >= audioFormatPrefixLen ?
3822 sfmt.c_str() + audioFormatPrefixLen - 1 : sfmt.c_str());
3823 }
3824}
3825
Eric Laurentc529cf62020-04-17 18:19:10 -07003826// Returns true if all devices types match the predicate and are supported by one HW module
3827bool AudioPolicyManager::areAllDevicesSupported(
jiabin6a02d532020-08-07 11:56:38 -07003828 const AudioDeviceTypeAddrVector& devices,
Eric Laurentc529cf62020-04-17 18:19:10 -07003829 std::function<bool(audio_devices_t)> predicate,
Eric Laurent78fedbf2023-03-09 14:40:44 +01003830 const char *context,
3831 bool matchAddress) {
Eric Laurentc529cf62020-04-17 18:19:10 -07003832 for (size_t i = 0; i < devices.size(); i++) {
3833 sp<DeviceDescriptor> devDesc = mHwModules.getDeviceDescriptor(
jiabin0a488932020-08-07 17:32:40 -07003834 devices[i].mType, devices[i].getAddress(), String8(),
Eric Laurent78fedbf2023-03-09 14:40:44 +01003835 AUDIO_FORMAT_DEFAULT, false /*allowToCreate*/, matchAddress);
Eric Laurentc529cf62020-04-17 18:19:10 -07003836 if (devDesc == nullptr || (predicate != nullptr && !predicate(devices[i].mType))) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003837 ALOGE("%s: device type %#x address %s not supported or not match predicate",
jiabin0a488932020-08-07 17:32:40 -07003838 context, devices[i].mType, devices[i].getAddress());
Eric Laurentc529cf62020-04-17 18:19:10 -07003839 return false;
3840 }
3841 }
3842 return true;
3843}
3844
Oscar Azucena6acf34b2023-04-27 16:32:09 -07003845void AudioPolicyManager::changeOutputDevicesMuteState(
3846 const AudioDeviceTypeAddrVector& devices) {
3847 ALOGVV("%s() num devices %zu", __func__, devices.size());
3848
3849 std::vector<sp<SwAudioOutputDescriptor>> outputs =
3850 getSoftwareOutputsForDevices(devices);
3851
3852 for (size_t i = 0; i < outputs.size(); i++) {
3853 sp<SwAudioOutputDescriptor> outputDesc = outputs[i];
3854 DeviceVector prevDevices = outputDesc->devices();
3855 checkDeviceMuteStrategies(outputDesc, prevDevices, 0 /* delayMs */);
3856 }
3857}
3858
3859std::vector<sp<SwAudioOutputDescriptor>> AudioPolicyManager::getSoftwareOutputsForDevices(
3860 const AudioDeviceTypeAddrVector& devices) const
3861{
3862 std::vector<sp<SwAudioOutputDescriptor>> outputs;
3863 DeviceVector deviceDescriptors;
3864 for (size_t j = 0; j < devices.size(); j++) {
3865 sp<DeviceDescriptor> desc = mHwModules.getDeviceDescriptor(
3866 devices[j].mType, devices[j].getAddress(), String8(), AUDIO_FORMAT_DEFAULT);
3867 if (desc == nullptr || !audio_is_output_device(devices[j].mType)) {
3868 ALOGE("%s: device type %#x address %s not supported or not an output device",
3869 __func__, devices[j].mType, devices[j].getAddress());
3870 continue;
3871 }
3872 deviceDescriptors.add(desc);
3873 }
3874 for (size_t i = 0; i < mOutputs.size(); i++) {
3875 if (!mOutputs.valueAt(i)->supportsAtLeastOne(deviceDescriptors)) {
3876 continue;
3877 }
3878 outputs.push_back(mOutputs.valueAt(i));
3879 }
3880 return outputs;
3881}
3882
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003883status_t AudioPolicyManager::setUidDeviceAffinities(uid_t uid,
jiabin6a02d532020-08-07 11:56:38 -07003884 const AudioDeviceTypeAddrVector& devices) {
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003885 ALOGV("%s() uid=%d num devices %zu", __FUNCTION__, uid, devices.size());
Eric Laurentc529cf62020-04-17 18:19:10 -07003886 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
3887 return BAD_VALUE;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003888 }
3889 status_t res = mPolicyMixes.setUidDeviceAffinities(uid, devices);
Eric Laurentc529cf62020-04-17 18:19:10 -07003890 if (res != NO_ERROR) {
3891 ALOGE("%s() Could not set all device affinities for uid = %d", __FUNCTION__, uid);
3892 return res;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003893 }
Eric Laurentc529cf62020-04-17 18:19:10 -07003894
3895 checkForDeviceAndOutputChanges();
3896 updateCallAndOutputRouting();
3897
3898 return NO_ERROR;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003899}
3900
3901status_t AudioPolicyManager::removeUidDeviceAffinities(uid_t uid) {
3902 ALOGV("%s() uid=%d", __FUNCTION__, uid);
Oscar Azucena4b2a8212019-04-26 23:48:59 -07003903 status_t res = mPolicyMixes.removeUidDeviceAffinities(uid);
3904 if (res != NO_ERROR) {
Eric Laurentc529cf62020-04-17 18:19:10 -07003905 ALOGE("%s() Could not remove all device affinities for uid = %d",
Oscar Azucena4b2a8212019-04-26 23:48:59 -07003906 __FUNCTION__, uid);
3907 return INVALID_OPERATION;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003908 }
3909
Eric Laurentc529cf62020-04-17 18:19:10 -07003910 checkForDeviceAndOutputChanges();
3911 updateCallAndOutputRouting();
3912
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003913 return res;
3914}
3915
Eric Laurent2517af32020-11-25 15:31:27 +01003916
jiabin0a488932020-08-07 17:32:40 -07003917status_t AudioPolicyManager::setDevicesRoleForStrategy(product_strategy_t strategy,
3918 device_role_t role,
3919 const AudioDeviceTypeAddrVector &devices) {
3920 ALOGV("%s() strategy=%d role=%d %s", __func__, strategy, role,
3921 dumpAudioDeviceTypeAddrVector(devices).c_str());
Eric Laurentc529cf62020-04-17 18:19:10 -07003922
Eric Laurentc529cf62020-04-17 18:19:10 -07003923 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003924 return BAD_VALUE;
3925 }
jiabin0a488932020-08-07 17:32:40 -07003926 status_t status = mEngine->setDevicesRoleForStrategy(strategy, role, devices);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003927 if (status != NO_ERROR) {
jiabin0a488932020-08-07 17:32:40 -07003928 ALOGW("Engine could not set preferred devices %s for strategy %d role %d",
3929 dumpAudioDeviceTypeAddrVector(devices).c_str(), strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003930 return status;
3931 }
3932
3933 checkForDeviceAndOutputChanges();
Eric Laurent2517af32020-11-25 15:31:27 +01003934
3935 bool forceVolumeReeval = false;
3936 // FIXME: workaround for truncated touch sounds
3937 // to be removed when the problem is handled by system UI
3938 uint32_t delayMs = 0;
3939 if (strategy == mCommunnicationStrategy) {
3940 forceVolumeReeval = true;
3941 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
3942 updateInputRouting();
3943 }
3944 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003945
3946 return NO_ERROR;
3947}
3948
Oscar Azucena6acf34b2023-04-27 16:32:09 -07003949void AudioPolicyManager::updateCallAndOutputRouting(bool forceVolumeReeval, uint32_t delayMs,
3950 bool skipDelays)
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003951{
3952 uint32_t waitMs = 0;
Eric Laurent96d1dda2022-03-14 17:14:19 +01003953 bool wasLeUnicastActive = isLeUnicastActive();
Francois Gaffie19fd6c52021-02-04 17:02:59 +01003954 if (updateCallRouting(true /*fromCache*/, delayMs, &waitMs) == NO_ERROR) {
Eric Laurentb36b4ac2020-08-21 12:50:41 -07003955 // Only apply special touch sound delay once
3956 delayMs = 0;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003957 }
jiabin3ff8d7d2022-12-13 06:27:44 +00003958 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003959 for (size_t i = 0; i < mOutputs.size(); i++) {
3960 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
3961 DeviceVector newDevices = getNewOutputDevices(outputDesc, true /*fromCache*/);
Francois Gaffie601801d2021-06-22 13:27:39 +02003962 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) ||
3963 (outputDesc != mPrimaryOutput && !isTelephonyRxOrTx(outputDesc))) {
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003964 // As done in setDeviceConnectionState, we could also fix default device issue by
3965 // preventing the force re-routing in case of default dev that distinguishes on address.
3966 // Let's give back to engine full device choice decision however.
Francois Gaffie601801d2021-06-22 13:27:39 +02003967 bool forceRouting = !newDevices.isEmpty();
jiabin3ff8d7d2022-12-13 06:27:44 +00003968 if (outputDesc->mUsePreferredMixerAttributes && newDevices != outputDesc->devices()) {
3969 // If the device is using preferred mixer attributes, the output need to reopen
3970 // with default configuration when the new selected devices are different from
3971 // current routing devices.
3972 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices);
3973 continue;
3974 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05303975
3976 waitMs = setOutputDevices(__func__, outputDesc, newDevices, forceRouting, delayMs,
3977 nullptr, !skipDelays /*requiresMuteCheck*/,
Oscar Azucena6acf34b2023-04-27 16:32:09 -07003978 !forceRouting /*requiresVolumeCheck*/, skipDelays);
Eric Laurentb36b4ac2020-08-21 12:50:41 -07003979 // Only apply special touch sound delay once
3980 delayMs = 0;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003981 }
3982 if (forceVolumeReeval && !newDevices.isEmpty()) {
3983 applyStreamVolumes(outputDesc, newDevices.types(), waitMs, true);
3984 }
3985 }
jiabin3ff8d7d2022-12-13 06:27:44 +00003986 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent96d1dda2022-03-14 17:14:19 +01003987 checkLeBroadcastRoutes(wasLeUnicastActive, nullptr, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003988}
3989
Eric Laurent2517af32020-11-25 15:31:27 +01003990void AudioPolicyManager::updateInputRouting() {
3991 for (const auto& activeDesc : mInputs.getActiveInputs()) {
Jaideep Sharma408349a2020-11-27 14:47:17 +05303992 // Skip for hotword recording as the input device switch
3993 // is handled within sound trigger HAL
3994 if (activeDesc->isSoundTrigger() && activeDesc->source() == AUDIO_SOURCE_HOTWORD) {
3995 continue;
3996 }
Eric Laurent2517af32020-11-25 15:31:27 +01003997 auto newDevice = getNewInputDevice(activeDesc);
3998 // Force new input selection if the new device can not be reached via current input
3999 if (activeDesc->mProfile->getSupportedDevices().contains(newDevice)) {
4000 setInputDevice(activeDesc->mIoHandle, newDevice);
4001 } else {
4002 closeInput(activeDesc->mIoHandle);
4003 }
4004 }
4005}
4006
Paul Wang5d7cdb52022-11-22 09:45:06 +00004007status_t
4008AudioPolicyManager::removeDevicesRoleForStrategy(product_strategy_t strategy,
4009 device_role_t role,
4010 const AudioDeviceTypeAddrVector &devices) {
4011 ALOGV("%s() strategy=%d role=%d %s", __func__, strategy, role,
4012 dumpAudioDeviceTypeAddrVector(devices).c_str());
4013
Eric Laurent78fedbf2023-03-09 14:40:44 +01004014 if (!areAllDevicesSupported(
4015 devices, audio_is_output_device, __func__, /*matchAddress*/false)) {
Paul Wang5d7cdb52022-11-22 09:45:06 +00004016 return BAD_VALUE;
4017 }
4018 status_t status = mEngine->removeDevicesRoleForStrategy(strategy, role, devices);
4019 if (status != NO_ERROR) {
4020 ALOGW("Engine could not remove devices %s for strategy %d role %d",
4021 dumpAudioDeviceTypeAddrVector(devices).c_str(), strategy, role);
4022 return status;
4023 }
4024
4025 checkForDeviceAndOutputChanges();
4026
4027 bool forceVolumeReeval = false;
4028 // TODO(b/263479999): workaround for truncated touch sounds
4029 // to be removed when the problem is handled by system UI
4030 uint32_t delayMs = 0;
4031 if (strategy == mCommunnicationStrategy) {
4032 forceVolumeReeval = true;
4033 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
4034 updateInputRouting();
4035 }
4036 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
4037
4038 return NO_ERROR;
4039}
4040
4041status_t AudioPolicyManager::clearDevicesRoleForStrategy(product_strategy_t strategy,
4042 device_role_t role)
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004043{
Eric Laurentfecbceb2021-02-09 14:46:43 +01004044 ALOGV("%s() strategy=%d role=%d", __func__, strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004045
Paul Wang5d7cdb52022-11-22 09:45:06 +00004046 status_t status = mEngine->clearDevicesRoleForStrategy(strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004047 if (status != NO_ERROR) {
Eric Laurent9ae44f32022-12-14 16:17:02 +01004048 ALOGW_IF(status != NAME_NOT_FOUND,
4049 "Engine could not remove device role for strategy %d status %d",
Eric Laurent2517af32020-11-25 15:31:27 +01004050 strategy, status);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004051 return status;
4052 }
4053
4054 checkForDeviceAndOutputChanges();
Eric Laurent2517af32020-11-25 15:31:27 +01004055
4056 bool forceVolumeReeval = false;
4057 // FIXME: workaround for truncated touch sounds
4058 // to be removed when the problem is handled by system UI
4059 uint32_t delayMs = 0;
4060 if (strategy == mCommunnicationStrategy) {
4061 forceVolumeReeval = true;
4062 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
4063 updateInputRouting();
4064 }
4065 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004066
4067 return NO_ERROR;
4068}
4069
jiabin0a488932020-08-07 17:32:40 -07004070status_t AudioPolicyManager::getDevicesForRoleAndStrategy(product_strategy_t strategy,
4071 device_role_t role,
4072 AudioDeviceTypeAddrVector &devices) {
4073 return mEngine->getDevicesForRoleAndStrategy(strategy, role, devices);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004074}
4075
Jiabin Huang3b98d322020-09-03 17:54:16 +00004076status_t AudioPolicyManager::setDevicesRoleForCapturePreset(
4077 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices) {
4078 ALOGV("%s() audioSource=%d role=%d %s", __func__, audioSource, role,
4079 dumpAudioDeviceTypeAddrVector(devices).c_str());
4080
Mikhail Naganov55773032020-10-01 15:08:13 -07004081 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00004082 return BAD_VALUE;
4083 }
4084 status_t status = mEngine->setDevicesRoleForCapturePreset(audioSource, role, devices);
4085 ALOGW_IF(status != NO_ERROR,
4086 "Engine could not set preferred devices %s for audio source %d role %d",
4087 dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
4088
4089 return status;
4090}
4091
4092status_t AudioPolicyManager::addDevicesRoleForCapturePreset(
4093 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices) {
4094 ALOGV("%s() audioSource=%d role=%d %s", __func__, audioSource, role,
4095 dumpAudioDeviceTypeAddrVector(devices).c_str());
4096
Mikhail Naganov55773032020-10-01 15:08:13 -07004097 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00004098 return BAD_VALUE;
4099 }
4100 status_t status = mEngine->addDevicesRoleForCapturePreset(audioSource, role, devices);
4101 ALOGW_IF(status != NO_ERROR,
4102 "Engine could not add preferred devices %s for audio source %d role %d",
4103 dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
4104
Eric Laurent2517af32020-11-25 15:31:27 +01004105 updateInputRouting();
Jiabin Huang3b98d322020-09-03 17:54:16 +00004106 return status;
4107}
4108
4109status_t AudioPolicyManager::removeDevicesRoleForCapturePreset(
4110 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector& devices)
4111{
4112 ALOGV("%s() audioSource=%d role=%d devices=%s", __func__, audioSource, role,
4113 dumpAudioDeviceTypeAddrVector(devices).c_str());
4114
Eric Laurent78fedbf2023-03-09 14:40:44 +01004115 if (!areAllDevicesSupported(
4116 devices, audio_call_is_input_device, __func__, /*matchAddress*/false)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00004117 return BAD_VALUE;
4118 }
4119
4120 status_t status = mEngine->removeDevicesRoleForCapturePreset(
4121 audioSource, role, devices);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004122 ALOGW_IF(status != NO_ERROR && status != NAME_NOT_FOUND,
Jiabin Huang3b98d322020-09-03 17:54:16 +00004123 "Engine could not remove devices role (%d) for capture preset %d", role, audioSource);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004124 if (status == NO_ERROR) {
4125 updateInputRouting();
4126 }
Jiabin Huang3b98d322020-09-03 17:54:16 +00004127 return status;
4128}
4129
4130status_t AudioPolicyManager::clearDevicesRoleForCapturePreset(audio_source_t audioSource,
4131 device_role_t role) {
4132 ALOGV("%s() audioSource=%d role=%d", __func__, audioSource, role);
4133
4134 status_t status = mEngine->clearDevicesRoleForCapturePreset(audioSource, role);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004135 ALOGW_IF(status != NO_ERROR && status != NAME_NOT_FOUND,
Jiabin Huang3b98d322020-09-03 17:54:16 +00004136 "Engine could not clear devices role (%d) for capture preset %d", role, audioSource);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004137 if (status == NO_ERROR) {
4138 updateInputRouting();
4139 }
Jiabin Huang3b98d322020-09-03 17:54:16 +00004140 return status;
4141}
4142
4143status_t AudioPolicyManager::getDevicesForRoleAndCapturePreset(
4144 audio_source_t audioSource, device_role_t role, AudioDeviceTypeAddrVector &devices) {
4145 return mEngine->getDevicesForRoleAndCapturePreset(audioSource, role, devices);
4146}
4147
Oscar Azucena90e77632019-11-27 17:12:28 -08004148status_t AudioPolicyManager::setUserIdDeviceAffinities(int userId,
jiabin6a02d532020-08-07 11:56:38 -07004149 const AudioDeviceTypeAddrVector& devices) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01004150 ALOGV("%s() userId=%d num devices %zu", __func__, userId, devices.size());
Eric Laurentc529cf62020-04-17 18:19:10 -07004151 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
4152 return BAD_VALUE;
Oscar Azucena90e77632019-11-27 17:12:28 -08004153 }
Oscar Azucena90e77632019-11-27 17:12:28 -08004154 status_t status = mPolicyMixes.setUserIdDeviceAffinities(userId, devices);
4155 if (status != NO_ERROR) {
4156 ALOGE("%s() could not set device affinity for userId %d",
4157 __FUNCTION__, userId);
4158 return status;
4159 }
4160
4161 // reevaluate outputs for all devices
4162 checkForDeviceAndOutputChanges();
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004163 changeOutputDevicesMuteState(devices);
4164 updateCallAndOutputRouting(false /* forceVolumeReeval */, 0 /* delayMs */,
4165 true /* skipDelays */);
4166 changeOutputDevicesMuteState(devices);
Oscar Azucena90e77632019-11-27 17:12:28 -08004167
4168 return NO_ERROR;
4169}
4170
4171status_t AudioPolicyManager::removeUserIdDeviceAffinities(int userId) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01004172 ALOGV("%s() userId=%d", __FUNCTION__, userId);
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004173 AudioDeviceTypeAddrVector devices;
4174 mPolicyMixes.getDevicesForUserId(userId, devices);
Oscar Azucena90e77632019-11-27 17:12:28 -08004175 status_t status = mPolicyMixes.removeUserIdDeviceAffinities(userId);
4176 if (status != NO_ERROR) {
4177 ALOGE("%s() Could not remove all device affinities fo userId = %d",
4178 __FUNCTION__, userId);
4179 return status;
4180 }
4181
4182 // reevaluate outputs for all devices
4183 checkForDeviceAndOutputChanges();
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004184 changeOutputDevicesMuteState(devices);
4185 updateCallAndOutputRouting(false /* forceVolumeReeval */, 0 /* delayMs */,
4186 true /* skipDelays */);
4187 changeOutputDevicesMuteState(devices);
Oscar Azucena90e77632019-11-27 17:12:28 -08004188
4189 return NO_ERROR;
4190}
4191
Andy Hungc29d82b2018-10-05 12:23:17 -07004192void AudioPolicyManager::dump(String8 *dst) const
Eric Laurente552edb2014-03-10 17:42:56 -07004193{
Andy Hungc29d82b2018-10-05 12:23:17 -07004194 dst->appendFormat("\nAudioPolicyManager Dump: %p\n", this);
Mikhail Naganov0dbe87b2021-12-01 02:03:31 +00004195 dst->appendFormat(" Primary Output I/O handle: %d\n",
Eric Laurent87ffa392015-05-22 10:32:38 -07004196 hasPrimaryOutput() ? mPrimaryOutput->mIoHandle : AUDIO_IO_HANDLE_NONE);
Mikhail Naganov0d6a0332016-04-19 17:12:38 -07004197 std::string stateLiteral;
4198 AudioModeConverter::toString(mEngine->getPhoneState(), stateLiteral);
Andy Hungc29d82b2018-10-05 12:23:17 -07004199 dst->appendFormat(" Phone state: %s\n", stateLiteral.c_str());
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07004200 const char* forceUses[AUDIO_POLICY_FORCE_USE_CNT] = {
4201 "communications", "media", "record", "dock", "system",
4202 "HDMI system audio", "encoded surround output", "vibrate ringing" };
4203 for (audio_policy_force_use_t i = AUDIO_POLICY_FORCE_FOR_COMMUNICATION;
4204 i < AUDIO_POLICY_FORCE_USE_CNT; i = (audio_policy_force_use_t)((int)i + 1)) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08004205 audio_policy_forced_cfg_t forceUseValue = mEngine->getForceUse(i);
4206 dst->appendFormat(" Force use for %s: %d", forceUses[i], forceUseValue);
4207 if (i == AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND &&
4208 forceUseValue == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
4209 dst->append(" (MANUAL: ");
4210 dumpManualSurroundFormats(dst);
4211 dst->append(")");
4212 }
4213 dst->append("\n");
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07004214 }
Andy Hungc29d82b2018-10-05 12:23:17 -07004215 dst->appendFormat(" TTS output %savailable\n", mTtsOutputAvailable ? "" : "not ");
4216 dst->appendFormat(" Master mono: %s\n", mMasterMono ? "on" : "off");
Mikhail Naganovb3bcb4f2022-02-23 23:46:56 +00004217 dst->appendFormat(" Communication Strategy id: %d\n", mCommunnicationStrategy);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07004218 dst->appendFormat(" Config source: %s\n", mConfig->getSource().c_str());
Eric Laurent2517af32020-11-25 15:31:27 +01004219
Mikhail Naganov0f413b22021-12-02 05:29:27 +00004220 dst->append("\n");
4221 mAvailableOutputDevices.dump(dst, String8("Available output"), 1);
4222 dst->append("\n");
4223 mAvailableInputDevices.dump(dst, String8("Available input"), 1);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07004224 mHwModules.dump(dst);
Andy Hungc29d82b2018-10-05 12:23:17 -07004225 mOutputs.dump(dst);
4226 mInputs.dump(dst);
Mikhail Naganov0f413b22021-12-02 05:29:27 +00004227 mEffects.dump(dst, 1);
Andy Hungc29d82b2018-10-05 12:23:17 -07004228 mAudioPatches.dump(dst);
4229 mPolicyMixes.dump(dst);
4230 mAudioSources.dump(dst);
François Gaffiec005e562018-11-06 15:04:49 +01004231
Kevin Rocardb99cc752019-03-21 20:52:24 -07004232 dst->appendFormat(" AllowedCapturePolicies:\n");
4233 for (auto& policy : mAllowedCapturePolicies) {
4234 dst->appendFormat(" - uid=%d flag_mask=%#x\n", policy.first, policy.second);
4235 }
4236
jiabina84c3d32022-12-02 18:59:55 +00004237 dst->appendFormat(" Preferred mixer audio configuration:\n");
4238 for (const auto it : mPreferredMixerAttrInfos) {
4239 dst->appendFormat(" - device port id: %d\n", it.first);
4240 for (const auto preferredMixerInfoIt : it.second) {
4241 dst->appendFormat(" - strategy: %d; ", preferredMixerInfoIt.first);
4242 preferredMixerInfoIt.second->dump(dst);
4243 }
4244 }
4245
François Gaffiec005e562018-11-06 15:04:49 +01004246 dst->appendFormat("\nPolicy Engine dump:\n");
4247 mEngine->dump(dst);
Andy Hungc29d82b2018-10-05 12:23:17 -07004248}
4249
4250status_t AudioPolicyManager::dump(int fd)
4251{
4252 String8 result;
4253 dump(&result);
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004254 write(fd, result.c_str(), result.size());
Eric Laurente552edb2014-03-10 17:42:56 -07004255 return NO_ERROR;
4256}
4257
Kevin Rocardb99cc752019-03-21 20:52:24 -07004258status_t AudioPolicyManager::setAllowedCapturePolicy(uid_t uid, audio_flags_mask_t capturePolicy)
4259{
4260 mAllowedCapturePolicies[uid] = capturePolicy;
4261 return NO_ERROR;
4262}
4263
Eric Laurente552edb2014-03-10 17:42:56 -07004264// This function checks for the parameters which can be offloaded.
4265// This can be enhanced depending on the capability of the DSP and policy
4266// of the system.
Eric Laurent90fe31c2020-11-26 20:06:35 +01004267audio_offload_mode_t AudioPolicyManager::getOffloadSupport(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07004268{
Eric Laurent90fe31c2020-11-26 20:06:35 +01004269 ALOGV("%s: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07004270 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurent90fe31c2020-11-26 20:06:35 +01004271 __func__, offloadInfo.sample_rate, offloadInfo.channel_mask,
Eric Laurente552edb2014-03-10 17:42:56 -07004272 offloadInfo.format,
4273 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
4274 offloadInfo.has_video);
4275
jiabin2b9d5a12021-12-10 01:06:29 +00004276 if (!isOffloadPossible(offloadInfo)) {
Eric Laurent90fe31c2020-11-26 20:06:35 +01004277 return AUDIO_OFFLOAD_NOT_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07004278 }
4279
4280 // See if there is a profile to support this.
4281 // AUDIO_DEVICE_NONE
François Gaffie11d30102018-11-02 16:09:09 +01004282 sp<IOProfile> profile = getProfileForOutput(DeviceVector() /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07004283 offloadInfo.sample_rate,
4284 offloadInfo.format,
4285 offloadInfo.channel_mask,
Michael Chana94fbb22018-04-24 14:31:19 +10004286 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD,
4287 true /* directOnly */);
Eric Laurent94365442021-01-08 18:36:05 +01004288 ALOGV("%s: profile %sfound%s", __func__, profile != nullptr ? "" : "NOT ",
4289 (profile != nullptr && (profile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD) != 0)
4290 ? ", supports gapless" : "");
Eric Laurent90fe31c2020-11-26 20:06:35 +01004291 if (profile == nullptr) {
4292 return AUDIO_OFFLOAD_NOT_SUPPORTED;
4293 }
4294 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD) != 0) {
4295 return AUDIO_OFFLOAD_GAPLESS_SUPPORTED;
4296 }
4297 return AUDIO_OFFLOAD_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07004298}
4299
Michael Chana94fbb22018-04-24 14:31:19 +10004300bool AudioPolicyManager::isDirectOutputSupported(const audio_config_base_t& config,
4301 const audio_attributes_t& attributes) {
4302 audio_output_flags_t output_flags = AUDIO_OUTPUT_FLAG_NONE;
François Gaffie58d4be52018-11-06 15:30:12 +01004303 audio_flags_to_audio_output_flags(attributes.flags, &output_flags);
Dorin Drimus9901eb02022-01-14 11:36:51 +00004304 DeviceVector outputDevices = mEngine->getOutputDevicesForAttributes(attributes);
4305 sp<IOProfile> profile = getProfileForOutput(outputDevices,
Michael Chana94fbb22018-04-24 14:31:19 +10004306 config.sample_rate,
4307 config.format,
4308 config.channel_mask,
4309 output_flags,
4310 true /* directOnly */);
4311 ALOGV("%s() profile %sfound with name: %s, "
4312 "sample rate: %u, format: 0x%x, channel_mask: 0x%x, output flags: 0x%x",
4313 __FUNCTION__, profile != 0 ? "" : "NOT ",
jiabin5740f082019-08-19 15:08:30 -07004314 (profile != 0 ? profile->getTagName().c_str() : "null"),
Michael Chana94fbb22018-04-24 14:31:19 +10004315 config.sample_rate, config.format, config.channel_mask, output_flags);
Dorin Drimusecc9f422022-03-09 17:57:40 +01004316
4317 // also try the MSD module if compatible profile not found
4318 if (profile == nullptr) {
4319 profile = getMsdProfileForOutput(outputDevices,
4320 config.sample_rate,
4321 config.format,
4322 config.channel_mask,
4323 output_flags,
4324 true /* directOnly */);
4325 ALOGV("%s() MSD profile %sfound with name: %s, "
4326 "sample rate: %u, format: 0x%x, channel_mask: 0x%x, output flags: 0x%x",
4327 __FUNCTION__, profile != 0 ? "" : "NOT ",
4328 (profile != 0 ? profile->getTagName().c_str() : "null"),
4329 config.sample_rate, config.format, config.channel_mask, output_flags);
4330 }
4331 return (profile != nullptr);
Michael Chana94fbb22018-04-24 14:31:19 +10004332}
4333
jiabin2b9d5a12021-12-10 01:06:29 +00004334bool AudioPolicyManager::isOffloadPossible(const audio_offload_info_t &offloadInfo,
4335 bool durationIgnored) {
4336 if (mMasterMono) {
4337 return false; // no offloading if mono is set.
4338 }
4339
4340 // Check if offload has been disabled
4341 if (property_get_bool("audio.offload.disable", false /* default_value */)) {
4342 ALOGV("%s: offload disabled by audio.offload.disable", __func__);
4343 return false;
4344 }
4345
4346 // Check if stream type is music, then only allow offload as of now.
4347 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
4348 {
4349 ALOGV("%s: stream_type != MUSIC, returning false", __func__);
4350 return false;
4351 }
4352
4353 //TODO: enable audio offloading with video when ready
4354 const bool allowOffloadWithVideo =
4355 property_get_bool("audio.offload.video", false /* default_value */);
4356 if (offloadInfo.has_video && !allowOffloadWithVideo) {
4357 ALOGV("%s: has_video == true, returning false", __func__);
4358 return false;
4359 }
4360
4361 //If duration is less than minimum value defined in property, return false
4362 const int min_duration_secs = property_get_int32(
4363 "audio.offload.min.duration.secs", -1 /* default_value */);
4364 if (!durationIgnored) {
4365 if (min_duration_secs >= 0) {
4366 if (offloadInfo.duration_us < min_duration_secs * 1000000LL) {
4367 ALOGV("%s: Offload denied by duration < audio.offload.min.duration.secs(=%d)",
4368 __func__, min_duration_secs);
4369 return false;
4370 }
4371 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
4372 ALOGV("%s: Offload denied by duration < default min(=%u)",
4373 __func__, OFFLOAD_DEFAULT_MIN_DURATION_SECS);
4374 return false;
4375 }
4376 }
4377
4378 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
4379 // creating an offloaded track and tearing it down immediately after start when audioflinger
4380 // detects there is an active non offloadable effect.
4381 // FIXME: We should check the audio session here but we do not have it in this context.
4382 // This may prevent offloading in rare situations where effects are left active by apps
4383 // in the background.
4384 if (mEffects.isNonOffloadableEffectEnabled()) {
4385 return false;
4386 }
4387
4388 return true;
4389}
4390
4391audio_direct_mode_t AudioPolicyManager::getDirectPlaybackSupport(const audio_attributes_t *attr,
4392 const audio_config_t *config) {
4393 audio_offload_info_t offloadInfo = AUDIO_INFO_INITIALIZER;
4394 offloadInfo.format = config->format;
4395 offloadInfo.sample_rate = config->sample_rate;
4396 offloadInfo.channel_mask = config->channel_mask;
4397 offloadInfo.stream_type = mEngine->getStreamTypeForAttributes(*attr);
4398 offloadInfo.has_video = false;
4399 offloadInfo.is_streaming = false;
4400 const bool offloadPossible = isOffloadPossible(offloadInfo, true /*durationIgnored*/);
4401
4402 audio_direct_mode_t directMode = AUDIO_DIRECT_NOT_SUPPORTED;
4403 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
4404 audio_flags_to_audio_output_flags(attr->flags, &flags);
4405 // only retain flags that will drive compressed offload or passthrough
4406 uint32_t relevantFlags = AUDIO_OUTPUT_FLAG_HW_AV_SYNC;
4407 if (offloadPossible) {
4408 relevantFlags |= AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD;
4409 }
4410 flags = (audio_output_flags_t)((flags & relevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
4411
Dorin Drimusfae3c642022-03-17 18:36:30 +01004412 DeviceVector engineOutputDevices = mEngine->getOutputDevicesForAttributes(*attr);
jiabin2b9d5a12021-12-10 01:06:29 +00004413 for (const auto& hwModule : mHwModules) {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004414 DeviceVector outputDevices = engineOutputDevices;
4415 // the MSD module checks for different conditions and output devices
4416 if (strcmp(hwModule->getName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0) {
4417 if (!msdHasPatchesToAllDevices(engineOutputDevices.toTypeAddrVector())) {
4418 continue;
4419 }
4420 outputDevices = getMsdAudioOutDevices();
4421 }
jiabin2b9d5a12021-12-10 01:06:29 +00004422 for (const auto& curProfile : hwModule->getOutputProfiles()) {
jiabinc8f7dfc2022-01-06 18:42:08 +00004423 if (!curProfile->isCompatibleProfile(outputDevices,
jiabin2b9d5a12021-12-10 01:06:29 +00004424 config->sample_rate, nullptr /*updatedSamplingRate*/,
4425 config->format, nullptr /*updatedFormat*/,
4426 config->channel_mask, nullptr /*updatedChannelMask*/,
4427 flags)) {
4428 continue;
4429 }
4430 // reject profiles not corresponding to a device currently available
4431 if (!mAvailableOutputDevices.containsAtLeastOne(curProfile->getSupportedDevices())) {
4432 continue;
4433 }
4434 if ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)
4435 != AUDIO_OUTPUT_FLAG_NONE) {
jiabinc6132d62022-01-01 07:36:31 +00004436 if ((directMode & AUDIO_DIRECT_OFFLOAD_GAPLESS_SUPPORTED)
jiabin2b9d5a12021-12-10 01:06:29 +00004437 != AUDIO_DIRECT_NOT_SUPPORTED) {
4438 // Already reports offload gapless supported. No need to report offload support.
4439 continue;
4440 }
4441 if ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD)
4442 != AUDIO_OUTPUT_FLAG_NONE) {
4443 // If offload gapless is reported, no need to report offload support.
4444 directMode = (audio_direct_mode_t) ((directMode &
4445 ~AUDIO_DIRECT_OFFLOAD_SUPPORTED) |
4446 AUDIO_DIRECT_OFFLOAD_GAPLESS_SUPPORTED);
4447 } else {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004448 directMode = (audio_direct_mode_t)(directMode | AUDIO_DIRECT_OFFLOAD_SUPPORTED);
jiabin2b9d5a12021-12-10 01:06:29 +00004449 }
4450 } else {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004451 directMode = (audio_direct_mode_t) (directMode | AUDIO_DIRECT_BITSTREAM_SUPPORTED);
jiabin2b9d5a12021-12-10 01:06:29 +00004452 }
4453 }
4454 }
4455 return directMode;
4456}
4457
Dorin Drimusf2196d82022-01-03 12:11:18 +01004458status_t AudioPolicyManager::getDirectProfilesForAttributes(const audio_attributes_t* attr,
4459 AudioProfileVector& audioProfilesVector) {
Dorin Drimus17112632022-09-23 15:28:51 +00004460 if (mEffects.isNonOffloadableEffectEnabled()) {
4461 return OK;
4462 }
jiabinf1c73972022-04-14 16:28:52 -07004463 DeviceVector devices;
4464 status_t status = getDevicesForAttributes(*attr, devices, false /* forVolume */);
Dorin Drimusf2196d82022-01-03 12:11:18 +01004465 if (status != OK) {
4466 return status;
4467 }
4468 ALOGV("%s: found %zu output devices for attributes.", __func__, devices.size());
4469 if (devices.empty()) {
4470 return OK; // no output devices for the attributes
4471 }
jiabinf1c73972022-04-14 16:28:52 -07004472 return getProfilesForDevices(devices, audioProfilesVector,
4473 AUDIO_OUTPUT_FLAG_DIRECT /*flags*/, false /*isInput*/);
Dorin Drimusf2196d82022-01-03 12:11:18 +01004474}
4475
jiabina84c3d32022-12-02 18:59:55 +00004476status_t AudioPolicyManager::getSupportedMixerAttributes(
4477 audio_port_handle_t portId, std::vector<audio_mixer_attributes_t> &mixerAttrs) {
4478 ALOGV("%s, portId=%d", __func__, portId);
4479 sp<DeviceDescriptor> deviceDescriptor = mAvailableOutputDevices.getDeviceFromId(portId);
4480 if (deviceDescriptor == nullptr) {
4481 ALOGE("%s the requested device is currently unavailable", __func__);
4482 return BAD_VALUE;
4483 }
jiabin96daffc2023-05-11 17:51:55 +00004484 if (!audio_is_usb_out_device(deviceDescriptor->type())) {
4485 ALOGE("%s the requested device(type=%#x) is not usb device", __func__,
4486 deviceDescriptor->type());
4487 return BAD_VALUE;
4488 }
jiabina84c3d32022-12-02 18:59:55 +00004489 for (const auto& hwModule : mHwModules) {
4490 for (const auto& curProfile : hwModule->getOutputProfiles()) {
4491 if (curProfile->supportsDevice(deviceDescriptor)) {
4492 curProfile->toSupportedMixerAttributes(&mixerAttrs);
4493 }
4494 }
4495 }
4496 return NO_ERROR;
4497}
4498
4499status_t AudioPolicyManager::setPreferredMixerAttributes(
4500 const audio_attributes_t *attr,
4501 audio_port_handle_t portId,
4502 uid_t uid,
4503 const audio_mixer_attributes_t *mixerAttributes) {
4504 ALOGV("%s, attr=%s, mixerAttributes={format=%#x, channelMask=%#x, samplingRate=%u, "
4505 "mixerBehavior=%d}, uid=%d, portId=%u",
4506 __func__, toString(*attr).c_str(), mixerAttributes->config.format,
4507 mixerAttributes->config.channel_mask, mixerAttributes->config.sample_rate,
4508 mixerAttributes->mixer_behavior, uid, portId);
4509 if (attr->usage != AUDIO_USAGE_MEDIA) {
4510 ALOGE("%s failed, only media is allowed, the given usage is %d", __func__, attr->usage);
4511 return BAD_VALUE;
4512 }
4513 sp<DeviceDescriptor> deviceDescriptor = mAvailableOutputDevices.getDeviceFromId(portId);
4514 if (deviceDescriptor == nullptr) {
4515 ALOGE("%s the requested device is currently unavailable", __func__);
4516 return BAD_VALUE;
4517 }
4518 if (!audio_is_usb_out_device(deviceDescriptor->type())) {
4519 ALOGE("%s(%d), type=%d, is not a usb output device",
4520 __func__, portId, deviceDescriptor->type());
4521 return BAD_VALUE;
4522 }
4523
4524 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
4525 audio_flags_to_audio_output_flags(attr->flags, &flags);
4526 flags = (audio_output_flags_t) (flags |
4527 audio_output_flags_from_mixer_behavior(mixerAttributes->mixer_behavior));
4528 sp<IOProfile> profile = nullptr;
4529 DeviceVector devices(deviceDescriptor);
4530 for (const auto& hwModule : mHwModules) {
4531 for (const auto& curProfile : hwModule->getOutputProfiles()) {
4532 if (curProfile->hasDynamicAudioProfile()
4533 && curProfile->isCompatibleProfile(devices,
4534 mixerAttributes->config.sample_rate,
4535 nullptr /*updatedSamplingRate*/,
4536 mixerAttributes->config.format,
4537 nullptr /*updatedFormat*/,
4538 mixerAttributes->config.channel_mask,
4539 nullptr /*updatedChannelMask*/,
4540 flags,
4541 false /*exactMatchRequiredForInputFlags*/)) {
4542 profile = curProfile;
4543 break;
4544 }
4545 }
4546 }
4547 if (profile == nullptr) {
4548 ALOGE("%s, there is no compatible profile found", __func__);
4549 return BAD_VALUE;
4550 }
4551
4552 sp<PreferredMixerAttributesInfo> mixerAttrInfo =
4553 sp<PreferredMixerAttributesInfo>::make(
4554 uid, portId, profile, flags, *mixerAttributes);
4555 const product_strategy_t strategy = mEngine->getProductStrategyForAttributes(*attr);
4556 mPreferredMixerAttrInfos[portId][strategy] = mixerAttrInfo;
4557
4558 // If 1) there is any client from the preferred mixer configuration owner that is currently
4559 // active and matches the strategy and 2) current output is on the preferred device and the
4560 // mixer configuration doesn't match the preferred one, reopen output with preferred mixer
4561 // configuration.
4562 std::vector<audio_io_handle_t> outputsToReopen;
4563 for (size_t i = 0; i < mOutputs.size(); i++) {
4564 const auto output = mOutputs.valueAt(i);
jiabin3ff8d7d2022-12-13 06:27:44 +00004565 if (output->mProfile == profile && output->devices().onlyContainsDevice(deviceDescriptor)) {
4566 if (output->isConfigurationMatched(mixerAttributes->config, flags)) {
4567 output->mUsePreferredMixerAttributes = true;
4568 } else {
4569 for (const auto &client: output->getActiveClients()) {
4570 if (client->uid() == uid && client->strategy() == strategy) {
4571 client->setIsInvalid();
4572 outputsToReopen.push_back(output->mIoHandle);
4573 }
jiabina84c3d32022-12-02 18:59:55 +00004574 }
4575 }
4576 }
4577 }
4578 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
4579 config.sample_rate = mixerAttributes->config.sample_rate;
4580 config.channel_mask = mixerAttributes->config.channel_mask;
4581 config.format = mixerAttributes->config.format;
4582 for (const auto output : outputsToReopen) {
jiabin3ff8d7d2022-12-13 06:27:44 +00004583 sp<SwAudioOutputDescriptor> desc =
4584 reopenOutput(mOutputs.valueFor(output), &config, flags, __func__);
4585 if (desc == nullptr) {
4586 ALOGE("%s, failed to reopen output with preferred mixer attributes", __func__);
4587 continue;
4588 }
4589 desc->mUsePreferredMixerAttributes = true;
jiabina84c3d32022-12-02 18:59:55 +00004590 }
4591
4592 return NO_ERROR;
4593}
4594
4595sp<PreferredMixerAttributesInfo> AudioPolicyManager::getPreferredMixerAttributesInfo(
jiabind9a58d32023-06-01 17:57:30 +00004596 audio_port_handle_t devicePortId,
4597 product_strategy_t strategy,
4598 bool activeBitPerfectPreferred) {
jiabina84c3d32022-12-02 18:59:55 +00004599 auto it = mPreferredMixerAttrInfos.find(devicePortId);
4600 if (it == mPreferredMixerAttrInfos.end()) {
4601 return nullptr;
4602 }
jiabind9a58d32023-06-01 17:57:30 +00004603 if (activeBitPerfectPreferred) {
4604 for (auto [strategy, info] : it->second) {
4605 if ((info->getFlags() & AUDIO_OUTPUT_FLAG_BIT_PERFECT) != AUDIO_OUTPUT_FLAG_NONE
4606 && info->getActiveClientCount() != 0) {
4607 return info;
4608 }
4609 }
jiabina84c3d32022-12-02 18:59:55 +00004610 }
jiabind9a58d32023-06-01 17:57:30 +00004611 auto strategyMatchedMixerAttrInfoIt = it->second.find(strategy);
4612 return strategyMatchedMixerAttrInfoIt == it->second.end()
4613 ? nullptr : strategyMatchedMixerAttrInfoIt->second;
jiabina84c3d32022-12-02 18:59:55 +00004614}
4615
4616status_t AudioPolicyManager::getPreferredMixerAttributes(
4617 const audio_attributes_t *attr,
4618 audio_port_handle_t portId,
4619 audio_mixer_attributes_t* mixerAttributes) {
4620 sp<PreferredMixerAttributesInfo> info = getPreferredMixerAttributesInfo(
4621 portId, mEngine->getProductStrategyForAttributes(*attr));
4622 if (info == nullptr) {
4623 return NAME_NOT_FOUND;
4624 }
4625 *mixerAttributes = info->getMixerAttributes();
4626 return NO_ERROR;
4627}
4628
4629status_t AudioPolicyManager::clearPreferredMixerAttributes(const audio_attributes_t *attr,
4630 audio_port_handle_t portId,
4631 uid_t uid) {
4632 const product_strategy_t strategy = mEngine->getProductStrategyForAttributes(*attr);
4633 const auto preferredMixerAttrInfo = getPreferredMixerAttributesInfo(portId, strategy);
4634 if (preferredMixerAttrInfo == nullptr) {
4635 return NAME_NOT_FOUND;
4636 }
4637 if (preferredMixerAttrInfo->getUid() != uid) {
4638 ALOGE("%s, requested uid=%d, owned uid=%d",
4639 __func__, uid, preferredMixerAttrInfo->getUid());
4640 return PERMISSION_DENIED;
4641 }
4642 mPreferredMixerAttrInfos[portId].erase(strategy);
4643 if (mPreferredMixerAttrInfos[portId].empty()) {
4644 mPreferredMixerAttrInfos.erase(portId);
4645 }
4646
4647 // Reconfig existing output
4648 std::vector<audio_io_handle_t> potentialOutputsToReopen;
4649 for (size_t i = 0; i < mOutputs.size(); i++) {
4650 if (mOutputs.valueAt(i)->mProfile == preferredMixerAttrInfo->getProfile()) {
4651 potentialOutputsToReopen.push_back(mOutputs.keyAt(i));
4652 }
4653 }
4654 for (const auto output : potentialOutputsToReopen) {
4655 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
4656 if (desc->isConfigurationMatched(preferredMixerAttrInfo->getConfigBase(),
4657 preferredMixerAttrInfo->getFlags())) {
4658 reopenOutput(desc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
4659 }
4660 }
4661 return NO_ERROR;
4662}
4663
Eric Laurent6a94d692014-05-20 11:18:06 -07004664status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
4665 audio_port_type_t type,
4666 unsigned int *num_ports,
jiabin19cdba52020-11-24 11:28:58 -08004667 struct audio_port_v7 *ports,
Eric Laurent6a94d692014-05-20 11:18:06 -07004668 unsigned int *generation)
4669{
jiabin19cdba52020-11-24 11:28:58 -08004670 if (num_ports == nullptr || (*num_ports != 0 && ports == nullptr) ||
4671 generation == nullptr) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004672 return BAD_VALUE;
4673 }
4674 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
jiabin19cdba52020-11-24 11:28:58 -08004675 if (ports == nullptr) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004676 *num_ports = 0;
4677 }
4678
4679 size_t portsWritten = 0;
4680 size_t portsMax = *num_ports;
4681 *num_ports = 0;
4682 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07004683 // do not report devices with type AUDIO_DEVICE_IN_STUB or AUDIO_DEVICE_OUT_STUB
4684 // as they are used by stub HALs by convention
Eric Laurent6a94d692014-05-20 11:18:06 -07004685 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004686 for (const auto& dev : mAvailableOutputDevices) {
4687 if (dev->type() == AUDIO_DEVICE_OUT_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07004688 continue;
4689 }
4690 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004691 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07004692 }
4693 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07004694 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004695 }
4696 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004697 for (const auto& dev : mAvailableInputDevices) {
4698 if (dev->type() == AUDIO_DEVICE_IN_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07004699 continue;
4700 }
4701 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004702 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07004703 }
4704 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07004705 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004706 }
4707 }
4708 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
4709 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
4710 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
4711 mInputs[i]->toAudioPort(&ports[portsWritten++]);
4712 }
4713 *num_ports += mInputs.size();
4714 }
4715 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent84c70242014-06-23 08:46:27 -07004716 size_t numOutputs = 0;
4717 for (size_t i = 0; i < mOutputs.size(); i++) {
4718 if (!mOutputs[i]->isDuplicated()) {
4719 numOutputs++;
4720 if (portsWritten < portsMax) {
4721 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
4722 }
4723 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004724 }
Eric Laurent84c70242014-06-23 08:46:27 -07004725 *num_ports += numOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07004726 }
4727 }
jiabina84c3d32022-12-02 18:59:55 +00004728
Eric Laurent6a94d692014-05-20 11:18:06 -07004729 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07004730 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
Eric Laurent6a94d692014-05-20 11:18:06 -07004731 return NO_ERROR;
4732}
4733
Mikhail Naganov5edc5ed2023-03-23 14:52:15 -07004734status_t AudioPolicyManager::listDeclaredDevicePorts(media::AudioPortRole role,
4735 std::vector<media::AudioPortFw>* _aidl_return) {
4736 auto pushPort = [&](const sp<DeviceDescriptor>& dev) -> status_t {
4737 audio_port_v7 port;
4738 dev->toAudioPort(&port);
4739 auto aidlPort = VALUE_OR_RETURN_STATUS(legacy2aidl_audio_port_v7_AudioPortFw(port));
4740 _aidl_return->push_back(std::move(aidlPort));
4741 return OK;
4742 };
4743
Mikhail Naganov68e3f642023-04-28 13:06:32 -07004744 for (const auto& module : mHwModules) {
Mikhail Naganov5edc5ed2023-03-23 14:52:15 -07004745 for (const auto& dev : module->getDeclaredDevices()) {
4746 if (role == media::AudioPortRole::NONE ||
4747 ((role == media::AudioPortRole::SOURCE)
4748 == audio_is_input_device(dev->type()))) {
4749 RETURN_STATUS_IF_ERROR(pushPort(dev));
4750 }
4751 }
4752 }
4753 return OK;
4754}
4755
jiabin19cdba52020-11-24 11:28:58 -08004756status_t AudioPolicyManager::getAudioPort(struct audio_port_v7 *port)
Eric Laurent6a94d692014-05-20 11:18:06 -07004757{
Eric Laurent99fcae42018-05-17 16:59:18 -07004758 if (port == nullptr || port->id == AUDIO_PORT_HANDLE_NONE) {
4759 return BAD_VALUE;
4760 }
4761 sp<DeviceDescriptor> dev = mAvailableOutputDevices.getDeviceFromId(port->id);
4762 if (dev != 0) {
4763 dev->toAudioPort(port);
4764 return NO_ERROR;
4765 }
4766 dev = mAvailableInputDevices.getDeviceFromId(port->id);
4767 if (dev != 0) {
4768 dev->toAudioPort(port);
4769 return NO_ERROR;
4770 }
4771 sp<SwAudioOutputDescriptor> out = mOutputs.getOutputFromId(port->id);
4772 if (out != 0) {
4773 out->toAudioPort(port);
4774 return NO_ERROR;
4775 }
4776 sp<AudioInputDescriptor> in = mInputs.getInputFromId(port->id);
4777 if (in != 0) {
4778 in->toAudioPort(port);
4779 return NO_ERROR;
4780 }
4781 return BAD_VALUE;
Eric Laurent6a94d692014-05-20 11:18:06 -07004782}
4783
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004784status_t AudioPolicyManager::createAudioPatch(const struct audio_patch *patch,
4785 audio_patch_handle_t *handle,
4786 uid_t uid)
Eric Laurent6a94d692014-05-20 11:18:06 -07004787{
François Gaffieafd4cea2019-11-18 15:50:22 +01004788 ALOGV("%s", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004789 if (handle == NULL || patch == NULL) {
4790 return BAD_VALUE;
4791 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004792 ALOGV("%s num sources %d num sinks %d", __func__, patch->num_sources, patch->num_sinks);
Mikhail Naganovac9858b2018-06-15 13:12:37 -07004793 if (!audio_patch_is_valid(patch)) {
Eric Laurent874c42872014-08-08 15:13:39 -07004794 return BAD_VALUE;
4795 }
4796 // only one source per audio patch supported for now
4797 if (patch->num_sources > 1) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004798 return INVALID_OPERATION;
4799 }
Eric Laurent874c42872014-08-08 15:13:39 -07004800 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004801 return INVALID_OPERATION;
4802 }
Eric Laurent874c42872014-08-08 15:13:39 -07004803 for (size_t i = 0; i < patch->num_sinks; i++) {
4804 if (patch->sinks[i].role != AUDIO_PORT_ROLE_SINK) {
4805 return INVALID_OPERATION;
4806 }
4807 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004808
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004809 sp<DeviceDescriptor> srcDevice = mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
4810 sp<DeviceDescriptor> sinkDevice = mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id);
4811 if (srcDevice == nullptr || sinkDevice == nullptr) {
4812 ALOGW("%s could not create patch, invalid sink and/or source device(s)", __func__);
4813 return BAD_VALUE;
4814 }
4815 ALOGV("%s between source %s and sink %s", __func__,
4816 srcDevice->toString().c_str(), sinkDevice->toString().c_str());
4817 audio_port_handle_t portId = PolicyAudioPort::getNextUniqueId();
4818 // Default attributes, default volume priority, not to infer with non raw audio patches.
4819 audio_attributes_t attributes = attributes_initializer(AUDIO_USAGE_MEDIA);
4820 const struct audio_port_config *source = &patch->sources[0];
4821 sp<SourceClientDescriptor> sourceDesc =
4822 new InternalSourceClientDescriptor(
4823 portId, uid, attributes, *source, srcDevice, sinkDevice,
4824 mEngine->getProductStrategyForAttributes(attributes), toVolumeSource(attributes));
4825
4826 status_t status =
4827 connectAudioSourceToSink(sourceDesc, sinkDevice, patch, *handle, uid, 0 /* delayMs */);
4828
4829 if (status != NO_ERROR) {
4830 return INVALID_OPERATION;
4831 }
4832 mAudioSources.add(portId, sourceDesc);
4833 return NO_ERROR;
4834}
4835
4836status_t AudioPolicyManager::connectAudioSourceToSink(
4837 const sp<SourceClientDescriptor>& sourceDesc, const sp<DeviceDescriptor> &sinkDevice,
4838 const struct audio_patch *patch,
4839 audio_patch_handle_t &handle,
4840 uid_t uid, uint32_t delayMs)
4841{
4842 status_t status = createAudioPatchInternal(patch, &handle, uid, delayMs, sourceDesc);
4843 if (status != NO_ERROR || mAudioPatches.indexOfKey(handle) < 0) {
4844 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
4845 return INVALID_OPERATION;
4846 }
4847 sourceDesc->connect(handle, sinkDevice);
4848 if (isMsdPatch(handle)) {
4849 return NO_ERROR;
4850 }
4851 // SW Bridge? (@todo: HW bridge, keep track of HwOutput for device selection "reconsideration")
4852 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
4853 ALOG_ASSERT(swOutput != nullptr, "%s: a swOutput shall always be associated", __func__);
4854 if (swOutput->getClient(sourceDesc->portId()) != nullptr) {
4855 ALOGW("%s source portId has already been attached to outputDesc", __func__);
4856 goto FailurePatchAdded;
4857 }
4858 status = swOutput->start();
4859 if (status != NO_ERROR) {
4860 goto FailureSourceAdded;
4861 }
4862 swOutput->addClient(sourceDesc);
4863 status = startSource(swOutput, sourceDesc, &delayMs);
4864 if (status != NO_ERROR) {
4865 ALOGW("%s failed to start source, error %d", __FUNCTION__, status);
4866 goto FailureSourceActive;
4867 }
4868 if (delayMs != 0) {
4869 usleep(delayMs * 1000);
4870 }
4871 return NO_ERROR;
4872
4873FailureSourceActive:
4874 swOutput->stop();
4875 releaseOutput(sourceDesc->portId());
4876FailureSourceAdded:
4877 sourceDesc->setSwOutput(nullptr);
4878FailurePatchAdded:
4879 releaseAudioPatchInternal(handle);
4880 return INVALID_OPERATION;
4881}
4882
4883status_t AudioPolicyManager::createAudioPatchInternal(const struct audio_patch *patch,
4884 audio_patch_handle_t *handle,
4885 uid_t uid, uint32_t delayMs,
4886 const sp<SourceClientDescriptor>& sourceDesc)
4887{
4888 ALOGV("%s num sources %d num sinks %d", __func__, patch->num_sources, patch->num_sinks);
Eric Laurent6a94d692014-05-20 11:18:06 -07004889 sp<AudioPatch> patchDesc;
4890 ssize_t index = mAudioPatches.indexOfKey(*handle);
4891
François Gaffieafd4cea2019-11-18 15:50:22 +01004892 ALOGV("%s source id %d role %d type %d", __func__, patch->sources[0].id,
4893 patch->sources[0].role,
4894 patch->sources[0].type);
Eric Laurent874c42872014-08-08 15:13:39 -07004895#if LOG_NDEBUG == 0
4896 for (size_t i = 0; i < patch->num_sinks; i++) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004897 ALOGV("%s sink %zu: id %d role %d type %d", __func__ ,i, patch->sinks[i].id,
4898 patch->sinks[i].role,
4899 patch->sinks[i].type);
Eric Laurent874c42872014-08-08 15:13:39 -07004900 }
4901#endif
Eric Laurent6a94d692014-05-20 11:18:06 -07004902
4903 if (index >= 0) {
4904 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01004905 ALOGV("%s mUidCached %d patchDesc->mUid %d uid %d",
4906 __func__, mUidCached, patchDesc->getUid(), uid);
4907 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004908 return INVALID_OPERATION;
4909 }
4910 } else {
Glenn Kastena13cde92016-03-28 15:26:02 -07004911 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07004912 }
4913
4914 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004915 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004916 if (outputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004917 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004918 return BAD_VALUE;
4919 }
Eric Laurent84c70242014-06-23 08:46:27 -07004920 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
4921 outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004922 if (patchDesc != 0) {
4923 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004924 ALOGV("%s source id differs for patch current id %d new id %d",
4925 __func__, patchDesc->mPatch.sources[0].id, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004926 return BAD_VALUE;
4927 }
4928 }
Eric Laurent874c42872014-08-08 15:13:39 -07004929 DeviceVector devices;
4930 for (size_t i = 0; i < patch->num_sinks; i++) {
4931 // Only support mix to devices connection
4932 // TODO add support for mix to mix connection
4933 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004934 ALOGV("%s source mix but sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07004935 return INVALID_OPERATION;
4936 }
4937 sp<DeviceDescriptor> devDesc =
4938 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
4939 if (devDesc == 0) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004940 ALOGV("%s out device not found for id %d", __func__, patch->sinks[i].id);
Eric Laurent874c42872014-08-08 15:13:39 -07004941 return BAD_VALUE;
4942 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004943
François Gaffie11d30102018-11-02 16:09:09 +01004944 if (!outputDesc->mProfile->isCompatibleProfile(DeviceVector(devDesc),
Eric Laurent874c42872014-08-08 15:13:39 -07004945 patch->sources[0].sample_rate,
François Gaffie53615e22015-03-19 09:24:12 +01004946 NULL, // updatedSamplingRate
4947 patch->sources[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07004948 NULL, // updatedFormat
François Gaffie53615e22015-03-19 09:24:12 +01004949 patch->sources[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07004950 NULL, // updatedChannelMask
François Gaffie53615e22015-03-19 09:24:12 +01004951 AUDIO_OUTPUT_FLAG_NONE /*FIXME*/)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004952 ALOGV("%s profile not supported for device %08x", __func__, devDesc->type());
Eric Laurent874c42872014-08-08 15:13:39 -07004953 return INVALID_OPERATION;
4954 }
4955 devices.add(devDesc);
4956 }
4957 if (devices.size() == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004958 return INVALID_OPERATION;
4959 }
Eric Laurent874c42872014-08-08 15:13:39 -07004960
Eric Laurent6a94d692014-05-20 11:18:06 -07004961 // TODO: reconfigure output format and channels here
François Gaffieafd4cea2019-11-18 15:50:22 +01004962 ALOGV("%s setting device %s on output %d",
4963 __func__, dumpDeviceTypes(devices.types()).c_str(), outputDesc->mIoHandle);
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05304964 setOutputDevices(__func__, outputDesc, devices, true, 0, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004965 index = mAudioPatches.indexOfKey(*handle);
4966 if (index >= 0) {
4967 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004968 ALOGW("%s setOutputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004969 }
4970 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01004971 patchDesc->setUid(uid);
4972 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004973 } else {
François Gaffieafd4cea2019-11-18 15:50:22 +01004974 ALOGW("%s setOutputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004975 return INVALID_OPERATION;
4976 }
4977 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
4978 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
4979 // input device to input mix connection
Eric Laurent874c42872014-08-08 15:13:39 -07004980 // only one sink supported when connecting an input device to a mix
4981 if (patch->num_sinks > 1) {
4982 return INVALID_OPERATION;
4983 }
François Gaffie53615e22015-03-19 09:24:12 +01004984 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004985 if (inputDesc == NULL) {
4986 return BAD_VALUE;
4987 }
4988 if (patchDesc != 0) {
4989 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
4990 return BAD_VALUE;
4991 }
4992 }
François Gaffie11d30102018-11-02 16:09:09 +01004993 sp<DeviceDescriptor> device =
Eric Laurent6a94d692014-05-20 11:18:06 -07004994 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01004995 if (device == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004996 return BAD_VALUE;
4997 }
4998
François Gaffie11d30102018-11-02 16:09:09 +01004999 if (!inputDesc->mProfile->isCompatibleProfile(DeviceVector(device),
Eric Laurent275e8e92014-11-30 15:14:47 -08005000 patch->sinks[0].sample_rate,
5001 NULL, /*updatedSampleRate*/
5002 patch->sinks[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07005003 NULL, /*updatedFormat*/
Eric Laurent275e8e92014-11-30 15:14:47 -08005004 patch->sinks[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07005005 NULL, /*updatedChannelMask*/
Eric Laurent275e8e92014-11-30 15:14:47 -08005006 // FIXME for the parameter type,
5007 // and the NONE
5008 (audio_output_flags_t)
Glenn Kasten6a8ab052014-07-24 14:08:35 -07005009 AUDIO_INPUT_FLAG_NONE)) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005010 return INVALID_OPERATION;
5011 }
5012 // TODO: reconfigure output format and channels here
François Gaffieafd4cea2019-11-18 15:50:22 +01005013 ALOGV("%s setting device %s on output %d", __func__,
François Gaffie11d30102018-11-02 16:09:09 +01005014 device->toString().c_str(), inputDesc->mIoHandle);
5015 setInputDevice(inputDesc->mIoHandle, device, true, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005016 index = mAudioPatches.indexOfKey(*handle);
5017 if (index >= 0) {
5018 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005019 ALOGW("%s setInputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005020 }
5021 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005022 patchDesc->setUid(uid);
5023 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005024 } else {
François Gaffieafd4cea2019-11-18 15:50:22 +01005025 ALOGW("%s setInputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005026 return INVALID_OPERATION;
5027 }
5028 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
5029 // device to device connection
5030 if (patchDesc != 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07005031 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005032 return BAD_VALUE;
5033 }
5034 }
François Gaffie11d30102018-11-02 16:09:09 +01005035 sp<DeviceDescriptor> srcDevice =
Eric Laurent6a94d692014-05-20 11:18:06 -07005036 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01005037 if (srcDevice == 0) {
Eric Laurent58f8eb72014-09-12 16:19:41 -07005038 return BAD_VALUE;
5039 }
Eric Laurent874c42872014-08-08 15:13:39 -07005040
Eric Laurent6a94d692014-05-20 11:18:06 -07005041 //update source and sink with our own data as the data passed in the patch may
5042 // be incomplete.
François Gaffieafd4cea2019-11-18 15:50:22 +01005043 PatchBuilder patchBuilder;
5044 audio_port_config sourcePortConfig = {};
Dean Wheatley8bee85a2021-02-10 16:02:23 +11005045
5046 // if first sink is to MSD, establish single MSD patch
5047 if (getMsdAudioOutDevices().contains(
5048 mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id))) {
5049 ALOGV("%s patching to MSD", __FUNCTION__);
5050 patchBuilder = buildMsdPatch(false /*msdIsSource*/, srcDevice);
5051 goto installPatch;
5052 }
5053
François Gaffieafd4cea2019-11-18 15:50:22 +01005054 srcDevice->toAudioPortConfig(&sourcePortConfig, &patch->sources[0]);
5055 patchBuilder.addSource(sourcePortConfig);
Eric Laurent6a94d692014-05-20 11:18:06 -07005056
Eric Laurent874c42872014-08-08 15:13:39 -07005057 for (size_t i = 0; i < patch->num_sinks; i++) {
5058 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005059 ALOGV("%s source device but one sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07005060 return INVALID_OPERATION;
5061 }
François Gaffie11d30102018-11-02 16:09:09 +01005062 sp<DeviceDescriptor> sinkDevice =
Eric Laurent874c42872014-08-08 15:13:39 -07005063 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
François Gaffie11d30102018-11-02 16:09:09 +01005064 if (sinkDevice == 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07005065 return BAD_VALUE;
5066 }
François Gaffieafd4cea2019-11-18 15:50:22 +01005067 audio_port_config sinkPortConfig = {};
5068 sinkDevice->toAudioPortConfig(&sinkPortConfig, &patch->sinks[i]);
5069 patchBuilder.addSink(sinkPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07005070
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005071 // Whatever Sw or Hw bridge, we do attach an SwOutput to an Audio Source for
5072 // volume management purpose (tracking activity)
5073 // In case of Hw bridge, it is a Work Around. The mixPort used is the one declared
5074 // in config XML to reach the sink so that is can be declared as available.
5075 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurent78b07302022-10-07 16:20:34 +02005076 sp<SwAudioOutputDescriptor> outputDesc;
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005077 if (!sourceDesc->isInternal()) {
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005078 // take care of dynamic routing for SwOutput selection,
5079 audio_attributes_t attributes = sourceDesc->attributes();
5080 audio_stream_type_t stream = sourceDesc->stream();
5081 audio_attributes_t resultAttr;
5082 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
5083 config.sample_rate = sourceDesc->config().sample_rate;
François Gaffie2a24db42022-04-04 16:45:02 +02005084 audio_channel_mask_t sourceMask = sourceDesc->config().channel_mask;
5085 config.channel_mask =
5086 (audio_channel_mask_get_representation(sourceMask)
5087 == AUDIO_CHANNEL_REPRESENTATION_INDEX) ? sourceMask
5088 : audio_channel_mask_in_to_out(sourceMask);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005089 config.format = sourceDesc->config().format;
5090 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
5091 audio_port_handle_t selectedDeviceId = AUDIO_PORT_HANDLE_NONE;
5092 bool isRequestedDeviceForExclusiveUse = false;
5093 output_type_t outputType;
Eric Laurentb0a7bc92022-04-05 15:06:08 +02005094 bool isSpatialized;
jiabinc658e452022-10-21 20:52:21 +00005095 bool isBitPerfect;
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005096 getOutputForAttrInt(&resultAttr, &output, AUDIO_SESSION_NONE, &attributes,
5097 &stream, sourceDesc->uid(), &config, &flags,
5098 &selectedDeviceId, &isRequestedDeviceForExclusiveUse,
jiabinc658e452022-10-21 20:52:21 +00005099 nullptr, &outputType, &isSpatialized, &isBitPerfect);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005100 if (output == AUDIO_IO_HANDLE_NONE) {
5101 ALOGV("%s no output for device %s",
5102 __FUNCTION__, sinkDevice->toString().c_str());
5103 return INVALID_OPERATION;
5104 }
5105 outputDesc = mOutputs.valueFor(output);
5106 if (outputDesc->isDuplicated()) {
5107 ALOGE("%s output is duplicated", __func__);
5108 return INVALID_OPERATION;
5109 }
François Gaffie7e39df22022-04-26 12:48:49 +02005110 bool closeOutput = outputDesc->mDirectOpenCount != 0;
5111 sourceDesc->setSwOutput(outputDesc, closeOutput);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005112 } else {
5113 // Same for "raw patches" aka created from createAudioPatch API
5114 SortedVector<audio_io_handle_t> outputs =
5115 getOutputsForDevices(DeviceVector(sinkDevice), mOutputs);
5116 // if the sink device is reachable via an opened output stream, request to
5117 // go via this output stream by adding a second source to the patch
5118 // description
5119 output = selectOutput(outputs);
5120 if (output == AUDIO_IO_HANDLE_NONE) {
5121 ALOGE("%s no output available for internal patch sink", __func__);
5122 return INVALID_OPERATION;
5123 }
5124 outputDesc = mOutputs.valueFor(output);
5125 if (outputDesc->isDuplicated()) {
5126 ALOGV("%s output for device %s is duplicated",
5127 __func__, sinkDevice->toString().c_str());
5128 return INVALID_OPERATION;
5129 }
François Gaffie7e39df22022-04-26 12:48:49 +02005130 sourceDesc->setSwOutput(outputDesc, /* closeOutput= */ false);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005131 }
Eric Laurent3bcf8592015-04-03 12:13:24 -07005132 // create a software bridge in PatchPanel if:
Scott Randolphf3172402018-01-23 17:06:53 -08005133 // - source and sink devices are on different HW modules OR
Eric Laurent3bcf8592015-04-03 12:13:24 -07005134 // - audio HAL version is < 3.0
Francois Gaffie99896da2018-04-09 11:05:33 +02005135 // - audio HAL version is >= 3.0 but no route has been declared between devices
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005136 // - called from startAudioSource (aka sourceDesc is not internal) and source device
5137 // does not have a gain controller
François Gaffie11d30102018-11-02 16:09:09 +01005138 if (!srcDevice->hasSameHwModuleAs(sinkDevice) ||
5139 (srcDevice->getModuleVersionMajor() < 3) ||
François Gaffieafd4cea2019-11-18 15:50:22 +01005140 !srcDevice->getModule()->supportsPatch(srcDevice, sinkDevice) ||
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005141 (!sourceDesc->isInternal() &&
François Gaffieafd4cea2019-11-18 15:50:22 +01005142 srcDevice->getAudioPort()->getGains().size() == 0)) {
Eric Laurent3bcf8592015-04-03 12:13:24 -07005143 // support only one sink device for now to simplify output selection logic
Eric Laurent874c42872014-08-08 15:13:39 -07005144 if (patch->num_sinks > 1) {
Eric Laurent83b88082014-06-20 18:31:16 -07005145 return INVALID_OPERATION;
5146 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005147 sourceDesc->setUseSwBridge();
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005148 if (outputDesc != nullptr) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005149 audio_port_config srcMixPortConfig = {};
Ytai Ben-Tsvic9d2a912021-11-22 16:43:09 -08005150 outputDesc->toAudioPortConfig(&srcMixPortConfig, nullptr);
François Gaffieafd4cea2019-11-18 15:50:22 +01005151 // for volume control, we may need a valid stream
Eric Laurent78b07302022-10-07 16:20:34 +02005152 srcMixPortConfig.ext.mix.usecase.stream =
5153 (!sourceDesc->isInternal() || isCallTxAudioSource(sourceDesc)) ?
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005154 mEngine->getStreamTypeForAttributes(sourceDesc->attributes()) :
5155 AUDIO_STREAM_PATCH;
François Gaffieafd4cea2019-11-18 15:50:22 +01005156 patchBuilder.addSource(srcMixPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07005157 }
Eric Laurent83b88082014-06-20 18:31:16 -07005158 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005159 }
5160 // TODO: check from routing capabilities in config file and other conflicting patches
5161
Dean Wheatley8bee85a2021-02-10 16:02:23 +11005162installPatch:
François Gaffieafd4cea2019-11-18 15:50:22 +01005163 status_t status = installPatch(
5164 __func__, index, handle, patchBuilder.patch(), delayMs, uid, &patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07005165 if (status != NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005166 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
Eric Laurent6a94d692014-05-20 11:18:06 -07005167 return INVALID_OPERATION;
5168 }
5169 } else {
5170 return BAD_VALUE;
5171 }
5172 } else {
5173 return BAD_VALUE;
5174 }
5175 return NO_ERROR;
5176}
5177
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005178status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle, uid_t uid)
Eric Laurent6a94d692014-05-20 11:18:06 -07005179{
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005180 ALOGV("%s patch %d", __func__, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005181 ssize_t index = mAudioPatches.indexOfKey(handle);
5182
5183 if (index < 0) {
5184 return BAD_VALUE;
5185 }
5186 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005187 ALOGV("%s() mUidCached %d patchDesc->mUid %d uid %d",
5188 __func__, mUidCached, patchDesc->getUid(), uid);
5189 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005190 return INVALID_OPERATION;
5191 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005192 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
5193 for (size_t i = 0; i < mAudioSources.size(); i++) {
5194 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
5195 if (sourceDesc != nullptr && sourceDesc->getPatchHandle() == handle) {
5196 portId = sourceDesc->portId();
5197 break;
5198 }
5199 }
5200 return portId != AUDIO_PORT_HANDLE_NONE ?
5201 stopAudioSource(portId) : releaseAudioPatchInternal(handle);
François Gaffieafd4cea2019-11-18 15:50:22 +01005202}
Eric Laurent6a94d692014-05-20 11:18:06 -07005203
François Gaffieafd4cea2019-11-18 15:50:22 +01005204status_t AudioPolicyManager::releaseAudioPatchInternal(audio_patch_handle_t handle,
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005205 uint32_t delayMs,
5206 const sp<SourceClientDescriptor>& sourceDesc)
François Gaffieafd4cea2019-11-18 15:50:22 +01005207{
5208 ALOGV("%s patch %d", __func__, handle);
5209 if (mAudioPatches.indexOfKey(handle) < 0) {
5210 ALOGE("%s: no patch found with handle=%d", __func__, handle);
5211 return BAD_VALUE;
5212 }
5213 sp<AudioPatch> patchDesc = mAudioPatches.valueFor(handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005214 struct audio_patch *patch = &patchDesc->mPatch;
François Gaffieafd4cea2019-11-18 15:50:22 +01005215 patchDesc->setUid(mUidCached);
Eric Laurent6a94d692014-05-20 11:18:06 -07005216 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005217 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005218 if (outputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005219 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005220 return BAD_VALUE;
5221 }
5222
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05305223 setOutputDevices(__func__, outputDesc,
François Gaffie11d30102018-11-02 16:09:09 +01005224 getNewOutputDevices(outputDesc, true /*fromCache*/),
5225 true,
5226 0,
5227 NULL);
Eric Laurent6a94d692014-05-20 11:18:06 -07005228 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
5229 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
François Gaffie53615e22015-03-19 09:24:12 +01005230 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005231 if (inputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005232 ALOGV("%s input not found for id %d", __func__, patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005233 return BAD_VALUE;
5234 }
5235 setInputDevice(inputDesc->mIoHandle,
Eric Laurentfb66dd92016-01-28 18:32:03 -08005236 getNewInputDevice(inputDesc),
Eric Laurent6a94d692014-05-20 11:18:06 -07005237 true,
5238 NULL);
5239 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005240 status_t status =
5241 mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
5242 ALOGV("%s patch panel returned %d patchHandle %d",
5243 __func__, status, patchDesc->getAfHandle());
5244 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005245 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005246 mpClientInterface->onAudioPatchListUpdate();
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005247 // SW or HW Bridge
5248 sp<SwAudioOutputDescriptor> outputDesc = nullptr;
5249 audio_patch_handle_t patchHandle = AUDIO_PATCH_HANDLE_NONE;
Francois Gaffie7feb8542020-04-06 17:39:47 +02005250 if (patch->num_sources > 1 && patch->sources[1].type == AUDIO_PORT_TYPE_MIX) {
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005251 outputDesc = mOutputs.getOutputFromId(patch->sources[1].id);
5252 } else if (patch->num_sources == 1 && sourceDesc != nullptr) {
5253 outputDesc = sourceDesc->swOutput().promote();
5254 }
5255 if (outputDesc == nullptr) {
5256 ALOGW("%s no output for id %d", __func__, patch->sources[0].id);
5257 // releaseOutput has already called closeOutput in case of direct output
5258 return NO_ERROR;
5259 }
François Gaffie7e39df22022-04-26 12:48:49 +02005260 patchHandle = outputDesc->getPatchHandle();
5261 // When a Sw bridge is released, the mixer used by this bridge will release its
5262 // patch at AudioFlinger side. Hence, the mixer audio patch must be recreated
5263 // Reuse patch handle to force audio flinger removing initial mixer patch removal
5264 // updating hal patch handle (prevent leaks).
5265 // While using a HwBridge, force reconsidering device only if not reusing an existing
5266 // output and no more activity on output (will force to close).
5267 bool force = sourceDesc->useSwBridge() ||
5268 (sourceDesc->canCloseOutput() && !outputDesc->isActive());
5269 // APM pattern is to have always outputs opened / patch realized for reachable devices.
5270 // Update device may result to NONE (empty), coupled with force, it releases the patch.
5271 // Reconsider device only for cases:
5272 // 1 / Active Output
5273 // 2 / Inactive Output previously hosting HwBridge
5274 // 3 / Inactive Output previously hosting SwBridge that can be closed.
5275 bool updateDevice = outputDesc->isActive() || !sourceDesc->useSwBridge() ||
5276 sourceDesc->canCloseOutput();
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05305277 setOutputDevices(__func__, outputDesc,
François Gaffie7e39df22022-04-26 12:48:49 +02005278 updateDevice ? getNewOutputDevices(outputDesc, true /*fromCache*/) :
5279 outputDesc->devices(),
5280 force,
5281 0,
5282 patchHandle == AUDIO_PATCH_HANDLE_NONE ? nullptr : &patchHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005283 } else {
5284 return BAD_VALUE;
5285 }
5286 } else {
5287 return BAD_VALUE;
5288 }
5289 return NO_ERROR;
5290}
5291
5292status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
5293 struct audio_patch *patches,
5294 unsigned int *generation)
5295{
François Gaffie53615e22015-03-19 09:24:12 +01005296 if (generation == NULL) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005297 return BAD_VALUE;
5298 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005299 *generation = curAudioPortGeneration();
François Gaffie53615e22015-03-19 09:24:12 +01005300 return mAudioPatches.listAudioPatches(num_patches, patches);
Eric Laurent6a94d692014-05-20 11:18:06 -07005301}
5302
Eric Laurente1715a42014-05-20 11:30:42 -07005303status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07005304{
Eric Laurente1715a42014-05-20 11:30:42 -07005305 ALOGV("setAudioPortConfig()");
5306
5307 if (config == NULL) {
5308 return BAD_VALUE;
5309 }
5310 ALOGV("setAudioPortConfig() on port handle %d", config->id);
5311 // Only support gain configuration for now
Eric Laurenta121f902014-06-03 13:32:54 -07005312 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
5313 return INVALID_OPERATION;
Eric Laurente1715a42014-05-20 11:30:42 -07005314 }
5315
Eric Laurenta121f902014-06-03 13:32:54 -07005316 sp<AudioPortConfig> audioPortConfig;
Eric Laurente1715a42014-05-20 11:30:42 -07005317 if (config->type == AUDIO_PORT_TYPE_MIX) {
5318 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005319 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07005320 if (outputDesc == NULL) {
5321 return BAD_VALUE;
5322 }
Eric Laurent84c70242014-06-23 08:46:27 -07005323 ALOG_ASSERT(!outputDesc->isDuplicated(),
5324 "setAudioPortConfig() called on duplicated output %d",
5325 outputDesc->mIoHandle);
Eric Laurenta121f902014-06-03 13:32:54 -07005326 audioPortConfig = outputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07005327 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
François Gaffie53615e22015-03-19 09:24:12 +01005328 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07005329 if (inputDesc == NULL) {
5330 return BAD_VALUE;
5331 }
Eric Laurenta121f902014-06-03 13:32:54 -07005332 audioPortConfig = inputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07005333 } else {
5334 return BAD_VALUE;
5335 }
5336 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
5337 sp<DeviceDescriptor> deviceDesc;
5338 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
5339 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
5340 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
5341 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
5342 } else {
5343 return BAD_VALUE;
5344 }
5345 if (deviceDesc == NULL) {
5346 return BAD_VALUE;
5347 }
Eric Laurenta121f902014-06-03 13:32:54 -07005348 audioPortConfig = deviceDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07005349 } else {
5350 return BAD_VALUE;
5351 }
5352
Mikhail Naganov7be71d22018-05-23 16:51:46 -07005353 struct audio_port_config backupConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07005354 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
5355 if (status == NO_ERROR) {
Mikhail Naganov7be71d22018-05-23 16:51:46 -07005356 struct audio_port_config newConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07005357 audioPortConfig->toAudioPortConfig(&newConfig, config);
5358 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
Eric Laurente1715a42014-05-20 11:30:42 -07005359 }
Eric Laurenta121f902014-06-03 13:32:54 -07005360 if (status != NO_ERROR) {
5361 audioPortConfig->applyAudioPortConfig(&backupConfig);
Eric Laurente1715a42014-05-20 11:30:42 -07005362 }
Eric Laurente1715a42014-05-20 11:30:42 -07005363
5364 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07005365}
5366
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005367void AudioPolicyManager::releaseResourcesForUid(uid_t uid)
5368{
Eric Laurentd60560a2015-04-10 11:31:20 -07005369 clearAudioSources(uid);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005370 clearAudioPatches(uid);
5371 clearSessionRoutes(uid);
5372}
5373
Eric Laurent6a94d692014-05-20 11:18:06 -07005374void AudioPolicyManager::clearAudioPatches(uid_t uid)
5375{
Eric Laurent0add0fd2014-12-04 18:58:14 -08005376 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005377 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
François Gaffieafd4cea2019-11-18 15:50:22 +01005378 if (patchDesc->getUid() == uid) {
Eric Laurent0add0fd2014-12-04 18:58:14 -08005379 releaseAudioPatch(mAudioPatches.keyAt(i), uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07005380 }
5381 }
5382}
5383
François Gaffiec005e562018-11-06 15:04:49 +01005384void AudioPolicyManager::checkStrategyRoute(product_strategy_t ps, audio_io_handle_t ouptutToSkip)
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005385{
François Gaffiec005e562018-11-06 15:04:49 +01005386 // Take the first attributes following the product strategy as it is used to retrieve the routed
5387 // device. All attributes wihin a strategy follows the same "routing strategy"
5388 auto attributes = mEngine->getAllAttributesForProductStrategy(ps).front();
5389 DeviceVector devices = mEngine->getOutputDevicesForAttributes(attributes, nullptr, false);
François Gaffie11d30102018-11-02 16:09:09 +01005390 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
jiabin3ff8d7d2022-12-13 06:27:44 +00005391 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005392 for (size_t j = 0; j < mOutputs.size(); j++) {
5393 if (mOutputs.keyAt(j) == ouptutToSkip) {
5394 continue;
5395 }
5396 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(j);
François Gaffiec005e562018-11-06 15:04:49 +01005397 if (!outputDesc->isStrategyActive(ps)) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005398 continue;
5399 }
5400 // If the default device for this strategy is on another output mix,
5401 // invalidate all tracks in this strategy to force re connection.
5402 // Otherwise select new device on the output mix.
5403 if (outputs.indexOf(mOutputs.keyAt(j)) < 0) {
jiabinc44b3462022-12-08 12:52:31 -08005404 invalidateStreams(mEngine->getStreamTypesForProductStrategy(ps));
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005405 } else {
jiabin3ff8d7d2022-12-13 06:27:44 +00005406 DeviceVector newDevices = getNewOutputDevices(outputDesc, false /*fromCache*/);
5407 if (outputDesc->mUsePreferredMixerAttributes && outputDesc->devices() != newDevices) {
5408 // If the device is using preferred mixer attributes, the output need to reopen
5409 // with default configuration when the new selected devices are different from
5410 // current routing devices.
5411 outputsToReopen.emplace(mOutputs.keyAt(j), newDevices);
5412 continue;
5413 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05305414 setOutputDevices(__func__, outputDesc, newDevices, false);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005415 }
5416 }
jiabin3ff8d7d2022-12-13 06:27:44 +00005417 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005418}
5419
5420void AudioPolicyManager::clearSessionRoutes(uid_t uid)
5421{
5422 // remove output routes associated with this uid
François Gaffiec005e562018-11-06 15:04:49 +01005423 std::vector<product_strategy_t> affectedStrategies;
Eric Laurent97ac8712018-07-27 18:59:02 -07005424 for (size_t i = 0; i < mOutputs.size(); i++) {
5425 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07005426 for (const auto& client : outputDesc->getClientIterable()) {
5427 if (client->hasPreferredDevice() && client->uid() == uid) {
5428 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
François Gaffiec005e562018-11-06 15:04:49 +01005429 auto clientStrategy = client->strategy();
5430 if (std::find(begin(affectedStrategies), end(affectedStrategies), clientStrategy) !=
5431 end(affectedStrategies)) {
5432 continue;
5433 }
5434 affectedStrategies.push_back(client->strategy());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005435 }
5436 }
5437 }
5438 // reroute outputs if necessary
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005439 for (const auto& strategy : affectedStrategies) {
5440 checkStrategyRoute(strategy, AUDIO_IO_HANDLE_NONE);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005441 }
5442
5443 // remove input routes associated with this uid
5444 SortedVector<audio_source_t> affectedSources;
Eric Laurent97ac8712018-07-27 18:59:02 -07005445 for (size_t i = 0; i < mInputs.size(); i++) {
5446 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07005447 for (const auto& client : inputDesc->getClientIterable()) {
5448 if (client->hasPreferredDevice() && client->uid() == uid) {
5449 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
5450 affectedSources.add(client->source());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005451 }
5452 }
5453 }
5454 // reroute inputs if necessary
5455 SortedVector<audio_io_handle_t> inputsToClose;
5456 for (size_t i = 0; i < mInputs.size(); i++) {
5457 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Eric Laurent4eb58f12018-12-07 16:41:02 -08005458 if (affectedSources.indexOf(inputDesc->source()) >= 0) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005459 inputsToClose.add(inputDesc->mIoHandle);
5460 }
5461 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005462 for (const auto& input : inputsToClose) {
5463 closeInput(input);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005464 }
5465}
5466
Eric Laurentd60560a2015-04-10 11:31:20 -07005467void AudioPolicyManager::clearAudioSources(uid_t uid)
5468{
5469 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005470 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
5471 if (sourceDesc->uid() == uid) {
Eric Laurentd60560a2015-04-10 11:31:20 -07005472 stopAudioSource(mAudioSources.keyAt(i));
5473 }
5474 }
5475}
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005476
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005477status_t AudioPolicyManager::acquireSoundTriggerSession(audio_session_t *session,
5478 audio_io_handle_t *ioHandle,
5479 audio_devices_t *device)
5480{
Glenn Kastenf0c6d7d2016-02-26 10:44:04 -08005481 *session = (audio_session_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
5482 *ioHandle = (audio_io_handle_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
Francois Gaffie716e1432019-01-14 16:58:59 +01005483 audio_attributes_t attr = { .source = AUDIO_SOURCE_HOTWORD };
Eric Laurentcedd5b52023-03-22 00:03:31 +00005484 sp<DeviceDescriptor> deviceDesc = mEngine->getInputDeviceForAttributes(attr);
5485 if (deviceDesc == nullptr) {
5486 return INVALID_OPERATION;
5487 }
5488 *device = deviceDesc->type();
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005489
François Gaffiedf372692015-03-19 10:43:27 +01005490 return mSoundTriggerSessions.acquireSession(*session, *ioHandle);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005491}
5492
Eric Laurentd60560a2015-04-10 11:31:20 -07005493status_t AudioPolicyManager::startAudioSource(const struct audio_port_config *source,
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005494 const audio_attributes_t *attributes,
5495 audio_port_handle_t *portId,
5496 uid_t uid)
Eric Laurent554a2772015-04-10 11:29:24 -07005497{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005498 ALOGV("%s", __FUNCTION__);
5499 *portId = AUDIO_PORT_HANDLE_NONE;
5500
5501 if (source == NULL || attributes == NULL || portId == NULL) {
5502 ALOGW("%s invalid argument: source %p attributes %p handle %p",
5503 __FUNCTION__, source, attributes, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005504 return BAD_VALUE;
5505 }
5506
Eric Laurentd60560a2015-04-10 11:31:20 -07005507 if (source->role != AUDIO_PORT_ROLE_SOURCE ||
5508 source->type != AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005509 ALOGW("%s INVALID_OPERATION source->role %d source->type %d",
5510 __FUNCTION__, source->role, source->type);
Eric Laurentd60560a2015-04-10 11:31:20 -07005511 return INVALID_OPERATION;
5512 }
5513
François Gaffie11d30102018-11-02 16:09:09 +01005514 sp<DeviceDescriptor> srcDevice =
Eric Laurentd60560a2015-04-10 11:31:20 -07005515 mAvailableInputDevices.getDevice(source->ext.device.type,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005516 String8(source->ext.device.address),
5517 AUDIO_FORMAT_DEFAULT);
François Gaffie11d30102018-11-02 16:09:09 +01005518 if (srcDevice == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005519 ALOGW("%s source->ext.device.type %08x not found", __FUNCTION__, source->ext.device.type);
Eric Laurentd60560a2015-04-10 11:31:20 -07005520 return BAD_VALUE;
5521 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005522
jiabin4ef93452019-09-10 14:29:54 -07005523 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurentd60560a2015-04-10 11:31:20 -07005524
François Gaffieaaac0fd2018-11-22 17:56:39 +01005525 sp<SourceClientDescriptor> sourceDesc =
François Gaffieafd4cea2019-11-18 15:50:22 +01005526 new SourceClientDescriptor(*portId, uid, *attributes, *source, srcDevice,
François Gaffieaaac0fd2018-11-22 17:56:39 +01005527 mEngine->getStreamTypeForAttributes(*attributes),
5528 mEngine->getProductStrategyForAttributes(*attributes),
5529 toVolumeSource(*attributes));
Eric Laurentd60560a2015-04-10 11:31:20 -07005530
5531 status_t status = connectAudioSource(sourceDesc);
5532 if (status == NO_ERROR) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005533 mAudioSources.add(*portId, sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07005534 }
5535 return status;
5536}
5537
Francois Gaffie601801d2021-06-22 13:27:39 +02005538sp<SourceClientDescriptor> AudioPolicyManager::startAudioSourceInternal(
5539 const struct audio_port_config *source, const audio_attributes_t *attributes, uid_t uid)
5540{
5541 ALOGV("%s", __FUNCTION__);
5542 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
5543
5544 status_t status = startAudioSource(source, attributes, &portId, uid);
5545 ALOGE_IF(status != OK, "%s: failed to start audio source (%d)", __func__, status);
5546 return mAudioSources.valueFor(portId);
5547}
5548
5549
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005550status_t AudioPolicyManager::connectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07005551{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005552 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->portId());
Eric Laurentd60560a2015-04-10 11:31:20 -07005553
5554 // make sure we only have one patch per source.
5555 disconnectAudioSource(sourceDesc);
5556
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005557 audio_attributes_t attributes = sourceDesc->attributes();
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005558 // May the device (dynamic) have been disconnected/reconnected, id has changed.
5559 sp<DeviceDescriptor> srcDevice = mAvailableInputDevices.getDevice(
5560 sourceDesc->srcDevice()->type(),
5561 String8(sourceDesc->srcDevice()->address().c_str()),
5562 AUDIO_FORMAT_DEFAULT);
François Gaffiec005e562018-11-06 15:04:49 +01005563 DeviceVector sinkDevices =
Francois Gaffieff1eb522020-05-06 18:37:04 +02005564 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false /*fromCache*/);
François Gaffiec005e562018-11-06 15:04:49 +01005565 ALOG_ASSERT(!sinkDevices.isEmpty(), "connectAudioSource(): no device found for attributes");
François Gaffie11d30102018-11-02 16:09:09 +01005566 sp<DeviceDescriptor> sinkDevice = sinkDevices.itemAt(0);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005567 if (!mAvailableOutputDevices.contains(sinkDevice)) {
5568 ALOGE("%s Device %s not available", __func__, sinkDevice->toString().c_str());
5569 return INVALID_OPERATION;
5570 }
François Gaffieafd4cea2019-11-18 15:50:22 +01005571 PatchBuilder patchBuilder;
5572 patchBuilder.addSink(sinkDevice).addSource(srcDevice);
5573 audio_patch_handle_t handle = AUDIO_PATCH_HANDLE_NONE;
François Gaffieafd4cea2019-11-18 15:50:22 +01005574
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005575 return connectAudioSourceToSink(
5576 sourceDesc, sinkDevice, patchBuilder.patch(), handle, mUidCached, 0 /*delayMs*/);
Eric Laurent554a2772015-04-10 11:29:24 -07005577}
5578
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005579status_t AudioPolicyManager::stopAudioSource(audio_port_handle_t portId)
Eric Laurent554a2772015-04-10 11:29:24 -07005580{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005581 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueFor(portId);
5582 ALOGV("%s port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005583 if (sourceDesc == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005584 ALOGW("%s unknown source for port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005585 return BAD_VALUE;
5586 }
5587 status_t status = disconnectAudioSource(sourceDesc);
5588
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005589 mAudioSources.removeItem(portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005590 return status;
5591}
5592
Andy Hung2ddee192015-12-18 17:34:44 -08005593status_t AudioPolicyManager::setMasterMono(bool mono)
5594{
5595 if (mMasterMono == mono) {
5596 return NO_ERROR;
5597 }
5598 mMasterMono = mono;
5599 // if enabling mono we close all offloaded devices, which will invalidate the
5600 // corresponding AudioTrack. The AudioTrack client/MediaPlayer is responsible
5601 // for recreating the new AudioTrack as non-offloaded PCM.
5602 //
5603 // If disabling mono, we leave all tracks as is: we don't know which clients
5604 // and tracks are able to be recreated as offloaded. The next "song" should
5605 // play back offloaded.
5606 if (mMasterMono) {
5607 Vector<audio_io_handle_t> offloaded;
5608 for (size_t i = 0; i < mOutputs.size(); ++i) {
5609 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
5610 if (desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
5611 offloaded.push(desc->mIoHandle);
5612 }
5613 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005614 for (const auto& handle : offloaded) {
5615 closeOutput(handle);
Andy Hung2ddee192015-12-18 17:34:44 -08005616 }
5617 }
5618 // update master mono for all remaining outputs
5619 for (size_t i = 0; i < mOutputs.size(); ++i) {
5620 updateMono(mOutputs.keyAt(i));
5621 }
5622 return NO_ERROR;
5623}
5624
5625status_t AudioPolicyManager::getMasterMono(bool *mono)
5626{
5627 *mono = mMasterMono;
5628 return NO_ERROR;
5629}
5630
Eric Laurentac9cef52017-06-09 15:46:26 -07005631float AudioPolicyManager::getStreamVolumeDB(
5632 audio_stream_type_t stream, int index, audio_devices_t device)
5633{
jiabin9a3361e2019-10-01 09:38:30 -07005634 return computeVolume(getVolumeCurves(stream), toVolumeSource(stream), index, {device});
Eric Laurentac9cef52017-06-09 15:46:26 -07005635}
5636
jiabin81772902018-04-02 17:52:27 -07005637status_t AudioPolicyManager::getSurroundFormats(unsigned int *numSurroundFormats,
5638 audio_format_t *surroundFormats,
Kriti Dang6537def2021-03-02 13:46:59 +01005639 bool *surroundFormatsEnabled)
jiabin81772902018-04-02 17:52:27 -07005640{
Kriti Dang6537def2021-03-02 13:46:59 +01005641 if (numSurroundFormats == nullptr || (*numSurroundFormats != 0 &&
5642 (surroundFormats == nullptr || surroundFormatsEnabled == nullptr))) {
jiabin81772902018-04-02 17:52:27 -07005643 return BAD_VALUE;
5644 }
Kriti Dang6537def2021-03-02 13:46:59 +01005645 ALOGV("%s() numSurroundFormats %d surroundFormats %p surroundFormatsEnabled %p",
5646 __func__, *numSurroundFormats, surroundFormats, surroundFormatsEnabled);
jiabin81772902018-04-02 17:52:27 -07005647
5648 size_t formatsWritten = 0;
5649 size_t formatsMax = *numSurroundFormats;
Kriti Dangef6be8f2020-11-05 11:58:19 +01005650
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005651 *numSurroundFormats = mConfig->getSurroundFormats().size();
Mikhail Naganov100f0122018-11-29 11:22:16 -08005652 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
5653 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005654 for (const auto& format: mConfig->getSurroundFormats()) {
jiabin81772902018-04-02 17:52:27 -07005655 if (formatsWritten < formatsMax) {
Kriti Dang6537def2021-03-02 13:46:59 +01005656 surroundFormats[formatsWritten] = format.first;
Mikhail Naganov100f0122018-11-29 11:22:16 -08005657 bool formatEnabled = true;
5658 switch (forceUse) {
5659 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL:
Kriti Dang6537def2021-03-02 13:46:59 +01005660 formatEnabled = mManualSurroundFormats.count(format.first) != 0;
Mikhail Naganov100f0122018-11-29 11:22:16 -08005661 break;
5662 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER:
5663 formatEnabled = false;
5664 break;
5665 default: // AUTO or ALWAYS => true
5666 break;
jiabin81772902018-04-02 17:52:27 -07005667 }
5668 surroundFormatsEnabled[formatsWritten++] = formatEnabled;
5669 }
jiabin81772902018-04-02 17:52:27 -07005670 }
5671 return NO_ERROR;
5672}
5673
Kriti Dang6537def2021-03-02 13:46:59 +01005674status_t AudioPolicyManager::getReportedSurroundFormats(unsigned int *numSurroundFormats,
5675 audio_format_t *surroundFormats) {
5676 if (numSurroundFormats == nullptr || (*numSurroundFormats != 0 && surroundFormats == nullptr)) {
5677 return BAD_VALUE;
5678 }
5679 ALOGV("%s() numSurroundFormats %d surroundFormats %p",
5680 __func__, *numSurroundFormats, surroundFormats);
5681
5682 size_t formatsWritten = 0;
5683 size_t formatsMax = *numSurroundFormats;
5684 std::unordered_set<audio_format_t> formats; // Uses primary surround formats only
5685
5686 // Return formats from all device profiles that have already been resolved by
5687 // checkOutputsForDevice().
5688 for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
5689 sp<DeviceDescriptor> device = mAvailableOutputDevices[i];
5690 audio_devices_t deviceType = device->type();
5691 // Enabling/disabling formats are applied to only HDMI devices. So, this function
5692 // returns formats reported by HDMI devices.
5693 if (deviceType != AUDIO_DEVICE_OUT_HDMI) {
5694 continue;
5695 }
5696 // Formats reported by sink devices
5697 std::unordered_set<audio_format_t> formatset;
5698 if (auto it = mReportedFormatsMap.find(device); it != mReportedFormatsMap.end()) {
5699 formatset.insert(it->second.begin(), it->second.end());
5700 }
5701
5702 // Formats hard-coded in the in policy configuration file (if any).
5703 FormatVector encodedFormats = device->encodedFormats();
5704 formatset.insert(encodedFormats.begin(), encodedFormats.end());
5705 // Filter the formats which are supported by the vendor hardware.
5706 for (auto it = formatset.begin(); it != formatset.end(); ++it) {
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005707 if (mConfig->getSurroundFormats().count(*it) != 0) {
Kriti Dang6537def2021-03-02 13:46:59 +01005708 formats.insert(*it);
5709 } else {
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005710 for (const auto& pair : mConfig->getSurroundFormats()) {
Kriti Dang6537def2021-03-02 13:46:59 +01005711 if (pair.second.count(*it) != 0) {
5712 formats.insert(pair.first);
5713 break;
5714 }
5715 }
5716 }
5717 }
5718 }
5719 *numSurroundFormats = formats.size();
5720 for (const auto& format: formats) {
5721 if (formatsWritten < formatsMax) {
5722 surroundFormats[formatsWritten++] = format;
5723 }
5724 }
5725 return NO_ERROR;
5726}
5727
jiabin81772902018-04-02 17:52:27 -07005728status_t AudioPolicyManager::setSurroundFormatEnabled(audio_format_t audioFormat, bool enabled)
5729{
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005730 ALOGV("%s() format 0x%X enabled %d", __func__, audioFormat, enabled);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005731 const auto& formatIter = mConfig->getSurroundFormats().find(audioFormat);
5732 if (formatIter == mConfig->getSurroundFormats().end()) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005733 ALOGW("%s() format 0x%X is not a known surround format", __func__, audioFormat);
jiabin81772902018-04-02 17:52:27 -07005734 return BAD_VALUE;
5735 }
5736
Mikhail Naganov100f0122018-11-29 11:22:16 -08005737 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND) !=
5738 AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005739 ALOGW("%s() not in manual mode for surround sound format selection", __func__);
jiabin81772902018-04-02 17:52:27 -07005740 return INVALID_OPERATION;
5741 }
5742
Mikhail Naganov100f0122018-11-29 11:22:16 -08005743 if ((mManualSurroundFormats.count(audioFormat) != 0) == enabled) {
jiabin81772902018-04-02 17:52:27 -07005744 return NO_ERROR;
5745 }
5746
Mikhail Naganov100f0122018-11-29 11:22:16 -08005747 std::unordered_set<audio_format_t> surroundFormatsBackup(mManualSurroundFormats);
jiabin81772902018-04-02 17:52:27 -07005748 if (enabled) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005749 mManualSurroundFormats.insert(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07005750 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005751 mManualSurroundFormats.insert(subFormat);
jiabin81772902018-04-02 17:52:27 -07005752 }
5753 } else {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005754 mManualSurroundFormats.erase(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07005755 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005756 mManualSurroundFormats.erase(subFormat);
jiabin81772902018-04-02 17:52:27 -07005757 }
5758 }
5759
5760 sp<SwAudioOutputDescriptor> outputDesc;
5761 bool profileUpdated = false;
jiabin9a3361e2019-10-01 09:38:30 -07005762 DeviceVector hdmiOutputDevices = mAvailableOutputDevices.getDevicesFromType(
5763 AUDIO_DEVICE_OUT_HDMI);
jiabin81772902018-04-02 17:52:27 -07005764 for (size_t i = 0; i < hdmiOutputDevices.size(); i++) {
5765 // Simulate reconnection to update enabled surround sound formats.
jiabince9f20e2019-09-12 16:29:15 -07005766 String8 address = String8(hdmiOutputDevices[i]->address().c_str());
jiabin5740f082019-08-19 15:08:30 -07005767 std::string name = hdmiOutputDevices[i]->getName();
jiabin81772902018-04-02 17:52:27 -07005768 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
5769 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
5770 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005771 name.c_str(),
5772 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005773 if (status != NO_ERROR) {
5774 continue;
5775 }
5776 status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
5777 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
5778 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005779 name.c_str(),
5780 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005781 profileUpdated |= (status == NO_ERROR);
5782 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08005783 // FIXME: Why doing this for input HDMI devices if we don't augment their reported formats?
jiabin9a3361e2019-10-01 09:38:30 -07005784 DeviceVector hdmiInputDevices = mAvailableInputDevices.getDevicesFromType(
jiabin81772902018-04-02 17:52:27 -07005785 AUDIO_DEVICE_IN_HDMI);
5786 for (size_t i = 0; i < hdmiInputDevices.size(); i++) {
5787 // Simulate reconnection to update enabled surround sound formats.
jiabince9f20e2019-09-12 16:29:15 -07005788 String8 address = String8(hdmiInputDevices[i]->address().c_str());
jiabin5740f082019-08-19 15:08:30 -07005789 std::string name = hdmiInputDevices[i]->getName();
jiabin81772902018-04-02 17:52:27 -07005790 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
5791 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
5792 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005793 name.c_str(),
5794 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005795 if (status != NO_ERROR) {
5796 continue;
5797 }
5798 status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
5799 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
5800 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005801 name.c_str(),
5802 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005803 profileUpdated |= (status == NO_ERROR);
5804 }
5805
jiabin81772902018-04-02 17:52:27 -07005806 if (!profileUpdated) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005807 ALOGW("%s() no audio profiles updated, undoing surround formats change", __func__);
Mikhail Naganov100f0122018-11-29 11:22:16 -08005808 mManualSurroundFormats = std::move(surroundFormatsBackup);
jiabin81772902018-04-02 17:52:27 -07005809 }
5810
5811 return profileUpdated ? NO_ERROR : INVALID_OPERATION;
5812}
5813
Eric Laurent5ada82e2019-08-29 17:53:54 -07005814void AudioPolicyManager::setAppState(audio_port_handle_t portId, app_state_t state)
Svet Ganovf4ddfef2018-01-16 07:37:58 -08005815{
Eric Laurent5ada82e2019-08-29 17:53:54 -07005816 ALOGV("%s(portId:%d, state:%d)", __func__, portId, state);
Eric Laurenta9f86652018-11-28 17:23:11 -08005817 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent5ada82e2019-08-29 17:53:54 -07005818 mInputs.valueAt(i)->setAppState(portId, state);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08005819 }
5820}
5821
jiabin6012f912018-11-02 17:06:30 -07005822bool AudioPolicyManager::isHapticPlaybackSupported()
5823{
5824 for (const auto& hwModule : mHwModules) {
5825 const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
5826 for (const auto &outProfile : outputProfiles) {
5827 struct audio_port audioPort;
5828 outProfile->toAudioPort(&audioPort);
5829 for (size_t i = 0; i < audioPort.num_channel_masks; i++) {
5830 if (audioPort.channel_masks[i] & AUDIO_CHANNEL_HAPTIC_ALL) {
5831 return true;
5832 }
5833 }
5834 }
5835 }
5836 return false;
5837}
5838
Carter Hsu325a8eb2022-01-19 19:56:51 +08005839bool AudioPolicyManager::isUltrasoundSupported()
5840{
5841 bool hasUltrasoundOutput = false;
5842 bool hasUltrasoundInput = false;
5843 for (const auto& hwModule : mHwModules) {
5844 const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
5845 if (!hasUltrasoundOutput) {
5846 for (const auto &outProfile : outputProfiles) {
5847 if (outProfile->getFlags() & AUDIO_OUTPUT_FLAG_ULTRASOUND) {
5848 hasUltrasoundOutput = true;
5849 break;
5850 }
5851 }
5852 }
5853
5854 const InputProfileCollection &inputProfiles = hwModule->getInputProfiles();
5855 if (!hasUltrasoundInput) {
5856 for (const auto &inputProfile : inputProfiles) {
5857 if (inputProfile->getFlags() & AUDIO_INPUT_FLAG_ULTRASOUND) {
5858 hasUltrasoundInput = true;
5859 break;
5860 }
5861 }
5862 }
5863
5864 if (hasUltrasoundOutput && hasUltrasoundInput)
5865 return true;
5866 }
5867 return false;
5868}
5869
Atneya Nair698f5ef2022-12-15 16:15:09 -08005870bool AudioPolicyManager::isHotwordStreamSupported(bool lookbackAudio)
5871{
5872 const auto mask = AUDIO_INPUT_FLAG_HOTWORD_TAP |
5873 (lookbackAudio ? AUDIO_INPUT_FLAG_HW_LOOKBACK : 0);
5874 for (const auto& hwModule : mHwModules) {
5875 const InputProfileCollection &inputProfiles = hwModule->getInputProfiles();
5876 for (const auto &inputProfile : inputProfiles) {
5877 if ((inputProfile->getFlags() & mask) == mask) {
5878 return true;
5879 }
5880 }
5881 }
5882 return false;
5883}
5884
Eric Laurent8340e672019-11-06 11:01:08 -08005885bool AudioPolicyManager::isCallScreenModeSupported()
5886{
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005887 return mConfig->isCallScreenModeSupported();
Eric Laurent8340e672019-11-06 11:01:08 -08005888}
5889
5890
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005891status_t AudioPolicyManager::disconnectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07005892{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005893 ALOGV("%s port Id %d", __FUNCTION__, sourceDesc->portId());
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005894 if (!sourceDesc->isConnected()) {
5895 ALOGV("%s port Id %d already disconnected", __FUNCTION__, sourceDesc->portId());
5896 return NO_ERROR;
5897 }
François Gaffieafd4cea2019-11-18 15:50:22 +01005898 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
5899 if (swOutput != 0) {
5900 status_t status = stopSource(swOutput, sourceDesc);
Eric Laurent733ce942017-12-07 12:18:25 -08005901 if (status == NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005902 swOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08005903 }
jiabinbce0c1d2020-10-05 11:20:18 -07005904 if (releaseOutput(sourceDesc->portId())) {
5905 // The output descriptor is reopened to query dynamic profiles. In that case, there is
5906 // no need to release audio patch here but just return NO_ERROR.
5907 return NO_ERROR;
5908 }
Eric Laurentd60560a2015-04-10 11:31:20 -07005909 } else {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005910 sp<HwAudioOutputDescriptor> hwOutputDesc = sourceDesc->hwOutput().promote();
Eric Laurentd60560a2015-04-10 11:31:20 -07005911 if (hwOutputDesc != 0) {
Eric Laurentd60560a2015-04-10 11:31:20 -07005912 // close Hwoutput and remove from mHwOutputs
5913 } else {
5914 ALOGW("%s source has neither SW nor HW output", __FUNCTION__);
5915 }
5916 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005917 status_t status = releaseAudioPatchInternal(sourceDesc->getPatchHandle(), 0, sourceDesc);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005918 sourceDesc->disconnect();
5919 return status;
Eric Laurentd60560a2015-04-10 11:31:20 -07005920}
5921
François Gaffiec005e562018-11-06 15:04:49 +01005922sp<SourceClientDescriptor> AudioPolicyManager::getSourceForAttributesOnOutput(
5923 audio_io_handle_t output, const audio_attributes_t &attr)
Eric Laurentd60560a2015-04-10 11:31:20 -07005924{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005925 sp<SourceClientDescriptor> source;
Eric Laurentd60560a2015-04-10 11:31:20 -07005926 for (size_t i = 0; i < mAudioSources.size(); i++) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005927 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005928 sp<SwAudioOutputDescriptor> outputDesc = sourceDesc->swOutput().promote();
François Gaffiec005e562018-11-06 15:04:49 +01005929 if (followsSameRouting(attr, sourceDesc->attributes()) &&
5930 outputDesc != 0 && outputDesc->mIoHandle == output) {
Eric Laurentd60560a2015-04-10 11:31:20 -07005931 source = sourceDesc;
5932 break;
5933 }
5934 }
5935 return source;
Eric Laurent554a2772015-04-10 11:29:24 -07005936}
5937
Eric Laurentb4f42a92022-01-17 17:37:31 +01005938bool AudioPolicyManager::canBeSpatializedInt(const audio_attributes_t *attr,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005939 const audio_config_t *config,
Andy Hung9dd1a5b2022-05-10 15:39:39 -07005940 const AudioDeviceTypeAddrVector &devices) const
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005941{
5942 // The caller can have the audio attributes criteria ignored by either passing a null ptr or
5943 // the AUDIO_ATTRIBUTES_INITIALIZER value.
Eric Laurentfa0f6742021-08-17 18:39:44 +02005944 // If attributes are specified, current policy is to only allow spatialization for media
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005945 // and game usages.
Eric Laurent39095982021-08-24 18:29:27 +02005946 if (attr != nullptr && *attr != AUDIO_ATTRIBUTES_INITIALIZER) {
5947 if (attr->usage != AUDIO_USAGE_MEDIA && attr->usage != AUDIO_USAGE_GAME) {
5948 return false;
5949 }
5950 if ((attr->flags & (AUDIO_FLAG_CONTENT_SPATIALIZED | AUDIO_FLAG_NEVER_SPATIALIZE)) != 0) {
5951 return false;
5952 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005953 }
5954
Eric Laurentd332bc82023-08-04 11:45:23 +02005955 // The caller can have the audio config criteria ignored by either passing a null ptr or
5956 // the AUDIO_CONFIG_INITIALIZER value.
5957 // If an audio config is specified, current policy is to only allow spatialization for
5958 // some positional channel masks and PCM format
5959
5960 if (config != nullptr && *config != AUDIO_CONFIG_INITIALIZER) {
5961 if (!audio_is_channel_mask_spatialized(config->channel_mask)) {
5962 return false;
5963 }
5964 if (!audio_is_linear_pcm(config->format)) {
5965 return false;
5966 }
5967 }
5968
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005969 sp<IOProfile> profile =
Eric Laurent39095982021-08-24 18:29:27 +02005970 getSpatializerOutputProfile(config, devices);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005971 if (profile == nullptr) {
5972 return false;
5973 }
5974
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005975 return true;
5976}
5977
5978void AudioPolicyManager::checkVirtualizerClientRoutes() {
5979 std::set<audio_stream_type_t> streamsToInvalidate;
5980 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent39095982021-08-24 18:29:27 +02005981 const sp<SwAudioOutputDescriptor>& desc = mOutputs[i];
5982 for (const sp<TrackClientDescriptor>& client : desc->getClientIterable()) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005983 audio_attributes_t attr = client->attributes();
5984 DeviceVector devices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false);
5985 AudioDeviceTypeAddrVector devicesTypeAddress = devices.toTypeAddrVector();
5986 audio_config_base_t clientConfig = client->config();
5987 audio_config_t config = audio_config_initializer(&clientConfig);
Eric Laurent39095982021-08-24 18:29:27 +02005988 if (desc != mSpatializerOutput
Andy Hung9dd1a5b2022-05-10 15:39:39 -07005989 && canBeSpatializedInt(&attr, &config, devicesTypeAddress)) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005990 streamsToInvalidate.insert(client->stream());
5991 }
5992 }
5993 }
5994
jiabinc44b3462022-12-08 12:52:31 -08005995 invalidateStreams(StreamTypeVector(streamsToInvalidate.begin(), streamsToInvalidate.end()));
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005996}
5997
Eric Laurente191d1b2022-04-15 11:59:25 +02005998
5999bool AudioPolicyManager::isOutputOnlyAvailableRouteToSomeDevice(
6000 const sp<SwAudioOutputDescriptor>& outputDesc) {
6001 if (outputDesc->isDuplicated()) {
6002 return false;
6003 }
6004 DeviceVector devices = outputDesc->supportedDevices();
6005 for (size_t i = 0; i < mOutputs.size(); i++) {
6006 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
6007 if (desc == outputDesc || desc->isDuplicated()) {
6008 continue;
6009 }
6010 DeviceVector sharedDevices = desc->filterSupportedDevices(devices);
6011 if (!sharedDevices.isEmpty()
6012 && (desc->devicesSupportEncodedFormats(sharedDevices.types())
6013 == outputDesc->devicesSupportEncodedFormats(sharedDevices.types()))) {
6014 return false;
6015 }
6016 }
6017 return true;
6018}
6019
6020
Eric Laurentfa0f6742021-08-17 18:39:44 +02006021status_t AudioPolicyManager::getSpatializerOutput(const audio_config_base_t *mixerConfig,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006022 const audio_attributes_t *attr,
6023 audio_io_handle_t *output) {
6024 *output = AUDIO_IO_HANDLE_NONE;
6025
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006026 DeviceVector devices = mEngine->getOutputDevicesForAttributes(*attr, nullptr, false);
6027 AudioDeviceTypeAddrVector devicesTypeAddress = devices.toTypeAddrVector();
6028 audio_config_t *configPtr = nullptr;
6029 audio_config_t config;
6030 if (mixerConfig != nullptr) {
6031 config = audio_config_initializer(mixerConfig);
6032 configPtr = &config;
6033 }
Andy Hung9dd1a5b2022-05-10 15:39:39 -07006034 if (!canBeSpatializedInt(attr, configPtr, devicesTypeAddress)) {
Eric Laurente191d1b2022-04-15 11:59:25 +02006035 ALOGV("%s provided attributes or mixer config cannot be spatialized", __func__);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006036 return BAD_VALUE;
6037 }
6038
6039 sp<IOProfile> profile =
Eric Laurent39095982021-08-24 18:29:27 +02006040 getSpatializerOutputProfile(configPtr, devicesTypeAddress);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006041 if (profile == nullptr) {
Eric Laurente191d1b2022-04-15 11:59:25 +02006042 ALOGV("%s no suitable output profile for provided attributes or mixer config", __func__);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006043 return BAD_VALUE;
6044 }
6045
Eric Laurente191d1b2022-04-15 11:59:25 +02006046 std::vector<sp<SwAudioOutputDescriptor>> spatializerOutputs;
Eric Laurent39095982021-08-24 18:29:27 +02006047 for (size_t i = 0; i < mOutputs.size(); i++) {
6048 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente191d1b2022-04-15 11:59:25 +02006049 if (!desc->isDuplicated()
6050 && (desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0) {
6051 spatializerOutputs.push_back(desc);
6052 ALOGV("%s adding opened spatializer Output %d", __func__, desc->mIoHandle);
Eric Laurent39095982021-08-24 18:29:27 +02006053 }
6054 }
Eric Laurente191d1b2022-04-15 11:59:25 +02006055 mSpatializerOutput.clear();
6056 bool outputsChanged = false;
6057 for (const auto& desc : spatializerOutputs) {
6058 if (desc->mProfile == profile
6059 && (configPtr == nullptr
6060 || configPtr->channel_mask == desc->mMixerChannelMask)) {
6061 mSpatializerOutput = desc;
6062 ALOGV("%s reusing current spatializer output %d", __func__, desc->mIoHandle);
6063 } else {
6064 ALOGV("%s closing spatializerOutput output %d to match channel mask %#x"
6065 " and devices %s", __func__, desc->mIoHandle,
6066 configPtr != nullptr ? configPtr->channel_mask : 0,
6067 devices.toString().c_str());
6068 closeOutput(desc->mIoHandle);
6069 outputsChanged = true;
6070 }
Eric Laurent39095982021-08-24 18:29:27 +02006071 }
6072
Eric Laurente191d1b2022-04-15 11:59:25 +02006073 if (mSpatializerOutput == nullptr) {
Eric Laurentb4f42a92022-01-17 17:37:31 +01006074 sp<SwAudioOutputDescriptor> desc =
6075 openOutputWithProfileAndDevice(profile, devices, mixerConfig);
Eric Laurente191d1b2022-04-15 11:59:25 +02006076 if (desc != nullptr) {
6077 mSpatializerOutput = desc;
6078 outputsChanged = true;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006079 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006080 }
6081
6082 checkVirtualizerClientRoutes();
6083
Eric Laurente191d1b2022-04-15 11:59:25 +02006084 if (outputsChanged) {
6085 mPreviousOutputs = mOutputs;
6086 mpClientInterface->onAudioPortListUpdate();
6087 }
6088
6089 if (mSpatializerOutput == nullptr) {
6090 ALOGV("%s could not open spatializer output with requested config", __func__);
6091 return BAD_VALUE;
6092 }
Eric Laurent39095982021-08-24 18:29:27 +02006093 *output = mSpatializerOutput->mIoHandle;
Eric Laurente191d1b2022-04-15 11:59:25 +02006094 ALOGV("%s returning new spatializer output %d", __func__, *output);
6095 return OK;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006096}
6097
Eric Laurentfa0f6742021-08-17 18:39:44 +02006098status_t AudioPolicyManager::releaseSpatializerOutput(audio_io_handle_t output) {
6099 if (mSpatializerOutput == nullptr) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006100 return INVALID_OPERATION;
6101 }
Eric Laurentfa0f6742021-08-17 18:39:44 +02006102 if (mSpatializerOutput->mIoHandle != output) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006103 return BAD_VALUE;
6104 }
Eric Laurent39095982021-08-24 18:29:27 +02006105
Eric Laurente191d1b2022-04-15 11:59:25 +02006106 if (!isOutputOnlyAvailableRouteToSomeDevice(mSpatializerOutput)) {
6107 ALOGV("%s closing spatializer output %d", __func__, mSpatializerOutput->mIoHandle);
6108 closeOutput(mSpatializerOutput->mIoHandle);
6109 //from now on mSpatializerOutput is null
6110 checkVirtualizerClientRoutes();
6111 }
Eric Laurent39095982021-08-24 18:29:27 +02006112
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006113 return NO_ERROR;
6114}
6115
Eric Laurente552edb2014-03-10 17:42:56 -07006116// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07006117// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07006118// ----------------------------------------------------------------------------
Eric Laurent6a94d692014-05-20 11:18:06 -07006119uint32_t AudioPolicyManager::nextAudioPortGeneration()
6120{
Mikhail Naganov2773dd72017-12-08 10:12:11 -08006121 return mAudioPortGeneration++;
Eric Laurent6a94d692014-05-20 11:18:06 -07006122}
6123
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006124AudioPolicyManager::AudioPolicyManager(const sp<const AudioPolicyConfig>& config,
Mikhail Naganovf1b6d972023-05-02 13:56:01 -07006125 EngineInstance&& engine,
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006126 AudioPolicyClientInterface *clientInterface)
Eric Laurente552edb2014-03-10 17:42:56 -07006127 :
Andy Hung4ef19fa2018-05-15 19:35:29 -07006128 mUidCached(AID_AUDIOSERVER), // no need to call getuid(), there's only one of us running.
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006129 mConfig(config),
Mikhail Naganovf1b6d972023-05-02 13:56:01 -07006130 mEngine(std::move(engine)),
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006131 mpClientInterface(clientInterface),
Eric Laurente552edb2014-03-10 17:42:56 -07006132 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
Eric Laurent3a4311c2014-03-17 12:00:47 -07006133 mA2dpSuspended(false),
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006134 mAudioPortGeneration(1),
6135 mBeaconMuteRefCount(0),
6136 mBeaconPlayingRefCount(0),
Eric Laurent9459fb02015-08-12 18:36:32 -07006137 mBeaconMuted(false),
Andy Hung2ddee192015-12-18 17:34:44 -08006138 mTtsOutputAvailable(false),
Eric Laurent36829f92017-04-07 19:04:42 -07006139 mMasterMono(false),
Eric Laurent4eb58f12018-12-07 16:41:02 -08006140 mMusicEffectOutput(AUDIO_IO_HANDLE_NONE)
Eric Laurente552edb2014-03-10 17:42:56 -07006141{
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006142}
François Gaffied1ab2bd2015-12-02 18:20:06 +01006143
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006144status_t AudioPolicyManager::initialize() {
Mikhail Naganovf1b6d972023-05-02 13:56:01 -07006145 if (mEngine == nullptr) {
6146 return NO_INIT;
François Gaffie2110e042015-03-24 08:41:51 +01006147 }
6148 mEngine->setObserver(this);
6149 status_t status = mEngine->initCheck();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006150 if (status != NO_ERROR) {
6151 LOG_FATAL("Policy engine not initialized(err=%d)", status);
6152 return status;
6153 }
François Gaffie2110e042015-03-24 08:41:51 +01006154
jiabin29230182023-04-04 21:02:36 +00006155 // The actual device selection cache will be updated when calling `updateDevicesAndOutputs`
6156 // at the end of this function.
6157 mEngine->initializeDeviceSelectionCache();
Eric Laurent1d69c872021-01-11 18:53:01 +01006158 mCommunnicationStrategy = mEngine->getProductStrategyForAttributes(
6159 mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL));
6160
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006161 // after parsing the config, mConfig contain all known devices;
Eric Laurente552edb2014-03-10 17:42:56 -07006162 // open all output streams needed to access attached devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006163 onNewAudioModulesAvailableInt(nullptr /*newDevices*/);
François Gaffie11d30102018-11-02 16:09:09 +01006164
Eric Laurent3a4311c2014-03-17 12:00:47 -07006165 // make sure default device is reachable
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006166 if (const auto defaultOutputDevice = mConfig->getDefaultOutputDevice();
6167 defaultOutputDevice == nullptr ||
6168 !mAvailableOutputDevices.contains(defaultOutputDevice)) {
6169 ALOGE_IF(defaultOutputDevice != nullptr, "Default device %s is unreachable",
6170 defaultOutputDevice->toString().c_str());
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006171 status = NO_INIT;
Eric Laurent3a4311c2014-03-17 12:00:47 -07006172 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02006173 ALOGW_IF(mPrimaryOutput == nullptr, "The policy configuration does not declare a primary output");
Eric Laurente552edb2014-03-10 17:42:56 -07006174
Tomoharu Kasahara71c90912018-10-31 09:10:12 +09006175 // Silence ALOGV statements
6176 property_set("log.tag." LOG_TAG, "D");
6177
Eric Laurente552edb2014-03-10 17:42:56 -07006178 updateDevicesAndOutputs();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006179 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07006180}
6181
Eric Laurente0720872014-03-11 09:30:41 -07006182AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07006183{
Eric Laurente552edb2014-03-10 17:42:56 -07006184 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08006185 mOutputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07006186 }
6187 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08006188 mInputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07006189 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07006190 mAvailableOutputDevices.clear();
6191 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07006192 mOutputs.clear();
6193 mInputs.clear();
6194 mHwModules.clear();
Mikhail Naganov100f0122018-11-29 11:22:16 -08006195 mManualSurroundFormats.clear();
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006196 mConfig.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07006197}
6198
Eric Laurente0720872014-03-11 09:30:41 -07006199status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07006200{
Eric Laurent87ffa392015-05-22 10:32:38 -07006201 return hasPrimaryOutput() ? NO_ERROR : NO_INIT;
Eric Laurente552edb2014-03-10 17:42:56 -07006202}
6203
Eric Laurente552edb2014-03-10 17:42:56 -07006204// ---
6205
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006206void AudioPolicyManager::onNewAudioModulesAvailable()
6207{
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006208 DeviceVector newDevices;
6209 onNewAudioModulesAvailableInt(&newDevices);
6210 if (!newDevices.empty()) {
6211 nextAudioPortGeneration();
6212 mpClientInterface->onAudioPortListUpdate();
6213 }
6214}
6215
6216void AudioPolicyManager::onNewAudioModulesAvailableInt(DeviceVector *newDevices)
6217{
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006218 for (const auto& hwModule : mConfig->getHwModules()) {
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006219 if (std::find(mHwModules.begin(), mHwModules.end(), hwModule) != mHwModules.end()) {
6220 continue;
6221 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006222 if (hwModule->getHandle() == AUDIO_MODULE_HANDLE_NONE) {
Mikhail Naganovffd97712023-05-03 17:45:36 -07006223 if (audio_module_handle_t handle = mpClientInterface->loadHwModule(hwModule->getName());
6224 handle != AUDIO_MODULE_HANDLE_NONE) {
6225 hwModule->setHandle(handle);
6226 } else {
6227 ALOGW("could not load HW module %s", hwModule->getName());
6228 continue;
6229 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006230 }
6231 mHwModules.push_back(hwModule);
Dean Wheatley12a87132021-04-16 10:08:49 +10006232 // open all output streams needed to access attached devices.
6233 // direct outputs are closed immediately after checking the availability of attached devices
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006234 // This also validates mAvailableOutputDevices list
6235 for (const auto& outProfile : hwModule->getOutputProfiles()) {
6236 if (!outProfile->canOpenNewIo()) {
6237 ALOGE("Invalid Output profile max open count %u for profile %s",
6238 outProfile->maxOpenCount, outProfile->getTagName().c_str());
6239 continue;
6240 }
6241 if (!outProfile->hasSupportedDevices()) {
6242 ALOGW("Output profile contains no device on module %s", hwModule->getName());
6243 continue;
6244 }
Carter Hsu1a3364a2022-01-21 15:32:56 +08006245 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_TTS) != 0 ||
6246 (outProfile->getFlags() & AUDIO_OUTPUT_FLAG_ULTRASOUND) != 0) {
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006247 mTtsOutputAvailable = true;
6248 }
6249
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006250 const DeviceVector &supportedDevices = outProfile->getSupportedDevices();
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006251 DeviceVector availProfileDevices = supportedDevices.filter(mConfig->getOutputDevices());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006252 sp<DeviceDescriptor> supportedDevice = 0;
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006253 if (supportedDevices.contains(mConfig->getDefaultOutputDevice())) {
6254 supportedDevice = mConfig->getDefaultOutputDevice();
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006255 } else {
6256 // choose first device present in profile's SupportedDevices also part of
6257 // mAvailableOutputDevices.
6258 if (availProfileDevices.isEmpty()) {
6259 continue;
6260 }
6261 supportedDevice = availProfileDevices.itemAt(0);
6262 }
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006263 if (!mConfig->getOutputDevices().contains(supportedDevice)) {
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006264 continue;
6265 }
6266 sp<SwAudioOutputDescriptor> outputDesc = new SwAudioOutputDescriptor(outProfile,
6267 mpClientInterface);
6268 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentf1f22e72021-07-13 14:04:14 +02006269 status_t status = outputDesc->open(nullptr /* halConfig */, nullptr /* mixerConfig */,
6270 DeviceVector(supportedDevice),
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006271 AUDIO_STREAM_DEFAULT,
6272 AUDIO_OUTPUT_FLAG_NONE, &output);
6273 if (status != NO_ERROR) {
6274 ALOGW("Cannot open output stream for devices %s on hw module %s",
6275 supportedDevice->toString().c_str(), hwModule->getName());
6276 continue;
6277 }
6278 for (const auto &device : availProfileDevices) {
6279 // give a valid ID to an attached device once confirmed it is reachable
6280 if (!device->isAttached()) {
6281 device->attach(hwModule);
6282 mAvailableOutputDevices.add(device);
jiabin1c4794b2020-05-05 10:08:05 -07006283 device->setEncapsulationInfoFromHal(mpClientInterface);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006284 if (newDevices) newDevices->add(device);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006285 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
6286 }
6287 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02006288 if (mPrimaryOutput == nullptr &&
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006289 outProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
6290 mPrimaryOutput = outputDesc;
François Gaffiedb1755b2023-09-01 11:50:35 +02006291 mPrimaryModuleHandle = mPrimaryOutput->getModuleHandle();
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006292 }
Eric Laurent39095982021-08-24 18:29:27 +02006293 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
Eric Laurentc529cf62020-04-17 18:19:10 -07006294 outputDesc->close();
6295 } else {
6296 addOutput(output, outputDesc);
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05306297 setOutputDevices(__func__, outputDesc,
Eric Laurentc529cf62020-04-17 18:19:10 -07006298 DeviceVector(supportedDevice),
6299 true,
6300 0,
6301 NULL);
6302 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006303 }
6304 // open input streams needed to access attached devices to validate
6305 // mAvailableInputDevices list
6306 for (const auto& inProfile : hwModule->getInputProfiles()) {
6307 if (!inProfile->canOpenNewIo()) {
6308 ALOGE("Invalid Input profile max open count %u for profile %s",
6309 inProfile->maxOpenCount, inProfile->getTagName().c_str());
6310 continue;
6311 }
6312 if (!inProfile->hasSupportedDevices()) {
6313 ALOGW("Input profile contains no device on module %s", hwModule->getName());
6314 continue;
6315 }
6316 // chose first device present in profile's SupportedDevices also part of
6317 // available input devices
6318 const DeviceVector &supportedDevices = inProfile->getSupportedDevices();
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006319 DeviceVector availProfileDevices = supportedDevices.filter(mConfig->getInputDevices());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006320 if (availProfileDevices.isEmpty()) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01006321 ALOGV("%s: Input device list is empty! for profile %s",
6322 __func__, inProfile->getTagName().c_str());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006323 continue;
6324 }
6325 sp<AudioInputDescriptor> inputDesc =
6326 new AudioInputDescriptor(inProfile, mpClientInterface);
6327
6328 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
6329 status_t status = inputDesc->open(nullptr,
6330 availProfileDevices.itemAt(0),
6331 AUDIO_SOURCE_MIC,
6332 AUDIO_INPUT_FLAG_NONE,
6333 &input);
6334 if (status != NO_ERROR) {
6335 ALOGW("Cannot open input stream for device %s on hw module %s",
6336 availProfileDevices.toString().c_str(),
6337 hwModule->getName());
6338 continue;
6339 }
6340 for (const auto &device : availProfileDevices) {
6341 // give a valid ID to an attached device once confirmed it is reachable
6342 if (!device->isAttached()) {
6343 device->attach(hwModule);
6344 device->importAudioPortAndPickAudioProfile(inProfile, true);
6345 mAvailableInputDevices.add(device);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006346 if (newDevices) newDevices->add(device);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006347 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
6348 }
6349 }
6350 inputDesc->close();
6351 }
6352 }
Eric Laurente191d1b2022-04-15 11:59:25 +02006353
6354 // Check if spatializer outputs can be closed until used.
6355 // mOutputs vector never contains duplicated outputs at this point.
6356 std::vector<audio_io_handle_t> outputsClosed;
6357 for (size_t i = 0; i < mOutputs.size(); i++) {
6358 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
6359 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0
6360 && !isOutputOnlyAvailableRouteToSomeDevice(desc)) {
6361 outputsClosed.push_back(desc->mIoHandle);
6362 desc->close();
6363 }
6364 }
6365 for (auto output : outputsClosed) {
6366 removeOutput(output);
6367 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006368}
6369
Eric Laurent98e38192018-02-15 18:31:53 -08006370void AudioPolicyManager::addOutput(audio_io_handle_t output,
6371 const sp<SwAudioOutputDescriptor>& outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07006372{
Eric Laurent1c333e22014-05-20 10:48:17 -07006373 mOutputs.add(output, outputDesc);
jiabin9a3361e2019-10-01 09:38:30 -07006374 applyStreamVolumes(outputDesc, DeviceTypeSet(), 0 /* delayMs */, true /* force */);
Andy Hung2ddee192015-12-18 17:34:44 -08006375 updateMono(output); // update mono status when adding to output list
Eric Laurent36829f92017-04-07 19:04:42 -07006376 selectOutputForMusicEffects();
Eric Laurent6a94d692014-05-20 11:18:06 -07006377 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07006378}
6379
François Gaffie53615e22015-03-19 09:24:12 +01006380void AudioPolicyManager::removeOutput(audio_io_handle_t output)
6381{
Francois Gaffiebce7cd42020-10-14 16:13:20 +02006382 if (mPrimaryOutput != 0 && mPrimaryOutput == mOutputs.valueFor(output)) {
6383 ALOGV("%s: removing primary output", __func__);
6384 mPrimaryOutput = nullptr;
6385 }
François Gaffie53615e22015-03-19 09:24:12 +01006386 mOutputs.removeItem(output);
Eric Laurent36829f92017-04-07 19:04:42 -07006387 selectOutputForMusicEffects();
François Gaffie53615e22015-03-19 09:24:12 +01006388}
6389
Eric Laurent98e38192018-02-15 18:31:53 -08006390void AudioPolicyManager::addInput(audio_io_handle_t input,
6391 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07006392{
Eric Laurent1c333e22014-05-20 10:48:17 -07006393 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07006394 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07006395}
Eric Laurente552edb2014-03-10 17:42:56 -07006396
François Gaffie11d30102018-11-02 16:09:09 +01006397status_t AudioPolicyManager::checkOutputsForDevice(const sp<DeviceDescriptor>& device,
François Gaffie53615e22015-03-19 09:24:12 +01006398 audio_policy_dev_state_t state,
François Gaffie11d30102018-11-02 16:09:09 +01006399 SortedVector<audio_io_handle_t>& outputs)
Eric Laurente552edb2014-03-10 17:42:56 -07006400{
François Gaffie11d30102018-11-02 16:09:09 +01006401 audio_devices_t deviceType = device->type();
jiabince9f20e2019-09-12 16:29:15 -07006402 const String8 &address = String8(device->address().c_str());
Eric Laurentc75307b2015-03-17 15:29:32 -07006403 sp<SwAudioOutputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07006404
François Gaffie11d30102018-11-02 16:09:09 +01006405 if (audio_device_is_digital(deviceType)) {
Eric Laurentcc750d32015-06-25 11:48:20 -07006406 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01006407 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07006408 }
Eric Laurente552edb2014-03-10 17:42:56 -07006409
Eric Laurent3b73df72014-03-11 09:06:29 -07006410 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
jiabinb4fed192020-09-22 14:45:40 -07006411 // first call getAudioPort to get the supported attributes from the HAL
6412 struct audio_port_v7 port = {};
6413 device->toAudioPort(&port);
6414 status_t status = mpClientInterface->getAudioPort(&port);
6415 if (status == NO_ERROR) {
6416 device->importAudioPort(port);
6417 }
6418
6419 // then list already open outputs that can be routed to this device
Eric Laurente552edb2014-03-10 17:42:56 -07006420 for (size_t i = 0; i < mOutputs.size(); i++) {
6421 desc = mOutputs.valueAt(i);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006422 if (!desc->isDuplicated() && desc->supportsDevice(device)
jiabin9a3361e2019-10-01 09:38:30 -07006423 && desc->devicesSupportEncodedFormats({deviceType})) {
François Gaffie11d30102018-11-02 16:09:09 +01006424 ALOGV("checkOutputsForDevice(): adding opened output %d on device %s",
6425 mOutputs.keyAt(i), device->toString().c_str());
6426 outputs.add(mOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07006427 }
6428 }
6429 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07006430 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006431 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006432 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
6433 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
François Gaffie11d30102018-11-02 16:09:09 +01006434 if (profile->supportsDevice(device)) {
6435 profiles.add(profile);
6436 ALOGV("checkOutputsForDevice(): adding profile %zu from module %s",
6437 j, hwModule->getName());
Eric Laurente552edb2014-03-10 17:42:56 -07006438 }
6439 }
6440 }
6441
Eric Laurent7b279bb2015-12-14 10:18:23 -08006442 ALOGV(" found %zu profiles, %zu outputs", profiles.size(), outputs.size());
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006443
Eric Laurente552edb2014-03-10 17:42:56 -07006444 if (profiles.isEmpty() && outputs.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006445 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07006446 return BAD_VALUE;
6447 }
6448
6449 // open outputs for matching profiles if needed. Direct outputs are also opened to
6450 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
6451 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07006452 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07006453
6454 // nothing to do if one output is already opened for this profile
6455 size_t j;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006456 for (j = 0; j < outputs.size(); j++) {
6457 desc = mOutputs.valueFor(outputs.itemAt(j));
Eric Laurente552edb2014-03-10 17:42:56 -07006458 if (!desc->isDuplicated() && desc->mProfile == profile) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07006459 // matching profile: save the sample rates, format and channel masks supported
6460 // by the profile in our device descriptor
François Gaffie11d30102018-11-02 16:09:09 +01006461 if (audio_device_is_digital(deviceType)) {
jiabin4ef93452019-09-10 14:29:54 -07006462 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006463 }
Eric Laurente552edb2014-03-10 17:42:56 -07006464 break;
6465 }
6466 }
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006467 if (j != outputs.size()) {
Eric Laurente552edb2014-03-10 17:42:56 -07006468 continue;
6469 }
6470
Eric Laurent3974e3b2017-12-07 17:58:43 -08006471 if (!profile->canOpenNewIo()) {
6472 ALOGW("Max Output number %u already opened for this profile %s",
6473 profile->maxOpenCount, profile->getTagName().c_str());
6474 continue;
6475 }
6476
Eric Laurent83efe1c2017-07-09 16:51:08 -07006477 ALOGV("opening output for device %08x with params %s profile %p name %s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00006478 deviceType, address.c_str(), profile.get(), profile->getName().c_str());
jiabinbce0c1d2020-10-05 11:20:18 -07006479 desc = openOutputWithProfileAndDevice(profile, DeviceVector(device));
6480 audio_io_handle_t output = desc == nullptr ? AUDIO_IO_HANDLE_NONE : desc->mIoHandle;
Eric Laurentcf2c0212014-07-25 16:20:43 -07006481 if (output == AUDIO_IO_HANDLE_NONE) {
François Gaffie11d30102018-11-02 16:09:09 +01006482 ALOGW("checkOutputsForDevice() could not open output for device %x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07006483 profiles.removeAt(profile_index);
6484 profile_index--;
6485 } else {
6486 outputs.add(output);
Paul McLean9080a4c2015-06-18 08:24:02 -07006487 // Load digital format info only for digital devices
François Gaffie11d30102018-11-02 16:09:09 +01006488 if (audio_device_is_digital(deviceType)) {
jiabinbce0c1d2020-10-05 11:20:18 -07006489 // TODO: when getAudioPort is ready, it may not be needed to import the audio
6490 // port but just pick audio profile
jiabin4ef93452019-09-10 14:29:54 -07006491 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006492 }
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07006493
François Gaffie11d30102018-11-02 16:09:09 +01006494 if (device_distinguishes_on_address(deviceType)) {
6495 ALOGV("checkOutputsForDevice(): setOutputDevices %s",
6496 device->toString().c_str());
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05306497 setOutputDevices(__func__, desc, DeviceVector(device), true/*force*/,
6498 0/*delay*/, NULL/*patch handle*/);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006499 }
Eric Laurente552edb2014-03-10 17:42:56 -07006500 ALOGV("checkOutputsForDevice(): adding output %d", output);
6501 }
6502 }
6503
6504 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006505 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07006506 return BAD_VALUE;
6507 }
Eric Laurentd4692962014-05-05 18:13:44 -07006508 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07006509 // check if one opened output is not needed any more after disconnecting one device
6510 for (size_t i = 0; i < mOutputs.size(); i++) {
6511 desc = mOutputs.valueAt(i);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006512 if (!desc->isDuplicated()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08006513 // exact match on device
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006514 if (device_distinguishes_on_address(deviceType) && desc->supportsDevice(device)
Francois Gaffiec7d4c222021-12-02 11:12:52 +01006515 && desc->containsSingleDeviceSupportingEncodedFormats(device)) {
François Gaffie11d30102018-11-02 16:09:09 +01006516 outputs.add(mOutputs.keyAt(i));
Francois Gaffie716e1432019-01-14 16:58:59 +01006517 } else if (!mAvailableOutputDevices.containsAtLeastOne(desc->supportedDevices())) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006518 ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
6519 mOutputs.keyAt(i));
6520 outputs.add(mOutputs.keyAt(i));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006521 }
Eric Laurente552edb2014-03-10 17:42:56 -07006522 }
6523 }
Eric Laurentd4692962014-05-05 18:13:44 -07006524 // Clear any profiles associated with the disconnected device.
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006525 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006526 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
6527 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
jiabinbce0c1d2020-10-05 11:20:18 -07006528 if (!profile->supportsDevice(device)) {
6529 continue;
6530 }
6531 ALOGV("checkOutputsForDevice(): "
6532 "clearing direct output profile %zu on module %s",
6533 j, hwModule->getName());
6534 profile->clearAudioProfiles();
6535 if (!profile->hasDynamicAudioProfile()) {
6536 continue;
6537 }
6538 // When a device is disconnected, if there is an IOProfile that contains dynamic
6539 // profiles and supports the disconnected device, call getAudioPort to repopulate
6540 // the capabilities of the devices that is supported by the IOProfile.
6541 for (const auto& supportedDevice : profile->getSupportedDevices()) {
6542 if (supportedDevice == device ||
6543 !mAvailableOutputDevices.contains(supportedDevice)) {
6544 continue;
6545 }
6546 struct audio_port_v7 port;
6547 supportedDevice->toAudioPort(&port);
6548 status_t status = mpClientInterface->getAudioPort(&port);
6549 if (status == NO_ERROR) {
6550 supportedDevice->importAudioPort(port);
6551 }
Eric Laurente552edb2014-03-10 17:42:56 -07006552 }
6553 }
6554 }
6555 }
6556 return NO_ERROR;
6557}
6558
François Gaffie11d30102018-11-02 16:09:09 +01006559status_t AudioPolicyManager::checkInputsForDevice(const sp<DeviceDescriptor>& device,
Eric Laurent0dd51852019-04-19 18:18:58 -07006560 audio_policy_dev_state_t state)
Eric Laurentd4692962014-05-05 18:13:44 -07006561{
Eric Laurent1f2f2232014-06-02 12:01:23 -07006562 sp<AudioInputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07006563
François Gaffie11d30102018-11-02 16:09:09 +01006564 if (audio_device_is_digital(device->type())) {
Eric Laurentcc750d32015-06-25 11:48:20 -07006565 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01006566 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07006567 }
6568
Eric Laurentd4692962014-05-05 18:13:44 -07006569 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
jiabinbf5f4262023-04-12 21:48:34 +00006570 // first call getAudioPort to get the supported attributes from the HAL
6571 struct audio_port_v7 port = {};
6572 device->toAudioPort(&port);
6573 status_t status = mpClientInterface->getAudioPort(&port);
6574 if (status == NO_ERROR) {
6575 device->importAudioPort(port);
6576 }
6577
Eric Laurent0dd51852019-04-19 18:18:58 -07006578 // look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07006579 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006580 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07006581 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006582 profile_index < hwModule->getInputProfiles().size();
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006583 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006584 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Eric Laurent275e8e92014-11-30 15:14:47 -08006585
François Gaffie11d30102018-11-02 16:09:09 +01006586 if (profile->supportsDevice(device)) {
6587 profiles.add(profile);
6588 ALOGV("checkInputsForDevice(): adding profile %zu from module %s",
6589 profile_index, hwModule->getName());
Eric Laurentd4692962014-05-05 18:13:44 -07006590 }
6591 }
6592 }
6593
Eric Laurent0dd51852019-04-19 18:18:58 -07006594 if (profiles.isEmpty()) {
6595 ALOGW("%s: No input profile available for device %s",
6596 __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07006597 return BAD_VALUE;
6598 }
6599
6600 // open inputs for matching profiles if needed. Direct inputs are also opened to
6601 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
6602 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
6603
Eric Laurent1c333e22014-05-20 10:48:17 -07006604 sp<IOProfile> profile = profiles[profile_index];
Eric Laurent3974e3b2017-12-07 17:58:43 -08006605
Eric Laurentd4692962014-05-05 18:13:44 -07006606 // nothing to do if one input is already opened for this profile
6607 size_t input_index;
6608 for (input_index = 0; input_index < mInputs.size(); input_index++) {
6609 desc = mInputs.valueAt(input_index);
6610 if (desc->mProfile == profile) {
François Gaffie11d30102018-11-02 16:09:09 +01006611 if (audio_device_is_digital(device->type())) {
jiabin4ef93452019-09-10 14:29:54 -07006612 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006613 }
Eric Laurentd4692962014-05-05 18:13:44 -07006614 break;
6615 }
6616 }
6617 if (input_index != mInputs.size()) {
6618 continue;
6619 }
6620
Eric Laurent3974e3b2017-12-07 17:58:43 -08006621 if (!profile->canOpenNewIo()) {
6622 ALOGW("Max Input number %u already opened for this profile %s",
6623 profile->maxOpenCount, profile->getTagName().c_str());
6624 continue;
6625 }
6626
Eric Laurentfe231122017-11-17 17:48:06 -08006627 desc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentcf2c0212014-07-25 16:20:43 -07006628 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
jiabinbf5f4262023-04-12 21:48:34 +00006629 status = desc->open(nullptr, device, AUDIO_SOURCE_MIC, AUDIO_INPUT_FLAG_NONE, &input);
Eric Laurentd4692962014-05-05 18:13:44 -07006630
Eric Laurentcf2c0212014-07-25 16:20:43 -07006631 if (status == NO_ERROR) {
jiabince9f20e2019-09-12 16:29:15 -07006632 const String8& address = String8(device->address().c_str());
Tomasz Wasilczykfd9ffd12023-08-14 17:56:22 +00006633 if (!address.empty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006634 char *param = audio_device_address_to_parameter(device->type(), address);
Eric Laurentcf2c0212014-07-25 16:20:43 -07006635 mpClientInterface->setParameters(input, String8(param));
6636 free(param);
Eric Laurentd4692962014-05-05 18:13:44 -07006637 }
François Gaffie11d30102018-11-02 16:09:09 +01006638 updateAudioProfiles(device, input, profile->getAudioProfiles());
François Gaffie112b0af2015-11-19 16:13:25 +01006639 if (!profile->hasValidAudioProfile()) {
Eric Laurentd4692962014-05-05 18:13:44 -07006640 ALOGW("checkInputsForDevice() direct input missing param");
Eric Laurentfe231122017-11-17 17:48:06 -08006641 desc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07006642 input = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07006643 }
6644
Eric Laurent0dd51852019-04-19 18:18:58 -07006645 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07006646 addInput(input, desc);
6647 }
6648 } // endif input != 0
6649
Eric Laurentcf2c0212014-07-25 16:20:43 -07006650 if (input == AUDIO_IO_HANDLE_NONE) {
Pattydd807582021-11-04 21:01:03 +08006651 ALOGW("%s could not open input for device %s", __func__,
François Gaffie11d30102018-11-02 16:09:09 +01006652 device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07006653 profiles.removeAt(profile_index);
6654 profile_index--;
6655 } else {
François Gaffie11d30102018-11-02 16:09:09 +01006656 if (audio_device_is_digital(device->type())) {
jiabin4ef93452019-09-10 14:29:54 -07006657 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006658 }
Eric Laurentd4692962014-05-05 18:13:44 -07006659 ALOGV("checkInputsForDevice(): adding input %d", input);
6660 }
6661 } // end scan profiles
6662
6663 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006664 ALOGW("%s: No input available for device %s", __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07006665 return BAD_VALUE;
6666 }
6667 } else {
6668 // Disconnect
Eric Laurentd4692962014-05-05 18:13:44 -07006669 // Clear any profiles associated with the disconnected device.
Mikhail Naganovd4120142017-12-06 15:49:22 -08006670 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07006671 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006672 profile_index < hwModule->getInputProfiles().size();
Eric Laurentd4692962014-05-05 18:13:44 -07006673 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006674 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Francois Gaffie716e1432019-01-14 16:58:59 +01006675 if (profile->supportsDevice(device)) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08006676 ALOGV("checkInputsForDevice(): clearing direct input profile %zu on module %s",
6677 profile_index, hwModule->getName());
François Gaffie112b0af2015-11-19 16:13:25 +01006678 profile->clearAudioProfiles();
Eric Laurentd4692962014-05-05 18:13:44 -07006679 }
6680 }
6681 }
6682 } // end disconnect
6683
6684 return NO_ERROR;
6685}
6686
6687
Eric Laurente0720872014-03-11 09:30:41 -07006688void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07006689{
6690 ALOGV("closeOutput(%d)", output);
6691
François Gaffie1c878552018-11-22 16:53:21 +01006692 sp<SwAudioOutputDescriptor> closingOutput = mOutputs.valueFor(output);
6693 if (closingOutput == NULL) {
Eric Laurente552edb2014-03-10 17:42:56 -07006694 ALOGW("closeOutput() unknown output %d", output);
6695 return;
6696 }
Mikhail Naganov32ebca32019-03-22 15:42:52 -07006697 const bool closingOutputWasActive = closingOutput->isActive();
François Gaffie1c878552018-11-22 16:53:21 +01006698 mPolicyMixes.closeOutput(closingOutput);
Eric Laurent275e8e92014-11-30 15:14:47 -08006699
Eric Laurente552edb2014-03-10 17:42:56 -07006700 // look for duplicated outputs connected to the output being removed.
6701 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie1c878552018-11-22 16:53:21 +01006702 sp<SwAudioOutputDescriptor> dupOutput = mOutputs.valueAt(i);
6703 if (dupOutput->isDuplicated() &&
6704 (dupOutput->mOutput1 == closingOutput || dupOutput->mOutput2 == closingOutput)) {
6705 sp<SwAudioOutputDescriptor> remainingOutput =
6706 dupOutput->mOutput1 == closingOutput ? dupOutput->mOutput2 : dupOutput->mOutput1;
Eric Laurente552edb2014-03-10 17:42:56 -07006707 // As all active tracks on duplicated output will be deleted,
6708 // and as they were also referenced on the other output, the reference
6709 // count for their stream type must be adjusted accordingly on
6710 // the other output.
François Gaffie1c878552018-11-22 16:53:21 +01006711 const bool wasActive = remainingOutput->isActive();
6712 // Note: no-op on the closing output where all clients has already been set inactive
6713 dupOutput->setAllClientsInactive();
Eric Laurent733ce942017-12-07 12:18:25 -08006714 // stop() will be a no op if the output is still active but is needed in case all
6715 // active streams refcounts where cleared above
6716 if (wasActive) {
François Gaffie1c878552018-11-22 16:53:21 +01006717 remainingOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08006718 }
Eric Laurente552edb2014-03-10 17:42:56 -07006719 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
6720 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
6721
6722 mpClientInterface->closeOutput(duplicatedOutput);
François Gaffie53615e22015-03-19 09:24:12 +01006723 removeOutput(duplicatedOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07006724 }
6725 }
6726
Eric Laurent05b90f82014-08-27 15:32:29 -07006727 nextAudioPortGeneration();
6728
François Gaffie1c878552018-11-22 16:53:21 +01006729 ssize_t index = mAudioPatches.indexOfKey(closingOutput->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07006730 if (index >= 0) {
6731 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006732 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
6733 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07006734 mAudioPatches.removeItemsAt(index);
6735 mpClientInterface->onAudioPatchListUpdate();
6736 }
6737
Mikhail Naganov32ebca32019-03-22 15:42:52 -07006738 if (closingOutputWasActive) {
6739 closingOutput->stop();
6740 }
François Gaffie1c878552018-11-22 16:53:21 +01006741 closingOutput->close();
Eric Laurente552edb2014-03-10 17:42:56 -07006742
François Gaffie53615e22015-03-19 09:24:12 +01006743 removeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07006744 mPreviousOutputs = mOutputs;
Eric Laurentb4f42a92022-01-17 17:37:31 +01006745 if (closingOutput == mSpatializerOutput) {
6746 mSpatializerOutput.clear();
6747 }
Dean Wheatley3023b382018-08-09 07:42:40 +10006748
6749 // MSD patches may have been released to support a non-MSD direct output. Reset MSD patch if
6750 // no direct outputs are open.
François Gaffie11d30102018-11-02 16:09:09 +01006751 if (!getMsdAudioOutDevices().isEmpty()) {
Dean Wheatley3023b382018-08-09 07:42:40 +10006752 bool directOutputOpen = false;
6753 for (size_t i = 0; i < mOutputs.size(); i++) {
6754 if (mOutputs[i]->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
6755 directOutputOpen = true;
6756 break;
6757 }
6758 }
6759 if (!directOutputOpen) {
Michael Chan6fb34492020-12-08 15:44:49 +11006760 ALOGV("no direct outputs open, reset MSD patches");
6761 // TODO: The MSD patches to be established here may differ to current MSD patches due to
6762 // how output devices for patching are resolved. Avoid by caching and reusing the
6763 // arguments to mEngine->getOutputDevicesForAttributes() when resolving which output
6764 // devices to patch to. This may be complicated by the fact that devices may become
6765 // unavailable.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11006766 setMsdOutputPatches();
Dean Wheatley3023b382018-08-09 07:42:40 +10006767 }
6768 }
Eric Laurent05b90f82014-08-27 15:32:29 -07006769}
6770
6771void AudioPolicyManager::closeInput(audio_io_handle_t input)
6772{
6773 ALOGV("closeInput(%d)", input);
6774
6775 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
6776 if (inputDesc == NULL) {
6777 ALOGW("closeInput() unknown input %d", input);
6778 return;
6779 }
6780
Eric Laurent6a94d692014-05-20 11:18:06 -07006781 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07006782
François Gaffie11d30102018-11-02 16:09:09 +01006783 sp<DeviceDescriptor> device = inputDesc->getDevice();
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08006784 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07006785 if (index >= 0) {
6786 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006787 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
6788 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07006789 mAudioPatches.removeItemsAt(index);
6790 mpClientInterface->onAudioPatchListUpdate();
6791 }
6792
François Gaffie6ebbce02023-07-19 13:27:53 +02006793 mEffects.putOrphanEffectsForIo(input);
Eric Laurentfe231122017-11-17 17:48:06 -08006794 inputDesc->close();
Eric Laurent05b90f82014-08-27 15:32:29 -07006795 mInputs.removeItem(input);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07006796
François Gaffie11d30102018-11-02 16:09:09 +01006797 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
6798 if (primaryInputDevices.contains(device) &&
Haynes Mathew George1d539d92018-03-16 11:40:49 -07006799 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07006800 mpClientInterface->setSoundTriggerCaptureState(false);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07006801 }
Eric Laurente552edb2014-03-10 17:42:56 -07006802}
6803
François Gaffie11d30102018-11-02 16:09:09 +01006804SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevices(
6805 const DeviceVector &devices,
6806 const SwAudioOutputCollection& openOutputs)
Eric Laurente552edb2014-03-10 17:42:56 -07006807{
6808 SortedVector<audio_io_handle_t> outputs;
6809
François Gaffie11d30102018-11-02 16:09:09 +01006810 ALOGVV("%s() devices %s", __func__, devices.toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07006811 for (size_t i = 0; i < openOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01006812 ALOGVV("output %zu isDuplicated=%d device=%s",
Eric Laurent8c7e6da2015-04-21 17:37:00 -07006813 i, openOutputs.valueAt(i)->isDuplicated(),
François Gaffie11d30102018-11-02 16:09:09 +01006814 openOutputs.valueAt(i)->supportedDevices().toString().c_str());
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006815 if (openOutputs.valueAt(i)->supportsAllDevices(devices)
jiabin9a3361e2019-10-01 09:38:30 -07006816 && openOutputs.valueAt(i)->devicesSupportEncodedFormats(devices.types())) {
François Gaffie11d30102018-11-02 16:09:09 +01006817 ALOGVV("%s() found output %d", __func__, openOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07006818 outputs.add(openOutputs.keyAt(i));
6819 }
6820 }
6821 return outputs;
6822}
6823
Mikhail Naganov37977152018-07-11 15:54:44 -07006824void AudioPolicyManager::checkForDeviceAndOutputChanges(std::function<bool()> onOutputsChecked)
6825{
6826 // checkA2dpSuspend must run before checkOutputForAllStrategies so that A2DP
6827 // output is suspended before any tracks are moved to it
6828 checkA2dpSuspend();
6829 checkOutputForAllStrategies();
Kevin Rocard153f92d2018-12-18 18:33:28 -08006830 checkSecondaryOutputs();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11006831 if (onOutputsChecked != nullptr && onOutputsChecked()) checkA2dpSuspend();
Mikhail Naganov37977152018-07-11 15:54:44 -07006832 updateDevicesAndOutputs();
Mikhail Naganov7bd9b8d2018-11-15 02:09:03 +00006833 if (mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD) != 0) {
Michael Chan6fb34492020-12-08 15:44:49 +11006834 // TODO: The MSD patches to be established here may differ to current MSD patches due to how
6835 // output devices for patching are resolved. Nevertheless, AudioTracks affected by device
6836 // configuration changes will ultimately be rerouted correctly. We can still avoid
6837 // unnecessary rerouting by caching and reusing the arguments to
6838 // mEngine->getOutputDevicesForAttributes() when resolving which output devices to patch to.
6839 // This may be complicated by the fact that devices may become unavailable.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11006840 setMsdOutputPatches();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11006841 }
Jean-Michel Trivi9a6b9ad2020-10-22 16:46:43 -07006842 // an event that changed routing likely occurred, inform upper layers
6843 mpClientInterface->onRoutingUpdated();
Mikhail Naganov37977152018-07-11 15:54:44 -07006844}
6845
François Gaffiec005e562018-11-06 15:04:49 +01006846bool AudioPolicyManager::followsSameRouting(const audio_attributes_t &lAttr,
6847 const audio_attributes_t &rAttr) const
Eric Laurente552edb2014-03-10 17:42:56 -07006848{
François Gaffiec005e562018-11-06 15:04:49 +01006849 return mEngine->getProductStrategyForAttributes(lAttr) ==
6850 mEngine->getProductStrategyForAttributes(rAttr);
6851}
6852
Francois Gaffieff1eb522020-05-06 18:37:04 +02006853void AudioPolicyManager::checkAudioSourceForAttributes(const audio_attributes_t &attr)
6854{
6855 for (size_t i = 0; i < mAudioSources.size(); i++) {
6856 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
6857 if (sourceDesc != nullptr && followsSameRouting(attr, sourceDesc->attributes())
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02006858 && sourceDesc->getPatchHandle() == AUDIO_PATCH_HANDLE_NONE
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02006859 && !isCallRxAudioSource(sourceDesc) && !sourceDesc->isInternal()) {
Francois Gaffieff1eb522020-05-06 18:37:04 +02006860 connectAudioSource(sourceDesc);
6861 }
6862 }
6863}
6864
6865void AudioPolicyManager::clearAudioSourcesForOutput(audio_io_handle_t output)
6866{
6867 for (size_t i = 0; i < mAudioSources.size(); i++) {
6868 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
6869 if (sourceDesc != nullptr && sourceDesc->swOutput().promote() != nullptr
6870 && sourceDesc->swOutput().promote()->mIoHandle == output) {
6871 disconnectAudioSource(sourceDesc);
6872 }
6873 }
6874}
6875
François Gaffiec005e562018-11-06 15:04:49 +01006876void AudioPolicyManager::checkOutputForAttributes(const audio_attributes_t &attr)
6877{
6878 auto psId = mEngine->getProductStrategyForAttributes(attr);
6879
6880 DeviceVector oldDevices = mEngine->getOutputDevicesForAttributes(attr, 0, true /*fromCache*/);
6881 DeviceVector newDevices = mEngine->getOutputDevicesForAttributes(attr, 0, false /*fromCache*/);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07006882
François Gaffie11d30102018-11-02 16:09:09 +01006883 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevices(oldDevices, mPreviousOutputs);
6884 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevices(newDevices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07006885
Eric Laurentc209fe42020-06-05 18:11:23 -07006886 uint32_t maxLatency = 0;
Oscar Azucena873d10f2023-01-12 18:34:42 -08006887 bool unneededUsePrimaryOutputFromPolicyMixes = false;
Eric Laurent56ed8842022-11-15 16:04:41 +01006888 std::vector<sp<SwAudioOutputDescriptor>> invalidatedOutputs;
Eric Laurentc209fe42020-06-05 18:11:23 -07006889 // take into account dynamic audio policies related changes: if a client is now associated
6890 // to a different policy mix than at creation time, invalidate corresponding stream
Eric Laurent56ed8842022-11-15 16:04:41 +01006891 for (size_t i = 0; i < mPreviousOutputs.size(); i++) {
Eric Laurentc209fe42020-06-05 18:11:23 -07006892 const sp<SwAudioOutputDescriptor>& desc = mPreviousOutputs.valueAt(i);
6893 if (desc->isDuplicated()) {
6894 continue;
Jean-Michel Trivife472e22014-12-16 14:23:13 -08006895 }
Eric Laurentc209fe42020-06-05 18:11:23 -07006896 for (const sp<TrackClientDescriptor>& client : desc->getClientIterable()) {
6897 if (mEngine->getProductStrategyForAttributes(client->attributes()) != psId) {
6898 continue;
6899 }
6900 sp<AudioPolicyMix> primaryMix;
Dean Wheatleyd082f472022-02-04 11:10:48 +11006901 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->config(),
Oscar Azucena873d10f2023-01-12 18:34:42 -08006902 client->uid(), client->session(), client->flags(), mAvailableOutputDevices,
6903 nullptr /* requestedDevice */, primaryMix, nullptr /* secondaryMixes */,
6904 unneededUsePrimaryOutputFromPolicyMixes);
Eric Laurentc209fe42020-06-05 18:11:23 -07006905 if (status != OK) {
6906 continue;
6907 }
yucliuf4de36d2020-09-14 14:57:56 -07006908 if (client->getPrimaryMix() != primaryMix || client->hasLostPrimaryMix()) {
Eric Laurent56ed8842022-11-15 16:04:41 +01006909 if (desc->isStrategyActive(psId) && maxLatency < desc->latency()) {
Eric Laurentc209fe42020-06-05 18:11:23 -07006910 maxLatency = desc->latency();
6911 }
Eric Laurent56ed8842022-11-15 16:04:41 +01006912 invalidatedOutputs.push_back(desc);
Eric Laurentc209fe42020-06-05 18:11:23 -07006913 }
Jean-Michel Trivife472e22014-12-16 14:23:13 -08006914 }
6915 }
6916
Eric Laurent56ed8842022-11-15 16:04:41 +01006917 if (srcOutputs != dstOutputs || !invalidatedOutputs.empty()) {
Eric Laurentac3a6902018-05-11 16:39:10 -07006918 // get maximum latency of all source outputs to determine the minimum mute time guaranteeing
6919 // audio from invalidated tracks will be rendered when unmuting
Eric Laurentac3a6902018-05-11 16:39:10 -07006920 for (audio_io_handle_t srcOut : srcOutputs) {
6921 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
Eric Laurentaa02db82019-09-05 17:31:49 -07006922 if (desc == nullptr) continue;
6923
6924 if (desc->isStrategyActive(psId) && maxLatency < desc->latency()) {
Eric Laurentac3a6902018-05-11 16:39:10 -07006925 maxLatency = desc->latency();
6926 }
Eric Laurentaa02db82019-09-05 17:31:49 -07006927
Eric Laurent56ed8842022-11-15 16:04:41 +01006928 bool invalidate = false;
Eric Laurentaa02db82019-09-05 17:31:49 -07006929 for (auto client : desc->clientsList(false /*activeOnly*/)) {
Eric Laurent78aade82019-09-13 18:55:08 -07006930 if (desc->isDuplicated() || !desc->mProfile->isDirectOutput()) {
Eric Laurentaa02db82019-09-05 17:31:49 -07006931 // a client on a non direct outputs has necessarily a linear PCM format
6932 // so we can call selectOutput() safely
6933 const audio_io_handle_t newOutput = selectOutput(dstOutputs,
6934 client->flags(),
6935 client->config().format,
6936 client->config().channel_mask,
jiabinebb6af42020-06-09 17:31:17 -07006937 client->config().sample_rate,
6938 client->session());
Eric Laurentaa02db82019-09-05 17:31:49 -07006939 if (newOutput != srcOut) {
6940 invalidate = true;
6941 break;
6942 }
6943 } else {
6944 sp<IOProfile> profile = getProfileForOutput(newDevices,
6945 client->config().sample_rate,
6946 client->config().format,
6947 client->config().channel_mask,
6948 client->flags(),
6949 true /* directOnly */);
6950 if (profile != desc->mProfile) {
6951 invalidate = true;
6952 break;
6953 }
6954 }
6955 }
Eric Laurent56ed8842022-11-15 16:04:41 +01006956 // mute strategy while moving tracks from one output to another
6957 if (invalidate) {
6958 invalidatedOutputs.push_back(desc);
6959 if (desc->isStrategyActive(psId)) {
6960 setStrategyMute(psId, true, desc);
6961 setStrategyMute(psId, false, desc, maxLatency * LATENCY_MUTE_FACTOR,
6962 newDevices.types());
6963 }
Eric Laurente552edb2014-03-10 17:42:56 -07006964 }
François Gaffiec005e562018-11-06 15:04:49 +01006965 sp<SourceClientDescriptor> source = getSourceForAttributesOnOutput(srcOut, attr);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02006966 if (source != nullptr && !isCallRxAudioSource(source) && !source->isInternal()) {
Eric Laurentd60560a2015-04-10 11:31:20 -07006967 connectAudioSource(source);
6968 }
Eric Laurente552edb2014-03-10 17:42:56 -07006969 }
6970
Eric Laurent56ed8842022-11-15 16:04:41 +01006971 ALOGV_IF(!(srcOutputs.isEmpty() || dstOutputs.isEmpty()),
6972 "%s: strategy %d, moving from output %s to output %s", __func__, psId,
6973 std::to_string(srcOutputs[0]).c_str(),
6974 std::to_string(dstOutputs[0]).c_str());
6975
François Gaffiec005e562018-11-06 15:04:49 +01006976 // Move effects associated to this stream from previous output to new output
6977 if (followsSameRouting(attr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07006978 selectOutputForMusicEffects();
Eric Laurente552edb2014-03-10 17:42:56 -07006979 }
François Gaffiec005e562018-11-06 15:04:49 +01006980 // Move tracks associated to this stream (and linked) from previous output to new output
Eric Laurent56ed8842022-11-15 16:04:41 +01006981 if (!invalidatedOutputs.empty()) {
jiabinc44b3462022-12-08 12:52:31 -08006982 invalidateStreams(mEngine->getStreamTypesForProductStrategy(psId));
Eric Laurent56ed8842022-11-15 16:04:41 +01006983 for (sp<SwAudioOutputDescriptor> desc : invalidatedOutputs) {
jiabin49256852022-03-09 11:21:35 -08006984 desc->setTracksInvalidatedStatusByStrategy(psId);
6985 }
Eric Laurente552edb2014-03-10 17:42:56 -07006986 }
6987 }
6988}
6989
Eric Laurente0720872014-03-11 09:30:41 -07006990void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07006991{
François Gaffiec005e562018-11-06 15:04:49 +01006992 for (const auto &strategy : mEngine->getOrderedProductStrategies()) {
6993 auto attributes = mEngine->getAllAttributesForProductStrategy(strategy).front();
6994 checkOutputForAttributes(attributes);
Francois Gaffieff1eb522020-05-06 18:37:04 +02006995 checkAudioSourceForAttributes(attributes);
François Gaffiec005e562018-11-06 15:04:49 +01006996 }
Eric Laurente552edb2014-03-10 17:42:56 -07006997}
6998
Kevin Rocard153f92d2018-12-18 18:33:28 -08006999void AudioPolicyManager::checkSecondaryOutputs() {
jiabinc44b3462022-12-08 12:52:31 -08007000 PortHandleVector clientsToInvalidate;
jiabin10a03f12021-05-07 23:46:28 +00007001 TrackSecondaryOutputsMap trackSecondaryOutputs;
Oscar Azucena873d10f2023-01-12 18:34:42 -08007002 bool unneededUsePrimaryOutputFromPolicyMixes = false;
Kevin Rocard153f92d2018-12-18 18:33:28 -08007003 for (size_t i = 0; i < mOutputs.size(); i++) {
7004 const sp<SwAudioOutputDescriptor>& outputDescriptor = mOutputs[i];
7005 for (const sp<TrackClientDescriptor>& client : outputDescriptor->getClientIterable()) {
Eric Laurentc529cf62020-04-17 18:19:10 -07007006 sp<AudioPolicyMix> primaryMix;
7007 std::vector<sp<AudioPolicyMix>> secondaryMixes;
Dean Wheatleyd082f472022-02-04 11:10:48 +11007008 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->config(),
Oscar Azucena873d10f2023-01-12 18:34:42 -08007009 client->uid(), client->session(), client->flags(), mAvailableOutputDevices,
7010 nullptr /* requestedDevice */, primaryMix, &secondaryMixes,
7011 unneededUsePrimaryOutputFromPolicyMixes);
Eric Laurentc529cf62020-04-17 18:19:10 -07007012 std::vector<sp<SwAudioOutputDescriptor>> secondaryDescs;
7013 for (auto &secondaryMix : secondaryMixes) {
7014 sp<SwAudioOutputDescriptor> outputDesc = secondaryMix->getOutput();
7015 if (outputDesc != nullptr &&
7016 outputDesc->mIoHandle != AUDIO_IO_HANDLE_NONE) {
7017 secondaryDescs.push_back(outputDesc);
7018 }
7019 }
7020
jiabinc44b3462022-12-08 12:52:31 -08007021 if (status != OK &&
7022 (client->flags() & AUDIO_OUTPUT_FLAG_MMAP_NOIRQ) == AUDIO_OUTPUT_FLAG_NONE) {
7023 // When it failed to query secondary output, only invalidate the client that is not
7024 // MMAP. The reason is that MMAP stream will not support secondary output.
7025 clientsToInvalidate.push_back(client->portId());
jiabin10a03f12021-05-07 23:46:28 +00007026 } else if (!std::equal(
7027 client->getSecondaryOutputs().begin(),
7028 client->getSecondaryOutputs().end(),
7029 secondaryDescs.begin(), secondaryDescs.end())) {
jiabina5281062021-11-23 00:10:23 +00007030 if (!audio_is_linear_pcm(client->config().format)) {
7031 // If the format is not PCM, the tracks should be invalidated to get correct
7032 // behavior when the secondary output is changed.
jiabinc44b3462022-12-08 12:52:31 -08007033 clientsToInvalidate.push_back(client->portId());
jiabina5281062021-11-23 00:10:23 +00007034 } else {
7035 std::vector<wp<SwAudioOutputDescriptor>> weakSecondaryDescs;
7036 std::vector<audio_io_handle_t> secondaryOutputIds;
7037 for (const auto &secondaryDesc: secondaryDescs) {
7038 secondaryOutputIds.push_back(secondaryDesc->mIoHandle);
7039 weakSecondaryDescs.push_back(secondaryDesc);
7040 }
7041 trackSecondaryOutputs.emplace(client->portId(), secondaryOutputIds);
7042 client->setSecondaryOutputs(std::move(weakSecondaryDescs));
jiabin10a03f12021-05-07 23:46:28 +00007043 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08007044 }
7045 }
7046 }
jiabin10a03f12021-05-07 23:46:28 +00007047 if (!trackSecondaryOutputs.empty()) {
7048 mpClientInterface->updateSecondaryOutputs(trackSecondaryOutputs);
7049 }
jiabinc44b3462022-12-08 12:52:31 -08007050 if (!clientsToInvalidate.empty()) {
7051 ALOGD("%s Invalidate clients due to fail getting output for attr", __func__);
7052 mpClientInterface->invalidateTracks(clientsToInvalidate);
Kevin Rocard153f92d2018-12-18 18:33:28 -08007053 }
7054}
7055
Eric Laurent2517af32020-11-25 15:31:27 +01007056bool AudioPolicyManager::isScoRequestedForComm() const {
7057 AudioDeviceTypeAddrVector devices;
7058 mEngine->getDevicesForRoleAndStrategy(mCommunnicationStrategy, DEVICE_ROLE_PREFERRED, devices);
7059 for (const auto &device : devices) {
7060 if (audio_is_bluetooth_out_sco_device(device.mType)) {
7061 return true;
7062 }
7063 }
7064 return false;
7065}
7066
Eric Laurent1a8b45f2022-04-13 16:01:47 +02007067bool AudioPolicyManager::isHearingAidUsedForComm() const {
7068 DeviceVector devices = mEngine->getOutputDevicesForStream(AUDIO_STREAM_VOICE_CALL,
7069 true /*fromCache*/);
7070 for (const auto &device : devices) {
7071 if (device->type() == AUDIO_DEVICE_OUT_HEARING_AID) {
7072 return true;
7073 }
7074 }
7075 return false;
7076}
7077
7078
Eric Laurente0720872014-03-11 09:30:41 -07007079void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07007080{
François Gaffie53615e22015-03-19 09:24:12 +01007081 audio_io_handle_t a2dpOutput = mOutputs.getA2dpOutput();
Aniket Kumar Lataa8ee9962018-01-31 20:24:23 -08007082 if (a2dpOutput == 0 || mOutputs.isA2dpOffloadedOnPrimary()) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07007083 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07007084 return;
7085 }
7086
Eric Laurent3a4311c2014-03-17 12:00:47 -07007087 bool isScoConnected =
jiabin9a3361e2019-10-01 09:38:30 -07007088 (mAvailableInputDevices.types().count(AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) != 0 ||
7089 !Intersection(mAvailableOutputDevices.types(), getAudioDeviceOutAllScoSet()).empty());
Eric Laurent2517af32020-11-25 15:31:27 +01007090 bool isScoRequested = isScoRequestedForComm();
Eric Laurentf732e072016-08-03 19:30:28 -07007091
7092 // if suspended, restore A2DP output if:
7093 // ((SCO device is NOT connected) ||
Eric Laurent2517af32020-11-25 15:31:27 +01007094 // ((SCO is not requested) &&
Eric Laurentf732e072016-08-03 19:30:28 -07007095 // (phone state is NOT in call) && (phone state is NOT ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07007096 //
Eric Laurentf732e072016-08-03 19:30:28 -07007097 // if not suspended, suspend A2DP output if:
7098 // (SCO device is connected) &&
Eric Laurent2517af32020-11-25 15:31:27 +01007099 // ((SCO is requested) ||
Eric Laurentf732e072016-08-03 19:30:28 -07007100 // ((phone state is in call) || (phone state is ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07007101 //
7102 if (mA2dpSuspended) {
Eric Laurentf732e072016-08-03 19:30:28 -07007103 if (!isScoConnected ||
Eric Laurent2517af32020-11-25 15:31:27 +01007104 (!isScoRequested &&
Eric Laurentf732e072016-08-03 19:30:28 -07007105 (mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) &&
François Gaffie2110e042015-03-24 08:41:51 +01007106 (mEngine->getPhoneState() != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07007107
7108 mpClientInterface->restoreOutput(a2dpOutput);
7109 mA2dpSuspended = false;
7110 }
7111 } else {
Eric Laurentf732e072016-08-03 19:30:28 -07007112 if (isScoConnected &&
Eric Laurent2517af32020-11-25 15:31:27 +01007113 (isScoRequested ||
Eric Laurentf732e072016-08-03 19:30:28 -07007114 (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) ||
François Gaffie2110e042015-03-24 08:41:51 +01007115 (mEngine->getPhoneState() == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07007116
7117 mpClientInterface->suspendOutput(a2dpOutput);
7118 mA2dpSuspended = true;
7119 }
7120 }
7121}
7122
François Gaffie11d30102018-11-02 16:09:09 +01007123DeviceVector AudioPolicyManager::getNewOutputDevices(const sp<SwAudioOutputDescriptor>& outputDesc,
7124 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07007125{
François Gaffiedb1755b2023-09-01 11:50:35 +02007126 if (outputDesc == nullptr) {
7127 return DeviceVector{};
7128 }
François Gaffie11d30102018-11-02 16:09:09 +01007129
Jean-Michel Triviff155c62016-02-26 12:07:16 -08007130 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007131 if (index >= 0) {
7132 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007133 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01007134 ALOGV("%s device %s forced by patch %d", __func__,
7135 outputDesc->devices().toString().c_str(), outputDesc->getPatchHandle());
7136 return outputDesc->devices();
Eric Laurent6a94d692014-05-20 11:18:06 -07007137 }
7138 }
7139
Dean Wheatley514b4312020-06-17 21:45:00 +10007140 // Do not retrieve engine device for outputs through MSD
7141 // TODO: support explicit routing requests by resetting MSD patch to engine device.
7142 if (outputDesc->devices() == getMsdAudioOutDevices()) {
7143 return outputDesc->devices();
7144 }
7145
Eric Laurent97ac8712018-07-27 18:59:02 -07007146 // Honor explicit routing requests only if no client using default routing is active on this
7147 // input: a specific app can not force routing for other apps by setting a preferred device.
7148 bool active; // unused
François Gaffie11d30102018-11-02 16:09:09 +01007149 sp<DeviceDescriptor> device =
François Gaffiec005e562018-11-06 15:04:49 +01007150 findPreferredDevice(outputDesc, PRODUCT_STRATEGY_NONE, active, mAvailableOutputDevices);
François Gaffie11d30102018-11-02 16:09:09 +01007151 if (device != nullptr) {
7152 return DeviceVector(device);
Eric Laurentf3a5a602018-05-22 18:42:55 -07007153 }
7154
François Gaffiea807ef92018-11-05 10:44:33 +01007155 // Legacy Engine cannot take care of bus devices and mix, so we need to handle the conflict
7156 // of setForceUse / Default Bus device here
7157 device = mPolicyMixes.getDeviceAndMixForOutput(outputDesc, mAvailableOutputDevices);
7158 if (device != nullptr) {
7159 return DeviceVector(device);
7160 }
7161
François Gaffiedb1755b2023-09-01 11:50:35 +02007162 DeviceVector devices;
François Gaffiec005e562018-11-06 15:04:49 +01007163 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
7164 StreamTypeVector streams = mEngine->getStreamTypesForProductStrategy(productStrategy);
7165 auto attr = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307166 auto hasStreamActive = [&](auto stream) {
7167 return hasStream(streams, stream) && isStreamActive(stream, 0);
7168 };
Eric Laurent484e9272018-06-07 17:29:23 -07007169
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307170 auto doGetOutputDevicesForVoice = [&]() {
7171 return hasVoiceStream(streams) && (outputDesc == mPrimaryOutput ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007172 outputDesc->isActive(toVolumeSource(AUDIO_STREAM_VOICE_CALL, false))) &&
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307173 (isInCall() ||
Henrik Backlund07c654a2021-10-14 15:57:10 +02007174 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc)) &&
7175 !isStreamActive(AUDIO_STREAM_ENFORCED_AUDIBLE, 0);
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307176 };
7177
7178 // With low-latency playing on speaker, music on WFD, when the first low-latency
7179 // output is stopped, getNewOutputDevices checks for a product strategy
7180 // from the list, as STRATEGY_SONIFICATION comes prior to STRATEGY_MEDIA.
Carter Hsucc58a6b2021-07-20 08:44:50 +00007181 // If an ALARM or ENFORCED_AUDIBLE stream is supported by the product strategy,
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307182 // devices are returned for STRATEGY_SONIFICATION without checking whether the
7183 // stream is associated to the output descriptor.
7184 if (doGetOutputDevicesForVoice() || outputDesc->isStrategyActive(productStrategy) ||
7185 ((hasStreamActive(AUDIO_STREAM_ALARM) ||
7186 hasStreamActive(AUDIO_STREAM_ENFORCED_AUDIBLE)) &&
7187 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc))) {
François Gaffiec005e562018-11-06 15:04:49 +01007188 // Retrieval of devices for voice DL is done on primary output profile, cannot
7189 // check the route (would force modifying configuration file for this profile)
7190 devices = mEngine->getOutputDevicesForAttributes(attr, nullptr, fromCache);
7191 break;
7192 }
Eric Laurente552edb2014-03-10 17:42:56 -07007193 }
François Gaffiec005e562018-11-06 15:04:49 +01007194 ALOGV("%s selected devices %s", __func__, devices.toString().c_str());
François Gaffie11d30102018-11-02 16:09:09 +01007195 return devices;
Eric Laurent1c333e22014-05-20 10:48:17 -07007196}
7197
François Gaffie11d30102018-11-02 16:09:09 +01007198sp<DeviceDescriptor> AudioPolicyManager::getNewInputDevice(
7199 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurent1c333e22014-05-20 10:48:17 -07007200{
François Gaffie11d30102018-11-02 16:09:09 +01007201 sp<DeviceDescriptor> device;
Eric Laurent6a94d692014-05-20 11:18:06 -07007202
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08007203 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007204 if (index >= 0) {
7205 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007206 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01007207 ALOGV("getNewInputDevice() device %s forced by patch %d",
7208 inputDesc->getDevice()->toString().c_str(), inputDesc->getPatchHandle());
7209 return inputDesc->getDevice();
Eric Laurent6a94d692014-05-20 11:18:06 -07007210 }
7211 }
7212
Eric Laurent97ac8712018-07-27 18:59:02 -07007213 // Honor explicit routing requests only if no client using default routing is active on this
7214 // input: a specific app can not force routing for other apps by setting a preferred device.
7215 bool active;
François Gaffie11d30102018-11-02 16:09:09 +01007216 device = findPreferredDevice(inputDesc, AUDIO_SOURCE_DEFAULT, active, mAvailableInputDevices);
7217 if (device != nullptr) {
7218 return device;
Eric Laurent97ac8712018-07-27 18:59:02 -07007219 }
7220
Eric Laurentdc95a252018-04-12 12:46:56 -07007221 // If we are not in call and no client is active on this input, this methods returns
Andy Hungf024a9e2019-01-30 16:01:02 -08007222 // a null sp<>, causing the patch on the input stream to be released.
yuanjiahsu0735bf32021-03-18 08:12:54 +08007223 audio_attributes_t attributes;
7224 uid_t uid;
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007225 audio_session_t session;
yuanjiahsu0735bf32021-03-18 08:12:54 +08007226 sp<RecordClientDescriptor> topClient = inputDesc->getHighestPriorityClient();
7227 if (topClient != nullptr) {
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01007228 attributes = topClient->attributes();
7229 uid = topClient->uid();
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007230 session = topClient->session();
yuanjiahsu0735bf32021-03-18 08:12:54 +08007231 } else {
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01007232 attributes = { .source = AUDIO_SOURCE_DEFAULT };
7233 uid = 0;
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007234 session = AUDIO_SESSION_NONE;
yuanjiahsu0735bf32021-03-18 08:12:54 +08007235 }
7236
Francois Gaffie716e1432019-01-14 16:58:59 +01007237 if (attributes.source == AUDIO_SOURCE_DEFAULT && isInCall()) {
7238 attributes.source = AUDIO_SOURCE_VOICE_COMMUNICATION;
Eric Laurentdc95a252018-04-12 12:46:56 -07007239 }
Francois Gaffie716e1432019-01-14 16:58:59 +01007240 if (attributes.source != AUDIO_SOURCE_DEFAULT) {
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007241 device = mEngine->getInputDeviceForAttributes(attributes, uid, session);
Eric Laurentfb66dd92016-01-28 18:32:03 -08007242 }
Eric Laurent1c333e22014-05-20 10:48:17 -07007243
Eric Laurente552edb2014-03-10 17:42:56 -07007244 return device;
7245}
7246
Eric Laurent794fde22016-03-11 09:50:45 -08007247bool AudioPolicyManager::streamsMatchForvolume(audio_stream_type_t stream1,
7248 audio_stream_type_t stream2) {
Jean-Michel Trivi99bb2f92016-11-23 15:52:07 -08007249 return (stream1 == stream2);
Eric Laurent28d09f02016-03-08 10:43:05 -08007250}
7251
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08007252status_t AudioPolicyManager::getDevicesForAttributes(
Andy Hung6d23c0f2022-02-16 09:37:15 -08007253 const audio_attributes_t &attr, AudioDeviceTypeAddrVector *devices, bool forVolume) {
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08007254 if (devices == nullptr) {
7255 return BAD_VALUE;
7256 }
Andy Hung6d23c0f2022-02-16 09:37:15 -08007257
Andy Hung6d23c0f2022-02-16 09:37:15 -08007258 DeviceVector curDevices;
jiabinf1c73972022-04-14 16:28:52 -07007259 if (status_t status = getDevicesForAttributes(attr, curDevices, forVolume); status != OK) {
7260 return status;
Andy Hung6d23c0f2022-02-16 09:37:15 -08007261 }
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08007262 for (const auto& device : curDevices) {
7263 devices->push_back(device->getDeviceTypeAddr());
7264 }
7265 return NO_ERROR;
7266}
7267
Eric Laurente0720872014-03-11 09:30:41 -07007268void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07007269 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07007270 case AUDIO_STREAM_MUSIC:
François Gaffiec005e562018-11-06 15:04:49 +01007271 checkOutputForAttributes(attributes_initializer(AUDIO_USAGE_NOTIFICATION));
Eric Laurente552edb2014-03-10 17:42:56 -07007272 updateDevicesAndOutputs();
7273 break;
7274 default:
7275 break;
7276 }
7277}
7278
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007279uint32_t AudioPolicyManager::handleEventForBeacon(int event) {
Eric Laurent9459fb02015-08-12 18:36:32 -07007280
7281 // skip beacon mute management if a dedicated TTS output is available
7282 if (mTtsOutputAvailable) {
7283 return 0;
7284 }
7285
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007286 switch(event) {
7287 case STARTING_OUTPUT:
7288 mBeaconMuteRefCount++;
7289 break;
7290 case STOPPING_OUTPUT:
7291 if (mBeaconMuteRefCount > 0) {
7292 mBeaconMuteRefCount--;
7293 }
7294 break;
7295 case STARTING_BEACON:
7296 mBeaconPlayingRefCount++;
7297 break;
7298 case STOPPING_BEACON:
7299 if (mBeaconPlayingRefCount > 0) {
7300 mBeaconPlayingRefCount--;
7301 }
7302 break;
7303 }
7304
7305 if (mBeaconMuteRefCount > 0) {
7306 // any playback causes beacon to be muted
7307 return setBeaconMute(true);
7308 } else {
7309 // no other playback: unmute when beacon starts playing, mute when it stops
7310 return setBeaconMute(mBeaconPlayingRefCount == 0);
7311 }
7312}
7313
7314uint32_t AudioPolicyManager::setBeaconMute(bool mute) {
7315 ALOGV("setBeaconMute(%d) mBeaconMuteRefCount=%d mBeaconPlayingRefCount=%d",
7316 mute, mBeaconMuteRefCount, mBeaconPlayingRefCount);
7317 // keep track of muted state to avoid repeating mute/unmute operations
7318 if (mBeaconMuted != mute) {
7319 // mute/unmute AUDIO_STREAM_TTS on all outputs
7320 ALOGV("\t muting %d", mute);
7321 uint32_t maxLatency = 0;
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007322 auto ttsVolumeSource = toVolumeSource(AUDIO_STREAM_TTS, false);
7323 if (ttsVolumeSource == VOLUME_SOURCE_NONE) {
7324 ALOGV("\t no tts volume source available");
7325 return 0;
7326 }
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007327 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07007328 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
jiabin9a3361e2019-10-01 09:38:30 -07007329 setVolumeSourceMute(ttsVolumeSource, mute/*on*/, desc, 0 /*delay*/, DeviceTypeSet());
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007330 const uint32_t latency = desc->latency() * 2;
Eric Laurentcdb2b352020-07-23 10:57:02 -07007331 if (desc->isActive(latency * 2) && latency > maxLatency) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007332 maxLatency = latency;
7333 }
7334 }
7335 mBeaconMuted = mute;
7336 return maxLatency;
7337 }
7338 return 0;
7339}
7340
Eric Laurente0720872014-03-11 09:30:41 -07007341void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07007342{
François Gaffiec005e562018-11-06 15:04:49 +01007343 mEngine->updateDeviceSelectionCache();
Eric Laurente552edb2014-03-10 17:42:56 -07007344 mPreviousOutputs = mOutputs;
7345}
7346
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07007347uint32_t AudioPolicyManager::checkDeviceMuteStrategies(const sp<AudioOutputDescriptor>& outputDesc,
François Gaffiec005e562018-11-06 15:04:49 +01007348 const DeviceVector &prevDevices,
Eric Laurente552edb2014-03-10 17:42:56 -07007349 uint32_t delayMs)
7350{
7351 // mute/unmute strategies using an incompatible device combination
7352 // if muting, wait for the audio in pcm buffer to be drained before proceeding
7353 // if unmuting, unmute only after the specified delay
7354 if (outputDesc->isDuplicated()) {
7355 return 0;
7356 }
7357
7358 uint32_t muteWaitMs = 0;
François Gaffiec005e562018-11-06 15:04:49 +01007359 DeviceVector devices = outputDesc->devices();
7360 bool shouldMute = outputDesc->isActive() && (devices.size() >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07007361
François Gaffiec005e562018-11-06 15:04:49 +01007362 auto productStrategies = mEngine->getOrderedProductStrategies();
7363 for (const auto &productStrategy : productStrategies) {
7364 auto attributes = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
7365 DeviceVector curDevices =
7366 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false/*fromCache*/);
7367 curDevices = curDevices.filter(outputDesc->supportedDevices());
7368 bool mute = shouldMute && curDevices.containsAtLeastOne(devices) && curDevices != devices;
Eric Laurente552edb2014-03-10 17:42:56 -07007369 bool doMute = false;
7370
François Gaffiec005e562018-11-06 15:04:49 +01007371 if (mute && !outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07007372 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01007373 outputDesc->setStrategyMutedByDevice(productStrategy, true);
7374 } else if (!mute && outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07007375 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01007376 outputDesc->setStrategyMutedByDevice(productStrategy, false);
Eric Laurente552edb2014-03-10 17:42:56 -07007377 }
Eric Laurent99401132014-05-07 19:48:15 -07007378 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07007379 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07007380 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07007381 // skip output if it does not share any device with current output
François Gaffie11d30102018-11-02 16:09:09 +01007382 if (!desc->supportedDevices().containsAtLeastOne(outputDesc->supportedDevices())) {
Eric Laurente552edb2014-03-10 17:42:56 -07007383 continue;
7384 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307385 ALOGVV("%s() output %s %s (curDevice %s)", __func__, desc->info().c_str(),
François Gaffiec005e562018-11-06 15:04:49 +01007386 mute ? "muting" : "unmuting", curDevices.toString().c_str());
7387 setStrategyMute(productStrategy, mute, desc, mute ? 0 : delayMs);
7388 if (desc->isStrategyActive(productStrategy)) {
Eric Laurent99401132014-05-07 19:48:15 -07007389 if (mute) {
7390 // FIXME: should not need to double latency if volume could be applied
7391 // immediately by the audioflinger mixer. We must account for the delay
7392 // between now and the next time the audioflinger thread for this output
7393 // will process a buffer (which corresponds to one buffer size,
7394 // usually 1/2 or 1/4 of the latency).
7395 if (muteWaitMs < desc->latency() * 2) {
7396 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07007397 }
7398 }
7399 }
7400 }
7401 }
7402 }
7403
Eric Laurent99401132014-05-07 19:48:15 -07007404 // temporary mute output if device selection changes to avoid volume bursts due to
7405 // different per device volumes
François Gaffiec005e562018-11-06 15:04:49 +01007406 if (outputDesc->isActive() && (devices != prevDevices)) {
Eric Laurentdc462862016-07-19 12:29:53 -07007407 uint32_t tempMuteWaitMs = outputDesc->latency() * 2;
Jasmine Chaf6074fe2021-08-17 13:44:31 +08007408
Eric Laurentdc462862016-07-19 12:29:53 -07007409 if (muteWaitMs < tempMuteWaitMs) {
7410 muteWaitMs = tempMuteWaitMs;
Eric Laurent99401132014-05-07 19:48:15 -07007411 }
Jasmine Chaf6074fe2021-08-17 13:44:31 +08007412
7413 // If recommended duration is defined, replace temporary mute duration to avoid
7414 // truncated notifications at beginning, which depends on duration of changing path in HAL.
7415 // Otherwise, temporary mute duration is conservatively set to 4 times the reported latency.
7416 uint32_t tempRecommendedMuteDuration = outputDesc->getRecommendedMuteDurationMs();
7417 uint32_t tempMuteDurationMs = tempRecommendedMuteDuration > 0 ?
7418 tempRecommendedMuteDuration : outputDesc->latency() * 4;
7419
François Gaffieaaac0fd2018-11-22 17:56:39 +01007420 for (const auto &activeVs : outputDesc->getActiveVolumeSources()) {
7421 // make sure that we do not start the temporary mute period too early in case of
7422 // delayed device change
7423 setVolumeSourceMute(activeVs, true, outputDesc, delayMs);
7424 setVolumeSourceMute(activeVs, false, outputDesc, delayMs + tempMuteDurationMs,
François Gaffiec005e562018-11-06 15:04:49 +01007425 devices.types());
Eric Laurent99401132014-05-07 19:48:15 -07007426 }
7427 }
7428
Eric Laurente552edb2014-03-10 17:42:56 -07007429 // wait for the PCM output buffers to empty before proceeding with the rest of the command
7430 if (muteWaitMs > delayMs) {
7431 muteWaitMs -= delayMs;
7432 usleep(muteWaitMs * 1000);
7433 return muteWaitMs;
7434 }
7435 return 0;
7436}
7437
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307438uint32_t AudioPolicyManager::setOutputDevices(const char *caller,
7439 const sp<SwAudioOutputDescriptor>& outputDesc,
François Gaffie11d30102018-11-02 16:09:09 +01007440 const DeviceVector &devices,
7441 bool force,
7442 int delayMs,
7443 audio_patch_handle_t *patchHandle,
Oscar Azucena6acf34b2023-04-27 16:32:09 -07007444 bool requiresMuteCheck, bool requiresVolumeCheck,
7445 bool skipMuteDelay)
Eric Laurente552edb2014-03-10 17:42:56 -07007446{
jiabin3ff8d7d2022-12-13 06:27:44 +00007447 // TODO(b/262404095): Consider if the output need to be reopened.
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307448 std::string logPrefix = std::string("caller ") + caller + outputDesc->info();
7449 ALOGV("%s %s device %s delayMs %d", __func__, logPrefix.c_str(),
7450 devices.toString().c_str(), delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07007451 uint32_t muteWaitMs;
7452
7453 if (outputDesc->isDuplicated()) {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307454 muteWaitMs = setOutputDevices(__func__, outputDesc->subOutput1(), devices, force, delayMs,
Oscar Azucena6acf34b2023-04-27 16:32:09 -07007455 nullptr /* patchHandle */, requiresMuteCheck, skipMuteDelay);
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307456 muteWaitMs += setOutputDevices(__func__, outputDesc->subOutput2(), devices, force, delayMs,
Oscar Azucena6acf34b2023-04-27 16:32:09 -07007457 nullptr /* patchHandle */, requiresMuteCheck, skipMuteDelay);
Eric Laurente552edb2014-03-10 17:42:56 -07007458 return muteWaitMs;
7459 }
Eric Laurente552edb2014-03-10 17:42:56 -07007460
7461 // filter devices according to output selected
Francois Gaffie716e1432019-01-14 16:58:59 +01007462 DeviceVector filteredDevices = outputDesc->filterSupportedDevices(devices);
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01007463 DeviceVector prevDevices = outputDesc->devices();
Francois Gaffie3523ab32021-06-22 13:24:34 +02007464 DeviceVector availPrevDevices = mAvailableOutputDevices.filter(prevDevices);
Eric Laurente552edb2014-03-10 17:42:56 -07007465
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307466 ALOGV("%s %s prevDevice %s", __func__, logPrefix.c_str(),
7467 prevDevices.toString().c_str());
François Gaffie11d30102018-11-02 16:09:09 +01007468
7469 if (!filteredDevices.isEmpty()) {
7470 outputDesc->setDevices(filteredDevices);
Eric Laurente552edb2014-03-10 17:42:56 -07007471 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00007472
7473 // if the outputs are not materially active, there is no need to mute.
7474 if (requiresMuteCheck) {
François Gaffiec005e562018-11-06 15:04:49 +01007475 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevices, delayMs);
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00007476 } else {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307477 ALOGV("%s: %s suppressing checkDeviceMuteStrategies", __func__,
7478 logPrefix.c_str());
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00007479 muteWaitMs = 0;
7480 }
Eric Laurente552edb2014-03-10 17:42:56 -07007481
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02007482 bool outputRouted = outputDesc->isRouted();
7483
Eric Laurent79ea9582020-06-11 18:49:24 -07007484 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
7485 // output profile or if new device is not supported AND previous device(s) is(are) still
7486 // available (otherwise reset device must be done on the output)
Francois Gaffie3523ab32021-06-22 13:24:34 +02007487 if (!devices.isEmpty() && filteredDevices.isEmpty() && !availPrevDevices.empty()) {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307488 ALOGV("%s: %s unsupported device %s for output", __func__, logPrefix.c_str(),
7489 devices.toString().c_str());
Eric Laurent79ea9582020-06-11 18:49:24 -07007490 // restore previous device after evaluating strategy mute state
7491 outputDesc->setDevices(prevDevices);
7492 return muteWaitMs;
7493 }
7494
Eric Laurente552edb2014-03-10 17:42:56 -07007495 // Do not change the routing if:
Eric Laurentb80a2a82014-10-27 16:07:59 -07007496 // the requested device is AUDIO_DEVICE_NONE
7497 // OR the requested device is the same as current device
7498 // AND force is not specified
7499 // AND the output is connected by a valid audio patch.
François Gaffie11d30102018-11-02 16:09:09 +01007500 // Doing this check here allows the caller to call setOutputDevices() without conditions
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02007501 if ((filteredDevices.isEmpty() || filteredDevices == prevDevices) && !force && outputRouted) {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307502 ALOGV("%s %s setting same device %s or null device, force=%d, patch handle=%d",
7503 __func__, logPrefix.c_str(), filteredDevices.toString().c_str(), force,
7504 outputDesc->getPatchHandle());
Francois Gaffie3523ab32021-06-22 13:24:34 +02007505 if (requiresVolumeCheck && !filteredDevices.isEmpty()) {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307506 ALOGV("%s %s setting same device on routed output, force apply volumes",
7507 __func__, logPrefix.c_str());
Francois Gaffie3523ab32021-06-22 13:24:34 +02007508 applyStreamVolumes(outputDesc, filteredDevices.types(), delayMs, true /*force*/);
7509 }
Eric Laurente552edb2014-03-10 17:42:56 -07007510 return muteWaitMs;
7511 }
7512
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307513 ALOGV("%s %s changing device to %s", __func__, logPrefix.c_str(),
7514 filteredDevices.toString().c_str());
Eric Laurent1c333e22014-05-20 10:48:17 -07007515
Eric Laurente552edb2014-03-10 17:42:56 -07007516 // do the routing
Francois Gaffie3523ab32021-06-22 13:24:34 +02007517 if (filteredDevices.isEmpty() || mAvailableOutputDevices.filter(filteredDevices).empty()) {
Eric Laurentc75307b2015-03-17 15:29:32 -07007518 resetOutputDevice(outputDesc, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07007519 } else {
François Gaffie11d30102018-11-02 16:09:09 +01007520 PatchBuilder patchBuilder;
7521 patchBuilder.addSource(outputDesc);
7522 ALOG_ASSERT(filteredDevices.size() <= AUDIO_PATCH_PORTS_MAX, "Too many sink ports");
7523 for (const auto &filteredDevice : filteredDevices) {
7524 patchBuilder.addSink(filteredDevice);
Eric Laurentc40d9692016-04-13 19:14:13 -07007525 }
7526
Jasmine Cha7f82d1a2020-03-16 13:21:47 +08007527 // Add half reported latency to delayMs when muteWaitMs is null in order
7528 // to avoid disordered sequence of muting volume and changing devices.
Oscar Azucena6acf34b2023-04-27 16:32:09 -07007529 int actualDelayMs = !skipMuteDelay && muteWaitMs == 0
7530 ? (delayMs + (outputDesc->latency() / 2)) : delayMs;
7531 installPatch(__func__, patchHandle, outputDesc.get(), patchBuilder.patch(), actualDelayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07007532 }
Eric Laurente552edb2014-03-10 17:42:56 -07007533
Oscar Azucena6acf34b2023-04-27 16:32:09 -07007534 // Since the mute is skip, also skip the apply stream volume as that will be applied externally
7535 if (!skipMuteDelay) {
7536 // update stream volumes according to new device
7537 applyStreamVolumes(outputDesc, filteredDevices.types(), delayMs);
7538 }
Eric Laurente552edb2014-03-10 17:42:56 -07007539
7540 return muteWaitMs;
7541}
7542
Eric Laurentc75307b2015-03-17 15:29:32 -07007543status_t AudioPolicyManager::resetOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurent6a94d692014-05-20 11:18:06 -07007544 int delayMs,
7545 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07007546{
Eric Laurent6a94d692014-05-20 11:18:06 -07007547 ssize_t index;
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02007548 if (patchHandle == nullptr && !outputDesc->isRouted()) {
7549 return INVALID_OPERATION;
7550 }
Eric Laurent6a94d692014-05-20 11:18:06 -07007551 if (patchHandle) {
7552 index = mAudioPatches.indexOfKey(*patchHandle);
7553 } else {
Jean-Michel Triviff155c62016-02-26 12:07:16 -08007554 index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007555 }
7556 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07007557 return INVALID_OPERATION;
7558 }
Eric Laurent6a94d692014-05-20 11:18:06 -07007559 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007560 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07007561 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07007562 outputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
François Gaffieafd4cea2019-11-18 15:50:22 +01007563 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007564 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07007565 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07007566 return status;
7567}
7568
7569status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
François Gaffie11d30102018-11-02 16:09:09 +01007570 const sp<DeviceDescriptor> &device,
Eric Laurent6a94d692014-05-20 11:18:06 -07007571 bool force,
7572 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07007573{
7574 status_t status = NO_ERROR;
7575
Eric Laurent1f2f2232014-06-02 12:01:23 -07007576 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
François Gaffie11d30102018-11-02 16:09:09 +01007577 if ((device != nullptr) && ((device != inputDesc->getDevice()) || force)) {
7578 inputDesc->setDevice(device);
Eric Laurent1c333e22014-05-20 10:48:17 -07007579
François Gaffie11d30102018-11-02 16:09:09 +01007580 if (mAvailableInputDevices.contains(device)) {
Mikhail Naganovdc769682018-05-04 15:34:08 -07007581 PatchBuilder patchBuilder;
7582 patchBuilder.addSink(inputDesc,
Eric Laurentdaf92cc2014-07-22 15:36:10 -07007583 // AUDIO_SOURCE_HOTWORD is for internal use only:
7584 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
Mikhail Naganovdc769682018-05-04 15:34:08 -07007585 [inputDesc](const PatchBuilder::mix_usecase_t& usecase) {
7586 auto result = usecase;
7587 if (result.source == AUDIO_SOURCE_HOTWORD && !inputDesc->isSoundTrigger()) {
7588 result.source = AUDIO_SOURCE_VOICE_RECOGNITION;
7589 }
7590 return result; }).
Eric Laurent1c333e22014-05-20 10:48:17 -07007591 //only one input device for now
François Gaffie11d30102018-11-02 16:09:09 +01007592 addSource(device);
Mikhail Naganovdc769682018-05-04 15:34:08 -07007593 status = installPatch(__func__, patchHandle, inputDesc.get(), patchBuilder.patch(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07007594 }
7595 }
7596 return status;
7597}
7598
Eric Laurent6a94d692014-05-20 11:18:06 -07007599status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
7600 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07007601{
Eric Laurent1f2f2232014-06-02 12:01:23 -07007602 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07007603 ssize_t index;
7604 if (patchHandle) {
7605 index = mAudioPatches.indexOfKey(*patchHandle);
7606 } else {
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08007607 index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007608 }
7609 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07007610 return INVALID_OPERATION;
7611 }
Eric Laurent6a94d692014-05-20 11:18:06 -07007612 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007613 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07007614 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07007615 inputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
François Gaffieafd4cea2019-11-18 15:50:22 +01007616 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007617 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07007618 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07007619 return status;
7620}
7621
François Gaffie11d30102018-11-02 16:09:09 +01007622sp<IOProfile> AudioPolicyManager::getInputProfile(const sp<DeviceDescriptor> &device,
François Gaffie53615e22015-03-19 09:24:12 +01007623 uint32_t& samplingRate,
Andy Hungf129b032015-04-07 13:45:50 -07007624 audio_format_t& format,
7625 audio_channel_mask_t& channelMask,
François Gaffie53615e22015-03-19 09:24:12 +01007626 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07007627{
7628 // Choose an input profile based on the requested capture parameters: select the first available
7629 // profile supporting all requested parameters.
jiabin2fd710d2022-05-02 23:20:22 +00007630 // The flags can be ignored if it doesn't contain a much match flag.
Andy Hungf129b032015-04-07 13:45:50 -07007631 //
7632 // TODO: perhaps isCompatibleProfile should return a "matching" score so we can return
7633 // the best matching profile, not the first one.
Eric Laurente552edb2014-03-10 17:42:56 -07007634
Atneya Nair0f0a8032022-12-12 16:20:12 -08007635 using underlying_input_flag_t = std::underlying_type_t<audio_input_flags_t>;
7636 const underlying_input_flag_t mustMatchFlag = AUDIO_INPUT_FLAG_MMAP_NOIRQ |
7637 AUDIO_INPUT_FLAG_HOTWORD_TAP | AUDIO_INPUT_FLAG_HW_LOOKBACK;
7638
7639 const underlying_input_flag_t oriFlags = flags;
Glenn Kasten730b9262018-03-29 15:01:26 -07007640
jiabin2fd710d2022-05-02 23:20:22 +00007641 for (;;) {
7642 sp<IOProfile> firstInexact = nullptr;
7643 uint32_t updatedSamplingRate = 0;
7644 audio_format_t updatedFormat = AUDIO_FORMAT_INVALID;
7645 audio_channel_mask_t updatedChannelMask = AUDIO_CHANNEL_INVALID;
7646 for (const auto& hwModule : mHwModules) {
7647 for (const auto& profile : hwModule->getInputProfiles()) {
7648 // profile->log();
7649 //updatedFormat = format;
7650 if (profile->isCompatibleProfile(DeviceVector(device), samplingRate,
7651 &samplingRate /*updatedSamplingRate*/,
7652 format,
7653 &format, /*updatedFormat*/
7654 channelMask,
7655 &channelMask /*updatedChannelMask*/,
7656 // FIXME ugly cast
7657 (audio_output_flags_t) flags,
7658 true /*exactMatchRequiredForInputFlags*/)) {
7659 return profile;
7660 }
7661 if (firstInexact == nullptr && profile->isCompatibleProfile(DeviceVector(device),
7662 samplingRate,
7663 &updatedSamplingRate,
7664 format,
7665 &updatedFormat,
7666 channelMask,
7667 &updatedChannelMask,
7668 // FIXME ugly cast
7669 (audio_output_flags_t) flags,
7670 false /*exactMatchRequiredForInputFlags*/)) {
7671 firstInexact = profile;
7672 }
7673 }
7674 }
7675
7676 if (firstInexact != nullptr) {
7677 samplingRate = updatedSamplingRate;
7678 format = updatedFormat;
7679 channelMask = updatedChannelMask;
7680 return firstInexact;
7681 } else if (flags & AUDIO_INPUT_FLAG_RAW) {
7682 flags = (audio_input_flags_t) (flags & ~AUDIO_INPUT_FLAG_RAW); // retry
7683 } else if ((flags & mustMatchFlag) == AUDIO_INPUT_FLAG_NONE &&
7684 flags != AUDIO_INPUT_FLAG_NONE && audio_is_linear_pcm(format)) {
7685 flags = AUDIO_INPUT_FLAG_NONE;
7686 } else { // fail
7687 ALOGW("%s could not find profile for device %s, sampling rate %u, format %#x, "
7688 "channel mask 0x%X, flags %#x", __func__, device->toString().c_str(),
7689 samplingRate, format, channelMask, oriFlags);
7690 break;
Eric Laurente552edb2014-03-10 17:42:56 -07007691 }
7692 }
jiabin2fd710d2022-05-02 23:20:22 +00007693
7694 return nullptr;
Eric Laurente552edb2014-03-10 17:42:56 -07007695}
7696
François Gaffieaaac0fd2018-11-22 17:56:39 +01007697float AudioPolicyManager::computeVolume(IVolumeCurves &curves,
7698 VolumeSource volumeSource,
François Gaffied1ab2bd2015-12-02 18:20:06 +01007699 int index,
jiabin9a3361e2019-10-01 09:38:30 -07007700 const DeviceTypeSet& deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07007701{
jiabin9a3361e2019-10-01 09:38:30 -07007702 float volumeDb = curves.volIndexToDb(Volume::getDeviceCategory(deviceTypes), index);
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07007703
7704 // handle the case of accessibility active while a ringtone is playing: if the ringtone is much
7705 // louder than the accessibility prompt, the prompt cannot be heard, thus masking the touch
7706 // exploration of the dialer UI. In this situation, bring the accessibility volume closer to
7707 // the ringtone volume
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007708 const auto callVolumeSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL, false);
7709 const auto ringVolumeSrc = toVolumeSource(AUDIO_STREAM_RING, false);
7710 const auto musicVolumeSrc = toVolumeSource(AUDIO_STREAM_MUSIC, false);
7711 const auto alarmVolumeSrc = toVolumeSource(AUDIO_STREAM_ALARM, false);
7712 const auto a11yVolumeSrc = toVolumeSource(AUDIO_STREAM_ACCESSIBILITY, false);
Oscar Azucena437ded52023-08-30 18:45:18 -07007713 // Verify that the current volume source is not the ringer volume to prevent recursively
7714 // calling to compute volume. This could happen in cases where a11y and ringer sounds belong
7715 // to the same volume group.
7716 if (volumeSource != ringVolumeSrc && volumeSource == a11yVolumeSrc
François Gaffieaaac0fd2018-11-22 17:56:39 +01007717 && (AUDIO_MODE_RINGTONE == mEngine->getPhoneState()) &&
7718 mOutputs.isActive(ringVolumeSrc, 0)) {
7719 auto &ringCurves = getVolumeCurves(AUDIO_STREAM_RING);
jiabin9a3361e2019-10-01 09:38:30 -07007720 const float ringVolumeDb = computeVolume(ringCurves, ringVolumeSrc, index, deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007721 return ringVolumeDb - 4 > volumeDb ? ringVolumeDb - 4 : volumeDb;
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07007722 }
7723
Eric Laurentdcd4ab12018-06-29 17:45:13 -07007724 // in-call: always cap volume by voice volume + some low headroom
François Gaffieaaac0fd2018-11-22 17:56:39 +01007725 if ((volumeSource != callVolumeSrc && (isInCall() ||
7726 mOutputs.isActiveLocally(callVolumeSrc))) &&
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007727 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM, false) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01007728 volumeSource == ringVolumeSrc || volumeSource == musicVolumeSrc ||
7729 volumeSource == alarmVolumeSrc ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007730 volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION, false) ||
7731 volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false) ||
7732 volumeSource == toVolumeSource(AUDIO_STREAM_DTMF, false) ||
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07007733 volumeSource == a11yVolumeSrc)) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007734 auto &voiceCurves = getVolumeCurves(callVolumeSrc);
jiabin9a3361e2019-10-01 09:38:30 -07007735 int voiceVolumeIndex = voiceCurves.getVolumeIndex(deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007736 const float maxVoiceVolDb =
jiabin9a3361e2019-10-01 09:38:30 -07007737 computeVolume(voiceCurves, callVolumeSrc, voiceVolumeIndex, deviceTypes)
Eric Laurent7731b5a2018-04-06 15:47:22 -07007738 + IN_CALL_EARPIECE_HEADROOM_DB;
Abhijith Shastry329ddab2019-04-23 11:53:26 -07007739 // FIXME: Workaround for call screening applications until a proper audio mode is defined
7740 // to support this scenario : Exempt the RING stream from the audio cap if the audio was
7741 // programmatically muted.
7742 // VOICE_CALL stream has minVolumeIndex > 0 : Users cannot set the volume of voice calls to
7743 // 0. We don't want to cap volume when the system has programmatically muted the voice call
7744 // stream. See setVolumeCurveIndex() for more information.
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07007745 bool exemptFromCapping =
7746 ((volumeSource == ringVolumeSrc) || (volumeSource == a11yVolumeSrc))
7747 && (voiceVolumeIndex == 0);
Abhijith Shastry329ddab2019-04-23 11:53:26 -07007748 ALOGV_IF(exemptFromCapping, "%s volume source %d at vol=%f not capped", __func__,
7749 volumeSource, volumeDb);
7750 if ((volumeDb > maxVoiceVolDb) && !exemptFromCapping) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007751 ALOGV("%s volume source %d at vol=%f overriden by volume group %d at vol=%f", __func__,
7752 volumeSource, volumeDb, callVolumeSrc, maxVoiceVolDb);
7753 volumeDb = maxVoiceVolDb;
Jean-Michel Trivi719a9872017-08-05 13:51:35 -07007754 }
7755 }
Eric Laurente552edb2014-03-10 17:42:56 -07007756 // if a headset is connected, apply the following rules to ring tones and notifications
7757 // to avoid sound level bursts in user's ears:
Eric Laurent6af1c1d2016-04-14 11:20:44 -07007758 // - always attenuate notifications volume by 6dB
7759 // - attenuate ring tones volume by 6dB unless music is not playing and
7760 // speaker is part of the select devices
Eric Laurente552edb2014-03-10 17:42:56 -07007761 // - if music is playing, always limit the volume to current music volume,
7762 // with a minimum threshold at -36dB so that notification is always perceived.
jiabin9a3361e2019-10-01 09:38:30 -07007763 if (!Intersection(deviceTypes,
7764 {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP, AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES,
7765 AUDIO_DEVICE_OUT_WIRED_HEADSET, AUDIO_DEVICE_OUT_WIRED_HEADPHONE,
Eric Laurentc42df452020-08-07 10:51:53 -07007766 AUDIO_DEVICE_OUT_USB_HEADSET, AUDIO_DEVICE_OUT_HEARING_AID,
7767 AUDIO_DEVICE_OUT_BLE_HEADSET}).empty() &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01007768 ((volumeSource == alarmVolumeSrc ||
7769 volumeSource == ringVolumeSrc) ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007770 (volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION, false)) ||
7771 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM, false)) ||
7772 ((volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false)) &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01007773 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) &&
7774 curves.canBeMuted()) {
7775
Eric Laurente552edb2014-03-10 17:42:56 -07007776 // when the phone is ringing we must consider that music could have been paused just before
7777 // by the music application and behave as if music was active if the last music track was
7778 // just stopped
Oscar Azucena437ded52023-08-30 18:45:18 -07007779 // Verify that the current volume source is not the music volume to prevent recursively
7780 // calling to compute volume. This could happen in cases where music and
7781 // (alarm, ring, notification, system, etc.) sounds belong to the same volume group.
7782 if (volumeSource != musicVolumeSrc &&
7783 (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY)
7784 || mLimitRingtoneVolume)) {
François Gaffie43c73442018-11-08 08:21:55 +01007785 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
jiabin9a3361e2019-10-01 09:38:30 -07007786 DeviceTypeSet musicDevice =
François Gaffiec005e562018-11-06 15:04:49 +01007787 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
7788 nullptr, true /*fromCache*/).types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01007789 auto &musicCurves = getVolumeCurves(AUDIO_STREAM_MUSIC);
jiabin9a3361e2019-10-01 09:38:30 -07007790 float musicVolDb = computeVolume(musicCurves,
7791 musicVolumeSrc,
7792 musicCurves.getVolumeIndex(musicDevice),
7793 musicDevice);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007794 float minVolDb = (musicVolDb > SONIFICATION_HEADSET_VOLUME_MIN_DB) ?
7795 musicVolDb : SONIFICATION_HEADSET_VOLUME_MIN_DB;
7796 if (volumeDb > minVolDb) {
7797 volumeDb = minVolDb;
7798 ALOGV("computeVolume limiting volume to %f musicVol %f", minVolDb, musicVolDb);
Eric Laurente552edb2014-03-10 17:42:56 -07007799 }
Eric Laurent7b6385c2021-05-12 17:55:36 +02007800 if (Volume::getDeviceForVolume(deviceTypes) != AUDIO_DEVICE_OUT_SPEAKER
7801 && !Intersection(deviceTypes, {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP,
7802 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES}).empty()) {
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07007803 // on A2DP, also ensure notification volume is not too low compared to media when
7804 // intended to be played
François Gaffie43c73442018-11-08 08:21:55 +01007805 if ((volumeDb > -96.0f) &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01007806 (musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB > volumeDb)) {
jiabin9a3361e2019-10-01 09:38:30 -07007807 ALOGV("%s increasing volume for volume source=%d device=%s from %f to %f",
7808 __func__, volumeSource, dumpDeviceTypes(deviceTypes).c_str(), volumeDb,
François Gaffieaaac0fd2018-11-22 17:56:39 +01007809 musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB);
7810 volumeDb = musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB;
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07007811 }
7812 }
jiabin9a3361e2019-10-01 09:38:30 -07007813 } else if ((Volume::getDeviceForVolume(deviceTypes) != AUDIO_DEVICE_OUT_SPEAKER) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01007814 (!(volumeSource == alarmVolumeSrc || volumeSource == ringVolumeSrc))) {
François Gaffie43c73442018-11-08 08:21:55 +01007815 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07007816 }
7817 }
7818
François Gaffie43c73442018-11-08 08:21:55 +01007819 return volumeDb;
Eric Laurente552edb2014-03-10 17:42:56 -07007820}
7821
Eric Laurent3839bc02018-07-10 18:33:34 -07007822int AudioPolicyManager::rescaleVolumeIndex(int srcIndex,
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01007823 VolumeSource fromVolumeSource,
7824 VolumeSource toVolumeSource)
Eric Laurent3839bc02018-07-10 18:33:34 -07007825{
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01007826 if (fromVolumeSource == toVolumeSource) {
Eric Laurent3839bc02018-07-10 18:33:34 -07007827 return srcIndex;
7828 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01007829 auto &srcCurves = getVolumeCurves(fromVolumeSource);
7830 auto &dstCurves = getVolumeCurves(toVolumeSource);
Eric Laurentf5aa58d2019-02-22 18:20:11 -08007831 float minSrc = (float)srcCurves.getVolumeIndexMin();
7832 float maxSrc = (float)srcCurves.getVolumeIndexMax();
7833 float minDst = (float)dstCurves.getVolumeIndexMin();
7834 float maxDst = (float)dstCurves.getVolumeIndexMax();
Eric Laurent3839bc02018-07-10 18:33:34 -07007835
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08007836 // preserve mute request or correct range
7837 if (srcIndex < minSrc) {
7838 if (srcIndex == 0) {
7839 return 0;
7840 }
7841 srcIndex = minSrc;
7842 } else if (srcIndex > maxSrc) {
7843 srcIndex = maxSrc;
7844 }
Eric Laurent3839bc02018-07-10 18:33:34 -07007845 return (int)(minDst + ((srcIndex - minSrc) * (maxDst - minDst)) / (maxSrc - minSrc));
7846}
7847
François Gaffieaaac0fd2018-11-22 17:56:39 +01007848status_t AudioPolicyManager::checkAndSetVolume(IVolumeCurves &curves,
7849 VolumeSource volumeSource,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08007850 int index,
7851 const sp<AudioOutputDescriptor>& outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07007852 DeviceTypeSet deviceTypes,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08007853 int delayMs,
7854 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07007855{
François Gaffieaaac0fd2018-11-22 17:56:39 +01007856 // do not change actual attributes volume if the attributes is muted
7857 if (outputDesc->isMuted(volumeSource)) {
7858 ALOGVV("%s: volume source %d muted count %d active=%d", __func__, volumeSource,
7859 outputDesc->getMuteCount(volumeSource), outputDesc->isActive(volumeSource));
Eric Laurente552edb2014-03-10 17:42:56 -07007860 return NO_ERROR;
7861 }
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007862 VolumeSource callVolSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL, false);
7863 VolumeSource btScoVolSrc = toVolumeSource(AUDIO_STREAM_BLUETOOTH_SCO, false);
7864 bool isVoiceVolSrc = (volumeSource != VOLUME_SOURCE_NONE) && (callVolSrc == volumeSource);
7865 bool isBtScoVolSrc = (volumeSource != VOLUME_SOURCE_NONE) && (btScoVolSrc == volumeSource);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007866
Eric Laurent2517af32020-11-25 15:31:27 +01007867 bool isScoRequested = isScoRequestedForComm();
Eric Laurent1a8b45f2022-04-13 16:01:47 +02007868 bool isHAUsed = isHearingAidUsedForComm();
7869
Eric Laurente552edb2014-03-10 17:42:56 -07007870 // do not change in call volume if bluetooth is connected and vice versa
François Gaffieaaac0fd2018-11-22 17:56:39 +01007871 // if sco and call follow same curves, bypass forceUseForComm
7872 if ((callVolSrc != btScoVolSrc) &&
Eric Laurent2517af32020-11-25 15:31:27 +01007873 ((isVoiceVolSrc && isScoRequested) ||
Beibeif660a512023-02-28 17:00:34 +08007874 (isBtScoVolSrc && !(isScoRequested || isHAUsed))) &&
7875 !isSingleDeviceType(deviceTypes, AUDIO_DEVICE_OUT_TELEPHONY_TX)) {
Eric Laurent2517af32020-11-25 15:31:27 +01007876 ALOGV("%s cannot set volume group %d volume when is%srequested for comm", __func__,
Eric Laurent1a8b45f2022-04-13 16:01:47 +02007877 volumeSource, isScoRequested ? " " : " not ");
Eric Laurent571ef962020-07-24 11:43:48 -07007878 // Do not return an error here as AudioService will always set both voice call
7879 // and bluetooth SCO volumes due to stream aliasing.
7880 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07007881 }
jiabin9a3361e2019-10-01 09:38:30 -07007882 if (deviceTypes.empty()) {
7883 deviceTypes = outputDesc->devices().types();
chenxin2080986da2023-07-17 11:45:21 +08007884 index = curves.getVolumeIndex(deviceTypes);
7885 ALOGD("%s if deviceTypes is change from none to device %s, need get index %d",
7886 __func__, dumpDeviceTypes(deviceTypes).c_str(), index);
Eric Laurentc75307b2015-03-17 15:29:32 -07007887 }
Eric Laurent275e8e92014-11-30 15:14:47 -08007888
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00007889 if (curves.getVolumeIndexMin() < 0 || curves.getVolumeIndexMax() < 0) {
7890 ALOGE("invalid volume index range");
7891 return BAD_VALUE;
7892 }
7893
jiabin9a3361e2019-10-01 09:38:30 -07007894 float volumeDb = computeVolume(curves, volumeSource, index, deviceTypes);
7895 if (outputDesc->isFixedVolume(deviceTypes) ||
Eric Laurent9698a4c2020-10-12 17:10:23 -07007896 // Force VoIP volume to max for bluetooth SCO device except if muted
7897 (index != 0 && (isVoiceVolSrc || isBtScoVolSrc) &&
jiabin9a3361e2019-10-01 09:38:30 -07007898 isSingleDeviceType(deviceTypes, audio_is_bluetooth_out_sco_device))) {
Eric Laurentffbc80f2015-03-18 18:30:19 -07007899 volumeDb = 0.0f;
Eric Laurent275e8e92014-11-30 15:14:47 -08007900 }
Francois Gaffie593634d2021-06-22 13:31:31 +02007901 const bool muted = (index == 0) && (volumeDb != 0.0f);
Eric Laurent31a428a2023-08-11 12:16:28 +02007902 outputDesc->setVolume(volumeDb, muted, volumeSource, curves.getStreamTypes(),
7903 deviceTypes, delayMs, force, isVoiceVolSrc);
Eric Laurentc75307b2015-03-17 15:29:32 -07007904
Eric Laurente8f2c0f2021-08-17 11:17:19 +02007905 if (outputDesc == mPrimaryOutput && (isVoiceVolSrc || isBtScoVolSrc)) {
Eric Laurente552edb2014-03-10 17:42:56 -07007906 float voiceVolume;
Eric Laurentfad001d2019-06-11 19:17:57 -07007907 // 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 +01007908 if (isVoiceVolSrc) {
7909 voiceVolume = (float)index/(float)curves.getVolumeIndexMax();
Eric Laurente552edb2014-03-10 17:42:56 -07007910 } else {
Eric Laurentfad001d2019-06-11 19:17:57 -07007911 voiceVolume = index == 0 ? 0.0 : 1.0;
Eric Laurente552edb2014-03-10 17:42:56 -07007912 }
Eric Laurent18fba842016-03-31 14:41:26 -07007913 if (voiceVolume != mLastVoiceVolume) {
Eric Laurente552edb2014-03-10 17:42:56 -07007914 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
7915 mLastVoiceVolume = voiceVolume;
7916 }
7917 }
Eric Laurente552edb2014-03-10 17:42:56 -07007918 return NO_ERROR;
7919}
7920
Eric Laurentc75307b2015-03-17 15:29:32 -07007921void AudioPolicyManager::applyStreamVolumes(const sp<AudioOutputDescriptor>& outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07007922 const DeviceTypeSet& deviceTypes,
7923 int delayMs,
7924 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07007925{
jiabincd510522020-01-22 09:40:55 -08007926 ALOGVV("applyStreamVolumes() for device %s", dumpDeviceTypes(deviceTypes).c_str());
François Gaffieaaac0fd2018-11-22 17:56:39 +01007927 for (const auto &volumeGroup : mEngine->getVolumeGroups()) {
7928 auto &curves = getVolumeCurves(toVolumeSource(volumeGroup));
7929 checkAndSetVolume(curves, toVolumeSource(volumeGroup),
jiabin9a3361e2019-10-01 09:38:30 -07007930 curves.getVolumeIndex(deviceTypes),
7931 outputDesc, deviceTypes, delayMs, force);
Eric Laurente552edb2014-03-10 17:42:56 -07007932 }
7933}
7934
François Gaffiec005e562018-11-06 15:04:49 +01007935void AudioPolicyManager::setStrategyMute(product_strategy_t strategy,
7936 bool on,
7937 const sp<AudioOutputDescriptor>& outputDesc,
7938 int delayMs,
jiabin9a3361e2019-10-01 09:38:30 -07007939 DeviceTypeSet deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07007940{
François Gaffieaaac0fd2018-11-22 17:56:39 +01007941 std::vector<VolumeSource> sourcesToMute;
7942 for (auto attributes: mEngine->getAllAttributesForProductStrategy(strategy)) {
7943 ALOGVV("%s() attributes %s, mute %d, output ID %d", __func__,
7944 toString(attributes).c_str(), on, outputDesc->getId());
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007945 VolumeSource source = toVolumeSource(attributes, false);
7946 if ((source != VOLUME_SOURCE_NONE) &&
7947 (std::find(begin(sourcesToMute), end(sourcesToMute), source)
7948 == end(sourcesToMute))) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007949 sourcesToMute.push_back(source);
7950 }
Eric Laurente552edb2014-03-10 17:42:56 -07007951 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01007952 for (auto source : sourcesToMute) {
jiabin9a3361e2019-10-01 09:38:30 -07007953 setVolumeSourceMute(source, on, outputDesc, delayMs, deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007954 }
7955
Eric Laurente552edb2014-03-10 17:42:56 -07007956}
7957
François Gaffieaaac0fd2018-11-22 17:56:39 +01007958void AudioPolicyManager::setVolumeSourceMute(VolumeSource volumeSource,
7959 bool on,
7960 const sp<AudioOutputDescriptor>& outputDesc,
7961 int delayMs,
jiabin9a3361e2019-10-01 09:38:30 -07007962 DeviceTypeSet deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07007963{
jiabin9a3361e2019-10-01 09:38:30 -07007964 if (deviceTypes.empty()) {
7965 deviceTypes = outputDesc->devices().types();
Eric Laurente552edb2014-03-10 17:42:56 -07007966 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01007967 auto &curves = getVolumeCurves(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07007968 if (on) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007969 if (!outputDesc->isMuted(volumeSource)) {
Eric Laurentf5aa58d2019-02-22 18:20:11 -08007970 if (curves.canBeMuted() &&
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007971 (volumeSource != toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01007972 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) ==
7973 AUDIO_POLICY_FORCE_NONE))) {
jiabin9a3361e2019-10-01 09:38:30 -07007974 checkAndSetVolume(curves, volumeSource, 0, outputDesc, deviceTypes, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07007975 }
7976 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01007977 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not
7978 // ignored
7979 outputDesc->incMuteCount(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07007980 } else {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007981 if (!outputDesc->isMuted(volumeSource)) {
7982 ALOGV("%s unmuting non muted attributes!", __func__);
Eric Laurente552edb2014-03-10 17:42:56 -07007983 return;
7984 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01007985 if (outputDesc->decMuteCount(volumeSource) == 0) {
7986 checkAndSetVolume(curves, volumeSource,
jiabin9a3361e2019-10-01 09:38:30 -07007987 curves.getVolumeIndex(deviceTypes),
Eric Laurentc75307b2015-03-17 15:29:32 -07007988 outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07007989 deviceTypes,
Eric Laurente552edb2014-03-10 17:42:56 -07007990 delayMs);
7991 }
7992 }
7993}
7994
François Gaffie53615e22015-03-19 09:24:12 +01007995bool AudioPolicyManager::isValidAttributes(const audio_attributes_t *paa)
7996{
François Gaffiec005e562018-11-06 15:04:49 +01007997 // has flags that map to a stream type?
Eric Laurente83b55d2014-11-14 10:06:21 -08007998 if ((paa->flags & (AUDIO_FLAG_AUDIBILITY_ENFORCED | AUDIO_FLAG_SCO | AUDIO_FLAG_BEACON)) != 0) {
7999 return true;
8000 }
8001
8002 // has known usage?
8003 switch (paa->usage) {
8004 case AUDIO_USAGE_UNKNOWN:
8005 case AUDIO_USAGE_MEDIA:
8006 case AUDIO_USAGE_VOICE_COMMUNICATION:
8007 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
8008 case AUDIO_USAGE_ALARM:
8009 case AUDIO_USAGE_NOTIFICATION:
8010 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
8011 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
8012 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
8013 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
8014 case AUDIO_USAGE_NOTIFICATION_EVENT:
8015 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
8016 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
8017 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
8018 case AUDIO_USAGE_GAME:
Eric Laurent275e8e92014-11-30 15:14:47 -08008019 case AUDIO_USAGE_VIRTUAL_SOURCE:
Jean-Michel Trivi36867762016-12-29 12:03:28 -08008020 case AUDIO_USAGE_ASSISTANT:
Eric Laurent21777f82019-12-06 18:12:06 -08008021 case AUDIO_USAGE_CALL_ASSISTANT:
Hayden Gomes524159d2019-12-23 14:41:47 -08008022 case AUDIO_USAGE_EMERGENCY:
8023 case AUDIO_USAGE_SAFETY:
8024 case AUDIO_USAGE_VEHICLE_STATUS:
8025 case AUDIO_USAGE_ANNOUNCEMENT:
Eric Laurente83b55d2014-11-14 10:06:21 -08008026 break;
8027 default:
8028 return false;
8029 }
8030 return true;
8031}
8032
François Gaffie2110e042015-03-24 08:41:51 +01008033audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
8034{
8035 return mEngine->getForceUse(usage);
8036}
8037
Eric Laurent96d1dda2022-03-14 17:14:19 +01008038bool AudioPolicyManager::isInCall() const {
François Gaffie2110e042015-03-24 08:41:51 +01008039 return isStateInCall(mEngine->getPhoneState());
8040}
8041
Eric Laurent96d1dda2022-03-14 17:14:19 +01008042bool AudioPolicyManager::isStateInCall(int state) const {
François Gaffie2110e042015-03-24 08:41:51 +01008043 return is_state_in_call(state);
8044}
8045
Eric Laurentf9cccec2022-11-16 19:12:00 +01008046bool AudioPolicyManager::isCallAudioAccessible() const {
Eric Laurent74b71512019-11-06 17:21:57 -08008047 audio_mode_t mode = mEngine->getPhoneState();
8048 return (mode == AUDIO_MODE_IN_CALL)
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01008049 || (mode == AUDIO_MODE_CALL_SCREEN)
8050 || (mode == AUDIO_MODE_CALL_REDIRECT);
Eric Laurent74b71512019-11-06 17:21:57 -08008051}
8052
Eric Laurentf9cccec2022-11-16 19:12:00 +01008053bool AudioPolicyManager::isInCallOrScreening() const {
8054 audio_mode_t mode = mEngine->getPhoneState();
8055 return isStateInCall(mode) || mode == AUDIO_MODE_CALL_SCREEN;
8056}
8057
Eric Laurentd60560a2015-04-10 11:31:20 -07008058void AudioPolicyManager::cleanUpForDevice(const sp<DeviceDescriptor>& deviceDesc)
8059{
8060 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07008061 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008062 if (sourceDesc->isConnected() && (sourceDesc->srcDevice()->equals(deviceDesc) ||
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02008063 sourceDesc->sinkDevice()->equals(deviceDesc))
8064 && !isCallRxAudioSource(sourceDesc)) {
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008065 disconnectAudioSource(sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07008066 }
8067 }
8068
8069 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
8070 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
8071 bool release = false;
8072 for (size_t j = 0; j < patchDesc->mPatch.num_sources && !release; j++) {
8073 const struct audio_port_config *source = &patchDesc->mPatch.sources[j];
8074 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
8075 source->ext.device.type == deviceDesc->type()) {
8076 release = true;
8077 }
8078 }
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008079 const char *address = deviceDesc->address().c_str();
Eric Laurentd60560a2015-04-10 11:31:20 -07008080 for (size_t j = 0; j < patchDesc->mPatch.num_sinks && !release; j++) {
8081 const struct audio_port_config *sink = &patchDesc->mPatch.sinks[j];
8082 if (sink->type == AUDIO_PORT_TYPE_DEVICE &&
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008083 sink->ext.device.type == deviceDesc->type() &&
8084 (strnlen(address, AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0
8085 || strncmp(sink->ext.device.address, address,
8086 AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0)) {
Eric Laurentd60560a2015-04-10 11:31:20 -07008087 release = true;
8088 }
8089 }
8090 if (release) {
François Gaffieafd4cea2019-11-18 15:50:22 +01008091 ALOGV("%s releasing patch %u", __FUNCTION__, patchDesc->getHandle());
8092 releaseAudioPatch(patchDesc->getHandle(), patchDesc->getUid());
Eric Laurentd60560a2015-04-10 11:31:20 -07008093 }
8094 }
Francois Gaffie716e1432019-01-14 16:58:59 +01008095
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01008096 mInputs.clearSessionRoutesForDevice(deviceDesc);
8097
Francois Gaffie716e1432019-01-14 16:58:59 +01008098 mHwModules.cleanUpForDevice(deviceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07008099}
8100
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008101void AudioPolicyManager::modifySurroundFormats(
8102 const sp<DeviceDescriptor>& devDesc, FormatVector *formatsPtr) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008103 std::unordered_set<audio_format_t> enforcedSurround(
8104 devDesc->encodedFormats().begin(), devDesc->encodedFormats().end());
Mikhail Naganov100f0122018-11-29 11:22:16 -08008105 std::unordered_set<audio_format_t> allSurround; // A flat set of all known surround formats
Mikhail Naganov68e3f642023-04-28 13:06:32 -07008106 for (const auto& pair : mConfig->getSurroundFormats()) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008107 allSurround.insert(pair.first);
8108 for (const auto& subformat : pair.second) allSurround.insert(subformat);
8109 }
Phil Burk09bc4612016-02-24 15:58:15 -08008110
8111 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
8112 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Phil Burk0709b0a2016-03-31 12:54:57 -07008113 ALOGD("%s: forced use = %d", __FUNCTION__, forceUse);
Mikhail Naganov100f0122018-11-29 11:22:16 -08008114 // This is the resulting set of formats depending on the surround mode:
8115 // 'all surround' = allSurround
8116 // 'enforced surround' = enforcedSurround [may include IEC69137 which isn't raw surround fmt]
8117 // 'non-surround' = not in 'all surround' and not in 'enforced surround'
8118 // 'manual surround' = mManualSurroundFormats
8119 // AUTO: formats v 'enforced surround'
8120 // ALWAYS: formats v 'all surround' v 'enforced surround'
8121 // NEVER: formats ^ 'non-surround'
8122 // MANUAL: formats ^ ('non-surround' v 'manual surround' v (IEC69137 ^ 'enforced surround'))
Phil Burk09bc4612016-02-24 15:58:15 -08008123
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008124 std::unordered_set<audio_format_t> formatSet;
8125 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL
8126 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008127 // formatSet is (formats ^ 'non-surround')
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008128 for (auto formatIter = formatsPtr->begin(); formatIter != formatsPtr->end(); ++formatIter) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008129 if (allSurround.count(*formatIter) == 0 && enforcedSurround.count(*formatIter) == 0) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008130 formatSet.insert(*formatIter);
8131 }
8132 }
8133 } else {
8134 formatSet.insert(formatsPtr->begin(), formatsPtr->end());
8135 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08008136 formatsPtr->clear(); // Re-filled from the formatSet at the end.
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008137
jiabin81772902018-04-02 17:52:27 -07008138 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008139 formatSet.insert(mManualSurroundFormats.begin(), mManualSurroundFormats.end());
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008140 // Enable IEC61937 when in MANUAL mode if it's enforced for this device.
8141 if (enforcedSurround.count(AUDIO_FORMAT_IEC61937) != 0) {
8142 formatSet.insert(AUDIO_FORMAT_IEC61937);
Phil Burk09bc4612016-02-24 15:58:15 -08008143 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08008144 } else if (forceUse != AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) { // AUTO or ALWAYS
8145 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS) {
8146 formatSet.insert(allSurround.begin(), allSurround.end());
Phil Burk07ac1142016-03-25 13:39:29 -07008147 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08008148 formatSet.insert(enforcedSurround.begin(), enforcedSurround.end());
Phil Burk09bc4612016-02-24 15:58:15 -08008149 }
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008150 for (const auto& format : formatSet) {
jiabin06e4bab2019-07-29 10:13:34 -07008151 formatsPtr->push_back(format);
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008152 }
Phil Burk0709b0a2016-03-31 12:54:57 -07008153}
8154
jiabin06e4bab2019-07-29 10:13:34 -07008155void AudioPolicyManager::modifySurroundChannelMasks(ChannelMaskSet *channelMasksPtr) {
8156 ChannelMaskSet &channelMasks = *channelMasksPtr;
Phil Burk0709b0a2016-03-31 12:54:57 -07008157 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
8158 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
8159
8160 // If NEVER, then remove support for channelMasks > stereo.
8161 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
jiabin06e4bab2019-07-29 10:13:34 -07008162 for (auto it = channelMasks.begin(); it != channelMasks.end();) {
8163 audio_channel_mask_t channelMask = *it;
Phil Burk0709b0a2016-03-31 12:54:57 -07008164 if (channelMask & ~AUDIO_CHANNEL_OUT_STEREO) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01008165 ALOGV("%s: force NEVER, so remove channelMask 0x%08x", __FUNCTION__, channelMask);
jiabin06e4bab2019-07-29 10:13:34 -07008166 it = channelMasks.erase(it);
Phil Burk0709b0a2016-03-31 12:54:57 -07008167 } else {
jiabin06e4bab2019-07-29 10:13:34 -07008168 ++it;
Phil Burk0709b0a2016-03-31 12:54:57 -07008169 }
8170 }
jiabin81772902018-04-02 17:52:27 -07008171 // If ALWAYS or MANUAL, then make sure we at least support 5.1
8172 } else if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS
8173 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Phil Burk0709b0a2016-03-31 12:54:57 -07008174 bool supports5dot1 = false;
8175 // Are there any channel masks that can be considered "surround"?
Mikhail Naganovcf84e592017-12-07 11:25:11 -08008176 for (audio_channel_mask_t channelMask : channelMasks) {
Phil Burk0709b0a2016-03-31 12:54:57 -07008177 if ((channelMask & AUDIO_CHANNEL_OUT_5POINT1) == AUDIO_CHANNEL_OUT_5POINT1) {
8178 supports5dot1 = true;
8179 break;
8180 }
8181 }
8182 // If not then add 5.1 support.
8183 if (!supports5dot1) {
jiabin06e4bab2019-07-29 10:13:34 -07008184 channelMasks.insert(AUDIO_CHANNEL_OUT_5POINT1);
Eric Laurentfecbceb2021-02-09 14:46:43 +01008185 ALOGV("%s: force MANUAL or ALWAYS, so adding channelMask for 5.1 surround", __func__);
Phil Burk0709b0a2016-03-31 12:54:57 -07008186 }
Phil Burk09bc4612016-02-24 15:58:15 -08008187 }
8188}
8189
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008190void AudioPolicyManager::updateAudioProfiles(const sp<DeviceDescriptor>& devDesc,
Phil Burk00eeb322016-03-31 12:41:00 -07008191 audio_io_handle_t ioHandle,
François Gaffie112b0af2015-11-19 16:13:25 +01008192 AudioProfileVector &profiles)
8193{
8194 String8 reply;
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008195 audio_devices_t device = devDesc->type();
Phil Burk0709b0a2016-03-31 12:54:57 -07008196
François Gaffie112b0af2015-11-19 16:13:25 +01008197 // Format MUST be checked first to update the list of AudioProfile
8198 if (profiles.hasDynamicFormat()) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07008199 reply = mpClientInterface->getParameters(
8200 ioHandle, String8(AudioParameter::keyStreamSupportedFormats));
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00008201 ALOGV("%s: supported formats %d, %s", __FUNCTION__, ioHandle, reply.c_str());
Eric Laurent62e4bc52016-02-02 18:37:28 -08008202 AudioParameter repliedParameters(reply);
jiabinf26596b2023-04-12 18:56:39 +00008203 FormatVector formats;
Eric Laurent62e4bc52016-02-02 18:37:28 -08008204 if (repliedParameters.get(
jiabinf26596b2023-04-12 18:56:39 +00008205 String8(AudioParameter::keyStreamSupportedFormats), reply) == NO_ERROR) {
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00008206 formats = formatsFromString(reply.c_str());
jiabinf26596b2023-04-12 18:56:39 +00008207 } else if (devDesc->hasValidAudioProfile()) {
8208 ALOGD("%s: using the device profiles", __func__);
8209 formats = devDesc->getAudioProfiles().getSupportedFormats();
8210 } else {
8211 ALOGE("%s: failed to retrieve format, bailing out", __func__);
François Gaffie112b0af2015-11-19 16:13:25 +01008212 return;
8213 }
Kriti Dangef6be8f2020-11-05 11:58:19 +01008214 mReportedFormatsMap[devDesc] = formats;
Mikhail Naganov100f0122018-11-29 11:22:16 -08008215 if (device == AUDIO_DEVICE_OUT_HDMI
8216 || isDeviceOfModule(devDesc, AUDIO_HARDWARE_MODULE_ID_MSD)) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008217 modifySurroundFormats(devDesc, &formats);
Phil Burk00eeb322016-03-31 12:41:00 -07008218 }
jiabin3e277cc2019-09-10 14:27:34 -07008219 addProfilesForFormats(profiles, formats);
François Gaffie112b0af2015-11-19 16:13:25 +01008220 }
François Gaffie112b0af2015-11-19 16:13:25 +01008221
Mikhail Naganovcf84e592017-12-07 11:25:11 -08008222 for (audio_format_t format : profiles.getSupportedFormats()) {
jiabinf26596b2023-04-12 18:56:39 +00008223 std::optional<ChannelMaskSet> channelMasks;
jiabin06e4bab2019-07-29 10:13:34 -07008224 SampleRateSet samplingRates;
François Gaffie112b0af2015-11-19 16:13:25 +01008225 AudioParameter requestedParameters;
Mikhail Naganov388360c2016-10-17 17:09:41 -07008226 requestedParameters.addInt(String8(AudioParameter::keyFormat), format);
François Gaffie112b0af2015-11-19 16:13:25 +01008227
8228 if (profiles.hasDynamicRateFor(format)) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07008229 reply = mpClientInterface->getParameters(
8230 ioHandle,
8231 requestedParameters.toString() + ";" +
8232 AudioParameter::keyStreamSupportedSamplingRates);
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00008233 ALOGV("%s: supported sampling rates %s", __FUNCTION__, reply.c_str());
Eric Laurent62e4bc52016-02-02 18:37:28 -08008234 AudioParameter repliedParameters(reply);
8235 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07008236 String8(AudioParameter::keyStreamSupportedSamplingRates), reply) == NO_ERROR) {
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00008237 samplingRates = samplingRatesFromString(reply.c_str());
jiabinf26596b2023-04-12 18:56:39 +00008238 } else {
8239 samplingRates = devDesc->getAudioProfiles().getSampleRatesFor(format);
François Gaffie112b0af2015-11-19 16:13:25 +01008240 }
8241 }
8242 if (profiles.hasDynamicChannelsFor(format)) {
8243 reply = mpClientInterface->getParameters(ioHandle,
8244 requestedParameters.toString() + ";" +
Mikhail Naganov388360c2016-10-17 17:09:41 -07008245 AudioParameter::keyStreamSupportedChannels);
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00008246 ALOGV("%s: supported channel masks %s", __FUNCTION__, reply.c_str());
Eric Laurent62e4bc52016-02-02 18:37:28 -08008247 AudioParameter repliedParameters(reply);
8248 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07008249 String8(AudioParameter::keyStreamSupportedChannels), reply) == NO_ERROR) {
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00008250 channelMasks = channelMasksFromString(reply.c_str());
jiabinf26596b2023-04-12 18:56:39 +00008251 } else {
8252 channelMasks = devDesc->getAudioProfiles().getChannelMasksFor(format);
8253 }
8254 if (channelMasks.has_value() && (device == AUDIO_DEVICE_OUT_HDMI
8255 || isDeviceOfModule(devDesc, AUDIO_HARDWARE_MODULE_ID_MSD))) {
8256 modifySurroundChannelMasks(&channelMasks.value());
François Gaffie112b0af2015-11-19 16:13:25 +01008257 }
8258 }
jiabin3e277cc2019-09-10 14:27:34 -07008259 addDynamicAudioProfileAndSort(
jiabinf26596b2023-04-12 18:56:39 +00008260 profiles, new AudioProfile(
8261 format, channelMasks.value_or(ChannelMaskSet()), samplingRates));
François Gaffie112b0af2015-11-19 16:13:25 +01008262 }
8263}
Eric Laurentd60560a2015-04-10 11:31:20 -07008264
Mikhail Naganovdc769682018-05-04 15:34:08 -07008265status_t AudioPolicyManager::installPatch(const char *caller,
8266 audio_patch_handle_t *patchHandle,
8267 AudioIODescriptorInterface *ioDescriptor,
8268 const struct audio_patch *patch,
8269 int delayMs)
8270{
8271 ssize_t index = mAudioPatches.indexOfKey(
8272 patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE ?
8273 *patchHandle : ioDescriptor->getPatchHandle());
8274 sp<AudioPatch> patchDesc;
8275 status_t status = installPatch(
8276 caller, index, patchHandle, patch, delayMs, mUidCached, &patchDesc);
8277 if (status == NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01008278 ioDescriptor->setPatchHandle(patchDesc->getHandle());
Mikhail Naganovdc769682018-05-04 15:34:08 -07008279 }
8280 return status;
8281}
8282
8283status_t AudioPolicyManager::installPatch(const char *caller,
8284 ssize_t index,
8285 audio_patch_handle_t *patchHandle,
8286 const struct audio_patch *patch,
8287 int delayMs,
8288 uid_t uid,
8289 sp<AudioPatch> *patchDescPtr)
8290{
8291 sp<AudioPatch> patchDesc;
8292 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
8293 if (index >= 0) {
8294 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01008295 afPatchHandle = patchDesc->getAfHandle();
Mikhail Naganovdc769682018-05-04 15:34:08 -07008296 }
8297
8298 status_t status = mpClientInterface->createAudioPatch(patch, &afPatchHandle, delayMs);
8299 ALOGV("%s() AF::createAudioPatch returned %d patchHandle %d num_sources %d num_sinks %d",
8300 caller, status, afPatchHandle, patch->num_sources, patch->num_sinks);
8301 if (status == NO_ERROR) {
8302 if (index < 0) {
8303 patchDesc = new AudioPatch(patch, uid);
François Gaffieafd4cea2019-11-18 15:50:22 +01008304 addAudioPatch(patchDesc->getHandle(), patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07008305 } else {
8306 patchDesc->mPatch = *patch;
8307 }
François Gaffieafd4cea2019-11-18 15:50:22 +01008308 patchDesc->setAfHandle(afPatchHandle);
Mikhail Naganovdc769682018-05-04 15:34:08 -07008309 if (patchHandle) {
François Gaffieafd4cea2019-11-18 15:50:22 +01008310 *patchHandle = patchDesc->getHandle();
Mikhail Naganovdc769682018-05-04 15:34:08 -07008311 }
8312 nextAudioPortGeneration();
8313 mpClientInterface->onAudioPatchListUpdate();
8314 }
8315 if (patchDescPtr) *patchDescPtr = patchDesc;
8316 return status;
8317}
8318
jiabinbce0c1d2020-10-05 11:20:18 -07008319bool AudioPolicyManager::areAllActiveTracksRerouted(const sp<SwAudioOutputDescriptor>& output)
8320{
8321 const TrackClientVector activeClients = output->getActiveClients();
8322 if (activeClients.empty()) {
8323 return true;
8324 }
8325 ssize_t index = mAudioPatches.indexOfKey(output->getPatchHandle());
8326 if (index < 0) {
8327 ALOGE("%s, no audio patch found while there are active clients on output %d",
8328 __func__, output->getId());
8329 return false;
8330 }
8331 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
8332 DeviceVector routedDevices;
8333 for (int i = 0; i < patchDesc->mPatch.num_sinks; ++i) {
8334 sp<DeviceDescriptor> device = mAvailableOutputDevices.getDeviceFromId(
8335 patchDesc->mPatch.sinks[i].id);
8336 if (device == nullptr) {
8337 ALOGE("%s, no audio device found with id(%d)",
8338 __func__, patchDesc->mPatch.sinks[i].id);
8339 return false;
8340 }
8341 routedDevices.add(device);
8342 }
8343 for (const auto& client : activeClients) {
jiabin49256852022-03-09 11:21:35 -08008344 if (client->isInvalid()) {
8345 // No need to take care about invalidated clients.
8346 continue;
8347 }
jiabinbce0c1d2020-10-05 11:20:18 -07008348 sp<DeviceDescriptor> preferredDevice =
8349 mAvailableOutputDevices.getDeviceFromId(client->preferredDeviceId());
8350 if (mEngine->getOutputDevicesForAttributes(
8351 client->attributes(), preferredDevice, false) == routedDevices) {
8352 return false;
8353 }
8354 }
8355 return true;
8356}
8357
8358sp<SwAudioOutputDescriptor> AudioPolicyManager::openOutputWithProfileAndDevice(
Eric Laurentb4f42a92022-01-17 17:37:31 +01008359 const sp<IOProfile>& profile, const DeviceVector& devices,
jiabina84c3d32022-12-02 18:59:55 +00008360 const audio_config_base_t *mixerConfig, const audio_config_t *halConfig,
8361 audio_output_flags_t flags)
jiabinbce0c1d2020-10-05 11:20:18 -07008362{
8363 for (const auto& device : devices) {
8364 // TODO: This should be checking if the profile supports the device combo.
8365 if (!profile->supportsDevice(device)) {
jiabina84c3d32022-12-02 18:59:55 +00008366 ALOGE("%s profile(%s) doesn't support device %#x", __func__, profile->getName().c_str(),
8367 device->type());
jiabinbce0c1d2020-10-05 11:20:18 -07008368 return nullptr;
8369 }
8370 }
8371 sp<SwAudioOutputDescriptor> desc = new SwAudioOutputDescriptor(profile, mpClientInterface);
8372 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
jiabina84c3d32022-12-02 18:59:55 +00008373 status_t status = desc->open(halConfig, mixerConfig, devices,
8374 AUDIO_STREAM_DEFAULT, flags, &output);
jiabinbce0c1d2020-10-05 11:20:18 -07008375 if (status != NO_ERROR) {
jiabina84c3d32022-12-02 18:59:55 +00008376 ALOGE("%s failed to open output %d", __func__, status);
jiabinbce0c1d2020-10-05 11:20:18 -07008377 return nullptr;
8378 }
8379
8380 // Here is where the out_set_parameters() for card & device gets called
8381 sp<DeviceDescriptor> device = devices.getDeviceForOpening();
8382 const audio_devices_t deviceType = device->type();
8383 const String8 &address = String8(device->address().c_str());
Tomasz Wasilczykfd9ffd12023-08-14 17:56:22 +00008384 if (!address.empty()) {
jiabinbce0c1d2020-10-05 11:20:18 -07008385 char *param = audio_device_address_to_parameter(deviceType, address.c_str());
8386 mpClientInterface->setParameters(output, String8(param));
8387 free(param);
8388 }
8389 updateAudioProfiles(device, output, profile->getAudioProfiles());
8390 if (!profile->hasValidAudioProfile()) {
8391 ALOGW("%s() missing param", __func__);
8392 desc->close();
8393 return nullptr;
jiabina84c3d32022-12-02 18:59:55 +00008394 } else if (profile->hasDynamicAudioProfile() && halConfig == nullptr) {
8395 // Reopen the output with the best audio profile picked by APM when the profile supports
8396 // dynamic audio profile and the hal config is not specified.
jiabinbce0c1d2020-10-05 11:20:18 -07008397 desc->close();
8398 output = AUDIO_IO_HANDLE_NONE;
8399 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
8400 profile->pickAudioProfile(
8401 config.sample_rate, config.channel_mask, config.format);
8402 config.offload_info.sample_rate = config.sample_rate;
8403 config.offload_info.channel_mask = config.channel_mask;
8404 config.offload_info.format = config.format;
8405
jiabina84c3d32022-12-02 18:59:55 +00008406 status = desc->open(&config, mixerConfig, devices, AUDIO_STREAM_DEFAULT, flags, &output);
jiabinbce0c1d2020-10-05 11:20:18 -07008407 if (status != NO_ERROR) {
8408 return nullptr;
8409 }
8410 }
8411
8412 addOutput(output, desc);
Eric Laurentb4f42a92022-01-17 17:37:31 +01008413
baek.kim -61c20122022-07-27 10:05:32 +00008414 sp<DeviceDescriptor> speaker = mAvailableOutputDevices.getDevice(
8415 AUDIO_DEVICE_OUT_SPEAKER, String8(""), AUDIO_FORMAT_DEFAULT);
8416
jiabinbce0c1d2020-10-05 11:20:18 -07008417 if (audio_is_remote_submix_device(deviceType) && address != "0") {
8418 sp<AudioPolicyMix> policyMix;
8419 if (mPolicyMixes.getAudioPolicyMix(deviceType, address, policyMix) == NO_ERROR) {
8420 policyMix->setOutput(desc);
8421 desc->mPolicyMix = policyMix;
8422 } else {
8423 ALOGW("checkOutputsForDevice() cannot find policy for address %s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00008424 address.c_str());
jiabinbce0c1d2020-10-05 11:20:18 -07008425 }
8426
baek.kim -61c20122022-07-27 10:05:32 +00008427 } else if (hasPrimaryOutput() && speaker != nullptr
8428 && mPrimaryOutput->supportsDevice(speaker) && !desc->supportsDevice(speaker)
Eric Laurentb4f42a92022-01-17 17:37:31 +01008429 && ((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0)) {
8430 // no duplicated output for:
8431 // - direct outputs
8432 // - outputs used by dynamic policy mixes
baek.kim -61c20122022-07-27 10:05:32 +00008433 // - outputs that supports SPEAKER while the primary output does not.
jiabinbce0c1d2020-10-05 11:20:18 -07008434 audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE;
8435
8436 //TODO: configure audio effect output stage here
8437
8438 // open a duplicating output thread for the new output and the primary output
8439 sp<SwAudioOutputDescriptor> dupOutputDesc =
8440 new SwAudioOutputDescriptor(nullptr, mpClientInterface);
8441 status = dupOutputDesc->openDuplicating(mPrimaryOutput, desc, &duplicatedOutput);
8442 if (status == NO_ERROR) {
8443 // add duplicated output descriptor
8444 addOutput(duplicatedOutput, dupOutputDesc);
8445 } else {
8446 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
8447 mPrimaryOutput->mIoHandle, output);
8448 desc->close();
8449 removeOutput(output);
8450 nextAudioPortGeneration();
8451 return nullptr;
8452 }
8453 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02008454 if (mPrimaryOutput == nullptr && profile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
8455 ALOGV("%s(): re-assigning mPrimaryOutput", __func__);
8456 mPrimaryOutput = desc;
François Gaffiedb1755b2023-09-01 11:50:35 +02008457 mPrimaryModuleHandle = mPrimaryOutput->getModuleHandle();
Francois Gaffiebce7cd42020-10-14 16:13:20 +02008458 }
jiabinbce0c1d2020-10-05 11:20:18 -07008459 return desc;
8460}
8461
jiabinf1c73972022-04-14 16:28:52 -07008462status_t AudioPolicyManager::getDevicesForAttributes(
8463 const audio_attributes_t &attr, DeviceVector &devices, bool forVolume) {
8464 // Devices are determined in the following precedence:
8465 //
8466 // 1) Devices associated with a dynamic policy matching the attributes. This is often
8467 // a remote submix from MIX_ROUTE_FLAG_LOOP_BACK.
8468 //
8469 // If no such dynamic policy then
8470 // 2) Devices containing an active client using setPreferredDevice
8471 // with same strategy as the attributes.
8472 // (from the default Engine::getOutputDevicesForAttributes() implementation).
8473 //
8474 // If no corresponding active client with setPreferredDevice then
8475 // 3) Devices associated with the strategy determined by the attributes
8476 // (from the default Engine::getOutputDevicesForAttributes() implementation).
8477 //
8478 // See related getOutputForAttrInt().
8479
8480 // check dynamic policies but only for primary descriptors (secondary not used for audible
8481 // audio routing, only used for duplication for playback capture)
8482 sp<AudioPolicyMix> policyMix;
Oscar Azucena873d10f2023-01-12 18:34:42 -08008483 bool unneededUsePrimaryOutputFromPolicyMixes = false;
jiabinf1c73972022-04-14 16:28:52 -07008484 status_t status = mPolicyMixes.getOutputForAttr(attr, AUDIO_CONFIG_BASE_INITIALIZER,
Oscar Azucena873d10f2023-01-12 18:34:42 -08008485 0 /*uid unknown here*/, AUDIO_SESSION_NONE, AUDIO_OUTPUT_FLAG_NONE,
8486 mAvailableOutputDevices, nullptr /* requestedDevice */, policyMix,
8487 nullptr /* secondaryMixes */, unneededUsePrimaryOutputFromPolicyMixes);
jiabinf1c73972022-04-14 16:28:52 -07008488 if (status != OK) {
8489 return status;
8490 }
8491
8492 if (policyMix != nullptr && policyMix->getOutput() != nullptr &&
8493 // For volume control, skip LOOPBACK mixes which use AUDIO_DEVICE_OUT_REMOTE_SUBMIX
8494 // as they are unaffected by device/stream volume
8495 // (per SwAudioOutputDescriptor::isFixedVolume()).
8496 (!forVolume || policyMix->mDeviceType != AUDIO_DEVICE_OUT_REMOTE_SUBMIX)
8497 ) {
8498 sp<DeviceDescriptor> deviceDesc = mAvailableOutputDevices.getDevice(
8499 policyMix->mDeviceType, policyMix->mDeviceAddress, AUDIO_FORMAT_DEFAULT);
8500 devices.add(deviceDesc);
8501 } else {
8502 // The default Engine::getOutputDevicesForAttributes() uses findPreferredDevice()
8503 // which selects setPreferredDevice if active. This means forVolume call
8504 // will take an active setPreferredDevice, if such exists.
8505
8506 devices = mEngine->getOutputDevicesForAttributes(
8507 attr, nullptr /* preferredDevice */, false /* fromCache */);
8508 }
8509
8510 if (forVolume) {
8511 // We alias the device AUDIO_DEVICE_OUT_SPEAKER_SAFE to AUDIO_DEVICE_OUT_SPEAKER
8512 // for single volume control in AudioService (such relationship should exist if
8513 // SPEAKER_SAFE is present).
8514 //
8515 // (This is unrelated to a different device grouping as Volume::getDeviceCategory)
8516 DeviceVector speakerSafeDevices =
8517 devices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER_SAFE);
8518 if (!speakerSafeDevices.isEmpty()) {
8519 devices.merge(mAvailableOutputDevices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER));
8520 devices.remove(speakerSafeDevices);
8521 }
8522 }
8523
8524 return NO_ERROR;
8525}
8526
8527status_t AudioPolicyManager::getProfilesForDevices(const DeviceVector& devices,
8528 AudioProfileVector& audioProfiles,
8529 uint32_t flags,
8530 bool isInput) {
8531 for (const auto& hwModule : mHwModules) {
8532 // the MSD module checks for different conditions
8533 if (strcmp(hwModule->getName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0) {
8534 continue;
8535 }
8536 IOProfileCollection ioProfiles = isInput ? hwModule->getInputProfiles()
8537 : hwModule->getOutputProfiles();
8538 for (const auto& profile : ioProfiles) {
8539 if (!profile->areAllDevicesSupported(devices) ||
8540 !profile->isCompatibleProfileForFlags(
8541 flags, false /*exactMatchRequiredForInputFlags*/)) {
8542 continue;
8543 }
8544 audioProfiles.addAllValidProfiles(profile->asAudioPort()->getAudioProfiles());
8545 }
8546 }
8547
8548 if (!isInput) {
8549 // add the direct profiles from MSD if present and has audio patches to all the output(s)
8550 const auto &msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
8551 if (msdModule != nullptr) {
8552 if (msdHasPatchesToAllDevices(devices.toTypeAddrVector())) {
8553 ALOGV("%s: MSD audio patches set to all output devices.", __func__);
8554 for (const auto &profile: msdModule->getOutputProfiles()) {
8555 if (!profile->asAudioPort()->isDirectOutput()) {
8556 continue;
8557 }
8558 audioProfiles.addAllValidProfiles(profile->asAudioPort()->getAudioProfiles());
8559 }
8560 } else {
8561 ALOGV("%s: MSD audio patches NOT set to all output devices.", __func__);
8562 }
8563 }
8564 }
8565
8566 return NO_ERROR;
8567}
8568
jiabin3ff8d7d2022-12-13 06:27:44 +00008569sp<SwAudioOutputDescriptor> AudioPolicyManager::reopenOutput(sp<SwAudioOutputDescriptor> outputDesc,
8570 const audio_config_t *config,
8571 audio_output_flags_t flags,
8572 const char* caller) {
jiabina84c3d32022-12-02 18:59:55 +00008573 closeOutput(outputDesc->mIoHandle);
8574 sp<SwAudioOutputDescriptor> preferredOutput = openOutputWithProfileAndDevice(
8575 outputDesc->mProfile, outputDesc->devices(), nullptr /*mixerConfig*/, config, flags);
8576 if (preferredOutput == nullptr) {
8577 ALOGE("%s failed to reopen output device=%d, caller=%s",
8578 __func__, outputDesc->devices()[0]->getId(), caller);
jiabina84c3d32022-12-02 18:59:55 +00008579 }
jiabin3ff8d7d2022-12-13 06:27:44 +00008580 return preferredOutput;
8581}
8582
8583void AudioPolicyManager::reopenOutputsWithDevices(
8584 const std::map<audio_io_handle_t, DeviceVector> &outputsToReopen) {
8585 for (const auto& [output, devices] : outputsToReopen) {
8586 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
8587 closeOutput(output);
8588 openOutputWithProfileAndDevice(desc->mProfile, devices);
8589 }
jiabina84c3d32022-12-02 18:59:55 +00008590}
8591
jiabinc44b3462022-12-08 12:52:31 -08008592PortHandleVector AudioPolicyManager::getClientsForStream(
8593 audio_stream_type_t streamType) const {
8594 PortHandleVector clients;
8595 for (size_t i = 0; i < mOutputs.size(); ++i) {
8596 PortHandleVector clientsForStream = mOutputs.valueAt(i)->getClientsForStream(streamType);
8597 clients.insert(clients.end(), clientsForStream.begin(), clientsForStream.end());
8598 }
8599 return clients;
8600}
8601
8602void AudioPolicyManager::invalidateStreams(StreamTypeVector streams) const {
8603 PortHandleVector clients;
8604 for (auto stream : streams) {
8605 PortHandleVector clientsForStream = getClientsForStream(stream);
8606 clients.insert(clients.end(), clientsForStream.begin(), clientsForStream.end());
8607 }
8608 mpClientInterface->invalidateTracks(clients);
8609}
8610
Mikhail Naganov1b2a7942017-12-08 10:18:09 -08008611} // namespace android