blob: 7e5319c63816a5d1e6c2fb9294c74e95b3950ea8 [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{
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800514 ALOGV("handleDeviceConfigChange(() device: 0x%X, address %s name %s encodedFormat: 0x%X",
515 device, device_address, device_name, encodedFormat);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800516
Pavlin Radoslavovc694ff42017-01-09 23:27:29 -0800517 // connect/disconnect only 1 device at a time
518 if (!audio_is_output_device(device) && !audio_is_input_device(device)) return BAD_VALUE;
519
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800520 // Check if the device is currently connected
jiabin9a3361e2019-10-01 09:38:30 -0700521 DeviceVector deviceList = mAvailableOutputDevices.getDevicesFromType(device);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800522 if (deviceList.empty()) {
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800523 // Nothing to do: device is not connected
524 return NO_ERROR;
525 }
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800526 sp<DeviceDescriptor> devDesc = deviceList.itemAt(0);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800527
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700528 // For offloaded A2DP, Hw modules may have the capability to
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800529 // configure codecs.
530 // Handle two specific cases by sending a set parameter to
531 // configure A2DP codecs. No need to toggle device state.
532 // Case 1: A2DP active device switches from primary to primary
533 // module
534 // Case 2: A2DP device config changes on primary module.
Eric Laurent7e3c0832023-11-30 15:04:50 +0100535 if (device_has_encoding_capability(device) && hasPrimaryOutput()) {
jiabin9a3361e2019-10-01 09:38:30 -0700536 sp<HwModule> module = mHwModules.getModuleForDeviceType(device, encodedFormat);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800537 audio_module_handle_t primaryHandle = mPrimaryOutput->getModuleHandle();
538 if (availablePrimaryOutputDevices().contains(devDesc) &&
539 (module != 0 && module->getHandle() == primaryHandle)) {
Eric Laurent7e3c0832023-11-30 15:04:50 +0100540 bool isA2dp = audio_is_a2dp_out_device(device);
541 const String8 supportKey = isA2dp ? String8(AudioParameter::keyReconfigA2dpSupported)
542 : String8(AudioParameter::keyReconfigLeSupported);
543 String8 reply = mpClientInterface->getParameters(AUDIO_IO_HANDLE_NONE, supportKey);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800544 AudioParameter repliedParameters(reply);
Eric Laurent7e3c0832023-11-30 15:04:50 +0100545 int isReconfigSupported;
546 repliedParameters.getInt(supportKey, isReconfigSupported);
547 if (isReconfigSupported) {
548 const String8 key = isA2dp ? String8(AudioParameter::keyReconfigA2dp)
549 : String8(AudioParameter::keyReconfigLe);
550 AudioParameter param;
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800551 param.add(key, String8("true"));
552 mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString());
553 devDesc->setEncodedFormat(encodedFormat);
554 return NO_ERROR;
555 }
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700556 }
557 }
cnx421bd2dcc42020-07-11 14:58:44 +0800558 auto musicStrategy = streamToStrategy(AUDIO_STREAM_MUSIC);
559 for (size_t i = 0; i < mOutputs.size(); i++) {
560 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
561 // mute media strategies and delay device switch by the largest
562 // This avoid sending the music tail into the earpiece or headset.
563 setStrategyMute(musicStrategy, true, desc);
564 setStrategyMute(musicStrategy, false, desc, MUTE_TIME_MS,
565 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
566 nullptr, true /*fromCache*/).types());
567 }
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800568 // Toggle the device state: UNAVAILABLE -> AVAILABLE
569 // This will force reading again the device configuration
Eric Laurent7e3c0832023-11-30 15:04:50 +0100570 status_t status = setDeviceConnectionState(device,
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800571 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800572 device_address, device_name,
573 devDesc->getEncodedFormat());
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800574 if (status != NO_ERROR) {
575 ALOGW("handleDeviceConfigChange() error disabling connection state: %d",
576 status);
577 return status;
578 }
579
580 status = setDeviceConnectionState(device,
581 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800582 device_address, device_name, encodedFormat);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800583 if (status != NO_ERROR) {
584 ALOGW("handleDeviceConfigChange() error enabling connection state: %d",
585 status);
586 return status;
587 }
588
589 return NO_ERROR;
590}
591
Pattydd807582021-11-04 21:01:03 +0800592status_t AudioPolicyManager::getHwOffloadFormatsSupportedForBluetoothMedia(
593 audio_devices_t device, std::vector<audio_format_t> *formats)
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800594{
Pattydd807582021-11-04 21:01:03 +0800595 ALOGV("getHwOffloadFormatsSupportedForBluetoothMedia()");
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800596 status_t status = NO_ERROR;
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800597 std::unordered_set<audio_format_t> formatSet;
598 sp<HwModule> primaryModule =
599 mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_PRIMARY);
Aniket Kumar Latafedb5982019-07-03 11:20:36 -0700600 if (primaryModule == nullptr) {
601 ALOGE("%s() unable to get primary module", __func__);
602 return NO_INIT;
603 }
Pattydd807582021-11-04 21:01:03 +0800604
605 DeviceTypeSet audioDeviceSet;
606
607 switch(device) {
608 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP:
609 audioDeviceSet = getAudioDeviceOutAllA2dpSet();
610 break;
611 case AUDIO_DEVICE_OUT_BLE_HEADSET:
Patty Huang36028df2022-07-06 00:14:12 +0800612 audioDeviceSet = getAudioDeviceOutLeAudioUnicastSet();
613 break;
614 case AUDIO_DEVICE_OUT_BLE_BROADCAST:
615 audioDeviceSet = getAudioDeviceOutLeAudioBroadcastSet();
Pattydd807582021-11-04 21:01:03 +0800616 break;
617 default:
618 ALOGE("%s() device type 0x%08x not supported", __func__, device);
619 return BAD_VALUE;
620 }
621
jiabin9a3361e2019-10-01 09:38:30 -0700622 DeviceVector declaredDevices = primaryModule->getDeclaredDevices().getDevicesFromTypes(
Pattydd807582021-11-04 21:01:03 +0800623 audioDeviceSet);
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800624 for (const auto& device : declaredDevices) {
625 formatSet.insert(device->encodedFormats().begin(), device->encodedFormats().end());
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800626 }
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800627 formats->assign(formatSet.begin(), formatSet.end());
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800628 return status;
629}
630
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100631DeviceVector AudioPolicyManager::selectBestRxSinkDevicesForCall(bool fromCache)
632{
633 DeviceVector rxSinkdevices{};
634 rxSinkdevices = mEngine->getOutputDevicesForAttributes(
635 attributes_initializer(AUDIO_USAGE_VOICE_COMMUNICATION), nullptr, fromCache);
636 if (!rxSinkdevices.isEmpty() && mAvailableOutputDevices.contains(rxSinkdevices.itemAt(0))) {
637 auto rxSinkDevice = rxSinkdevices.itemAt(0);
638 auto telephonyRxModule = mHwModules.getModuleForDeviceType(
639 AUDIO_DEVICE_IN_TELEPHONY_RX, AUDIO_FORMAT_DEFAULT);
640 // retrieve Rx Source device descriptor
641 sp<DeviceDescriptor> rxSourceDevice = mAvailableInputDevices.getDevice(
642 AUDIO_DEVICE_IN_TELEPHONY_RX, String8(), AUDIO_FORMAT_DEFAULT);
643
644 // RX Telephony and Rx sink devices are declared by Primary Audio HAL
645 if (isPrimaryModule(telephonyRxModule) && (telephonyRxModule->getHalVersionMajor() >= 3) &&
646 telephonyRxModule->supportsPatch(rxSourceDevice, rxSinkDevice)) {
647 ALOGW("%s() device %s using HW Bridge", __func__, rxSinkDevice->toString().c_str());
648 return DeviceVector(rxSinkDevice);
649 }
650 }
651 // Note that despite the fact that getNewOutputDevices() is called on the primary output,
652 // the device returned is not necessarily reachable via this output
653 // (filter later by setOutputDevices())
654 return getNewOutputDevices(mPrimaryOutput, fromCache);
655}
656
657status_t AudioPolicyManager::updateCallRouting(bool fromCache, uint32_t delayMs, uint32_t *waitMs)
658{
François Gaffiedb1755b2023-09-01 11:50:35 +0200659 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) {
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100660 DeviceVector rxDevices = selectBestRxSinkDevicesForCall(fromCache);
661 return updateCallRoutingInternal(rxDevices, delayMs, waitMs);
662 }
663 return INVALID_OPERATION;
664}
665
666status_t AudioPolicyManager::updateCallRoutingInternal(
667 const DeviceVector &rxDevices, uint32_t delayMs, uint32_t *waitMs)
Eric Laurentc2730ba2014-07-20 15:47:07 -0700668{
669 bool createTxPatch = false;
François Gaffie9eb18552018-11-05 10:33:26 +0100670 bool createRxPatch = false;
Eric Laurentdc462862016-07-19 12:29:53 -0700671 uint32_t muteWaitMs = 0;
François Gaffiedb1755b2023-09-01 11:50:35 +0200672 if (hasPrimaryOutput() &&
jiabin9a3361e2019-10-01 09:38:30 -0700673 mPrimaryOutput->devices().onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_STUB)) {
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100674 return INVALID_OPERATION;
Eric Laurent87ffa392015-05-22 10:32:38 -0700675 }
François Gaffie11d30102018-11-02 16:09:09 +0100676
Francois Gaffie716e1432019-01-14 16:58:59 +0100677 audio_attributes_t attr = { .source = AUDIO_SOURCE_VOICE_COMMUNICATION };
François Gaffiec005e562018-11-06 15:04:49 +0100678 auto txSourceDevice = mEngine->getInputDeviceForAttributes(attr);
François Gaffiedb1755b2023-09-01 11:50:35 +0200679
680 disconnectTelephonyAudioSource(mCallRxSourceClient);
681 disconnectTelephonyAudioSource(mCallTxSourceClient);
682
683 if (rxDevices.isEmpty()) {
684 ALOGW("%s() no selected output device", __func__);
685 return INVALID_OPERATION;
686 }
Eric Laurentcedd5b52023-03-22 00:03:31 +0000687 if (txSourceDevice == nullptr) {
688 ALOGE("%s() selected input device not available", __func__);
689 return INVALID_OPERATION;
690 }
François Gaffiec005e562018-11-06 15:04:49 +0100691
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100692 ALOGV("%s device rxDevice %s txDevice %s", __func__,
François Gaffie9eb18552018-11-05 10:33:26 +0100693 rxDevices.itemAt(0)->toString().c_str(), txSourceDevice->toString().c_str());
Eric Laurentc2730ba2014-07-20 15:47:07 -0700694
François Gaffie9eb18552018-11-05 10:33:26 +0100695 auto telephonyRxModule =
jiabin9a3361e2019-10-01 09:38:30 -0700696 mHwModules.getModuleForDeviceType(AUDIO_DEVICE_IN_TELEPHONY_RX, AUDIO_FORMAT_DEFAULT);
François Gaffie9eb18552018-11-05 10:33:26 +0100697 auto telephonyTxModule =
jiabin9a3361e2019-10-01 09:38:30 -0700698 mHwModules.getModuleForDeviceType(AUDIO_DEVICE_OUT_TELEPHONY_TX, AUDIO_FORMAT_DEFAULT);
François Gaffie9eb18552018-11-05 10:33:26 +0100699 // retrieve Rx Source and Tx Sink device descriptors
700 sp<DeviceDescriptor> rxSourceDevice =
701 mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_TELEPHONY_RX,
702 String8(),
703 AUDIO_FORMAT_DEFAULT);
704 sp<DeviceDescriptor> txSinkDevice =
705 mAvailableOutputDevices.getDevice(AUDIO_DEVICE_OUT_TELEPHONY_TX,
706 String8(),
707 AUDIO_FORMAT_DEFAULT);
708
709 // RX and TX Telephony device are declared by Primary Audio HAL
710 if (isPrimaryModule(telephonyRxModule) && isPrimaryModule(telephonyTxModule) &&
711 (telephonyRxModule->getHalVersionMajor() >= 3)) {
712 if (rxSourceDevice == 0 || txSinkDevice == 0) {
713 // RX / TX Telephony device(s) is(are) not currently available
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100714 ALOGE("%s() no telephony Tx and/or RX device", __func__);
715 return INVALID_OPERATION;
François Gaffie9eb18552018-11-05 10:33:26 +0100716 }
François Gaffieafd4cea2019-11-18 15:50:22 +0100717 // createAudioPatchInternal now supports both HW / SW bridging
718 createRxPatch = true;
719 createTxPatch = true;
François Gaffie9eb18552018-11-05 10:33:26 +0100720 } else {
721 // If the RX device is on the primary HW module, then use legacy routing method for
722 // voice calls via setOutputDevice() on primary output.
723 // Otherwise, create two audio patches for TX and RX path.
724 createRxPatch = !(availablePrimaryOutputDevices().contains(rxDevices.itemAt(0))) &&
725 (rxSourceDevice != 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700726 // If the TX device is also on the primary HW module, setOutputDevice() will take care
727 // of it due to legacy implementation. If not, create a patch.
François Gaffie9eb18552018-11-05 10:33:26 +0100728 createTxPatch = !(availablePrimaryModuleInputDevices().contains(txSourceDevice)) &&
729 (txSinkDevice != 0);
730 }
731 // Use legacy routing method for voice calls via setOutputDevice() on primary output.
732 // Otherwise, create two audio patches for TX and RX path.
733 if (!createRxPatch) {
François Gaffiedb1755b2023-09-01 11:50:35 +0200734 if (!hasPrimaryOutput()) {
735 ALOGW("%s() no primary output available", __func__);
736 return INVALID_OPERATION;
737 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +0530738 muteWaitMs = setOutputDevices(__func__, mPrimaryOutput, rxDevices, true, delayMs);
Eric Laurent8ae73122016-04-12 10:13:29 -0700739 } else { // create RX path audio patch
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200740 connectTelephonyRxAudioSource();
juyuchen2224c5a2019-01-21 12:00:58 +0800741 // If the TX device is on the primary HW module but RX device is
742 // on other HW module, SinkMetaData of telephony input should handle it
743 // assuming the device uses audio HAL V5.0 and above
Eric Laurentc2730ba2014-07-20 15:47:07 -0700744 }
Eric Laurent8ae73122016-04-12 10:13:29 -0700745 if (createTxPatch) { // create TX path audio patch
François Gaffieafd4cea2019-11-18 15:50:22 +0100746 // terminate active capture if on the same HW module as the call TX source device
747 // FIXME: would be better to refine to only inputs whose profile connects to the
748 // call TX device but this information is not in the audio patch and logic here must be
749 // symmetric to the one in startInput()
750 for (const auto& activeDesc : mInputs.getActiveInputs()) {
751 if (activeDesc->hasSameHwModuleAs(txSourceDevice)) {
752 closeActiveClients(activeDesc);
753 }
754 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200755 connectTelephonyTxAudioSource(txSourceDevice, txSinkDevice, delayMs);
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800756 }
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100757 if (waitMs != nullptr) {
758 *waitMs = muteWaitMs;
759 }
760 return NO_ERROR;
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800761}
Eric Laurentc2730ba2014-07-20 15:47:07 -0700762
Mikhail Naganov100f0122018-11-29 11:22:16 -0800763bool AudioPolicyManager::isDeviceOfModule(
764 const sp<DeviceDescriptor>& devDesc, const char *moduleId) const {
765 sp<HwModule> module = mHwModules.getModuleFromName(moduleId);
766 if (module != 0) {
767 return mAvailableOutputDevices.getDevicesFromHwModule(module->getHandle())
768 .indexOf(devDesc) != NAME_NOT_FOUND
769 || mAvailableInputDevices.getDevicesFromHwModule(module->getHandle())
770 .indexOf(devDesc) != NAME_NOT_FOUND;
771 }
772 return false;
773}
774
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200775void AudioPolicyManager::connectTelephonyRxAudioSource()
776{
Francois Gaffie601801d2021-06-22 13:27:39 +0200777 disconnectTelephonyAudioSource(mCallRxSourceClient);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200778 const struct audio_port_config source = {
779 .role = AUDIO_PORT_ROLE_SOURCE, .type = AUDIO_PORT_TYPE_DEVICE,
780 .ext.device.type = AUDIO_DEVICE_IN_TELEPHONY_RX, .ext.device.address = ""
781 };
782 const auto aa = mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL);
Francois Gaffie601801d2021-06-22 13:27:39 +0200783 mCallRxSourceClient = startAudioSourceInternal(&source, &aa, 0/*uid*/);
784 ALOGE_IF(mCallRxSourceClient == nullptr,
785 "%s failed to start Telephony Rx AudioSource", __func__);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200786}
787
Francois Gaffie601801d2021-06-22 13:27:39 +0200788void AudioPolicyManager::disconnectTelephonyAudioSource(sp<SourceClientDescriptor> &clientDesc)
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200789{
Francois Gaffie601801d2021-06-22 13:27:39 +0200790 if (clientDesc == nullptr) {
791 return;
792 }
793 ALOGW_IF(stopAudioSource(clientDesc->portId()) != NO_ERROR,
794 "%s error stopping audio source", __func__);
795 clientDesc.clear();
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200796}
797
798void AudioPolicyManager::connectTelephonyTxAudioSource(
799 const sp<DeviceDescriptor> &srcDevice, const sp<DeviceDescriptor> &sinkDevice,
800 uint32_t delayMs)
801{
Francois Gaffie601801d2021-06-22 13:27:39 +0200802 disconnectTelephonyAudioSource(mCallTxSourceClient);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200803 if (srcDevice == nullptr || sinkDevice == nullptr) {
804 ALOGW("%s could not create patch, invalid sink and/or source device(s)", __func__);
805 return;
806 }
807 PatchBuilder patchBuilder;
808 patchBuilder.addSource(srcDevice).addSink(sinkDevice);
809 ALOGV("%s between source %s and sink %s", __func__,
810 srcDevice->toString().c_str(), sinkDevice->toString().c_str());
Francois Gaffie601801d2021-06-22 13:27:39 +0200811 auto callTxSourceClientPortId = PolicyAudioPort::getNextUniqueId();
Eric Laurent78b07302022-10-07 16:20:34 +0200812 const auto aa = mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL);
813
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200814 struct audio_port_config source = {};
815 srcDevice->toAudioPortConfig(&source);
Francois Gaffie601801d2021-06-22 13:27:39 +0200816 mCallTxSourceClient = new InternalSourceClientDescriptor(
817 callTxSourceClientPortId, mUidCached, aa, source, srcDevice, sinkDevice,
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200818 mCommunnicationStrategy, toVolumeSource(aa));
819 audio_patch_handle_t patchHandle = AUDIO_PATCH_HANDLE_NONE;
820 status_t status = connectAudioSourceToSink(
Francois Gaffie601801d2021-06-22 13:27:39 +0200821 mCallTxSourceClient, sinkDevice, patchBuilder.patch(), patchHandle, mUidCached,
822 delayMs);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200823 ALOGE_IF(status != NO_ERROR, "%s() error %d creating TX audio patch", __func__, status);
824 if (status == NO_ERROR) {
Francois Gaffie601801d2021-06-22 13:27:39 +0200825 mAudioSources.add(callTxSourceClientPortId, mCallTxSourceClient);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200826 }
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200827}
828
Eric Laurente0720872014-03-11 09:30:41 -0700829void AudioPolicyManager::setPhoneState(audio_mode_t state)
Eric Laurente552edb2014-03-10 17:42:56 -0700830{
831 ALOGV("setPhoneState() state %d", state);
François Gaffie2110e042015-03-24 08:41:51 +0100832 // store previous phone state for management of sonification strategy below
833 int oldState = mEngine->getPhoneState();
Eric Laurent96d1dda2022-03-14 17:14:19 +0100834 bool wasLeUnicastActive = isLeUnicastActive();
François Gaffie2110e042015-03-24 08:41:51 +0100835
836 if (mEngine->setPhoneState(state) != NO_ERROR) {
837 ALOGW("setPhoneState() invalid or same state %d", state);
Eric Laurente552edb2014-03-10 17:42:56 -0700838 return;
839 }
François Gaffie2110e042015-03-24 08:41:51 +0100840 /// Opens: can these line be executed after the switch of volume curves???
Eric Laurent63dea1d2015-07-02 17:10:28 -0700841 if (isStateInCall(oldState)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700842 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent63dea1d2015-07-02 17:10:28 -0700843 // force reevaluating accessibility routing when call stops
jiabinc44b3462022-12-08 12:52:31 -0800844 invalidateStreams({AUDIO_STREAM_ACCESSIBILITY});
Eric Laurente552edb2014-03-10 17:42:56 -0700845 }
846
François Gaffie2110e042015-03-24 08:41:51 +0100847 /**
848 * Switching to or from incall state or switching between telephony and VoIP lead to force
849 * routing command.
850 */
Eric Laurent74b71512019-11-06 17:21:57 -0800851 bool force = ((isStateInCall(oldState) != isStateInCall(state))
852 || (isStateInCall(state) && (state != oldState)));
Eric Laurente552edb2014-03-10 17:42:56 -0700853
854 // check for device and output changes triggered by new phone state
Mikhail Naganov37977152018-07-11 15:54:44 -0700855 checkForDeviceAndOutputChanges();
Eric Laurente552edb2014-03-10 17:42:56 -0700856
Eric Laurente552edb2014-03-10 17:42:56 -0700857 int delayMs = 0;
858 if (isStateInCall(state)) {
859 nsecs_t sysTime = systemTime();
François Gaffiec005e562018-11-06 15:04:49 +0100860 auto musicStrategy = streamToStrategy(AUDIO_STREAM_MUSIC);
861 auto sonificationStrategy = streamToStrategy(AUDIO_STREAM_ALARM);
Eric Laurente552edb2014-03-10 17:42:56 -0700862 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700863 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700864 // mute media and sonification strategies and delay device switch by the largest
865 // latency of any output where either strategy is active.
866 // This avoid sending the ring tone or music tail into the earpiece or headset.
François Gaffiec005e562018-11-06 15:04:49 +0100867 if ((desc->isStrategyActive(musicStrategy, SONIFICATION_HEADSET_MUSIC_DELAY, sysTime) ||
868 desc->isStrategyActive(sonificationStrategy, SONIFICATION_HEADSET_MUSIC_DELAY,
869 sysTime)) &&
Eric Laurentc75307b2015-03-17 15:29:32 -0700870 (delayMs < (int)desc->latency()*2)) {
871 delayMs = desc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -0700872 }
François Gaffiec005e562018-11-06 15:04:49 +0100873 setStrategyMute(musicStrategy, true, desc);
874 setStrategyMute(musicStrategy, false, desc, MUTE_TIME_MS,
875 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
876 nullptr, true /*fromCache*/).types());
877 setStrategyMute(sonificationStrategy, true, desc);
878 setStrategyMute(sonificationStrategy, false, desc, MUTE_TIME_MS,
879 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_ALARM),
880 nullptr, true /*fromCache*/).types());
Eric Laurente552edb2014-03-10 17:42:56 -0700881 }
882 }
883
François Gaffiedb1755b2023-09-01 11:50:35 +0200884 if (state == AUDIO_MODE_IN_CALL) {
885 (void)updateCallRouting(false /*fromCache*/, delayMs);
886 } else {
887 if (oldState == AUDIO_MODE_IN_CALL) {
888 disconnectTelephonyAudioSource(mCallRxSourceClient);
889 disconnectTelephonyAudioSource(mCallTxSourceClient);
890 }
891 if (hasPrimaryOutput()) {
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100892 DeviceVector rxDevices = getNewOutputDevices(mPrimaryOutput, false /*fromCache*/);
893 // force routing command to audio hardware when ending call
894 // even if no device change is needed
895 if (isStateInCall(oldState) && rxDevices.isEmpty()) {
896 rxDevices = mPrimaryOutput->devices();
897 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +0530898 setOutputDevices(__func__, mPrimaryOutput, rxDevices, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700899 }
Eric Laurentc2730ba2014-07-20 15:47:07 -0700900 }
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700901
jiabin3ff8d7d2022-12-13 06:27:44 +0000902 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700903 // reevaluate routing on all outputs in case tracks have been started during the call
904 for (size_t i = 0; i < mOutputs.size(); i++) {
905 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
François Gaffie11d30102018-11-02 16:09:09 +0100906 DeviceVector newDevices = getNewOutputDevices(desc, true /*fromCache*/);
Francois Gaffie601801d2021-06-22 13:27:39 +0200907 if (state != AUDIO_MODE_IN_CALL || (desc != mPrimaryOutput && !isTelephonyRxOrTx(desc))) {
908 bool forceRouting = !newDevices.isEmpty();
jiabin3ff8d7d2022-12-13 06:27:44 +0000909 if (desc->mUsePreferredMixerAttributes && newDevices != desc->devices()) {
910 // If the device is using preferred mixer attributes, the output need to reopen
911 // with default configuration when the new selected devices are different from
912 // current routing devices.
913 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices);
914 continue;
915 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +0530916 setOutputDevices(__func__, desc, newDevices, forceRouting, 0 /*delayMs*/, nullptr,
Francois Gaffie601801d2021-06-22 13:27:39 +0200917 true /*requiresMuteCheck*/, !forceRouting /*requiresVolumeCheck*/);
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700918 }
919 }
jiabin3ff8d7d2022-12-13 06:27:44 +0000920 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700921
Eric Laurent96d1dda2022-03-14 17:14:19 +0100922 checkLeBroadcastRoutes(wasLeUnicastActive, nullptr, delayMs);
923
Eric Laurente552edb2014-03-10 17:42:56 -0700924 if (isStateInCall(state)) {
925 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent63dea1d2015-07-02 17:10:28 -0700926 // force reevaluating accessibility routing when call starts
jiabinc44b3462022-12-08 12:52:31 -0800927 invalidateStreams({AUDIO_STREAM_ACCESSIBILITY});
Eric Laurente552edb2014-03-10 17:42:56 -0700928 }
929
930 // Flag that ringtone volume must be limited to music volume until we exit MODE_RINGTONE
François Gaffiec005e562018-11-06 15:04:49 +0100931 mLimitRingtoneVolume = (state == AUDIO_MODE_RINGTONE &&
932 isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY));
Eric Laurente552edb2014-03-10 17:42:56 -0700933}
934
Jean-Michel Trivi887a9ed2015-03-31 18:02:24 -0700935audio_mode_t AudioPolicyManager::getPhoneState() {
936 return mEngine->getPhoneState();
937}
938
Eric Laurente0720872014-03-11 09:30:41 -0700939void AudioPolicyManager::setForceUse(audio_policy_force_use_t usage,
François Gaffie11d30102018-11-02 16:09:09 +0100940 audio_policy_forced_cfg_t config)
Eric Laurente552edb2014-03-10 17:42:56 -0700941{
François Gaffie2110e042015-03-24 08:41:51 +0100942 ALOGV("setForceUse() usage %d, config %d, mPhoneState %d", usage, config, mEngine->getPhoneState());
Eric Laurent8dc87a62017-05-16 19:00:40 -0700943 if (config == mEngine->getForceUse(usage)) {
944 return;
945 }
Eric Laurente552edb2014-03-10 17:42:56 -0700946
François Gaffie2110e042015-03-24 08:41:51 +0100947 if (mEngine->setForceUse(usage, config) != NO_ERROR) {
948 ALOGW("setForceUse() could not set force cfg %d for usage %d", config, usage);
949 return;
Eric Laurente552edb2014-03-10 17:42:56 -0700950 }
François Gaffie2110e042015-03-24 08:41:51 +0100951 bool forceVolumeReeval = (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) ||
952 (usage == AUDIO_POLICY_FORCE_FOR_DOCK) ||
953 (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM);
Eric Laurente552edb2014-03-10 17:42:56 -0700954
955 // check for device and output changes triggered by new force usage
Mikhail Naganov37977152018-07-11 15:54:44 -0700956 checkForDeviceAndOutputChanges();
Phil Burk09bc4612016-02-24 15:58:15 -0800957
Eric Laurent22fcda22019-05-17 16:28:47 -0700958 // force client reconnection to reevaluate flag AUDIO_FLAG_AUDIBILITY_ENFORCED
959 if (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM) {
jiabinc44b3462022-12-08 12:52:31 -0800960 invalidateStreams({AUDIO_STREAM_SYSTEM, AUDIO_STREAM_ENFORCED_AUDIBLE});
Eric Laurent22fcda22019-05-17 16:28:47 -0700961 }
962
Eric Laurentdc462862016-07-19 12:29:53 -0700963 //FIXME: workaround for truncated touch sounds
964 // to be removed when the problem is handled by system UI
965 uint32_t delayMs = 0;
Eric Laurentdc462862016-07-19 12:29:53 -0700966 if (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) {
967 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
968 }
Jean-Michel Trivi30857152019-11-01 11:04:15 -0700969
970 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Eric Laurent2517af32020-11-25 15:31:27 +0100971 updateInputRouting();
Eric Laurente552edb2014-03-10 17:42:56 -0700972}
973
Eric Laurente0720872014-03-11 09:30:41 -0700974void AudioPolicyManager::setSystemProperty(const char* property, const char* value)
Eric Laurente552edb2014-03-10 17:42:56 -0700975{
976 ALOGV("setSystemProperty() property %s, value %s", property, value);
977}
978
Dorin Drimusecc9f422022-03-09 17:57:40 +0100979// Find an MSD output profile compatible with the parameters passed.
980// When "directOnly" is set, restrict search to profiles for direct outputs.
981sp<IOProfile> AudioPolicyManager::getMsdProfileForOutput(
982 const DeviceVector& devices,
983 uint32_t samplingRate,
984 audio_format_t format,
985 audio_channel_mask_t channelMask,
986 audio_output_flags_t flags,
987 bool directOnly)
988{
989 flags = getRelevantFlags(flags, directOnly);
990
991 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
992 if (msdModule != nullptr) {
993 // for the msd module check if there are patches to the output devices
994 if (msdHasPatchesToAllDevices(devices.toTypeAddrVector())) {
995 HwModuleCollection modules;
996 modules.add(msdModule);
997 return searchCompatibleProfileHwModules(
998 modules, getMsdAudioOutDevices(), samplingRate, format, channelMask,
999 flags, directOnly);
1000 }
1001 }
1002 return nullptr;
1003}
1004
Michael Chana94fbb22018-04-24 14:31:19 +10001005// Find an output profile compatible with the parameters passed. When "directOnly" is set, restrict
1006// search to profiles for direct outputs.
1007sp<IOProfile> AudioPolicyManager::getProfileForOutput(
François Gaffie11d30102018-11-02 16:09:09 +01001008 const DeviceVector& devices,
Michael Chana94fbb22018-04-24 14:31:19 +10001009 uint32_t samplingRate,
1010 audio_format_t format,
1011 audio_channel_mask_t channelMask,
1012 audio_output_flags_t flags,
1013 bool directOnly)
Eric Laurente552edb2014-03-10 17:42:56 -07001014{
Dorin Drimusecc9f422022-03-09 17:57:40 +01001015 flags = getRelevantFlags(flags, directOnly);
1016
1017 return searchCompatibleProfileHwModules(
1018 mHwModules, devices, samplingRate, format, channelMask, flags, directOnly);
1019}
1020
1021audio_output_flags_t AudioPolicyManager::getRelevantFlags (
1022 audio_output_flags_t flags, bool directOnly) {
Michael Chana94fbb22018-04-24 14:31:19 +10001023 if (directOnly) {
Dorin Drimusecc9f422022-03-09 17:57:40 +01001024 // only retain flags that will drive the direct output profile selection
1025 // if explicitly requested
1026 static const uint32_t kRelevantFlags =
Michael Chana94fbb22018-04-24 14:31:19 +10001027 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD |
Dorin Drimusecc9f422022-03-09 17:57:40 +01001028 AUDIO_OUTPUT_FLAG_VOIP_RX | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ);
1029 flags = (audio_output_flags_t)((flags & kRelevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
Michael Chana94fbb22018-04-24 14:31:19 +10001030 }
Dorin Drimusecc9f422022-03-09 17:57:40 +01001031 return flags;
1032}
Eric Laurent861a6282015-05-18 15:40:16 -07001033
Dorin Drimusecc9f422022-03-09 17:57:40 +01001034sp<IOProfile> AudioPolicyManager::searchCompatibleProfileHwModules (
1035 const HwModuleCollection& hwModules,
1036 const DeviceVector& devices,
1037 uint32_t samplingRate,
1038 audio_format_t format,
1039 audio_channel_mask_t channelMask,
1040 audio_output_flags_t flags,
1041 bool directOnly) {
Eric Laurent861a6282015-05-18 15:40:16 -07001042 sp<IOProfile> profile;
Dorin Drimusecc9f422022-03-09 17:57:40 +01001043 for (const auto& hwModule : hwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08001044 for (const auto& curProfile : hwModule->getOutputProfiles()) {
Dorin Drimusecc9f422022-03-09 17:57:40 +01001045 if (!curProfile->isCompatibleProfile(devices,
1046 samplingRate, NULL /*updatedSamplingRate*/,
1047 format, NULL /*updatedFormat*/,
1048 channelMask, NULL /*updatedChannelMask*/,
1049 flags)) {
1050 continue;
1051 }
1052 // reject profiles not corresponding to a device currently available
1053 if (!mAvailableOutputDevices.containsAtLeastOne(curProfile->getSupportedDevices())) {
1054 continue;
1055 }
1056 // reject profiles if connected device does not support codec
1057 if (!curProfile->devicesSupportEncodedFormats(devices.types())) {
1058 continue;
1059 }
1060 if (!directOnly) {
1061 return curProfile;
1062 }
1063
1064 // when searching for direct outputs, if several profiles are compatible, give priority
1065 // to one with offload capability
Patty Huang36028df2022-07-06 00:14:12 +08001066 if (profile != 0 &&
Dorin Drimusecc9f422022-03-09 17:57:40 +01001067 ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0)) {
Eric Laurent861a6282015-05-18 15:40:16 -07001068 continue;
Dorin Drimusecc9f422022-03-09 17:57:40 +01001069 }
1070 profile = curProfile;
1071 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1072 break;
1073 }
Eric Laurente552edb2014-03-10 17:42:56 -07001074 }
1075 }
Eric Laurent861a6282015-05-18 15:40:16 -07001076 return profile;
Eric Laurente552edb2014-03-10 17:42:56 -07001077}
1078
Eric Laurentfa0f6742021-08-17 18:39:44 +02001079sp<IOProfile> AudioPolicyManager::getSpatializerOutputProfile(
Eric Laurent39095982021-08-24 18:29:27 +02001080 const audio_config_t *config __unused, const AudioDeviceTypeAddrVector &devices) const
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001081{
1082 for (const auto& hwModule : mHwModules) {
1083 for (const auto& curProfile : hwModule->getOutputProfiles()) {
Eric Laurent1c5e2e32021-08-18 18:50:28 +02001084 if (curProfile->getFlags() != AUDIO_OUTPUT_FLAG_SPATIALIZER) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001085 continue;
1086 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001087 if (!devices.empty()) {
Eric Laurent0c8f7cc2022-06-24 14:32:36 +02001088 // reject profiles not corresponding to a device currently available
1089 DeviceVector supportedDevices = curProfile->getSupportedDevices();
1090 if (!mAvailableOutputDevices.containsAtLeastOne(supportedDevices)) {
1091 continue;
1092 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001093 if (supportedDevices.getDevicesFromDeviceTypeAddrVec(devices).size()
1094 != devices.size()) {
1095 continue;
1096 }
1097 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001098 ALOGV("%s found profile %s", __func__, curProfile->getName().c_str());
1099 return curProfile;
1100 }
1101 }
1102 return nullptr;
1103}
1104
Eric Laurentf4e63452017-11-06 19:31:46 +00001105audio_io_handle_t AudioPolicyManager::getOutput(audio_stream_type_t stream)
Eric Laurente552edb2014-03-10 17:42:56 -07001106{
François Gaffiec005e562018-11-06 15:04:49 +01001107 DeviceVector devices = mEngine->getOutputDevicesForStream(stream, false /*fromCache*/);
Andy Hungc9901522017-11-10 20:07:54 -08001108
1109 // Note that related method getOutputForAttr() uses getOutputForDevice() not selectOutput().
1110 // We use selectOutput() here since we don't have the desired AudioTrack sample rate,
1111 // format, flags, etc. This may result in some discrepancy for functions that utilize
1112 // getOutput() solely on audio_stream_type such as AudioSystem::getOutputFrameCount()
1113 // and AudioSystem::getOutputSamplingRate().
1114
François Gaffie11d30102018-11-02 16:09:09 +01001115 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Mingyu Shih75563d32023-05-24 04:47:40 +08001116 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
1117 if (stream == AUDIO_STREAM_MUSIC &&
1118 property_get_bool("audio.deep_buffer.media", false /* default_value */)) {
1119 flags = AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
1120 }
1121 const audio_io_handle_t output = selectOutput(outputs, flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001122
François Gaffie11d30102018-11-02 16:09:09 +01001123 ALOGV("getOutput() stream %d selected devices %s, output %d", stream,
1124 devices.toString().c_str(), output);
Eric Laurentf4e63452017-11-06 19:31:46 +00001125 return output;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001126}
1127
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001128status_t AudioPolicyManager::getAudioAttributes(audio_attributes_t *dstAttr,
1129 const audio_attributes_t *srcAttr,
1130 audio_stream_type_t srcStream)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001131{
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001132 if (srcAttr != NULL) {
1133 if (!isValidAttributes(srcAttr)) {
1134 ALOGE("%s invalid attributes: usage=%d content=%d flags=0x%x tags=[%s]",
1135 __func__,
1136 srcAttr->usage, srcAttr->content_type, srcAttr->flags,
1137 srcAttr->tags);
1138 return BAD_VALUE;
1139 }
1140 *dstAttr = *srcAttr;
1141 } else {
1142 if (srcStream < AUDIO_STREAM_MIN || srcStream >= AUDIO_STREAM_PUBLIC_CNT) {
1143 ALOGE("%s: invalid stream type", __func__);
1144 return BAD_VALUE;
1145 }
François Gaffiec005e562018-11-06 15:04:49 +01001146 *dstAttr = mEngine->getAttributesForStreamType(srcStream);
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001147 }
Eric Laurent22fcda22019-05-17 16:28:47 -07001148
1149 // Only honor audibility enforced when required. The client will be
1150 // forced to reconnect if the forced usage changes.
1151 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Mikhail Naganov55773032020-10-01 15:08:13 -07001152 dstAttr->flags = static_cast<audio_flags_mask_t>(
1153 dstAttr->flags & ~AUDIO_FLAG_AUDIBILITY_ENFORCED);
Eric Laurent22fcda22019-05-17 16:28:47 -07001154 }
1155
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001156 return NO_ERROR;
1157}
1158
Kevin Rocard153f92d2018-12-18 18:33:28 -08001159status_t AudioPolicyManager::getOutputForAttrInt(
1160 audio_attributes_t *resultAttr,
1161 audio_io_handle_t *output,
1162 audio_session_t session,
1163 const audio_attributes_t *attr,
1164 audio_stream_type_t *stream,
1165 uid_t uid,
jiabinf1c73972022-04-14 16:28:52 -07001166 audio_config_t *config,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001167 audio_output_flags_t *flags,
1168 audio_port_handle_t *selectedDeviceId,
1169 bool *isRequestedDeviceForExclusiveUse,
Eric Laurentc529cf62020-04-17 18:19:10 -07001170 std::vector<sp<AudioPolicyMix>> *secondaryMixes,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001171 output_type_t *outputType,
jiabinc658e452022-10-21 20:52:21 +00001172 bool *isSpatialized,
1173 bool *isBitPerfect)
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001174{
François Gaffiec005e562018-11-06 15:04:49 +01001175 DeviceVector outputDevices;
Francois Gaffie716e1432019-01-14 16:58:59 +01001176 const audio_port_handle_t requestedPortId = *selectedDeviceId;
François Gaffie11d30102018-11-02 16:09:09 +01001177 DeviceVector msdDevices = getMsdAudioOutDevices();
François Gaffiec005e562018-11-06 15:04:49 +01001178 const sp<DeviceDescriptor> requestedDevice =
1179 mAvailableOutputDevices.getDeviceFromId(requestedPortId);
1180
Eric Laurent8a1095a2019-11-08 14:44:16 -08001181 *outputType = API_OUTPUT_INVALID;
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001182 *isSpatialized = false;
1183
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001184 status_t status = getAudioAttributes(resultAttr, attr, *stream);
1185 if (status != NO_ERROR) {
1186 return status;
Eric Laurent8f42ea12018-08-08 09:08:25 -07001187 }
Kevin Rocardb99cc752019-03-21 20:52:24 -07001188 if (auto it = mAllowedCapturePolicies.find(uid); it != end(mAllowedCapturePolicies)) {
Mikhail Naganov55773032020-10-01 15:08:13 -07001189 resultAttr->flags = static_cast<audio_flags_mask_t>(resultAttr->flags | it->second);
Kevin Rocardb99cc752019-03-21 20:52:24 -07001190 }
François Gaffiec005e562018-11-06 15:04:49 +01001191 *stream = mEngine->getStreamTypeForAttributes(*resultAttr);
Eric Laurent8f42ea12018-08-08 09:08:25 -07001192
François Gaffiec005e562018-11-06 15:04:49 +01001193 ALOGV("%s() attributes=%s stream=%s session %d selectedDeviceId %d", __func__,
1194 toString(*resultAttr).c_str(), toString(*stream).c_str(), session, requestedPortId);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001195
Oscar Azucena873d10f2023-01-12 18:34:42 -08001196 bool usePrimaryOutputFromPolicyMixes = false;
1197
Kevin Rocard153f92d2018-12-18 18:33:28 -08001198 // The primary output is the explicit routing (eg. setPreferredDevice) if specified,
1199 // otherwise, fallback to the dynamic policies, if none match, query the engine.
1200 // Secondary outputs are always found by dynamic policies as the engine do not support them
Eric Laurentc529cf62020-04-17 18:19:10 -07001201 sp<AudioPolicyMix> primaryMix;
Dean Wheatleyd082f472022-02-04 11:10:48 +11001202 const audio_config_base_t clientConfig = {.sample_rate = config->sample_rate,
1203 .channel_mask = config->channel_mask,
1204 .format = config->format,
1205 };
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02001206 status = mPolicyMixes.getOutputForAttr(*resultAttr, clientConfig, uid, session, *flags,
Oscar Azucena873d10f2023-01-12 18:34:42 -08001207 mAvailableOutputDevices, requestedDevice, primaryMix,
1208 secondaryMixes, usePrimaryOutputFromPolicyMixes);
Kevin Rocard94114a22019-04-01 19:38:23 -07001209 if (status != OK) {
1210 return status;
Kevin Rocard153f92d2018-12-18 18:33:28 -08001211 }
Kevin Rocard94114a22019-04-01 19:38:23 -07001212
Kevin Rocard153f92d2018-12-18 18:33:28 -08001213 // FIXME: in case of RENDER policy, the output capabilities should be checked
Dean Wheatleyd082f472022-02-04 11:10:48 +11001214 if ((secondaryMixes != nullptr && !secondaryMixes->empty())
1215 && !audio_is_linear_pcm(config->format)) {
1216 ALOGD("%s: rejecting request as secondary mixes only support pcm", __func__);
Kevin Rocard153f92d2018-12-18 18:33:28 -08001217 return BAD_VALUE;
1218 }
1219 if (usePrimaryOutputFromPolicyMixes) {
jiabin24ff57a2023-11-27 21:06:51 +00001220 sp<DeviceDescriptor> policyMixDevice =
Eric Laurentc529cf62020-04-17 18:19:10 -07001221 mAvailableOutputDevices.getDevice(primaryMix->mDeviceType,
1222 primaryMix->mDeviceAddress,
1223 AUDIO_FORMAT_DEFAULT);
1224 sp<SwAudioOutputDescriptor> policyDesc = primaryMix->getOutput();
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001225 bool tryDirectForFlags = policyDesc == nullptr ||
jiabin24ff57a2023-11-27 21:06:51 +00001226 (policyDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) ||
1227 (*flags & (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ));
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001228 // if a direct output can be opened to deliver the track's multi-channel content to the
1229 // output rather than being downmixed by the primary output, then use this direct
1230 // output by by-passing the primary mix if possible, otherwise fall-through to primary
1231 // mix.
1232 bool tryDirectForChannelMask = policyDesc != nullptr
1233 && (audio_channel_count_from_out_mask(policyDesc->getConfig().channel_mask) <
1234 audio_channel_count_from_out_mask(config->channel_mask));
jiabin24ff57a2023-11-27 21:06:51 +00001235 if (policyMixDevice != nullptr && (tryDirectForFlags || tryDirectForChannelMask)) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001236 audio_io_handle_t newOutput;
1237 status = openDirectOutput(
1238 *stream, session, config,
1239 (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT),
jiabin24ff57a2023-11-27 21:06:51 +00001240 DeviceVector(policyMixDevice), &newOutput);
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001241 if (status == NO_ERROR) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001242 policyDesc = mOutputs.valueFor(newOutput);
1243 primaryMix->setOutput(policyDesc);
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001244 } else if (tryDirectForFlags) {
jiabin24ff57a2023-11-27 21:06:51 +00001245 ALOGW("%s, failed open direct, status: %d", __func__, status);
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001246 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;
jiabin24ff57a2023-11-27 21:06:51 +00001252 *selectedDeviceId = policyMixDevice != nullptr ? policyMixDevice->getId()
1253 : AUDIO_PORT_HANDLE_NONE;
1254 if ((policyDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != AUDIO_OUTPUT_FLAG_DIRECT) {
1255 // Remove direct flag as it is not on a direct output.
1256 *flags = (audio_output_flags_t) (*flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
1257 }
Eric Laurent8a1095a2019-11-08 14:44:16 -08001258
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08001259 ALOGV("getOutputForAttr() returns output %d", *output);
1260 if (resultAttr->usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
1261 *outputType = API_OUT_MIX_PLAYBACK;
1262 } else {
1263 *outputType = API_OUTPUT_LEGACY;
1264 }
1265 return NO_ERROR;
jiabin24ff57a2023-11-27 21:06:51 +00001266 } else {
1267 if (policyMixDevice != nullptr) {
1268 ALOGE("%s, try to use primary mix but no output found", __func__);
1269 return INVALID_OPERATION;
1270 }
1271 // Fallback to default engine selection as the selected primary mix device is not
1272 // available.
Eric Laurent8a1095a2019-11-08 14:44:16 -08001273 }
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001274 }
François Gaffiec005e562018-11-06 15:04:49 +01001275 // Virtual sources must always be dynamicaly or explicitly routed
1276 if (resultAttr->usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
1277 ALOGW("getOutputForAttr() no policy mix found for usage AUDIO_USAGE_VIRTUAL_SOURCE");
1278 return BAD_VALUE;
1279 }
1280 // explicit routing managed by getDeviceForStrategy in APM is now handled by engine
1281 // in order to let the choice of the order to future vendor engine
1282 outputDevices = mEngine->getOutputDevicesForAttributes(*resultAttr, requestedDevice, false);
Scott Randolph7b1fd232018-06-18 15:33:03 -07001283
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001284 if ((resultAttr->flags & AUDIO_FLAG_HW_AV_SYNC) != 0) {
Nadav Bar766fb022018-01-07 12:18:03 +02001285 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
Eric Laurent93c3d412014-08-01 14:48:35 -07001286 }
1287
Nadav Barb2f18162018-07-18 13:01:53 +03001288 // Set incall music only if device was explicitly set, and fallback to the device which is
1289 // chosen by the engine if not.
1290 // FIXME: provide a more generic approach which is not device specific and move this back
1291 // to getOutputForDevice.
Nadav Bar20919492018-11-20 10:20:51 +02001292 // TODO: Remove check of AUDIO_STREAM_MUSIC once migration is completed on the app side.
jiabin9a3361e2019-10-01 09:38:30 -07001293 if (outputDevices.onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_TELEPHONY_TX) &&
François Gaffiec005e562018-11-06 15:04:49 +01001294 (*stream == AUDIO_STREAM_MUSIC || resultAttr->usage == AUDIO_USAGE_VOICE_COMMUNICATION) &&
Nadav Barb2f18162018-07-18 13:01:53 +03001295 audio_is_linear_pcm(config->format) &&
Eric Laurent74b71512019-11-06 17:21:57 -08001296 isCallAudioAccessible()) {
Francois Gaffie716e1432019-01-14 16:58:59 +01001297 if (requestedPortId != AUDIO_PORT_HANDLE_NONE) {
Nadav Barb2f18162018-07-18 13:01:53 +03001298 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_INCALL_MUSIC;
François Gaffief579db52018-11-13 11:25:16 +01001299 *isRequestedDeviceForExclusiveUse = true;
Nadav Barb2f18162018-07-18 13:01:53 +03001300 }
1301 }
1302
François Gaffiec005e562018-11-06 15:04:49 +01001303 ALOGV("%s() device %s, sampling rate %d, format %#x, channel mask %#x, flags %#x stream %s",
1304 __func__, outputDevices.toString().c_str(), config->sample_rate, config->format,
1305 config->channel_mask, *flags, toString(*stream).c_str());
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001306
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001307 *output = AUDIO_IO_HANDLE_NONE;
François Gaffie11d30102018-11-02 16:09:09 +01001308 if (!msdDevices.isEmpty()) {
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001309 *output = getOutputForDevices(msdDevices, session, resultAttr, config, flags, isSpatialized);
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001310 if (*output != AUDIO_IO_HANDLE_NONE && setMsdOutputPatches(&outputDevices) == NO_ERROR) {
François Gaffiec005e562018-11-06 15:04:49 +01001311 ALOGV("%s() Using MSD devices %s instead of devices %s",
1312 __func__, msdDevices.toString().c_str(), outputDevices.toString().c_str());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001313 } else {
1314 *output = AUDIO_IO_HANDLE_NONE;
1315 }
1316 }
1317 if (*output == AUDIO_IO_HANDLE_NONE) {
jiabina84c3d32022-12-02 18:59:55 +00001318 sp<PreferredMixerAttributesInfo> info = nullptr;
1319 if (outputDevices.size() == 1) {
1320 info = getPreferredMixerAttributesInfo(
1321 outputDevices.itemAt(0)->getId(),
jiabind9a58d32023-06-01 17:57:30 +00001322 mEngine->getProductStrategyForAttributes(*resultAttr),
1323 true /*activeBitPerfectPreferred*/);
jiabin5eaf0962022-12-20 20:11:38 +00001324 // Only use preferred mixer if the uid matches or the preferred mixer is bit-perfect
1325 // and it is currently active.
1326 if (info != nullptr && info->getUid() != uid &&
1327 ((info->getFlags() & AUDIO_OUTPUT_FLAG_BIT_PERFECT) == AUDIO_OUTPUT_FLAG_NONE ||
1328 info->getActiveClientCount() == 0)) {
jiabina84c3d32022-12-02 18:59:55 +00001329 info = nullptr;
1330 }
1331 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001332 *output = getOutputForDevices(outputDevices, session, resultAttr, config,
jiabina84c3d32022-12-02 18:59:55 +00001333 flags, isSpatialized, info, resultAttr->flags & AUDIO_FLAG_MUTE_HAPTIC);
jiabin5eaf0962022-12-20 20:11:38 +00001334 // The client will be active if the client is currently preferred mixer owner and the
1335 // requested configuration matches the preferred mixer configuration.
jiabinc658e452022-10-21 20:52:21 +00001336 *isBitPerfect = (info != nullptr
1337 && (info->getFlags() & AUDIO_OUTPUT_FLAG_BIT_PERFECT) != AUDIO_OUTPUT_FLAG_NONE
jiabin5eaf0962022-12-20 20:11:38 +00001338 && info->getUid() == uid
1339 && *output != AUDIO_IO_HANDLE_NONE
1340 // When bit-perfect output is selected for the preferred mixer attributes owner,
1341 // only need to consider the config matches.
1342 && mOutputs.valueFor(*output)->isConfigurationMatched(
1343 clientConfig, AUDIO_OUTPUT_FLAG_NONE));
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001344 }
Eric Laurente83b55d2014-11-14 10:06:21 -08001345 if (*output == AUDIO_IO_HANDLE_NONE) {
jiabinf1c73972022-04-14 16:28:52 -07001346 AudioProfileVector profiles;
1347 status_t ret = getProfilesForDevices(outputDevices, profiles, *flags, false /*isInput*/);
1348 if (ret == NO_ERROR && !profiles.empty()) {
Robert Wub98ff1b2023-06-15 22:53:58 +00001349 const auto channels = profiles[0]->getChannels();
1350 if (!channels.empty() && (channels.find(config->channel_mask) == channels.end())) {
1351 config->channel_mask = *channels.begin();
1352 }
1353 const auto sampleRates = profiles[0]->getSampleRates();
1354 if (!sampleRates.empty() &&
1355 (sampleRates.find(config->sample_rate) == sampleRates.end())) {
1356 config->sample_rate = *sampleRates.begin();
1357 }
jiabinf1c73972022-04-14 16:28:52 -07001358 config->format = profiles[0]->getFormat();
1359 }
Eric Laurente83b55d2014-11-14 10:06:21 -08001360 return INVALID_OPERATION;
1361 }
Paul McLeanaa981192015-03-21 09:55:15 -07001362
François Gaffiec005e562018-11-06 15:04:49 +01001363 *selectedDeviceId = getFirstDeviceId(outputDevices);
Michael Chan6fb34492020-12-08 15:44:49 +11001364 for (auto &outputDevice : outputDevices) {
Mikhail Naganov68e3f642023-04-28 13:06:32 -07001365 if (outputDevice->getId() == mConfig->getDefaultOutputDevice()->getId()) {
Michael Chan6fb34492020-12-08 15:44:49 +11001366 *selectedDeviceId = outputDevice->getId();
1367 break;
1368 }
1369 }
Eric Laurent2ac76942017-06-22 17:17:09 -07001370
Eric Laurent8a1095a2019-11-08 14:44:16 -08001371 if (outputDevices.onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_TELEPHONY_TX)) {
1372 *outputType = API_OUTPUT_TELEPHONY_TX;
1373 } else {
1374 *outputType = API_OUTPUT_LEGACY;
1375 }
1376
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001377 ALOGV("%s returns output %d selectedDeviceId %d", __func__, *output, *selectedDeviceId);
1378
1379 return NO_ERROR;
1380}
1381
1382status_t AudioPolicyManager::getOutputForAttr(const audio_attributes_t *attr,
1383 audio_io_handle_t *output,
1384 audio_session_t session,
1385 audio_stream_type_t *stream,
Svet Ganov3e5f14f2021-05-13 22:51:08 +00001386 const AttributionSourceState& attributionSource,
jiabinf1c73972022-04-14 16:28:52 -07001387 audio_config_t *config,
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001388 audio_output_flags_t *flags,
1389 audio_port_handle_t *selectedDeviceId,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001390 audio_port_handle_t *portId,
Eric Laurent8a1095a2019-11-08 14:44:16 -08001391 std::vector<audio_io_handle_t> *secondaryOutputs,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001392 output_type_t *outputType,
jiabinc658e452022-10-21 20:52:21 +00001393 bool *isSpatialized,
1394 bool *isBitPerfect)
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001395{
1396 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
1397 if (*portId != AUDIO_PORT_HANDLE_NONE) {
1398 return INVALID_OPERATION;
1399 }
Philip P. Moltmannbda45752020-07-17 16:41:18 -07001400 const uid_t uid = VALUE_OR_RETURN_STATUS(
Svet Ganov3e5f14f2021-05-13 22:51:08 +00001401 aidl2legacy_int32_t_uid_t(attributionSource.uid));
Francois Gaffie716e1432019-01-14 16:58:59 +01001402 const audio_port_handle_t requestedPortId = *selectedDeviceId;
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001403 audio_attributes_t resultAttr;
François Gaffief579db52018-11-13 11:25:16 +01001404 bool isRequestedDeviceForExclusiveUse = false;
Eric Laurentc529cf62020-04-17 18:19:10 -07001405 std::vector<sp<AudioPolicyMix>> secondaryMixes;
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001406 const sp<DeviceDescriptor> requestedDevice =
1407 mAvailableOutputDevices.getDeviceFromId(requestedPortId);
1408
1409 // Prevent from storing invalid requested device id in clients
1410 const audio_port_handle_t sanitizedRequestedPortId =
1411 requestedDevice != nullptr ? requestedPortId : AUDIO_PORT_HANDLE_NONE;
1412 *selectedDeviceId = sanitizedRequestedPortId;
1413
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001414 status_t status = getOutputForAttrInt(&resultAttr, output, session, attr, stream, uid,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001415 config, flags, selectedDeviceId, &isRequestedDeviceForExclusiveUse,
jiabinc658e452022-10-21 20:52:21 +00001416 secondaryOutputs != nullptr ? &secondaryMixes : nullptr, outputType, isSpatialized,
1417 isBitPerfect);
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001418 if (status != NO_ERROR) {
1419 return status;
1420 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001421 std::vector<wp<SwAudioOutputDescriptor>> weakSecondaryOutputDescs;
Eric Laurentc529cf62020-04-17 18:19:10 -07001422 if (secondaryOutputs != nullptr) {
1423 for (auto &secondaryMix : secondaryMixes) {
1424 sp<SwAudioOutputDescriptor> outputDesc = secondaryMix->getOutput();
1425 if (outputDesc != nullptr &&
1426 outputDesc->mIoHandle != AUDIO_IO_HANDLE_NONE) {
1427 secondaryOutputs->push_back(outputDesc->mIoHandle);
1428 weakSecondaryOutputDescs.push_back(outputDesc);
1429 }
1430 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001431 }
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001432
Eric Laurent8fc147b2018-07-22 19:13:55 -07001433 audio_config_base_t clientConfig = {.sample_rate = config->sample_rate,
Nick Desaulniersa30e3202019-10-18 13:38:23 -07001434 .channel_mask = config->channel_mask,
Eric Laurent8fc147b2018-07-22 19:13:55 -07001435 .format = config->format,
Nick Desaulniersa30e3202019-10-18 13:38:23 -07001436 };
jiabin4ef93452019-09-10 14:29:54 -07001437 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurent8f42ea12018-08-08 09:08:25 -07001438
Eric Laurentc209fe42020-06-05 18:11:23 -07001439 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(*output);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001440 sp<TrackClientDescriptor> clientDesc =
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001441 new TrackClientDescriptor(*portId, uid, session, resultAttr, clientConfig,
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001442 sanitizedRequestedPortId, *stream,
François Gaffiec005e562018-11-06 15:04:49 +01001443 mEngine->getProductStrategyForAttributes(resultAttr),
François Gaffieaaac0fd2018-11-22 17:56:39 +01001444 toVolumeSource(resultAttr),
Kevin Rocard153f92d2018-12-18 18:33:28 -08001445 *flags, isRequestedDeviceForExclusiveUse,
Eric Laurentc209fe42020-06-05 18:11:23 -07001446 std::move(weakSecondaryOutputDescs),
1447 outputDesc->mPolicyMix);
Andy Hung39efb7a2018-09-26 15:39:28 -07001448 outputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001449
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001450 ALOGV("%s() returns output %d requestedPortId %d selectedDeviceId %d for port ID %d", __func__,
1451 *output, requestedPortId, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07001452
Eric Laurente83b55d2014-11-14 10:06:21 -08001453 return NO_ERROR;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001454}
1455
Eric Laurentc529cf62020-04-17 18:19:10 -07001456status_t AudioPolicyManager::openDirectOutput(audio_stream_type_t stream,
1457 audio_session_t session,
1458 const audio_config_t *config,
1459 audio_output_flags_t flags,
1460 const DeviceVector &devices,
1461 audio_io_handle_t *output) {
1462
1463 *output = AUDIO_IO_HANDLE_NONE;
1464
1465 // skip direct output selection if the request can obviously be attached to a mixed output
1466 // and not explicitly requested
1467 if (((flags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
1468 audio_is_linear_pcm(config->format) && config->sample_rate <= SAMPLE_RATE_HZ_MAX &&
1469 audio_channel_count_from_out_mask(config->channel_mask) <= 2) {
1470 return NAME_NOT_FOUND;
1471 }
1472
1473 // Do not allow offloading if one non offloadable effect is enabled or MasterMono is enabled.
1474 // This prevents creating an offloaded track and tearing it down immediately after start
1475 // when audioflinger detects there is an active non offloadable effect.
1476 // FIXME: We should check the audio session here but we do not have it in this context.
1477 // This may prevent offloading in rare situations where effects are left active by apps
1478 // in the background.
1479 sp<IOProfile> profile;
1480 if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) ||
1481 !(mEffects.isNonOffloadableEffectEnabled() || mMasterMono)) {
1482 profile = getProfileForOutput(
1483 devices, config->sample_rate, config->format, config->channel_mask,
1484 flags, true /* directOnly */);
1485 }
1486
1487 if (profile == nullptr) {
1488 return NAME_NOT_FOUND;
1489 }
1490
1491 // exclusive outputs for MMAP and Offload are enforced by different session ids.
1492 for (size_t i = 0; i < mOutputs.size(); i++) {
1493 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
1494 if (!desc->isDuplicated() && (profile == desc->mProfile)) {
1495 // reuse direct output if currently open by the same client
1496 // and configured with same parameters
1497 if ((config->sample_rate == desc->getSamplingRate()) &&
1498 (config->format == desc->getFormat()) &&
1499 (config->channel_mask == desc->getChannelMask()) &&
1500 (session == desc->mDirectClientSession)) {
1501 desc->mDirectOpenCount++;
Eric Laurentfecbceb2021-02-09 14:46:43 +01001502 ALOGV("%s reusing direct output %d for session %d", __func__,
Eric Laurentc529cf62020-04-17 18:19:10 -07001503 mOutputs.keyAt(i), session);
1504 *output = mOutputs.keyAt(i);
1505 return NO_ERROR;
1506 }
1507 }
1508 }
1509
1510 if (!profile->canOpenNewIo()) {
1511 return NAME_NOT_FOUND;
1512 }
1513
1514 sp<SwAudioOutputDescriptor> outputDesc =
1515 new SwAudioOutputDescriptor(profile, mpClientInterface);
1516
Michael Chan6fb34492020-12-08 15:44:49 +11001517 // An MSD patch may be using the only output stream that can service this request. Release
1518 // all MSD patches to prioritize this request over any active output on MSD.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001519 releaseMsdOutputPatches(devices);
Eric Laurentc529cf62020-04-17 18:19:10 -07001520
Eric Laurentf1f22e72021-07-13 14:04:14 +02001521 status_t status =
1522 outputDesc->open(config, nullptr /* mixerConfig */, devices, stream, flags, output);
Eric Laurentc529cf62020-04-17 18:19:10 -07001523
1524 // only accept an output with the requested parameters
1525 if (status != NO_ERROR ||
1526 (config->sample_rate != 0 && config->sample_rate != outputDesc->getSamplingRate()) ||
1527 (config->format != AUDIO_FORMAT_DEFAULT && config->format != outputDesc->getFormat()) ||
1528 (config->channel_mask != 0 && config->channel_mask != outputDesc->getChannelMask())) {
1529 ALOGV("%s failed opening direct output: output %d sample rate %d %d,"
1530 "format %d %d, channel mask %04x %04x", __func__, *output, config->sample_rate,
1531 outputDesc->getSamplingRate(), config->format, outputDesc->getFormat(),
1532 config->channel_mask, outputDesc->getChannelMask());
1533 if (*output != AUDIO_IO_HANDLE_NONE) {
1534 outputDesc->close();
1535 }
1536 // fall back to mixer output if possible when the direct output could not be open
1537 if (audio_is_linear_pcm(config->format) &&
1538 config->sample_rate <= SAMPLE_RATE_HZ_MAX) {
1539 return NAME_NOT_FOUND;
1540 }
1541 *output = AUDIO_IO_HANDLE_NONE;
1542 return BAD_VALUE;
1543 }
1544 outputDesc->mDirectOpenCount = 1;
1545 outputDesc->mDirectClientSession = session;
1546
1547 addOutput(*output, outputDesc);
1548 mPreviousOutputs = mOutputs;
1549 ALOGV("%s returns new direct output %d", __func__, *output);
1550 mpClientInterface->onAudioPortListUpdate();
1551 return NO_ERROR;
1552}
1553
François Gaffie11d30102018-11-02 16:09:09 +01001554audio_io_handle_t AudioPolicyManager::getOutputForDevices(
1555 const DeviceVector &devices,
Kevin Rocard169753c2017-03-06 14:18:23 -08001556 audio_session_t session,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001557 const audio_attributes_t *attr,
Eric Laurentfe231122017-11-17 17:48:06 -08001558 const audio_config_t *config,
jiabine375d412019-02-26 12:54:53 -08001559 audio_output_flags_t *flags,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001560 bool *isSpatialized,
jiabina84c3d32022-12-02 18:59:55 +00001561 sp<PreferredMixerAttributesInfo> prefMixerConfigInfo,
jiabine375d412019-02-26 12:54:53 -08001562 bool forceMutingHaptic)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001563{
Andy Hungc88b0642018-04-27 15:42:35 -07001564 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001565
jiabine375d412019-02-26 12:54:53 -08001566 // Discard haptic channel mask when forcing muting haptic channels.
1567 audio_channel_mask_t channelMask = forceMutingHaptic
Mikhail Naganov55773032020-10-01 15:08:13 -07001568 ? static_cast<audio_channel_mask_t>(config->channel_mask & ~AUDIO_CHANNEL_HAPTIC_ALL)
1569 : config->channel_mask;
jiabine375d412019-02-26 12:54:53 -08001570
Eric Laurente552edb2014-03-10 17:42:56 -07001571 // open a direct output if required by specified parameters
1572 //force direct flag if offload flag is set: offloading implies a direct output stream
1573 // and all common behaviors are driven by checking only the direct flag
1574 // this should normally be set appropriately in the policy configuration file
Nadav Bar766fb022018-01-07 12:18:03 +02001575 if ((*flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1576 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurente552edb2014-03-10 17:42:56 -07001577 }
Nadav Bar766fb022018-01-07 12:18:03 +02001578 if ((*flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
1579 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent93c3d412014-08-01 14:48:35 -07001580 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001581
1582 audio_stream_type_t stream = mEngine->getStreamTypeForAttributes(*attr);
1583
Eric Laurente83b55d2014-11-14 10:06:21 -08001584 // only allow deep buffering for music stream type
1585 if (stream != AUDIO_STREAM_MUSIC) {
Nadav Bar766fb022018-01-07 12:18:03 +02001586 *flags = (audio_output_flags_t)(*flags &~AUDIO_OUTPUT_FLAG_DEEP_BUFFER);
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -07001587 } else if (/* stream == AUDIO_STREAM_MUSIC && */
Nadav Bar766fb022018-01-07 12:18:03 +02001588 *flags == AUDIO_OUTPUT_FLAG_NONE &&
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -07001589 property_get_bool("audio.deep_buffer.media", false /* default_value */)) {
1590 // use DEEP_BUFFER as default output for music stream type
Nadav Bar766fb022018-01-07 12:18:03 +02001591 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
Eric Laurente83b55d2014-11-14 10:06:21 -08001592 }
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -07001593 if (stream == AUDIO_STREAM_TTS) {
Nadav Bar766fb022018-01-07 12:18:03 +02001594 *flags = AUDIO_OUTPUT_FLAG_TTS;
Haynes Mathew George84c621e2017-04-25 11:41:50 -07001595 } else if (stream == AUDIO_STREAM_VOICE_CALL &&
Nadav Bar20919492018-11-20 10:20:51 +02001596 audio_is_linear_pcm(config->format) &&
1597 (*flags & AUDIO_OUTPUT_FLAG_INCALL_MUSIC) == 0) {
Nadav Bar766fb022018-01-07 12:18:03 +02001598 *flags = (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_VOIP_RX |
Haynes Mathew George84c621e2017-04-25 11:41:50 -07001599 AUDIO_OUTPUT_FLAG_DIRECT);
1600 ALOGV("Set VoIP and Direct output flags for PCM format");
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -07001601 }
Eric Laurente552edb2014-03-10 17:42:56 -07001602
Carter Hsua3abb402021-10-26 11:11:20 +08001603 // Attach the Ultrasound flag for the AUDIO_CONTENT_TYPE_ULTRASOUND
1604 if (attr->content_type == AUDIO_CONTENT_TYPE_ULTRASOUND) {
1605 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_ULTRASOUND);
1606 }
1607
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001608 *isSpatialized = false;
Eric Laurentfa0f6742021-08-17 18:39:44 +02001609 if (mSpatializerOutput != nullptr
Andy Hung9dd1a5b2022-05-10 15:39:39 -07001610 && canBeSpatializedInt(attr, config, devices.toTypeAddrVector())) {
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001611 *isSpatialized = true;
Eric Laurentfa0f6742021-08-17 18:39:44 +02001612 return mSpatializerOutput->mIoHandle;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001613 }
1614
Eric Laurentc529cf62020-04-17 18:19:10 -07001615 audio_config_t directConfig = *config;
1616 directConfig.channel_mask = channelMask;
1617 status_t status = openDirectOutput(stream, session, &directConfig, *flags, devices, &output);
1618 if (status != NAME_NOT_FOUND) {
Eric Laurente552edb2014-03-10 17:42:56 -07001619 return output;
1620 }
1621
Eric Laurent14cbfca2016-03-17 09:42:16 -07001622 // A request for HW A/V sync cannot fallback to a mixed output because time
1623 // stamps are embedded in audio data
Phil Burk2d059932018-02-15 15:55:11 -08001624 if ((*flags & (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ)) != 0) {
Eric Laurent14cbfca2016-03-17 09:42:16 -07001625 return AUDIO_IO_HANDLE_NONE;
1626 }
Pierre Couillaude73496b2023-03-06 16:19:05 +00001627 // A request for Tuner cannot fallback to a mixed output
1628 if ((directConfig.offload_info.content_id || directConfig.offload_info.sync_id)) {
1629 return AUDIO_IO_HANDLE_NONE;
1630 }
Eric Laurent14cbfca2016-03-17 09:42:16 -07001631
Eric Laurente552edb2014-03-10 17:42:56 -07001632 // ignoring channel mask due to downmix capability in mixer
1633
1634 // open a non direct output
1635
1636 // for non direct outputs, only PCM is supported
Eric Laurentfe231122017-11-17 17:48:06 -08001637 if (audio_is_linear_pcm(config->format)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001638 // get which output is suitable for the specified stream. The actual
1639 // routing change will happen when startOutput() will be called
François Gaffie11d30102018-11-02 16:09:09 +01001640 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
jiabina84c3d32022-12-02 18:59:55 +00001641 if (prefMixerConfigInfo != nullptr) {
1642 for (audio_io_handle_t outputHandle : outputs) {
1643 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(outputHandle);
1644 if (outputDesc->mProfile == prefMixerConfigInfo->getProfile()) {
1645 output = outputHandle;
1646 break;
1647 }
1648 }
1649 if (output == AUDIO_IO_HANDLE_NONE) {
1650 // No output open with the preferred profile. Open a new one.
1651 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
1652 config.channel_mask = prefMixerConfigInfo->getConfigBase().channel_mask;
1653 config.sample_rate = prefMixerConfigInfo->getConfigBase().sample_rate;
1654 config.format = prefMixerConfigInfo->getConfigBase().format;
1655 sp<SwAudioOutputDescriptor> preferredOutput = openOutputWithProfileAndDevice(
1656 prefMixerConfigInfo->getProfile(), devices, nullptr /*mixerConfig*/,
1657 &config, prefMixerConfigInfo->getFlags());
1658 if (preferredOutput == nullptr) {
1659 ALOGE("%s failed to open output with preferred mixer config", __func__);
1660 } else {
1661 output = preferredOutput->mIoHandle;
1662 }
1663 }
1664 } else {
1665 // at this stage we should ignore the DIRECT flag as no direct output could be
1666 // found earlier
1667 *flags = (audio_output_flags_t) (*flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
1668 output = selectOutput(
1669 outputs, *flags, config->format, channelMask, config->sample_rate, session);
1670 }
Eric Laurente552edb2014-03-10 17:42:56 -07001671 }
François Gaffie11d30102018-11-02 16:09:09 +01001672 ALOGW_IF((output == 0), "getOutputForDevices() could not find output for stream %d, "
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001673 "sampling rate %d, format %#x, channels %#x, flags %#x",
jiabine375d412019-02-26 12:54:53 -08001674 stream, config->sample_rate, config->format, channelMask, *flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001675
Eric Laurente552edb2014-03-10 17:42:56 -07001676 return output;
1677}
1678
Mikhail Naganovf02f3672018-11-09 12:44:16 -08001679sp<DeviceDescriptor> AudioPolicyManager::getMsdAudioInDevice() const {
François Gaffie11d30102018-11-02 16:09:09 +01001680 auto msdInDevices = mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1681 mAvailableInputDevices);
1682 return msdInDevices.isEmpty()? nullptr : msdInDevices.itemAt(0);
1683}
1684
1685DeviceVector AudioPolicyManager::getMsdAudioOutDevices() const {
1686 return mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1687 mAvailableOutputDevices);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001688}
1689
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001690const AudioPatchCollection AudioPolicyManager::getMsdOutputPatches() const {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001691 AudioPatchCollection msdPatches;
Mikhail Naganov86112352018-10-04 09:02:49 -07001692 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1693 if (msdModule != 0) {
1694 for (size_t i = 0; i < mAudioPatches.size(); ++i) {
1695 sp<AudioPatch> patch = mAudioPatches.valueAt(i);
1696 for (size_t j = 0; j < patch->mPatch.num_sources; ++j) {
1697 const struct audio_port_config *source = &patch->mPatch.sources[j];
1698 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
1699 source->ext.device.hw_module == msdModule->getHandle()) {
François Gaffieafd4cea2019-11-18 15:50:22 +01001700 msdPatches.addAudioPatch(patch->getHandle(), patch);
Mikhail Naganov86112352018-10-04 09:02:49 -07001701 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001702 }
1703 }
1704 }
1705 return msdPatches;
1706}
1707
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02001708bool AudioPolicyManager::isMsdPatch(const audio_patch_handle_t &handle) const {
1709 ssize_t index = mAudioPatches.indexOfKey(handle);
1710 if (index < 0) {
1711 return false;
1712 }
1713 const sp<AudioPatch> patch = mAudioPatches.valueAt(index);
1714 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1715 if (msdModule == nullptr) {
1716 return false;
1717 }
1718 const struct audio_port_config *sink = &patch->mPatch.sinks[0];
1719 if (getMsdAudioOutDevices().contains(mAvailableOutputDevices.getDeviceFromId(sink->id))) {
1720 return true;
1721 }
1722 index = getMsdOutputPatches().indexOfKey(handle);
1723 if (index < 0) {
1724 return false;
1725 }
1726 return true;
1727}
1728
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001729status_t AudioPolicyManager::getMsdProfiles(bool hwAvSync,
1730 const InputProfileCollection &inputProfiles,
1731 const OutputProfileCollection &outputProfiles,
1732 const sp<DeviceDescriptor> &sourceDevice,
1733 const sp<DeviceDescriptor> &sinkDevice,
1734 AudioProfileVector& sourceProfiles,
1735 AudioProfileVector& sinkProfiles) const {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001736 if (inputProfiles.isEmpty()) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001737 ALOGE("%s() no input profiles for source module", __func__);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001738 return NO_INIT;
1739 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001740 if (outputProfiles.isEmpty()) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001741 ALOGE("%s() no output profiles for sink module", __func__);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001742 return NO_INIT;
1743 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001744 for (const auto &inProfile : inputProfiles) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001745 if (hwAvSync == ((inProfile->getFlags() & AUDIO_INPUT_FLAG_HW_AV_SYNC) != 0) &&
1746 inProfile->supportsDevice(sourceDevice)) {
1747 appendAudioProfiles(sourceProfiles, inProfile->getAudioProfiles());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001748 }
1749 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001750 for (const auto &outProfile : outputProfiles) {
Michael Chan6fb34492020-12-08 15:44:49 +11001751 if (hwAvSync == ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) &&
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001752 outProfile->supportsDevice(sinkDevice)) {
1753 appendAudioProfiles(sinkProfiles, outProfile->getAudioProfiles());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001754 }
1755 }
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001756 return NO_ERROR;
1757}
1758
1759status_t AudioPolicyManager::getBestMsdConfig(bool hwAvSync,
1760 const AudioProfileVector &sourceProfiles, const AudioProfileVector &sinkProfiles,
1761 audio_port_config *sourceConfig, audio_port_config *sinkConfig) const
1762{
Dean Wheatley16809da2022-12-09 14:55:46 +11001763 // Compressed formats for MSD module, ordered from most preferred to least preferred.
1764 static const std::vector<audio_format_t> formatsOrder = {{
1765 AUDIO_FORMAT_IEC60958, AUDIO_FORMAT_MAT_2_1, AUDIO_FORMAT_MAT_2_0, AUDIO_FORMAT_E_AC3,
Dean Wheatley0f27c602023-08-23 13:57:21 +10001766 AUDIO_FORMAT_AC3, AUDIO_FORMAT_PCM_FLOAT, AUDIO_FORMAT_PCM_32_BIT,
1767 AUDIO_FORMAT_PCM_8_24_BIT, AUDIO_FORMAT_PCM_24_BIT_PACKED, AUDIO_FORMAT_PCM_16_BIT }};
Dean Wheatley16809da2022-12-09 14:55:46 +11001768 static const std::vector<audio_channel_mask_t> channelMasksOrder = [](){
1769 // Channel position masks for MSD module, 3D > 2D > 1D ordering (most preferred to least
1770 // preferred).
1771 std::vector<audio_channel_mask_t> masks = {{
1772 AUDIO_CHANNEL_OUT_3POINT1POINT2, AUDIO_CHANNEL_OUT_3POINT0POINT2,
1773 AUDIO_CHANNEL_OUT_2POINT1POINT2, AUDIO_CHANNEL_OUT_2POINT0POINT2,
1774 AUDIO_CHANNEL_OUT_5POINT1, AUDIO_CHANNEL_OUT_STEREO }};
1775 // insert index masks (higher counts most preferred) as preferred over position masks
1776 for (int i = 1; i <= AUDIO_CHANNEL_COUNT_MAX; i++) {
1777 masks.insert(
1778 masks.begin(), audio_channel_mask_for_index_assignment_from_count(i));
1779 }
1780 return masks;
1781 }();
1782
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001783 struct audio_config_base bestSinkConfig;
Dean Wheatley16809da2022-12-09 14:55:46 +11001784 status_t result = findBestMatchingOutputConfig(sourceProfiles, sinkProfiles, formatsOrder,
1785 channelMasksOrder, true /*preferHigherSamplingRates*/, bestSinkConfig);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001786 if (result != NO_ERROR) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001787 ALOGD("%s() no matching config found for sink, hwAvSync: %d",
1788 __func__, hwAvSync);
Greg Kaiser83289652018-07-30 06:13:57 -07001789 return result;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001790 }
1791 sinkConfig->sample_rate = bestSinkConfig.sample_rate;
1792 sinkConfig->channel_mask = bestSinkConfig.channel_mask;
1793 sinkConfig->format = bestSinkConfig.format;
1794 // For encoded streams force direct flag to prevent downstream mixing.
1795 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1796 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_DIRECT);
Dean Wheatley5c9f0832019-11-21 13:39:31 +11001797 if (audio_is_iec61937_compatible(sinkConfig->format)) {
1798 // For formats compatible with IEC61937 encapsulation, assume that
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001799 // the input is IEC61937 framed (for proportional buffer sizing).
Dean Wheatley5c9f0832019-11-21 13:39:31 +11001800 // Add the AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO flag so downstream HAL can distinguish between
1801 // raw and IEC61937 framed streams.
1802 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1803 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO);
1804 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001805 sourceConfig->sample_rate = bestSinkConfig.sample_rate;
1806 // Specify exact channel mask to prevent guessing by bit count in PatchPanel.
Dean Wheatley16809da2022-12-09 14:55:46 +11001807 sourceConfig->channel_mask =
1808 audio_channel_mask_get_representation(bestSinkConfig.channel_mask)
1809 == AUDIO_CHANNEL_REPRESENTATION_INDEX ?
1810 bestSinkConfig.channel_mask : audio_channel_mask_out_to_in(bestSinkConfig.channel_mask);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001811 sourceConfig->format = bestSinkConfig.format;
1812 // Copy input stream directly without any processing (e.g. resampling).
1813 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1814 sourceConfig->flags.input | AUDIO_INPUT_FLAG_DIRECT);
1815 if (hwAvSync) {
1816 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1817 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
1818 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1819 sourceConfig->flags.input | AUDIO_INPUT_FLAG_HW_AV_SYNC);
1820 }
1821 const unsigned int config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE |
1822 AUDIO_PORT_CONFIG_CHANNEL_MASK | AUDIO_PORT_CONFIG_FORMAT | AUDIO_PORT_CONFIG_FLAGS;
1823 sinkConfig->config_mask |= config_mask;
1824 sourceConfig->config_mask |= config_mask;
1825 return NO_ERROR;
1826}
1827
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001828PatchBuilder AudioPolicyManager::buildMsdPatch(bool msdIsSource,
1829 const sp<DeviceDescriptor> &device) const
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001830{
1831 PatchBuilder patchBuilder;
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001832 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1833 ALOG_ASSERT(msdModule != nullptr, "MSD module not available");
1834 sp<HwModule> deviceModule = mHwModules.getModuleForDevice(device, AUDIO_FORMAT_DEFAULT);
1835 if (deviceModule == nullptr) {
1836 ALOGE("%s() unable to get module for %s", __func__, device->toString().c_str());
1837 return patchBuilder;
1838 }
1839 const InputProfileCollection inputProfiles = msdIsSource ?
1840 msdModule->getInputProfiles() : deviceModule->getInputProfiles();
1841 const OutputProfileCollection outputProfiles = msdIsSource ?
1842 deviceModule->getOutputProfiles() : msdModule->getOutputProfiles();
1843
1844 const sp<DeviceDescriptor> sourceDevice = msdIsSource ? getMsdAudioInDevice() : device;
1845 const sp<DeviceDescriptor> sinkDevice = msdIsSource ?
1846 device : getMsdAudioOutDevices().itemAt(0);
1847 patchBuilder.addSource(sourceDevice).addSink(sinkDevice);
1848
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001849 audio_port_config sourceConfig = patchBuilder.patch()->sources[0];
1850 audio_port_config sinkConfig = patchBuilder.patch()->sinks[0];
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001851 AudioProfileVector sourceProfiles;
1852 AudioProfileVector sinkProfiles;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001853 // TODO: Figure out whether MSD module has HW_AV_SYNC flag set in the AP config file.
1854 // For now, we just forcefully try with HwAvSync first.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001855 for (auto hwAvSync : { true, false }) {
1856 if (getMsdProfiles(hwAvSync, inputProfiles, outputProfiles, sourceDevice, sinkDevice,
1857 sourceProfiles, sinkProfiles) != NO_ERROR) {
1858 continue;
1859 }
1860 if (getBestMsdConfig(hwAvSync, sourceProfiles, sinkProfiles, &sourceConfig,
1861 &sinkConfig) == NO_ERROR) {
1862 // Found a matching config. Re-create PatchBuilder with this config.
1863 return (PatchBuilder()).addSource(sourceConfig).addSink(sinkConfig);
1864 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001865 }
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001866 ALOGV("%s() no matching config found. Fall through to default PCM patch"
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001867 " supporting PCM format conversion.", __func__);
1868 return patchBuilder;
1869}
1870
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001871status_t AudioPolicyManager::setMsdOutputPatches(const DeviceVector *outputDevices) {
Michael Chan6fb34492020-12-08 15:44:49 +11001872 DeviceVector devices;
1873 if (outputDevices != nullptr && outputDevices->size() > 0) {
1874 devices.add(*outputDevices);
1875 } else {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001876 // Use media strategy for unspecified output device. This should only
1877 // occur on checkForDeviceAndOutputChanges(). Device connection events may
1878 // therefore invalidate explicit routing requests.
Michael Chan6fb34492020-12-08 15:44:49 +11001879 devices = mEngine->getOutputDevicesForAttributes(
François Gaffiec005e562018-11-06 15:04:49 +01001880 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
Michael Chan6fb34492020-12-08 15:44:49 +11001881 LOG_ALWAYS_FATAL_IF(devices.isEmpty(), "no output device to set MSD patch");
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001882 }
Michael Chan6fb34492020-12-08 15:44:49 +11001883 std::vector<PatchBuilder> patchesToCreate;
1884 for (auto i = 0u; i < devices.size(); ++i) {
1885 ALOGV("%s() for device %s", __func__, devices[i]->toString().c_str());
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001886 patchesToCreate.push_back(buildMsdPatch(true /*msdIsSource*/, devices[i]));
Michael Chan6fb34492020-12-08 15:44:49 +11001887 }
1888 // Retain only the MSD patches associated with outputDevices request.
1889 // Tear down the others, and create new ones as needed.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001890 AudioPatchCollection patchesToRemove = getMsdOutputPatches();
Michael Chan6fb34492020-12-08 15:44:49 +11001891 for (auto it = patchesToCreate.begin(); it != patchesToCreate.end(); ) {
1892 auto retainedPatch = false;
1893 for (auto i = 0u; i < patchesToRemove.size(); ++i) {
1894 if (audio_patches_are_equal(it->patch(), &patchesToRemove[i]->mPatch)) {
1895 patchesToRemove.removeItemsAt(i);
1896 retainedPatch = true;
1897 break;
1898 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001899 }
Michael Chan6fb34492020-12-08 15:44:49 +11001900 if (retainedPatch) {
1901 it = patchesToCreate.erase(it);
1902 continue;
1903 }
1904 ++it;
1905 }
1906 if (patchesToCreate.size() == 0 && patchesToRemove.size() == 0) {
1907 return NO_ERROR;
1908 }
1909 for (auto i = 0u; i < patchesToRemove.size(); ++i) {
1910 auto &currentPatch = patchesToRemove.valueAt(i);
François Gaffieafd4cea2019-11-18 15:50:22 +01001911 releaseAudioPatch(currentPatch->getHandle(), mUidCached);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001912 }
Michael Chan6fb34492020-12-08 15:44:49 +11001913 status_t status = NO_ERROR;
1914 for (const auto &p : patchesToCreate) {
1915 auto currStatus = installPatch(__func__, -1 /*index*/, nullptr /*patchHandle*/,
1916 p.patch(), 0 /*delayMs*/, mUidCached, nullptr /*patchDescPtr*/);
1917 char message[256];
1918 snprintf(message, sizeof(message), "%s() %s: creating MSD patch from device:IN_BUS to "
1919 "device:%#x (format:%#x channels:%#x samplerate:%d)", __func__,
1920 currStatus == NO_ERROR ? "Success" : "Error",
1921 p.patch()->sinks[0].ext.device.type, p.patch()->sources[0].format,
1922 p.patch()->sources[0].channel_mask, p.patch()->sources[0].sample_rate);
1923 if (currStatus == NO_ERROR) {
1924 ALOGD("%s", message);
1925 } else {
1926 ALOGE("%s", message);
1927 if (status == NO_ERROR) {
1928 status = currStatus;
1929 }
1930 }
1931 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001932 return status;
1933}
1934
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001935void AudioPolicyManager::releaseMsdOutputPatches(const DeviceVector& devices) {
1936 AudioPatchCollection msdPatches = getMsdOutputPatches();
Michael Chan6fb34492020-12-08 15:44:49 +11001937 for (size_t i = 0; i < msdPatches.size(); i++) {
1938 const auto& patch = msdPatches[i];
1939 for (size_t j = 0; j < patch->mPatch.num_sinks; ++j) {
1940 const struct audio_port_config *sink = &patch->mPatch.sinks[j];
1941 if (sink->type == AUDIO_PORT_TYPE_DEVICE && devices.getDevice(sink->ext.device.type,
1942 String8(sink->ext.device.address), AUDIO_FORMAT_DEFAULT) != nullptr) {
1943 releaseAudioPatch(patch->getHandle(), mUidCached);
1944 break;
1945 }
1946 }
1947 }
1948}
1949
Dorin Drimus94d94412022-02-02 09:05:02 +01001950bool AudioPolicyManager::msdHasPatchesToAllDevices(const AudioDeviceTypeAddrVector& devices) {
Mikhail Naganov68e3f642023-04-28 13:06:32 -07001951 DeviceVector devicesToCheck =
1952 mConfig->getOutputDevices().getDevicesFromDeviceTypeAddrVec(devices);
Dorin Drimus94d94412022-02-02 09:05:02 +01001953 AudioPatchCollection msdPatches = getMsdOutputPatches();
1954 for (size_t i = 0; i < msdPatches.size(); i++) {
1955 const auto& patch = msdPatches[i];
1956 for (size_t j = 0; j < patch->mPatch.num_sinks; ++j) {
1957 const struct audio_port_config *sink = &patch->mPatch.sinks[j];
1958 if (sink->type == AUDIO_PORT_TYPE_DEVICE) {
1959 const auto& foundDevice = devicesToCheck.getDevice(
1960 sink->ext.device.type, String8(sink->ext.device.address), AUDIO_FORMAT_DEFAULT);
1961 if (foundDevice != nullptr) {
1962 devicesToCheck.remove(foundDevice);
1963 if (devicesToCheck.isEmpty()) {
1964 return true;
1965 }
1966 }
1967 }
1968 }
1969 }
1970 return false;
1971}
1972
Eric Laurente0720872014-03-11 09:30:41 -07001973audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
jiabinebb6af42020-06-09 17:31:17 -07001974 audio_output_flags_t flags,
1975 audio_format_t format,
1976 audio_channel_mask_t channelMask,
1977 uint32_t samplingRate,
1978 audio_session_t sessionId)
Eric Laurente552edb2014-03-10 17:42:56 -07001979{
Eric Laurent16c66dd2019-05-01 17:54:10 -07001980 LOG_ALWAYS_FATAL_IF(!(format == AUDIO_FORMAT_INVALID || audio_is_linear_pcm(format)),
1981 "%s called with format %#x", __func__, format);
1982
jiabinebb6af42020-06-09 17:31:17 -07001983 // Return the output that haptic-generating attached to when 1) session id is specified,
1984 // 2) haptic-generating effect exists for given session id and 3) the output that
1985 // haptic-generating effect attached to is in given outputs.
1986 if (sessionId != AUDIO_SESSION_NONE) {
1987 audio_io_handle_t hapticGeneratingOutput = mEffects.getIoForSession(
1988 sessionId, FX_IID_HAPTICGENERATOR);
1989 if (outputs.indexOf(hapticGeneratingOutput) >= 0) {
1990 return hapticGeneratingOutput;
1991 }
1992 }
1993
Eric Laurent16c66dd2019-05-01 17:54:10 -07001994 // Flags disqualifying an output: the match must happen before calling selectOutput()
1995 static const audio_output_flags_t kExcludedFlags = (audio_output_flags_t)
1996 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ | AUDIO_OUTPUT_FLAG_DIRECT);
1997
1998 // Flags expressing a functional request: must be honored in priority over
1999 // other criteria
2000 static const audio_output_flags_t kFunctionalFlags = (audio_output_flags_t)
2001 (AUDIO_OUTPUT_FLAG_VOIP_RX | AUDIO_OUTPUT_FLAG_INCALL_MUSIC |
Eric Laurente28c66d2022-01-21 13:40:41 +01002002 AUDIO_OUTPUT_FLAG_TTS | AUDIO_OUTPUT_FLAG_DIRECT_PCM | AUDIO_OUTPUT_FLAG_ULTRASOUND |
2003 AUDIO_OUTPUT_FLAG_SPATIALIZER);
Eric Laurent16c66dd2019-05-01 17:54:10 -07002004 // Flags expressing a performance request: have lower priority than serving
2005 // requested sampling rate or channel mask
2006 static const audio_output_flags_t kPerformanceFlags = (audio_output_flags_t)
2007 (AUDIO_OUTPUT_FLAG_FAST | AUDIO_OUTPUT_FLAG_DEEP_BUFFER |
2008 AUDIO_OUTPUT_FLAG_RAW | AUDIO_OUTPUT_FLAG_SYNC);
2009
2010 const audio_output_flags_t functionalFlags =
2011 (audio_output_flags_t)(flags & kFunctionalFlags);
2012 const audio_output_flags_t performanceFlags =
2013 (audio_output_flags_t)(flags & kPerformanceFlags);
2014
2015 audio_io_handle_t bestOutput = (outputs.size() == 0) ? AUDIO_IO_HANDLE_NONE : outputs[0];
2016
Eric Laurente552edb2014-03-10 17:42:56 -07002017 // select one output among several that provide a path to a particular device or set of
François Gaffie11d30102018-11-02 16:09:09 +01002018 // devices (the list was previously build by getOutputsForDevices()).
Eric Laurente552edb2014-03-10 17:42:56 -07002019 // The priority is as follows:
jiabin40573322018-11-08 12:08:02 -08002020 // 1: the output supporting haptic playback when requesting haptic playback
Eric Laurent16c66dd2019-05-01 17:54:10 -07002021 // 2: the output with the highest number of requested functional flags
Carter Hsu199f1892021-10-15 15:47:29 +08002022 // with tiebreak preferring the minimum number of extra functional flags
2023 // (see b/200293124, the incorrect selection of AUDIO_OUTPUT_FLAG_VOIP_RX).
Eric Laurent16c66dd2019-05-01 17:54:10 -07002024 // 3: the output supporting the exact channel mask
2025 // 4: the output with a higher channel count than requested
jiabinb12a6da2022-06-03 20:48:18 +00002026 // 5: the output with the highest sampling rate if the requested sample rate is
2027 // greater than default sampling rate
Eric Laurent16c66dd2019-05-01 17:54:10 -07002028 // 6: the output with the highest number of requested performance flags
2029 // 7: the output with the bit depth the closest to the requested one
2030 // 8: the primary output
2031 // 9: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07002032
Eric Laurent16c66dd2019-05-01 17:54:10 -07002033 // matching criteria values in priority order for best matching output so far
2034 std::vector<uint32_t> bestMatchCriteria(8, 0);
Eric Laurente552edb2014-03-10 17:42:56 -07002035
Eric Laurent16c66dd2019-05-01 17:54:10 -07002036 const uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
2037 const uint32_t hapticChannelCount = audio_channel_count_from_out_mask(
2038 channelMask & AUDIO_CHANNEL_HAPTIC_ALL);
Eric Laurente78b6762018-12-19 16:29:01 -08002039
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002040 for (audio_io_handle_t output : outputs) {
2041 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent16c66dd2019-05-01 17:54:10 -07002042 // matching criteria values in priority order for current output
2043 std::vector<uint32_t> currentMatchCriteria(8, 0);
jiabin40573322018-11-08 12:08:02 -08002044
Eric Laurent16c66dd2019-05-01 17:54:10 -07002045 if (outputDesc->isDuplicated()) {
2046 continue;
2047 }
2048 if ((kExcludedFlags & outputDesc->mFlags) != 0) {
2049 continue;
2050 }
Eric Laurent8838a382014-09-08 16:44:28 -07002051
Eric Laurent16c66dd2019-05-01 17:54:10 -07002052 // If haptic channel is specified, use the haptic output if present.
2053 // When using haptic output, same audio format and sample rate are required.
2054 const uint32_t outputHapticChannelCount = audio_channel_count_from_out_mask(
jiabin5740f082019-08-19 15:08:30 -07002055 outputDesc->getChannelMask() & AUDIO_CHANNEL_HAPTIC_ALL);
Eric Laurent16c66dd2019-05-01 17:54:10 -07002056 if ((hapticChannelCount == 0) != (outputHapticChannelCount == 0)) {
2057 continue;
2058 }
2059 if (outputHapticChannelCount >= hapticChannelCount
jiabin5740f082019-08-19 15:08:30 -07002060 && format == outputDesc->getFormat()
2061 && samplingRate == outputDesc->getSamplingRate()) {
Eric Laurent16c66dd2019-05-01 17:54:10 -07002062 currentMatchCriteria[0] = outputHapticChannelCount;
2063 }
2064
2065 // functional flags match
Carter Hsu199f1892021-10-15 15:47:29 +08002066 const int matchingFunctionalFlags =
2067 __builtin_popcount(outputDesc->mFlags & functionalFlags);
2068 const int totalFunctionalFlags =
2069 __builtin_popcount(outputDesc->mFlags & kFunctionalFlags);
2070 // Prefer matching functional flags, but subtract unnecessary functional flags.
2071 currentMatchCriteria[1] = 100 * (matchingFunctionalFlags + 1) - totalFunctionalFlags;
Eric Laurent16c66dd2019-05-01 17:54:10 -07002072
2073 // channel mask and channel count match
jiabin5740f082019-08-19 15:08:30 -07002074 uint32_t outputChannelCount = audio_channel_count_from_out_mask(
2075 outputDesc->getChannelMask());
Eric Laurent16c66dd2019-05-01 17:54:10 -07002076 if (channelMask != AUDIO_CHANNEL_NONE && channelCount > 2 &&
2077 channelCount <= outputChannelCount) {
2078 if ((audio_channel_mask_get_representation(channelMask) ==
jiabin5740f082019-08-19 15:08:30 -07002079 audio_channel_mask_get_representation(outputDesc->getChannelMask())) &&
2080 ((channelMask & outputDesc->getChannelMask()) == channelMask)) {
Eric Laurent16c66dd2019-05-01 17:54:10 -07002081 currentMatchCriteria[2] = outputChannelCount;
Eric Laurente552edb2014-03-10 17:42:56 -07002082 }
Eric Laurent16c66dd2019-05-01 17:54:10 -07002083 currentMatchCriteria[3] = outputChannelCount;
2084 }
2085
2086 // sampling rate match
jiabinb12a6da2022-06-03 20:48:18 +00002087 if (samplingRate > SAMPLE_RATE_HZ_DEFAULT) {
jiabin5740f082019-08-19 15:08:30 -07002088 currentMatchCriteria[4] = outputDesc->getSamplingRate();
Eric Laurent16c66dd2019-05-01 17:54:10 -07002089 }
2090
2091 // performance flags match
2092 currentMatchCriteria[5] = popcount(outputDesc->mFlags & performanceFlags);
2093
2094 // format match
2095 if (format != AUDIO_FORMAT_INVALID) {
2096 currentMatchCriteria[6] =
jiabin4ef93452019-09-10 14:29:54 -07002097 PolicyAudioPort::kFormatDistanceMax -
2098 PolicyAudioPort::formatDistance(format, outputDesc->getFormat());
Eric Laurent16c66dd2019-05-01 17:54:10 -07002099 }
2100
2101 // primary output match
2102 currentMatchCriteria[7] = outputDesc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY;
2103
2104 // compare match criteria by priority then value
2105 if (std::lexicographical_compare(bestMatchCriteria.begin(), bestMatchCriteria.end(),
2106 currentMatchCriteria.begin(), currentMatchCriteria.end())) {
2107 bestMatchCriteria = currentMatchCriteria;
2108 bestOutput = output;
2109
2110 std::stringstream result;
2111 std::copy(bestMatchCriteria.begin(), bestMatchCriteria.end(),
2112 std::ostream_iterator<int>(result, " "));
2113 ALOGV("%s new bestOutput %d criteria %s",
2114 __func__, bestOutput, result.str().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07002115 }
2116 }
2117
Eric Laurent16c66dd2019-05-01 17:54:10 -07002118 return bestOutput;
Eric Laurente552edb2014-03-10 17:42:56 -07002119}
2120
Eric Laurent8fc147b2018-07-22 19:13:55 -07002121status_t AudioPolicyManager::startOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002122{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002123 ALOGV("%s portId %d", __FUNCTION__, portId);
2124
2125 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2126 if (outputDesc == 0) {
2127 ALOGW("startOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002128 return BAD_VALUE;
2129 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002130 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002131
Eric Laurent8fc147b2018-07-22 19:13:55 -07002132 ALOGV("startOutput() output %d, stream %d, session %d",
Eric Laurent97ac8712018-07-27 18:59:02 -07002133 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurentc75307b2015-03-17 15:29:32 -07002134
Eric Laurent733ce942017-12-07 12:18:25 -08002135 status_t status = outputDesc->start();
2136 if (status != NO_ERROR) {
2137 return status;
Eric Laurent3974e3b2017-12-07 17:58:43 -08002138 }
2139
Eric Laurent97ac8712018-07-27 18:59:02 -07002140 uint32_t delayMs;
2141 status = startSource(outputDesc, client, &delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07002142
2143 if (status != NO_ERROR) {
Eric Laurent733ce942017-12-07 12:18:25 -08002144 outputDesc->stop();
jiabin3ff8d7d2022-12-13 06:27:44 +00002145 if (status == DEAD_OBJECT) {
2146 sp<SwAudioOutputDescriptor> desc =
2147 reopenOutput(outputDesc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
2148 if (desc == nullptr) {
2149 // This is not common, it may indicate something wrong with the HAL.
2150 ALOGE("%s unable to open output with default config", __func__);
2151 return status;
2152 }
2153 desc->mUsePreferredMixerAttributes = true;
2154 }
Eric Laurent8c7e6da2015-04-21 17:37:00 -07002155 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07002156 }
jiabina84c3d32022-12-02 18:59:55 +00002157
2158 // If the client is the first one active on preferred mixer parameters, reopen the output
2159 // if the current mixer parameters doesn't match the preferred one.
2160 if (outputDesc->devices().size() == 1) {
2161 sp<PreferredMixerAttributesInfo> info = getPreferredMixerAttributesInfo(
2162 outputDesc->devices()[0]->getId(), client->strategy());
2163 if (info != nullptr && info->getUid() == client->uid()) {
2164 if (info->getActiveClientCount() == 0 && !outputDesc->isConfigurationMatched(
2165 info->getConfigBase(), info->getFlags())) {
2166 stopSource(outputDesc, client);
2167 outputDesc->stop();
2168 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
2169 config.channel_mask = info->getConfigBase().channel_mask;
2170 config.sample_rate = info->getConfigBase().sample_rate;
2171 config.format = info->getConfigBase().format;
jiabin3ff8d7d2022-12-13 06:27:44 +00002172 sp<SwAudioOutputDescriptor> desc =
2173 reopenOutput(outputDesc, &config, info->getFlags(), __func__);
2174 if (desc == nullptr) {
2175 return BAD_VALUE;
jiabina84c3d32022-12-02 18:59:55 +00002176 }
jiabin3ff8d7d2022-12-13 06:27:44 +00002177 desc->mUsePreferredMixerAttributes = true;
jiabina84c3d32022-12-02 18:59:55 +00002178 // Intentionally return error to let the client side resending request for
2179 // creating and starting.
2180 return DEAD_OBJECT;
2181 }
2182 info->increaseActiveClient();
jiabine3d1f552023-06-14 17:42:17 +00002183 if (info->getActiveClientCount() == 1 &&
2184 (info->getFlags() & AUDIO_OUTPUT_FLAG_BIT_PERFECT) != AUDIO_OUTPUT_FLAG_NONE) {
2185 // If it is first bit-perfect client, reroute all clients that will be routed to
2186 // the bit-perfect sink so that it is guaranteed only bit-perfect stream is active.
2187 PortHandleVector clientsToInvalidate;
2188 for (size_t i = 0; i < mOutputs.size(); i++) {
2189 if (mOutputs[i] == outputDesc ||
jiabin98c519c2023-07-05 17:34:21 +00002190 mOutputs[i]->devices().filter(outputDesc->devices()).isEmpty()) {
jiabine3d1f552023-06-14 17:42:17 +00002191 continue;
2192 }
2193 for (const auto& c : mOutputs[i]->getClientIterable()) {
2194 clientsToInvalidate.push_back(c->portId());
2195 }
2196 }
2197 if (!clientsToInvalidate.empty()) {
2198 ALOGD("%s Invalidate clients due to first bit-perfect client started",
2199 __func__);
2200 mpClientInterface->invalidateTracks(clientsToInvalidate);
2201 }
2202 }
jiabina84c3d32022-12-02 18:59:55 +00002203 }
2204 }
2205
Jean-Michel Trivib1f6e642023-02-07 20:49:04 +00002206 if (client->hasPreferredDevice()) {
2207 // playback activity with preferred device impacts routing occurred, inform upper layers
2208 mpClientInterface->onRoutingUpdated();
2209 }
Eric Laurentc75307b2015-03-17 15:29:32 -07002210 if (delayMs != 0) {
2211 usleep(delayMs * 1000);
2212 }
2213
2214 return status;
2215}
2216
Eric Laurent96d1dda2022-03-14 17:14:19 +01002217bool AudioPolicyManager::isLeUnicastActive() const {
2218 if (isInCall()) {
2219 return true;
2220 }
2221 return isAnyDeviceTypeActive(getAudioDeviceOutLeAudioUnicastSet());
2222}
2223
2224bool AudioPolicyManager::isAnyDeviceTypeActive(const DeviceTypeSet& deviceTypes) const {
2225 if (mAvailableOutputDevices.getDevicesFromTypes(deviceTypes).isEmpty()) {
2226 return false;
2227 }
2228 bool active = mOutputs.isAnyDeviceTypeActive(deviceTypes);
2229 ALOGV("%s active %d", __func__, active);
2230 return active;
2231}
2232
Eric Laurent97ac8712018-07-27 18:59:02 -07002233status_t AudioPolicyManager::startSource(const sp<SwAudioOutputDescriptor>& outputDesc,
2234 const sp<TrackClientDescriptor>& client,
2235 uint32_t *delayMs)
Eric Laurentc75307b2015-03-17 15:29:32 -07002236{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002237 // cannot start playback of STREAM_TTS if any other output is being used
2238 uint32_t beaconMuteLatency = 0;
Eric Laurentc75307b2015-03-17 15:29:32 -07002239
2240 *delayMs = 0;
Eric Laurent97ac8712018-07-27 18:59:02 -07002241 audio_stream_type_t stream = client->stream();
François Gaffie1c878552018-11-22 16:53:21 +01002242 auto clientVolSrc = client->volumeSource();
François Gaffiec005e562018-11-06 15:04:49 +01002243 auto clientStrategy = client->strategy();
2244 auto clientAttr = client->attributes();
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002245 if (stream == AUDIO_STREAM_TTS) {
2246 ALOGV("\t found BEACON stream");
François Gaffie1c878552018-11-22 16:53:21 +01002247 if (!mTtsOutputAvailable && mOutputs.isAnyOutputActive(
Francois Gaffie4404ddb2021-02-04 17:03:38 +01002248 toVolumeSource(AUDIO_STREAM_TTS, false) /*sourceToIgnore*/)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002249 return INVALID_OPERATION;
2250 } else {
2251 beaconMuteLatency = handleEventForBeacon(STARTING_BEACON);
2252 }
2253 } else {
2254 // some playback other than beacon starts
2255 beaconMuteLatency = handleEventForBeacon(STARTING_OUTPUT);
2256 }
2257
Eric Laurent77305a62016-07-25 16:39:22 -07002258 // force device change if the output is inactive and no audio patch is already present.
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002259 // check active before incrementing usage count
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02002260 bool force = !outputDesc->isActive() && !outputDesc->isRouted();
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002261
François Gaffie11d30102018-11-02 16:09:09 +01002262 DeviceVector devices;
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002263 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
Eric Laurent97ac8712018-07-27 18:59:02 -07002264 const char *address = NULL;
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002265 if (policyMix != nullptr) {
François Gaffie11d30102018-11-02 16:09:09 +01002266 audio_devices_t newDeviceType;
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00002267 address = policyMix->mDeviceAddress.c_str();
Kevin Rocard153f92d2018-12-18 18:33:28 -08002268 if ((policyMix->mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie11d30102018-11-02 16:09:09 +01002269 newDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Kevin Rocard153f92d2018-12-18 18:33:28 -08002270 } else {
2271 newDeviceType = policyMix->mDeviceType;
Eric Laurent97ac8712018-07-27 18:59:02 -07002272 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08002273 sp device = mAvailableOutputDevices.getDevice(newDeviceType, String8(address),
2274 AUDIO_FORMAT_DEFAULT);
2275 ALOG_ASSERT(device, "%s: no device found t=%u, a=%s", __func__, newDeviceType, address);
2276 devices.add(device);
Eric Laurent97ac8712018-07-27 18:59:02 -07002277 }
2278
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002279 // requiresMuteCheck is false when we can bypass mute strategy.
2280 // It covers a common case when there is no materially active audio
2281 // and muting would result in unnecessary delay and dropped audio.
2282 const uint32_t outputLatencyMs = outputDesc->latency();
2283 bool requiresMuteCheck = outputDesc->isActive(outputLatencyMs * 2); // account for drain
Eric Laurent96d1dda2022-03-14 17:14:19 +01002284 bool wasLeUnicastActive = isLeUnicastActive();
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002285
Eric Laurente552edb2014-03-10 17:42:56 -07002286 // increment usage count for this stream on the requested output:
2287 // NOTE that the usage count is the same for duplicated output and hardware output which is
2288 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
Eric Laurent592dd7b2018-08-05 18:58:48 -07002289 outputDesc->setClientActive(client, true);
Eric Laurent97ac8712018-07-27 18:59:02 -07002290
2291 if (client->hasPreferredDevice(true)) {
Eric Laurent72af8012023-03-15 17:36:22 +01002292 if (outputDesc->sameExclusivePreferredDevicesCount() > 0) {
François Gaffief96e5432019-04-09 17:13:56 +02002293 // Preferred device may be exclusive, use only if no other active clients on this output
2294 devices = DeviceVector(
2295 mAvailableOutputDevices.getDeviceFromId(client->preferredDeviceId()));
2296 } else {
2297 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
2298 }
François Gaffie11d30102018-11-02 16:09:09 +01002299 if (devices != outputDesc->devices()) {
François Gaffiec005e562018-11-06 15:04:49 +01002300 checkStrategyRoute(clientStrategy, outputDesc->mIoHandle);
Eric Laurent97ac8712018-07-27 18:59:02 -07002301 }
2302 }
Eric Laurente552edb2014-03-10 17:42:56 -07002303
François Gaffiec005e562018-11-06 15:04:49 +01002304 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07002305 selectOutputForMusicEffects();
2306 }
2307
François Gaffie1c878552018-11-22 16:53:21 +01002308 if (outputDesc->getActivityCount(clientVolSrc) == 1 || !devices.isEmpty()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08002309 // starting an output being rerouted?
François Gaffie11d30102018-11-02 16:09:09 +01002310 if (devices.isEmpty()) {
2311 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Eric Laurent275e8e92014-11-30 15:14:47 -08002312 }
François Gaffiec005e562018-11-06 15:04:49 +01002313 bool shouldWait =
2314 (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM)) ||
2315 followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_NOTIFICATION)) ||
2316 (beaconMuteLatency > 0));
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002317 uint32_t waitMs = beaconMuteLatency;
Eric Laurente552edb2014-03-10 17:42:56 -07002318 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01002319 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07002320 if (desc != outputDesc) {
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002321 // An output has a shared device if
2322 // - managed by the same hw module
2323 // - supports the currently selected device
2324 const bool sharedDevice = outputDesc->sharesHwModuleWith(desc)
François Gaffie11d30102018-11-02 16:09:09 +01002325 && (!desc->filterSupportedDevices(devices).isEmpty());
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002326
Eric Laurent77305a62016-07-25 16:39:22 -07002327 // force a device change if any other output is:
2328 // - managed by the same hw module
Jean-Michel Trivi4a5b4812018-02-08 17:22:32 +00002329 // - supports currently selected device
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002330 // - has a current device selection that differs from selected device.
Eric Laurent77305a62016-07-25 16:39:22 -07002331 // - has an active audio patch
Eric Laurente552edb2014-03-10 17:42:56 -07002332 // In this case, the audio HAL must receive the new device selection so that it can
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002333 // change the device currently selected by the other output.
2334 if (sharedDevice &&
François Gaffie11d30102018-11-02 16:09:09 +01002335 desc->devices() != devices &&
Eric Laurent77305a62016-07-25 16:39:22 -07002336 desc->getPatchHandle() != AUDIO_PATCH_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07002337 force = true;
2338 }
2339 // wait for audio on other active outputs to be presented when starting
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002340 // a notification so that audio focus effect can propagate, or that a mute/unmute
2341 // event occurred for beacon
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002342 const uint32_t latencyMs = desc->latency();
2343 const bool isActive = desc->isActive(latencyMs * 2); // account for drain
2344
2345 if (shouldWait && isActive && (waitMs < latencyMs)) {
2346 waitMs = latencyMs;
Eric Laurente552edb2014-03-10 17:42:56 -07002347 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002348
2349 // Require mute check if another output is on a shared device
2350 // and currently active to have proper drain and avoid pops.
2351 // Note restoring AudioTracks onto this output needs to invoke
2352 // a volume ramp if there is no mute.
2353 requiresMuteCheck |= sharedDevice && isActive;
Eric Laurente552edb2014-03-10 17:42:56 -07002354 }
2355 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002356
jiabin3ff8d7d2022-12-13 06:27:44 +00002357 if (outputDesc->mUsePreferredMixerAttributes && devices != outputDesc->devices()) {
2358 // If the output is open with preferred mixer attributes, but the routed device is
2359 // changed when calling this function, returning DEAD_OBJECT to indicate routing
2360 // changed.
2361 return DEAD_OBJECT;
2362 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002363 const uint32_t muteWaitMs =
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05302364 setOutputDevices(__func__, outputDesc, devices, force, 0, nullptr,
2365 requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07002366
Eric Laurente552edb2014-03-10 17:42:56 -07002367 // apply volume rules for current stream and device if necessary
François Gaffieaaac0fd2018-11-22 17:56:39 +01002368 auto &curves = getVolumeCurves(client->attributes());
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00002369 if (NO_ERROR != checkAndSetVolume(curves, client->volumeSource(),
François Gaffieaaac0fd2018-11-22 17:56:39 +01002370 curves.getVolumeIndex(outputDesc->devices().types()),
Eric Laurentc75307b2015-03-17 15:29:32 -07002371 outputDesc,
Francois Gaffied11442b2020-04-27 11:51:09 +02002372 outputDesc->devices().types(), 0 /*delay*/,
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00002373 outputDesc->useHwGain() /*force*/)) {
2374 // request AudioService to reinitialize the volume curves asynchronously
2375 ALOGE("checkAndSetVolume failed, requesting volume range init");
2376 mpClientInterface->onVolumeRangeInitRequest();
2377 };
Eric Laurente552edb2014-03-10 17:42:56 -07002378
2379 // update the outputs if starting an output with a stream that can affect notification
2380 // routing
2381 handleNotificationRoutingForStream(stream);
Eric Laurentc722f302014-12-10 11:21:49 -08002382
Eric Laurent2cbe89a2014-12-19 11:49:08 -08002383 // force reevaluating accessibility routing when ringtone or alarm starts
François Gaffiec005e562018-11-06 15:04:49 +01002384 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM))) {
jiabinc44b3462022-12-08 12:52:31 -08002385 invalidateStreams({AUDIO_STREAM_ACCESSIBILITY});
Eric Laurent2cbe89a2014-12-19 11:49:08 -08002386 }
Eric Laurentdc462862016-07-19 12:29:53 -07002387
2388 if (waitMs > muteWaitMs) {
2389 *delayMs = waitMs - muteWaitMs;
2390 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002391
2392 // FIXME: A device change (muteWaitMs > 0) likely introduces a volume change.
2393 // A volume change enacted by APM with 0 delay is not synchronous, as it goes
2394 // via AudioCommandThread to AudioFlinger. Hence it is possible that the volume
2395 // change occurs after the MixerThread starts and causes a stream volume
2396 // glitch.
2397 //
2398 // We do not introduce additional delay here.
Eric Laurente552edb2014-03-10 17:42:56 -07002399 }
Eric Laurentdc462862016-07-19 12:29:53 -07002400
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002401 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
jiabin9a3361e2019-10-01 09:38:30 -07002402 mEngine->getForceUse(
2403 AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
François Gaffiec005e562018-11-06 15:04:49 +01002404 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), true, outputDesc);
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002405 }
2406
Eric Laurent97ac8712018-07-27 18:59:02 -07002407 // Automatically enable the remote submix input when output is started on a re routing mix
2408 // of type MIX_TYPE_RECORDERS
jiabin9a3361e2019-10-01 09:38:30 -07002409 if (isSingleDeviceType(devices.types(), &audio_is_remote_submix_device) &&
2410 policyMix != NULL && policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002411 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2412 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2413 address,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002414 "remote-submix",
2415 AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07002416 }
2417
Eric Laurent96d1dda2022-03-14 17:14:19 +01002418 checkLeBroadcastRoutes(wasLeUnicastActive, outputDesc, *delayMs);
2419
Eric Laurente552edb2014-03-10 17:42:56 -07002420 return NO_ERROR;
2421}
2422
Eric Laurent96d1dda2022-03-14 17:14:19 +01002423void AudioPolicyManager::checkLeBroadcastRoutes(bool wasUnicastActive,
2424 sp<SwAudioOutputDescriptor> ignoredOutput, uint32_t delayMs) {
2425 bool isUnicastActive = isLeUnicastActive();
2426
2427 if (wasUnicastActive != isUnicastActive) {
jiabin3ff8d7d2022-12-13 06:27:44 +00002428 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent96d1dda2022-03-14 17:14:19 +01002429 //reroute all outputs routed to LE broadcast if LE unicast activy changed on any output
2430 for (size_t i = 0; i < mOutputs.size(); i++) {
2431 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
2432 if (desc != ignoredOutput && desc->isActive()
2433 && ((isUnicastActive &&
2434 !desc->devices().
2435 getDevicesFromType(AUDIO_DEVICE_OUT_BLE_BROADCAST).isEmpty())
2436 || (wasUnicastActive &&
2437 !desc->devices().getDevicesFromTypes(
2438 getAudioDeviceOutLeAudioUnicastSet()).isEmpty()))) {
2439 DeviceVector newDevices = getNewOutputDevices(desc, false /*fromCache*/);
2440 bool force = desc->devices() != newDevices;
jiabin3ff8d7d2022-12-13 06:27:44 +00002441 if (desc->mUsePreferredMixerAttributes && force) {
2442 // If the device is using preferred mixer attributes, the output need to reopen
2443 // with default configuration when the new selected devices are different from
2444 // current routing devices.
2445 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices);
2446 continue;
2447 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05302448 setOutputDevices(__func__, desc, newDevices, force, delayMs);
Eric Laurent96d1dda2022-03-14 17:14:19 +01002449 // re-apply device specific volume if not done by setOutputDevice()
2450 if (!force) {
2451 applyStreamVolumes(desc, newDevices.types(), delayMs);
2452 }
2453 }
2454 }
jiabin3ff8d7d2022-12-13 06:27:44 +00002455 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent96d1dda2022-03-14 17:14:19 +01002456 }
2457}
2458
Eric Laurent8fc147b2018-07-22 19:13:55 -07002459status_t AudioPolicyManager::stopOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002460{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002461 ALOGV("%s portId %d", __FUNCTION__, portId);
2462
2463 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2464 if (outputDesc == 0) {
2465 ALOGW("stopOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002466 return BAD_VALUE;
2467 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002468 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002469
Jean-Michel Trivib1f6e642023-02-07 20:49:04 +00002470 if (client->hasPreferredDevice(true)) {
2471 // playback activity with preferred device impacts routing occurred, inform upper layers
2472 mpClientInterface->onRoutingUpdated();
2473 }
2474
Eric Laurent97ac8712018-07-27 18:59:02 -07002475 ALOGV("stopOutput() output %d, stream %d, session %d",
2476 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurente552edb2014-03-10 17:42:56 -07002477
Eric Laurent97ac8712018-07-27 18:59:02 -07002478 status_t status = stopSource(outputDesc, client);
Eric Laurent3974e3b2017-12-07 17:58:43 -08002479
Eric Laurent733ce942017-12-07 12:18:25 -08002480 if (status == NO_ERROR ) {
2481 outputDesc->stop();
jiabina84c3d32022-12-02 18:59:55 +00002482 } else {
2483 return status;
2484 }
2485
2486 if (outputDesc->devices().size() == 1) {
2487 sp<PreferredMixerAttributesInfo> info = getPreferredMixerAttributesInfo(
2488 outputDesc->devices()[0]->getId(), client->strategy());
2489 if (info != nullptr && info->getUid() == client->uid()) {
2490 info->decreaseActiveClient();
2491 if (info->getActiveClientCount() == 0) {
2492 reopenOutput(outputDesc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
2493 }
2494 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002495 }
2496 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07002497}
2498
Eric Laurent97ac8712018-07-27 18:59:02 -07002499status_t AudioPolicyManager::stopSource(const sp<SwAudioOutputDescriptor>& outputDesc,
2500 const sp<TrackClientDescriptor>& client)
Eric Laurentc75307b2015-03-17 15:29:32 -07002501{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002502 // always handle stream stop, check which stream type is stopping
Eric Laurent97ac8712018-07-27 18:59:02 -07002503 audio_stream_type_t stream = client->stream();
François Gaffie1c878552018-11-22 16:53:21 +01002504 auto clientVolSrc = client->volumeSource();
Eric Laurent96d1dda2022-03-14 17:14:19 +01002505 bool wasLeUnicastActive = isLeUnicastActive();
Eric Laurent97ac8712018-07-27 18:59:02 -07002506
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002507 handleEventForBeacon(stream == AUDIO_STREAM_TTS ? STOPPING_BEACON : STOPPING_OUTPUT);
2508
François Gaffie1c878552018-11-22 16:53:21 +01002509 if (outputDesc->getActivityCount(clientVolSrc) > 0) {
2510 if (outputDesc->getActivityCount(clientVolSrc) == 1) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002511 // Automatically disable the remote submix input when output is stopped on a
2512 // re routing mix of type MIX_TYPE_RECORDERS
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002513 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
jiabin9a3361e2019-10-01 09:38:30 -07002514 if (isSingleDeviceType(
2515 outputDesc->devices().types(), &audio_is_remote_submix_device) &&
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002516 policyMix != nullptr &&
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002517 policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002518 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2519 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002520 policyMix->mDeviceAddress,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002521 "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07002522 }
2523 }
2524 bool forceDeviceUpdate = false;
Eric Laurent72af8012023-03-15 17:36:22 +01002525 if (client->hasPreferredDevice(true) &&
2526 outputDesc->sameExclusivePreferredDevicesCount() < 2) {
François Gaffiec005e562018-11-06 15:04:49 +01002527 checkStrategyRoute(client->strategy(), AUDIO_IO_HANDLE_NONE);
Eric Laurent97ac8712018-07-27 18:59:02 -07002528 forceDeviceUpdate = true;
2529 }
2530
Eric Laurente552edb2014-03-10 17:42:56 -07002531 // decrement usage count of this stream on the output
Eric Laurent592dd7b2018-08-05 18:58:48 -07002532 outputDesc->setClientActive(client, false);
Paul McLeanaa981192015-03-21 09:55:15 -07002533
Eric Laurente552edb2014-03-10 17:42:56 -07002534 // store time at which the stream was stopped - see isStreamActive()
François Gaffie1c878552018-11-22 16:53:21 +01002535 if (outputDesc->getActivityCount(clientVolSrc) == 0 || forceDeviceUpdate) {
François Gaffiec005e562018-11-06 15:04:49 +01002536 outputDesc->setStopTime(client, systemTime());
François Gaffie11d30102018-11-02 16:09:09 +01002537 DeviceVector newDevices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Francois Gaffie3523ab32021-06-22 13:24:34 +02002538
2539 // If the routing does not change, if an output is routed on a device using HwGain
2540 // (aka setAudioPortConfig) and there are still active clients following different
2541 // volume group(s), force reapply volume
2542 bool requiresVolumeCheck = outputDesc->getActivityCount(clientVolSrc) == 0 &&
2543 outputDesc->useHwGain() && outputDesc->isAnyActive(VOLUME_SOURCE_NONE);
2544
Eric Laurente552edb2014-03-10 17:42:56 -07002545 // delay the device switch by twice the latency because stopOutput() is executed when
2546 // the track stop() command is received and at that time the audio track buffer can
2547 // still contain data that needs to be drained. The latency only covers the audio HAL
2548 // and kernel buffers. Also the latency does not always include additional delay in the
2549 // audio path (audio DSP, CODEC ...)
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05302550 setOutputDevices(__func__, outputDesc, newDevices, false, outputDesc->latency()*2,
Francois Gaffie3523ab32021-06-22 13:24:34 +02002551 nullptr, true /*requiresMuteCheck*/, requiresVolumeCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07002552
2553 // force restoring the device selection on other active outputs if it differs from the
2554 // one being selected for this output
jiabin3ff8d7d2022-12-13 06:27:44 +00002555 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent57de36c2016-09-28 16:59:11 -07002556 uint32_t delayMs = outputDesc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -07002557 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01002558 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07002559 if (desc != outputDesc &&
Eric Laurente552edb2014-03-10 17:42:56 -07002560 desc->isActive() &&
2561 outputDesc->sharesHwModuleWith(desc) &&
François Gaffie11d30102018-11-02 16:09:09 +01002562 (newDevices != desc->devices())) {
2563 DeviceVector newDevices2 = getNewOutputDevices(desc, false /*fromCache*/);
2564 bool force = desc->devices() != newDevices2;
Eric Laurentf3a5a602018-05-22 18:42:55 -07002565
jiabin3ff8d7d2022-12-13 06:27:44 +00002566 if (desc->mUsePreferredMixerAttributes && force) {
2567 // If the device is using preferred mixer attributes, the output need to
2568 // reopen with default configuration when the new selected devices are
2569 // different from current routing devices.
2570 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices2);
2571 continue;
2572 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05302573 setOutputDevices(__func__, desc, newDevices2, force, delayMs);
François Gaffie11d30102018-11-02 16:09:09 +01002574
Eric Laurent57de36c2016-09-28 16:59:11 -07002575 // re-apply device specific volume if not done by setOutputDevice()
2576 if (!force) {
François Gaffie11d30102018-11-02 16:09:09 +01002577 applyStreamVolumes(desc, newDevices2.types(), delayMs);
Eric Laurent57de36c2016-09-28 16:59:11 -07002578 }
Eric Laurente552edb2014-03-10 17:42:56 -07002579 }
2580 }
jiabin3ff8d7d2022-12-13 06:27:44 +00002581 reopenOutputsWithDevices(outputsToReopen);
Eric Laurente552edb2014-03-10 17:42:56 -07002582 // update the outputs if stopping one with a stream that can affect notification routing
2583 handleNotificationRoutingForStream(stream);
2584 }
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002585
2586 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
2587 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Jean-Michel Trivi74e01fa2019-02-25 12:18:09 -08002588 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), false, outputDesc);
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002589 }
2590
François Gaffiec005e562018-11-06 15:04:49 +01002591 if (followsSameRouting(client->attributes(), attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07002592 selectOutputForMusicEffects();
2593 }
Eric Laurent96d1dda2022-03-14 17:14:19 +01002594
2595 checkLeBroadcastRoutes(wasLeUnicastActive, outputDesc, outputDesc->latency()*2);
2596
Eric Laurente552edb2014-03-10 17:42:56 -07002597 return NO_ERROR;
2598 } else {
Eric Laurentc75307b2015-03-17 15:29:32 -07002599 ALOGW("stopOutput() refcount is already 0");
Eric Laurente552edb2014-03-10 17:42:56 -07002600 return INVALID_OPERATION;
2601 }
2602}
2603
jiabinbce0c1d2020-10-05 11:20:18 -07002604bool AudioPolicyManager::releaseOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002605{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002606 ALOGV("%s portId %d", __FUNCTION__, portId);
2607
2608 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2609 if (outputDesc == 0) {
Andy Hung39efb7a2018-09-26 15:39:28 -07002610 // If an output descriptor is closed due to a device routing change,
2611 // then there are race conditions with releaseOutput from tracks
2612 // that may be destroyed (with no PlaybackThread) or a PlaybackThread
2613 // destroyed shortly thereafter.
2614 //
2615 // Here we just log a warning, instead of a fatal error.
Eric Laurent8fc147b2018-07-22 19:13:55 -07002616 ALOGW("releaseOutput() no output for client %d", portId);
jiabinbce0c1d2020-10-05 11:20:18 -07002617 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002618 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002619
2620 ALOGV("releaseOutput() %d", outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -07002621
Jaideep Sharma7bf382e2020-11-26 17:07:29 +05302622 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
2623 if (outputDesc->isClientActive(client)) {
2624 ALOGW("releaseOutput() inactivates portId %d in good faith", portId);
2625 stopOutput(portId);
2626 }
2627
Eric Laurent8fc147b2018-07-22 19:13:55 -07002628 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
2629 if (outputDesc->mDirectOpenCount <= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07002630 ALOGW("releaseOutput() invalid open count %d for output %d",
Eric Laurent8fc147b2018-07-22 19:13:55 -07002631 outputDesc->mDirectOpenCount, outputDesc->mIoHandle);
jiabinbce0c1d2020-10-05 11:20:18 -07002632 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002633 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002634 if (--outputDesc->mDirectOpenCount == 0) {
2635 closeOutput(outputDesc->mIoHandle);
Eric Laurentb52c1522014-05-20 11:27:36 -07002636 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07002637 }
2638 }
Jaideep Sharma7bf382e2020-11-26 17:07:29 +05302639
Andy Hung39efb7a2018-09-26 15:39:28 -07002640 outputDesc->removeClient(portId);
jiabinbce0c1d2020-10-05 11:20:18 -07002641 if (outputDesc->mPendingReopenToQueryProfiles && outputDesc->getClientCount() == 0) {
2642 // The output is pending reopened to query dynamic profiles and
2643 // there is no active clients
2644 closeOutput(outputDesc->mIoHandle);
2645 sp<SwAudioOutputDescriptor> newOutputDesc = openOutputWithProfileAndDevice(
2646 outputDesc->mProfile, mEngine->getActiveMediaDevices(mAvailableOutputDevices));
2647 if (newOutputDesc == nullptr) {
2648 ALOGE("%s failed to open output", __func__);
2649 }
2650 return true;
2651 }
2652 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002653}
2654
Eric Laurentcaf7f482014-11-25 17:50:47 -08002655status_t AudioPolicyManager::getInputForAttr(const audio_attributes_t *attr,
2656 audio_io_handle_t *input,
Mikhail Naganov2996f672019-04-18 12:29:59 -07002657 audio_unique_id_t riid,
Eric Laurentcaf7f482014-11-25 17:50:47 -08002658 audio_session_t session,
Svet Ganov3e5f14f2021-05-13 22:51:08 +00002659 const AttributionSourceState& attributionSource,
jiabinf1c73972022-04-14 16:28:52 -07002660 audio_config_base_t *config,
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002661 audio_input_flags_t flags,
Eric Laurent2ac76942017-06-22 17:17:09 -07002662 audio_port_handle_t *selectedDeviceId,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002663 input_type_t *inputType,
2664 audio_port_handle_t *portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002665{
François Gaffiec005e562018-11-06 15:04:49 +01002666 ALOGV("%s() source %d, sampling rate %d, format %#x, channel mask %#x, session %d, "
Eric Laurent2f2c1982021-06-02 14:03:11 +02002667 "flags %#x attributes=%s requested device ID %d",
2668 __func__, attr->source, config->sample_rate, config->format, config->channel_mask,
2669 session, flags, toString(*attr).c_str(), *selectedDeviceId);
Eric Laurente552edb2014-03-10 17:42:56 -07002670
Eric Laurentad2e7b92017-09-14 20:06:42 -07002671 status_t status = NO_ERROR;
Francois Gaffie716e1432019-01-14 16:58:59 +01002672 audio_attributes_t attributes = *attr;
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002673 sp<AudioPolicyMix> policyMix;
François Gaffie11d30102018-11-02 16:09:09 +01002674 sp<DeviceDescriptor> device;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002675 sp<AudioInputDescriptor> inputDesc;
François Gaffie1b4753e2023-02-06 10:36:33 +01002676 sp<AudioInputDescriptor> previousInputDesc;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002677 sp<RecordClientDescriptor> clientDesc;
2678 audio_port_handle_t requestedDeviceId = *selectedDeviceId;
Svet Ganov3e5f14f2021-05-13 22:51:08 +00002679 uid_t uid = VALUE_OR_RETURN_STATUS(aidl2legacy_int32_t_uid_t(attributionSource.uid));
Eric Laurent8f42ea12018-08-08 09:08:25 -07002680 bool isSoundTrigger;
Eric Laurent8f42ea12018-08-08 09:08:25 -07002681
2682 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
2683 if (*portId != AUDIO_PORT_HANDLE_NONE) {
2684 return INVALID_OPERATION;
2685 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08002686
Francois Gaffie716e1432019-01-14 16:58:59 +01002687 if (attr->source == AUDIO_SOURCE_DEFAULT) {
2688 attributes.source = AUDIO_SOURCE_MIC;
Eric Laurentfe231122017-11-17 17:48:06 -08002689 }
2690
Paul McLean466dc8e2015-04-17 13:15:36 -06002691 // Explicit routing?
Pattydd807582021-11-04 21:01:03 +08002692 sp<DeviceDescriptor> explicitRoutingDevice =
François Gaffie11d30102018-11-02 16:09:09 +01002693 mAvailableInputDevices.getDeviceFromId(*selectedDeviceId);
Paul McLean466dc8e2015-04-17 13:15:36 -06002694
Eric Laurentad2e7b92017-09-14 20:06:42 -07002695 // special case for mmap capture: if an input IO handle is specified, we reuse this input if
2696 // possible
2697 if ((flags & AUDIO_INPUT_FLAG_MMAP_NOIRQ) == AUDIO_INPUT_FLAG_MMAP_NOIRQ &&
2698 *input != AUDIO_IO_HANDLE_NONE) {
2699 ssize_t index = mInputs.indexOfKey(*input);
2700 if (index < 0) {
2701 ALOGW("getInputForAttr() unknown MMAP input %d", *input);
2702 status = BAD_VALUE;
2703 goto error;
2704 }
2705 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002706 RecordClientVector clients = inputDesc->getClientsForSession(session);
2707 if (clients.size() == 0) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07002708 ALOGW("getInputForAttr() unknown session %d on input %d", session, *input);
2709 status = BAD_VALUE;
2710 goto error;
2711 }
2712 // For MMAP mode, the first call to getInputForAttr() is made on behalf of audioflinger.
2713 // The second call is for the first active client and sets the UID. Any further call
Eric Laurent331679c2018-04-16 17:03:16 -07002714 // corresponds to a new client and is only permitted from the same UID.
2715 // If the first UID is silenced, allow a new UID connection and replace with new UID
Eric Laurent8f42ea12018-08-08 09:08:25 -07002716 if (clients.size() > 1) {
2717 for (const auto& client : clients) {
2718 // The client map is ordered by key values (portId) and portIds are allocated
2719 // incrementaly. So the first client in this list is the one opened by audio flinger
2720 // when the mmap stream is created and should be ignored as it does not correspond
2721 // to an actual client
2722 if (client == *clients.cbegin()) {
2723 continue;
2724 }
2725 if (uid != client->uid() && !client->isSilenced()) {
2726 ALOGW("getInputForAttr() bad uid %d for client %d uid %d",
2727 uid, client->portId(), client->uid());
2728 status = INVALID_OPERATION;
2729 goto error;
2730 }
Eric Laurent331679c2018-04-16 17:03:16 -07002731 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002732 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002733 *inputType = API_INPUT_LEGACY;
François Gaffie11d30102018-11-02 16:09:09 +01002734 device = inputDesc->getDevice();
Eric Laurentad2e7b92017-09-14 20:06:42 -07002735
Eric Laurentfecbceb2021-02-09 14:46:43 +01002736 ALOGV("%s reusing MMAP input %d for session %d", __FUNCTION__, *input, session);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002737 goto exit;
Eric Laurentad2e7b92017-09-14 20:06:42 -07002738 }
2739
2740 *input = AUDIO_IO_HANDLE_NONE;
2741 *inputType = API_INPUT_INVALID;
2742
Francois Gaffie716e1432019-01-14 16:58:59 +01002743 if (attributes.source == AUDIO_SOURCE_REMOTE_SUBMIX &&
Jan Sebechlebskybc56bcd2022-09-26 13:15:19 +02002744 extractAddressFromAudioAttributes(attributes).has_value()) {
Francois Gaffie716e1432019-01-14 16:58:59 +01002745 status = mPolicyMixes.getInputMixForAttr(attributes, &policyMix);
Eric Laurentad2e7b92017-09-14 20:06:42 -07002746 if (status != NO_ERROR) {
jiabinc1de2df2019-05-07 14:26:40 -07002747 ALOGW("%s could not find input mix for attr %s",
2748 __func__, toString(attributes).c_str());
Eric Laurentad2e7b92017-09-14 20:06:42 -07002749 goto error;
François Gaffie036e1e92015-03-19 10:16:24 +01002750 }
jiabinc1de2df2019-05-07 14:26:40 -07002751 device = mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2752 String8(attr->tags + strlen("addr=")),
2753 AUDIO_FORMAT_DEFAULT);
2754 if (device == nullptr) {
Kevin Rocard04ed0462019-05-02 17:53:24 -07002755 ALOGW("%s could not find in Remote Submix device for source %d, tags %s",
jiabinc1de2df2019-05-07 14:26:40 -07002756 __func__, attributes.source, attributes.tags);
2757 status = BAD_VALUE;
2758 goto error;
2759 }
2760
Kevin Rocard25f9b052019-02-27 15:08:54 -08002761 if (is_mix_loopback_render(policyMix->mRouteFlags)) {
2762 *inputType = API_INPUT_MIX_PUBLIC_CAPTURE_PLAYBACK;
2763 } else {
2764 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
2765 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002766 } else {
François Gaffie11d30102018-11-02 16:09:09 +01002767 if (explicitRoutingDevice != nullptr) {
2768 device = explicitRoutingDevice;
Eric Laurent97ac8712018-07-27 18:59:02 -07002769 } else {
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01002770 // Prevent from storing invalid requested device id in clients
2771 requestedDeviceId = AUDIO_PORT_HANDLE_NONE;
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02002772 device = mEngine->getInputDeviceForAttributes(attributes, uid, session, &policyMix);
yuanjiahsu4069d5d2021-04-19 07:54:27 +08002773 ALOGV_IF(device != nullptr, "%s found device type is 0x%X",
2774 __FUNCTION__, device->type());
Eric Laurent97ac8712018-07-27 18:59:02 -07002775 }
François Gaffie11d30102018-11-02 16:09:09 +01002776 if (device == nullptr) {
Francois Gaffie716e1432019-01-14 16:58:59 +01002777 ALOGW("getInputForAttr() could not find device for source %d", attributes.source);
Eric Laurentad2e7b92017-09-14 20:06:42 -07002778 status = BAD_VALUE;
2779 goto error;
Eric Laurent275e8e92014-11-30 15:14:47 -08002780 }
Alden DSouzab7d20782021-02-08 08:51:42 -08002781 if (device->type() == AUDIO_DEVICE_IN_ECHO_REFERENCE) {
2782 *inputType = API_INPUT_MIX_CAPTURE;
2783 } else if (policyMix) {
François Gaffie11d30102018-11-02 16:09:09 +01002784 ALOG_ASSERT(policyMix->mMixType == MIX_TYPE_RECORDERS, "Invalid Mix Type");
2785 // there is an external policy, but this input is attached to a mix of recorders,
2786 // meaning it receives audio injected into the framework, so the recorder doesn't
2787 // know about it and is therefore considered "legacy"
2788 *inputType = API_INPUT_LEGACY;
2789 } else if (audio_is_remote_submix_device(device->type())) {
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002790 *inputType = API_INPUT_MIX_CAPTURE;
François Gaffie11d30102018-11-02 16:09:09 +01002791 } else if (device->type() == AUDIO_DEVICE_IN_TELEPHONY_RX) {
Eric Laurent82db2692015-08-07 13:59:42 -07002792 *inputType = API_INPUT_TELEPHONY_RX;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002793 } else {
2794 *inputType = API_INPUT_LEGACY;
Eric Laurentc722f302014-12-10 11:21:49 -08002795 }
Ravi Kumar Alamandab367f5b2015-08-25 08:21:37 -07002796
Eric Laurent599c7582015-12-07 18:05:55 -08002797 }
2798
François Gaffiec005e562018-11-06 15:04:49 +01002799 *input = getInputForDevice(device, session, attributes, config, flags, policyMix);
Eric Laurent599c7582015-12-07 18:05:55 -08002800 if (*input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07002801 status = INVALID_OPERATION;
jiabinf1c73972022-04-14 16:28:52 -07002802 AudioProfileVector profiles;
2803 status_t ret = getProfilesForDevices(
2804 DeviceVector(device), profiles, flags, true /*isInput*/);
2805 if (ret == NO_ERROR && !profiles.empty()) {
Robert Wub98ff1b2023-06-15 22:53:58 +00002806 const auto channels = profiles[0]->getChannels();
2807 if (!channels.empty() && (channels.find(config->channel_mask) == channels.end())) {
2808 config->channel_mask = *channels.begin();
2809 }
2810 const auto sampleRates = profiles[0]->getSampleRates();
2811 if (!sampleRates.empty() &&
2812 (sampleRates.find(config->sample_rate) == sampleRates.end())) {
2813 config->sample_rate = *sampleRates.begin();
2814 }
jiabinf1c73972022-04-14 16:28:52 -07002815 config->format = profiles[0]->getFormat();
2816 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002817 goto error;
Eric Laurent599c7582015-12-07 18:05:55 -08002818 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08002819
Eric Laurent8f42ea12018-08-08 09:08:25 -07002820exit:
2821
François Gaffiec005e562018-11-06 15:04:49 +01002822 *selectedDeviceId = mAvailableInputDevices.contains(device) ?
2823 device->getId() : AUDIO_PORT_HANDLE_NONE;
Eric Laurent2ac76942017-06-22 17:17:09 -07002824
Francois Gaffie716e1432019-01-14 16:58:59 +01002825 isSoundTrigger = attributes.source == AUDIO_SOURCE_HOTWORD &&
Carter Hsud0cce2e2019-05-03 17:36:28 +08002826 mSoundTriggerSessions.indexOfKey(session) >= 0;
jiabin4ef93452019-09-10 14:29:54 -07002827 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002828
Mikhail Naganov2996f672019-04-18 12:29:59 -07002829 clientDesc = new RecordClientDescriptor(*portId, riid, uid, session, attributes, *config,
Francois Gaffie716e1432019-01-14 16:58:59 +01002830 requestedDeviceId, attributes.source, flags,
2831 isSoundTrigger);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002832 inputDesc = mInputs.valueFor(*input);
François Gaffie1b4753e2023-02-06 10:36:33 +01002833 // Move (if found) effect for the client session to its input
2834 mEffects.moveEffectsForIo(session, *input, &mInputs, mpClientInterface);
Andy Hung39efb7a2018-09-26 15:39:28 -07002835 inputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002836
2837 ALOGV("getInputForAttr() returns input %d type %d selectedDeviceId %d for port ID %d",
2838 *input, *inputType, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07002839
Eric Laurent599c7582015-12-07 18:05:55 -08002840 return NO_ERROR;
Eric Laurentad2e7b92017-09-14 20:06:42 -07002841
2842error:
Eric Laurentad2e7b92017-09-14 20:06:42 -07002843 return status;
Eric Laurent599c7582015-12-07 18:05:55 -08002844}
2845
2846
François Gaffie11d30102018-11-02 16:09:09 +01002847audio_io_handle_t AudioPolicyManager::getInputForDevice(const sp<DeviceDescriptor> &device,
Eric Laurent599c7582015-12-07 18:05:55 -08002848 audio_session_t session,
François Gaffiec005e562018-11-06 15:04:49 +01002849 const audio_attributes_t &attributes,
jiabinf1c73972022-04-14 16:28:52 -07002850 audio_config_base_t *config,
Eric Laurent599c7582015-12-07 18:05:55 -08002851 audio_input_flags_t flags,
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002852 const sp<AudioPolicyMix> &policyMix)
Eric Laurent599c7582015-12-07 18:05:55 -08002853{
2854 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
François Gaffiec005e562018-11-06 15:04:49 +01002855 audio_source_t halInputSource = attributes.source;
Eric Laurent599c7582015-12-07 18:05:55 -08002856 bool isSoundTrigger = false;
2857
François Gaffiec005e562018-11-06 15:04:49 +01002858 if (attributes.source == AUDIO_SOURCE_HOTWORD) {
Eric Laurent599c7582015-12-07 18:05:55 -08002859 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
2860 if (index >= 0) {
2861 input = mSoundTriggerSessions.valueFor(session);
2862 isSoundTrigger = true;
2863 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_HW_HOTWORD);
2864 ALOGV("SoundTrigger capture on session %d input %d", session, input);
2865 } else {
2866 halInputSource = AUDIO_SOURCE_VOICE_RECOGNITION;
Eric Laurent5dbe4712014-09-19 19:04:57 -07002867 }
François Gaffiec005e562018-11-06 15:04:49 +01002868 } else if (attributes.source == AUDIO_SOURCE_VOICE_COMMUNICATION &&
Eric Laurentfe231122017-11-17 17:48:06 -08002869 audio_is_linear_pcm(config->format)) {
Haynes Mathew George851d3ff2017-06-19 20:01:57 -07002870 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_VOIP_TX);
Eric Laurent5dbe4712014-09-19 19:04:57 -07002871 }
2872
Carter Hsua3abb402021-10-26 11:11:20 +08002873 if (attributes.source == AUDIO_SOURCE_ULTRASOUND) {
2874 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_ULTRASOUND);
2875 }
2876
Eric Laurentfe231122017-11-17 17:48:06 -08002877 // sampling rate and flags may be updated by getInputProfile
2878 uint32_t profileSamplingRate = (config->sample_rate == 0) ?
2879 SAMPLE_RATE_HZ_DEFAULT : config->sample_rate;
jiabin2fd710d2022-05-02 23:20:22 +00002880 audio_format_t profileFormat = config->format;
Eric Laurentfe231122017-11-17 17:48:06 -08002881 audio_channel_mask_t profileChannelMask = config->channel_mask;
Andy Hungf129b032015-04-07 13:45:50 -07002882 audio_input_flags_t profileFlags = flags;
jiabin2fd710d2022-05-02 23:20:22 +00002883 // find a compatible input profile (not necessarily identical in parameters)
2884 sp<IOProfile> profile = getInputProfile(
2885 device, profileSamplingRate, profileFormat, profileChannelMask, profileFlags);
2886 if (profile == nullptr) {
2887 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07002888 }
jiabin2fd710d2022-05-02 23:20:22 +00002889
Glenn Kasten05ddca52016-02-11 08:17:12 -08002890 // Pick input sampling rate if not specified by client
Eric Laurentfe231122017-11-17 17:48:06 -08002891 uint32_t samplingRate = config->sample_rate;
Glenn Kasten05ddca52016-02-11 08:17:12 -08002892 if (samplingRate == 0) {
2893 samplingRate = profileSamplingRate;
2894 }
Eric Laurente552edb2014-03-10 17:42:56 -07002895
Eric Laurent322b4d22015-04-03 15:57:54 -07002896 if (profile->getModuleHandle() == 0) {
2897 ALOGE("getInputForAttr(): HW module %s not opened", profile->getModuleName());
Eric Laurent599c7582015-12-07 18:05:55 -08002898 return input;
Eric Laurentcf2c0212014-07-25 16:20:43 -07002899 }
2900
Eric Laurentec376dc2021-04-08 20:41:22 +02002901 // Reuse an already opened input if a client with the same session ID already exists
2902 // on that input
2903 for (size_t i = 0; i < mInputs.size(); i++) {
2904 sp <AudioInputDescriptor> desc = mInputs.valueAt(i);
2905 if (desc->mProfile != profile) {
2906 continue;
2907 }
2908 RecordClientVector clients = desc->clientsList();
2909 for (const auto &client : clients) {
2910 if (session == client->session()) {
2911 return desc->mIoHandle;
2912 }
2913 }
2914 }
2915
Eric Laurent3974e3b2017-12-07 17:58:43 -08002916 if (!profile->canOpenNewIo()) {
Eric Laurent4eb58f12018-12-07 16:41:02 -08002917 for (size_t i = 0; i < mInputs.size(); ) {
Eric Laurentc529cf62020-04-17 18:19:10 -07002918 sp<AudioInputDescriptor> desc = mInputs.valueAt(i);
Eric Laurent4eb58f12018-12-07 16:41:02 -08002919 if (desc->mProfile != profile) {
Carter Hsu9a645a92019-05-15 12:15:32 +08002920 i++;
Eric Laurent4eb58f12018-12-07 16:41:02 -08002921 continue;
2922 }
2923 // if sound trigger, reuse input if used by other sound trigger on same session
2924 // else
2925 // reuse input if active client app is not in IDLE state
2926 //
2927 RecordClientVector clients = desc->clientsList();
2928 bool doClose = false;
2929 for (const auto& client : clients) {
2930 if (isSoundTrigger != client->isSoundTrigger()) {
2931 continue;
2932 }
2933 if (client->isSoundTrigger()) {
2934 if (session == client->session()) {
2935 return desc->mIoHandle;
2936 }
2937 continue;
2938 }
2939 if (client->active() && client->appState() != APP_STATE_IDLE) {
2940 return desc->mIoHandle;
2941 }
2942 doClose = true;
2943 }
2944 if (doClose) {
2945 closeInput(desc->mIoHandle);
2946 } else {
2947 i++;
2948 }
2949 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002950 }
2951
Eric Laurentfe231122017-11-17 17:48:06 -08002952 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07002953
Eric Laurentfe231122017-11-17 17:48:06 -08002954 audio_config_t lConfig = AUDIO_CONFIG_INITIALIZER;
2955 lConfig.sample_rate = profileSamplingRate;
2956 lConfig.channel_mask = profileChannelMask;
2957 lConfig.format = profileFormat;
Eric Laurente3014102017-05-03 11:15:43 -07002958
François Gaffie11d30102018-11-02 16:09:09 +01002959 status_t status = inputDesc->open(&lConfig, device, halInputSource, profileFlags, &input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07002960
2961 // only accept input with the exact requested set of parameters
Eric Laurent599c7582015-12-07 18:05:55 -08002962 if (status != NO_ERROR || input == AUDIO_IO_HANDLE_NONE ||
Eric Laurentfe231122017-11-17 17:48:06 -08002963 (profileSamplingRate != lConfig.sample_rate) ||
2964 !audio_formats_match(profileFormat, lConfig.format) ||
2965 (profileChannelMask != lConfig.channel_mask)) {
2966 ALOGW("getInputForAttr() failed opening input: sampling rate %d"
Glenn Kasten49f36ba2017-12-06 13:02:02 -08002967 ", format %#x, channel mask %#x",
Eric Laurentfe231122017-11-17 17:48:06 -08002968 profileSamplingRate, profileFormat, profileChannelMask);
Eric Laurent599c7582015-12-07 18:05:55 -08002969 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfe231122017-11-17 17:48:06 -08002970 inputDesc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07002971 }
Eric Laurent599c7582015-12-07 18:05:55 -08002972 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07002973 }
2974
Eric Laurentc722f302014-12-10 11:21:49 -08002975 inputDesc->mPolicyMix = policyMix;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002976
Eric Laurent599c7582015-12-07 18:05:55 -08002977 addInput(input, inputDesc);
Eric Laurentb52c1522014-05-20 11:27:36 -07002978 mpClientInterface->onAudioPortListUpdate();
Paul McLean466dc8e2015-04-17 13:15:36 -06002979
Eric Laurent599c7582015-12-07 18:05:55 -08002980 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07002981}
2982
Eric Laurent4eb58f12018-12-07 16:41:02 -08002983status_t AudioPolicyManager::startInput(audio_port_handle_t portId)
Eric Laurentbb948092017-01-23 18:33:30 -08002984{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002985 ALOGV("%s portId %d", __FUNCTION__, portId);
2986
2987 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2988 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002989 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurentd52a28c2020-08-21 17:10:39 -07002990 return DEAD_OBJECT;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002991 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002992 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07002993 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002994 if (client->active()) {
2995 ALOGW("%s input %d client %d already started", __FUNCTION__, input, client->portId());
2996 return INVALID_OPERATION;
Eric Laurent4dc68062014-07-28 17:26:49 -07002997 }
2998
Eric Laurent8f42ea12018-08-08 09:08:25 -07002999 audio_session_t session = client->session();
3000
Eric Laurent4eb58f12018-12-07 16:41:02 -08003001 ALOGV("%s input:%d, session:%d)", __FUNCTION__, input, session);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003002
Eric Laurent4eb58f12018-12-07 16:41:02 -08003003 Vector<sp<AudioInputDescriptor>> activeInputs = mInputs.getActiveInputs();
Eric Laurent74708e72017-04-07 17:13:42 -07003004
Eric Laurent4eb58f12018-12-07 16:41:02 -08003005 status_t status = inputDesc->start();
3006 if (status != NO_ERROR) {
3007 return status;
Eric Laurent74708e72017-04-07 17:13:42 -07003008 }
Eric Laurente552edb2014-03-10 17:42:56 -07003009
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003010 // increment activity count before calling getNewInputDevice() below as only active sessions
Eric Laurent313d1e72016-01-29 09:56:57 -08003011 // are considered for device selection
Eric Laurent8f42ea12018-08-08 09:08:25 -07003012 inputDesc->setClientActive(client, true);
Eric Laurent313d1e72016-01-29 09:56:57 -08003013
Eric Laurent8f42ea12018-08-08 09:08:25 -07003014 // indicate active capture to sound trigger service if starting capture from a mic on
3015 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01003016 sp<DeviceDescriptor> device = getNewInputDevice(inputDesc);
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003017 if (device != nullptr) {
3018 status = setInputDevice(input, device, true /* force */);
3019 } else {
3020 ALOGW("%s no new input device can be found for descriptor %d",
3021 __FUNCTION__, inputDesc->getId());
3022 status = BAD_VALUE;
3023 }
Eric Laurente552edb2014-03-10 17:42:56 -07003024
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003025 if (status == NO_ERROR && inputDesc->activeCount() == 1) {
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003026 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003027 // if input maps to a dynamic policy with an activity listener, notify of state change
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003028 if ((policyMix != nullptr)
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003029 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
3030 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
Eric Laurent8f42ea12018-08-08 09:08:25 -07003031 MIX_STATE_MIXING);
Eric Laurent733ce942017-12-07 12:18:25 -08003032 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08003033
François Gaffie11d30102018-11-02 16:09:09 +01003034 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
3035 if (primaryInputDevices.contains(device) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07003036 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 1) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07003037 mpClientInterface->setSoundTriggerCaptureState(true);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003038 }
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07003039
Eric Laurent8f42ea12018-08-08 09:08:25 -07003040 // automatically enable the remote submix output when input is started if not
3041 // used by a policy mix of type MIX_TYPE_RECORDERS
3042 // For remote submix (a virtual device), we open only one input per capture request.
François Gaffie11d30102018-11-02 16:09:09 +01003043 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003044 String8 address = String8("");
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003045 if (policyMix == nullptr) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003046 address = String8("0");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003047 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
3048 address = policyMix->mDeviceAddress;
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07003049 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07003050 if (address != "") {
3051 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
3052 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08003053 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurentc722f302014-12-10 11:21:49 -08003054 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07003055 }
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003056 } else if (status != NO_ERROR) {
3057 // Restore client activity state.
3058 inputDesc->setClientActive(client, false);
3059 inputDesc->stop();
Eric Laurente552edb2014-03-10 17:42:56 -07003060 }
3061
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003062 ALOGV("%s input %d source = %d status = %d exit",
3063 __FUNCTION__, input, client->source(), status);
Eric Laurente552edb2014-03-10 17:42:56 -07003064
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003065 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07003066}
3067
Eric Laurent8fc147b2018-07-22 19:13:55 -07003068status_t AudioPolicyManager::stopInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07003069{
Eric Laurent8fc147b2018-07-22 19:13:55 -07003070 ALOGV("%s portId %d", __FUNCTION__, portId);
3071
3072 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
3073 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003074 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07003075 return BAD_VALUE;
3076 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07003077 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07003078 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003079 if (!client->active()) {
3080 ALOGW("%s input %d client %d already stopped", __FUNCTION__, input, client->portId());
Eric Laurente552edb2014-03-10 17:42:56 -07003081 return INVALID_OPERATION;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003082 }
Carter Hsue6139d52021-07-08 10:30:20 +08003083 auto old_source = inputDesc->source();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003084 inputDesc->setClientActive(client, false);
Paul McLean466dc8e2015-04-17 13:15:36 -06003085
Eric Laurent8f42ea12018-08-08 09:08:25 -07003086 inputDesc->stop();
3087 if (inputDesc->isActive()) {
Carter Hsue6139d52021-07-08 10:30:20 +08003088 auto current_source = inputDesc->source();
3089 setInputDevice(input, getNewInputDevice(inputDesc),
3090 old_source != current_source /* force */);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003091 } else {
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003092 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003093 // if input maps to a dynamic policy with an activity listener, notify of state change
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003094 if ((policyMix != nullptr)
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003095 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
3096 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
Eric Laurent8f42ea12018-08-08 09:08:25 -07003097 MIX_STATE_IDLE);
Eric Laurent84332aa2016-01-28 22:19:18 +00003098 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07003099
3100 // automatically disable the remote submix output when input is stopped if not
3101 // used by a policy mix of type MIX_TYPE_RECORDERS
François Gaffie11d30102018-11-02 16:09:09 +01003102 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003103 String8 address = String8("");
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003104 if (policyMix == nullptr) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003105 address = String8("0");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003106 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
3107 address = policyMix->mDeviceAddress;
Eric Laurent8f42ea12018-08-08 09:08:25 -07003108 }
3109 if (address != "") {
3110 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
3111 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08003112 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003113 }
3114 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07003115 resetInputDevice(input);
3116
3117 // indicate inactive capture to sound trigger service if stopping capture from a mic on
3118 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01003119 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
3120 if (primaryInputDevices.contains(inputDesc->getDevice()) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07003121 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07003122 mpClientInterface->setSoundTriggerCaptureState(false);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003123 }
3124 inputDesc->clearPreemptedSessions();
Eric Laurente552edb2014-03-10 17:42:56 -07003125 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003126 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07003127}
3128
Eric Laurent8fc147b2018-07-22 19:13:55 -07003129void AudioPolicyManager::releaseInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07003130{
Eric Laurent8fc147b2018-07-22 19:13:55 -07003131 ALOGV("%s portId %d", __FUNCTION__, portId);
3132
3133 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
3134 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003135 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07003136 return;
3137 }
Andy Hung39efb7a2018-09-26 15:39:28 -07003138 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8fc147b2018-07-22 19:13:55 -07003139 audio_io_handle_t input = inputDesc->mIoHandle;
3140
Eric Laurent8f42ea12018-08-08 09:08:25 -07003141 ALOGV("%s %d", __FUNCTION__, input);
Paul McLean466dc8e2015-04-17 13:15:36 -06003142
Andy Hung39efb7a2018-09-26 15:39:28 -07003143 inputDesc->removeClient(portId);
François Gaffie1b4753e2023-02-06 10:36:33 +01003144 mEffects.putOrphanEffects(client->session(), input, &mInputs, mpClientInterface);
Andy Hung39efb7a2018-09-26 15:39:28 -07003145 if (inputDesc->getClientCount() > 0) {
3146 ALOGV("%s(%d) %zu clients remaining", __func__, portId, inputDesc->getClientCount());
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003147 return;
3148 }
3149
Eric Laurent05b90f82014-08-27 15:32:29 -07003150 closeInput(input);
Eric Laurentb52c1522014-05-20 11:27:36 -07003151 mpClientInterface->onAudioPortListUpdate();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003152 ALOGV("%s exit", __FUNCTION__);
Eric Laurente552edb2014-03-10 17:42:56 -07003153}
3154
Eric Laurent8f42ea12018-08-08 09:08:25 -07003155void AudioPolicyManager::closeActiveClients(const sp<AudioInputDescriptor>& input)
Eric Laurent8fc147b2018-07-22 19:13:55 -07003156{
Eric Laurent8f42ea12018-08-08 09:08:25 -07003157 RecordClientVector clients = input->clientsList(true);
Eric Laurent8fc147b2018-07-22 19:13:55 -07003158
3159 for (const auto& client : clients) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003160 closeClient(client->portId());
Eric Laurent8fc147b2018-07-22 19:13:55 -07003161 }
3162}
3163
Eric Laurent8f42ea12018-08-08 09:08:25 -07003164void AudioPolicyManager::closeClient(audio_port_handle_t portId)
3165{
3166 stopInput(portId);
3167 releaseInput(portId);
3168}
Eric Laurent8fc147b2018-07-22 19:13:55 -07003169
Eric Laurent0dd51852019-04-19 18:18:58 -07003170void AudioPolicyManager::checkCloseInputs() {
3171 // After connecting or disconnecting an input device, close input if:
3172 // - it has no client (was just opened to check profile) OR
3173 // - none of its supported devices are connected anymore OR
3174 // - one of its clients cannot be routed to one of its supported
3175 // devices anymore. Otherwise update device selection
3176 std::vector<audio_io_handle_t> inputsToClose;
3177 for (size_t i = 0; i < mInputs.size(); i++) {
3178 const sp<AudioInputDescriptor> input = mInputs.valueAt(i);
3179 if (input->clientsList().size() == 0
Eric Laurent85732f42020-03-19 11:31:10 -07003180 || !mAvailableInputDevices.containsAtLeastOne(input->supportedDevices())) {
Eric Laurent0dd51852019-04-19 18:18:58 -07003181 inputsToClose.push_back(mInputs.keyAt(i));
3182 } else {
3183 bool close = false;
3184 for (const auto& client : input->clientsList()) {
3185 sp<DeviceDescriptor> device =
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02003186 mEngine->getInputDeviceForAttributes(client->attributes(), client->uid(),
3187 client->session());
Eric Laurent0dd51852019-04-19 18:18:58 -07003188 if (!input->supportedDevices().contains(device)) {
3189 close = true;
3190 break;
3191 }
3192 }
3193 if (close) {
3194 inputsToClose.push_back(mInputs.keyAt(i));
3195 } else {
3196 setInputDevice(input->mIoHandle, getNewInputDevice(input));
3197 }
3198 }
3199 }
3200
3201 for (const audio_io_handle_t handle : inputsToClose) {
3202 ALOGV("%s closing input %d", __func__, handle);
3203 closeInput(handle);
Eric Laurent05b90f82014-08-27 15:32:29 -07003204 }
Eric Laurentd4692962014-05-05 18:13:44 -07003205}
3206
François Gaffie251c7f02018-11-07 10:41:08 +01003207void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream, int indexMin, int indexMax)
Eric Laurente552edb2014-03-10 17:42:56 -07003208{
3209 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08003210 if (indexMin < 0 || indexMax < 0) {
3211 ALOGE("%s for stream %d: invalid min %d or max %d", __func__, stream , indexMin, indexMax);
3212 return;
3213 }
Eric Laurentf5aa58d2019-02-22 18:20:11 -08003214 getVolumeCurves(stream).initVolume(indexMin, indexMax);
Eric Laurent28d09f02016-03-08 10:43:05 -08003215
3216 // initialize other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08003217 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
3218 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08003219 continue;
3220 }
Eric Laurentf5aa58d2019-02-22 18:20:11 -08003221 getVolumeCurves((audio_stream_type_t)curStream).initVolume(indexMin, indexMax);
Eric Laurent223fd5c2014-11-11 13:43:36 -08003222 }
Eric Laurente552edb2014-03-10 17:42:56 -07003223}
3224
Eric Laurente0720872014-03-11 09:30:41 -07003225status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
François Gaffie53615e22015-03-19 09:24:12 +01003226 int index,
3227 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07003228{
François Gaffieaaac0fd2018-11-22 17:56:39 +01003229 auto attributes = mEngine->getAttributesForStreamType(stream);
Eric Laurent242a9f82020-03-23 15:57:04 -07003230 if (attributes == AUDIO_ATTRIBUTES_INITIALIZER) {
3231 ALOGW("%s: no group for stream %s, bailing out", __func__, toString(stream).c_str());
3232 return NO_ERROR;
3233 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01003234 ALOGV("%s: stream %s attributes=%s", __func__,
3235 toString(stream).c_str(), toString(attributes).c_str());
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003236 return setVolumeIndexForAttributes(attributes, index, device);
Eric Laurente552edb2014-03-10 17:42:56 -07003237}
3238
Eric Laurente0720872014-03-11 09:30:41 -07003239status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
François Gaffieaaac0fd2018-11-22 17:56:39 +01003240 int *index,
3241 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07003242{
François Gaffiec005e562018-11-06 15:04:49 +01003243 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
3244 // stream by the engine.
jiabin9a3361e2019-10-01 09:38:30 -07003245 DeviceTypeSet deviceTypes = {device};
Eric Laurent5a2b6292016-04-14 18:05:57 -07003246 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
jiabin9a3361e2019-10-01 09:38:30 -07003247 deviceTypes = mEngine->getOutputDevicesForStream(
3248 stream, true /*fromCache*/).types();
Eric Laurente552edb2014-03-10 17:42:56 -07003249 }
jiabin9a3361e2019-10-01 09:38:30 -07003250 return getVolumeIndex(getVolumeCurves(stream), *index, deviceTypes);
Eric Laurente552edb2014-03-10 17:42:56 -07003251}
3252
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003253status_t AudioPolicyManager::setVolumeIndexForAttributes(const audio_attributes_t &attributes,
François Gaffiecfe17322018-11-07 13:41:29 +01003254 int index,
3255 audio_devices_t device)
3256{
3257 // Get Volume group matching the Audio Attributes
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003258 auto group = mEngine->getVolumeGroupForAttributes(attributes);
3259 if (group == VOLUME_GROUP_NONE) {
3260 ALOGD("%s: no group matching with %s", __FUNCTION__, toString(attributes).c_str());
François Gaffiecfe17322018-11-07 13:41:29 +01003261 return BAD_VALUE;
3262 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003263 ALOGV("%s: group %d matching with %s", __FUNCTION__, group, toString(attributes).c_str());
François Gaffiecfe17322018-11-07 13:41:29 +01003264 status_t status = NO_ERROR;
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003265 IVolumeCurves &curves = getVolumeCurves(attributes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01003266 VolumeSource vs = toVolumeSource(group);
Eric Laurentf9cccec2022-11-16 19:12:00 +01003267 // AUDIO_STREAM_BLUETOOTH_SCO is only used for volume control so we remap
3268 // to AUDIO_STREAM_VOICE_CALL to match with relevant playback activity
3269 VolumeSource activityVs = (vs == toVolumeSource(AUDIO_STREAM_BLUETOOTH_SCO, false)) ?
3270 toVolumeSource(AUDIO_STREAM_VOICE_CALL, false) : vs;
François Gaffieaaac0fd2018-11-22 17:56:39 +01003271 product_strategy_t strategy = mEngine->getProductStrategyForAttributes(attributes);
3272
3273 status = setVolumeCurveIndex(index, device, curves);
3274 if (status != NO_ERROR) {
3275 ALOGE("%s failed to set curve index for group %d device 0x%X", __func__, group, device);
3276 return status;
3277 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003278
jiabin9a3361e2019-10-01 09:38:30 -07003279 DeviceTypeSet curSrcDevices;
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003280 auto curCurvAttrs = curves.getAttributes();
3281 if (!curCurvAttrs.empty() && curCurvAttrs.front() != defaultAttr) {
3282 auto attr = curCurvAttrs.front();
jiabin9a3361e2019-10-01 09:38:30 -07003283 curSrcDevices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false).types();
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003284 } else if (!curves.getStreamTypes().empty()) {
3285 auto stream = curves.getStreamTypes().front();
jiabin9a3361e2019-10-01 09:38:30 -07003286 curSrcDevices = mEngine->getOutputDevicesForStream(stream, false).types();
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003287 } else {
3288 ALOGE("%s: Invalid src %d: no valid attributes nor stream",__func__, vs);
3289 return BAD_VALUE;
3290 }
jiabin9a3361e2019-10-01 09:38:30 -07003291 audio_devices_t curSrcDevice = Volume::getDeviceForVolume(curSrcDevices);
3292 resetDeviceTypes(curSrcDevices, curSrcDevice);
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003293
François Gaffiecfe17322018-11-07 13:41:29 +01003294 // update volume on all outputs and streams matching the following:
3295 // - The requested stream (or a stream matching for volume control) is active on the output
3296 // - The device (or devices) selected by the engine for this stream includes
3297 // the requested device
3298 // - For non default requested device, currently selected device on the output is either the
3299 // requested device or one of the devices selected by the engine for this stream
3300 // - For default requested device (AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME), apply volume only if
3301 // no specific device volume value exists for currently selected device.
François Gaffieaaac0fd2018-11-22 17:56:39 +01003302 for (size_t i = 0; i < mOutputs.size(); i++) {
3303 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
jiabin9a3361e2019-10-01 09:38:30 -07003304 DeviceTypeSet curDevices = desc->devices().types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01003305
jiabin9a3361e2019-10-01 09:38:30 -07003306 if (curDevices.erase(AUDIO_DEVICE_OUT_SPEAKER_SAFE)) {
3307 curDevices.insert(AUDIO_DEVICE_OUT_SPEAKER);
Robert Lee5e66e792019-04-03 18:37:15 +08003308 }
Eric Laurentf9cccec2022-11-16 19:12:00 +01003309
3310 if (!(desc->isActive(activityVs) || isInCallOrScreening())) {
François Gaffieed91f582020-01-31 10:35:37 +01003311 continue;
3312 }
3313 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME &&
3314 curDevices.find(device) == curDevices.end()) {
3315 continue;
3316 }
3317 bool applyVolume = false;
3318 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
3319 curSrcDevices.insert(device);
3320 applyVolume = (curSrcDevices.find(
3321 Volume::getDeviceForVolume(curDevices)) != curSrcDevices.end());
3322 } else {
3323 applyVolume = !curves.hasVolumeIndexForDevice(curSrcDevice);
3324 }
3325 if (!applyVolume) {
3326 continue; // next output
3327 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01003328 // Inter / intra volume group priority management: Loop on strategies arranged by priority
3329 // If a higher priority strategy is active, and the output is routed to a device with a
3330 // HW Gain management, do not change the volume
François Gaffieaaac0fd2018-11-22 17:56:39 +01003331 if (desc->useHwGain()) {
François Gaffieed91f582020-01-31 10:35:37 +01003332 applyVolume = false;
Francois Gaffie593634d2021-06-22 13:31:31 +02003333 // If the volume source is active with higher priority source, ensure at least Sw Muted
3334 desc->setSwMute((index == 0), vs, curves.getStreamTypes(), curDevices, 0 /*delayMs*/);
François Gaffieaaac0fd2018-11-22 17:56:39 +01003335 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
3336 auto activeClients = desc->clientsList(true /*activeOnly*/, productStrategy,
3337 false /*preferredDevice*/);
3338 if (activeClients.empty()) {
3339 continue;
3340 }
3341 bool isPreempted = false;
3342 bool isHigherPriority = productStrategy < strategy;
3343 for (const auto &client : activeClients) {
Eric Laurentf9cccec2022-11-16 19:12:00 +01003344 if (isHigherPriority && (client->volumeSource() != activityVs)) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01003345 ALOGV("%s: Strategy=%d (\nrequester:\n"
3346 " group %d, volumeGroup=%d attributes=%s)\n"
3347 " higher priority source active:\n"
3348 " volumeGroup=%d attributes=%s) \n"
3349 " on output %zu, bailing out", __func__, productStrategy,
3350 group, group, toString(attributes).c_str(),
3351 client->volumeSource(), toString(client->attributes()).c_str(), i);
3352 applyVolume = false;
3353 isPreempted = true;
3354 break;
3355 }
3356 // However, continue for loop to ensure no higher prio clients running on output
Eric Laurentf9cccec2022-11-16 19:12:00 +01003357 if (client->volumeSource() == activityVs) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01003358 applyVolume = true;
3359 }
3360 }
3361 if (isPreempted || applyVolume) {
3362 break;
3363 }
3364 }
3365 if (!applyVolume) {
3366 continue; // next output
3367 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01003368 }
François Gaffieed91f582020-01-31 10:35:37 +01003369 //FIXME: workaround for truncated touch sounds
3370 // delayed volume change for system stream to be removed when the problem is
3371 // handled by system UI
3372 status_t volStatus = checkAndSetVolume(
3373 curves, vs, index, desc, curDevices,
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003374 ((vs == toVolumeSource(AUDIO_STREAM_SYSTEM, false))?
François Gaffieed91f582020-01-31 10:35:37 +01003375 TOUCH_SOUND_FIXED_DELAY_MS : 0));
3376 if (volStatus != NO_ERROR) {
3377 status = volStatus;
François Gaffieaaac0fd2018-11-22 17:56:39 +01003378 }
3379 }
François Gaffiecfe17322018-11-07 13:41:29 +01003380 mpClientInterface->onAudioVolumeGroupChanged(group, 0 /*flags*/);
3381 return status;
3382}
3383
François Gaffieaaac0fd2018-11-22 17:56:39 +01003384status_t AudioPolicyManager::setVolumeCurveIndex(int index,
François Gaffiecfe17322018-11-07 13:41:29 +01003385 audio_devices_t device,
3386 IVolumeCurves &volumeCurves)
3387{
3388 // VOICE_CALL stream has minVolumeIndex > 0 but can be muted directly by an
3389 // app that has MODIFY_PHONE_STATE permission.
François Gaffieaaac0fd2018-11-22 17:56:39 +01003390 bool hasVoice = hasVoiceStream(volumeCurves.getStreamTypes());
3391 if (((index < volumeCurves.getVolumeIndexMin()) && !(hasVoice && index == 0)) ||
François Gaffiecfe17322018-11-07 13:41:29 +01003392 (index > volumeCurves.getVolumeIndexMax())) {
3393 ALOGD("%s: wrong index %d min=%d max=%d", __FUNCTION__, index,
3394 volumeCurves.getVolumeIndexMin(), volumeCurves.getVolumeIndexMax());
3395 return BAD_VALUE;
3396 }
3397 if (!audio_is_output_device(device)) {
3398 return BAD_VALUE;
3399 }
3400
3401 // Force max volume if stream cannot be muted
3402 if (!volumeCurves.canBeMuted()) index = volumeCurves.getVolumeIndexMax();
3403
François Gaffieaaac0fd2018-11-22 17:56:39 +01003404 ALOGV("%s device %08x, index %d", __FUNCTION__ , device, index);
François Gaffiecfe17322018-11-07 13:41:29 +01003405 volumeCurves.addCurrentVolumeIndex(device, index);
3406 return NO_ERROR;
3407}
3408
3409status_t AudioPolicyManager::getVolumeIndexForAttributes(const audio_attributes_t &attr,
3410 int &index,
3411 audio_devices_t device)
3412{
3413 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
3414 // stream by the engine.
jiabin9a3361e2019-10-01 09:38:30 -07003415 DeviceTypeSet deviceTypes = {device};
François Gaffiecfe17322018-11-07 13:41:29 +01003416 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
Mikhail Naganovbb990f22022-06-15 00:46:43 +00003417 deviceTypes = mEngine->getOutputDevicesForAttributes(
jiabin9a3361e2019-10-01 09:38:30 -07003418 attr, nullptr, true /*fromCache*/).types();
François Gaffiecfe17322018-11-07 13:41:29 +01003419 }
jiabin9a3361e2019-10-01 09:38:30 -07003420 return getVolumeIndex(getVolumeCurves(attr), index, deviceTypes);
François Gaffiecfe17322018-11-07 13:41:29 +01003421}
3422
3423status_t AudioPolicyManager::getVolumeIndex(const IVolumeCurves &curves,
3424 int &index,
jiabin9a3361e2019-10-01 09:38:30 -07003425 const DeviceTypeSet& deviceTypes) const
François Gaffiecfe17322018-11-07 13:41:29 +01003426{
Mikhail Naganovbb990f22022-06-15 00:46:43 +00003427 if (!isSingleDeviceType(deviceTypes, audio_is_output_device)) {
François Gaffiecfe17322018-11-07 13:41:29 +01003428 return BAD_VALUE;
3429 }
jiabin9a3361e2019-10-01 09:38:30 -07003430 index = curves.getVolumeIndex(deviceTypes);
3431 ALOGV("%s: device %s index %d", __FUNCTION__, dumpDeviceTypes(deviceTypes).c_str(), index);
François Gaffiecfe17322018-11-07 13:41:29 +01003432 return NO_ERROR;
3433}
3434
3435status_t AudioPolicyManager::getMinVolumeIndexForAttributes(const audio_attributes_t &attr,
3436 int &index)
3437{
3438 index = getVolumeCurves(attr).getVolumeIndexMin();
3439 return NO_ERROR;
3440}
3441
3442status_t AudioPolicyManager::getMaxVolumeIndexForAttributes(const audio_attributes_t &attr,
3443 int &index)
3444{
3445 index = getVolumeCurves(attr).getVolumeIndexMax();
3446 return NO_ERROR;
3447}
3448
Eric Laurent36829f92017-04-07 19:04:42 -07003449audio_io_handle_t AudioPolicyManager::selectOutputForMusicEffects()
Eric Laurente552edb2014-03-10 17:42:56 -07003450{
3451 // select one output among several suitable for global effects.
3452 // The priority is as follows:
3453 // 1: An offloaded output. If the effect ends up not being offloadable,
3454 // AudioFlinger will invalidate the track and the offloaded output
3455 // will be closed causing the effect to be moved to a PCM output.
3456 // 2: A deep buffer output
Eric Laurent36829f92017-04-07 19:04:42 -07003457 // 3: The primary output
3458 // 4: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07003459
François Gaffiec005e562018-11-06 15:04:49 +01003460 DeviceVector devices = mEngine->getOutputDevicesForAttributes(
3461 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
François Gaffie11d30102018-11-02 16:09:09 +01003462 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07003463
Eric Laurent36829f92017-04-07 19:04:42 -07003464 if (outputs.size() == 0) {
3465 return AUDIO_IO_HANDLE_NONE;
3466 }
Eric Laurente552edb2014-03-10 17:42:56 -07003467
Eric Laurent36829f92017-04-07 19:04:42 -07003468 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
3469 bool activeOnly = true;
3470
3471 while (output == AUDIO_IO_HANDLE_NONE) {
3472 audio_io_handle_t outputOffloaded = AUDIO_IO_HANDLE_NONE;
3473 audio_io_handle_t outputDeepBuffer = AUDIO_IO_HANDLE_NONE;
3474 audio_io_handle_t outputPrimary = AUDIO_IO_HANDLE_NONE;
3475
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003476 for (audio_io_handle_t output : outputs) {
3477 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
Eric Laurent83d17c22019-04-02 17:10:01 -07003478 if (activeOnly && !desc->isActive(toVolumeSource(AUDIO_STREAM_MUSIC))) {
Eric Laurent36829f92017-04-07 19:04:42 -07003479 continue;
3480 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003481 ALOGV("selectOutputForMusicEffects activeOnly %d output %d flags 0x%08x",
3482 activeOnly, output, desc->mFlags);
Eric Laurent36829f92017-04-07 19:04:42 -07003483 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003484 outputOffloaded = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003485 }
3486 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003487 outputDeepBuffer = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003488 }
3489 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003490 outputPrimary = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003491 }
3492 }
3493 if (outputOffloaded != AUDIO_IO_HANDLE_NONE) {
3494 output = outputOffloaded;
3495 } else if (outputDeepBuffer != AUDIO_IO_HANDLE_NONE) {
3496 output = outputDeepBuffer;
3497 } else if (outputPrimary != AUDIO_IO_HANDLE_NONE) {
3498 output = outputPrimary;
3499 } else {
3500 output = outputs[0];
3501 }
3502 activeOnly = false;
3503 }
3504
3505 if (output != mMusicEffectOutput) {
François Gaffie1b4753e2023-02-06 10:36:33 +01003506 mEffects.moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output,
3507 mpClientInterface);
Eric Laurent36829f92017-04-07 19:04:42 -07003508 mMusicEffectOutput = output;
3509 }
3510
3511 ALOGV("selectOutputForMusicEffects selected output %d", output);
Eric Laurente552edb2014-03-10 17:42:56 -07003512 return output;
3513}
3514
Eric Laurent36829f92017-04-07 19:04:42 -07003515audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc __unused)
3516{
3517 return selectOutputForMusicEffects();
3518}
3519
Eric Laurente0720872014-03-11 09:30:41 -07003520status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07003521 audio_io_handle_t io,
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08003522 product_strategy_t strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07003523 int session,
3524 int id)
3525{
Eric Laurentb82e6b72019-11-22 17:25:04 -08003526 if (session != AUDIO_SESSION_DEVICE) {
3527 ssize_t index = mOutputs.indexOfKey(io);
Eric Laurente552edb2014-03-10 17:42:56 -07003528 if (index < 0) {
Eric Laurentb82e6b72019-11-22 17:25:04 -08003529 index = mInputs.indexOfKey(io);
3530 if (index < 0) {
3531 ALOGW("registerEffect() unknown io %d", io);
3532 return INVALID_OPERATION;
3533 }
Eric Laurente552edb2014-03-10 17:42:56 -07003534 }
3535 }
Eric Laurentbf8f69f2022-03-25 17:48:38 +01003536 bool isMusicEffect = (session != AUDIO_SESSION_OUTPUT_STAGE)
3537 && ((strategy == streamToStrategy(AUDIO_STREAM_MUSIC)
3538 || strategy == PRODUCT_STRATEGY_NONE));
3539 return mEffects.registerEffect(desc, io, session, id, isMusicEffect);
Eric Laurente552edb2014-03-10 17:42:56 -07003540}
3541
Eric Laurentc241b0d2018-11-28 09:08:49 -08003542status_t AudioPolicyManager::unregisterEffect(int id)
3543{
3544 if (mEffects.getEffect(id) == nullptr) {
3545 return INVALID_OPERATION;
3546 }
Eric Laurentc241b0d2018-11-28 09:08:49 -08003547 if (mEffects.isEffectEnabled(id)) {
3548 ALOGW("%s effect %d enabled", __FUNCTION__, id);
3549 setEffectEnabled(id, false);
3550 }
3551 return mEffects.unregisterEffect(id);
3552}
3553
3554status_t AudioPolicyManager::setEffectEnabled(int id, bool enabled)
3555{
3556 sp<EffectDescriptor> effect = mEffects.getEffect(id);
3557 if (effect == nullptr) {
3558 return INVALID_OPERATION;
3559 }
3560
3561 status_t status = mEffects.setEffectEnabled(id, enabled);
3562 if (status == NO_ERROR) {
3563 mInputs.trackEffectEnabled(effect, enabled);
3564 }
3565 return status;
3566}
3567
Eric Laurent6c796322019-04-09 14:13:17 -07003568
3569status_t AudioPolicyManager::moveEffectsToIo(const std::vector<int>& ids, audio_io_handle_t io)
3570{
3571 mEffects.moveEffects(ids, io);
3572 return NO_ERROR;
3573}
3574
Eric Laurentc75307b2015-03-17 15:29:32 -07003575bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
3576{
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003577 auto vs = toVolumeSource(stream, false);
3578 return vs != VOLUME_SOURCE_NONE ? mOutputs.isActive(vs, inPastMs) : false;
Eric Laurentc75307b2015-03-17 15:29:32 -07003579}
3580
3581bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream, uint32_t inPastMs) const
3582{
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003583 auto vs = toVolumeSource(stream, false);
3584 return vs != VOLUME_SOURCE_NONE ? mOutputs.isActiveRemotely(vs, inPastMs) : false;
Eric Laurentc75307b2015-03-17 15:29:32 -07003585}
3586
Eric Laurente0720872014-03-11 09:30:41 -07003587bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07003588{
3589 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003590 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08003591 if (inputDescriptor->isSourceActive(source)) {
Eric Laurente552edb2014-03-10 17:42:56 -07003592 return true;
3593 }
3594 }
3595 return false;
3596}
3597
Eric Laurent275e8e92014-11-30 15:14:47 -08003598// Register a list of custom mixes with their attributes and format.
3599// When a mix is registered, corresponding input and output profiles are
3600// added to the remote submix hw module. The profile contains only the
3601// parameters (sampling rate, format...) specified by the mix.
3602// The corresponding input remote submix device is also connected.
3603//
3604// When a remote submix device is connected, the address is checked to select the
3605// appropriate profile and the corresponding input or output stream is opened.
3606//
3607// When capture starts, getInputForAttr() will:
3608// - 1 look for a mix matching the address passed in attribtutes tags if any
3609// - 2 if none found, getDeviceForInputSource() will:
3610// - 2.1 look for a mix matching the attributes source
3611// - 2.2 if none found, default to device selection by policy rules
3612// At this time, the corresponding output remote submix device is also connected
3613// and active playback use cases can be transferred to this mix if needed when reconnecting
3614// after AudioTracks are invalidated
3615//
3616// When playback starts, getOutputForAttr() will:
3617// - 1 look for a mix matching the address passed in attribtutes tags if any
3618// - 2 if none found, look for a mix matching the attributes usage
3619// - 3 if none found, default to device and output selection by policy rules.
3620
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003621status_t AudioPolicyManager::registerPolicyMixes(const Vector<AudioMix>& mixes)
Eric Laurent275e8e92014-11-30 15:14:47 -08003622{
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003623 ALOGV("registerPolicyMixes() %zu mix(es)", mixes.size());
3624 status_t res = NO_ERROR;
Eric Laurentc209fe42020-06-05 18:11:23 -07003625 bool checkOutputs = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003626 sp<HwModule> rSubmixModule;
3627 // examine each mix's route type
3628 for (size_t i = 0; i < mixes.size(); i++) {
Eric Laurent97ac8712018-07-27 18:59:02 -07003629 AudioMix mix = mixes[i];
Kevin Rocard153f92d2018-12-18 18:33:28 -08003630 // Only capture of playback is allowed in LOOP_BACK & RENDER mode
3631 if (is_mix_loopback_render(mix.mRouteFlags) && mix.mMixType != MIX_TYPE_PLAYERS) {
3632 ALOGE("Unsupported Policy Mix %zu of %zu: "
3633 "Only capture of playback is allowed in LOOP_BACK & RENDER mode",
3634 i, mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003635 res = INVALID_OPERATION;
Eric Laurent275e8e92014-11-30 15:14:47 -08003636 break;
3637 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08003638 // LOOP_BACK and LOOP_BACK | RENDER have the same remote submix backend and are handled
3639 // in the same way.
Eric Laurent97ac8712018-07-27 18:59:02 -07003640 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003641 ALOGV("registerPolicyMixes() mix %zu of %zu is LOOP_BACK %d", i, mixes.size(),
3642 mix.mRouteFlags);
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003643 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003644 rSubmixModule = mHwModules.getModuleFromName(
3645 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
3646 if (rSubmixModule == 0) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003647 ALOGE("Unable to find audio module for submix, aborting mix %zu registration",
Mikhail Naganovd4120142017-12-06 15:49:22 -08003648 i);
3649 res = INVALID_OPERATION;
3650 break;
3651 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003652 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003653
Eric Laurent97ac8712018-07-27 18:59:02 -07003654 String8 address = mix.mDeviceAddress;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003655 audio_devices_t deviceTypeToMakeAvailable;
Eric Laurent97ac8712018-07-27 18:59:02 -07003656 if (mix.mMixType == MIX_TYPE_PLAYERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07003657 mix.mDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003658 deviceTypeToMakeAvailable = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
3659 } else {
3660 mix.mDeviceType = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
3661 deviceTypeToMakeAvailable = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Eric Laurent97ac8712018-07-27 18:59:02 -07003662 }
François Gaffie036e1e92015-03-19 10:16:24 +01003663
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003664 if (mPolicyMixes.registerMix(mix, 0 /*output desc*/) != NO_ERROR) {
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003665 ALOGE("Error registering mix %zu for address %s", i, address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003666 res = INVALID_OPERATION;
3667 break;
3668 }
Eric Laurent97ac8712018-07-27 18:59:02 -07003669 audio_config_t outputConfig = mix.mFormat;
3670 audio_config_t inputConfig = mix.mFormat;
Eric Laurentc529cf62020-04-17 18:19:10 -07003671 // NOTE: audio flinger mixer does not support mono output: configure remote submix HAL
3672 // in stereo and let audio flinger do the channel conversion if needed.
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003673 outputConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
3674 inputConfig.channel_mask = AUDIO_CHANNEL_IN_STEREO;
jiabin5740f082019-08-19 15:08:30 -07003675 rSubmixModule->addOutputProfile(address.c_str(), &outputConfig,
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003676 AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address);
jiabin5740f082019-08-19 15:08:30 -07003677 rSubmixModule->addInputProfile(address.c_str(), &inputConfig,
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003678 AUDIO_DEVICE_IN_REMOTE_SUBMIX, address);
François Gaffie036e1e92015-03-19 10:16:24 +01003679
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003680 if ((res = setDeviceConnectionStateInt(deviceTypeToMakeAvailable,
jiabinc1de2df2019-05-07 14:26:40 -07003681 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003682 address.c_str(), "remote-submix", AUDIO_FORMAT_DEFAULT)) != NO_ERROR) {
jiabinc1de2df2019-05-07 14:26:40 -07003683 ALOGE("Failed to set remote submix device available, type %u, address %s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003684 mix.mDeviceType, address.c_str());
jiabinc1de2df2019-05-07 14:26:40 -07003685 break;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003686 }
Eric Laurent97ac8712018-07-27 18:59:02 -07003687 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
3688 String8 address = mix.mDeviceAddress;
Eric Laurent2c80be02019-01-23 18:06:37 -08003689 audio_devices_t type = mix.mDeviceType;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003690 ALOGV(" registerPolicyMixes() mix %zu of %zu is RENDER, dev=0x%X addr=%s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003691 i, mixes.size(), type, address.c_str());
Eric Laurent2c80be02019-01-23 18:06:37 -08003692
3693 sp<DeviceDescriptor> device = mHwModules.getDeviceDescriptor(
3694 mix.mDeviceType, mix.mDeviceAddress,
3695 String8(), AUDIO_FORMAT_DEFAULT);
3696 if (device == nullptr) {
3697 res = INVALID_OPERATION;
3698 break;
3699 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003700
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003701 bool foundOutput = false;
Eric Laurentc529cf62020-04-17 18:19:10 -07003702 // First try to find an already opened output supporting the device
3703 for (size_t j = 0 ; j < mOutputs.size() && !foundOutput && res == NO_ERROR; j++) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003704 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurent2c80be02019-01-23 18:06:37 -08003705
Eric Laurentc529cf62020-04-17 18:19:10 -07003706 if (!desc->isDuplicated() && desc->supportedDevices().contains(device)) {
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003707 if (mPolicyMixes.registerMix(mix, desc) != NO_ERROR) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003708 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003709 address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003710 res = INVALID_OPERATION;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003711 } else {
3712 foundOutput = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003713 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003714 }
3715 }
Eric Laurentc529cf62020-04-17 18:19:10 -07003716 // If no output found, try to find a direct output profile supporting the device
3717 for (size_t i = 0; i < mHwModules.size() && !foundOutput && res == NO_ERROR; i++) {
3718 sp<HwModule> module = mHwModules[i];
3719 for (size_t j = 0;
3720 j < module->getOutputProfiles().size() && !foundOutput && res == NO_ERROR;
3721 j++) {
3722 sp<IOProfile> profile = module->getOutputProfiles()[j];
3723 if (profile->isDirectOutput() && profile->supportsDevice(device)) {
3724 if (mPolicyMixes.registerMix(mix, nullptr) != NO_ERROR) {
3725 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003726 address.c_str());
Eric Laurentc529cf62020-04-17 18:19:10 -07003727 res = INVALID_OPERATION;
3728 } else {
3729 foundOutput = true;
3730 }
3731 }
3732 }
3733 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003734 if (res != NO_ERROR) {
3735 ALOGE(" Error registering mix %zu for device 0x%X addr %s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003736 i, type, address.c_str());
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003737 res = INVALID_OPERATION;
3738 break;
3739 } else if (!foundOutput) {
3740 ALOGE(" Output not found for mix %zu for device 0x%X addr %s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003741 i, type, address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003742 res = INVALID_OPERATION;
3743 break;
Eric Laurentc209fe42020-06-05 18:11:23 -07003744 } else {
3745 checkOutputs = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003746 }
Eric Laurentc722f302014-12-10 11:21:49 -08003747 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003748 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003749 if (res != NO_ERROR) {
3750 unregisterPolicyMixes(mixes);
Eric Laurentc209fe42020-06-05 18:11:23 -07003751 } else if (checkOutputs) {
3752 checkForDeviceAndOutputChanges();
3753 updateCallAndOutputRouting();
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003754 }
3755 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08003756}
3757
3758status_t AudioPolicyManager::unregisterPolicyMixes(Vector<AudioMix> mixes)
3759{
Eric Laurent7b279bb2015-12-14 10:18:23 -08003760 ALOGV("unregisterPolicyMixes() num mixes %zu", mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003761 status_t res = NO_ERROR;
Eric Laurentc209fe42020-06-05 18:11:23 -07003762 bool checkOutputs = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003763 sp<HwModule> rSubmixModule;
3764 // examine each mix's route type
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003765 for (const auto& mix : mixes) {
3766 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie036e1e92015-03-19 10:16:24 +01003767
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003768 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003769 rSubmixModule = mHwModules.getModuleFromName(
3770 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
3771 if (rSubmixModule == 0) {
3772 res = INVALID_OPERATION;
3773 continue;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003774 }
3775 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003776
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003777 String8 address = mix.mDeviceAddress;
Eric Laurent275e8e92014-11-30 15:14:47 -08003778
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003779 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003780 res = INVALID_OPERATION;
3781 continue;
3782 }
3783
Kevin Rocard04ed0462019-05-02 17:53:24 -07003784 for (auto device : {AUDIO_DEVICE_IN_REMOTE_SUBMIX, AUDIO_DEVICE_OUT_REMOTE_SUBMIX}) {
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003785 if (getDeviceConnectionState(device, address.c_str()) ==
Kevin Rocard04ed0462019-05-02 17:53:24 -07003786 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
3787 res = setDeviceConnectionStateInt(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003788 address.c_str(), "remote-submix",
Kevin Rocard04ed0462019-05-02 17:53:24 -07003789 AUDIO_FORMAT_DEFAULT);
3790 if (res != OK) {
3791 ALOGE("Error making RemoteSubmix device unavailable for mix "
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003792 "with type %d, address %s", device, address.c_str());
Kevin Rocard04ed0462019-05-02 17:53:24 -07003793 }
3794 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003795 }
jiabin5740f082019-08-19 15:08:30 -07003796 rSubmixModule->removeOutputProfile(address.c_str());
3797 rSubmixModule->removeInputProfile(address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003798
Kevin Rocard153f92d2018-12-18 18:33:28 -08003799 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003800 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003801 res = INVALID_OPERATION;
3802 continue;
Eric Laurentc209fe42020-06-05 18:11:23 -07003803 } else {
3804 checkOutputs = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003805 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003806 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003807 }
Eric Laurentc209fe42020-06-05 18:11:23 -07003808 if (res == NO_ERROR && checkOutputs) {
3809 checkForDeviceAndOutputChanges();
3810 updateCallAndOutputRouting();
3811 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003812 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08003813}
3814
Jan Sebechlebsky0af8e872023-08-11 14:45:08 +02003815status_t AudioPolicyManager::updatePolicyMix(
3816 const AudioMix& mix,
3817 const std::vector<AudioMixMatchCriterion>& updatedCriteria) {
3818 status_t res = mPolicyMixes.updateMix(mix, updatedCriteria);
3819 if (res == NO_ERROR) {
3820 checkForDeviceAndOutputChanges();
3821 updateCallAndOutputRouting();
3822 }
3823 return res;
3824}
3825
Mikhail Naganov100f0122018-11-29 11:22:16 -08003826void AudioPolicyManager::dumpManualSurroundFormats(String8 *dst) const
3827{
3828 size_t i = 0;
3829 constexpr size_t audioFormatPrefixLen = sizeof("AUDIO_FORMAT_");
3830 for (const auto& fmt : mManualSurroundFormats) {
3831 if (i++ != 0) dst->append(", ");
3832 std::string sfmt;
3833 FormatConverter::toString(fmt, sfmt);
3834 dst->append(sfmt.size() >= audioFormatPrefixLen ?
3835 sfmt.c_str() + audioFormatPrefixLen - 1 : sfmt.c_str());
3836 }
3837}
3838
Eric Laurentc529cf62020-04-17 18:19:10 -07003839// Returns true if all devices types match the predicate and are supported by one HW module
3840bool AudioPolicyManager::areAllDevicesSupported(
jiabin6a02d532020-08-07 11:56:38 -07003841 const AudioDeviceTypeAddrVector& devices,
Eric Laurentc529cf62020-04-17 18:19:10 -07003842 std::function<bool(audio_devices_t)> predicate,
Eric Laurent78fedbf2023-03-09 14:40:44 +01003843 const char *context,
3844 bool matchAddress) {
Eric Laurentc529cf62020-04-17 18:19:10 -07003845 for (size_t i = 0; i < devices.size(); i++) {
3846 sp<DeviceDescriptor> devDesc = mHwModules.getDeviceDescriptor(
jiabin0a488932020-08-07 17:32:40 -07003847 devices[i].mType, devices[i].getAddress(), String8(),
Eric Laurent78fedbf2023-03-09 14:40:44 +01003848 AUDIO_FORMAT_DEFAULT, false /*allowToCreate*/, matchAddress);
Eric Laurentc529cf62020-04-17 18:19:10 -07003849 if (devDesc == nullptr || (predicate != nullptr && !predicate(devices[i].mType))) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003850 ALOGE("%s: device type %#x address %s not supported or not match predicate",
jiabin0a488932020-08-07 17:32:40 -07003851 context, devices[i].mType, devices[i].getAddress());
Eric Laurentc529cf62020-04-17 18:19:10 -07003852 return false;
3853 }
3854 }
3855 return true;
3856}
3857
Oscar Azucena6acf34b2023-04-27 16:32:09 -07003858void AudioPolicyManager::changeOutputDevicesMuteState(
3859 const AudioDeviceTypeAddrVector& devices) {
3860 ALOGVV("%s() num devices %zu", __func__, devices.size());
3861
3862 std::vector<sp<SwAudioOutputDescriptor>> outputs =
3863 getSoftwareOutputsForDevices(devices);
3864
3865 for (size_t i = 0; i < outputs.size(); i++) {
3866 sp<SwAudioOutputDescriptor> outputDesc = outputs[i];
3867 DeviceVector prevDevices = outputDesc->devices();
3868 checkDeviceMuteStrategies(outputDesc, prevDevices, 0 /* delayMs */);
3869 }
3870}
3871
3872std::vector<sp<SwAudioOutputDescriptor>> AudioPolicyManager::getSoftwareOutputsForDevices(
3873 const AudioDeviceTypeAddrVector& devices) const
3874{
3875 std::vector<sp<SwAudioOutputDescriptor>> outputs;
3876 DeviceVector deviceDescriptors;
3877 for (size_t j = 0; j < devices.size(); j++) {
3878 sp<DeviceDescriptor> desc = mHwModules.getDeviceDescriptor(
3879 devices[j].mType, devices[j].getAddress(), String8(), AUDIO_FORMAT_DEFAULT);
3880 if (desc == nullptr || !audio_is_output_device(devices[j].mType)) {
3881 ALOGE("%s: device type %#x address %s not supported or not an output device",
3882 __func__, devices[j].mType, devices[j].getAddress());
3883 continue;
3884 }
3885 deviceDescriptors.add(desc);
3886 }
3887 for (size_t i = 0; i < mOutputs.size(); i++) {
3888 if (!mOutputs.valueAt(i)->supportsAtLeastOne(deviceDescriptors)) {
3889 continue;
3890 }
3891 outputs.push_back(mOutputs.valueAt(i));
3892 }
3893 return outputs;
3894}
3895
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003896status_t AudioPolicyManager::setUidDeviceAffinities(uid_t uid,
jiabin6a02d532020-08-07 11:56:38 -07003897 const AudioDeviceTypeAddrVector& devices) {
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003898 ALOGV("%s() uid=%d num devices %zu", __FUNCTION__, uid, devices.size());
Eric Laurentc529cf62020-04-17 18:19:10 -07003899 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
3900 return BAD_VALUE;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003901 }
3902 status_t res = mPolicyMixes.setUidDeviceAffinities(uid, devices);
Eric Laurentc529cf62020-04-17 18:19:10 -07003903 if (res != NO_ERROR) {
3904 ALOGE("%s() Could not set all device affinities for uid = %d", __FUNCTION__, uid);
3905 return res;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003906 }
Eric Laurentc529cf62020-04-17 18:19:10 -07003907
3908 checkForDeviceAndOutputChanges();
3909 updateCallAndOutputRouting();
3910
3911 return NO_ERROR;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003912}
3913
3914status_t AudioPolicyManager::removeUidDeviceAffinities(uid_t uid) {
3915 ALOGV("%s() uid=%d", __FUNCTION__, uid);
Oscar Azucena4b2a8212019-04-26 23:48:59 -07003916 status_t res = mPolicyMixes.removeUidDeviceAffinities(uid);
3917 if (res != NO_ERROR) {
Eric Laurentc529cf62020-04-17 18:19:10 -07003918 ALOGE("%s() Could not remove all device affinities for uid = %d",
Oscar Azucena4b2a8212019-04-26 23:48:59 -07003919 __FUNCTION__, uid);
3920 return INVALID_OPERATION;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003921 }
3922
Eric Laurentc529cf62020-04-17 18:19:10 -07003923 checkForDeviceAndOutputChanges();
3924 updateCallAndOutputRouting();
3925
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003926 return res;
3927}
3928
Eric Laurent2517af32020-11-25 15:31:27 +01003929
jiabin0a488932020-08-07 17:32:40 -07003930status_t AudioPolicyManager::setDevicesRoleForStrategy(product_strategy_t strategy,
3931 device_role_t role,
3932 const AudioDeviceTypeAddrVector &devices) {
3933 ALOGV("%s() strategy=%d role=%d %s", __func__, strategy, role,
3934 dumpAudioDeviceTypeAddrVector(devices).c_str());
Eric Laurentc529cf62020-04-17 18:19:10 -07003935
Eric Laurentc529cf62020-04-17 18:19:10 -07003936 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003937 return BAD_VALUE;
3938 }
jiabin0a488932020-08-07 17:32:40 -07003939 status_t status = mEngine->setDevicesRoleForStrategy(strategy, role, devices);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003940 if (status != NO_ERROR) {
jiabin0a488932020-08-07 17:32:40 -07003941 ALOGW("Engine could not set preferred devices %s for strategy %d role %d",
3942 dumpAudioDeviceTypeAddrVector(devices).c_str(), strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003943 return status;
3944 }
3945
3946 checkForDeviceAndOutputChanges();
Eric Laurent2517af32020-11-25 15:31:27 +01003947
3948 bool forceVolumeReeval = false;
3949 // FIXME: workaround for truncated touch sounds
3950 // to be removed when the problem is handled by system UI
3951 uint32_t delayMs = 0;
3952 if (strategy == mCommunnicationStrategy) {
3953 forceVolumeReeval = true;
3954 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
3955 updateInputRouting();
3956 }
3957 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003958
3959 return NO_ERROR;
3960}
3961
Oscar Azucena6acf34b2023-04-27 16:32:09 -07003962void AudioPolicyManager::updateCallAndOutputRouting(bool forceVolumeReeval, uint32_t delayMs,
3963 bool skipDelays)
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003964{
3965 uint32_t waitMs = 0;
Eric Laurent96d1dda2022-03-14 17:14:19 +01003966 bool wasLeUnicastActive = isLeUnicastActive();
Francois Gaffie19fd6c52021-02-04 17:02:59 +01003967 if (updateCallRouting(true /*fromCache*/, delayMs, &waitMs) == NO_ERROR) {
Eric Laurentb36b4ac2020-08-21 12:50:41 -07003968 // Only apply special touch sound delay once
3969 delayMs = 0;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003970 }
jiabin3ff8d7d2022-12-13 06:27:44 +00003971 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003972 for (size_t i = 0; i < mOutputs.size(); i++) {
3973 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
3974 DeviceVector newDevices = getNewOutputDevices(outputDesc, true /*fromCache*/);
Francois Gaffie601801d2021-06-22 13:27:39 +02003975 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) ||
3976 (outputDesc != mPrimaryOutput && !isTelephonyRxOrTx(outputDesc))) {
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003977 // As done in setDeviceConnectionState, we could also fix default device issue by
3978 // preventing the force re-routing in case of default dev that distinguishes on address.
3979 // Let's give back to engine full device choice decision however.
Francois Gaffie601801d2021-06-22 13:27:39 +02003980 bool forceRouting = !newDevices.isEmpty();
jiabin3ff8d7d2022-12-13 06:27:44 +00003981 if (outputDesc->mUsePreferredMixerAttributes && newDevices != outputDesc->devices()) {
3982 // If the device is using preferred mixer attributes, the output need to reopen
3983 // with default configuration when the new selected devices are different from
3984 // current routing devices.
3985 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices);
3986 continue;
3987 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05303988
3989 waitMs = setOutputDevices(__func__, outputDesc, newDevices, forceRouting, delayMs,
3990 nullptr, !skipDelays /*requiresMuteCheck*/,
Oscar Azucena6acf34b2023-04-27 16:32:09 -07003991 !forceRouting /*requiresVolumeCheck*/, skipDelays);
Eric Laurentb36b4ac2020-08-21 12:50:41 -07003992 // Only apply special touch sound delay once
3993 delayMs = 0;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003994 }
3995 if (forceVolumeReeval && !newDevices.isEmpty()) {
3996 applyStreamVolumes(outputDesc, newDevices.types(), waitMs, true);
3997 }
3998 }
jiabin3ff8d7d2022-12-13 06:27:44 +00003999 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent96d1dda2022-03-14 17:14:19 +01004000 checkLeBroadcastRoutes(wasLeUnicastActive, nullptr, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004001}
4002
Eric Laurent2517af32020-11-25 15:31:27 +01004003void AudioPolicyManager::updateInputRouting() {
4004 for (const auto& activeDesc : mInputs.getActiveInputs()) {
Jaideep Sharma408349a2020-11-27 14:47:17 +05304005 // Skip for hotword recording as the input device switch
4006 // is handled within sound trigger HAL
4007 if (activeDesc->isSoundTrigger() && activeDesc->source() == AUDIO_SOURCE_HOTWORD) {
4008 continue;
4009 }
Eric Laurent2517af32020-11-25 15:31:27 +01004010 auto newDevice = getNewInputDevice(activeDesc);
4011 // Force new input selection if the new device can not be reached via current input
4012 if (activeDesc->mProfile->getSupportedDevices().contains(newDevice)) {
4013 setInputDevice(activeDesc->mIoHandle, newDevice);
4014 } else {
4015 closeInput(activeDesc->mIoHandle);
4016 }
4017 }
4018}
4019
Paul Wang5d7cdb52022-11-22 09:45:06 +00004020status_t
4021AudioPolicyManager::removeDevicesRoleForStrategy(product_strategy_t strategy,
4022 device_role_t role,
4023 const AudioDeviceTypeAddrVector &devices) {
4024 ALOGV("%s() strategy=%d role=%d %s", __func__, strategy, role,
4025 dumpAudioDeviceTypeAddrVector(devices).c_str());
4026
Eric Laurent78fedbf2023-03-09 14:40:44 +01004027 if (!areAllDevicesSupported(
4028 devices, audio_is_output_device, __func__, /*matchAddress*/false)) {
Paul Wang5d7cdb52022-11-22 09:45:06 +00004029 return BAD_VALUE;
4030 }
4031 status_t status = mEngine->removeDevicesRoleForStrategy(strategy, role, devices);
4032 if (status != NO_ERROR) {
4033 ALOGW("Engine could not remove devices %s for strategy %d role %d",
4034 dumpAudioDeviceTypeAddrVector(devices).c_str(), strategy, role);
4035 return status;
4036 }
4037
4038 checkForDeviceAndOutputChanges();
4039
4040 bool forceVolumeReeval = false;
4041 // TODO(b/263479999): workaround for truncated touch sounds
4042 // to be removed when the problem is handled by system UI
4043 uint32_t delayMs = 0;
4044 if (strategy == mCommunnicationStrategy) {
4045 forceVolumeReeval = true;
4046 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
4047 updateInputRouting();
4048 }
4049 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
4050
4051 return NO_ERROR;
4052}
4053
4054status_t AudioPolicyManager::clearDevicesRoleForStrategy(product_strategy_t strategy,
4055 device_role_t role)
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004056{
Eric Laurentfecbceb2021-02-09 14:46:43 +01004057 ALOGV("%s() strategy=%d role=%d", __func__, strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004058
Paul Wang5d7cdb52022-11-22 09:45:06 +00004059 status_t status = mEngine->clearDevicesRoleForStrategy(strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004060 if (status != NO_ERROR) {
Eric Laurent9ae44f32022-12-14 16:17:02 +01004061 ALOGW_IF(status != NAME_NOT_FOUND,
4062 "Engine could not remove device role for strategy %d status %d",
Eric Laurent2517af32020-11-25 15:31:27 +01004063 strategy, status);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004064 return status;
4065 }
4066
4067 checkForDeviceAndOutputChanges();
Eric Laurent2517af32020-11-25 15:31:27 +01004068
4069 bool forceVolumeReeval = false;
4070 // FIXME: workaround for truncated touch sounds
4071 // to be removed when the problem is handled by system UI
4072 uint32_t delayMs = 0;
4073 if (strategy == mCommunnicationStrategy) {
4074 forceVolumeReeval = true;
4075 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
4076 updateInputRouting();
4077 }
4078 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004079
4080 return NO_ERROR;
4081}
4082
jiabin0a488932020-08-07 17:32:40 -07004083status_t AudioPolicyManager::getDevicesForRoleAndStrategy(product_strategy_t strategy,
4084 device_role_t role,
4085 AudioDeviceTypeAddrVector &devices) {
4086 return mEngine->getDevicesForRoleAndStrategy(strategy, role, devices);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004087}
4088
Jiabin Huang3b98d322020-09-03 17:54:16 +00004089status_t AudioPolicyManager::setDevicesRoleForCapturePreset(
4090 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices) {
4091 ALOGV("%s() audioSource=%d role=%d %s", __func__, audioSource, role,
4092 dumpAudioDeviceTypeAddrVector(devices).c_str());
4093
Mikhail Naganov55773032020-10-01 15:08:13 -07004094 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00004095 return BAD_VALUE;
4096 }
4097 status_t status = mEngine->setDevicesRoleForCapturePreset(audioSource, role, devices);
4098 ALOGW_IF(status != NO_ERROR,
4099 "Engine could not set preferred devices %s for audio source %d role %d",
4100 dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
4101
4102 return status;
4103}
4104
4105status_t AudioPolicyManager::addDevicesRoleForCapturePreset(
4106 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices) {
4107 ALOGV("%s() audioSource=%d role=%d %s", __func__, audioSource, role,
4108 dumpAudioDeviceTypeAddrVector(devices).c_str());
4109
Mikhail Naganov55773032020-10-01 15:08:13 -07004110 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00004111 return BAD_VALUE;
4112 }
4113 status_t status = mEngine->addDevicesRoleForCapturePreset(audioSource, role, devices);
4114 ALOGW_IF(status != NO_ERROR,
4115 "Engine could not add preferred devices %s for audio source %d role %d",
4116 dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
4117
Eric Laurent2517af32020-11-25 15:31:27 +01004118 updateInputRouting();
Jiabin Huang3b98d322020-09-03 17:54:16 +00004119 return status;
4120}
4121
4122status_t AudioPolicyManager::removeDevicesRoleForCapturePreset(
4123 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector& devices)
4124{
4125 ALOGV("%s() audioSource=%d role=%d devices=%s", __func__, audioSource, role,
4126 dumpAudioDeviceTypeAddrVector(devices).c_str());
4127
Eric Laurent78fedbf2023-03-09 14:40:44 +01004128 if (!areAllDevicesSupported(
4129 devices, audio_call_is_input_device, __func__, /*matchAddress*/false)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00004130 return BAD_VALUE;
4131 }
4132
4133 status_t status = mEngine->removeDevicesRoleForCapturePreset(
4134 audioSource, role, devices);
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 remove 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::clearDevicesRoleForCapturePreset(audio_source_t audioSource,
4144 device_role_t role) {
4145 ALOGV("%s() audioSource=%d role=%d", __func__, audioSource, role);
4146
4147 status_t status = mEngine->clearDevicesRoleForCapturePreset(audioSource, role);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004148 ALOGW_IF(status != NO_ERROR && status != NAME_NOT_FOUND,
Jiabin Huang3b98d322020-09-03 17:54:16 +00004149 "Engine could not clear devices role (%d) for capture preset %d", role, audioSource);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004150 if (status == NO_ERROR) {
4151 updateInputRouting();
4152 }
Jiabin Huang3b98d322020-09-03 17:54:16 +00004153 return status;
4154}
4155
4156status_t AudioPolicyManager::getDevicesForRoleAndCapturePreset(
4157 audio_source_t audioSource, device_role_t role, AudioDeviceTypeAddrVector &devices) {
4158 return mEngine->getDevicesForRoleAndCapturePreset(audioSource, role, devices);
4159}
4160
Oscar Azucena90e77632019-11-27 17:12:28 -08004161status_t AudioPolicyManager::setUserIdDeviceAffinities(int userId,
jiabin6a02d532020-08-07 11:56:38 -07004162 const AudioDeviceTypeAddrVector& devices) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01004163 ALOGV("%s() userId=%d num devices %zu", __func__, userId, devices.size());
Eric Laurentc529cf62020-04-17 18:19:10 -07004164 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
4165 return BAD_VALUE;
Oscar Azucena90e77632019-11-27 17:12:28 -08004166 }
Oscar Azucena90e77632019-11-27 17:12:28 -08004167 status_t status = mPolicyMixes.setUserIdDeviceAffinities(userId, devices);
4168 if (status != NO_ERROR) {
4169 ALOGE("%s() could not set device affinity for userId %d",
4170 __FUNCTION__, userId);
4171 return status;
4172 }
4173
4174 // reevaluate outputs for all devices
4175 checkForDeviceAndOutputChanges();
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004176 changeOutputDevicesMuteState(devices);
4177 updateCallAndOutputRouting(false /* forceVolumeReeval */, 0 /* delayMs */,
4178 true /* skipDelays */);
4179 changeOutputDevicesMuteState(devices);
Oscar Azucena90e77632019-11-27 17:12:28 -08004180
4181 return NO_ERROR;
4182}
4183
4184status_t AudioPolicyManager::removeUserIdDeviceAffinities(int userId) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01004185 ALOGV("%s() userId=%d", __FUNCTION__, userId);
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004186 AudioDeviceTypeAddrVector devices;
4187 mPolicyMixes.getDevicesForUserId(userId, devices);
Oscar Azucena90e77632019-11-27 17:12:28 -08004188 status_t status = mPolicyMixes.removeUserIdDeviceAffinities(userId);
4189 if (status != NO_ERROR) {
4190 ALOGE("%s() Could not remove all device affinities fo userId = %d",
4191 __FUNCTION__, userId);
4192 return status;
4193 }
4194
4195 // reevaluate outputs for all devices
4196 checkForDeviceAndOutputChanges();
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004197 changeOutputDevicesMuteState(devices);
4198 updateCallAndOutputRouting(false /* forceVolumeReeval */, 0 /* delayMs */,
4199 true /* skipDelays */);
4200 changeOutputDevicesMuteState(devices);
Oscar Azucena90e77632019-11-27 17:12:28 -08004201
4202 return NO_ERROR;
4203}
4204
Andy Hungc29d82b2018-10-05 12:23:17 -07004205void AudioPolicyManager::dump(String8 *dst) const
Eric Laurente552edb2014-03-10 17:42:56 -07004206{
Andy Hungc29d82b2018-10-05 12:23:17 -07004207 dst->appendFormat("\nAudioPolicyManager Dump: %p\n", this);
Mikhail Naganov0dbe87b2021-12-01 02:03:31 +00004208 dst->appendFormat(" Primary Output I/O handle: %d\n",
Eric Laurent87ffa392015-05-22 10:32:38 -07004209 hasPrimaryOutput() ? mPrimaryOutput->mIoHandle : AUDIO_IO_HANDLE_NONE);
Mikhail Naganov0d6a0332016-04-19 17:12:38 -07004210 std::string stateLiteral;
4211 AudioModeConverter::toString(mEngine->getPhoneState(), stateLiteral);
Andy Hungc29d82b2018-10-05 12:23:17 -07004212 dst->appendFormat(" Phone state: %s\n", stateLiteral.c_str());
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07004213 const char* forceUses[AUDIO_POLICY_FORCE_USE_CNT] = {
4214 "communications", "media", "record", "dock", "system",
4215 "HDMI system audio", "encoded surround output", "vibrate ringing" };
4216 for (audio_policy_force_use_t i = AUDIO_POLICY_FORCE_FOR_COMMUNICATION;
4217 i < AUDIO_POLICY_FORCE_USE_CNT; i = (audio_policy_force_use_t)((int)i + 1)) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08004218 audio_policy_forced_cfg_t forceUseValue = mEngine->getForceUse(i);
4219 dst->appendFormat(" Force use for %s: %d", forceUses[i], forceUseValue);
4220 if (i == AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND &&
4221 forceUseValue == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
4222 dst->append(" (MANUAL: ");
4223 dumpManualSurroundFormats(dst);
4224 dst->append(")");
4225 }
4226 dst->append("\n");
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07004227 }
Andy Hungc29d82b2018-10-05 12:23:17 -07004228 dst->appendFormat(" TTS output %savailable\n", mTtsOutputAvailable ? "" : "not ");
4229 dst->appendFormat(" Master mono: %s\n", mMasterMono ? "on" : "off");
Mikhail Naganovb3bcb4f2022-02-23 23:46:56 +00004230 dst->appendFormat(" Communication Strategy id: %d\n", mCommunnicationStrategy);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07004231 dst->appendFormat(" Config source: %s\n", mConfig->getSource().c_str());
Eric Laurent2517af32020-11-25 15:31:27 +01004232
Mikhail Naganov0f413b22021-12-02 05:29:27 +00004233 dst->append("\n");
4234 mAvailableOutputDevices.dump(dst, String8("Available output"), 1);
4235 dst->append("\n");
4236 mAvailableInputDevices.dump(dst, String8("Available input"), 1);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07004237 mHwModules.dump(dst);
Andy Hungc29d82b2018-10-05 12:23:17 -07004238 mOutputs.dump(dst);
4239 mInputs.dump(dst);
Mikhail Naganov0f413b22021-12-02 05:29:27 +00004240 mEffects.dump(dst, 1);
Andy Hungc29d82b2018-10-05 12:23:17 -07004241 mAudioPatches.dump(dst);
4242 mPolicyMixes.dump(dst);
4243 mAudioSources.dump(dst);
François Gaffiec005e562018-11-06 15:04:49 +01004244
Kevin Rocardb99cc752019-03-21 20:52:24 -07004245 dst->appendFormat(" AllowedCapturePolicies:\n");
4246 for (auto& policy : mAllowedCapturePolicies) {
4247 dst->appendFormat(" - uid=%d flag_mask=%#x\n", policy.first, policy.second);
4248 }
4249
jiabina84c3d32022-12-02 18:59:55 +00004250 dst->appendFormat(" Preferred mixer audio configuration:\n");
4251 for (const auto it : mPreferredMixerAttrInfos) {
4252 dst->appendFormat(" - device port id: %d\n", it.first);
4253 for (const auto preferredMixerInfoIt : it.second) {
4254 dst->appendFormat(" - strategy: %d; ", preferredMixerInfoIt.first);
4255 preferredMixerInfoIt.second->dump(dst);
4256 }
4257 }
4258
François Gaffiec005e562018-11-06 15:04:49 +01004259 dst->appendFormat("\nPolicy Engine dump:\n");
4260 mEngine->dump(dst);
Andy Hungc29d82b2018-10-05 12:23:17 -07004261}
4262
4263status_t AudioPolicyManager::dump(int fd)
4264{
4265 String8 result;
4266 dump(&result);
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004267 write(fd, result.c_str(), result.size());
Eric Laurente552edb2014-03-10 17:42:56 -07004268 return NO_ERROR;
4269}
4270
Kevin Rocardb99cc752019-03-21 20:52:24 -07004271status_t AudioPolicyManager::setAllowedCapturePolicy(uid_t uid, audio_flags_mask_t capturePolicy)
4272{
4273 mAllowedCapturePolicies[uid] = capturePolicy;
4274 return NO_ERROR;
4275}
4276
Eric Laurente552edb2014-03-10 17:42:56 -07004277// This function checks for the parameters which can be offloaded.
4278// This can be enhanced depending on the capability of the DSP and policy
4279// of the system.
Eric Laurent90fe31c2020-11-26 20:06:35 +01004280audio_offload_mode_t AudioPolicyManager::getOffloadSupport(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07004281{
Eric Laurent90fe31c2020-11-26 20:06:35 +01004282 ALOGV("%s: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07004283 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurent90fe31c2020-11-26 20:06:35 +01004284 __func__, offloadInfo.sample_rate, offloadInfo.channel_mask,
Eric Laurente552edb2014-03-10 17:42:56 -07004285 offloadInfo.format,
4286 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
4287 offloadInfo.has_video);
4288
jiabin2b9d5a12021-12-10 01:06:29 +00004289 if (!isOffloadPossible(offloadInfo)) {
Eric Laurent90fe31c2020-11-26 20:06:35 +01004290 return AUDIO_OFFLOAD_NOT_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07004291 }
4292
4293 // See if there is a profile to support this.
4294 // AUDIO_DEVICE_NONE
François Gaffie11d30102018-11-02 16:09:09 +01004295 sp<IOProfile> profile = getProfileForOutput(DeviceVector() /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07004296 offloadInfo.sample_rate,
4297 offloadInfo.format,
4298 offloadInfo.channel_mask,
Michael Chana94fbb22018-04-24 14:31:19 +10004299 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD,
4300 true /* directOnly */);
Eric Laurent94365442021-01-08 18:36:05 +01004301 ALOGV("%s: profile %sfound%s", __func__, profile != nullptr ? "" : "NOT ",
4302 (profile != nullptr && (profile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD) != 0)
4303 ? ", supports gapless" : "");
Eric Laurent90fe31c2020-11-26 20:06:35 +01004304 if (profile == nullptr) {
4305 return AUDIO_OFFLOAD_NOT_SUPPORTED;
4306 }
4307 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD) != 0) {
4308 return AUDIO_OFFLOAD_GAPLESS_SUPPORTED;
4309 }
4310 return AUDIO_OFFLOAD_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07004311}
4312
Michael Chana94fbb22018-04-24 14:31:19 +10004313bool AudioPolicyManager::isDirectOutputSupported(const audio_config_base_t& config,
4314 const audio_attributes_t& attributes) {
4315 audio_output_flags_t output_flags = AUDIO_OUTPUT_FLAG_NONE;
François Gaffie58d4be52018-11-06 15:30:12 +01004316 audio_flags_to_audio_output_flags(attributes.flags, &output_flags);
Dorin Drimus9901eb02022-01-14 11:36:51 +00004317 DeviceVector outputDevices = mEngine->getOutputDevicesForAttributes(attributes);
4318 sp<IOProfile> profile = getProfileForOutput(outputDevices,
Michael Chana94fbb22018-04-24 14:31:19 +10004319 config.sample_rate,
4320 config.format,
4321 config.channel_mask,
4322 output_flags,
4323 true /* directOnly */);
4324 ALOGV("%s() profile %sfound with name: %s, "
4325 "sample rate: %u, format: 0x%x, channel_mask: 0x%x, output flags: 0x%x",
4326 __FUNCTION__, profile != 0 ? "" : "NOT ",
jiabin5740f082019-08-19 15:08:30 -07004327 (profile != 0 ? profile->getTagName().c_str() : "null"),
Michael Chana94fbb22018-04-24 14:31:19 +10004328 config.sample_rate, config.format, config.channel_mask, output_flags);
Dorin Drimusecc9f422022-03-09 17:57:40 +01004329
4330 // also try the MSD module if compatible profile not found
4331 if (profile == nullptr) {
4332 profile = getMsdProfileForOutput(outputDevices,
4333 config.sample_rate,
4334 config.format,
4335 config.channel_mask,
4336 output_flags,
4337 true /* directOnly */);
4338 ALOGV("%s() MSD profile %sfound with name: %s, "
4339 "sample rate: %u, format: 0x%x, channel_mask: 0x%x, output flags: 0x%x",
4340 __FUNCTION__, profile != 0 ? "" : "NOT ",
4341 (profile != 0 ? profile->getTagName().c_str() : "null"),
4342 config.sample_rate, config.format, config.channel_mask, output_flags);
4343 }
4344 return (profile != nullptr);
Michael Chana94fbb22018-04-24 14:31:19 +10004345}
4346
jiabin2b9d5a12021-12-10 01:06:29 +00004347bool AudioPolicyManager::isOffloadPossible(const audio_offload_info_t &offloadInfo,
4348 bool durationIgnored) {
4349 if (mMasterMono) {
4350 return false; // no offloading if mono is set.
4351 }
4352
4353 // Check if offload has been disabled
4354 if (property_get_bool("audio.offload.disable", false /* default_value */)) {
4355 ALOGV("%s: offload disabled by audio.offload.disable", __func__);
4356 return false;
4357 }
4358
4359 // Check if stream type is music, then only allow offload as of now.
4360 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
4361 {
4362 ALOGV("%s: stream_type != MUSIC, returning false", __func__);
4363 return false;
4364 }
4365
4366 //TODO: enable audio offloading with video when ready
4367 const bool allowOffloadWithVideo =
4368 property_get_bool("audio.offload.video", false /* default_value */);
4369 if (offloadInfo.has_video && !allowOffloadWithVideo) {
4370 ALOGV("%s: has_video == true, returning false", __func__);
4371 return false;
4372 }
4373
4374 //If duration is less than minimum value defined in property, return false
4375 const int min_duration_secs = property_get_int32(
4376 "audio.offload.min.duration.secs", -1 /* default_value */);
4377 if (!durationIgnored) {
4378 if (min_duration_secs >= 0) {
4379 if (offloadInfo.duration_us < min_duration_secs * 1000000LL) {
4380 ALOGV("%s: Offload denied by duration < audio.offload.min.duration.secs(=%d)",
4381 __func__, min_duration_secs);
4382 return false;
4383 }
4384 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
4385 ALOGV("%s: Offload denied by duration < default min(=%u)",
4386 __func__, OFFLOAD_DEFAULT_MIN_DURATION_SECS);
4387 return false;
4388 }
4389 }
4390
4391 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
4392 // creating an offloaded track and tearing it down immediately after start when audioflinger
4393 // detects there is an active non offloadable effect.
4394 // FIXME: We should check the audio session here but we do not have it in this context.
4395 // This may prevent offloading in rare situations where effects are left active by apps
4396 // in the background.
4397 if (mEffects.isNonOffloadableEffectEnabled()) {
4398 return false;
4399 }
4400
4401 return true;
4402}
4403
4404audio_direct_mode_t AudioPolicyManager::getDirectPlaybackSupport(const audio_attributes_t *attr,
4405 const audio_config_t *config) {
4406 audio_offload_info_t offloadInfo = AUDIO_INFO_INITIALIZER;
4407 offloadInfo.format = config->format;
4408 offloadInfo.sample_rate = config->sample_rate;
4409 offloadInfo.channel_mask = config->channel_mask;
4410 offloadInfo.stream_type = mEngine->getStreamTypeForAttributes(*attr);
4411 offloadInfo.has_video = false;
4412 offloadInfo.is_streaming = false;
4413 const bool offloadPossible = isOffloadPossible(offloadInfo, true /*durationIgnored*/);
4414
4415 audio_direct_mode_t directMode = AUDIO_DIRECT_NOT_SUPPORTED;
4416 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
4417 audio_flags_to_audio_output_flags(attr->flags, &flags);
4418 // only retain flags that will drive compressed offload or passthrough
4419 uint32_t relevantFlags = AUDIO_OUTPUT_FLAG_HW_AV_SYNC;
4420 if (offloadPossible) {
4421 relevantFlags |= AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD;
4422 }
4423 flags = (audio_output_flags_t)((flags & relevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
4424
Dorin Drimusfae3c642022-03-17 18:36:30 +01004425 DeviceVector engineOutputDevices = mEngine->getOutputDevicesForAttributes(*attr);
jiabin2b9d5a12021-12-10 01:06:29 +00004426 for (const auto& hwModule : mHwModules) {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004427 DeviceVector outputDevices = engineOutputDevices;
4428 // the MSD module checks for different conditions and output devices
4429 if (strcmp(hwModule->getName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0) {
4430 if (!msdHasPatchesToAllDevices(engineOutputDevices.toTypeAddrVector())) {
4431 continue;
4432 }
4433 outputDevices = getMsdAudioOutDevices();
4434 }
jiabin2b9d5a12021-12-10 01:06:29 +00004435 for (const auto& curProfile : hwModule->getOutputProfiles()) {
jiabinc8f7dfc2022-01-06 18:42:08 +00004436 if (!curProfile->isCompatibleProfile(outputDevices,
jiabin2b9d5a12021-12-10 01:06:29 +00004437 config->sample_rate, nullptr /*updatedSamplingRate*/,
4438 config->format, nullptr /*updatedFormat*/,
4439 config->channel_mask, nullptr /*updatedChannelMask*/,
4440 flags)) {
4441 continue;
4442 }
4443 // reject profiles not corresponding to a device currently available
4444 if (!mAvailableOutputDevices.containsAtLeastOne(curProfile->getSupportedDevices())) {
4445 continue;
4446 }
4447 if ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)
4448 != AUDIO_OUTPUT_FLAG_NONE) {
jiabinc6132d62022-01-01 07:36:31 +00004449 if ((directMode & AUDIO_DIRECT_OFFLOAD_GAPLESS_SUPPORTED)
jiabin2b9d5a12021-12-10 01:06:29 +00004450 != AUDIO_DIRECT_NOT_SUPPORTED) {
4451 // Already reports offload gapless supported. No need to report offload support.
4452 continue;
4453 }
4454 if ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD)
4455 != AUDIO_OUTPUT_FLAG_NONE) {
4456 // If offload gapless is reported, no need to report offload support.
4457 directMode = (audio_direct_mode_t) ((directMode &
4458 ~AUDIO_DIRECT_OFFLOAD_SUPPORTED) |
4459 AUDIO_DIRECT_OFFLOAD_GAPLESS_SUPPORTED);
4460 } else {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004461 directMode = (audio_direct_mode_t)(directMode | AUDIO_DIRECT_OFFLOAD_SUPPORTED);
jiabin2b9d5a12021-12-10 01:06:29 +00004462 }
4463 } else {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004464 directMode = (audio_direct_mode_t) (directMode | AUDIO_DIRECT_BITSTREAM_SUPPORTED);
jiabin2b9d5a12021-12-10 01:06:29 +00004465 }
4466 }
4467 }
4468 return directMode;
4469}
4470
Dorin Drimusf2196d82022-01-03 12:11:18 +01004471status_t AudioPolicyManager::getDirectProfilesForAttributes(const audio_attributes_t* attr,
4472 AudioProfileVector& audioProfilesVector) {
Dorin Drimus17112632022-09-23 15:28:51 +00004473 if (mEffects.isNonOffloadableEffectEnabled()) {
4474 return OK;
4475 }
jiabinf1c73972022-04-14 16:28:52 -07004476 DeviceVector devices;
4477 status_t status = getDevicesForAttributes(*attr, devices, false /* forVolume */);
Dorin Drimusf2196d82022-01-03 12:11:18 +01004478 if (status != OK) {
4479 return status;
4480 }
4481 ALOGV("%s: found %zu output devices for attributes.", __func__, devices.size());
4482 if (devices.empty()) {
4483 return OK; // no output devices for the attributes
4484 }
jiabinf1c73972022-04-14 16:28:52 -07004485 return getProfilesForDevices(devices, audioProfilesVector,
4486 AUDIO_OUTPUT_FLAG_DIRECT /*flags*/, false /*isInput*/);
Dorin Drimusf2196d82022-01-03 12:11:18 +01004487}
4488
jiabina84c3d32022-12-02 18:59:55 +00004489status_t AudioPolicyManager::getSupportedMixerAttributes(
4490 audio_port_handle_t portId, std::vector<audio_mixer_attributes_t> &mixerAttrs) {
4491 ALOGV("%s, portId=%d", __func__, portId);
4492 sp<DeviceDescriptor> deviceDescriptor = mAvailableOutputDevices.getDeviceFromId(portId);
4493 if (deviceDescriptor == nullptr) {
4494 ALOGE("%s the requested device is currently unavailable", __func__);
4495 return BAD_VALUE;
4496 }
jiabin96daffc2023-05-11 17:51:55 +00004497 if (!audio_is_usb_out_device(deviceDescriptor->type())) {
4498 ALOGE("%s the requested device(type=%#x) is not usb device", __func__,
4499 deviceDescriptor->type());
4500 return BAD_VALUE;
4501 }
jiabina84c3d32022-12-02 18:59:55 +00004502 for (const auto& hwModule : mHwModules) {
4503 for (const auto& curProfile : hwModule->getOutputProfiles()) {
4504 if (curProfile->supportsDevice(deviceDescriptor)) {
4505 curProfile->toSupportedMixerAttributes(&mixerAttrs);
4506 }
4507 }
4508 }
4509 return NO_ERROR;
4510}
4511
4512status_t AudioPolicyManager::setPreferredMixerAttributes(
4513 const audio_attributes_t *attr,
4514 audio_port_handle_t portId,
4515 uid_t uid,
4516 const audio_mixer_attributes_t *mixerAttributes) {
4517 ALOGV("%s, attr=%s, mixerAttributes={format=%#x, channelMask=%#x, samplingRate=%u, "
4518 "mixerBehavior=%d}, uid=%d, portId=%u",
4519 __func__, toString(*attr).c_str(), mixerAttributes->config.format,
4520 mixerAttributes->config.channel_mask, mixerAttributes->config.sample_rate,
4521 mixerAttributes->mixer_behavior, uid, portId);
4522 if (attr->usage != AUDIO_USAGE_MEDIA) {
4523 ALOGE("%s failed, only media is allowed, the given usage is %d", __func__, attr->usage);
4524 return BAD_VALUE;
4525 }
4526 sp<DeviceDescriptor> deviceDescriptor = mAvailableOutputDevices.getDeviceFromId(portId);
4527 if (deviceDescriptor == nullptr) {
4528 ALOGE("%s the requested device is currently unavailable", __func__);
4529 return BAD_VALUE;
4530 }
4531 if (!audio_is_usb_out_device(deviceDescriptor->type())) {
4532 ALOGE("%s(%d), type=%d, is not a usb output device",
4533 __func__, portId, deviceDescriptor->type());
4534 return BAD_VALUE;
4535 }
4536
4537 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
4538 audio_flags_to_audio_output_flags(attr->flags, &flags);
4539 flags = (audio_output_flags_t) (flags |
4540 audio_output_flags_from_mixer_behavior(mixerAttributes->mixer_behavior));
4541 sp<IOProfile> profile = nullptr;
4542 DeviceVector devices(deviceDescriptor);
4543 for (const auto& hwModule : mHwModules) {
4544 for (const auto& curProfile : hwModule->getOutputProfiles()) {
4545 if (curProfile->hasDynamicAudioProfile()
4546 && curProfile->isCompatibleProfile(devices,
4547 mixerAttributes->config.sample_rate,
4548 nullptr /*updatedSamplingRate*/,
4549 mixerAttributes->config.format,
4550 nullptr /*updatedFormat*/,
4551 mixerAttributes->config.channel_mask,
4552 nullptr /*updatedChannelMask*/,
4553 flags,
4554 false /*exactMatchRequiredForInputFlags*/)) {
4555 profile = curProfile;
4556 break;
4557 }
4558 }
4559 }
4560 if (profile == nullptr) {
4561 ALOGE("%s, there is no compatible profile found", __func__);
4562 return BAD_VALUE;
4563 }
4564
4565 sp<PreferredMixerAttributesInfo> mixerAttrInfo =
4566 sp<PreferredMixerAttributesInfo>::make(
4567 uid, portId, profile, flags, *mixerAttributes);
4568 const product_strategy_t strategy = mEngine->getProductStrategyForAttributes(*attr);
4569 mPreferredMixerAttrInfos[portId][strategy] = mixerAttrInfo;
4570
4571 // If 1) there is any client from the preferred mixer configuration owner that is currently
4572 // active and matches the strategy and 2) current output is on the preferred device and the
4573 // mixer configuration doesn't match the preferred one, reopen output with preferred mixer
4574 // configuration.
4575 std::vector<audio_io_handle_t> outputsToReopen;
4576 for (size_t i = 0; i < mOutputs.size(); i++) {
4577 const auto output = mOutputs.valueAt(i);
jiabin3ff8d7d2022-12-13 06:27:44 +00004578 if (output->mProfile == profile && output->devices().onlyContainsDevice(deviceDescriptor)) {
4579 if (output->isConfigurationMatched(mixerAttributes->config, flags)) {
4580 output->mUsePreferredMixerAttributes = true;
4581 } else {
4582 for (const auto &client: output->getActiveClients()) {
4583 if (client->uid() == uid && client->strategy() == strategy) {
4584 client->setIsInvalid();
4585 outputsToReopen.push_back(output->mIoHandle);
4586 }
jiabina84c3d32022-12-02 18:59:55 +00004587 }
4588 }
4589 }
4590 }
4591 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
4592 config.sample_rate = mixerAttributes->config.sample_rate;
4593 config.channel_mask = mixerAttributes->config.channel_mask;
4594 config.format = mixerAttributes->config.format;
4595 for (const auto output : outputsToReopen) {
jiabin3ff8d7d2022-12-13 06:27:44 +00004596 sp<SwAudioOutputDescriptor> desc =
4597 reopenOutput(mOutputs.valueFor(output), &config, flags, __func__);
4598 if (desc == nullptr) {
4599 ALOGE("%s, failed to reopen output with preferred mixer attributes", __func__);
4600 continue;
4601 }
4602 desc->mUsePreferredMixerAttributes = true;
jiabina84c3d32022-12-02 18:59:55 +00004603 }
4604
4605 return NO_ERROR;
4606}
4607
4608sp<PreferredMixerAttributesInfo> AudioPolicyManager::getPreferredMixerAttributesInfo(
jiabind9a58d32023-06-01 17:57:30 +00004609 audio_port_handle_t devicePortId,
4610 product_strategy_t strategy,
4611 bool activeBitPerfectPreferred) {
jiabina84c3d32022-12-02 18:59:55 +00004612 auto it = mPreferredMixerAttrInfos.find(devicePortId);
4613 if (it == mPreferredMixerAttrInfos.end()) {
4614 return nullptr;
4615 }
jiabind9a58d32023-06-01 17:57:30 +00004616 if (activeBitPerfectPreferred) {
4617 for (auto [strategy, info] : it->second) {
4618 if ((info->getFlags() & AUDIO_OUTPUT_FLAG_BIT_PERFECT) != AUDIO_OUTPUT_FLAG_NONE
4619 && info->getActiveClientCount() != 0) {
4620 return info;
4621 }
4622 }
jiabina84c3d32022-12-02 18:59:55 +00004623 }
jiabind9a58d32023-06-01 17:57:30 +00004624 auto strategyMatchedMixerAttrInfoIt = it->second.find(strategy);
4625 return strategyMatchedMixerAttrInfoIt == it->second.end()
4626 ? nullptr : strategyMatchedMixerAttrInfoIt->second;
jiabina84c3d32022-12-02 18:59:55 +00004627}
4628
4629status_t AudioPolicyManager::getPreferredMixerAttributes(
4630 const audio_attributes_t *attr,
4631 audio_port_handle_t portId,
4632 audio_mixer_attributes_t* mixerAttributes) {
4633 sp<PreferredMixerAttributesInfo> info = getPreferredMixerAttributesInfo(
4634 portId, mEngine->getProductStrategyForAttributes(*attr));
4635 if (info == nullptr) {
4636 return NAME_NOT_FOUND;
4637 }
4638 *mixerAttributes = info->getMixerAttributes();
4639 return NO_ERROR;
4640}
4641
4642status_t AudioPolicyManager::clearPreferredMixerAttributes(const audio_attributes_t *attr,
4643 audio_port_handle_t portId,
4644 uid_t uid) {
4645 const product_strategy_t strategy = mEngine->getProductStrategyForAttributes(*attr);
4646 const auto preferredMixerAttrInfo = getPreferredMixerAttributesInfo(portId, strategy);
4647 if (preferredMixerAttrInfo == nullptr) {
4648 return NAME_NOT_FOUND;
4649 }
4650 if (preferredMixerAttrInfo->getUid() != uid) {
4651 ALOGE("%s, requested uid=%d, owned uid=%d",
4652 __func__, uid, preferredMixerAttrInfo->getUid());
4653 return PERMISSION_DENIED;
4654 }
4655 mPreferredMixerAttrInfos[portId].erase(strategy);
4656 if (mPreferredMixerAttrInfos[portId].empty()) {
4657 mPreferredMixerAttrInfos.erase(portId);
4658 }
4659
4660 // Reconfig existing output
4661 std::vector<audio_io_handle_t> potentialOutputsToReopen;
4662 for (size_t i = 0; i < mOutputs.size(); i++) {
4663 if (mOutputs.valueAt(i)->mProfile == preferredMixerAttrInfo->getProfile()) {
4664 potentialOutputsToReopen.push_back(mOutputs.keyAt(i));
4665 }
4666 }
4667 for (const auto output : potentialOutputsToReopen) {
4668 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
4669 if (desc->isConfigurationMatched(preferredMixerAttrInfo->getConfigBase(),
4670 preferredMixerAttrInfo->getFlags())) {
4671 reopenOutput(desc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
4672 }
4673 }
4674 return NO_ERROR;
4675}
4676
Eric Laurent6a94d692014-05-20 11:18:06 -07004677status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
4678 audio_port_type_t type,
4679 unsigned int *num_ports,
jiabin19cdba52020-11-24 11:28:58 -08004680 struct audio_port_v7 *ports,
Eric Laurent6a94d692014-05-20 11:18:06 -07004681 unsigned int *generation)
4682{
jiabin19cdba52020-11-24 11:28:58 -08004683 if (num_ports == nullptr || (*num_ports != 0 && ports == nullptr) ||
4684 generation == nullptr) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004685 return BAD_VALUE;
4686 }
4687 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
jiabin19cdba52020-11-24 11:28:58 -08004688 if (ports == nullptr) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004689 *num_ports = 0;
4690 }
4691
4692 size_t portsWritten = 0;
4693 size_t portsMax = *num_ports;
4694 *num_ports = 0;
4695 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07004696 // do not report devices with type AUDIO_DEVICE_IN_STUB or AUDIO_DEVICE_OUT_STUB
4697 // as they are used by stub HALs by convention
Eric Laurent6a94d692014-05-20 11:18:06 -07004698 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004699 for (const auto& dev : mAvailableOutputDevices) {
4700 if (dev->type() == AUDIO_DEVICE_OUT_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07004701 continue;
4702 }
4703 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004704 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07004705 }
4706 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07004707 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004708 }
4709 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004710 for (const auto& dev : mAvailableInputDevices) {
4711 if (dev->type() == AUDIO_DEVICE_IN_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07004712 continue;
4713 }
4714 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004715 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07004716 }
4717 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07004718 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004719 }
4720 }
4721 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
4722 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
4723 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
4724 mInputs[i]->toAudioPort(&ports[portsWritten++]);
4725 }
4726 *num_ports += mInputs.size();
4727 }
4728 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent84c70242014-06-23 08:46:27 -07004729 size_t numOutputs = 0;
4730 for (size_t i = 0; i < mOutputs.size(); i++) {
4731 if (!mOutputs[i]->isDuplicated()) {
4732 numOutputs++;
4733 if (portsWritten < portsMax) {
4734 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
4735 }
4736 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004737 }
Eric Laurent84c70242014-06-23 08:46:27 -07004738 *num_ports += numOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07004739 }
4740 }
jiabina84c3d32022-12-02 18:59:55 +00004741
Eric Laurent6a94d692014-05-20 11:18:06 -07004742 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07004743 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
Eric Laurent6a94d692014-05-20 11:18:06 -07004744 return NO_ERROR;
4745}
4746
Mikhail Naganov5edc5ed2023-03-23 14:52:15 -07004747status_t AudioPolicyManager::listDeclaredDevicePorts(media::AudioPortRole role,
4748 std::vector<media::AudioPortFw>* _aidl_return) {
4749 auto pushPort = [&](const sp<DeviceDescriptor>& dev) -> status_t {
4750 audio_port_v7 port;
4751 dev->toAudioPort(&port);
4752 auto aidlPort = VALUE_OR_RETURN_STATUS(legacy2aidl_audio_port_v7_AudioPortFw(port));
4753 _aidl_return->push_back(std::move(aidlPort));
4754 return OK;
4755 };
4756
Mikhail Naganov68e3f642023-04-28 13:06:32 -07004757 for (const auto& module : mHwModules) {
Mikhail Naganov5edc5ed2023-03-23 14:52:15 -07004758 for (const auto& dev : module->getDeclaredDevices()) {
4759 if (role == media::AudioPortRole::NONE ||
4760 ((role == media::AudioPortRole::SOURCE)
4761 == audio_is_input_device(dev->type()))) {
4762 RETURN_STATUS_IF_ERROR(pushPort(dev));
4763 }
4764 }
4765 }
4766 return OK;
4767}
4768
jiabin19cdba52020-11-24 11:28:58 -08004769status_t AudioPolicyManager::getAudioPort(struct audio_port_v7 *port)
Eric Laurent6a94d692014-05-20 11:18:06 -07004770{
Eric Laurent99fcae42018-05-17 16:59:18 -07004771 if (port == nullptr || port->id == AUDIO_PORT_HANDLE_NONE) {
4772 return BAD_VALUE;
4773 }
4774 sp<DeviceDescriptor> dev = mAvailableOutputDevices.getDeviceFromId(port->id);
4775 if (dev != 0) {
4776 dev->toAudioPort(port);
4777 return NO_ERROR;
4778 }
4779 dev = mAvailableInputDevices.getDeviceFromId(port->id);
4780 if (dev != 0) {
4781 dev->toAudioPort(port);
4782 return NO_ERROR;
4783 }
4784 sp<SwAudioOutputDescriptor> out = mOutputs.getOutputFromId(port->id);
4785 if (out != 0) {
4786 out->toAudioPort(port);
4787 return NO_ERROR;
4788 }
4789 sp<AudioInputDescriptor> in = mInputs.getInputFromId(port->id);
4790 if (in != 0) {
4791 in->toAudioPort(port);
4792 return NO_ERROR;
4793 }
4794 return BAD_VALUE;
Eric Laurent6a94d692014-05-20 11:18:06 -07004795}
4796
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004797status_t AudioPolicyManager::createAudioPatch(const struct audio_patch *patch,
4798 audio_patch_handle_t *handle,
4799 uid_t uid)
Eric Laurent6a94d692014-05-20 11:18:06 -07004800{
François Gaffieafd4cea2019-11-18 15:50:22 +01004801 ALOGV("%s", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004802 if (handle == NULL || patch == NULL) {
4803 return BAD_VALUE;
4804 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004805 ALOGV("%s num sources %d num sinks %d", __func__, patch->num_sources, patch->num_sinks);
Mikhail Naganovac9858b2018-06-15 13:12:37 -07004806 if (!audio_patch_is_valid(patch)) {
Eric Laurent874c42872014-08-08 15:13:39 -07004807 return BAD_VALUE;
4808 }
4809 // only one source per audio patch supported for now
4810 if (patch->num_sources > 1) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004811 return INVALID_OPERATION;
4812 }
Eric Laurent874c42872014-08-08 15:13:39 -07004813 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004814 return INVALID_OPERATION;
4815 }
Eric Laurent874c42872014-08-08 15:13:39 -07004816 for (size_t i = 0; i < patch->num_sinks; i++) {
4817 if (patch->sinks[i].role != AUDIO_PORT_ROLE_SINK) {
4818 return INVALID_OPERATION;
4819 }
4820 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004821
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004822 sp<DeviceDescriptor> srcDevice = mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
4823 sp<DeviceDescriptor> sinkDevice = mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id);
4824 if (srcDevice == nullptr || sinkDevice == nullptr) {
4825 ALOGW("%s could not create patch, invalid sink and/or source device(s)", __func__);
4826 return BAD_VALUE;
4827 }
4828 ALOGV("%s between source %s and sink %s", __func__,
4829 srcDevice->toString().c_str(), sinkDevice->toString().c_str());
4830 audio_port_handle_t portId = PolicyAudioPort::getNextUniqueId();
4831 // Default attributes, default volume priority, not to infer with non raw audio patches.
4832 audio_attributes_t attributes = attributes_initializer(AUDIO_USAGE_MEDIA);
4833 const struct audio_port_config *source = &patch->sources[0];
4834 sp<SourceClientDescriptor> sourceDesc =
4835 new InternalSourceClientDescriptor(
4836 portId, uid, attributes, *source, srcDevice, sinkDevice,
4837 mEngine->getProductStrategyForAttributes(attributes), toVolumeSource(attributes));
4838
4839 status_t status =
4840 connectAudioSourceToSink(sourceDesc, sinkDevice, patch, *handle, uid, 0 /* delayMs */);
4841
4842 if (status != NO_ERROR) {
4843 return INVALID_OPERATION;
4844 }
4845 mAudioSources.add(portId, sourceDesc);
4846 return NO_ERROR;
4847}
4848
4849status_t AudioPolicyManager::connectAudioSourceToSink(
4850 const sp<SourceClientDescriptor>& sourceDesc, const sp<DeviceDescriptor> &sinkDevice,
4851 const struct audio_patch *patch,
4852 audio_patch_handle_t &handle,
4853 uid_t uid, uint32_t delayMs)
4854{
4855 status_t status = createAudioPatchInternal(patch, &handle, uid, delayMs, sourceDesc);
4856 if (status != NO_ERROR || mAudioPatches.indexOfKey(handle) < 0) {
4857 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
4858 return INVALID_OPERATION;
4859 }
4860 sourceDesc->connect(handle, sinkDevice);
4861 if (isMsdPatch(handle)) {
4862 return NO_ERROR;
4863 }
4864 // SW Bridge? (@todo: HW bridge, keep track of HwOutput for device selection "reconsideration")
4865 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
4866 ALOG_ASSERT(swOutput != nullptr, "%s: a swOutput shall always be associated", __func__);
4867 if (swOutput->getClient(sourceDesc->portId()) != nullptr) {
4868 ALOGW("%s source portId has already been attached to outputDesc", __func__);
4869 goto FailurePatchAdded;
4870 }
4871 status = swOutput->start();
4872 if (status != NO_ERROR) {
4873 goto FailureSourceAdded;
4874 }
4875 swOutput->addClient(sourceDesc);
4876 status = startSource(swOutput, sourceDesc, &delayMs);
4877 if (status != NO_ERROR) {
4878 ALOGW("%s failed to start source, error %d", __FUNCTION__, status);
4879 goto FailureSourceActive;
4880 }
4881 if (delayMs != 0) {
4882 usleep(delayMs * 1000);
4883 }
4884 return NO_ERROR;
4885
4886FailureSourceActive:
4887 swOutput->stop();
4888 releaseOutput(sourceDesc->portId());
4889FailureSourceAdded:
4890 sourceDesc->setSwOutput(nullptr);
4891FailurePatchAdded:
4892 releaseAudioPatchInternal(handle);
4893 return INVALID_OPERATION;
4894}
4895
4896status_t AudioPolicyManager::createAudioPatchInternal(const struct audio_patch *patch,
4897 audio_patch_handle_t *handle,
4898 uid_t uid, uint32_t delayMs,
4899 const sp<SourceClientDescriptor>& sourceDesc)
4900{
4901 ALOGV("%s num sources %d num sinks %d", __func__, patch->num_sources, patch->num_sinks);
Eric Laurent6a94d692014-05-20 11:18:06 -07004902 sp<AudioPatch> patchDesc;
4903 ssize_t index = mAudioPatches.indexOfKey(*handle);
4904
François Gaffieafd4cea2019-11-18 15:50:22 +01004905 ALOGV("%s source id %d role %d type %d", __func__, patch->sources[0].id,
4906 patch->sources[0].role,
4907 patch->sources[0].type);
Eric Laurent874c42872014-08-08 15:13:39 -07004908#if LOG_NDEBUG == 0
4909 for (size_t i = 0; i < patch->num_sinks; i++) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004910 ALOGV("%s sink %zu: id %d role %d type %d", __func__ ,i, patch->sinks[i].id,
4911 patch->sinks[i].role,
4912 patch->sinks[i].type);
Eric Laurent874c42872014-08-08 15:13:39 -07004913 }
4914#endif
Eric Laurent6a94d692014-05-20 11:18:06 -07004915
4916 if (index >= 0) {
4917 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01004918 ALOGV("%s mUidCached %d patchDesc->mUid %d uid %d",
4919 __func__, mUidCached, patchDesc->getUid(), uid);
4920 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004921 return INVALID_OPERATION;
4922 }
4923 } else {
Glenn Kastena13cde92016-03-28 15:26:02 -07004924 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07004925 }
4926
4927 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004928 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004929 if (outputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004930 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004931 return BAD_VALUE;
4932 }
Eric Laurent84c70242014-06-23 08:46:27 -07004933 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
4934 outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004935 if (patchDesc != 0) {
4936 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004937 ALOGV("%s source id differs for patch current id %d new id %d",
4938 __func__, patchDesc->mPatch.sources[0].id, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004939 return BAD_VALUE;
4940 }
4941 }
Eric Laurent874c42872014-08-08 15:13:39 -07004942 DeviceVector devices;
4943 for (size_t i = 0; i < patch->num_sinks; i++) {
4944 // Only support mix to devices connection
4945 // TODO add support for mix to mix connection
4946 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004947 ALOGV("%s source mix but sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07004948 return INVALID_OPERATION;
4949 }
4950 sp<DeviceDescriptor> devDesc =
4951 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
4952 if (devDesc == 0) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004953 ALOGV("%s out device not found for id %d", __func__, patch->sinks[i].id);
Eric Laurent874c42872014-08-08 15:13:39 -07004954 return BAD_VALUE;
4955 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004956
François Gaffie11d30102018-11-02 16:09:09 +01004957 if (!outputDesc->mProfile->isCompatibleProfile(DeviceVector(devDesc),
Eric Laurent874c42872014-08-08 15:13:39 -07004958 patch->sources[0].sample_rate,
François Gaffie53615e22015-03-19 09:24:12 +01004959 NULL, // updatedSamplingRate
4960 patch->sources[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07004961 NULL, // updatedFormat
François Gaffie53615e22015-03-19 09:24:12 +01004962 patch->sources[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07004963 NULL, // updatedChannelMask
François Gaffie53615e22015-03-19 09:24:12 +01004964 AUDIO_OUTPUT_FLAG_NONE /*FIXME*/)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004965 ALOGV("%s profile not supported for device %08x", __func__, devDesc->type());
Eric Laurent874c42872014-08-08 15:13:39 -07004966 return INVALID_OPERATION;
4967 }
4968 devices.add(devDesc);
4969 }
4970 if (devices.size() == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004971 return INVALID_OPERATION;
4972 }
Eric Laurent874c42872014-08-08 15:13:39 -07004973
Eric Laurent6a94d692014-05-20 11:18:06 -07004974 // TODO: reconfigure output format and channels here
François Gaffieafd4cea2019-11-18 15:50:22 +01004975 ALOGV("%s setting device %s on output %d",
4976 __func__, dumpDeviceTypes(devices.types()).c_str(), outputDesc->mIoHandle);
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05304977 setOutputDevices(__func__, outputDesc, devices, true, 0, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004978 index = mAudioPatches.indexOfKey(*handle);
4979 if (index >= 0) {
4980 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004981 ALOGW("%s setOutputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004982 }
4983 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01004984 patchDesc->setUid(uid);
4985 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004986 } else {
François Gaffieafd4cea2019-11-18 15:50:22 +01004987 ALOGW("%s setOutputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004988 return INVALID_OPERATION;
4989 }
4990 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
4991 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
4992 // input device to input mix connection
Eric Laurent874c42872014-08-08 15:13:39 -07004993 // only one sink supported when connecting an input device to a mix
4994 if (patch->num_sinks > 1) {
4995 return INVALID_OPERATION;
4996 }
François Gaffie53615e22015-03-19 09:24:12 +01004997 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004998 if (inputDesc == NULL) {
4999 return BAD_VALUE;
5000 }
5001 if (patchDesc != 0) {
5002 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
5003 return BAD_VALUE;
5004 }
5005 }
François Gaffie11d30102018-11-02 16:09:09 +01005006 sp<DeviceDescriptor> device =
Eric Laurent6a94d692014-05-20 11:18:06 -07005007 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01005008 if (device == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005009 return BAD_VALUE;
5010 }
5011
François Gaffie11d30102018-11-02 16:09:09 +01005012 if (!inputDesc->mProfile->isCompatibleProfile(DeviceVector(device),
Eric Laurent275e8e92014-11-30 15:14:47 -08005013 patch->sinks[0].sample_rate,
5014 NULL, /*updatedSampleRate*/
5015 patch->sinks[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07005016 NULL, /*updatedFormat*/
Eric Laurent275e8e92014-11-30 15:14:47 -08005017 patch->sinks[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07005018 NULL, /*updatedChannelMask*/
Eric Laurent275e8e92014-11-30 15:14:47 -08005019 // FIXME for the parameter type,
5020 // and the NONE
5021 (audio_output_flags_t)
Glenn Kasten6a8ab052014-07-24 14:08:35 -07005022 AUDIO_INPUT_FLAG_NONE)) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005023 return INVALID_OPERATION;
5024 }
5025 // TODO: reconfigure output format and channels here
François Gaffieafd4cea2019-11-18 15:50:22 +01005026 ALOGV("%s setting device %s on output %d", __func__,
François Gaffie11d30102018-11-02 16:09:09 +01005027 device->toString().c_str(), inputDesc->mIoHandle);
5028 setInputDevice(inputDesc->mIoHandle, device, true, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005029 index = mAudioPatches.indexOfKey(*handle);
5030 if (index >= 0) {
5031 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005032 ALOGW("%s setInputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005033 }
5034 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005035 patchDesc->setUid(uid);
5036 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005037 } else {
François Gaffieafd4cea2019-11-18 15:50:22 +01005038 ALOGW("%s setInputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005039 return INVALID_OPERATION;
5040 }
5041 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
5042 // device to device connection
5043 if (patchDesc != 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07005044 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005045 return BAD_VALUE;
5046 }
5047 }
François Gaffie11d30102018-11-02 16:09:09 +01005048 sp<DeviceDescriptor> srcDevice =
Eric Laurent6a94d692014-05-20 11:18:06 -07005049 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01005050 if (srcDevice == 0) {
Eric Laurent58f8eb72014-09-12 16:19:41 -07005051 return BAD_VALUE;
5052 }
Eric Laurent874c42872014-08-08 15:13:39 -07005053
Eric Laurent6a94d692014-05-20 11:18:06 -07005054 //update source and sink with our own data as the data passed in the patch may
5055 // be incomplete.
François Gaffieafd4cea2019-11-18 15:50:22 +01005056 PatchBuilder patchBuilder;
5057 audio_port_config sourcePortConfig = {};
Dean Wheatley8bee85a2021-02-10 16:02:23 +11005058
5059 // if first sink is to MSD, establish single MSD patch
5060 if (getMsdAudioOutDevices().contains(
5061 mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id))) {
5062 ALOGV("%s patching to MSD", __FUNCTION__);
5063 patchBuilder = buildMsdPatch(false /*msdIsSource*/, srcDevice);
5064 goto installPatch;
5065 }
5066
François Gaffieafd4cea2019-11-18 15:50:22 +01005067 srcDevice->toAudioPortConfig(&sourcePortConfig, &patch->sources[0]);
5068 patchBuilder.addSource(sourcePortConfig);
Eric Laurent6a94d692014-05-20 11:18:06 -07005069
Eric Laurent874c42872014-08-08 15:13:39 -07005070 for (size_t i = 0; i < patch->num_sinks; i++) {
5071 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005072 ALOGV("%s source device but one sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07005073 return INVALID_OPERATION;
5074 }
François Gaffie11d30102018-11-02 16:09:09 +01005075 sp<DeviceDescriptor> sinkDevice =
Eric Laurent874c42872014-08-08 15:13:39 -07005076 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
François Gaffie11d30102018-11-02 16:09:09 +01005077 if (sinkDevice == 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07005078 return BAD_VALUE;
5079 }
François Gaffieafd4cea2019-11-18 15:50:22 +01005080 audio_port_config sinkPortConfig = {};
5081 sinkDevice->toAudioPortConfig(&sinkPortConfig, &patch->sinks[i]);
5082 patchBuilder.addSink(sinkPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07005083
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005084 // Whatever Sw or Hw bridge, we do attach an SwOutput to an Audio Source for
5085 // volume management purpose (tracking activity)
5086 // In case of Hw bridge, it is a Work Around. The mixPort used is the one declared
5087 // in config XML to reach the sink so that is can be declared as available.
5088 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurent78b07302022-10-07 16:20:34 +02005089 sp<SwAudioOutputDescriptor> outputDesc;
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005090 if (!sourceDesc->isInternal()) {
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005091 // take care of dynamic routing for SwOutput selection,
5092 audio_attributes_t attributes = sourceDesc->attributes();
5093 audio_stream_type_t stream = sourceDesc->stream();
5094 audio_attributes_t resultAttr;
5095 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
5096 config.sample_rate = sourceDesc->config().sample_rate;
François Gaffie2a24db42022-04-04 16:45:02 +02005097 audio_channel_mask_t sourceMask = sourceDesc->config().channel_mask;
5098 config.channel_mask =
5099 (audio_channel_mask_get_representation(sourceMask)
5100 == AUDIO_CHANNEL_REPRESENTATION_INDEX) ? sourceMask
5101 : audio_channel_mask_in_to_out(sourceMask);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005102 config.format = sourceDesc->config().format;
5103 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
5104 audio_port_handle_t selectedDeviceId = AUDIO_PORT_HANDLE_NONE;
5105 bool isRequestedDeviceForExclusiveUse = false;
5106 output_type_t outputType;
Eric Laurentb0a7bc92022-04-05 15:06:08 +02005107 bool isSpatialized;
jiabinc658e452022-10-21 20:52:21 +00005108 bool isBitPerfect;
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005109 getOutputForAttrInt(&resultAttr, &output, AUDIO_SESSION_NONE, &attributes,
5110 &stream, sourceDesc->uid(), &config, &flags,
5111 &selectedDeviceId, &isRequestedDeviceForExclusiveUse,
jiabinc658e452022-10-21 20:52:21 +00005112 nullptr, &outputType, &isSpatialized, &isBitPerfect);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005113 if (output == AUDIO_IO_HANDLE_NONE) {
5114 ALOGV("%s no output for device %s",
5115 __FUNCTION__, sinkDevice->toString().c_str());
5116 return INVALID_OPERATION;
5117 }
5118 outputDesc = mOutputs.valueFor(output);
5119 if (outputDesc->isDuplicated()) {
5120 ALOGE("%s output is duplicated", __func__);
5121 return INVALID_OPERATION;
5122 }
François Gaffie7e39df22022-04-26 12:48:49 +02005123 bool closeOutput = outputDesc->mDirectOpenCount != 0;
5124 sourceDesc->setSwOutput(outputDesc, closeOutput);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005125 } else {
5126 // Same for "raw patches" aka created from createAudioPatch API
5127 SortedVector<audio_io_handle_t> outputs =
5128 getOutputsForDevices(DeviceVector(sinkDevice), mOutputs);
5129 // if the sink device is reachable via an opened output stream, request to
5130 // go via this output stream by adding a second source to the patch
5131 // description
5132 output = selectOutput(outputs);
5133 if (output == AUDIO_IO_HANDLE_NONE) {
5134 ALOGE("%s no output available for internal patch sink", __func__);
5135 return INVALID_OPERATION;
5136 }
5137 outputDesc = mOutputs.valueFor(output);
5138 if (outputDesc->isDuplicated()) {
5139 ALOGV("%s output for device %s is duplicated",
5140 __func__, sinkDevice->toString().c_str());
5141 return INVALID_OPERATION;
5142 }
François Gaffie7e39df22022-04-26 12:48:49 +02005143 sourceDesc->setSwOutput(outputDesc, /* closeOutput= */ false);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005144 }
Eric Laurent3bcf8592015-04-03 12:13:24 -07005145 // create a software bridge in PatchPanel if:
Scott Randolphf3172402018-01-23 17:06:53 -08005146 // - source and sink devices are on different HW modules OR
Eric Laurent3bcf8592015-04-03 12:13:24 -07005147 // - audio HAL version is < 3.0
Francois Gaffie99896da2018-04-09 11:05:33 +02005148 // - audio HAL version is >= 3.0 but no route has been declared between devices
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005149 // - called from startAudioSource (aka sourceDesc is not internal) and source device
5150 // does not have a gain controller
François Gaffie11d30102018-11-02 16:09:09 +01005151 if (!srcDevice->hasSameHwModuleAs(sinkDevice) ||
5152 (srcDevice->getModuleVersionMajor() < 3) ||
François Gaffieafd4cea2019-11-18 15:50:22 +01005153 !srcDevice->getModule()->supportsPatch(srcDevice, sinkDevice) ||
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005154 (!sourceDesc->isInternal() &&
François Gaffieafd4cea2019-11-18 15:50:22 +01005155 srcDevice->getAudioPort()->getGains().size() == 0)) {
Eric Laurent3bcf8592015-04-03 12:13:24 -07005156 // support only one sink device for now to simplify output selection logic
Eric Laurent874c42872014-08-08 15:13:39 -07005157 if (patch->num_sinks > 1) {
Eric Laurent83b88082014-06-20 18:31:16 -07005158 return INVALID_OPERATION;
5159 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005160 sourceDesc->setUseSwBridge();
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005161 if (outputDesc != nullptr) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005162 audio_port_config srcMixPortConfig = {};
Ytai Ben-Tsvic9d2a912021-11-22 16:43:09 -08005163 outputDesc->toAudioPortConfig(&srcMixPortConfig, nullptr);
François Gaffieafd4cea2019-11-18 15:50:22 +01005164 // for volume control, we may need a valid stream
Eric Laurent78b07302022-10-07 16:20:34 +02005165 srcMixPortConfig.ext.mix.usecase.stream =
5166 (!sourceDesc->isInternal() || isCallTxAudioSource(sourceDesc)) ?
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005167 mEngine->getStreamTypeForAttributes(sourceDesc->attributes()) :
5168 AUDIO_STREAM_PATCH;
François Gaffieafd4cea2019-11-18 15:50:22 +01005169 patchBuilder.addSource(srcMixPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07005170 }
Eric Laurent83b88082014-06-20 18:31:16 -07005171 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005172 }
5173 // TODO: check from routing capabilities in config file and other conflicting patches
5174
Dean Wheatley8bee85a2021-02-10 16:02:23 +11005175installPatch:
François Gaffieafd4cea2019-11-18 15:50:22 +01005176 status_t status = installPatch(
5177 __func__, index, handle, patchBuilder.patch(), delayMs, uid, &patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07005178 if (status != NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005179 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
Eric Laurent6a94d692014-05-20 11:18:06 -07005180 return INVALID_OPERATION;
5181 }
5182 } else {
5183 return BAD_VALUE;
5184 }
5185 } else {
5186 return BAD_VALUE;
5187 }
5188 return NO_ERROR;
5189}
5190
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005191status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle, uid_t uid)
Eric Laurent6a94d692014-05-20 11:18:06 -07005192{
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005193 ALOGV("%s patch %d", __func__, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005194 ssize_t index = mAudioPatches.indexOfKey(handle);
5195
5196 if (index < 0) {
5197 return BAD_VALUE;
5198 }
5199 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005200 ALOGV("%s() mUidCached %d patchDesc->mUid %d uid %d",
5201 __func__, mUidCached, patchDesc->getUid(), uid);
5202 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005203 return INVALID_OPERATION;
5204 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005205 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
5206 for (size_t i = 0; i < mAudioSources.size(); i++) {
5207 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
5208 if (sourceDesc != nullptr && sourceDesc->getPatchHandle() == handle) {
5209 portId = sourceDesc->portId();
5210 break;
5211 }
5212 }
5213 return portId != AUDIO_PORT_HANDLE_NONE ?
5214 stopAudioSource(portId) : releaseAudioPatchInternal(handle);
François Gaffieafd4cea2019-11-18 15:50:22 +01005215}
Eric Laurent6a94d692014-05-20 11:18:06 -07005216
François Gaffieafd4cea2019-11-18 15:50:22 +01005217status_t AudioPolicyManager::releaseAudioPatchInternal(audio_patch_handle_t handle,
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005218 uint32_t delayMs,
5219 const sp<SourceClientDescriptor>& sourceDesc)
François Gaffieafd4cea2019-11-18 15:50:22 +01005220{
5221 ALOGV("%s patch %d", __func__, handle);
5222 if (mAudioPatches.indexOfKey(handle) < 0) {
5223 ALOGE("%s: no patch found with handle=%d", __func__, handle);
5224 return BAD_VALUE;
5225 }
5226 sp<AudioPatch> patchDesc = mAudioPatches.valueFor(handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005227 struct audio_patch *patch = &patchDesc->mPatch;
François Gaffieafd4cea2019-11-18 15:50:22 +01005228 patchDesc->setUid(mUidCached);
Eric Laurent6a94d692014-05-20 11:18:06 -07005229 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005230 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005231 if (outputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005232 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005233 return BAD_VALUE;
5234 }
5235
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05305236 setOutputDevices(__func__, outputDesc,
François Gaffie11d30102018-11-02 16:09:09 +01005237 getNewOutputDevices(outputDesc, true /*fromCache*/),
5238 true,
5239 0,
5240 NULL);
Eric Laurent6a94d692014-05-20 11:18:06 -07005241 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
5242 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
François Gaffie53615e22015-03-19 09:24:12 +01005243 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005244 if (inputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005245 ALOGV("%s input not found for id %d", __func__, patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005246 return BAD_VALUE;
5247 }
5248 setInputDevice(inputDesc->mIoHandle,
Eric Laurentfb66dd92016-01-28 18:32:03 -08005249 getNewInputDevice(inputDesc),
Eric Laurent6a94d692014-05-20 11:18:06 -07005250 true,
5251 NULL);
5252 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005253 status_t status =
5254 mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
5255 ALOGV("%s patch panel returned %d patchHandle %d",
5256 __func__, status, patchDesc->getAfHandle());
5257 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005258 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005259 mpClientInterface->onAudioPatchListUpdate();
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005260 // SW or HW Bridge
5261 sp<SwAudioOutputDescriptor> outputDesc = nullptr;
5262 audio_patch_handle_t patchHandle = AUDIO_PATCH_HANDLE_NONE;
Francois Gaffie7feb8542020-04-06 17:39:47 +02005263 if (patch->num_sources > 1 && patch->sources[1].type == AUDIO_PORT_TYPE_MIX) {
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005264 outputDesc = mOutputs.getOutputFromId(patch->sources[1].id);
5265 } else if (patch->num_sources == 1 && sourceDesc != nullptr) {
5266 outputDesc = sourceDesc->swOutput().promote();
5267 }
5268 if (outputDesc == nullptr) {
5269 ALOGW("%s no output for id %d", __func__, patch->sources[0].id);
5270 // releaseOutput has already called closeOutput in case of direct output
5271 return NO_ERROR;
5272 }
François Gaffie7e39df22022-04-26 12:48:49 +02005273 patchHandle = outputDesc->getPatchHandle();
François Gaffie7e39df22022-04-26 12:48:49 +02005274 // While using a HwBridge, force reconsidering device only if not reusing an existing
5275 // output and no more activity on output (will force to close).
François Gaffie150fcc62023-09-15 11:02:39 +02005276 const bool force = sourceDesc->canCloseOutput() && !outputDesc->isActive();
François Gaffie7e39df22022-04-26 12:48:49 +02005277 // APM pattern is to have always outputs opened / patch realized for reachable devices.
5278 // Update device may result to NONE (empty), coupled with force, it releases the patch.
5279 // Reconsider device only for cases:
5280 // 1 / Active Output
5281 // 2 / Inactive Output previously hosting HwBridge
5282 // 3 / Inactive Output previously hosting SwBridge that can be closed.
5283 bool updateDevice = outputDesc->isActive() || !sourceDesc->useSwBridge() ||
5284 sourceDesc->canCloseOutput();
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05305285 setOutputDevices(__func__, outputDesc,
François Gaffie7e39df22022-04-26 12:48:49 +02005286 updateDevice ? getNewOutputDevices(outputDesc, true /*fromCache*/) :
5287 outputDesc->devices(),
5288 force,
5289 0,
5290 patchHandle == AUDIO_PATCH_HANDLE_NONE ? nullptr : &patchHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005291 } else {
5292 return BAD_VALUE;
5293 }
5294 } else {
5295 return BAD_VALUE;
5296 }
5297 return NO_ERROR;
5298}
5299
5300status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
5301 struct audio_patch *patches,
5302 unsigned int *generation)
5303{
François Gaffie53615e22015-03-19 09:24:12 +01005304 if (generation == NULL) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005305 return BAD_VALUE;
5306 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005307 *generation = curAudioPortGeneration();
François Gaffie53615e22015-03-19 09:24:12 +01005308 return mAudioPatches.listAudioPatches(num_patches, patches);
Eric Laurent6a94d692014-05-20 11:18:06 -07005309}
5310
Eric Laurente1715a42014-05-20 11:30:42 -07005311status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07005312{
Eric Laurente1715a42014-05-20 11:30:42 -07005313 ALOGV("setAudioPortConfig()");
5314
5315 if (config == NULL) {
5316 return BAD_VALUE;
5317 }
5318 ALOGV("setAudioPortConfig() on port handle %d", config->id);
5319 // Only support gain configuration for now
Eric Laurenta121f902014-06-03 13:32:54 -07005320 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
5321 return INVALID_OPERATION;
Eric Laurente1715a42014-05-20 11:30:42 -07005322 }
5323
Eric Laurenta121f902014-06-03 13:32:54 -07005324 sp<AudioPortConfig> audioPortConfig;
Eric Laurente1715a42014-05-20 11:30:42 -07005325 if (config->type == AUDIO_PORT_TYPE_MIX) {
5326 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005327 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07005328 if (outputDesc == NULL) {
5329 return BAD_VALUE;
5330 }
Eric Laurent84c70242014-06-23 08:46:27 -07005331 ALOG_ASSERT(!outputDesc->isDuplicated(),
5332 "setAudioPortConfig() called on duplicated output %d",
5333 outputDesc->mIoHandle);
Eric Laurenta121f902014-06-03 13:32:54 -07005334 audioPortConfig = outputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07005335 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
François Gaffie53615e22015-03-19 09:24:12 +01005336 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07005337 if (inputDesc == NULL) {
5338 return BAD_VALUE;
5339 }
Eric Laurenta121f902014-06-03 13:32:54 -07005340 audioPortConfig = inputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07005341 } else {
5342 return BAD_VALUE;
5343 }
5344 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
5345 sp<DeviceDescriptor> deviceDesc;
5346 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
5347 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
5348 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
5349 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
5350 } else {
5351 return BAD_VALUE;
5352 }
5353 if (deviceDesc == NULL) {
5354 return BAD_VALUE;
5355 }
Eric Laurenta121f902014-06-03 13:32:54 -07005356 audioPortConfig = deviceDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07005357 } else {
5358 return BAD_VALUE;
5359 }
5360
Mikhail Naganov7be71d22018-05-23 16:51:46 -07005361 struct audio_port_config backupConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07005362 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
5363 if (status == NO_ERROR) {
Mikhail Naganov7be71d22018-05-23 16:51:46 -07005364 struct audio_port_config newConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07005365 audioPortConfig->toAudioPortConfig(&newConfig, config);
5366 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
Eric Laurente1715a42014-05-20 11:30:42 -07005367 }
Eric Laurenta121f902014-06-03 13:32:54 -07005368 if (status != NO_ERROR) {
5369 audioPortConfig->applyAudioPortConfig(&backupConfig);
Eric Laurente1715a42014-05-20 11:30:42 -07005370 }
Eric Laurente1715a42014-05-20 11:30:42 -07005371
5372 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07005373}
5374
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005375void AudioPolicyManager::releaseResourcesForUid(uid_t uid)
5376{
Eric Laurentd60560a2015-04-10 11:31:20 -07005377 clearAudioSources(uid);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005378 clearAudioPatches(uid);
5379 clearSessionRoutes(uid);
5380}
5381
Eric Laurent6a94d692014-05-20 11:18:06 -07005382void AudioPolicyManager::clearAudioPatches(uid_t uid)
5383{
Eric Laurent0add0fd2014-12-04 18:58:14 -08005384 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005385 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
François Gaffieafd4cea2019-11-18 15:50:22 +01005386 if (patchDesc->getUid() == uid) {
Eric Laurent0add0fd2014-12-04 18:58:14 -08005387 releaseAudioPatch(mAudioPatches.keyAt(i), uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07005388 }
5389 }
5390}
5391
François Gaffiec005e562018-11-06 15:04:49 +01005392void AudioPolicyManager::checkStrategyRoute(product_strategy_t ps, audio_io_handle_t ouptutToSkip)
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005393{
François Gaffiec005e562018-11-06 15:04:49 +01005394 // Take the first attributes following the product strategy as it is used to retrieve the routed
5395 // device. All attributes wihin a strategy follows the same "routing strategy"
5396 auto attributes = mEngine->getAllAttributesForProductStrategy(ps).front();
5397 DeviceVector devices = mEngine->getOutputDevicesForAttributes(attributes, nullptr, false);
François Gaffie11d30102018-11-02 16:09:09 +01005398 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
jiabin3ff8d7d2022-12-13 06:27:44 +00005399 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005400 for (size_t j = 0; j < mOutputs.size(); j++) {
5401 if (mOutputs.keyAt(j) == ouptutToSkip) {
5402 continue;
5403 }
5404 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(j);
François Gaffiec005e562018-11-06 15:04:49 +01005405 if (!outputDesc->isStrategyActive(ps)) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005406 continue;
5407 }
5408 // If the default device for this strategy is on another output mix,
5409 // invalidate all tracks in this strategy to force re connection.
5410 // Otherwise select new device on the output mix.
5411 if (outputs.indexOf(mOutputs.keyAt(j)) < 0) {
jiabinc44b3462022-12-08 12:52:31 -08005412 invalidateStreams(mEngine->getStreamTypesForProductStrategy(ps));
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005413 } else {
jiabin3ff8d7d2022-12-13 06:27:44 +00005414 DeviceVector newDevices = getNewOutputDevices(outputDesc, false /*fromCache*/);
5415 if (outputDesc->mUsePreferredMixerAttributes && outputDesc->devices() != newDevices) {
5416 // If the device is using preferred mixer attributes, the output need to reopen
5417 // with default configuration when the new selected devices are different from
5418 // current routing devices.
5419 outputsToReopen.emplace(mOutputs.keyAt(j), newDevices);
5420 continue;
5421 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05305422 setOutputDevices(__func__, outputDesc, newDevices, false);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005423 }
5424 }
jiabin3ff8d7d2022-12-13 06:27:44 +00005425 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005426}
5427
5428void AudioPolicyManager::clearSessionRoutes(uid_t uid)
5429{
5430 // remove output routes associated with this uid
François Gaffiec005e562018-11-06 15:04:49 +01005431 std::vector<product_strategy_t> affectedStrategies;
Eric Laurent97ac8712018-07-27 18:59:02 -07005432 for (size_t i = 0; i < mOutputs.size(); i++) {
5433 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07005434 for (const auto& client : outputDesc->getClientIterable()) {
5435 if (client->hasPreferredDevice() && client->uid() == uid) {
5436 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
François Gaffiec005e562018-11-06 15:04:49 +01005437 auto clientStrategy = client->strategy();
5438 if (std::find(begin(affectedStrategies), end(affectedStrategies), clientStrategy) !=
5439 end(affectedStrategies)) {
5440 continue;
5441 }
5442 affectedStrategies.push_back(client->strategy());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005443 }
5444 }
5445 }
5446 // reroute outputs if necessary
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005447 for (const auto& strategy : affectedStrategies) {
5448 checkStrategyRoute(strategy, AUDIO_IO_HANDLE_NONE);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005449 }
5450
5451 // remove input routes associated with this uid
5452 SortedVector<audio_source_t> affectedSources;
Eric Laurent97ac8712018-07-27 18:59:02 -07005453 for (size_t i = 0; i < mInputs.size(); i++) {
5454 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07005455 for (const auto& client : inputDesc->getClientIterable()) {
5456 if (client->hasPreferredDevice() && client->uid() == uid) {
5457 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
5458 affectedSources.add(client->source());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005459 }
5460 }
5461 }
5462 // reroute inputs if necessary
5463 SortedVector<audio_io_handle_t> inputsToClose;
5464 for (size_t i = 0; i < mInputs.size(); i++) {
5465 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Eric Laurent4eb58f12018-12-07 16:41:02 -08005466 if (affectedSources.indexOf(inputDesc->source()) >= 0) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005467 inputsToClose.add(inputDesc->mIoHandle);
5468 }
5469 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005470 for (const auto& input : inputsToClose) {
5471 closeInput(input);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005472 }
5473}
5474
Eric Laurentd60560a2015-04-10 11:31:20 -07005475void AudioPolicyManager::clearAudioSources(uid_t uid)
5476{
5477 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005478 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
5479 if (sourceDesc->uid() == uid) {
Eric Laurentd60560a2015-04-10 11:31:20 -07005480 stopAudioSource(mAudioSources.keyAt(i));
5481 }
5482 }
5483}
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005484
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005485status_t AudioPolicyManager::acquireSoundTriggerSession(audio_session_t *session,
5486 audio_io_handle_t *ioHandle,
5487 audio_devices_t *device)
5488{
Glenn Kastenf0c6d7d2016-02-26 10:44:04 -08005489 *session = (audio_session_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
5490 *ioHandle = (audio_io_handle_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
Francois Gaffie716e1432019-01-14 16:58:59 +01005491 audio_attributes_t attr = { .source = AUDIO_SOURCE_HOTWORD };
Eric Laurentcedd5b52023-03-22 00:03:31 +00005492 sp<DeviceDescriptor> deviceDesc = mEngine->getInputDeviceForAttributes(attr);
5493 if (deviceDesc == nullptr) {
5494 return INVALID_OPERATION;
5495 }
5496 *device = deviceDesc->type();
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005497
François Gaffiedf372692015-03-19 10:43:27 +01005498 return mSoundTriggerSessions.acquireSession(*session, *ioHandle);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005499}
5500
Eric Laurentd60560a2015-04-10 11:31:20 -07005501status_t AudioPolicyManager::startAudioSource(const struct audio_port_config *source,
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005502 const audio_attributes_t *attributes,
5503 audio_port_handle_t *portId,
5504 uid_t uid)
Eric Laurent554a2772015-04-10 11:29:24 -07005505{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005506 ALOGV("%s", __FUNCTION__);
5507 *portId = AUDIO_PORT_HANDLE_NONE;
5508
5509 if (source == NULL || attributes == NULL || portId == NULL) {
5510 ALOGW("%s invalid argument: source %p attributes %p handle %p",
5511 __FUNCTION__, source, attributes, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005512 return BAD_VALUE;
5513 }
5514
Eric Laurentd60560a2015-04-10 11:31:20 -07005515 if (source->role != AUDIO_PORT_ROLE_SOURCE ||
5516 source->type != AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005517 ALOGW("%s INVALID_OPERATION source->role %d source->type %d",
5518 __FUNCTION__, source->role, source->type);
Eric Laurentd60560a2015-04-10 11:31:20 -07005519 return INVALID_OPERATION;
5520 }
5521
François Gaffie11d30102018-11-02 16:09:09 +01005522 sp<DeviceDescriptor> srcDevice =
Eric Laurentd60560a2015-04-10 11:31:20 -07005523 mAvailableInputDevices.getDevice(source->ext.device.type,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005524 String8(source->ext.device.address),
5525 AUDIO_FORMAT_DEFAULT);
François Gaffie11d30102018-11-02 16:09:09 +01005526 if (srcDevice == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005527 ALOGW("%s source->ext.device.type %08x not found", __FUNCTION__, source->ext.device.type);
Eric Laurentd60560a2015-04-10 11:31:20 -07005528 return BAD_VALUE;
5529 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005530
jiabin4ef93452019-09-10 14:29:54 -07005531 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurentd60560a2015-04-10 11:31:20 -07005532
François Gaffieaaac0fd2018-11-22 17:56:39 +01005533 sp<SourceClientDescriptor> sourceDesc =
François Gaffieafd4cea2019-11-18 15:50:22 +01005534 new SourceClientDescriptor(*portId, uid, *attributes, *source, srcDevice,
François Gaffieaaac0fd2018-11-22 17:56:39 +01005535 mEngine->getStreamTypeForAttributes(*attributes),
5536 mEngine->getProductStrategyForAttributes(*attributes),
5537 toVolumeSource(*attributes));
Eric Laurentd60560a2015-04-10 11:31:20 -07005538
5539 status_t status = connectAudioSource(sourceDesc);
5540 if (status == NO_ERROR) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005541 mAudioSources.add(*portId, sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07005542 }
5543 return status;
5544}
5545
Francois Gaffie601801d2021-06-22 13:27:39 +02005546sp<SourceClientDescriptor> AudioPolicyManager::startAudioSourceInternal(
5547 const struct audio_port_config *source, const audio_attributes_t *attributes, uid_t uid)
5548{
5549 ALOGV("%s", __FUNCTION__);
5550 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
5551
5552 status_t status = startAudioSource(source, attributes, &portId, uid);
5553 ALOGE_IF(status != OK, "%s: failed to start audio source (%d)", __func__, status);
5554 return mAudioSources.valueFor(portId);
5555}
5556
5557
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005558status_t AudioPolicyManager::connectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07005559{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005560 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->portId());
Eric Laurentd60560a2015-04-10 11:31:20 -07005561
5562 // make sure we only have one patch per source.
5563 disconnectAudioSource(sourceDesc);
5564
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005565 audio_attributes_t attributes = sourceDesc->attributes();
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005566 // May the device (dynamic) have been disconnected/reconnected, id has changed.
5567 sp<DeviceDescriptor> srcDevice = mAvailableInputDevices.getDevice(
5568 sourceDesc->srcDevice()->type(),
5569 String8(sourceDesc->srcDevice()->address().c_str()),
5570 AUDIO_FORMAT_DEFAULT);
François Gaffiec005e562018-11-06 15:04:49 +01005571 DeviceVector sinkDevices =
Francois Gaffieff1eb522020-05-06 18:37:04 +02005572 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false /*fromCache*/);
François Gaffiec005e562018-11-06 15:04:49 +01005573 ALOG_ASSERT(!sinkDevices.isEmpty(), "connectAudioSource(): no device found for attributes");
François Gaffie11d30102018-11-02 16:09:09 +01005574 sp<DeviceDescriptor> sinkDevice = sinkDevices.itemAt(0);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005575 if (!mAvailableOutputDevices.contains(sinkDevice)) {
5576 ALOGE("%s Device %s not available", __func__, sinkDevice->toString().c_str());
5577 return INVALID_OPERATION;
5578 }
François Gaffieafd4cea2019-11-18 15:50:22 +01005579 PatchBuilder patchBuilder;
5580 patchBuilder.addSink(sinkDevice).addSource(srcDevice);
5581 audio_patch_handle_t handle = AUDIO_PATCH_HANDLE_NONE;
François Gaffieafd4cea2019-11-18 15:50:22 +01005582
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005583 return connectAudioSourceToSink(
5584 sourceDesc, sinkDevice, patchBuilder.patch(), handle, mUidCached, 0 /*delayMs*/);
Eric Laurent554a2772015-04-10 11:29:24 -07005585}
5586
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005587status_t AudioPolicyManager::stopAudioSource(audio_port_handle_t portId)
Eric Laurent554a2772015-04-10 11:29:24 -07005588{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005589 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueFor(portId);
5590 ALOGV("%s port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005591 if (sourceDesc == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005592 ALOGW("%s unknown source for port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005593 return BAD_VALUE;
5594 }
5595 status_t status = disconnectAudioSource(sourceDesc);
5596
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005597 mAudioSources.removeItem(portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005598 return status;
5599}
5600
Andy Hung2ddee192015-12-18 17:34:44 -08005601status_t AudioPolicyManager::setMasterMono(bool mono)
5602{
5603 if (mMasterMono == mono) {
5604 return NO_ERROR;
5605 }
5606 mMasterMono = mono;
5607 // if enabling mono we close all offloaded devices, which will invalidate the
5608 // corresponding AudioTrack. The AudioTrack client/MediaPlayer is responsible
5609 // for recreating the new AudioTrack as non-offloaded PCM.
5610 //
5611 // If disabling mono, we leave all tracks as is: we don't know which clients
5612 // and tracks are able to be recreated as offloaded. The next "song" should
5613 // play back offloaded.
5614 if (mMasterMono) {
5615 Vector<audio_io_handle_t> offloaded;
5616 for (size_t i = 0; i < mOutputs.size(); ++i) {
5617 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
5618 if (desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
5619 offloaded.push(desc->mIoHandle);
5620 }
5621 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005622 for (const auto& handle : offloaded) {
5623 closeOutput(handle);
Andy Hung2ddee192015-12-18 17:34:44 -08005624 }
5625 }
5626 // update master mono for all remaining outputs
5627 for (size_t i = 0; i < mOutputs.size(); ++i) {
5628 updateMono(mOutputs.keyAt(i));
5629 }
5630 return NO_ERROR;
5631}
5632
5633status_t AudioPolicyManager::getMasterMono(bool *mono)
5634{
5635 *mono = mMasterMono;
5636 return NO_ERROR;
5637}
5638
Eric Laurentac9cef52017-06-09 15:46:26 -07005639float AudioPolicyManager::getStreamVolumeDB(
5640 audio_stream_type_t stream, int index, audio_devices_t device)
5641{
jiabin9a3361e2019-10-01 09:38:30 -07005642 return computeVolume(getVolumeCurves(stream), toVolumeSource(stream), index, {device});
Eric Laurentac9cef52017-06-09 15:46:26 -07005643}
5644
jiabin81772902018-04-02 17:52:27 -07005645status_t AudioPolicyManager::getSurroundFormats(unsigned int *numSurroundFormats,
5646 audio_format_t *surroundFormats,
Kriti Dang6537def2021-03-02 13:46:59 +01005647 bool *surroundFormatsEnabled)
jiabin81772902018-04-02 17:52:27 -07005648{
Kriti Dang6537def2021-03-02 13:46:59 +01005649 if (numSurroundFormats == nullptr || (*numSurroundFormats != 0 &&
5650 (surroundFormats == nullptr || surroundFormatsEnabled == nullptr))) {
jiabin81772902018-04-02 17:52:27 -07005651 return BAD_VALUE;
5652 }
Kriti Dang6537def2021-03-02 13:46:59 +01005653 ALOGV("%s() numSurroundFormats %d surroundFormats %p surroundFormatsEnabled %p",
5654 __func__, *numSurroundFormats, surroundFormats, surroundFormatsEnabled);
jiabin81772902018-04-02 17:52:27 -07005655
5656 size_t formatsWritten = 0;
5657 size_t formatsMax = *numSurroundFormats;
Kriti Dangef6be8f2020-11-05 11:58:19 +01005658
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005659 *numSurroundFormats = mConfig->getSurroundFormats().size();
Mikhail Naganov100f0122018-11-29 11:22:16 -08005660 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
5661 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005662 for (const auto& format: mConfig->getSurroundFormats()) {
jiabin81772902018-04-02 17:52:27 -07005663 if (formatsWritten < formatsMax) {
Kriti Dang6537def2021-03-02 13:46:59 +01005664 surroundFormats[formatsWritten] = format.first;
Mikhail Naganov100f0122018-11-29 11:22:16 -08005665 bool formatEnabled = true;
5666 switch (forceUse) {
5667 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL:
Kriti Dang6537def2021-03-02 13:46:59 +01005668 formatEnabled = mManualSurroundFormats.count(format.first) != 0;
Mikhail Naganov100f0122018-11-29 11:22:16 -08005669 break;
5670 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER:
5671 formatEnabled = false;
5672 break;
5673 default: // AUTO or ALWAYS => true
5674 break;
jiabin81772902018-04-02 17:52:27 -07005675 }
5676 surroundFormatsEnabled[formatsWritten++] = formatEnabled;
5677 }
jiabin81772902018-04-02 17:52:27 -07005678 }
5679 return NO_ERROR;
5680}
5681
Kriti Dang6537def2021-03-02 13:46:59 +01005682status_t AudioPolicyManager::getReportedSurroundFormats(unsigned int *numSurroundFormats,
5683 audio_format_t *surroundFormats) {
5684 if (numSurroundFormats == nullptr || (*numSurroundFormats != 0 && surroundFormats == nullptr)) {
5685 return BAD_VALUE;
5686 }
5687 ALOGV("%s() numSurroundFormats %d surroundFormats %p",
5688 __func__, *numSurroundFormats, surroundFormats);
5689
5690 size_t formatsWritten = 0;
5691 size_t formatsMax = *numSurroundFormats;
5692 std::unordered_set<audio_format_t> formats; // Uses primary surround formats only
5693
5694 // Return formats from all device profiles that have already been resolved by
5695 // checkOutputsForDevice().
5696 for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
5697 sp<DeviceDescriptor> device = mAvailableOutputDevices[i];
5698 audio_devices_t deviceType = device->type();
5699 // Enabling/disabling formats are applied to only HDMI devices. So, this function
5700 // returns formats reported by HDMI devices.
5701 if (deviceType != AUDIO_DEVICE_OUT_HDMI) {
5702 continue;
5703 }
5704 // Formats reported by sink devices
5705 std::unordered_set<audio_format_t> formatset;
5706 if (auto it = mReportedFormatsMap.find(device); it != mReportedFormatsMap.end()) {
5707 formatset.insert(it->second.begin(), it->second.end());
5708 }
5709
5710 // Formats hard-coded in the in policy configuration file (if any).
5711 FormatVector encodedFormats = device->encodedFormats();
5712 formatset.insert(encodedFormats.begin(), encodedFormats.end());
5713 // Filter the formats which are supported by the vendor hardware.
5714 for (auto it = formatset.begin(); it != formatset.end(); ++it) {
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005715 if (mConfig->getSurroundFormats().count(*it) != 0) {
Kriti Dang6537def2021-03-02 13:46:59 +01005716 formats.insert(*it);
5717 } else {
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005718 for (const auto& pair : mConfig->getSurroundFormats()) {
Kriti Dang6537def2021-03-02 13:46:59 +01005719 if (pair.second.count(*it) != 0) {
5720 formats.insert(pair.first);
5721 break;
5722 }
5723 }
5724 }
5725 }
5726 }
5727 *numSurroundFormats = formats.size();
5728 for (const auto& format: formats) {
5729 if (formatsWritten < formatsMax) {
5730 surroundFormats[formatsWritten++] = format;
5731 }
5732 }
5733 return NO_ERROR;
5734}
5735
jiabin81772902018-04-02 17:52:27 -07005736status_t AudioPolicyManager::setSurroundFormatEnabled(audio_format_t audioFormat, bool enabled)
5737{
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005738 ALOGV("%s() format 0x%X enabled %d", __func__, audioFormat, enabled);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005739 const auto& formatIter = mConfig->getSurroundFormats().find(audioFormat);
5740 if (formatIter == mConfig->getSurroundFormats().end()) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005741 ALOGW("%s() format 0x%X is not a known surround format", __func__, audioFormat);
jiabin81772902018-04-02 17:52:27 -07005742 return BAD_VALUE;
5743 }
5744
Mikhail Naganov100f0122018-11-29 11:22:16 -08005745 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND) !=
5746 AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005747 ALOGW("%s() not in manual mode for surround sound format selection", __func__);
jiabin81772902018-04-02 17:52:27 -07005748 return INVALID_OPERATION;
5749 }
5750
Mikhail Naganov100f0122018-11-29 11:22:16 -08005751 if ((mManualSurroundFormats.count(audioFormat) != 0) == enabled) {
jiabin81772902018-04-02 17:52:27 -07005752 return NO_ERROR;
5753 }
5754
Mikhail Naganov100f0122018-11-29 11:22:16 -08005755 std::unordered_set<audio_format_t> surroundFormatsBackup(mManualSurroundFormats);
jiabin81772902018-04-02 17:52:27 -07005756 if (enabled) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005757 mManualSurroundFormats.insert(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07005758 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005759 mManualSurroundFormats.insert(subFormat);
jiabin81772902018-04-02 17:52:27 -07005760 }
5761 } else {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005762 mManualSurroundFormats.erase(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07005763 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005764 mManualSurroundFormats.erase(subFormat);
jiabin81772902018-04-02 17:52:27 -07005765 }
5766 }
5767
5768 sp<SwAudioOutputDescriptor> outputDesc;
5769 bool profileUpdated = false;
jiabin9a3361e2019-10-01 09:38:30 -07005770 DeviceVector hdmiOutputDevices = mAvailableOutputDevices.getDevicesFromType(
5771 AUDIO_DEVICE_OUT_HDMI);
jiabin81772902018-04-02 17:52:27 -07005772 for (size_t i = 0; i < hdmiOutputDevices.size(); i++) {
5773 // Simulate reconnection to update enabled surround sound formats.
jiabince9f20e2019-09-12 16:29:15 -07005774 String8 address = String8(hdmiOutputDevices[i]->address().c_str());
jiabin5740f082019-08-19 15:08:30 -07005775 std::string name = hdmiOutputDevices[i]->getName();
jiabin81772902018-04-02 17:52:27 -07005776 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
5777 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
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 if (status != NO_ERROR) {
5782 continue;
5783 }
5784 status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
5785 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
5786 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005787 name.c_str(),
5788 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005789 profileUpdated |= (status == NO_ERROR);
5790 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08005791 // FIXME: Why doing this for input HDMI devices if we don't augment their reported formats?
jiabin9a3361e2019-10-01 09:38:30 -07005792 DeviceVector hdmiInputDevices = mAvailableInputDevices.getDevicesFromType(
jiabin81772902018-04-02 17:52:27 -07005793 AUDIO_DEVICE_IN_HDMI);
5794 for (size_t i = 0; i < hdmiInputDevices.size(); i++) {
5795 // Simulate reconnection to update enabled surround sound formats.
jiabince9f20e2019-09-12 16:29:15 -07005796 String8 address = String8(hdmiInputDevices[i]->address().c_str());
jiabin5740f082019-08-19 15:08:30 -07005797 std::string name = hdmiInputDevices[i]->getName();
jiabin81772902018-04-02 17:52:27 -07005798 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
5799 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
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 if (status != NO_ERROR) {
5804 continue;
5805 }
5806 status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
5807 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
5808 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005809 name.c_str(),
5810 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005811 profileUpdated |= (status == NO_ERROR);
5812 }
5813
jiabin81772902018-04-02 17:52:27 -07005814 if (!profileUpdated) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005815 ALOGW("%s() no audio profiles updated, undoing surround formats change", __func__);
Mikhail Naganov100f0122018-11-29 11:22:16 -08005816 mManualSurroundFormats = std::move(surroundFormatsBackup);
jiabin81772902018-04-02 17:52:27 -07005817 }
5818
5819 return profileUpdated ? NO_ERROR : INVALID_OPERATION;
5820}
5821
Eric Laurent5ada82e2019-08-29 17:53:54 -07005822void AudioPolicyManager::setAppState(audio_port_handle_t portId, app_state_t state)
Svet Ganovf4ddfef2018-01-16 07:37:58 -08005823{
Eric Laurent5ada82e2019-08-29 17:53:54 -07005824 ALOGV("%s(portId:%d, state:%d)", __func__, portId, state);
Eric Laurenta9f86652018-11-28 17:23:11 -08005825 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent5ada82e2019-08-29 17:53:54 -07005826 mInputs.valueAt(i)->setAppState(portId, state);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08005827 }
5828}
5829
jiabin6012f912018-11-02 17:06:30 -07005830bool AudioPolicyManager::isHapticPlaybackSupported()
5831{
5832 for (const auto& hwModule : mHwModules) {
5833 const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
5834 for (const auto &outProfile : outputProfiles) {
5835 struct audio_port audioPort;
5836 outProfile->toAudioPort(&audioPort);
5837 for (size_t i = 0; i < audioPort.num_channel_masks; i++) {
5838 if (audioPort.channel_masks[i] & AUDIO_CHANNEL_HAPTIC_ALL) {
5839 return true;
5840 }
5841 }
5842 }
5843 }
5844 return false;
5845}
5846
Carter Hsu325a8eb2022-01-19 19:56:51 +08005847bool AudioPolicyManager::isUltrasoundSupported()
5848{
5849 bool hasUltrasoundOutput = false;
5850 bool hasUltrasoundInput = false;
5851 for (const auto& hwModule : mHwModules) {
5852 const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
5853 if (!hasUltrasoundOutput) {
5854 for (const auto &outProfile : outputProfiles) {
5855 if (outProfile->getFlags() & AUDIO_OUTPUT_FLAG_ULTRASOUND) {
5856 hasUltrasoundOutput = true;
5857 break;
5858 }
5859 }
5860 }
5861
5862 const InputProfileCollection &inputProfiles = hwModule->getInputProfiles();
5863 if (!hasUltrasoundInput) {
5864 for (const auto &inputProfile : inputProfiles) {
5865 if (inputProfile->getFlags() & AUDIO_INPUT_FLAG_ULTRASOUND) {
5866 hasUltrasoundInput = true;
5867 break;
5868 }
5869 }
5870 }
5871
5872 if (hasUltrasoundOutput && hasUltrasoundInput)
5873 return true;
5874 }
5875 return false;
5876}
5877
Atneya Nair698f5ef2022-12-15 16:15:09 -08005878bool AudioPolicyManager::isHotwordStreamSupported(bool lookbackAudio)
5879{
5880 const auto mask = AUDIO_INPUT_FLAG_HOTWORD_TAP |
5881 (lookbackAudio ? AUDIO_INPUT_FLAG_HW_LOOKBACK : 0);
5882 for (const auto& hwModule : mHwModules) {
5883 const InputProfileCollection &inputProfiles = hwModule->getInputProfiles();
5884 for (const auto &inputProfile : inputProfiles) {
5885 if ((inputProfile->getFlags() & mask) == mask) {
5886 return true;
5887 }
5888 }
5889 }
5890 return false;
5891}
5892
Eric Laurent8340e672019-11-06 11:01:08 -08005893bool AudioPolicyManager::isCallScreenModeSupported()
5894{
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005895 return mConfig->isCallScreenModeSupported();
Eric Laurent8340e672019-11-06 11:01:08 -08005896}
5897
5898
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005899status_t AudioPolicyManager::disconnectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07005900{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005901 ALOGV("%s port Id %d", __FUNCTION__, sourceDesc->portId());
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005902 if (!sourceDesc->isConnected()) {
5903 ALOGV("%s port Id %d already disconnected", __FUNCTION__, sourceDesc->portId());
5904 return NO_ERROR;
5905 }
François Gaffieafd4cea2019-11-18 15:50:22 +01005906 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
5907 if (swOutput != 0) {
5908 status_t status = stopSource(swOutput, sourceDesc);
Eric Laurent733ce942017-12-07 12:18:25 -08005909 if (status == NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005910 swOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08005911 }
jiabinbce0c1d2020-10-05 11:20:18 -07005912 if (releaseOutput(sourceDesc->portId())) {
5913 // The output descriptor is reopened to query dynamic profiles. In that case, there is
5914 // no need to release audio patch here but just return NO_ERROR.
5915 return NO_ERROR;
5916 }
Eric Laurentd60560a2015-04-10 11:31:20 -07005917 } else {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005918 sp<HwAudioOutputDescriptor> hwOutputDesc = sourceDesc->hwOutput().promote();
Eric Laurentd60560a2015-04-10 11:31:20 -07005919 if (hwOutputDesc != 0) {
Eric Laurentd60560a2015-04-10 11:31:20 -07005920 // close Hwoutput and remove from mHwOutputs
5921 } else {
5922 ALOGW("%s source has neither SW nor HW output", __FUNCTION__);
5923 }
5924 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005925 status_t status = releaseAudioPatchInternal(sourceDesc->getPatchHandle(), 0, sourceDesc);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005926 sourceDesc->disconnect();
5927 return status;
Eric Laurentd60560a2015-04-10 11:31:20 -07005928}
5929
François Gaffiec005e562018-11-06 15:04:49 +01005930sp<SourceClientDescriptor> AudioPolicyManager::getSourceForAttributesOnOutput(
5931 audio_io_handle_t output, const audio_attributes_t &attr)
Eric Laurentd60560a2015-04-10 11:31:20 -07005932{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005933 sp<SourceClientDescriptor> source;
Eric Laurentd60560a2015-04-10 11:31:20 -07005934 for (size_t i = 0; i < mAudioSources.size(); i++) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005935 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005936 sp<SwAudioOutputDescriptor> outputDesc = sourceDesc->swOutput().promote();
François Gaffiec005e562018-11-06 15:04:49 +01005937 if (followsSameRouting(attr, sourceDesc->attributes()) &&
5938 outputDesc != 0 && outputDesc->mIoHandle == output) {
Eric Laurentd60560a2015-04-10 11:31:20 -07005939 source = sourceDesc;
5940 break;
5941 }
5942 }
5943 return source;
Eric Laurent554a2772015-04-10 11:29:24 -07005944}
5945
Eric Laurentb4f42a92022-01-17 17:37:31 +01005946bool AudioPolicyManager::canBeSpatializedInt(const audio_attributes_t *attr,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005947 const audio_config_t *config,
Andy Hung9dd1a5b2022-05-10 15:39:39 -07005948 const AudioDeviceTypeAddrVector &devices) const
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005949{
5950 // The caller can have the audio attributes criteria ignored by either passing a null ptr or
5951 // the AUDIO_ATTRIBUTES_INITIALIZER value.
Eric Laurentfa0f6742021-08-17 18:39:44 +02005952 // If attributes are specified, current policy is to only allow spatialization for media
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005953 // and game usages.
Eric Laurent39095982021-08-24 18:29:27 +02005954 if (attr != nullptr && *attr != AUDIO_ATTRIBUTES_INITIALIZER) {
5955 if (attr->usage != AUDIO_USAGE_MEDIA && attr->usage != AUDIO_USAGE_GAME) {
5956 return false;
5957 }
5958 if ((attr->flags & (AUDIO_FLAG_CONTENT_SPATIALIZED | AUDIO_FLAG_NEVER_SPATIALIZE)) != 0) {
5959 return false;
5960 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005961 }
5962
Eric Laurentd332bc82023-08-04 11:45:23 +02005963 // The caller can have the audio config criteria ignored by either passing a null ptr or
5964 // the AUDIO_CONFIG_INITIALIZER value.
5965 // If an audio config is specified, current policy is to only allow spatialization for
5966 // some positional channel masks and PCM format
5967
5968 if (config != nullptr && *config != AUDIO_CONFIG_INITIALIZER) {
5969 if (!audio_is_channel_mask_spatialized(config->channel_mask)) {
5970 return false;
5971 }
5972 if (!audio_is_linear_pcm(config->format)) {
5973 return false;
5974 }
5975 }
5976
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005977 sp<IOProfile> profile =
Eric Laurent39095982021-08-24 18:29:27 +02005978 getSpatializerOutputProfile(config, devices);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005979 if (profile == nullptr) {
5980 return false;
5981 }
5982
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005983 return true;
5984}
5985
5986void AudioPolicyManager::checkVirtualizerClientRoutes() {
5987 std::set<audio_stream_type_t> streamsToInvalidate;
5988 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent39095982021-08-24 18:29:27 +02005989 const sp<SwAudioOutputDescriptor>& desc = mOutputs[i];
5990 for (const sp<TrackClientDescriptor>& client : desc->getClientIterable()) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005991 audio_attributes_t attr = client->attributes();
5992 DeviceVector devices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false);
5993 AudioDeviceTypeAddrVector devicesTypeAddress = devices.toTypeAddrVector();
5994 audio_config_base_t clientConfig = client->config();
5995 audio_config_t config = audio_config_initializer(&clientConfig);
Eric Laurent39095982021-08-24 18:29:27 +02005996 if (desc != mSpatializerOutput
Andy Hung9dd1a5b2022-05-10 15:39:39 -07005997 && canBeSpatializedInt(&attr, &config, devicesTypeAddress)) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005998 streamsToInvalidate.insert(client->stream());
5999 }
6000 }
6001 }
6002
jiabinc44b3462022-12-08 12:52:31 -08006003 invalidateStreams(StreamTypeVector(streamsToInvalidate.begin(), streamsToInvalidate.end()));
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006004}
6005
Eric Laurente191d1b2022-04-15 11:59:25 +02006006
6007bool AudioPolicyManager::isOutputOnlyAvailableRouteToSomeDevice(
6008 const sp<SwAudioOutputDescriptor>& outputDesc) {
6009 if (outputDesc->isDuplicated()) {
6010 return false;
6011 }
6012 DeviceVector devices = outputDesc->supportedDevices();
6013 for (size_t i = 0; i < mOutputs.size(); i++) {
6014 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
6015 if (desc == outputDesc || desc->isDuplicated()) {
6016 continue;
6017 }
6018 DeviceVector sharedDevices = desc->filterSupportedDevices(devices);
6019 if (!sharedDevices.isEmpty()
6020 && (desc->devicesSupportEncodedFormats(sharedDevices.types())
6021 == outputDesc->devicesSupportEncodedFormats(sharedDevices.types()))) {
6022 return false;
6023 }
6024 }
6025 return true;
6026}
6027
6028
Eric Laurentfa0f6742021-08-17 18:39:44 +02006029status_t AudioPolicyManager::getSpatializerOutput(const audio_config_base_t *mixerConfig,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006030 const audio_attributes_t *attr,
6031 audio_io_handle_t *output) {
6032 *output = AUDIO_IO_HANDLE_NONE;
6033
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006034 DeviceVector devices = mEngine->getOutputDevicesForAttributes(*attr, nullptr, false);
6035 AudioDeviceTypeAddrVector devicesTypeAddress = devices.toTypeAddrVector();
6036 audio_config_t *configPtr = nullptr;
6037 audio_config_t config;
6038 if (mixerConfig != nullptr) {
6039 config = audio_config_initializer(mixerConfig);
6040 configPtr = &config;
6041 }
Andy Hung9dd1a5b2022-05-10 15:39:39 -07006042 if (!canBeSpatializedInt(attr, configPtr, devicesTypeAddress)) {
Eric Laurente191d1b2022-04-15 11:59:25 +02006043 ALOGV("%s provided attributes or mixer config cannot be spatialized", __func__);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006044 return BAD_VALUE;
6045 }
6046
6047 sp<IOProfile> profile =
Eric Laurent39095982021-08-24 18:29:27 +02006048 getSpatializerOutputProfile(configPtr, devicesTypeAddress);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006049 if (profile == nullptr) {
Eric Laurente191d1b2022-04-15 11:59:25 +02006050 ALOGV("%s no suitable output profile for provided attributes or mixer config", __func__);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006051 return BAD_VALUE;
6052 }
6053
Eric Laurente191d1b2022-04-15 11:59:25 +02006054 std::vector<sp<SwAudioOutputDescriptor>> spatializerOutputs;
Eric Laurent39095982021-08-24 18:29:27 +02006055 for (size_t i = 0; i < mOutputs.size(); i++) {
6056 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente191d1b2022-04-15 11:59:25 +02006057 if (!desc->isDuplicated()
6058 && (desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0) {
6059 spatializerOutputs.push_back(desc);
6060 ALOGV("%s adding opened spatializer Output %d", __func__, desc->mIoHandle);
Eric Laurent39095982021-08-24 18:29:27 +02006061 }
6062 }
Eric Laurente191d1b2022-04-15 11:59:25 +02006063 mSpatializerOutput.clear();
6064 bool outputsChanged = false;
6065 for (const auto& desc : spatializerOutputs) {
6066 if (desc->mProfile == profile
6067 && (configPtr == nullptr
6068 || configPtr->channel_mask == desc->mMixerChannelMask)) {
6069 mSpatializerOutput = desc;
6070 ALOGV("%s reusing current spatializer output %d", __func__, desc->mIoHandle);
6071 } else {
6072 ALOGV("%s closing spatializerOutput output %d to match channel mask %#x"
6073 " and devices %s", __func__, desc->mIoHandle,
6074 configPtr != nullptr ? configPtr->channel_mask : 0,
6075 devices.toString().c_str());
6076 closeOutput(desc->mIoHandle);
6077 outputsChanged = true;
6078 }
Eric Laurent39095982021-08-24 18:29:27 +02006079 }
6080
Eric Laurente191d1b2022-04-15 11:59:25 +02006081 if (mSpatializerOutput == nullptr) {
Eric Laurentb4f42a92022-01-17 17:37:31 +01006082 sp<SwAudioOutputDescriptor> desc =
6083 openOutputWithProfileAndDevice(profile, devices, mixerConfig);
Eric Laurente191d1b2022-04-15 11:59:25 +02006084 if (desc != nullptr) {
6085 mSpatializerOutput = desc;
6086 outputsChanged = true;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006087 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006088 }
6089
6090 checkVirtualizerClientRoutes();
6091
Eric Laurente191d1b2022-04-15 11:59:25 +02006092 if (outputsChanged) {
6093 mPreviousOutputs = mOutputs;
6094 mpClientInterface->onAudioPortListUpdate();
6095 }
6096
6097 if (mSpatializerOutput == nullptr) {
6098 ALOGV("%s could not open spatializer output with requested config", __func__);
6099 return BAD_VALUE;
6100 }
Eric Laurent39095982021-08-24 18:29:27 +02006101 *output = mSpatializerOutput->mIoHandle;
Eric Laurente191d1b2022-04-15 11:59:25 +02006102 ALOGV("%s returning new spatializer output %d", __func__, *output);
6103 return OK;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006104}
6105
Eric Laurentfa0f6742021-08-17 18:39:44 +02006106status_t AudioPolicyManager::releaseSpatializerOutput(audio_io_handle_t output) {
6107 if (mSpatializerOutput == nullptr) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006108 return INVALID_OPERATION;
6109 }
Eric Laurentfa0f6742021-08-17 18:39:44 +02006110 if (mSpatializerOutput->mIoHandle != output) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006111 return BAD_VALUE;
6112 }
Eric Laurent39095982021-08-24 18:29:27 +02006113
Eric Laurente191d1b2022-04-15 11:59:25 +02006114 if (!isOutputOnlyAvailableRouteToSomeDevice(mSpatializerOutput)) {
6115 ALOGV("%s closing spatializer output %d", __func__, mSpatializerOutput->mIoHandle);
6116 closeOutput(mSpatializerOutput->mIoHandle);
6117 //from now on mSpatializerOutput is null
6118 checkVirtualizerClientRoutes();
6119 }
Eric Laurent39095982021-08-24 18:29:27 +02006120
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006121 return NO_ERROR;
6122}
6123
Eric Laurente552edb2014-03-10 17:42:56 -07006124// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07006125// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07006126// ----------------------------------------------------------------------------
Eric Laurent6a94d692014-05-20 11:18:06 -07006127uint32_t AudioPolicyManager::nextAudioPortGeneration()
6128{
Mikhail Naganov2773dd72017-12-08 10:12:11 -08006129 return mAudioPortGeneration++;
Eric Laurent6a94d692014-05-20 11:18:06 -07006130}
6131
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006132AudioPolicyManager::AudioPolicyManager(const sp<const AudioPolicyConfig>& config,
Mikhail Naganovf1b6d972023-05-02 13:56:01 -07006133 EngineInstance&& engine,
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006134 AudioPolicyClientInterface *clientInterface)
Eric Laurente552edb2014-03-10 17:42:56 -07006135 :
Andy Hung4ef19fa2018-05-15 19:35:29 -07006136 mUidCached(AID_AUDIOSERVER), // no need to call getuid(), there's only one of us running.
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006137 mConfig(config),
Mikhail Naganovf1b6d972023-05-02 13:56:01 -07006138 mEngine(std::move(engine)),
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006139 mpClientInterface(clientInterface),
Eric Laurente552edb2014-03-10 17:42:56 -07006140 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
Eric Laurent3a4311c2014-03-17 12:00:47 -07006141 mA2dpSuspended(false),
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006142 mAudioPortGeneration(1),
6143 mBeaconMuteRefCount(0),
6144 mBeaconPlayingRefCount(0),
Eric Laurent9459fb02015-08-12 18:36:32 -07006145 mBeaconMuted(false),
Andy Hung2ddee192015-12-18 17:34:44 -08006146 mTtsOutputAvailable(false),
Eric Laurent36829f92017-04-07 19:04:42 -07006147 mMasterMono(false),
Eric Laurent4eb58f12018-12-07 16:41:02 -08006148 mMusicEffectOutput(AUDIO_IO_HANDLE_NONE)
Eric Laurente552edb2014-03-10 17:42:56 -07006149{
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006150}
François Gaffied1ab2bd2015-12-02 18:20:06 +01006151
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006152status_t AudioPolicyManager::initialize() {
Mikhail Naganovf1b6d972023-05-02 13:56:01 -07006153 if (mEngine == nullptr) {
6154 return NO_INIT;
François Gaffie2110e042015-03-24 08:41:51 +01006155 }
6156 mEngine->setObserver(this);
6157 status_t status = mEngine->initCheck();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006158 if (status != NO_ERROR) {
6159 LOG_FATAL("Policy engine not initialized(err=%d)", status);
6160 return status;
6161 }
François Gaffie2110e042015-03-24 08:41:51 +01006162
jiabin29230182023-04-04 21:02:36 +00006163 // The actual device selection cache will be updated when calling `updateDevicesAndOutputs`
6164 // at the end of this function.
6165 mEngine->initializeDeviceSelectionCache();
Eric Laurent1d69c872021-01-11 18:53:01 +01006166 mCommunnicationStrategy = mEngine->getProductStrategyForAttributes(
6167 mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL));
6168
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006169 // after parsing the config, mConfig contain all known devices;
Eric Laurente552edb2014-03-10 17:42:56 -07006170 // open all output streams needed to access attached devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006171 onNewAudioModulesAvailableInt(nullptr /*newDevices*/);
François Gaffie11d30102018-11-02 16:09:09 +01006172
Eric Laurent3a4311c2014-03-17 12:00:47 -07006173 // make sure default device is reachable
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006174 if (const auto defaultOutputDevice = mConfig->getDefaultOutputDevice();
6175 defaultOutputDevice == nullptr ||
6176 !mAvailableOutputDevices.contains(defaultOutputDevice)) {
6177 ALOGE_IF(defaultOutputDevice != nullptr, "Default device %s is unreachable",
6178 defaultOutputDevice->toString().c_str());
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006179 status = NO_INIT;
Eric Laurent3a4311c2014-03-17 12:00:47 -07006180 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02006181 ALOGW_IF(mPrimaryOutput == nullptr, "The policy configuration does not declare a primary output");
Eric Laurente552edb2014-03-10 17:42:56 -07006182
Tomoharu Kasahara71c90912018-10-31 09:10:12 +09006183 // Silence ALOGV statements
6184 property_set("log.tag." LOG_TAG, "D");
6185
Eric Laurente552edb2014-03-10 17:42:56 -07006186 updateDevicesAndOutputs();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006187 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07006188}
6189
Eric Laurente0720872014-03-11 09:30:41 -07006190AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07006191{
Eric Laurente552edb2014-03-10 17:42:56 -07006192 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08006193 mOutputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07006194 }
6195 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08006196 mInputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07006197 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07006198 mAvailableOutputDevices.clear();
6199 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07006200 mOutputs.clear();
6201 mInputs.clear();
6202 mHwModules.clear();
Mikhail Naganov100f0122018-11-29 11:22:16 -08006203 mManualSurroundFormats.clear();
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006204 mConfig.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07006205}
6206
Eric Laurente0720872014-03-11 09:30:41 -07006207status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07006208{
Eric Laurent87ffa392015-05-22 10:32:38 -07006209 return hasPrimaryOutput() ? NO_ERROR : NO_INIT;
Eric Laurente552edb2014-03-10 17:42:56 -07006210}
6211
Eric Laurente552edb2014-03-10 17:42:56 -07006212// ---
6213
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006214void AudioPolicyManager::onNewAudioModulesAvailable()
6215{
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006216 DeviceVector newDevices;
6217 onNewAudioModulesAvailableInt(&newDevices);
6218 if (!newDevices.empty()) {
6219 nextAudioPortGeneration();
6220 mpClientInterface->onAudioPortListUpdate();
6221 }
6222}
6223
6224void AudioPolicyManager::onNewAudioModulesAvailableInt(DeviceVector *newDevices)
6225{
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006226 for (const auto& hwModule : mConfig->getHwModules()) {
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006227 if (std::find(mHwModules.begin(), mHwModules.end(), hwModule) != mHwModules.end()) {
6228 continue;
6229 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006230 if (hwModule->getHandle() == AUDIO_MODULE_HANDLE_NONE) {
Mikhail Naganovffd97712023-05-03 17:45:36 -07006231 if (audio_module_handle_t handle = mpClientInterface->loadHwModule(hwModule->getName());
6232 handle != AUDIO_MODULE_HANDLE_NONE) {
6233 hwModule->setHandle(handle);
6234 } else {
6235 ALOGW("could not load HW module %s", hwModule->getName());
6236 continue;
6237 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006238 }
6239 mHwModules.push_back(hwModule);
Dean Wheatley12a87132021-04-16 10:08:49 +10006240 // open all output streams needed to access attached devices.
6241 // direct outputs are closed immediately after checking the availability of attached devices
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006242 // This also validates mAvailableOutputDevices list
6243 for (const auto& outProfile : hwModule->getOutputProfiles()) {
6244 if (!outProfile->canOpenNewIo()) {
6245 ALOGE("Invalid Output profile max open count %u for profile %s",
6246 outProfile->maxOpenCount, outProfile->getTagName().c_str());
6247 continue;
6248 }
6249 if (!outProfile->hasSupportedDevices()) {
6250 ALOGW("Output profile contains no device on module %s", hwModule->getName());
6251 continue;
6252 }
Carter Hsu1a3364a2022-01-21 15:32:56 +08006253 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_TTS) != 0 ||
6254 (outProfile->getFlags() & AUDIO_OUTPUT_FLAG_ULTRASOUND) != 0) {
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006255 mTtsOutputAvailable = true;
6256 }
6257
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006258 const DeviceVector &supportedDevices = outProfile->getSupportedDevices();
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006259 DeviceVector availProfileDevices = supportedDevices.filter(mConfig->getOutputDevices());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006260 sp<DeviceDescriptor> supportedDevice = 0;
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006261 if (supportedDevices.contains(mConfig->getDefaultOutputDevice())) {
6262 supportedDevice = mConfig->getDefaultOutputDevice();
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006263 } else {
6264 // choose first device present in profile's SupportedDevices also part of
6265 // mAvailableOutputDevices.
6266 if (availProfileDevices.isEmpty()) {
6267 continue;
6268 }
6269 supportedDevice = availProfileDevices.itemAt(0);
6270 }
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006271 if (!mConfig->getOutputDevices().contains(supportedDevice)) {
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006272 continue;
6273 }
6274 sp<SwAudioOutputDescriptor> outputDesc = new SwAudioOutputDescriptor(outProfile,
6275 mpClientInterface);
6276 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentf1f22e72021-07-13 14:04:14 +02006277 status_t status = outputDesc->open(nullptr /* halConfig */, nullptr /* mixerConfig */,
6278 DeviceVector(supportedDevice),
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006279 AUDIO_STREAM_DEFAULT,
6280 AUDIO_OUTPUT_FLAG_NONE, &output);
6281 if (status != NO_ERROR) {
6282 ALOGW("Cannot open output stream for devices %s on hw module %s",
6283 supportedDevice->toString().c_str(), hwModule->getName());
6284 continue;
6285 }
6286 for (const auto &device : availProfileDevices) {
6287 // give a valid ID to an attached device once confirmed it is reachable
6288 if (!device->isAttached()) {
6289 device->attach(hwModule);
6290 mAvailableOutputDevices.add(device);
jiabin1c4794b2020-05-05 10:08:05 -07006291 device->setEncapsulationInfoFromHal(mpClientInterface);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006292 if (newDevices) newDevices->add(device);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006293 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
6294 }
6295 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02006296 if (mPrimaryOutput == nullptr &&
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006297 outProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
6298 mPrimaryOutput = outputDesc;
François Gaffiedb1755b2023-09-01 11:50:35 +02006299 mPrimaryModuleHandle = mPrimaryOutput->getModuleHandle();
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006300 }
Eric Laurent39095982021-08-24 18:29:27 +02006301 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
Eric Laurentc529cf62020-04-17 18:19:10 -07006302 outputDesc->close();
6303 } else {
6304 addOutput(output, outputDesc);
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05306305 setOutputDevices(__func__, outputDesc,
Eric Laurentc529cf62020-04-17 18:19:10 -07006306 DeviceVector(supportedDevice),
6307 true,
6308 0,
6309 NULL);
6310 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006311 }
6312 // open input streams needed to access attached devices to validate
6313 // mAvailableInputDevices list
6314 for (const auto& inProfile : hwModule->getInputProfiles()) {
6315 if (!inProfile->canOpenNewIo()) {
6316 ALOGE("Invalid Input profile max open count %u for profile %s",
6317 inProfile->maxOpenCount, inProfile->getTagName().c_str());
6318 continue;
6319 }
6320 if (!inProfile->hasSupportedDevices()) {
6321 ALOGW("Input profile contains no device on module %s", hwModule->getName());
6322 continue;
6323 }
6324 // chose first device present in profile's SupportedDevices also part of
6325 // available input devices
6326 const DeviceVector &supportedDevices = inProfile->getSupportedDevices();
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006327 DeviceVector availProfileDevices = supportedDevices.filter(mConfig->getInputDevices());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006328 if (availProfileDevices.isEmpty()) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01006329 ALOGV("%s: Input device list is empty! for profile %s",
6330 __func__, inProfile->getTagName().c_str());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006331 continue;
6332 }
6333 sp<AudioInputDescriptor> inputDesc =
6334 new AudioInputDescriptor(inProfile, mpClientInterface);
6335
6336 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
6337 status_t status = inputDesc->open(nullptr,
6338 availProfileDevices.itemAt(0),
6339 AUDIO_SOURCE_MIC,
6340 AUDIO_INPUT_FLAG_NONE,
6341 &input);
6342 if (status != NO_ERROR) {
6343 ALOGW("Cannot open input stream for device %s on hw module %s",
6344 availProfileDevices.toString().c_str(),
6345 hwModule->getName());
6346 continue;
6347 }
6348 for (const auto &device : availProfileDevices) {
6349 // give a valid ID to an attached device once confirmed it is reachable
6350 if (!device->isAttached()) {
6351 device->attach(hwModule);
6352 device->importAudioPortAndPickAudioProfile(inProfile, true);
6353 mAvailableInputDevices.add(device);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006354 if (newDevices) newDevices->add(device);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006355 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
6356 }
6357 }
6358 inputDesc->close();
6359 }
6360 }
Eric Laurente191d1b2022-04-15 11:59:25 +02006361
6362 // Check if spatializer outputs can be closed until used.
6363 // mOutputs vector never contains duplicated outputs at this point.
6364 std::vector<audio_io_handle_t> outputsClosed;
6365 for (size_t i = 0; i < mOutputs.size(); i++) {
6366 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
6367 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0
6368 && !isOutputOnlyAvailableRouteToSomeDevice(desc)) {
6369 outputsClosed.push_back(desc->mIoHandle);
6370 desc->close();
6371 }
6372 }
6373 for (auto output : outputsClosed) {
6374 removeOutput(output);
6375 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006376}
6377
Eric Laurent98e38192018-02-15 18:31:53 -08006378void AudioPolicyManager::addOutput(audio_io_handle_t output,
6379 const sp<SwAudioOutputDescriptor>& outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07006380{
Eric Laurent1c333e22014-05-20 10:48:17 -07006381 mOutputs.add(output, outputDesc);
jiabin9a3361e2019-10-01 09:38:30 -07006382 applyStreamVolumes(outputDesc, DeviceTypeSet(), 0 /* delayMs */, true /* force */);
Andy Hung2ddee192015-12-18 17:34:44 -08006383 updateMono(output); // update mono status when adding to output list
Eric Laurent36829f92017-04-07 19:04:42 -07006384 selectOutputForMusicEffects();
Eric Laurent6a94d692014-05-20 11:18:06 -07006385 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07006386}
6387
François Gaffie53615e22015-03-19 09:24:12 +01006388void AudioPolicyManager::removeOutput(audio_io_handle_t output)
6389{
Francois Gaffiebce7cd42020-10-14 16:13:20 +02006390 if (mPrimaryOutput != 0 && mPrimaryOutput == mOutputs.valueFor(output)) {
6391 ALOGV("%s: removing primary output", __func__);
6392 mPrimaryOutput = nullptr;
6393 }
François Gaffie53615e22015-03-19 09:24:12 +01006394 mOutputs.removeItem(output);
Eric Laurent36829f92017-04-07 19:04:42 -07006395 selectOutputForMusicEffects();
François Gaffie53615e22015-03-19 09:24:12 +01006396}
6397
Eric Laurent98e38192018-02-15 18:31:53 -08006398void AudioPolicyManager::addInput(audio_io_handle_t input,
6399 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07006400{
Eric Laurent1c333e22014-05-20 10:48:17 -07006401 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07006402 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07006403}
Eric Laurente552edb2014-03-10 17:42:56 -07006404
François Gaffie11d30102018-11-02 16:09:09 +01006405status_t AudioPolicyManager::checkOutputsForDevice(const sp<DeviceDescriptor>& device,
François Gaffie53615e22015-03-19 09:24:12 +01006406 audio_policy_dev_state_t state,
François Gaffie11d30102018-11-02 16:09:09 +01006407 SortedVector<audio_io_handle_t>& outputs)
Eric Laurente552edb2014-03-10 17:42:56 -07006408{
François Gaffie11d30102018-11-02 16:09:09 +01006409 audio_devices_t deviceType = device->type();
jiabince9f20e2019-09-12 16:29:15 -07006410 const String8 &address = String8(device->address().c_str());
Eric Laurentc75307b2015-03-17 15:29:32 -07006411 sp<SwAudioOutputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07006412
François Gaffie11d30102018-11-02 16:09:09 +01006413 if (audio_device_is_digital(deviceType)) {
Eric Laurentcc750d32015-06-25 11:48:20 -07006414 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01006415 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07006416 }
Eric Laurente552edb2014-03-10 17:42:56 -07006417
Eric Laurent3b73df72014-03-11 09:06:29 -07006418 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
jiabinb4fed192020-09-22 14:45:40 -07006419 // first call getAudioPort to get the supported attributes from the HAL
6420 struct audio_port_v7 port = {};
6421 device->toAudioPort(&port);
6422 status_t status = mpClientInterface->getAudioPort(&port);
6423 if (status == NO_ERROR) {
6424 device->importAudioPort(port);
6425 }
6426
6427 // then list already open outputs that can be routed to this device
Eric Laurente552edb2014-03-10 17:42:56 -07006428 for (size_t i = 0; i < mOutputs.size(); i++) {
6429 desc = mOutputs.valueAt(i);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006430 if (!desc->isDuplicated() && desc->supportsDevice(device)
jiabin9a3361e2019-10-01 09:38:30 -07006431 && desc->devicesSupportEncodedFormats({deviceType})) {
François Gaffie11d30102018-11-02 16:09:09 +01006432 ALOGV("checkOutputsForDevice(): adding opened output %d on device %s",
6433 mOutputs.keyAt(i), device->toString().c_str());
6434 outputs.add(mOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07006435 }
6436 }
6437 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07006438 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006439 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006440 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
6441 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
François Gaffie11d30102018-11-02 16:09:09 +01006442 if (profile->supportsDevice(device)) {
6443 profiles.add(profile);
6444 ALOGV("checkOutputsForDevice(): adding profile %zu from module %s",
6445 j, hwModule->getName());
Eric Laurente552edb2014-03-10 17:42:56 -07006446 }
6447 }
6448 }
6449
Eric Laurent7b279bb2015-12-14 10:18:23 -08006450 ALOGV(" found %zu profiles, %zu outputs", profiles.size(), outputs.size());
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006451
Eric Laurente552edb2014-03-10 17:42:56 -07006452 if (profiles.isEmpty() && outputs.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006453 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07006454 return BAD_VALUE;
6455 }
6456
6457 // open outputs for matching profiles if needed. Direct outputs are also opened to
6458 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
6459 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07006460 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07006461
6462 // nothing to do if one output is already opened for this profile
6463 size_t j;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006464 for (j = 0; j < outputs.size(); j++) {
6465 desc = mOutputs.valueFor(outputs.itemAt(j));
Eric Laurente552edb2014-03-10 17:42:56 -07006466 if (!desc->isDuplicated() && desc->mProfile == profile) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07006467 // matching profile: save the sample rates, format and channel masks supported
6468 // by the profile in our device descriptor
François Gaffie11d30102018-11-02 16:09:09 +01006469 if (audio_device_is_digital(deviceType)) {
jiabin4ef93452019-09-10 14:29:54 -07006470 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006471 }
Eric Laurente552edb2014-03-10 17:42:56 -07006472 break;
6473 }
6474 }
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006475 if (j != outputs.size()) {
Eric Laurente552edb2014-03-10 17:42:56 -07006476 continue;
6477 }
6478
Eric Laurent3974e3b2017-12-07 17:58:43 -08006479 if (!profile->canOpenNewIo()) {
6480 ALOGW("Max Output number %u already opened for this profile %s",
6481 profile->maxOpenCount, profile->getTagName().c_str());
6482 continue;
6483 }
6484
Eric Laurent83efe1c2017-07-09 16:51:08 -07006485 ALOGV("opening output for device %08x with params %s profile %p name %s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00006486 deviceType, address.c_str(), profile.get(), profile->getName().c_str());
jiabinbce0c1d2020-10-05 11:20:18 -07006487 desc = openOutputWithProfileAndDevice(profile, DeviceVector(device));
6488 audio_io_handle_t output = desc == nullptr ? AUDIO_IO_HANDLE_NONE : desc->mIoHandle;
Eric Laurentcf2c0212014-07-25 16:20:43 -07006489 if (output == AUDIO_IO_HANDLE_NONE) {
François Gaffie11d30102018-11-02 16:09:09 +01006490 ALOGW("checkOutputsForDevice() could not open output for device %x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07006491 profiles.removeAt(profile_index);
6492 profile_index--;
6493 } else {
6494 outputs.add(output);
Paul McLean9080a4c2015-06-18 08:24:02 -07006495 // Load digital format info only for digital devices
François Gaffie11d30102018-11-02 16:09:09 +01006496 if (audio_device_is_digital(deviceType)) {
jiabinbce0c1d2020-10-05 11:20:18 -07006497 // TODO: when getAudioPort is ready, it may not be needed to import the audio
6498 // port but just pick audio profile
jiabin4ef93452019-09-10 14:29:54 -07006499 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006500 }
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07006501
François Gaffie11d30102018-11-02 16:09:09 +01006502 if (device_distinguishes_on_address(deviceType)) {
6503 ALOGV("checkOutputsForDevice(): setOutputDevices %s",
6504 device->toString().c_str());
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05306505 setOutputDevices(__func__, desc, DeviceVector(device), true/*force*/,
6506 0/*delay*/, NULL/*patch handle*/);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006507 }
Eric Laurente552edb2014-03-10 17:42:56 -07006508 ALOGV("checkOutputsForDevice(): adding output %d", output);
6509 }
6510 }
6511
6512 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006513 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07006514 return BAD_VALUE;
6515 }
Eric Laurentd4692962014-05-05 18:13:44 -07006516 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07006517 // check if one opened output is not needed any more after disconnecting one device
6518 for (size_t i = 0; i < mOutputs.size(); i++) {
6519 desc = mOutputs.valueAt(i);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006520 if (!desc->isDuplicated()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08006521 // exact match on device
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006522 if (device_distinguishes_on_address(deviceType) && desc->supportsDevice(device)
Francois Gaffiec7d4c222021-12-02 11:12:52 +01006523 && desc->containsSingleDeviceSupportingEncodedFormats(device)) {
François Gaffie11d30102018-11-02 16:09:09 +01006524 outputs.add(mOutputs.keyAt(i));
Francois Gaffie716e1432019-01-14 16:58:59 +01006525 } else if (!mAvailableOutputDevices.containsAtLeastOne(desc->supportedDevices())) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006526 ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
6527 mOutputs.keyAt(i));
6528 outputs.add(mOutputs.keyAt(i));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006529 }
Eric Laurente552edb2014-03-10 17:42:56 -07006530 }
6531 }
Eric Laurentd4692962014-05-05 18:13:44 -07006532 // Clear any profiles associated with the disconnected device.
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006533 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006534 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
6535 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
jiabinbce0c1d2020-10-05 11:20:18 -07006536 if (!profile->supportsDevice(device)) {
6537 continue;
6538 }
6539 ALOGV("checkOutputsForDevice(): "
6540 "clearing direct output profile %zu on module %s",
6541 j, hwModule->getName());
6542 profile->clearAudioProfiles();
6543 if (!profile->hasDynamicAudioProfile()) {
6544 continue;
6545 }
6546 // When a device is disconnected, if there is an IOProfile that contains dynamic
6547 // profiles and supports the disconnected device, call getAudioPort to repopulate
6548 // the capabilities of the devices that is supported by the IOProfile.
6549 for (const auto& supportedDevice : profile->getSupportedDevices()) {
6550 if (supportedDevice == device ||
6551 !mAvailableOutputDevices.contains(supportedDevice)) {
6552 continue;
6553 }
6554 struct audio_port_v7 port;
6555 supportedDevice->toAudioPort(&port);
6556 status_t status = mpClientInterface->getAudioPort(&port);
6557 if (status == NO_ERROR) {
6558 supportedDevice->importAudioPort(port);
6559 }
Eric Laurente552edb2014-03-10 17:42:56 -07006560 }
6561 }
6562 }
6563 }
6564 return NO_ERROR;
6565}
6566
François Gaffie11d30102018-11-02 16:09:09 +01006567status_t AudioPolicyManager::checkInputsForDevice(const sp<DeviceDescriptor>& device,
Eric Laurent0dd51852019-04-19 18:18:58 -07006568 audio_policy_dev_state_t state)
Eric Laurentd4692962014-05-05 18:13:44 -07006569{
Eric Laurent1f2f2232014-06-02 12:01:23 -07006570 sp<AudioInputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07006571
François Gaffie11d30102018-11-02 16:09:09 +01006572 if (audio_device_is_digital(device->type())) {
Eric Laurentcc750d32015-06-25 11:48:20 -07006573 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01006574 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07006575 }
6576
Eric Laurentd4692962014-05-05 18:13:44 -07006577 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
jiabinbf5f4262023-04-12 21:48:34 +00006578 // first call getAudioPort to get the supported attributes from the HAL
6579 struct audio_port_v7 port = {};
6580 device->toAudioPort(&port);
6581 status_t status = mpClientInterface->getAudioPort(&port);
6582 if (status == NO_ERROR) {
6583 device->importAudioPort(port);
6584 }
6585
Eric Laurent0dd51852019-04-19 18:18:58 -07006586 // look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07006587 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006588 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07006589 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006590 profile_index < hwModule->getInputProfiles().size();
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006591 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006592 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Eric Laurent275e8e92014-11-30 15:14:47 -08006593
François Gaffie11d30102018-11-02 16:09:09 +01006594 if (profile->supportsDevice(device)) {
6595 profiles.add(profile);
6596 ALOGV("checkInputsForDevice(): adding profile %zu from module %s",
6597 profile_index, hwModule->getName());
Eric Laurentd4692962014-05-05 18:13:44 -07006598 }
6599 }
6600 }
6601
Eric Laurent0dd51852019-04-19 18:18:58 -07006602 if (profiles.isEmpty()) {
6603 ALOGW("%s: No input profile available for device %s",
6604 __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07006605 return BAD_VALUE;
6606 }
6607
6608 // open inputs for matching profiles if needed. Direct inputs are also opened to
6609 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
6610 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
6611
Eric Laurent1c333e22014-05-20 10:48:17 -07006612 sp<IOProfile> profile = profiles[profile_index];
Eric Laurent3974e3b2017-12-07 17:58:43 -08006613
Eric Laurentd4692962014-05-05 18:13:44 -07006614 // nothing to do if one input is already opened for this profile
6615 size_t input_index;
6616 for (input_index = 0; input_index < mInputs.size(); input_index++) {
6617 desc = mInputs.valueAt(input_index);
6618 if (desc->mProfile == profile) {
François Gaffie11d30102018-11-02 16:09:09 +01006619 if (audio_device_is_digital(device->type())) {
jiabin4ef93452019-09-10 14:29:54 -07006620 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006621 }
Eric Laurentd4692962014-05-05 18:13:44 -07006622 break;
6623 }
6624 }
6625 if (input_index != mInputs.size()) {
6626 continue;
6627 }
6628
Eric Laurent3974e3b2017-12-07 17:58:43 -08006629 if (!profile->canOpenNewIo()) {
6630 ALOGW("Max Input number %u already opened for this profile %s",
6631 profile->maxOpenCount, profile->getTagName().c_str());
6632 continue;
6633 }
6634
Eric Laurentfe231122017-11-17 17:48:06 -08006635 desc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentcf2c0212014-07-25 16:20:43 -07006636 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
jiabinbf5f4262023-04-12 21:48:34 +00006637 status = desc->open(nullptr, device, AUDIO_SOURCE_MIC, AUDIO_INPUT_FLAG_NONE, &input);
Eric Laurentd4692962014-05-05 18:13:44 -07006638
Eric Laurentcf2c0212014-07-25 16:20:43 -07006639 if (status == NO_ERROR) {
jiabince9f20e2019-09-12 16:29:15 -07006640 const String8& address = String8(device->address().c_str());
Tomasz Wasilczykfd9ffd12023-08-14 17:56:22 +00006641 if (!address.empty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006642 char *param = audio_device_address_to_parameter(device->type(), address);
Eric Laurentcf2c0212014-07-25 16:20:43 -07006643 mpClientInterface->setParameters(input, String8(param));
6644 free(param);
Eric Laurentd4692962014-05-05 18:13:44 -07006645 }
jiabin12537fc2023-10-12 17:56:08 +00006646 updateAudioProfiles(device, input, profile);
François Gaffie112b0af2015-11-19 16:13:25 +01006647 if (!profile->hasValidAudioProfile()) {
Eric Laurentd4692962014-05-05 18:13:44 -07006648 ALOGW("checkInputsForDevice() direct input missing param");
Eric Laurentfe231122017-11-17 17:48:06 -08006649 desc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07006650 input = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07006651 }
6652
Eric Laurent0dd51852019-04-19 18:18:58 -07006653 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07006654 addInput(input, desc);
6655 }
6656 } // endif input != 0
6657
Eric Laurentcf2c0212014-07-25 16:20:43 -07006658 if (input == AUDIO_IO_HANDLE_NONE) {
Pattydd807582021-11-04 21:01:03 +08006659 ALOGW("%s could not open input for device %s", __func__,
François Gaffie11d30102018-11-02 16:09:09 +01006660 device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07006661 profiles.removeAt(profile_index);
6662 profile_index--;
6663 } else {
François Gaffie11d30102018-11-02 16:09:09 +01006664 if (audio_device_is_digital(device->type())) {
jiabin4ef93452019-09-10 14:29:54 -07006665 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006666 }
Eric Laurentd4692962014-05-05 18:13:44 -07006667 ALOGV("checkInputsForDevice(): adding input %d", input);
6668 }
6669 } // end scan profiles
6670
6671 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006672 ALOGW("%s: No input available for device %s", __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07006673 return BAD_VALUE;
6674 }
6675 } else {
6676 // Disconnect
Eric Laurentd4692962014-05-05 18:13:44 -07006677 // Clear any profiles associated with the disconnected device.
Mikhail Naganovd4120142017-12-06 15:49:22 -08006678 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07006679 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006680 profile_index < hwModule->getInputProfiles().size();
Eric Laurentd4692962014-05-05 18:13:44 -07006681 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006682 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Francois Gaffie716e1432019-01-14 16:58:59 +01006683 if (profile->supportsDevice(device)) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08006684 ALOGV("checkInputsForDevice(): clearing direct input profile %zu on module %s",
6685 profile_index, hwModule->getName());
François Gaffie112b0af2015-11-19 16:13:25 +01006686 profile->clearAudioProfiles();
Eric Laurentd4692962014-05-05 18:13:44 -07006687 }
6688 }
6689 }
6690 } // end disconnect
6691
6692 return NO_ERROR;
6693}
6694
6695
Eric Laurente0720872014-03-11 09:30:41 -07006696void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07006697{
6698 ALOGV("closeOutput(%d)", output);
6699
François Gaffie1c878552018-11-22 16:53:21 +01006700 sp<SwAudioOutputDescriptor> closingOutput = mOutputs.valueFor(output);
6701 if (closingOutput == NULL) {
Eric Laurente552edb2014-03-10 17:42:56 -07006702 ALOGW("closeOutput() unknown output %d", output);
6703 return;
6704 }
Mikhail Naganov32ebca32019-03-22 15:42:52 -07006705 const bool closingOutputWasActive = closingOutput->isActive();
jiabin24ff57a2023-11-27 21:06:51 +00006706 mPolicyMixes.closeOutput(closingOutput, mOutputs);
Eric Laurent275e8e92014-11-30 15:14:47 -08006707
Eric Laurente552edb2014-03-10 17:42:56 -07006708 // look for duplicated outputs connected to the output being removed.
6709 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie1c878552018-11-22 16:53:21 +01006710 sp<SwAudioOutputDescriptor> dupOutput = mOutputs.valueAt(i);
6711 if (dupOutput->isDuplicated() &&
6712 (dupOutput->mOutput1 == closingOutput || dupOutput->mOutput2 == closingOutput)) {
6713 sp<SwAudioOutputDescriptor> remainingOutput =
6714 dupOutput->mOutput1 == closingOutput ? dupOutput->mOutput2 : dupOutput->mOutput1;
Eric Laurente552edb2014-03-10 17:42:56 -07006715 // As all active tracks on duplicated output will be deleted,
6716 // and as they were also referenced on the other output, the reference
6717 // count for their stream type must be adjusted accordingly on
6718 // the other output.
François Gaffie1c878552018-11-22 16:53:21 +01006719 const bool wasActive = remainingOutput->isActive();
6720 // Note: no-op on the closing output where all clients has already been set inactive
6721 dupOutput->setAllClientsInactive();
Eric Laurent733ce942017-12-07 12:18:25 -08006722 // stop() will be a no op if the output is still active but is needed in case all
6723 // active streams refcounts where cleared above
6724 if (wasActive) {
François Gaffie1c878552018-11-22 16:53:21 +01006725 remainingOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08006726 }
Eric Laurente552edb2014-03-10 17:42:56 -07006727 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
6728 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
6729
6730 mpClientInterface->closeOutput(duplicatedOutput);
François Gaffie53615e22015-03-19 09:24:12 +01006731 removeOutput(duplicatedOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07006732 }
6733 }
6734
Eric Laurent05b90f82014-08-27 15:32:29 -07006735 nextAudioPortGeneration();
6736
François Gaffie1c878552018-11-22 16:53:21 +01006737 ssize_t index = mAudioPatches.indexOfKey(closingOutput->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07006738 if (index >= 0) {
6739 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006740 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
6741 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07006742 mAudioPatches.removeItemsAt(index);
6743 mpClientInterface->onAudioPatchListUpdate();
6744 }
6745
Mikhail Naganov32ebca32019-03-22 15:42:52 -07006746 if (closingOutputWasActive) {
6747 closingOutput->stop();
6748 }
François Gaffie1c878552018-11-22 16:53:21 +01006749 closingOutput->close();
jiabin14b50cc2023-12-13 19:01:52 +00006750 if ((closingOutput->getFlags().output & AUDIO_OUTPUT_FLAG_BIT_PERFECT)
6751 == AUDIO_OUTPUT_FLAG_BIT_PERFECT) {
6752 for (const auto device : closingOutput->devices()) {
6753 device->setPreferredConfig(nullptr);
6754 }
6755 }
Eric Laurente552edb2014-03-10 17:42:56 -07006756
François Gaffie53615e22015-03-19 09:24:12 +01006757 removeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07006758 mPreviousOutputs = mOutputs;
Eric Laurentb4f42a92022-01-17 17:37:31 +01006759 if (closingOutput == mSpatializerOutput) {
6760 mSpatializerOutput.clear();
6761 }
Dean Wheatley3023b382018-08-09 07:42:40 +10006762
6763 // MSD patches may have been released to support a non-MSD direct output. Reset MSD patch if
6764 // no direct outputs are open.
François Gaffie11d30102018-11-02 16:09:09 +01006765 if (!getMsdAudioOutDevices().isEmpty()) {
Dean Wheatley3023b382018-08-09 07:42:40 +10006766 bool directOutputOpen = false;
6767 for (size_t i = 0; i < mOutputs.size(); i++) {
6768 if (mOutputs[i]->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
6769 directOutputOpen = true;
6770 break;
6771 }
6772 }
6773 if (!directOutputOpen) {
Michael Chan6fb34492020-12-08 15:44:49 +11006774 ALOGV("no direct outputs open, reset MSD patches");
6775 // TODO: The MSD patches to be established here may differ to current MSD patches due to
6776 // how output devices for patching are resolved. Avoid by caching and reusing the
6777 // arguments to mEngine->getOutputDevicesForAttributes() when resolving which output
6778 // devices to patch to. This may be complicated by the fact that devices may become
6779 // unavailable.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11006780 setMsdOutputPatches();
Dean Wheatley3023b382018-08-09 07:42:40 +10006781 }
6782 }
Eric Laurent05b90f82014-08-27 15:32:29 -07006783}
6784
6785void AudioPolicyManager::closeInput(audio_io_handle_t input)
6786{
6787 ALOGV("closeInput(%d)", input);
6788
6789 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
6790 if (inputDesc == NULL) {
6791 ALOGW("closeInput() unknown input %d", input);
6792 return;
6793 }
6794
Eric Laurent6a94d692014-05-20 11:18:06 -07006795 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07006796
François Gaffie11d30102018-11-02 16:09:09 +01006797 sp<DeviceDescriptor> device = inputDesc->getDevice();
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08006798 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07006799 if (index >= 0) {
6800 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006801 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
6802 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07006803 mAudioPatches.removeItemsAt(index);
6804 mpClientInterface->onAudioPatchListUpdate();
6805 }
6806
François Gaffie6ebbce02023-07-19 13:27:53 +02006807 mEffects.putOrphanEffectsForIo(input);
Eric Laurentfe231122017-11-17 17:48:06 -08006808 inputDesc->close();
Eric Laurent05b90f82014-08-27 15:32:29 -07006809 mInputs.removeItem(input);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07006810
François Gaffie11d30102018-11-02 16:09:09 +01006811 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
6812 if (primaryInputDevices.contains(device) &&
Haynes Mathew George1d539d92018-03-16 11:40:49 -07006813 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07006814 mpClientInterface->setSoundTriggerCaptureState(false);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07006815 }
Eric Laurente552edb2014-03-10 17:42:56 -07006816}
6817
François Gaffie11d30102018-11-02 16:09:09 +01006818SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevices(
6819 const DeviceVector &devices,
6820 const SwAudioOutputCollection& openOutputs)
Eric Laurente552edb2014-03-10 17:42:56 -07006821{
6822 SortedVector<audio_io_handle_t> outputs;
6823
François Gaffie11d30102018-11-02 16:09:09 +01006824 ALOGVV("%s() devices %s", __func__, devices.toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07006825 for (size_t i = 0; i < openOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01006826 ALOGVV("output %zu isDuplicated=%d device=%s",
Eric Laurent8c7e6da2015-04-21 17:37:00 -07006827 i, openOutputs.valueAt(i)->isDuplicated(),
François Gaffie11d30102018-11-02 16:09:09 +01006828 openOutputs.valueAt(i)->supportedDevices().toString().c_str());
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006829 if (openOutputs.valueAt(i)->supportsAllDevices(devices)
jiabin9a3361e2019-10-01 09:38:30 -07006830 && openOutputs.valueAt(i)->devicesSupportEncodedFormats(devices.types())) {
François Gaffie11d30102018-11-02 16:09:09 +01006831 ALOGVV("%s() found output %d", __func__, openOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07006832 outputs.add(openOutputs.keyAt(i));
6833 }
6834 }
6835 return outputs;
6836}
6837
Mikhail Naganov37977152018-07-11 15:54:44 -07006838void AudioPolicyManager::checkForDeviceAndOutputChanges(std::function<bool()> onOutputsChecked)
6839{
6840 // checkA2dpSuspend must run before checkOutputForAllStrategies so that A2DP
6841 // output is suspended before any tracks are moved to it
6842 checkA2dpSuspend();
6843 checkOutputForAllStrategies();
Kevin Rocard153f92d2018-12-18 18:33:28 -08006844 checkSecondaryOutputs();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11006845 if (onOutputsChecked != nullptr && onOutputsChecked()) checkA2dpSuspend();
Mikhail Naganov37977152018-07-11 15:54:44 -07006846 updateDevicesAndOutputs();
Mikhail Naganov7bd9b8d2018-11-15 02:09:03 +00006847 if (mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD) != 0) {
Michael Chan6fb34492020-12-08 15:44:49 +11006848 // TODO: The MSD patches to be established here may differ to current MSD patches due to how
6849 // output devices for patching are resolved. Nevertheless, AudioTracks affected by device
6850 // configuration changes will ultimately be rerouted correctly. We can still avoid
6851 // unnecessary rerouting by caching and reusing the arguments to
6852 // mEngine->getOutputDevicesForAttributes() when resolving which output devices to patch to.
6853 // This may be complicated by the fact that devices may become unavailable.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11006854 setMsdOutputPatches();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11006855 }
Jean-Michel Trivi9a6b9ad2020-10-22 16:46:43 -07006856 // an event that changed routing likely occurred, inform upper layers
6857 mpClientInterface->onRoutingUpdated();
Mikhail Naganov37977152018-07-11 15:54:44 -07006858}
6859
François Gaffiec005e562018-11-06 15:04:49 +01006860bool AudioPolicyManager::followsSameRouting(const audio_attributes_t &lAttr,
6861 const audio_attributes_t &rAttr) const
Eric Laurente552edb2014-03-10 17:42:56 -07006862{
François Gaffiec005e562018-11-06 15:04:49 +01006863 return mEngine->getProductStrategyForAttributes(lAttr) ==
6864 mEngine->getProductStrategyForAttributes(rAttr);
6865}
6866
Francois Gaffieff1eb522020-05-06 18:37:04 +02006867void AudioPolicyManager::checkAudioSourceForAttributes(const audio_attributes_t &attr)
6868{
6869 for (size_t i = 0; i < mAudioSources.size(); i++) {
6870 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
6871 if (sourceDesc != nullptr && followsSameRouting(attr, sourceDesc->attributes())
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02006872 && sourceDesc->getPatchHandle() == AUDIO_PATCH_HANDLE_NONE
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02006873 && !isCallRxAudioSource(sourceDesc) && !sourceDesc->isInternal()) {
Francois Gaffieff1eb522020-05-06 18:37:04 +02006874 connectAudioSource(sourceDesc);
6875 }
6876 }
6877}
6878
6879void AudioPolicyManager::clearAudioSourcesForOutput(audio_io_handle_t output)
6880{
6881 for (size_t i = 0; i < mAudioSources.size(); i++) {
6882 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
6883 if (sourceDesc != nullptr && sourceDesc->swOutput().promote() != nullptr
6884 && sourceDesc->swOutput().promote()->mIoHandle == output) {
6885 disconnectAudioSource(sourceDesc);
6886 }
6887 }
6888}
6889
François Gaffiec005e562018-11-06 15:04:49 +01006890void AudioPolicyManager::checkOutputForAttributes(const audio_attributes_t &attr)
6891{
6892 auto psId = mEngine->getProductStrategyForAttributes(attr);
6893
6894 DeviceVector oldDevices = mEngine->getOutputDevicesForAttributes(attr, 0, true /*fromCache*/);
6895 DeviceVector newDevices = mEngine->getOutputDevicesForAttributes(attr, 0, false /*fromCache*/);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07006896
François Gaffie11d30102018-11-02 16:09:09 +01006897 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevices(oldDevices, mPreviousOutputs);
6898 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevices(newDevices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07006899
Eric Laurentc209fe42020-06-05 18:11:23 -07006900 uint32_t maxLatency = 0;
Oscar Azucena873d10f2023-01-12 18:34:42 -08006901 bool unneededUsePrimaryOutputFromPolicyMixes = false;
Eric Laurent56ed8842022-11-15 16:04:41 +01006902 std::vector<sp<SwAudioOutputDescriptor>> invalidatedOutputs;
Eric Laurentc209fe42020-06-05 18:11:23 -07006903 // take into account dynamic audio policies related changes: if a client is now associated
6904 // to a different policy mix than at creation time, invalidate corresponding stream
Eric Laurent56ed8842022-11-15 16:04:41 +01006905 for (size_t i = 0; i < mPreviousOutputs.size(); i++) {
Eric Laurentc209fe42020-06-05 18:11:23 -07006906 const sp<SwAudioOutputDescriptor>& desc = mPreviousOutputs.valueAt(i);
6907 if (desc->isDuplicated()) {
6908 continue;
Jean-Michel Trivife472e22014-12-16 14:23:13 -08006909 }
Eric Laurentc209fe42020-06-05 18:11:23 -07006910 for (const sp<TrackClientDescriptor>& client : desc->getClientIterable()) {
6911 if (mEngine->getProductStrategyForAttributes(client->attributes()) != psId) {
6912 continue;
6913 }
6914 sp<AudioPolicyMix> primaryMix;
Dean Wheatleyd082f472022-02-04 11:10:48 +11006915 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->config(),
Oscar Azucena873d10f2023-01-12 18:34:42 -08006916 client->uid(), client->session(), client->flags(), mAvailableOutputDevices,
6917 nullptr /* requestedDevice */, primaryMix, nullptr /* secondaryMixes */,
6918 unneededUsePrimaryOutputFromPolicyMixes);
Eric Laurentc209fe42020-06-05 18:11:23 -07006919 if (status != OK) {
6920 continue;
6921 }
yucliuf4de36d2020-09-14 14:57:56 -07006922 if (client->getPrimaryMix() != primaryMix || client->hasLostPrimaryMix()) {
Eric Laurent56ed8842022-11-15 16:04:41 +01006923 if (desc->isStrategyActive(psId) && maxLatency < desc->latency()) {
Eric Laurentc209fe42020-06-05 18:11:23 -07006924 maxLatency = desc->latency();
6925 }
Eric Laurent56ed8842022-11-15 16:04:41 +01006926 invalidatedOutputs.push_back(desc);
Eric Laurentc209fe42020-06-05 18:11:23 -07006927 }
Jean-Michel Trivife472e22014-12-16 14:23:13 -08006928 }
6929 }
6930
Eric Laurent56ed8842022-11-15 16:04:41 +01006931 if (srcOutputs != dstOutputs || !invalidatedOutputs.empty()) {
Eric Laurentac3a6902018-05-11 16:39:10 -07006932 // get maximum latency of all source outputs to determine the minimum mute time guaranteeing
6933 // audio from invalidated tracks will be rendered when unmuting
Eric Laurentac3a6902018-05-11 16:39:10 -07006934 for (audio_io_handle_t srcOut : srcOutputs) {
6935 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
Eric Laurentaa02db82019-09-05 17:31:49 -07006936 if (desc == nullptr) continue;
6937
6938 if (desc->isStrategyActive(psId) && maxLatency < desc->latency()) {
Eric Laurentac3a6902018-05-11 16:39:10 -07006939 maxLatency = desc->latency();
6940 }
Eric Laurentaa02db82019-09-05 17:31:49 -07006941
Eric Laurent56ed8842022-11-15 16:04:41 +01006942 bool invalidate = false;
Eric Laurentaa02db82019-09-05 17:31:49 -07006943 for (auto client : desc->clientsList(false /*activeOnly*/)) {
Eric Laurent78aade82019-09-13 18:55:08 -07006944 if (desc->isDuplicated() || !desc->mProfile->isDirectOutput()) {
Eric Laurentaa02db82019-09-05 17:31:49 -07006945 // a client on a non direct outputs has necessarily a linear PCM format
6946 // so we can call selectOutput() safely
6947 const audio_io_handle_t newOutput = selectOutput(dstOutputs,
6948 client->flags(),
6949 client->config().format,
6950 client->config().channel_mask,
jiabinebb6af42020-06-09 17:31:17 -07006951 client->config().sample_rate,
6952 client->session());
Eric Laurentaa02db82019-09-05 17:31:49 -07006953 if (newOutput != srcOut) {
6954 invalidate = true;
6955 break;
6956 }
6957 } else {
6958 sp<IOProfile> profile = getProfileForOutput(newDevices,
6959 client->config().sample_rate,
6960 client->config().format,
6961 client->config().channel_mask,
6962 client->flags(),
6963 true /* directOnly */);
6964 if (profile != desc->mProfile) {
6965 invalidate = true;
6966 break;
6967 }
6968 }
6969 }
Eric Laurent56ed8842022-11-15 16:04:41 +01006970 // mute strategy while moving tracks from one output to another
6971 if (invalidate) {
6972 invalidatedOutputs.push_back(desc);
6973 if (desc->isStrategyActive(psId)) {
6974 setStrategyMute(psId, true, desc);
6975 setStrategyMute(psId, false, desc, maxLatency * LATENCY_MUTE_FACTOR,
6976 newDevices.types());
6977 }
Eric Laurente552edb2014-03-10 17:42:56 -07006978 }
François Gaffiec005e562018-11-06 15:04:49 +01006979 sp<SourceClientDescriptor> source = getSourceForAttributesOnOutput(srcOut, attr);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02006980 if (source != nullptr && !isCallRxAudioSource(source) && !source->isInternal()) {
Eric Laurentd60560a2015-04-10 11:31:20 -07006981 connectAudioSource(source);
6982 }
Eric Laurente552edb2014-03-10 17:42:56 -07006983 }
6984
Eric Laurent56ed8842022-11-15 16:04:41 +01006985 ALOGV_IF(!(srcOutputs.isEmpty() || dstOutputs.isEmpty()),
6986 "%s: strategy %d, moving from output %s to output %s", __func__, psId,
6987 std::to_string(srcOutputs[0]).c_str(),
6988 std::to_string(dstOutputs[0]).c_str());
6989
François Gaffiec005e562018-11-06 15:04:49 +01006990 // Move effects associated to this stream from previous output to new output
6991 if (followsSameRouting(attr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07006992 selectOutputForMusicEffects();
Eric Laurente552edb2014-03-10 17:42:56 -07006993 }
François Gaffiec005e562018-11-06 15:04:49 +01006994 // Move tracks associated to this stream (and linked) from previous output to new output
Eric Laurent56ed8842022-11-15 16:04:41 +01006995 if (!invalidatedOutputs.empty()) {
jiabinc44b3462022-12-08 12:52:31 -08006996 invalidateStreams(mEngine->getStreamTypesForProductStrategy(psId));
Eric Laurent56ed8842022-11-15 16:04:41 +01006997 for (sp<SwAudioOutputDescriptor> desc : invalidatedOutputs) {
jiabin49256852022-03-09 11:21:35 -08006998 desc->setTracksInvalidatedStatusByStrategy(psId);
6999 }
Eric Laurente552edb2014-03-10 17:42:56 -07007000 }
7001 }
7002}
7003
Eric Laurente0720872014-03-11 09:30:41 -07007004void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07007005{
François Gaffiec005e562018-11-06 15:04:49 +01007006 for (const auto &strategy : mEngine->getOrderedProductStrategies()) {
7007 auto attributes = mEngine->getAllAttributesForProductStrategy(strategy).front();
7008 checkOutputForAttributes(attributes);
Francois Gaffieff1eb522020-05-06 18:37:04 +02007009 checkAudioSourceForAttributes(attributes);
François Gaffiec005e562018-11-06 15:04:49 +01007010 }
Eric Laurente552edb2014-03-10 17:42:56 -07007011}
7012
Kevin Rocard153f92d2018-12-18 18:33:28 -08007013void AudioPolicyManager::checkSecondaryOutputs() {
jiabinc44b3462022-12-08 12:52:31 -08007014 PortHandleVector clientsToInvalidate;
jiabin10a03f12021-05-07 23:46:28 +00007015 TrackSecondaryOutputsMap trackSecondaryOutputs;
Oscar Azucena873d10f2023-01-12 18:34:42 -08007016 bool unneededUsePrimaryOutputFromPolicyMixes = false;
Kevin Rocard153f92d2018-12-18 18:33:28 -08007017 for (size_t i = 0; i < mOutputs.size(); i++) {
7018 const sp<SwAudioOutputDescriptor>& outputDescriptor = mOutputs[i];
7019 for (const sp<TrackClientDescriptor>& client : outputDescriptor->getClientIterable()) {
Eric Laurentc529cf62020-04-17 18:19:10 -07007020 sp<AudioPolicyMix> primaryMix;
7021 std::vector<sp<AudioPolicyMix>> secondaryMixes;
Dean Wheatleyd082f472022-02-04 11:10:48 +11007022 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->config(),
Oscar Azucena873d10f2023-01-12 18:34:42 -08007023 client->uid(), client->session(), client->flags(), mAvailableOutputDevices,
7024 nullptr /* requestedDevice */, primaryMix, &secondaryMixes,
7025 unneededUsePrimaryOutputFromPolicyMixes);
Eric Laurentc529cf62020-04-17 18:19:10 -07007026 std::vector<sp<SwAudioOutputDescriptor>> secondaryDescs;
7027 for (auto &secondaryMix : secondaryMixes) {
7028 sp<SwAudioOutputDescriptor> outputDesc = secondaryMix->getOutput();
7029 if (outputDesc != nullptr &&
7030 outputDesc->mIoHandle != AUDIO_IO_HANDLE_NONE) {
7031 secondaryDescs.push_back(outputDesc);
7032 }
7033 }
7034
jiabinc44b3462022-12-08 12:52:31 -08007035 if (status != OK &&
7036 (client->flags() & AUDIO_OUTPUT_FLAG_MMAP_NOIRQ) == AUDIO_OUTPUT_FLAG_NONE) {
7037 // When it failed to query secondary output, only invalidate the client that is not
7038 // MMAP. The reason is that MMAP stream will not support secondary output.
7039 clientsToInvalidate.push_back(client->portId());
jiabin10a03f12021-05-07 23:46:28 +00007040 } else if (!std::equal(
7041 client->getSecondaryOutputs().begin(),
7042 client->getSecondaryOutputs().end(),
7043 secondaryDescs.begin(), secondaryDescs.end())) {
jiabina5281062021-11-23 00:10:23 +00007044 if (!audio_is_linear_pcm(client->config().format)) {
7045 // If the format is not PCM, the tracks should be invalidated to get correct
7046 // behavior when the secondary output is changed.
jiabinc44b3462022-12-08 12:52:31 -08007047 clientsToInvalidate.push_back(client->portId());
jiabina5281062021-11-23 00:10:23 +00007048 } else {
7049 std::vector<wp<SwAudioOutputDescriptor>> weakSecondaryDescs;
7050 std::vector<audio_io_handle_t> secondaryOutputIds;
7051 for (const auto &secondaryDesc: secondaryDescs) {
7052 secondaryOutputIds.push_back(secondaryDesc->mIoHandle);
7053 weakSecondaryDescs.push_back(secondaryDesc);
7054 }
7055 trackSecondaryOutputs.emplace(client->portId(), secondaryOutputIds);
7056 client->setSecondaryOutputs(std::move(weakSecondaryDescs));
jiabin10a03f12021-05-07 23:46:28 +00007057 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08007058 }
7059 }
7060 }
jiabin10a03f12021-05-07 23:46:28 +00007061 if (!trackSecondaryOutputs.empty()) {
7062 mpClientInterface->updateSecondaryOutputs(trackSecondaryOutputs);
7063 }
jiabinc44b3462022-12-08 12:52:31 -08007064 if (!clientsToInvalidate.empty()) {
7065 ALOGD("%s Invalidate clients due to fail getting output for attr", __func__);
7066 mpClientInterface->invalidateTracks(clientsToInvalidate);
Kevin Rocard153f92d2018-12-18 18:33:28 -08007067 }
7068}
7069
Eric Laurent2517af32020-11-25 15:31:27 +01007070bool AudioPolicyManager::isScoRequestedForComm() const {
7071 AudioDeviceTypeAddrVector devices;
7072 mEngine->getDevicesForRoleAndStrategy(mCommunnicationStrategy, DEVICE_ROLE_PREFERRED, devices);
7073 for (const auto &device : devices) {
7074 if (audio_is_bluetooth_out_sco_device(device.mType)) {
7075 return true;
7076 }
7077 }
7078 return false;
7079}
7080
Eric Laurent1a8b45f2022-04-13 16:01:47 +02007081bool AudioPolicyManager::isHearingAidUsedForComm() const {
7082 DeviceVector devices = mEngine->getOutputDevicesForStream(AUDIO_STREAM_VOICE_CALL,
7083 true /*fromCache*/);
7084 for (const auto &device : devices) {
7085 if (device->type() == AUDIO_DEVICE_OUT_HEARING_AID) {
7086 return true;
7087 }
7088 }
7089 return false;
7090}
7091
7092
Eric Laurente0720872014-03-11 09:30:41 -07007093void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07007094{
François Gaffie53615e22015-03-19 09:24:12 +01007095 audio_io_handle_t a2dpOutput = mOutputs.getA2dpOutput();
Aniket Kumar Lataa8ee9962018-01-31 20:24:23 -08007096 if (a2dpOutput == 0 || mOutputs.isA2dpOffloadedOnPrimary()) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07007097 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07007098 return;
7099 }
7100
Eric Laurent3a4311c2014-03-17 12:00:47 -07007101 bool isScoConnected =
jiabin9a3361e2019-10-01 09:38:30 -07007102 (mAvailableInputDevices.types().count(AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) != 0 ||
7103 !Intersection(mAvailableOutputDevices.types(), getAudioDeviceOutAllScoSet()).empty());
Eric Laurent2517af32020-11-25 15:31:27 +01007104 bool isScoRequested = isScoRequestedForComm();
Eric Laurentf732e072016-08-03 19:30:28 -07007105
7106 // if suspended, restore A2DP output if:
7107 // ((SCO device is NOT connected) ||
Eric Laurent2517af32020-11-25 15:31:27 +01007108 // ((SCO is not requested) &&
Eric Laurentf732e072016-08-03 19:30:28 -07007109 // (phone state is NOT in call) && (phone state is NOT ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07007110 //
Eric Laurentf732e072016-08-03 19:30:28 -07007111 // if not suspended, suspend A2DP output if:
7112 // (SCO device is connected) &&
Eric Laurent2517af32020-11-25 15:31:27 +01007113 // ((SCO is requested) ||
Eric Laurentf732e072016-08-03 19:30:28 -07007114 // ((phone state is in call) || (phone state is ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07007115 //
7116 if (mA2dpSuspended) {
Eric Laurentf732e072016-08-03 19:30:28 -07007117 if (!isScoConnected ||
Eric Laurent2517af32020-11-25 15:31:27 +01007118 (!isScoRequested &&
Eric Laurentf732e072016-08-03 19:30:28 -07007119 (mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) &&
François Gaffie2110e042015-03-24 08:41:51 +01007120 (mEngine->getPhoneState() != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07007121
7122 mpClientInterface->restoreOutput(a2dpOutput);
7123 mA2dpSuspended = false;
7124 }
7125 } else {
Eric Laurentf732e072016-08-03 19:30:28 -07007126 if (isScoConnected &&
Eric Laurent2517af32020-11-25 15:31:27 +01007127 (isScoRequested ||
Eric Laurentf732e072016-08-03 19:30:28 -07007128 (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) ||
François Gaffie2110e042015-03-24 08:41:51 +01007129 (mEngine->getPhoneState() == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07007130
7131 mpClientInterface->suspendOutput(a2dpOutput);
7132 mA2dpSuspended = true;
7133 }
7134 }
7135}
7136
François Gaffie11d30102018-11-02 16:09:09 +01007137DeviceVector AudioPolicyManager::getNewOutputDevices(const sp<SwAudioOutputDescriptor>& outputDesc,
7138 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07007139{
François Gaffiedb1755b2023-09-01 11:50:35 +02007140 if (outputDesc == nullptr) {
7141 return DeviceVector{};
7142 }
François Gaffie11d30102018-11-02 16:09:09 +01007143
Jean-Michel Triviff155c62016-02-26 12:07:16 -08007144 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007145 if (index >= 0) {
7146 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007147 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01007148 ALOGV("%s device %s forced by patch %d", __func__,
7149 outputDesc->devices().toString().c_str(), outputDesc->getPatchHandle());
7150 return outputDesc->devices();
Eric Laurent6a94d692014-05-20 11:18:06 -07007151 }
7152 }
7153
Dean Wheatley514b4312020-06-17 21:45:00 +10007154 // Do not retrieve engine device for outputs through MSD
7155 // TODO: support explicit routing requests by resetting MSD patch to engine device.
7156 if (outputDesc->devices() == getMsdAudioOutDevices()) {
7157 return outputDesc->devices();
7158 }
7159
Eric Laurent97ac8712018-07-27 18:59:02 -07007160 // Honor explicit routing requests only if no client using default routing is active on this
7161 // input: a specific app can not force routing for other apps by setting a preferred device.
7162 bool active; // unused
François Gaffie11d30102018-11-02 16:09:09 +01007163 sp<DeviceDescriptor> device =
François Gaffiec005e562018-11-06 15:04:49 +01007164 findPreferredDevice(outputDesc, PRODUCT_STRATEGY_NONE, active, mAvailableOutputDevices);
François Gaffie11d30102018-11-02 16:09:09 +01007165 if (device != nullptr) {
7166 return DeviceVector(device);
Eric Laurentf3a5a602018-05-22 18:42:55 -07007167 }
7168
François Gaffiea807ef92018-11-05 10:44:33 +01007169 // Legacy Engine cannot take care of bus devices and mix, so we need to handle the conflict
7170 // of setForceUse / Default Bus device here
7171 device = mPolicyMixes.getDeviceAndMixForOutput(outputDesc, mAvailableOutputDevices);
7172 if (device != nullptr) {
7173 return DeviceVector(device);
7174 }
7175
François Gaffiedb1755b2023-09-01 11:50:35 +02007176 DeviceVector devices;
François Gaffiec005e562018-11-06 15:04:49 +01007177 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
7178 StreamTypeVector streams = mEngine->getStreamTypesForProductStrategy(productStrategy);
7179 auto attr = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307180 auto hasStreamActive = [&](auto stream) {
7181 return hasStream(streams, stream) && isStreamActive(stream, 0);
7182 };
Eric Laurent484e9272018-06-07 17:29:23 -07007183
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307184 auto doGetOutputDevicesForVoice = [&]() {
7185 return hasVoiceStream(streams) && (outputDesc == mPrimaryOutput ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007186 outputDesc->isActive(toVolumeSource(AUDIO_STREAM_VOICE_CALL, false))) &&
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307187 (isInCall() ||
Henrik Backlund07c654a2021-10-14 15:57:10 +02007188 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc)) &&
7189 !isStreamActive(AUDIO_STREAM_ENFORCED_AUDIBLE, 0);
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307190 };
7191
7192 // With low-latency playing on speaker, music on WFD, when the first low-latency
7193 // output is stopped, getNewOutputDevices checks for a product strategy
7194 // from the list, as STRATEGY_SONIFICATION comes prior to STRATEGY_MEDIA.
Carter Hsucc58a6b2021-07-20 08:44:50 +00007195 // If an ALARM or ENFORCED_AUDIBLE stream is supported by the product strategy,
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307196 // devices are returned for STRATEGY_SONIFICATION without checking whether the
7197 // stream is associated to the output descriptor.
7198 if (doGetOutputDevicesForVoice() || outputDesc->isStrategyActive(productStrategy) ||
7199 ((hasStreamActive(AUDIO_STREAM_ALARM) ||
7200 hasStreamActive(AUDIO_STREAM_ENFORCED_AUDIBLE)) &&
7201 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc))) {
François Gaffiec005e562018-11-06 15:04:49 +01007202 // Retrieval of devices for voice DL is done on primary output profile, cannot
7203 // check the route (would force modifying configuration file for this profile)
7204 devices = mEngine->getOutputDevicesForAttributes(attr, nullptr, fromCache);
7205 break;
7206 }
Eric Laurente552edb2014-03-10 17:42:56 -07007207 }
François Gaffiec005e562018-11-06 15:04:49 +01007208 ALOGV("%s selected devices %s", __func__, devices.toString().c_str());
François Gaffie11d30102018-11-02 16:09:09 +01007209 return devices;
Eric Laurent1c333e22014-05-20 10:48:17 -07007210}
7211
François Gaffie11d30102018-11-02 16:09:09 +01007212sp<DeviceDescriptor> AudioPolicyManager::getNewInputDevice(
7213 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurent1c333e22014-05-20 10:48:17 -07007214{
François Gaffie11d30102018-11-02 16:09:09 +01007215 sp<DeviceDescriptor> device;
Eric Laurent6a94d692014-05-20 11:18:06 -07007216
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08007217 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007218 if (index >= 0) {
7219 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007220 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01007221 ALOGV("getNewInputDevice() device %s forced by patch %d",
7222 inputDesc->getDevice()->toString().c_str(), inputDesc->getPatchHandle());
7223 return inputDesc->getDevice();
Eric Laurent6a94d692014-05-20 11:18:06 -07007224 }
7225 }
7226
Eric Laurent97ac8712018-07-27 18:59:02 -07007227 // Honor explicit routing requests only if no client using default routing is active on this
7228 // input: a specific app can not force routing for other apps by setting a preferred device.
7229 bool active;
François Gaffie11d30102018-11-02 16:09:09 +01007230 device = findPreferredDevice(inputDesc, AUDIO_SOURCE_DEFAULT, active, mAvailableInputDevices);
7231 if (device != nullptr) {
7232 return device;
Eric Laurent97ac8712018-07-27 18:59:02 -07007233 }
7234
Eric Laurentdc95a252018-04-12 12:46:56 -07007235 // If we are not in call and no client is active on this input, this methods returns
Andy Hungf024a9e2019-01-30 16:01:02 -08007236 // a null sp<>, causing the patch on the input stream to be released.
yuanjiahsu0735bf32021-03-18 08:12:54 +08007237 audio_attributes_t attributes;
7238 uid_t uid;
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007239 audio_session_t session;
yuanjiahsu0735bf32021-03-18 08:12:54 +08007240 sp<RecordClientDescriptor> topClient = inputDesc->getHighestPriorityClient();
7241 if (topClient != nullptr) {
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01007242 attributes = topClient->attributes();
7243 uid = topClient->uid();
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007244 session = topClient->session();
yuanjiahsu0735bf32021-03-18 08:12:54 +08007245 } else {
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01007246 attributes = { .source = AUDIO_SOURCE_DEFAULT };
7247 uid = 0;
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007248 session = AUDIO_SESSION_NONE;
yuanjiahsu0735bf32021-03-18 08:12:54 +08007249 }
7250
Francois Gaffie716e1432019-01-14 16:58:59 +01007251 if (attributes.source == AUDIO_SOURCE_DEFAULT && isInCall()) {
7252 attributes.source = AUDIO_SOURCE_VOICE_COMMUNICATION;
Eric Laurentdc95a252018-04-12 12:46:56 -07007253 }
Francois Gaffie716e1432019-01-14 16:58:59 +01007254 if (attributes.source != AUDIO_SOURCE_DEFAULT) {
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007255 device = mEngine->getInputDeviceForAttributes(attributes, uid, session);
Eric Laurentfb66dd92016-01-28 18:32:03 -08007256 }
Eric Laurent1c333e22014-05-20 10:48:17 -07007257
Eric Laurente552edb2014-03-10 17:42:56 -07007258 return device;
7259}
7260
Eric Laurent794fde22016-03-11 09:50:45 -08007261bool AudioPolicyManager::streamsMatchForvolume(audio_stream_type_t stream1,
7262 audio_stream_type_t stream2) {
Jean-Michel Trivi99bb2f92016-11-23 15:52:07 -08007263 return (stream1 == stream2);
Eric Laurent28d09f02016-03-08 10:43:05 -08007264}
7265
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08007266status_t AudioPolicyManager::getDevicesForAttributes(
Andy Hung6d23c0f2022-02-16 09:37:15 -08007267 const audio_attributes_t &attr, AudioDeviceTypeAddrVector *devices, bool forVolume) {
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08007268 if (devices == nullptr) {
7269 return BAD_VALUE;
7270 }
Andy Hung6d23c0f2022-02-16 09:37:15 -08007271
Andy Hung6d23c0f2022-02-16 09:37:15 -08007272 DeviceVector curDevices;
jiabinf1c73972022-04-14 16:28:52 -07007273 if (status_t status = getDevicesForAttributes(attr, curDevices, forVolume); status != OK) {
7274 return status;
Andy Hung6d23c0f2022-02-16 09:37:15 -08007275 }
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08007276 for (const auto& device : curDevices) {
7277 devices->push_back(device->getDeviceTypeAddr());
7278 }
7279 return NO_ERROR;
7280}
7281
Eric Laurente0720872014-03-11 09:30:41 -07007282void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07007283 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07007284 case AUDIO_STREAM_MUSIC:
François Gaffiec005e562018-11-06 15:04:49 +01007285 checkOutputForAttributes(attributes_initializer(AUDIO_USAGE_NOTIFICATION));
Eric Laurente552edb2014-03-10 17:42:56 -07007286 updateDevicesAndOutputs();
7287 break;
7288 default:
7289 break;
7290 }
7291}
7292
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007293uint32_t AudioPolicyManager::handleEventForBeacon(int event) {
Eric Laurent9459fb02015-08-12 18:36:32 -07007294
7295 // skip beacon mute management if a dedicated TTS output is available
7296 if (mTtsOutputAvailable) {
7297 return 0;
7298 }
7299
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007300 switch(event) {
7301 case STARTING_OUTPUT:
7302 mBeaconMuteRefCount++;
7303 break;
7304 case STOPPING_OUTPUT:
7305 if (mBeaconMuteRefCount > 0) {
7306 mBeaconMuteRefCount--;
7307 }
7308 break;
7309 case STARTING_BEACON:
7310 mBeaconPlayingRefCount++;
7311 break;
7312 case STOPPING_BEACON:
7313 if (mBeaconPlayingRefCount > 0) {
7314 mBeaconPlayingRefCount--;
7315 }
7316 break;
7317 }
7318
7319 if (mBeaconMuteRefCount > 0) {
7320 // any playback causes beacon to be muted
7321 return setBeaconMute(true);
7322 } else {
7323 // no other playback: unmute when beacon starts playing, mute when it stops
7324 return setBeaconMute(mBeaconPlayingRefCount == 0);
7325 }
7326}
7327
7328uint32_t AudioPolicyManager::setBeaconMute(bool mute) {
7329 ALOGV("setBeaconMute(%d) mBeaconMuteRefCount=%d mBeaconPlayingRefCount=%d",
7330 mute, mBeaconMuteRefCount, mBeaconPlayingRefCount);
7331 // keep track of muted state to avoid repeating mute/unmute operations
7332 if (mBeaconMuted != mute) {
7333 // mute/unmute AUDIO_STREAM_TTS on all outputs
7334 ALOGV("\t muting %d", mute);
7335 uint32_t maxLatency = 0;
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007336 auto ttsVolumeSource = toVolumeSource(AUDIO_STREAM_TTS, false);
7337 if (ttsVolumeSource == VOLUME_SOURCE_NONE) {
7338 ALOGV("\t no tts volume source available");
7339 return 0;
7340 }
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007341 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07007342 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
jiabin9a3361e2019-10-01 09:38:30 -07007343 setVolumeSourceMute(ttsVolumeSource, mute/*on*/, desc, 0 /*delay*/, DeviceTypeSet());
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007344 const uint32_t latency = desc->latency() * 2;
Eric Laurentcdb2b352020-07-23 10:57:02 -07007345 if (desc->isActive(latency * 2) && latency > maxLatency) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007346 maxLatency = latency;
7347 }
7348 }
7349 mBeaconMuted = mute;
7350 return maxLatency;
7351 }
7352 return 0;
7353}
7354
Eric Laurente0720872014-03-11 09:30:41 -07007355void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07007356{
François Gaffiec005e562018-11-06 15:04:49 +01007357 mEngine->updateDeviceSelectionCache();
Eric Laurente552edb2014-03-10 17:42:56 -07007358 mPreviousOutputs = mOutputs;
7359}
7360
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07007361uint32_t AudioPolicyManager::checkDeviceMuteStrategies(const sp<AudioOutputDescriptor>& outputDesc,
François Gaffiec005e562018-11-06 15:04:49 +01007362 const DeviceVector &prevDevices,
Eric Laurente552edb2014-03-10 17:42:56 -07007363 uint32_t delayMs)
7364{
7365 // mute/unmute strategies using an incompatible device combination
7366 // if muting, wait for the audio in pcm buffer to be drained before proceeding
7367 // if unmuting, unmute only after the specified delay
7368 if (outputDesc->isDuplicated()) {
7369 return 0;
7370 }
7371
7372 uint32_t muteWaitMs = 0;
François Gaffiec005e562018-11-06 15:04:49 +01007373 DeviceVector devices = outputDesc->devices();
7374 bool shouldMute = outputDesc->isActive() && (devices.size() >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07007375
François Gaffiec005e562018-11-06 15:04:49 +01007376 auto productStrategies = mEngine->getOrderedProductStrategies();
7377 for (const auto &productStrategy : productStrategies) {
7378 auto attributes = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
7379 DeviceVector curDevices =
7380 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false/*fromCache*/);
7381 curDevices = curDevices.filter(outputDesc->supportedDevices());
7382 bool mute = shouldMute && curDevices.containsAtLeastOne(devices) && curDevices != devices;
Eric Laurente552edb2014-03-10 17:42:56 -07007383 bool doMute = false;
7384
François Gaffiec005e562018-11-06 15:04:49 +01007385 if (mute && !outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07007386 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01007387 outputDesc->setStrategyMutedByDevice(productStrategy, true);
7388 } else if (!mute && outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07007389 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01007390 outputDesc->setStrategyMutedByDevice(productStrategy, false);
Eric Laurente552edb2014-03-10 17:42:56 -07007391 }
Eric Laurent99401132014-05-07 19:48:15 -07007392 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07007393 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07007394 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07007395 // skip output if it does not share any device with current output
François Gaffie11d30102018-11-02 16:09:09 +01007396 if (!desc->supportedDevices().containsAtLeastOne(outputDesc->supportedDevices())) {
Eric Laurente552edb2014-03-10 17:42:56 -07007397 continue;
7398 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307399 ALOGVV("%s() output %s %s (curDevice %s)", __func__, desc->info().c_str(),
François Gaffiec005e562018-11-06 15:04:49 +01007400 mute ? "muting" : "unmuting", curDevices.toString().c_str());
7401 setStrategyMute(productStrategy, mute, desc, mute ? 0 : delayMs);
7402 if (desc->isStrategyActive(productStrategy)) {
Eric Laurent99401132014-05-07 19:48:15 -07007403 if (mute) {
7404 // FIXME: should not need to double latency if volume could be applied
7405 // immediately by the audioflinger mixer. We must account for the delay
7406 // between now and the next time the audioflinger thread for this output
7407 // will process a buffer (which corresponds to one buffer size,
7408 // usually 1/2 or 1/4 of the latency).
7409 if (muteWaitMs < desc->latency() * 2) {
7410 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07007411 }
7412 }
7413 }
7414 }
7415 }
7416 }
7417
Eric Laurent99401132014-05-07 19:48:15 -07007418 // temporary mute output if device selection changes to avoid volume bursts due to
7419 // different per device volumes
François Gaffiec005e562018-11-06 15:04:49 +01007420 if (outputDesc->isActive() && (devices != prevDevices)) {
Eric Laurentdc462862016-07-19 12:29:53 -07007421 uint32_t tempMuteWaitMs = outputDesc->latency() * 2;
Jasmine Chaf6074fe2021-08-17 13:44:31 +08007422
Eric Laurentdc462862016-07-19 12:29:53 -07007423 if (muteWaitMs < tempMuteWaitMs) {
7424 muteWaitMs = tempMuteWaitMs;
Eric Laurent99401132014-05-07 19:48:15 -07007425 }
Jasmine Chaf6074fe2021-08-17 13:44:31 +08007426
7427 // If recommended duration is defined, replace temporary mute duration to avoid
7428 // truncated notifications at beginning, which depends on duration of changing path in HAL.
7429 // Otherwise, temporary mute duration is conservatively set to 4 times the reported latency.
7430 uint32_t tempRecommendedMuteDuration = outputDesc->getRecommendedMuteDurationMs();
7431 uint32_t tempMuteDurationMs = tempRecommendedMuteDuration > 0 ?
7432 tempRecommendedMuteDuration : outputDesc->latency() * 4;
7433
François Gaffieaaac0fd2018-11-22 17:56:39 +01007434 for (const auto &activeVs : outputDesc->getActiveVolumeSources()) {
7435 // make sure that we do not start the temporary mute period too early in case of
7436 // delayed device change
7437 setVolumeSourceMute(activeVs, true, outputDesc, delayMs);
7438 setVolumeSourceMute(activeVs, false, outputDesc, delayMs + tempMuteDurationMs,
François Gaffiec005e562018-11-06 15:04:49 +01007439 devices.types());
Eric Laurent99401132014-05-07 19:48:15 -07007440 }
7441 }
7442
Eric Laurente552edb2014-03-10 17:42:56 -07007443 // wait for the PCM output buffers to empty before proceeding with the rest of the command
7444 if (muteWaitMs > delayMs) {
7445 muteWaitMs -= delayMs;
7446 usleep(muteWaitMs * 1000);
7447 return muteWaitMs;
7448 }
7449 return 0;
7450}
7451
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307452uint32_t AudioPolicyManager::setOutputDevices(const char *caller,
7453 const sp<SwAudioOutputDescriptor>& outputDesc,
François Gaffie11d30102018-11-02 16:09:09 +01007454 const DeviceVector &devices,
7455 bool force,
7456 int delayMs,
7457 audio_patch_handle_t *patchHandle,
Oscar Azucena6acf34b2023-04-27 16:32:09 -07007458 bool requiresMuteCheck, bool requiresVolumeCheck,
7459 bool skipMuteDelay)
Eric Laurente552edb2014-03-10 17:42:56 -07007460{
jiabin3ff8d7d2022-12-13 06:27:44 +00007461 // TODO(b/262404095): Consider if the output need to be reopened.
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307462 std::string logPrefix = std::string("caller ") + caller + outputDesc->info();
7463 ALOGV("%s %s device %s delayMs %d", __func__, logPrefix.c_str(),
7464 devices.toString().c_str(), delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07007465 uint32_t muteWaitMs;
7466
7467 if (outputDesc->isDuplicated()) {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307468 muteWaitMs = setOutputDevices(__func__, outputDesc->subOutput1(), devices, force, delayMs,
Oscar Azucena6acf34b2023-04-27 16:32:09 -07007469 nullptr /* patchHandle */, requiresMuteCheck, skipMuteDelay);
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307470 muteWaitMs += setOutputDevices(__func__, outputDesc->subOutput2(), devices, force, delayMs,
Oscar Azucena6acf34b2023-04-27 16:32:09 -07007471 nullptr /* patchHandle */, requiresMuteCheck, skipMuteDelay);
Eric Laurente552edb2014-03-10 17:42:56 -07007472 return muteWaitMs;
7473 }
Eric Laurente552edb2014-03-10 17:42:56 -07007474
7475 // filter devices according to output selected
Francois Gaffie716e1432019-01-14 16:58:59 +01007476 DeviceVector filteredDevices = outputDesc->filterSupportedDevices(devices);
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01007477 DeviceVector prevDevices = outputDesc->devices();
Francois Gaffie3523ab32021-06-22 13:24:34 +02007478 DeviceVector availPrevDevices = mAvailableOutputDevices.filter(prevDevices);
Eric Laurente552edb2014-03-10 17:42:56 -07007479
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307480 ALOGV("%s %s prevDevice %s", __func__, logPrefix.c_str(),
7481 prevDevices.toString().c_str());
François Gaffie11d30102018-11-02 16:09:09 +01007482
7483 if (!filteredDevices.isEmpty()) {
7484 outputDesc->setDevices(filteredDevices);
Eric Laurente552edb2014-03-10 17:42:56 -07007485 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00007486
7487 // if the outputs are not materially active, there is no need to mute.
7488 if (requiresMuteCheck) {
François Gaffiec005e562018-11-06 15:04:49 +01007489 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevices, delayMs);
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00007490 } else {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307491 ALOGV("%s: %s suppressing checkDeviceMuteStrategies", __func__,
7492 logPrefix.c_str());
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00007493 muteWaitMs = 0;
7494 }
Eric Laurente552edb2014-03-10 17:42:56 -07007495
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02007496 bool outputRouted = outputDesc->isRouted();
7497
Eric Laurent79ea9582020-06-11 18:49:24 -07007498 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
7499 // output profile or if new device is not supported AND previous device(s) is(are) still
7500 // available (otherwise reset device must be done on the output)
Francois Gaffie3523ab32021-06-22 13:24:34 +02007501 if (!devices.isEmpty() && filteredDevices.isEmpty() && !availPrevDevices.empty()) {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307502 ALOGV("%s: %s unsupported device %s for output", __func__, logPrefix.c_str(),
7503 devices.toString().c_str());
Eric Laurent79ea9582020-06-11 18:49:24 -07007504 // restore previous device after evaluating strategy mute state
7505 outputDesc->setDevices(prevDevices);
7506 return muteWaitMs;
7507 }
7508
Eric Laurente552edb2014-03-10 17:42:56 -07007509 // Do not change the routing if:
Eric Laurentb80a2a82014-10-27 16:07:59 -07007510 // the requested device is AUDIO_DEVICE_NONE
7511 // OR the requested device is the same as current device
7512 // AND force is not specified
7513 // AND the output is connected by a valid audio patch.
François Gaffie11d30102018-11-02 16:09:09 +01007514 // Doing this check here allows the caller to call setOutputDevices() without conditions
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02007515 if ((filteredDevices.isEmpty() || filteredDevices == prevDevices) && !force && outputRouted) {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307516 ALOGV("%s %s setting same device %s or null device, force=%d, patch handle=%d",
7517 __func__, logPrefix.c_str(), filteredDevices.toString().c_str(), force,
7518 outputDesc->getPatchHandle());
Francois Gaffie3523ab32021-06-22 13:24:34 +02007519 if (requiresVolumeCheck && !filteredDevices.isEmpty()) {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307520 ALOGV("%s %s setting same device on routed output, force apply volumes",
7521 __func__, logPrefix.c_str());
Francois Gaffie3523ab32021-06-22 13:24:34 +02007522 applyStreamVolumes(outputDesc, filteredDevices.types(), delayMs, true /*force*/);
7523 }
Eric Laurente552edb2014-03-10 17:42:56 -07007524 return muteWaitMs;
7525 }
7526
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307527 ALOGV("%s %s changing device to %s", __func__, logPrefix.c_str(),
7528 filteredDevices.toString().c_str());
Eric Laurent1c333e22014-05-20 10:48:17 -07007529
Eric Laurente552edb2014-03-10 17:42:56 -07007530 // do the routing
Francois Gaffie3523ab32021-06-22 13:24:34 +02007531 if (filteredDevices.isEmpty() || mAvailableOutputDevices.filter(filteredDevices).empty()) {
Eric Laurentc75307b2015-03-17 15:29:32 -07007532 resetOutputDevice(outputDesc, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07007533 } else {
François Gaffie11d30102018-11-02 16:09:09 +01007534 PatchBuilder patchBuilder;
7535 patchBuilder.addSource(outputDesc);
7536 ALOG_ASSERT(filteredDevices.size() <= AUDIO_PATCH_PORTS_MAX, "Too many sink ports");
7537 for (const auto &filteredDevice : filteredDevices) {
7538 patchBuilder.addSink(filteredDevice);
Eric Laurentc40d9692016-04-13 19:14:13 -07007539 }
7540
Jasmine Cha7f82d1a2020-03-16 13:21:47 +08007541 // Add half reported latency to delayMs when muteWaitMs is null in order
7542 // to avoid disordered sequence of muting volume and changing devices.
Oscar Azucena6acf34b2023-04-27 16:32:09 -07007543 int actualDelayMs = !skipMuteDelay && muteWaitMs == 0
7544 ? (delayMs + (outputDesc->latency() / 2)) : delayMs;
7545 installPatch(__func__, patchHandle, outputDesc.get(), patchBuilder.patch(), actualDelayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07007546 }
Eric Laurente552edb2014-03-10 17:42:56 -07007547
Oscar Azucena6acf34b2023-04-27 16:32:09 -07007548 // Since the mute is skip, also skip the apply stream volume as that will be applied externally
7549 if (!skipMuteDelay) {
7550 // update stream volumes according to new device
7551 applyStreamVolumes(outputDesc, filteredDevices.types(), delayMs);
7552 }
Eric Laurente552edb2014-03-10 17:42:56 -07007553
7554 return muteWaitMs;
7555}
7556
Eric Laurentc75307b2015-03-17 15:29:32 -07007557status_t AudioPolicyManager::resetOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurent6a94d692014-05-20 11:18:06 -07007558 int delayMs,
7559 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07007560{
Eric Laurent6a94d692014-05-20 11:18:06 -07007561 ssize_t index;
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02007562 if (patchHandle == nullptr && !outputDesc->isRouted()) {
7563 return INVALID_OPERATION;
7564 }
Eric Laurent6a94d692014-05-20 11:18:06 -07007565 if (patchHandle) {
7566 index = mAudioPatches.indexOfKey(*patchHandle);
7567 } else {
Jean-Michel Triviff155c62016-02-26 12:07:16 -08007568 index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007569 }
7570 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07007571 return INVALID_OPERATION;
7572 }
Eric Laurent6a94d692014-05-20 11:18:06 -07007573 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007574 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07007575 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07007576 outputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
François Gaffieafd4cea2019-11-18 15:50:22 +01007577 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007578 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07007579 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07007580 return status;
7581}
7582
7583status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
François Gaffie11d30102018-11-02 16:09:09 +01007584 const sp<DeviceDescriptor> &device,
Eric Laurent6a94d692014-05-20 11:18:06 -07007585 bool force,
7586 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07007587{
7588 status_t status = NO_ERROR;
7589
Eric Laurent1f2f2232014-06-02 12:01:23 -07007590 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
François Gaffie11d30102018-11-02 16:09:09 +01007591 if ((device != nullptr) && ((device != inputDesc->getDevice()) || force)) {
7592 inputDesc->setDevice(device);
Eric Laurent1c333e22014-05-20 10:48:17 -07007593
François Gaffie11d30102018-11-02 16:09:09 +01007594 if (mAvailableInputDevices.contains(device)) {
Mikhail Naganovdc769682018-05-04 15:34:08 -07007595 PatchBuilder patchBuilder;
7596 patchBuilder.addSink(inputDesc,
Eric Laurentdaf92cc2014-07-22 15:36:10 -07007597 // AUDIO_SOURCE_HOTWORD is for internal use only:
7598 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
Mikhail Naganovdc769682018-05-04 15:34:08 -07007599 [inputDesc](const PatchBuilder::mix_usecase_t& usecase) {
7600 auto result = usecase;
7601 if (result.source == AUDIO_SOURCE_HOTWORD && !inputDesc->isSoundTrigger()) {
7602 result.source = AUDIO_SOURCE_VOICE_RECOGNITION;
7603 }
7604 return result; }).
Eric Laurent1c333e22014-05-20 10:48:17 -07007605 //only one input device for now
François Gaffie11d30102018-11-02 16:09:09 +01007606 addSource(device);
Mikhail Naganovdc769682018-05-04 15:34:08 -07007607 status = installPatch(__func__, patchHandle, inputDesc.get(), patchBuilder.patch(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07007608 }
7609 }
7610 return status;
7611}
7612
Eric Laurent6a94d692014-05-20 11:18:06 -07007613status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
7614 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07007615{
Eric Laurent1f2f2232014-06-02 12:01:23 -07007616 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07007617 ssize_t index;
7618 if (patchHandle) {
7619 index = mAudioPatches.indexOfKey(*patchHandle);
7620 } else {
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08007621 index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007622 }
7623 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07007624 return INVALID_OPERATION;
7625 }
Eric Laurent6a94d692014-05-20 11:18:06 -07007626 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007627 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07007628 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07007629 inputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
François Gaffieafd4cea2019-11-18 15:50:22 +01007630 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007631 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07007632 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07007633 return status;
7634}
7635
François Gaffie11d30102018-11-02 16:09:09 +01007636sp<IOProfile> AudioPolicyManager::getInputProfile(const sp<DeviceDescriptor> &device,
François Gaffie53615e22015-03-19 09:24:12 +01007637 uint32_t& samplingRate,
Andy Hungf129b032015-04-07 13:45:50 -07007638 audio_format_t& format,
7639 audio_channel_mask_t& channelMask,
François Gaffie53615e22015-03-19 09:24:12 +01007640 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07007641{
7642 // Choose an input profile based on the requested capture parameters: select the first available
7643 // profile supporting all requested parameters.
jiabin2fd710d2022-05-02 23:20:22 +00007644 // The flags can be ignored if it doesn't contain a much match flag.
Andy Hungf129b032015-04-07 13:45:50 -07007645 //
7646 // TODO: perhaps isCompatibleProfile should return a "matching" score so we can return
7647 // the best matching profile, not the first one.
Eric Laurente552edb2014-03-10 17:42:56 -07007648
Atneya Nair0f0a8032022-12-12 16:20:12 -08007649 using underlying_input_flag_t = std::underlying_type_t<audio_input_flags_t>;
7650 const underlying_input_flag_t mustMatchFlag = AUDIO_INPUT_FLAG_MMAP_NOIRQ |
7651 AUDIO_INPUT_FLAG_HOTWORD_TAP | AUDIO_INPUT_FLAG_HW_LOOKBACK;
7652
7653 const underlying_input_flag_t oriFlags = flags;
Glenn Kasten730b9262018-03-29 15:01:26 -07007654
jiabin2fd710d2022-05-02 23:20:22 +00007655 for (;;) {
7656 sp<IOProfile> firstInexact = nullptr;
7657 uint32_t updatedSamplingRate = 0;
7658 audio_format_t updatedFormat = AUDIO_FORMAT_INVALID;
7659 audio_channel_mask_t updatedChannelMask = AUDIO_CHANNEL_INVALID;
7660 for (const auto& hwModule : mHwModules) {
7661 for (const auto& profile : hwModule->getInputProfiles()) {
7662 // profile->log();
7663 //updatedFormat = format;
7664 if (profile->isCompatibleProfile(DeviceVector(device), samplingRate,
7665 &samplingRate /*updatedSamplingRate*/,
7666 format,
7667 &format, /*updatedFormat*/
7668 channelMask,
7669 &channelMask /*updatedChannelMask*/,
7670 // FIXME ugly cast
7671 (audio_output_flags_t) flags,
7672 true /*exactMatchRequiredForInputFlags*/)) {
7673 return profile;
7674 }
7675 if (firstInexact == nullptr && profile->isCompatibleProfile(DeviceVector(device),
7676 samplingRate,
7677 &updatedSamplingRate,
7678 format,
7679 &updatedFormat,
7680 channelMask,
7681 &updatedChannelMask,
7682 // FIXME ugly cast
7683 (audio_output_flags_t) flags,
7684 false /*exactMatchRequiredForInputFlags*/)) {
7685 firstInexact = profile;
7686 }
7687 }
7688 }
7689
7690 if (firstInexact != nullptr) {
7691 samplingRate = updatedSamplingRate;
7692 format = updatedFormat;
7693 channelMask = updatedChannelMask;
7694 return firstInexact;
7695 } else if (flags & AUDIO_INPUT_FLAG_RAW) {
7696 flags = (audio_input_flags_t) (flags & ~AUDIO_INPUT_FLAG_RAW); // retry
7697 } else if ((flags & mustMatchFlag) == AUDIO_INPUT_FLAG_NONE &&
7698 flags != AUDIO_INPUT_FLAG_NONE && audio_is_linear_pcm(format)) {
7699 flags = AUDIO_INPUT_FLAG_NONE;
7700 } else { // fail
7701 ALOGW("%s could not find profile for device %s, sampling rate %u, format %#x, "
7702 "channel mask 0x%X, flags %#x", __func__, device->toString().c_str(),
7703 samplingRate, format, channelMask, oriFlags);
7704 break;
Eric Laurente552edb2014-03-10 17:42:56 -07007705 }
7706 }
jiabin2fd710d2022-05-02 23:20:22 +00007707
7708 return nullptr;
Eric Laurente552edb2014-03-10 17:42:56 -07007709}
7710
François Gaffieaaac0fd2018-11-22 17:56:39 +01007711float AudioPolicyManager::computeVolume(IVolumeCurves &curves,
7712 VolumeSource volumeSource,
François Gaffied1ab2bd2015-12-02 18:20:06 +01007713 int index,
jiabin9a3361e2019-10-01 09:38:30 -07007714 const DeviceTypeSet& deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07007715{
jiabin9a3361e2019-10-01 09:38:30 -07007716 float volumeDb = curves.volIndexToDb(Volume::getDeviceCategory(deviceTypes), index);
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07007717
7718 // handle the case of accessibility active while a ringtone is playing: if the ringtone is much
7719 // louder than the accessibility prompt, the prompt cannot be heard, thus masking the touch
7720 // exploration of the dialer UI. In this situation, bring the accessibility volume closer to
7721 // the ringtone volume
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007722 const auto callVolumeSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL, false);
7723 const auto ringVolumeSrc = toVolumeSource(AUDIO_STREAM_RING, false);
7724 const auto musicVolumeSrc = toVolumeSource(AUDIO_STREAM_MUSIC, false);
7725 const auto alarmVolumeSrc = toVolumeSource(AUDIO_STREAM_ALARM, false);
7726 const auto a11yVolumeSrc = toVolumeSource(AUDIO_STREAM_ACCESSIBILITY, false);
Oscar Azucena437ded52023-08-30 18:45:18 -07007727 // Verify that the current volume source is not the ringer volume to prevent recursively
7728 // calling to compute volume. This could happen in cases where a11y and ringer sounds belong
7729 // to the same volume group.
7730 if (volumeSource != ringVolumeSrc && volumeSource == a11yVolumeSrc
François Gaffieaaac0fd2018-11-22 17:56:39 +01007731 && (AUDIO_MODE_RINGTONE == mEngine->getPhoneState()) &&
7732 mOutputs.isActive(ringVolumeSrc, 0)) {
7733 auto &ringCurves = getVolumeCurves(AUDIO_STREAM_RING);
jiabin9a3361e2019-10-01 09:38:30 -07007734 const float ringVolumeDb = computeVolume(ringCurves, ringVolumeSrc, index, deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007735 return ringVolumeDb - 4 > volumeDb ? ringVolumeDb - 4 : volumeDb;
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07007736 }
7737
Eric Laurentdcd4ab12018-06-29 17:45:13 -07007738 // in-call: always cap volume by voice volume + some low headroom
François Gaffieaaac0fd2018-11-22 17:56:39 +01007739 if ((volumeSource != callVolumeSrc && (isInCall() ||
7740 mOutputs.isActiveLocally(callVolumeSrc))) &&
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007741 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM, false) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01007742 volumeSource == ringVolumeSrc || volumeSource == musicVolumeSrc ||
7743 volumeSource == alarmVolumeSrc ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007744 volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION, false) ||
7745 volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false) ||
7746 volumeSource == toVolumeSource(AUDIO_STREAM_DTMF, false) ||
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07007747 volumeSource == a11yVolumeSrc)) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007748 auto &voiceCurves = getVolumeCurves(callVolumeSrc);
jiabin9a3361e2019-10-01 09:38:30 -07007749 int voiceVolumeIndex = voiceCurves.getVolumeIndex(deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007750 const float maxVoiceVolDb =
jiabin9a3361e2019-10-01 09:38:30 -07007751 computeVolume(voiceCurves, callVolumeSrc, voiceVolumeIndex, deviceTypes)
Eric Laurent7731b5a2018-04-06 15:47:22 -07007752 + IN_CALL_EARPIECE_HEADROOM_DB;
Abhijith Shastry329ddab2019-04-23 11:53:26 -07007753 // FIXME: Workaround for call screening applications until a proper audio mode is defined
7754 // to support this scenario : Exempt the RING stream from the audio cap if the audio was
7755 // programmatically muted.
7756 // VOICE_CALL stream has minVolumeIndex > 0 : Users cannot set the volume of voice calls to
7757 // 0. We don't want to cap volume when the system has programmatically muted the voice call
7758 // stream. See setVolumeCurveIndex() for more information.
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07007759 bool exemptFromCapping =
7760 ((volumeSource == ringVolumeSrc) || (volumeSource == a11yVolumeSrc))
7761 && (voiceVolumeIndex == 0);
Abhijith Shastry329ddab2019-04-23 11:53:26 -07007762 ALOGV_IF(exemptFromCapping, "%s volume source %d at vol=%f not capped", __func__,
7763 volumeSource, volumeDb);
7764 if ((volumeDb > maxVoiceVolDb) && !exemptFromCapping) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007765 ALOGV("%s volume source %d at vol=%f overriden by volume group %d at vol=%f", __func__,
7766 volumeSource, volumeDb, callVolumeSrc, maxVoiceVolDb);
7767 volumeDb = maxVoiceVolDb;
Jean-Michel Trivi719a9872017-08-05 13:51:35 -07007768 }
7769 }
Eric Laurente552edb2014-03-10 17:42:56 -07007770 // if a headset is connected, apply the following rules to ring tones and notifications
7771 // to avoid sound level bursts in user's ears:
Eric Laurent6af1c1d2016-04-14 11:20:44 -07007772 // - always attenuate notifications volume by 6dB
7773 // - attenuate ring tones volume by 6dB unless music is not playing and
7774 // speaker is part of the select devices
Eric Laurente552edb2014-03-10 17:42:56 -07007775 // - if music is playing, always limit the volume to current music volume,
7776 // with a minimum threshold at -36dB so that notification is always perceived.
jiabin9a3361e2019-10-01 09:38:30 -07007777 if (!Intersection(deviceTypes,
7778 {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP, AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES,
7779 AUDIO_DEVICE_OUT_WIRED_HEADSET, AUDIO_DEVICE_OUT_WIRED_HEADPHONE,
Eric Laurentc42df452020-08-07 10:51:53 -07007780 AUDIO_DEVICE_OUT_USB_HEADSET, AUDIO_DEVICE_OUT_HEARING_AID,
7781 AUDIO_DEVICE_OUT_BLE_HEADSET}).empty() &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01007782 ((volumeSource == alarmVolumeSrc ||
7783 volumeSource == ringVolumeSrc) ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007784 (volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION, false)) ||
7785 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM, false)) ||
7786 ((volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false)) &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01007787 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) &&
7788 curves.canBeMuted()) {
7789
Eric Laurente552edb2014-03-10 17:42:56 -07007790 // when the phone is ringing we must consider that music could have been paused just before
7791 // by the music application and behave as if music was active if the last music track was
7792 // just stopped
Oscar Azucena437ded52023-08-30 18:45:18 -07007793 // Verify that the current volume source is not the music volume to prevent recursively
7794 // calling to compute volume. This could happen in cases where music and
7795 // (alarm, ring, notification, system, etc.) sounds belong to the same volume group.
7796 if (volumeSource != musicVolumeSrc &&
7797 (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY)
7798 || mLimitRingtoneVolume)) {
François Gaffie43c73442018-11-08 08:21:55 +01007799 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
jiabin9a3361e2019-10-01 09:38:30 -07007800 DeviceTypeSet musicDevice =
François Gaffiec005e562018-11-06 15:04:49 +01007801 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
7802 nullptr, true /*fromCache*/).types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01007803 auto &musicCurves = getVolumeCurves(AUDIO_STREAM_MUSIC);
jiabin9a3361e2019-10-01 09:38:30 -07007804 float musicVolDb = computeVolume(musicCurves,
7805 musicVolumeSrc,
7806 musicCurves.getVolumeIndex(musicDevice),
7807 musicDevice);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007808 float minVolDb = (musicVolDb > SONIFICATION_HEADSET_VOLUME_MIN_DB) ?
7809 musicVolDb : SONIFICATION_HEADSET_VOLUME_MIN_DB;
7810 if (volumeDb > minVolDb) {
7811 volumeDb = minVolDb;
7812 ALOGV("computeVolume limiting volume to %f musicVol %f", minVolDb, musicVolDb);
Eric Laurente552edb2014-03-10 17:42:56 -07007813 }
Eric Laurent7b6385c2021-05-12 17:55:36 +02007814 if (Volume::getDeviceForVolume(deviceTypes) != AUDIO_DEVICE_OUT_SPEAKER
7815 && !Intersection(deviceTypes, {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP,
7816 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES}).empty()) {
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07007817 // on A2DP, also ensure notification volume is not too low compared to media when
7818 // intended to be played
François Gaffie43c73442018-11-08 08:21:55 +01007819 if ((volumeDb > -96.0f) &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01007820 (musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB > volumeDb)) {
jiabin9a3361e2019-10-01 09:38:30 -07007821 ALOGV("%s increasing volume for volume source=%d device=%s from %f to %f",
7822 __func__, volumeSource, dumpDeviceTypes(deviceTypes).c_str(), volumeDb,
François Gaffieaaac0fd2018-11-22 17:56:39 +01007823 musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB);
7824 volumeDb = musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB;
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07007825 }
7826 }
jiabin9a3361e2019-10-01 09:38:30 -07007827 } else if ((Volume::getDeviceForVolume(deviceTypes) != AUDIO_DEVICE_OUT_SPEAKER) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01007828 (!(volumeSource == alarmVolumeSrc || volumeSource == ringVolumeSrc))) {
François Gaffie43c73442018-11-08 08:21:55 +01007829 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07007830 }
7831 }
7832
François Gaffie43c73442018-11-08 08:21:55 +01007833 return volumeDb;
Eric Laurente552edb2014-03-10 17:42:56 -07007834}
7835
Eric Laurent3839bc02018-07-10 18:33:34 -07007836int AudioPolicyManager::rescaleVolumeIndex(int srcIndex,
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01007837 VolumeSource fromVolumeSource,
7838 VolumeSource toVolumeSource)
Eric Laurent3839bc02018-07-10 18:33:34 -07007839{
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01007840 if (fromVolumeSource == toVolumeSource) {
Eric Laurent3839bc02018-07-10 18:33:34 -07007841 return srcIndex;
7842 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01007843 auto &srcCurves = getVolumeCurves(fromVolumeSource);
7844 auto &dstCurves = getVolumeCurves(toVolumeSource);
Eric Laurentf5aa58d2019-02-22 18:20:11 -08007845 float minSrc = (float)srcCurves.getVolumeIndexMin();
7846 float maxSrc = (float)srcCurves.getVolumeIndexMax();
7847 float minDst = (float)dstCurves.getVolumeIndexMin();
7848 float maxDst = (float)dstCurves.getVolumeIndexMax();
Eric Laurent3839bc02018-07-10 18:33:34 -07007849
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08007850 // preserve mute request or correct range
7851 if (srcIndex < minSrc) {
7852 if (srcIndex == 0) {
7853 return 0;
7854 }
7855 srcIndex = minSrc;
7856 } else if (srcIndex > maxSrc) {
7857 srcIndex = maxSrc;
7858 }
Eric Laurent3839bc02018-07-10 18:33:34 -07007859 return (int)(minDst + ((srcIndex - minSrc) * (maxDst - minDst)) / (maxSrc - minSrc));
7860}
7861
François Gaffieaaac0fd2018-11-22 17:56:39 +01007862status_t AudioPolicyManager::checkAndSetVolume(IVolumeCurves &curves,
7863 VolumeSource volumeSource,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08007864 int index,
7865 const sp<AudioOutputDescriptor>& outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07007866 DeviceTypeSet deviceTypes,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08007867 int delayMs,
7868 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07007869{
François Gaffieaaac0fd2018-11-22 17:56:39 +01007870 // do not change actual attributes volume if the attributes is muted
7871 if (outputDesc->isMuted(volumeSource)) {
7872 ALOGVV("%s: volume source %d muted count %d active=%d", __func__, volumeSource,
7873 outputDesc->getMuteCount(volumeSource), outputDesc->isActive(volumeSource));
Eric Laurente552edb2014-03-10 17:42:56 -07007874 return NO_ERROR;
7875 }
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007876 VolumeSource callVolSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL, false);
7877 VolumeSource btScoVolSrc = toVolumeSource(AUDIO_STREAM_BLUETOOTH_SCO, false);
7878 bool isVoiceVolSrc = (volumeSource != VOLUME_SOURCE_NONE) && (callVolSrc == volumeSource);
7879 bool isBtScoVolSrc = (volumeSource != VOLUME_SOURCE_NONE) && (btScoVolSrc == volumeSource);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007880
Eric Laurent2517af32020-11-25 15:31:27 +01007881 bool isScoRequested = isScoRequestedForComm();
Eric Laurent1a8b45f2022-04-13 16:01:47 +02007882 bool isHAUsed = isHearingAidUsedForComm();
7883
Eric Laurente552edb2014-03-10 17:42:56 -07007884 // do not change in call volume if bluetooth is connected and vice versa
François Gaffieaaac0fd2018-11-22 17:56:39 +01007885 // if sco and call follow same curves, bypass forceUseForComm
7886 if ((callVolSrc != btScoVolSrc) &&
Eric Laurent2517af32020-11-25 15:31:27 +01007887 ((isVoiceVolSrc && isScoRequested) ||
Beibeif660a512023-02-28 17:00:34 +08007888 (isBtScoVolSrc && !(isScoRequested || isHAUsed))) &&
7889 !isSingleDeviceType(deviceTypes, AUDIO_DEVICE_OUT_TELEPHONY_TX)) {
Eric Laurent2517af32020-11-25 15:31:27 +01007890 ALOGV("%s cannot set volume group %d volume when is%srequested for comm", __func__,
Eric Laurent1a8b45f2022-04-13 16:01:47 +02007891 volumeSource, isScoRequested ? " " : " not ");
Eric Laurent571ef962020-07-24 11:43:48 -07007892 // Do not return an error here as AudioService will always set both voice call
7893 // and bluetooth SCO volumes due to stream aliasing.
7894 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07007895 }
jiabin9a3361e2019-10-01 09:38:30 -07007896 if (deviceTypes.empty()) {
7897 deviceTypes = outputDesc->devices().types();
chenxin2080986da2023-07-17 11:45:21 +08007898 index = curves.getVolumeIndex(deviceTypes);
7899 ALOGD("%s if deviceTypes is change from none to device %s, need get index %d",
7900 __func__, dumpDeviceTypes(deviceTypes).c_str(), index);
Eric Laurentc75307b2015-03-17 15:29:32 -07007901 }
Eric Laurent275e8e92014-11-30 15:14:47 -08007902
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00007903 if (curves.getVolumeIndexMin() < 0 || curves.getVolumeIndexMax() < 0) {
7904 ALOGE("invalid volume index range");
7905 return BAD_VALUE;
7906 }
7907
jiabin9a3361e2019-10-01 09:38:30 -07007908 float volumeDb = computeVolume(curves, volumeSource, index, deviceTypes);
7909 if (outputDesc->isFixedVolume(deviceTypes) ||
Eric Laurent9698a4c2020-10-12 17:10:23 -07007910 // Force VoIP volume to max for bluetooth SCO device except if muted
7911 (index != 0 && (isVoiceVolSrc || isBtScoVolSrc) &&
jiabin9a3361e2019-10-01 09:38:30 -07007912 isSingleDeviceType(deviceTypes, audio_is_bluetooth_out_sco_device))) {
Eric Laurentffbc80f2015-03-18 18:30:19 -07007913 volumeDb = 0.0f;
Eric Laurent275e8e92014-11-30 15:14:47 -08007914 }
Francois Gaffie593634d2021-06-22 13:31:31 +02007915 const bool muted = (index == 0) && (volumeDb != 0.0f);
Eric Laurent31a428a2023-08-11 12:16:28 +02007916 outputDesc->setVolume(volumeDb, muted, volumeSource, curves.getStreamTypes(),
7917 deviceTypes, delayMs, force, isVoiceVolSrc);
Eric Laurentc75307b2015-03-17 15:29:32 -07007918
Eric Laurente8f2c0f2021-08-17 11:17:19 +02007919 if (outputDesc == mPrimaryOutput && (isVoiceVolSrc || isBtScoVolSrc)) {
Eric Laurente552edb2014-03-10 17:42:56 -07007920 float voiceVolume;
Eric Laurentfad001d2019-06-11 19:17:57 -07007921 // 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 +01007922 if (isVoiceVolSrc) {
7923 voiceVolume = (float)index/(float)curves.getVolumeIndexMax();
Eric Laurente552edb2014-03-10 17:42:56 -07007924 } else {
Eric Laurentfad001d2019-06-11 19:17:57 -07007925 voiceVolume = index == 0 ? 0.0 : 1.0;
Eric Laurente552edb2014-03-10 17:42:56 -07007926 }
Eric Laurent18fba842016-03-31 14:41:26 -07007927 if (voiceVolume != mLastVoiceVolume) {
Eric Laurente552edb2014-03-10 17:42:56 -07007928 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
7929 mLastVoiceVolume = voiceVolume;
7930 }
7931 }
Eric Laurente552edb2014-03-10 17:42:56 -07007932 return NO_ERROR;
7933}
7934
Eric Laurentc75307b2015-03-17 15:29:32 -07007935void AudioPolicyManager::applyStreamVolumes(const sp<AudioOutputDescriptor>& outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07007936 const DeviceTypeSet& deviceTypes,
7937 int delayMs,
7938 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07007939{
jiabincd510522020-01-22 09:40:55 -08007940 ALOGVV("applyStreamVolumes() for device %s", dumpDeviceTypes(deviceTypes).c_str());
François Gaffieaaac0fd2018-11-22 17:56:39 +01007941 for (const auto &volumeGroup : mEngine->getVolumeGroups()) {
7942 auto &curves = getVolumeCurves(toVolumeSource(volumeGroup));
7943 checkAndSetVolume(curves, toVolumeSource(volumeGroup),
jiabin9a3361e2019-10-01 09:38:30 -07007944 curves.getVolumeIndex(deviceTypes),
7945 outputDesc, deviceTypes, delayMs, force);
Eric Laurente552edb2014-03-10 17:42:56 -07007946 }
7947}
7948
François Gaffiec005e562018-11-06 15:04:49 +01007949void AudioPolicyManager::setStrategyMute(product_strategy_t strategy,
7950 bool on,
7951 const sp<AudioOutputDescriptor>& outputDesc,
7952 int delayMs,
jiabin9a3361e2019-10-01 09:38:30 -07007953 DeviceTypeSet deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07007954{
François Gaffieaaac0fd2018-11-22 17:56:39 +01007955 std::vector<VolumeSource> sourcesToMute;
7956 for (auto attributes: mEngine->getAllAttributesForProductStrategy(strategy)) {
7957 ALOGVV("%s() attributes %s, mute %d, output ID %d", __func__,
7958 toString(attributes).c_str(), on, outputDesc->getId());
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007959 VolumeSource source = toVolumeSource(attributes, false);
7960 if ((source != VOLUME_SOURCE_NONE) &&
7961 (std::find(begin(sourcesToMute), end(sourcesToMute), source)
7962 == end(sourcesToMute))) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007963 sourcesToMute.push_back(source);
7964 }
Eric Laurente552edb2014-03-10 17:42:56 -07007965 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01007966 for (auto source : sourcesToMute) {
jiabin9a3361e2019-10-01 09:38:30 -07007967 setVolumeSourceMute(source, on, outputDesc, delayMs, deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007968 }
7969
Eric Laurente552edb2014-03-10 17:42:56 -07007970}
7971
François Gaffieaaac0fd2018-11-22 17:56:39 +01007972void AudioPolicyManager::setVolumeSourceMute(VolumeSource volumeSource,
7973 bool on,
7974 const sp<AudioOutputDescriptor>& outputDesc,
7975 int delayMs,
jiabin9a3361e2019-10-01 09:38:30 -07007976 DeviceTypeSet deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07007977{
jiabin9a3361e2019-10-01 09:38:30 -07007978 if (deviceTypes.empty()) {
7979 deviceTypes = outputDesc->devices().types();
Eric Laurente552edb2014-03-10 17:42:56 -07007980 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01007981 auto &curves = getVolumeCurves(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07007982 if (on) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007983 if (!outputDesc->isMuted(volumeSource)) {
Eric Laurentf5aa58d2019-02-22 18:20:11 -08007984 if (curves.canBeMuted() &&
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007985 (volumeSource != toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01007986 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) ==
7987 AUDIO_POLICY_FORCE_NONE))) {
jiabin9a3361e2019-10-01 09:38:30 -07007988 checkAndSetVolume(curves, volumeSource, 0, outputDesc, deviceTypes, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07007989 }
7990 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01007991 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not
7992 // ignored
7993 outputDesc->incMuteCount(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07007994 } else {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007995 if (!outputDesc->isMuted(volumeSource)) {
7996 ALOGV("%s unmuting non muted attributes!", __func__);
Eric Laurente552edb2014-03-10 17:42:56 -07007997 return;
7998 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01007999 if (outputDesc->decMuteCount(volumeSource) == 0) {
8000 checkAndSetVolume(curves, volumeSource,
jiabin9a3361e2019-10-01 09:38:30 -07008001 curves.getVolumeIndex(deviceTypes),
Eric Laurentc75307b2015-03-17 15:29:32 -07008002 outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07008003 deviceTypes,
Eric Laurente552edb2014-03-10 17:42:56 -07008004 delayMs);
8005 }
8006 }
8007}
8008
François Gaffie53615e22015-03-19 09:24:12 +01008009bool AudioPolicyManager::isValidAttributes(const audio_attributes_t *paa)
8010{
François Gaffiec005e562018-11-06 15:04:49 +01008011 // has flags that map to a stream type?
Eric Laurente83b55d2014-11-14 10:06:21 -08008012 if ((paa->flags & (AUDIO_FLAG_AUDIBILITY_ENFORCED | AUDIO_FLAG_SCO | AUDIO_FLAG_BEACON)) != 0) {
8013 return true;
8014 }
8015
8016 // has known usage?
8017 switch (paa->usage) {
8018 case AUDIO_USAGE_UNKNOWN:
8019 case AUDIO_USAGE_MEDIA:
8020 case AUDIO_USAGE_VOICE_COMMUNICATION:
8021 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
8022 case AUDIO_USAGE_ALARM:
8023 case AUDIO_USAGE_NOTIFICATION:
8024 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
8025 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
8026 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
8027 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
8028 case AUDIO_USAGE_NOTIFICATION_EVENT:
8029 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
8030 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
8031 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
8032 case AUDIO_USAGE_GAME:
Eric Laurent275e8e92014-11-30 15:14:47 -08008033 case AUDIO_USAGE_VIRTUAL_SOURCE:
Jean-Michel Trivi36867762016-12-29 12:03:28 -08008034 case AUDIO_USAGE_ASSISTANT:
Eric Laurent21777f82019-12-06 18:12:06 -08008035 case AUDIO_USAGE_CALL_ASSISTANT:
Hayden Gomes524159d2019-12-23 14:41:47 -08008036 case AUDIO_USAGE_EMERGENCY:
8037 case AUDIO_USAGE_SAFETY:
8038 case AUDIO_USAGE_VEHICLE_STATUS:
8039 case AUDIO_USAGE_ANNOUNCEMENT:
Eric Laurente83b55d2014-11-14 10:06:21 -08008040 break;
8041 default:
8042 return false;
8043 }
8044 return true;
8045}
8046
François Gaffie2110e042015-03-24 08:41:51 +01008047audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
8048{
8049 return mEngine->getForceUse(usage);
8050}
8051
Eric Laurent96d1dda2022-03-14 17:14:19 +01008052bool AudioPolicyManager::isInCall() const {
François Gaffie2110e042015-03-24 08:41:51 +01008053 return isStateInCall(mEngine->getPhoneState());
8054}
8055
Eric Laurent96d1dda2022-03-14 17:14:19 +01008056bool AudioPolicyManager::isStateInCall(int state) const {
François Gaffie2110e042015-03-24 08:41:51 +01008057 return is_state_in_call(state);
8058}
8059
Eric Laurentf9cccec2022-11-16 19:12:00 +01008060bool AudioPolicyManager::isCallAudioAccessible() const {
Eric Laurent74b71512019-11-06 17:21:57 -08008061 audio_mode_t mode = mEngine->getPhoneState();
8062 return (mode == AUDIO_MODE_IN_CALL)
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01008063 || (mode == AUDIO_MODE_CALL_SCREEN)
8064 || (mode == AUDIO_MODE_CALL_REDIRECT);
Eric Laurent74b71512019-11-06 17:21:57 -08008065}
8066
Eric Laurentf9cccec2022-11-16 19:12:00 +01008067bool AudioPolicyManager::isInCallOrScreening() const {
8068 audio_mode_t mode = mEngine->getPhoneState();
8069 return isStateInCall(mode) || mode == AUDIO_MODE_CALL_SCREEN;
8070}
8071
Eric Laurentd60560a2015-04-10 11:31:20 -07008072void AudioPolicyManager::cleanUpForDevice(const sp<DeviceDescriptor>& deviceDesc)
8073{
8074 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07008075 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008076 if (sourceDesc->isConnected() && (sourceDesc->srcDevice()->equals(deviceDesc) ||
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02008077 sourceDesc->sinkDevice()->equals(deviceDesc))
8078 && !isCallRxAudioSource(sourceDesc)) {
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008079 disconnectAudioSource(sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07008080 }
8081 }
8082
8083 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
8084 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
8085 bool release = false;
8086 for (size_t j = 0; j < patchDesc->mPatch.num_sources && !release; j++) {
8087 const struct audio_port_config *source = &patchDesc->mPatch.sources[j];
8088 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
8089 source->ext.device.type == deviceDesc->type()) {
8090 release = true;
8091 }
8092 }
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008093 const char *address = deviceDesc->address().c_str();
Eric Laurentd60560a2015-04-10 11:31:20 -07008094 for (size_t j = 0; j < patchDesc->mPatch.num_sinks && !release; j++) {
8095 const struct audio_port_config *sink = &patchDesc->mPatch.sinks[j];
8096 if (sink->type == AUDIO_PORT_TYPE_DEVICE &&
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008097 sink->ext.device.type == deviceDesc->type() &&
8098 (strnlen(address, AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0
8099 || strncmp(sink->ext.device.address, address,
8100 AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0)) {
Eric Laurentd60560a2015-04-10 11:31:20 -07008101 release = true;
8102 }
8103 }
8104 if (release) {
François Gaffieafd4cea2019-11-18 15:50:22 +01008105 ALOGV("%s releasing patch %u", __FUNCTION__, patchDesc->getHandle());
8106 releaseAudioPatch(patchDesc->getHandle(), patchDesc->getUid());
Eric Laurentd60560a2015-04-10 11:31:20 -07008107 }
8108 }
Francois Gaffie716e1432019-01-14 16:58:59 +01008109
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01008110 mInputs.clearSessionRoutesForDevice(deviceDesc);
8111
Francois Gaffie716e1432019-01-14 16:58:59 +01008112 mHwModules.cleanUpForDevice(deviceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07008113}
8114
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008115void AudioPolicyManager::modifySurroundFormats(
8116 const sp<DeviceDescriptor>& devDesc, FormatVector *formatsPtr) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008117 std::unordered_set<audio_format_t> enforcedSurround(
8118 devDesc->encodedFormats().begin(), devDesc->encodedFormats().end());
Mikhail Naganov100f0122018-11-29 11:22:16 -08008119 std::unordered_set<audio_format_t> allSurround; // A flat set of all known surround formats
Mikhail Naganov68e3f642023-04-28 13:06:32 -07008120 for (const auto& pair : mConfig->getSurroundFormats()) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008121 allSurround.insert(pair.first);
8122 for (const auto& subformat : pair.second) allSurround.insert(subformat);
8123 }
Phil Burk09bc4612016-02-24 15:58:15 -08008124
8125 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
8126 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Phil Burk0709b0a2016-03-31 12:54:57 -07008127 ALOGD("%s: forced use = %d", __FUNCTION__, forceUse);
Mikhail Naganov100f0122018-11-29 11:22:16 -08008128 // This is the resulting set of formats depending on the surround mode:
8129 // 'all surround' = allSurround
8130 // 'enforced surround' = enforcedSurround [may include IEC69137 which isn't raw surround fmt]
8131 // 'non-surround' = not in 'all surround' and not in 'enforced surround'
8132 // 'manual surround' = mManualSurroundFormats
8133 // AUTO: formats v 'enforced surround'
8134 // ALWAYS: formats v 'all surround' v 'enforced surround'
8135 // NEVER: formats ^ 'non-surround'
8136 // MANUAL: formats ^ ('non-surround' v 'manual surround' v (IEC69137 ^ 'enforced surround'))
Phil Burk09bc4612016-02-24 15:58:15 -08008137
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008138 std::unordered_set<audio_format_t> formatSet;
8139 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL
8140 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008141 // formatSet is (formats ^ 'non-surround')
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008142 for (auto formatIter = formatsPtr->begin(); formatIter != formatsPtr->end(); ++formatIter) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008143 if (allSurround.count(*formatIter) == 0 && enforcedSurround.count(*formatIter) == 0) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008144 formatSet.insert(*formatIter);
8145 }
8146 }
8147 } else {
8148 formatSet.insert(formatsPtr->begin(), formatsPtr->end());
8149 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08008150 formatsPtr->clear(); // Re-filled from the formatSet at the end.
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008151
jiabin81772902018-04-02 17:52:27 -07008152 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008153 formatSet.insert(mManualSurroundFormats.begin(), mManualSurroundFormats.end());
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008154 // Enable IEC61937 when in MANUAL mode if it's enforced for this device.
8155 if (enforcedSurround.count(AUDIO_FORMAT_IEC61937) != 0) {
8156 formatSet.insert(AUDIO_FORMAT_IEC61937);
Phil Burk09bc4612016-02-24 15:58:15 -08008157 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08008158 } else if (forceUse != AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) { // AUTO or ALWAYS
8159 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS) {
8160 formatSet.insert(allSurround.begin(), allSurround.end());
Phil Burk07ac1142016-03-25 13:39:29 -07008161 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08008162 formatSet.insert(enforcedSurround.begin(), enforcedSurround.end());
Phil Burk09bc4612016-02-24 15:58:15 -08008163 }
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008164 for (const auto& format : formatSet) {
jiabin06e4bab2019-07-29 10:13:34 -07008165 formatsPtr->push_back(format);
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008166 }
Phil Burk0709b0a2016-03-31 12:54:57 -07008167}
8168
jiabin06e4bab2019-07-29 10:13:34 -07008169void AudioPolicyManager::modifySurroundChannelMasks(ChannelMaskSet *channelMasksPtr) {
8170 ChannelMaskSet &channelMasks = *channelMasksPtr;
Phil Burk0709b0a2016-03-31 12:54:57 -07008171 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
8172 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
8173
8174 // If NEVER, then remove support for channelMasks > stereo.
8175 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
jiabin06e4bab2019-07-29 10:13:34 -07008176 for (auto it = channelMasks.begin(); it != channelMasks.end();) {
8177 audio_channel_mask_t channelMask = *it;
Phil Burk0709b0a2016-03-31 12:54:57 -07008178 if (channelMask & ~AUDIO_CHANNEL_OUT_STEREO) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01008179 ALOGV("%s: force NEVER, so remove channelMask 0x%08x", __FUNCTION__, channelMask);
jiabin06e4bab2019-07-29 10:13:34 -07008180 it = channelMasks.erase(it);
Phil Burk0709b0a2016-03-31 12:54:57 -07008181 } else {
jiabin06e4bab2019-07-29 10:13:34 -07008182 ++it;
Phil Burk0709b0a2016-03-31 12:54:57 -07008183 }
8184 }
jiabin81772902018-04-02 17:52:27 -07008185 // If ALWAYS or MANUAL, then make sure we at least support 5.1
8186 } else if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS
8187 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Phil Burk0709b0a2016-03-31 12:54:57 -07008188 bool supports5dot1 = false;
8189 // Are there any channel masks that can be considered "surround"?
Mikhail Naganovcf84e592017-12-07 11:25:11 -08008190 for (audio_channel_mask_t channelMask : channelMasks) {
Phil Burk0709b0a2016-03-31 12:54:57 -07008191 if ((channelMask & AUDIO_CHANNEL_OUT_5POINT1) == AUDIO_CHANNEL_OUT_5POINT1) {
8192 supports5dot1 = true;
8193 break;
8194 }
8195 }
8196 // If not then add 5.1 support.
8197 if (!supports5dot1) {
jiabin06e4bab2019-07-29 10:13:34 -07008198 channelMasks.insert(AUDIO_CHANNEL_OUT_5POINT1);
Eric Laurentfecbceb2021-02-09 14:46:43 +01008199 ALOGV("%s: force MANUAL or ALWAYS, so adding channelMask for 5.1 surround", __func__);
Phil Burk0709b0a2016-03-31 12:54:57 -07008200 }
Phil Burk09bc4612016-02-24 15:58:15 -08008201 }
8202}
8203
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008204void AudioPolicyManager::updateAudioProfiles(const sp<DeviceDescriptor>& devDesc,
Phil Burk00eeb322016-03-31 12:41:00 -07008205 audio_io_handle_t ioHandle,
jiabin12537fc2023-10-12 17:56:08 +00008206 const sp<IOProfile>& profile) {
8207 if (!profile->hasDynamicAudioProfile()) {
8208 return;
François Gaffie112b0af2015-11-19 16:13:25 +01008209 }
François Gaffie112b0af2015-11-19 16:13:25 +01008210
jiabin12537fc2023-10-12 17:56:08 +00008211 audio_port_v7 devicePort;
8212 devDesc->toAudioPort(&devicePort);
François Gaffie112b0af2015-11-19 16:13:25 +01008213
jiabin12537fc2023-10-12 17:56:08 +00008214 audio_port_v7 mixPort;
8215 profile->toAudioPort(&mixPort);
8216 mixPort.ext.mix.handle = ioHandle;
8217
8218 status_t status = mpClientInterface->getAudioMixPort(&devicePort, &mixPort);
8219 if (status != NO_ERROR) {
8220 ALOGE("%s failed to query the attributes of the mix port", __func__);
8221 return;
François Gaffie112b0af2015-11-19 16:13:25 +01008222 }
jiabin12537fc2023-10-12 17:56:08 +00008223
8224 std::set<audio_format_t> supportedFormats;
8225 for (size_t i = 0; i < mixPort.num_audio_profiles; ++i) {
8226 supportedFormats.insert(mixPort.audio_profiles[i].format);
8227 }
8228 FormatVector formats(supportedFormats.begin(), supportedFormats.end());
8229 mReportedFormatsMap[devDesc] = formats;
8230
8231 if (devDesc->type() == AUDIO_DEVICE_OUT_HDMI ||
8232 isDeviceOfModule(devDesc,AUDIO_HARDWARE_MODULE_ID_MSD)) {
8233 modifySurroundFormats(devDesc, &formats);
8234 size_t modifiedNumProfiles = 0;
8235 for (size_t i = 0; i < mixPort.num_audio_profiles; ++i) {
8236 if (std::find(formats.begin(), formats.end(), mixPort.audio_profiles[i].format) ==
8237 formats.end()) {
8238 // Skip the format that is not present after modifying surround formats.
8239 continue;
8240 }
8241 memcpy(&mixPort.audio_profiles[modifiedNumProfiles], &mixPort.audio_profiles[i],
8242 sizeof(struct audio_profile));
8243 ChannelMaskSet channels(mixPort.audio_profiles[modifiedNumProfiles].channel_masks,
8244 mixPort.audio_profiles[modifiedNumProfiles].channel_masks +
8245 mixPort.audio_profiles[modifiedNumProfiles].num_channel_masks);
8246 modifySurroundChannelMasks(&channels);
8247 std::copy(channels.begin(), channels.end(),
8248 std::begin(mixPort.audio_profiles[modifiedNumProfiles].channel_masks));
8249 mixPort.audio_profiles[modifiedNumProfiles++].num_channel_masks = channels.size();
8250 }
8251 mixPort.num_audio_profiles = modifiedNumProfiles;
8252 }
8253 profile->importAudioPort(mixPort);
François Gaffie112b0af2015-11-19 16:13:25 +01008254}
Eric Laurentd60560a2015-04-10 11:31:20 -07008255
Mikhail Naganovdc769682018-05-04 15:34:08 -07008256status_t AudioPolicyManager::installPatch(const char *caller,
8257 audio_patch_handle_t *patchHandle,
8258 AudioIODescriptorInterface *ioDescriptor,
8259 const struct audio_patch *patch,
8260 int delayMs)
8261{
8262 ssize_t index = mAudioPatches.indexOfKey(
8263 patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE ?
8264 *patchHandle : ioDescriptor->getPatchHandle());
8265 sp<AudioPatch> patchDesc;
8266 status_t status = installPatch(
8267 caller, index, patchHandle, patch, delayMs, mUidCached, &patchDesc);
8268 if (status == NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01008269 ioDescriptor->setPatchHandle(patchDesc->getHandle());
Mikhail Naganovdc769682018-05-04 15:34:08 -07008270 }
8271 return status;
8272}
8273
8274status_t AudioPolicyManager::installPatch(const char *caller,
8275 ssize_t index,
8276 audio_patch_handle_t *patchHandle,
8277 const struct audio_patch *patch,
8278 int delayMs,
8279 uid_t uid,
8280 sp<AudioPatch> *patchDescPtr)
8281{
8282 sp<AudioPatch> patchDesc;
8283 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
8284 if (index >= 0) {
8285 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01008286 afPatchHandle = patchDesc->getAfHandle();
Mikhail Naganovdc769682018-05-04 15:34:08 -07008287 }
8288
8289 status_t status = mpClientInterface->createAudioPatch(patch, &afPatchHandle, delayMs);
8290 ALOGV("%s() AF::createAudioPatch returned %d patchHandle %d num_sources %d num_sinks %d",
8291 caller, status, afPatchHandle, patch->num_sources, patch->num_sinks);
8292 if (status == NO_ERROR) {
8293 if (index < 0) {
8294 patchDesc = new AudioPatch(patch, uid);
François Gaffieafd4cea2019-11-18 15:50:22 +01008295 addAudioPatch(patchDesc->getHandle(), patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07008296 } else {
8297 patchDesc->mPatch = *patch;
8298 }
François Gaffieafd4cea2019-11-18 15:50:22 +01008299 patchDesc->setAfHandle(afPatchHandle);
Mikhail Naganovdc769682018-05-04 15:34:08 -07008300 if (patchHandle) {
François Gaffieafd4cea2019-11-18 15:50:22 +01008301 *patchHandle = patchDesc->getHandle();
Mikhail Naganovdc769682018-05-04 15:34:08 -07008302 }
8303 nextAudioPortGeneration();
8304 mpClientInterface->onAudioPatchListUpdate();
8305 }
8306 if (patchDescPtr) *patchDescPtr = patchDesc;
8307 return status;
8308}
8309
jiabinbce0c1d2020-10-05 11:20:18 -07008310bool AudioPolicyManager::areAllActiveTracksRerouted(const sp<SwAudioOutputDescriptor>& output)
8311{
8312 const TrackClientVector activeClients = output->getActiveClients();
8313 if (activeClients.empty()) {
8314 return true;
8315 }
8316 ssize_t index = mAudioPatches.indexOfKey(output->getPatchHandle());
8317 if (index < 0) {
8318 ALOGE("%s, no audio patch found while there are active clients on output %d",
8319 __func__, output->getId());
8320 return false;
8321 }
8322 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
8323 DeviceVector routedDevices;
8324 for (int i = 0; i < patchDesc->mPatch.num_sinks; ++i) {
8325 sp<DeviceDescriptor> device = mAvailableOutputDevices.getDeviceFromId(
8326 patchDesc->mPatch.sinks[i].id);
8327 if (device == nullptr) {
8328 ALOGE("%s, no audio device found with id(%d)",
8329 __func__, patchDesc->mPatch.sinks[i].id);
8330 return false;
8331 }
8332 routedDevices.add(device);
8333 }
8334 for (const auto& client : activeClients) {
jiabin49256852022-03-09 11:21:35 -08008335 if (client->isInvalid()) {
8336 // No need to take care about invalidated clients.
8337 continue;
8338 }
jiabinbce0c1d2020-10-05 11:20:18 -07008339 sp<DeviceDescriptor> preferredDevice =
8340 mAvailableOutputDevices.getDeviceFromId(client->preferredDeviceId());
8341 if (mEngine->getOutputDevicesForAttributes(
8342 client->attributes(), preferredDevice, false) == routedDevices) {
8343 return false;
8344 }
8345 }
8346 return true;
8347}
8348
8349sp<SwAudioOutputDescriptor> AudioPolicyManager::openOutputWithProfileAndDevice(
Eric Laurentb4f42a92022-01-17 17:37:31 +01008350 const sp<IOProfile>& profile, const DeviceVector& devices,
jiabina84c3d32022-12-02 18:59:55 +00008351 const audio_config_base_t *mixerConfig, const audio_config_t *halConfig,
8352 audio_output_flags_t flags)
jiabinbce0c1d2020-10-05 11:20:18 -07008353{
8354 for (const auto& device : devices) {
8355 // TODO: This should be checking if the profile supports the device combo.
8356 if (!profile->supportsDevice(device)) {
jiabina84c3d32022-12-02 18:59:55 +00008357 ALOGE("%s profile(%s) doesn't support device %#x", __func__, profile->getName().c_str(),
8358 device->type());
jiabinbce0c1d2020-10-05 11:20:18 -07008359 return nullptr;
8360 }
8361 }
8362 sp<SwAudioOutputDescriptor> desc = new SwAudioOutputDescriptor(profile, mpClientInterface);
8363 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
jiabina84c3d32022-12-02 18:59:55 +00008364 status_t status = desc->open(halConfig, mixerConfig, devices,
8365 AUDIO_STREAM_DEFAULT, flags, &output);
jiabinbce0c1d2020-10-05 11:20:18 -07008366 if (status != NO_ERROR) {
jiabina84c3d32022-12-02 18:59:55 +00008367 ALOGE("%s failed to open output %d", __func__, status);
jiabinbce0c1d2020-10-05 11:20:18 -07008368 return nullptr;
8369 }
jiabin14b50cc2023-12-13 19:01:52 +00008370 if ((flags & AUDIO_OUTPUT_FLAG_BIT_PERFECT) == AUDIO_OUTPUT_FLAG_BIT_PERFECT) {
8371 auto portConfig = desc->getConfig();
8372 for (const auto& device : devices) {
8373 device->setPreferredConfig(&portConfig);
8374 }
8375 }
jiabinbce0c1d2020-10-05 11:20:18 -07008376
8377 // Here is where the out_set_parameters() for card & device gets called
8378 sp<DeviceDescriptor> device = devices.getDeviceForOpening();
8379 const audio_devices_t deviceType = device->type();
8380 const String8 &address = String8(device->address().c_str());
Tomasz Wasilczykfd9ffd12023-08-14 17:56:22 +00008381 if (!address.empty()) {
jiabinbce0c1d2020-10-05 11:20:18 -07008382 char *param = audio_device_address_to_parameter(deviceType, address.c_str());
8383 mpClientInterface->setParameters(output, String8(param));
8384 free(param);
8385 }
jiabin12537fc2023-10-12 17:56:08 +00008386 updateAudioProfiles(device, output, profile);
jiabinbce0c1d2020-10-05 11:20:18 -07008387 if (!profile->hasValidAudioProfile()) {
8388 ALOGW("%s() missing param", __func__);
8389 desc->close();
8390 return nullptr;
jiabina84c3d32022-12-02 18:59:55 +00008391 } else if (profile->hasDynamicAudioProfile() && halConfig == nullptr) {
8392 // Reopen the output with the best audio profile picked by APM when the profile supports
8393 // dynamic audio profile and the hal config is not specified.
jiabinbce0c1d2020-10-05 11:20:18 -07008394 desc->close();
8395 output = AUDIO_IO_HANDLE_NONE;
8396 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
8397 profile->pickAudioProfile(
8398 config.sample_rate, config.channel_mask, config.format);
8399 config.offload_info.sample_rate = config.sample_rate;
8400 config.offload_info.channel_mask = config.channel_mask;
8401 config.offload_info.format = config.format;
8402
jiabina84c3d32022-12-02 18:59:55 +00008403 status = desc->open(&config, mixerConfig, devices, AUDIO_STREAM_DEFAULT, flags, &output);
jiabinbce0c1d2020-10-05 11:20:18 -07008404 if (status != NO_ERROR) {
8405 return nullptr;
8406 }
8407 }
8408
8409 addOutput(output, desc);
Eric Laurentb4f42a92022-01-17 17:37:31 +01008410
baek.kim -61c20122022-07-27 10:05:32 +00008411 sp<DeviceDescriptor> speaker = mAvailableOutputDevices.getDevice(
8412 AUDIO_DEVICE_OUT_SPEAKER, String8(""), AUDIO_FORMAT_DEFAULT);
8413
jiabinbce0c1d2020-10-05 11:20:18 -07008414 if (audio_is_remote_submix_device(deviceType) && address != "0") {
8415 sp<AudioPolicyMix> policyMix;
8416 if (mPolicyMixes.getAudioPolicyMix(deviceType, address, policyMix) == NO_ERROR) {
8417 policyMix->setOutput(desc);
8418 desc->mPolicyMix = policyMix;
8419 } else {
8420 ALOGW("checkOutputsForDevice() cannot find policy for address %s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00008421 address.c_str());
jiabinbce0c1d2020-10-05 11:20:18 -07008422 }
8423
baek.kim -61c20122022-07-27 10:05:32 +00008424 } else if (hasPrimaryOutput() && speaker != nullptr
8425 && mPrimaryOutput->supportsDevice(speaker) && !desc->supportsDevice(speaker)
Eric Laurentb4f42a92022-01-17 17:37:31 +01008426 && ((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0)) {
8427 // no duplicated output for:
8428 // - direct outputs
8429 // - outputs used by dynamic policy mixes
baek.kim -61c20122022-07-27 10:05:32 +00008430 // - outputs that supports SPEAKER while the primary output does not.
jiabinbce0c1d2020-10-05 11:20:18 -07008431 audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE;
8432
8433 //TODO: configure audio effect output stage here
8434
8435 // open a duplicating output thread for the new output and the primary output
8436 sp<SwAudioOutputDescriptor> dupOutputDesc =
8437 new SwAudioOutputDescriptor(nullptr, mpClientInterface);
8438 status = dupOutputDesc->openDuplicating(mPrimaryOutput, desc, &duplicatedOutput);
8439 if (status == NO_ERROR) {
8440 // add duplicated output descriptor
8441 addOutput(duplicatedOutput, dupOutputDesc);
8442 } else {
8443 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
8444 mPrimaryOutput->mIoHandle, output);
8445 desc->close();
8446 removeOutput(output);
8447 nextAudioPortGeneration();
8448 return nullptr;
8449 }
8450 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02008451 if (mPrimaryOutput == nullptr && profile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
8452 ALOGV("%s(): re-assigning mPrimaryOutput", __func__);
8453 mPrimaryOutput = desc;
François Gaffiedb1755b2023-09-01 11:50:35 +02008454 mPrimaryModuleHandle = mPrimaryOutput->getModuleHandle();
Francois Gaffiebce7cd42020-10-14 16:13:20 +02008455 }
jiabinbce0c1d2020-10-05 11:20:18 -07008456 return desc;
8457}
8458
jiabinf1c73972022-04-14 16:28:52 -07008459status_t AudioPolicyManager::getDevicesForAttributes(
8460 const audio_attributes_t &attr, DeviceVector &devices, bool forVolume) {
8461 // Devices are determined in the following precedence:
8462 //
8463 // 1) Devices associated with a dynamic policy matching the attributes. This is often
8464 // a remote submix from MIX_ROUTE_FLAG_LOOP_BACK.
8465 //
8466 // If no such dynamic policy then
8467 // 2) Devices containing an active client using setPreferredDevice
8468 // with same strategy as the attributes.
8469 // (from the default Engine::getOutputDevicesForAttributes() implementation).
8470 //
8471 // If no corresponding active client with setPreferredDevice then
8472 // 3) Devices associated with the strategy determined by the attributes
8473 // (from the default Engine::getOutputDevicesForAttributes() implementation).
8474 //
8475 // See related getOutputForAttrInt().
8476
8477 // check dynamic policies but only for primary descriptors (secondary not used for audible
8478 // audio routing, only used for duplication for playback capture)
8479 sp<AudioPolicyMix> policyMix;
Oscar Azucena873d10f2023-01-12 18:34:42 -08008480 bool unneededUsePrimaryOutputFromPolicyMixes = false;
jiabinf1c73972022-04-14 16:28:52 -07008481 status_t status = mPolicyMixes.getOutputForAttr(attr, AUDIO_CONFIG_BASE_INITIALIZER,
Oscar Azucena873d10f2023-01-12 18:34:42 -08008482 0 /*uid unknown here*/, AUDIO_SESSION_NONE, AUDIO_OUTPUT_FLAG_NONE,
8483 mAvailableOutputDevices, nullptr /* requestedDevice */, policyMix,
8484 nullptr /* secondaryMixes */, unneededUsePrimaryOutputFromPolicyMixes);
jiabinf1c73972022-04-14 16:28:52 -07008485 if (status != OK) {
8486 return status;
8487 }
8488
8489 if (policyMix != nullptr && policyMix->getOutput() != nullptr &&
8490 // For volume control, skip LOOPBACK mixes which use AUDIO_DEVICE_OUT_REMOTE_SUBMIX
8491 // as they are unaffected by device/stream volume
8492 // (per SwAudioOutputDescriptor::isFixedVolume()).
8493 (!forVolume || policyMix->mDeviceType != AUDIO_DEVICE_OUT_REMOTE_SUBMIX)
8494 ) {
8495 sp<DeviceDescriptor> deviceDesc = mAvailableOutputDevices.getDevice(
8496 policyMix->mDeviceType, policyMix->mDeviceAddress, AUDIO_FORMAT_DEFAULT);
8497 devices.add(deviceDesc);
8498 } else {
8499 // The default Engine::getOutputDevicesForAttributes() uses findPreferredDevice()
8500 // which selects setPreferredDevice if active. This means forVolume call
8501 // will take an active setPreferredDevice, if such exists.
8502
8503 devices = mEngine->getOutputDevicesForAttributes(
8504 attr, nullptr /* preferredDevice */, false /* fromCache */);
8505 }
8506
8507 if (forVolume) {
8508 // We alias the device AUDIO_DEVICE_OUT_SPEAKER_SAFE to AUDIO_DEVICE_OUT_SPEAKER
8509 // for single volume control in AudioService (such relationship should exist if
8510 // SPEAKER_SAFE is present).
8511 //
8512 // (This is unrelated to a different device grouping as Volume::getDeviceCategory)
8513 DeviceVector speakerSafeDevices =
8514 devices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER_SAFE);
8515 if (!speakerSafeDevices.isEmpty()) {
8516 devices.merge(mAvailableOutputDevices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER));
8517 devices.remove(speakerSafeDevices);
8518 }
8519 }
8520
8521 return NO_ERROR;
8522}
8523
8524status_t AudioPolicyManager::getProfilesForDevices(const DeviceVector& devices,
8525 AudioProfileVector& audioProfiles,
8526 uint32_t flags,
8527 bool isInput) {
8528 for (const auto& hwModule : mHwModules) {
8529 // the MSD module checks for different conditions
8530 if (strcmp(hwModule->getName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0) {
8531 continue;
8532 }
8533 IOProfileCollection ioProfiles = isInput ? hwModule->getInputProfiles()
8534 : hwModule->getOutputProfiles();
8535 for (const auto& profile : ioProfiles) {
8536 if (!profile->areAllDevicesSupported(devices) ||
8537 !profile->isCompatibleProfileForFlags(
8538 flags, false /*exactMatchRequiredForInputFlags*/)) {
8539 continue;
8540 }
8541 audioProfiles.addAllValidProfiles(profile->asAudioPort()->getAudioProfiles());
8542 }
8543 }
8544
8545 if (!isInput) {
8546 // add the direct profiles from MSD if present and has audio patches to all the output(s)
8547 const auto &msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
8548 if (msdModule != nullptr) {
8549 if (msdHasPatchesToAllDevices(devices.toTypeAddrVector())) {
8550 ALOGV("%s: MSD audio patches set to all output devices.", __func__);
8551 for (const auto &profile: msdModule->getOutputProfiles()) {
8552 if (!profile->asAudioPort()->isDirectOutput()) {
8553 continue;
8554 }
8555 audioProfiles.addAllValidProfiles(profile->asAudioPort()->getAudioProfiles());
8556 }
8557 } else {
8558 ALOGV("%s: MSD audio patches NOT set to all output devices.", __func__);
8559 }
8560 }
8561 }
8562
8563 return NO_ERROR;
8564}
8565
jiabin3ff8d7d2022-12-13 06:27:44 +00008566sp<SwAudioOutputDescriptor> AudioPolicyManager::reopenOutput(sp<SwAudioOutputDescriptor> outputDesc,
8567 const audio_config_t *config,
8568 audio_output_flags_t flags,
8569 const char* caller) {
jiabina84c3d32022-12-02 18:59:55 +00008570 closeOutput(outputDesc->mIoHandle);
8571 sp<SwAudioOutputDescriptor> preferredOutput = openOutputWithProfileAndDevice(
8572 outputDesc->mProfile, outputDesc->devices(), nullptr /*mixerConfig*/, config, flags);
8573 if (preferredOutput == nullptr) {
8574 ALOGE("%s failed to reopen output device=%d, caller=%s",
8575 __func__, outputDesc->devices()[0]->getId(), caller);
jiabina84c3d32022-12-02 18:59:55 +00008576 }
jiabin3ff8d7d2022-12-13 06:27:44 +00008577 return preferredOutput;
8578}
8579
8580void AudioPolicyManager::reopenOutputsWithDevices(
8581 const std::map<audio_io_handle_t, DeviceVector> &outputsToReopen) {
8582 for (const auto& [output, devices] : outputsToReopen) {
8583 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
8584 closeOutput(output);
8585 openOutputWithProfileAndDevice(desc->mProfile, devices);
8586 }
jiabina84c3d32022-12-02 18:59:55 +00008587}
8588
jiabinc44b3462022-12-08 12:52:31 -08008589PortHandleVector AudioPolicyManager::getClientsForStream(
8590 audio_stream_type_t streamType) const {
8591 PortHandleVector clients;
8592 for (size_t i = 0; i < mOutputs.size(); ++i) {
8593 PortHandleVector clientsForStream = mOutputs.valueAt(i)->getClientsForStream(streamType);
8594 clients.insert(clients.end(), clientsForStream.begin(), clientsForStream.end());
8595 }
8596 return clients;
8597}
8598
8599void AudioPolicyManager::invalidateStreams(StreamTypeVector streams) const {
8600 PortHandleVector clients;
8601 for (auto stream : streams) {
8602 PortHandleVector clientsForStream = getClientsForStream(stream);
8603 clients.insert(clients.end(), clientsForStream.begin(), clientsForStream.end());
8604 }
8605 mpClientInterface->invalidateTracks(clients);
8606}
8607
Mikhail Naganov1b2a7942017-12-08 10:18:09 -08008608} // namespace android