blob: 69d3b5db9acd00175bd833d84482820a150c6afe [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) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001220 sp<DeviceDescriptor> deviceDesc =
1221 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 ||
1226 (policyDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT);
1227 // if a direct output can be opened to deliver the track's multi-channel content to the
1228 // output rather than being downmixed by the primary output, then use this direct
1229 // output by by-passing the primary mix if possible, otherwise fall-through to primary
1230 // mix.
1231 bool tryDirectForChannelMask = policyDesc != nullptr
1232 && (audio_channel_count_from_out_mask(policyDesc->getConfig().channel_mask) <
1233 audio_channel_count_from_out_mask(config->channel_mask));
1234 if (deviceDesc != nullptr && (tryDirectForFlags || tryDirectForChannelMask)) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001235 audio_io_handle_t newOutput;
1236 status = openDirectOutput(
1237 *stream, session, config,
1238 (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT),
1239 DeviceVector(deviceDesc), &newOutput);
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001240 if (status == NO_ERROR) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001241 policyDesc = mOutputs.valueFor(newOutput);
1242 primaryMix->setOutput(policyDesc);
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001243 } else if (tryDirectForFlags) {
1244 policyDesc = nullptr;
1245 } // otherwise use primary if available.
Eric Laurentc529cf62020-04-17 18:19:10 -07001246 }
1247 if (policyDesc != nullptr) {
1248 policyDesc->mPolicyMix = primaryMix;
1249 *output = policyDesc->mIoHandle;
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08001250 *selectedDeviceId = deviceDesc != 0 ? deviceDesc->getId() : AUDIO_PORT_HANDLE_NONE;
Eric Laurent8a1095a2019-11-08 14:44:16 -08001251
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08001252 ALOGV("getOutputForAttr() returns output %d", *output);
1253 if (resultAttr->usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
1254 *outputType = API_OUT_MIX_PLAYBACK;
1255 } else {
1256 *outputType = API_OUTPUT_LEGACY;
1257 }
1258 return NO_ERROR;
Eric Laurent8a1095a2019-11-08 14:44:16 -08001259 }
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001260 }
François Gaffiec005e562018-11-06 15:04:49 +01001261 // Virtual sources must always be dynamicaly or explicitly routed
1262 if (resultAttr->usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
1263 ALOGW("getOutputForAttr() no policy mix found for usage AUDIO_USAGE_VIRTUAL_SOURCE");
1264 return BAD_VALUE;
1265 }
1266 // explicit routing managed by getDeviceForStrategy in APM is now handled by engine
1267 // in order to let the choice of the order to future vendor engine
1268 outputDevices = mEngine->getOutputDevicesForAttributes(*resultAttr, requestedDevice, false);
Scott Randolph7b1fd232018-06-18 15:33:03 -07001269
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001270 if ((resultAttr->flags & AUDIO_FLAG_HW_AV_SYNC) != 0) {
Nadav Bar766fb022018-01-07 12:18:03 +02001271 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
Eric Laurent93c3d412014-08-01 14:48:35 -07001272 }
1273
Nadav Barb2f18162018-07-18 13:01:53 +03001274 // Set incall music only if device was explicitly set, and fallback to the device which is
1275 // chosen by the engine if not.
1276 // FIXME: provide a more generic approach which is not device specific and move this back
1277 // to getOutputForDevice.
Nadav Bar20919492018-11-20 10:20:51 +02001278 // TODO: Remove check of AUDIO_STREAM_MUSIC once migration is completed on the app side.
jiabin9a3361e2019-10-01 09:38:30 -07001279 if (outputDevices.onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_TELEPHONY_TX) &&
François Gaffiec005e562018-11-06 15:04:49 +01001280 (*stream == AUDIO_STREAM_MUSIC || resultAttr->usage == AUDIO_USAGE_VOICE_COMMUNICATION) &&
Nadav Barb2f18162018-07-18 13:01:53 +03001281 audio_is_linear_pcm(config->format) &&
Eric Laurent74b71512019-11-06 17:21:57 -08001282 isCallAudioAccessible()) {
Francois Gaffie716e1432019-01-14 16:58:59 +01001283 if (requestedPortId != AUDIO_PORT_HANDLE_NONE) {
Nadav Barb2f18162018-07-18 13:01:53 +03001284 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_INCALL_MUSIC;
François Gaffief579db52018-11-13 11:25:16 +01001285 *isRequestedDeviceForExclusiveUse = true;
Nadav Barb2f18162018-07-18 13:01:53 +03001286 }
1287 }
1288
François Gaffiec005e562018-11-06 15:04:49 +01001289 ALOGV("%s() device %s, sampling rate %d, format %#x, channel mask %#x, flags %#x stream %s",
1290 __func__, outputDevices.toString().c_str(), config->sample_rate, config->format,
1291 config->channel_mask, *flags, toString(*stream).c_str());
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001292
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001293 *output = AUDIO_IO_HANDLE_NONE;
François Gaffie11d30102018-11-02 16:09:09 +01001294 if (!msdDevices.isEmpty()) {
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001295 *output = getOutputForDevices(msdDevices, session, resultAttr, config, flags, isSpatialized);
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001296 if (*output != AUDIO_IO_HANDLE_NONE && setMsdOutputPatches(&outputDevices) == NO_ERROR) {
François Gaffiec005e562018-11-06 15:04:49 +01001297 ALOGV("%s() Using MSD devices %s instead of devices %s",
1298 __func__, msdDevices.toString().c_str(), outputDevices.toString().c_str());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001299 } else {
1300 *output = AUDIO_IO_HANDLE_NONE;
1301 }
1302 }
1303 if (*output == AUDIO_IO_HANDLE_NONE) {
jiabina84c3d32022-12-02 18:59:55 +00001304 sp<PreferredMixerAttributesInfo> info = nullptr;
1305 if (outputDevices.size() == 1) {
1306 info = getPreferredMixerAttributesInfo(
1307 outputDevices.itemAt(0)->getId(),
jiabind9a58d32023-06-01 17:57:30 +00001308 mEngine->getProductStrategyForAttributes(*resultAttr),
1309 true /*activeBitPerfectPreferred*/);
jiabin5eaf0962022-12-20 20:11:38 +00001310 // Only use preferred mixer if the uid matches or the preferred mixer is bit-perfect
1311 // and it is currently active.
1312 if (info != nullptr && info->getUid() != uid &&
1313 ((info->getFlags() & AUDIO_OUTPUT_FLAG_BIT_PERFECT) == AUDIO_OUTPUT_FLAG_NONE ||
1314 info->getActiveClientCount() == 0)) {
jiabina84c3d32022-12-02 18:59:55 +00001315 info = nullptr;
1316 }
1317 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001318 *output = getOutputForDevices(outputDevices, session, resultAttr, config,
jiabina84c3d32022-12-02 18:59:55 +00001319 flags, isSpatialized, info, resultAttr->flags & AUDIO_FLAG_MUTE_HAPTIC);
jiabin5eaf0962022-12-20 20:11:38 +00001320 // The client will be active if the client is currently preferred mixer owner and the
1321 // requested configuration matches the preferred mixer configuration.
jiabinc658e452022-10-21 20:52:21 +00001322 *isBitPerfect = (info != nullptr
1323 && (info->getFlags() & AUDIO_OUTPUT_FLAG_BIT_PERFECT) != AUDIO_OUTPUT_FLAG_NONE
jiabin5eaf0962022-12-20 20:11:38 +00001324 && info->getUid() == uid
1325 && *output != AUDIO_IO_HANDLE_NONE
1326 // When bit-perfect output is selected for the preferred mixer attributes owner,
1327 // only need to consider the config matches.
1328 && mOutputs.valueFor(*output)->isConfigurationMatched(
1329 clientConfig, AUDIO_OUTPUT_FLAG_NONE));
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001330 }
Eric Laurente83b55d2014-11-14 10:06:21 -08001331 if (*output == AUDIO_IO_HANDLE_NONE) {
jiabinf1c73972022-04-14 16:28:52 -07001332 AudioProfileVector profiles;
1333 status_t ret = getProfilesForDevices(outputDevices, profiles, *flags, false /*isInput*/);
1334 if (ret == NO_ERROR && !profiles.empty()) {
Robert Wub98ff1b2023-06-15 22:53:58 +00001335 const auto channels = profiles[0]->getChannels();
1336 if (!channels.empty() && (channels.find(config->channel_mask) == channels.end())) {
1337 config->channel_mask = *channels.begin();
1338 }
1339 const auto sampleRates = profiles[0]->getSampleRates();
1340 if (!sampleRates.empty() &&
1341 (sampleRates.find(config->sample_rate) == sampleRates.end())) {
1342 config->sample_rate = *sampleRates.begin();
1343 }
jiabinf1c73972022-04-14 16:28:52 -07001344 config->format = profiles[0]->getFormat();
1345 }
Eric Laurente83b55d2014-11-14 10:06:21 -08001346 return INVALID_OPERATION;
1347 }
Paul McLeanaa981192015-03-21 09:55:15 -07001348
François Gaffiec005e562018-11-06 15:04:49 +01001349 *selectedDeviceId = getFirstDeviceId(outputDevices);
Michael Chan6fb34492020-12-08 15:44:49 +11001350 for (auto &outputDevice : outputDevices) {
Mikhail Naganov68e3f642023-04-28 13:06:32 -07001351 if (outputDevice->getId() == mConfig->getDefaultOutputDevice()->getId()) {
Michael Chan6fb34492020-12-08 15:44:49 +11001352 *selectedDeviceId = outputDevice->getId();
1353 break;
1354 }
1355 }
Eric Laurent2ac76942017-06-22 17:17:09 -07001356
Eric Laurent8a1095a2019-11-08 14:44:16 -08001357 if (outputDevices.onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_TELEPHONY_TX)) {
1358 *outputType = API_OUTPUT_TELEPHONY_TX;
1359 } else {
1360 *outputType = API_OUTPUT_LEGACY;
1361 }
1362
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001363 ALOGV("%s returns output %d selectedDeviceId %d", __func__, *output, *selectedDeviceId);
1364
1365 return NO_ERROR;
1366}
1367
1368status_t AudioPolicyManager::getOutputForAttr(const audio_attributes_t *attr,
1369 audio_io_handle_t *output,
1370 audio_session_t session,
1371 audio_stream_type_t *stream,
Svet Ganov3e5f14f2021-05-13 22:51:08 +00001372 const AttributionSourceState& attributionSource,
jiabinf1c73972022-04-14 16:28:52 -07001373 audio_config_t *config,
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001374 audio_output_flags_t *flags,
1375 audio_port_handle_t *selectedDeviceId,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001376 audio_port_handle_t *portId,
Eric Laurent8a1095a2019-11-08 14:44:16 -08001377 std::vector<audio_io_handle_t> *secondaryOutputs,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001378 output_type_t *outputType,
jiabinc658e452022-10-21 20:52:21 +00001379 bool *isSpatialized,
1380 bool *isBitPerfect)
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001381{
1382 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
1383 if (*portId != AUDIO_PORT_HANDLE_NONE) {
1384 return INVALID_OPERATION;
1385 }
Philip P. Moltmannbda45752020-07-17 16:41:18 -07001386 const uid_t uid = VALUE_OR_RETURN_STATUS(
Svet Ganov3e5f14f2021-05-13 22:51:08 +00001387 aidl2legacy_int32_t_uid_t(attributionSource.uid));
Francois Gaffie716e1432019-01-14 16:58:59 +01001388 const audio_port_handle_t requestedPortId = *selectedDeviceId;
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001389 audio_attributes_t resultAttr;
François Gaffief579db52018-11-13 11:25:16 +01001390 bool isRequestedDeviceForExclusiveUse = false;
Eric Laurentc529cf62020-04-17 18:19:10 -07001391 std::vector<sp<AudioPolicyMix>> secondaryMixes;
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001392 const sp<DeviceDescriptor> requestedDevice =
1393 mAvailableOutputDevices.getDeviceFromId(requestedPortId);
1394
1395 // Prevent from storing invalid requested device id in clients
1396 const audio_port_handle_t sanitizedRequestedPortId =
1397 requestedDevice != nullptr ? requestedPortId : AUDIO_PORT_HANDLE_NONE;
1398 *selectedDeviceId = sanitizedRequestedPortId;
1399
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001400 status_t status = getOutputForAttrInt(&resultAttr, output, session, attr, stream, uid,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001401 config, flags, selectedDeviceId, &isRequestedDeviceForExclusiveUse,
jiabinc658e452022-10-21 20:52:21 +00001402 secondaryOutputs != nullptr ? &secondaryMixes : nullptr, outputType, isSpatialized,
1403 isBitPerfect);
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001404 if (status != NO_ERROR) {
1405 return status;
1406 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001407 std::vector<wp<SwAudioOutputDescriptor>> weakSecondaryOutputDescs;
Eric Laurentc529cf62020-04-17 18:19:10 -07001408 if (secondaryOutputs != nullptr) {
1409 for (auto &secondaryMix : secondaryMixes) {
1410 sp<SwAudioOutputDescriptor> outputDesc = secondaryMix->getOutput();
1411 if (outputDesc != nullptr &&
1412 outputDesc->mIoHandle != AUDIO_IO_HANDLE_NONE) {
1413 secondaryOutputs->push_back(outputDesc->mIoHandle);
1414 weakSecondaryOutputDescs.push_back(outputDesc);
1415 }
1416 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001417 }
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001418
Eric Laurent8fc147b2018-07-22 19:13:55 -07001419 audio_config_base_t clientConfig = {.sample_rate = config->sample_rate,
Nick Desaulniersa30e3202019-10-18 13:38:23 -07001420 .channel_mask = config->channel_mask,
Eric Laurent8fc147b2018-07-22 19:13:55 -07001421 .format = config->format,
Nick Desaulniersa30e3202019-10-18 13:38:23 -07001422 };
jiabin4ef93452019-09-10 14:29:54 -07001423 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurent8f42ea12018-08-08 09:08:25 -07001424
Eric Laurentc209fe42020-06-05 18:11:23 -07001425 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(*output);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001426 sp<TrackClientDescriptor> clientDesc =
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001427 new TrackClientDescriptor(*portId, uid, session, resultAttr, clientConfig,
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001428 sanitizedRequestedPortId, *stream,
François Gaffiec005e562018-11-06 15:04:49 +01001429 mEngine->getProductStrategyForAttributes(resultAttr),
François Gaffieaaac0fd2018-11-22 17:56:39 +01001430 toVolumeSource(resultAttr),
Kevin Rocard153f92d2018-12-18 18:33:28 -08001431 *flags, isRequestedDeviceForExclusiveUse,
Eric Laurentc209fe42020-06-05 18:11:23 -07001432 std::move(weakSecondaryOutputDescs),
1433 outputDesc->mPolicyMix);
Andy Hung39efb7a2018-09-26 15:39:28 -07001434 outputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001435
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001436 ALOGV("%s() returns output %d requestedPortId %d selectedDeviceId %d for port ID %d", __func__,
1437 *output, requestedPortId, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07001438
Eric Laurente83b55d2014-11-14 10:06:21 -08001439 return NO_ERROR;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001440}
1441
Eric Laurentc529cf62020-04-17 18:19:10 -07001442status_t AudioPolicyManager::openDirectOutput(audio_stream_type_t stream,
1443 audio_session_t session,
1444 const audio_config_t *config,
1445 audio_output_flags_t flags,
1446 const DeviceVector &devices,
1447 audio_io_handle_t *output) {
1448
1449 *output = AUDIO_IO_HANDLE_NONE;
1450
1451 // skip direct output selection if the request can obviously be attached to a mixed output
1452 // and not explicitly requested
1453 if (((flags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
1454 audio_is_linear_pcm(config->format) && config->sample_rate <= SAMPLE_RATE_HZ_MAX &&
1455 audio_channel_count_from_out_mask(config->channel_mask) <= 2) {
1456 return NAME_NOT_FOUND;
1457 }
1458
1459 // Do not allow offloading if one non offloadable effect is enabled or MasterMono is enabled.
1460 // This prevents creating an offloaded track and tearing it down immediately after start
1461 // when audioflinger detects there is an active non offloadable effect.
1462 // FIXME: We should check the audio session here but we do not have it in this context.
1463 // This may prevent offloading in rare situations where effects are left active by apps
1464 // in the background.
1465 sp<IOProfile> profile;
1466 if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) ||
1467 !(mEffects.isNonOffloadableEffectEnabled() || mMasterMono)) {
1468 profile = getProfileForOutput(
1469 devices, config->sample_rate, config->format, config->channel_mask,
1470 flags, true /* directOnly */);
1471 }
1472
1473 if (profile == nullptr) {
1474 return NAME_NOT_FOUND;
1475 }
1476
1477 // exclusive outputs for MMAP and Offload are enforced by different session ids.
1478 for (size_t i = 0; i < mOutputs.size(); i++) {
1479 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
1480 if (!desc->isDuplicated() && (profile == desc->mProfile)) {
1481 // reuse direct output if currently open by the same client
1482 // and configured with same parameters
1483 if ((config->sample_rate == desc->getSamplingRate()) &&
1484 (config->format == desc->getFormat()) &&
1485 (config->channel_mask == desc->getChannelMask()) &&
1486 (session == desc->mDirectClientSession)) {
1487 desc->mDirectOpenCount++;
Eric Laurentfecbceb2021-02-09 14:46:43 +01001488 ALOGV("%s reusing direct output %d for session %d", __func__,
Eric Laurentc529cf62020-04-17 18:19:10 -07001489 mOutputs.keyAt(i), session);
1490 *output = mOutputs.keyAt(i);
1491 return NO_ERROR;
1492 }
1493 }
1494 }
1495
1496 if (!profile->canOpenNewIo()) {
1497 return NAME_NOT_FOUND;
1498 }
1499
1500 sp<SwAudioOutputDescriptor> outputDesc =
1501 new SwAudioOutputDescriptor(profile, mpClientInterface);
1502
Michael Chan6fb34492020-12-08 15:44:49 +11001503 // An MSD patch may be using the only output stream that can service this request. Release
1504 // all MSD patches to prioritize this request over any active output on MSD.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001505 releaseMsdOutputPatches(devices);
Eric Laurentc529cf62020-04-17 18:19:10 -07001506
Eric Laurentf1f22e72021-07-13 14:04:14 +02001507 status_t status =
1508 outputDesc->open(config, nullptr /* mixerConfig */, devices, stream, flags, output);
Eric Laurentc529cf62020-04-17 18:19:10 -07001509
1510 // only accept an output with the requested parameters
1511 if (status != NO_ERROR ||
1512 (config->sample_rate != 0 && config->sample_rate != outputDesc->getSamplingRate()) ||
1513 (config->format != AUDIO_FORMAT_DEFAULT && config->format != outputDesc->getFormat()) ||
1514 (config->channel_mask != 0 && config->channel_mask != outputDesc->getChannelMask())) {
1515 ALOGV("%s failed opening direct output: output %d sample rate %d %d,"
1516 "format %d %d, channel mask %04x %04x", __func__, *output, config->sample_rate,
1517 outputDesc->getSamplingRate(), config->format, outputDesc->getFormat(),
1518 config->channel_mask, outputDesc->getChannelMask());
1519 if (*output != AUDIO_IO_HANDLE_NONE) {
1520 outputDesc->close();
1521 }
1522 // fall back to mixer output if possible when the direct output could not be open
1523 if (audio_is_linear_pcm(config->format) &&
1524 config->sample_rate <= SAMPLE_RATE_HZ_MAX) {
1525 return NAME_NOT_FOUND;
1526 }
1527 *output = AUDIO_IO_HANDLE_NONE;
1528 return BAD_VALUE;
1529 }
1530 outputDesc->mDirectOpenCount = 1;
1531 outputDesc->mDirectClientSession = session;
1532
1533 addOutput(*output, outputDesc);
1534 mPreviousOutputs = mOutputs;
1535 ALOGV("%s returns new direct output %d", __func__, *output);
1536 mpClientInterface->onAudioPortListUpdate();
1537 return NO_ERROR;
1538}
1539
François Gaffie11d30102018-11-02 16:09:09 +01001540audio_io_handle_t AudioPolicyManager::getOutputForDevices(
1541 const DeviceVector &devices,
Kevin Rocard169753c2017-03-06 14:18:23 -08001542 audio_session_t session,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001543 const audio_attributes_t *attr,
Eric Laurentfe231122017-11-17 17:48:06 -08001544 const audio_config_t *config,
jiabine375d412019-02-26 12:54:53 -08001545 audio_output_flags_t *flags,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001546 bool *isSpatialized,
jiabina84c3d32022-12-02 18:59:55 +00001547 sp<PreferredMixerAttributesInfo> prefMixerConfigInfo,
jiabine375d412019-02-26 12:54:53 -08001548 bool forceMutingHaptic)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001549{
Andy Hungc88b0642018-04-27 15:42:35 -07001550 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001551
jiabine375d412019-02-26 12:54:53 -08001552 // Discard haptic channel mask when forcing muting haptic channels.
1553 audio_channel_mask_t channelMask = forceMutingHaptic
Mikhail Naganov55773032020-10-01 15:08:13 -07001554 ? static_cast<audio_channel_mask_t>(config->channel_mask & ~AUDIO_CHANNEL_HAPTIC_ALL)
1555 : config->channel_mask;
jiabine375d412019-02-26 12:54:53 -08001556
Eric Laurente552edb2014-03-10 17:42:56 -07001557 // open a direct output if required by specified parameters
1558 //force direct flag if offload flag is set: offloading implies a direct output stream
1559 // and all common behaviors are driven by checking only the direct flag
1560 // this should normally be set appropriately in the policy configuration file
Nadav Bar766fb022018-01-07 12:18:03 +02001561 if ((*flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1562 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurente552edb2014-03-10 17:42:56 -07001563 }
Nadav Bar766fb022018-01-07 12:18:03 +02001564 if ((*flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
1565 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent93c3d412014-08-01 14:48:35 -07001566 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001567
1568 audio_stream_type_t stream = mEngine->getStreamTypeForAttributes(*attr);
1569
Eric Laurente83b55d2014-11-14 10:06:21 -08001570 // only allow deep buffering for music stream type
1571 if (stream != AUDIO_STREAM_MUSIC) {
Nadav Bar766fb022018-01-07 12:18:03 +02001572 *flags = (audio_output_flags_t)(*flags &~AUDIO_OUTPUT_FLAG_DEEP_BUFFER);
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -07001573 } else if (/* stream == AUDIO_STREAM_MUSIC && */
Nadav Bar766fb022018-01-07 12:18:03 +02001574 *flags == AUDIO_OUTPUT_FLAG_NONE &&
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -07001575 property_get_bool("audio.deep_buffer.media", false /* default_value */)) {
1576 // use DEEP_BUFFER as default output for music stream type
Nadav Bar766fb022018-01-07 12:18:03 +02001577 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
Eric Laurente83b55d2014-11-14 10:06:21 -08001578 }
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -07001579 if (stream == AUDIO_STREAM_TTS) {
Nadav Bar766fb022018-01-07 12:18:03 +02001580 *flags = AUDIO_OUTPUT_FLAG_TTS;
Haynes Mathew George84c621e2017-04-25 11:41:50 -07001581 } else if (stream == AUDIO_STREAM_VOICE_CALL &&
Nadav Bar20919492018-11-20 10:20:51 +02001582 audio_is_linear_pcm(config->format) &&
1583 (*flags & AUDIO_OUTPUT_FLAG_INCALL_MUSIC) == 0) {
Nadav Bar766fb022018-01-07 12:18:03 +02001584 *flags = (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_VOIP_RX |
Haynes Mathew George84c621e2017-04-25 11:41:50 -07001585 AUDIO_OUTPUT_FLAG_DIRECT);
1586 ALOGV("Set VoIP and Direct output flags for PCM format");
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -07001587 }
Eric Laurente552edb2014-03-10 17:42:56 -07001588
Carter Hsua3abb402021-10-26 11:11:20 +08001589 // Attach the Ultrasound flag for the AUDIO_CONTENT_TYPE_ULTRASOUND
1590 if (attr->content_type == AUDIO_CONTENT_TYPE_ULTRASOUND) {
1591 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_ULTRASOUND);
1592 }
1593
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001594 *isSpatialized = false;
Eric Laurentfa0f6742021-08-17 18:39:44 +02001595 if (mSpatializerOutput != nullptr
Andy Hung9dd1a5b2022-05-10 15:39:39 -07001596 && canBeSpatializedInt(attr, config, devices.toTypeAddrVector())) {
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001597 *isSpatialized = true;
Eric Laurentfa0f6742021-08-17 18:39:44 +02001598 return mSpatializerOutput->mIoHandle;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001599 }
1600
Eric Laurentc529cf62020-04-17 18:19:10 -07001601 audio_config_t directConfig = *config;
1602 directConfig.channel_mask = channelMask;
1603 status_t status = openDirectOutput(stream, session, &directConfig, *flags, devices, &output);
1604 if (status != NAME_NOT_FOUND) {
Eric Laurente552edb2014-03-10 17:42:56 -07001605 return output;
1606 }
1607
Eric Laurent14cbfca2016-03-17 09:42:16 -07001608 // A request for HW A/V sync cannot fallback to a mixed output because time
1609 // stamps are embedded in audio data
Phil Burk2d059932018-02-15 15:55:11 -08001610 if ((*flags & (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ)) != 0) {
Eric Laurent14cbfca2016-03-17 09:42:16 -07001611 return AUDIO_IO_HANDLE_NONE;
1612 }
Pierre Couillaude73496b2023-03-06 16:19:05 +00001613 // A request for Tuner cannot fallback to a mixed output
1614 if ((directConfig.offload_info.content_id || directConfig.offload_info.sync_id)) {
1615 return AUDIO_IO_HANDLE_NONE;
1616 }
Eric Laurent14cbfca2016-03-17 09:42:16 -07001617
Eric Laurente552edb2014-03-10 17:42:56 -07001618 // ignoring channel mask due to downmix capability in mixer
1619
1620 // open a non direct output
1621
1622 // for non direct outputs, only PCM is supported
Eric Laurentfe231122017-11-17 17:48:06 -08001623 if (audio_is_linear_pcm(config->format)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001624 // get which output is suitable for the specified stream. The actual
1625 // routing change will happen when startOutput() will be called
François Gaffie11d30102018-11-02 16:09:09 +01001626 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
jiabina84c3d32022-12-02 18:59:55 +00001627 if (prefMixerConfigInfo != nullptr) {
1628 for (audio_io_handle_t outputHandle : outputs) {
1629 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(outputHandle);
1630 if (outputDesc->mProfile == prefMixerConfigInfo->getProfile()) {
1631 output = outputHandle;
1632 break;
1633 }
1634 }
1635 if (output == AUDIO_IO_HANDLE_NONE) {
1636 // No output open with the preferred profile. Open a new one.
1637 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
1638 config.channel_mask = prefMixerConfigInfo->getConfigBase().channel_mask;
1639 config.sample_rate = prefMixerConfigInfo->getConfigBase().sample_rate;
1640 config.format = prefMixerConfigInfo->getConfigBase().format;
1641 sp<SwAudioOutputDescriptor> preferredOutput = openOutputWithProfileAndDevice(
1642 prefMixerConfigInfo->getProfile(), devices, nullptr /*mixerConfig*/,
1643 &config, prefMixerConfigInfo->getFlags());
1644 if (preferredOutput == nullptr) {
1645 ALOGE("%s failed to open output with preferred mixer config", __func__);
1646 } else {
1647 output = preferredOutput->mIoHandle;
1648 }
1649 }
1650 } else {
1651 // at this stage we should ignore the DIRECT flag as no direct output could be
1652 // found earlier
1653 *flags = (audio_output_flags_t) (*flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
1654 output = selectOutput(
1655 outputs, *flags, config->format, channelMask, config->sample_rate, session);
1656 }
Eric Laurente552edb2014-03-10 17:42:56 -07001657 }
François Gaffie11d30102018-11-02 16:09:09 +01001658 ALOGW_IF((output == 0), "getOutputForDevices() could not find output for stream %d, "
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001659 "sampling rate %d, format %#x, channels %#x, flags %#x",
jiabine375d412019-02-26 12:54:53 -08001660 stream, config->sample_rate, config->format, channelMask, *flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001661
Eric Laurente552edb2014-03-10 17:42:56 -07001662 return output;
1663}
1664
Mikhail Naganovf02f3672018-11-09 12:44:16 -08001665sp<DeviceDescriptor> AudioPolicyManager::getMsdAudioInDevice() const {
François Gaffie11d30102018-11-02 16:09:09 +01001666 auto msdInDevices = mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1667 mAvailableInputDevices);
1668 return msdInDevices.isEmpty()? nullptr : msdInDevices.itemAt(0);
1669}
1670
1671DeviceVector AudioPolicyManager::getMsdAudioOutDevices() const {
1672 return mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1673 mAvailableOutputDevices);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001674}
1675
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001676const AudioPatchCollection AudioPolicyManager::getMsdOutputPatches() const {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001677 AudioPatchCollection msdPatches;
Mikhail Naganov86112352018-10-04 09:02:49 -07001678 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1679 if (msdModule != 0) {
1680 for (size_t i = 0; i < mAudioPatches.size(); ++i) {
1681 sp<AudioPatch> patch = mAudioPatches.valueAt(i);
1682 for (size_t j = 0; j < patch->mPatch.num_sources; ++j) {
1683 const struct audio_port_config *source = &patch->mPatch.sources[j];
1684 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
1685 source->ext.device.hw_module == msdModule->getHandle()) {
François Gaffieafd4cea2019-11-18 15:50:22 +01001686 msdPatches.addAudioPatch(patch->getHandle(), patch);
Mikhail Naganov86112352018-10-04 09:02:49 -07001687 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001688 }
1689 }
1690 }
1691 return msdPatches;
1692}
1693
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02001694bool AudioPolicyManager::isMsdPatch(const audio_patch_handle_t &handle) const {
1695 ssize_t index = mAudioPatches.indexOfKey(handle);
1696 if (index < 0) {
1697 return false;
1698 }
1699 const sp<AudioPatch> patch = mAudioPatches.valueAt(index);
1700 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1701 if (msdModule == nullptr) {
1702 return false;
1703 }
1704 const struct audio_port_config *sink = &patch->mPatch.sinks[0];
1705 if (getMsdAudioOutDevices().contains(mAvailableOutputDevices.getDeviceFromId(sink->id))) {
1706 return true;
1707 }
1708 index = getMsdOutputPatches().indexOfKey(handle);
1709 if (index < 0) {
1710 return false;
1711 }
1712 return true;
1713}
1714
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001715status_t AudioPolicyManager::getMsdProfiles(bool hwAvSync,
1716 const InputProfileCollection &inputProfiles,
1717 const OutputProfileCollection &outputProfiles,
1718 const sp<DeviceDescriptor> &sourceDevice,
1719 const sp<DeviceDescriptor> &sinkDevice,
1720 AudioProfileVector& sourceProfiles,
1721 AudioProfileVector& sinkProfiles) const {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001722 if (inputProfiles.isEmpty()) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001723 ALOGE("%s() no input profiles for source module", __func__);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001724 return NO_INIT;
1725 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001726 if (outputProfiles.isEmpty()) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001727 ALOGE("%s() no output profiles for sink module", __func__);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001728 return NO_INIT;
1729 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001730 for (const auto &inProfile : inputProfiles) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001731 if (hwAvSync == ((inProfile->getFlags() & AUDIO_INPUT_FLAG_HW_AV_SYNC) != 0) &&
1732 inProfile->supportsDevice(sourceDevice)) {
1733 appendAudioProfiles(sourceProfiles, inProfile->getAudioProfiles());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001734 }
1735 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001736 for (const auto &outProfile : outputProfiles) {
Michael Chan6fb34492020-12-08 15:44:49 +11001737 if (hwAvSync == ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) &&
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001738 outProfile->supportsDevice(sinkDevice)) {
1739 appendAudioProfiles(sinkProfiles, outProfile->getAudioProfiles());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001740 }
1741 }
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001742 return NO_ERROR;
1743}
1744
1745status_t AudioPolicyManager::getBestMsdConfig(bool hwAvSync,
1746 const AudioProfileVector &sourceProfiles, const AudioProfileVector &sinkProfiles,
1747 audio_port_config *sourceConfig, audio_port_config *sinkConfig) const
1748{
Dean Wheatley16809da2022-12-09 14:55:46 +11001749 // Compressed formats for MSD module, ordered from most preferred to least preferred.
1750 static const std::vector<audio_format_t> formatsOrder = {{
1751 AUDIO_FORMAT_IEC60958, AUDIO_FORMAT_MAT_2_1, AUDIO_FORMAT_MAT_2_0, AUDIO_FORMAT_E_AC3,
Dean Wheatley0f27c602023-08-23 13:57:21 +10001752 AUDIO_FORMAT_AC3, AUDIO_FORMAT_PCM_FLOAT, AUDIO_FORMAT_PCM_32_BIT,
1753 AUDIO_FORMAT_PCM_8_24_BIT, AUDIO_FORMAT_PCM_24_BIT_PACKED, AUDIO_FORMAT_PCM_16_BIT }};
Dean Wheatley16809da2022-12-09 14:55:46 +11001754 static const std::vector<audio_channel_mask_t> channelMasksOrder = [](){
1755 // Channel position masks for MSD module, 3D > 2D > 1D ordering (most preferred to least
1756 // preferred).
1757 std::vector<audio_channel_mask_t> masks = {{
1758 AUDIO_CHANNEL_OUT_3POINT1POINT2, AUDIO_CHANNEL_OUT_3POINT0POINT2,
1759 AUDIO_CHANNEL_OUT_2POINT1POINT2, AUDIO_CHANNEL_OUT_2POINT0POINT2,
1760 AUDIO_CHANNEL_OUT_5POINT1, AUDIO_CHANNEL_OUT_STEREO }};
1761 // insert index masks (higher counts most preferred) as preferred over position masks
1762 for (int i = 1; i <= AUDIO_CHANNEL_COUNT_MAX; i++) {
1763 masks.insert(
1764 masks.begin(), audio_channel_mask_for_index_assignment_from_count(i));
1765 }
1766 return masks;
1767 }();
1768
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001769 struct audio_config_base bestSinkConfig;
Dean Wheatley16809da2022-12-09 14:55:46 +11001770 status_t result = findBestMatchingOutputConfig(sourceProfiles, sinkProfiles, formatsOrder,
1771 channelMasksOrder, true /*preferHigherSamplingRates*/, bestSinkConfig);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001772 if (result != NO_ERROR) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001773 ALOGD("%s() no matching config found for sink, hwAvSync: %d",
1774 __func__, hwAvSync);
Greg Kaiser83289652018-07-30 06:13:57 -07001775 return result;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001776 }
1777 sinkConfig->sample_rate = bestSinkConfig.sample_rate;
1778 sinkConfig->channel_mask = bestSinkConfig.channel_mask;
1779 sinkConfig->format = bestSinkConfig.format;
1780 // For encoded streams force direct flag to prevent downstream mixing.
1781 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1782 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_DIRECT);
Dean Wheatley5c9f0832019-11-21 13:39:31 +11001783 if (audio_is_iec61937_compatible(sinkConfig->format)) {
1784 // For formats compatible with IEC61937 encapsulation, assume that
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001785 // the input is IEC61937 framed (for proportional buffer sizing).
Dean Wheatley5c9f0832019-11-21 13:39:31 +11001786 // Add the AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO flag so downstream HAL can distinguish between
1787 // raw and IEC61937 framed streams.
1788 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1789 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO);
1790 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001791 sourceConfig->sample_rate = bestSinkConfig.sample_rate;
1792 // Specify exact channel mask to prevent guessing by bit count in PatchPanel.
Dean Wheatley16809da2022-12-09 14:55:46 +11001793 sourceConfig->channel_mask =
1794 audio_channel_mask_get_representation(bestSinkConfig.channel_mask)
1795 == AUDIO_CHANNEL_REPRESENTATION_INDEX ?
1796 bestSinkConfig.channel_mask : audio_channel_mask_out_to_in(bestSinkConfig.channel_mask);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001797 sourceConfig->format = bestSinkConfig.format;
1798 // Copy input stream directly without any processing (e.g. resampling).
1799 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1800 sourceConfig->flags.input | AUDIO_INPUT_FLAG_DIRECT);
1801 if (hwAvSync) {
1802 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1803 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
1804 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1805 sourceConfig->flags.input | AUDIO_INPUT_FLAG_HW_AV_SYNC);
1806 }
1807 const unsigned int config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE |
1808 AUDIO_PORT_CONFIG_CHANNEL_MASK | AUDIO_PORT_CONFIG_FORMAT | AUDIO_PORT_CONFIG_FLAGS;
1809 sinkConfig->config_mask |= config_mask;
1810 sourceConfig->config_mask |= config_mask;
1811 return NO_ERROR;
1812}
1813
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001814PatchBuilder AudioPolicyManager::buildMsdPatch(bool msdIsSource,
1815 const sp<DeviceDescriptor> &device) const
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001816{
1817 PatchBuilder patchBuilder;
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001818 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1819 ALOG_ASSERT(msdModule != nullptr, "MSD module not available");
1820 sp<HwModule> deviceModule = mHwModules.getModuleForDevice(device, AUDIO_FORMAT_DEFAULT);
1821 if (deviceModule == nullptr) {
1822 ALOGE("%s() unable to get module for %s", __func__, device->toString().c_str());
1823 return patchBuilder;
1824 }
1825 const InputProfileCollection inputProfiles = msdIsSource ?
1826 msdModule->getInputProfiles() : deviceModule->getInputProfiles();
1827 const OutputProfileCollection outputProfiles = msdIsSource ?
1828 deviceModule->getOutputProfiles() : msdModule->getOutputProfiles();
1829
1830 const sp<DeviceDescriptor> sourceDevice = msdIsSource ? getMsdAudioInDevice() : device;
1831 const sp<DeviceDescriptor> sinkDevice = msdIsSource ?
1832 device : getMsdAudioOutDevices().itemAt(0);
1833 patchBuilder.addSource(sourceDevice).addSink(sinkDevice);
1834
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001835 audio_port_config sourceConfig = patchBuilder.patch()->sources[0];
1836 audio_port_config sinkConfig = patchBuilder.patch()->sinks[0];
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001837 AudioProfileVector sourceProfiles;
1838 AudioProfileVector sinkProfiles;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001839 // TODO: Figure out whether MSD module has HW_AV_SYNC flag set in the AP config file.
1840 // For now, we just forcefully try with HwAvSync first.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001841 for (auto hwAvSync : { true, false }) {
1842 if (getMsdProfiles(hwAvSync, inputProfiles, outputProfiles, sourceDevice, sinkDevice,
1843 sourceProfiles, sinkProfiles) != NO_ERROR) {
1844 continue;
1845 }
1846 if (getBestMsdConfig(hwAvSync, sourceProfiles, sinkProfiles, &sourceConfig,
1847 &sinkConfig) == NO_ERROR) {
1848 // Found a matching config. Re-create PatchBuilder with this config.
1849 return (PatchBuilder()).addSource(sourceConfig).addSink(sinkConfig);
1850 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001851 }
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001852 ALOGV("%s() no matching config found. Fall through to default PCM patch"
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001853 " supporting PCM format conversion.", __func__);
1854 return patchBuilder;
1855}
1856
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001857status_t AudioPolicyManager::setMsdOutputPatches(const DeviceVector *outputDevices) {
Michael Chan6fb34492020-12-08 15:44:49 +11001858 DeviceVector devices;
1859 if (outputDevices != nullptr && outputDevices->size() > 0) {
1860 devices.add(*outputDevices);
1861 } else {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001862 // Use media strategy for unspecified output device. This should only
1863 // occur on checkForDeviceAndOutputChanges(). Device connection events may
1864 // therefore invalidate explicit routing requests.
Michael Chan6fb34492020-12-08 15:44:49 +11001865 devices = mEngine->getOutputDevicesForAttributes(
François Gaffiec005e562018-11-06 15:04:49 +01001866 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
Michael Chan6fb34492020-12-08 15:44:49 +11001867 LOG_ALWAYS_FATAL_IF(devices.isEmpty(), "no output device to set MSD patch");
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001868 }
Michael Chan6fb34492020-12-08 15:44:49 +11001869 std::vector<PatchBuilder> patchesToCreate;
1870 for (auto i = 0u; i < devices.size(); ++i) {
1871 ALOGV("%s() for device %s", __func__, devices[i]->toString().c_str());
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001872 patchesToCreate.push_back(buildMsdPatch(true /*msdIsSource*/, devices[i]));
Michael Chan6fb34492020-12-08 15:44:49 +11001873 }
1874 // Retain only the MSD patches associated with outputDevices request.
1875 // Tear down the others, and create new ones as needed.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001876 AudioPatchCollection patchesToRemove = getMsdOutputPatches();
Michael Chan6fb34492020-12-08 15:44:49 +11001877 for (auto it = patchesToCreate.begin(); it != patchesToCreate.end(); ) {
1878 auto retainedPatch = false;
1879 for (auto i = 0u; i < patchesToRemove.size(); ++i) {
1880 if (audio_patches_are_equal(it->patch(), &patchesToRemove[i]->mPatch)) {
1881 patchesToRemove.removeItemsAt(i);
1882 retainedPatch = true;
1883 break;
1884 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001885 }
Michael Chan6fb34492020-12-08 15:44:49 +11001886 if (retainedPatch) {
1887 it = patchesToCreate.erase(it);
1888 continue;
1889 }
1890 ++it;
1891 }
1892 if (patchesToCreate.size() == 0 && patchesToRemove.size() == 0) {
1893 return NO_ERROR;
1894 }
1895 for (auto i = 0u; i < patchesToRemove.size(); ++i) {
1896 auto &currentPatch = patchesToRemove.valueAt(i);
François Gaffieafd4cea2019-11-18 15:50:22 +01001897 releaseAudioPatch(currentPatch->getHandle(), mUidCached);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001898 }
Michael Chan6fb34492020-12-08 15:44:49 +11001899 status_t status = NO_ERROR;
1900 for (const auto &p : patchesToCreate) {
1901 auto currStatus = installPatch(__func__, -1 /*index*/, nullptr /*patchHandle*/,
1902 p.patch(), 0 /*delayMs*/, mUidCached, nullptr /*patchDescPtr*/);
1903 char message[256];
1904 snprintf(message, sizeof(message), "%s() %s: creating MSD patch from device:IN_BUS to "
1905 "device:%#x (format:%#x channels:%#x samplerate:%d)", __func__,
1906 currStatus == NO_ERROR ? "Success" : "Error",
1907 p.patch()->sinks[0].ext.device.type, p.patch()->sources[0].format,
1908 p.patch()->sources[0].channel_mask, p.patch()->sources[0].sample_rate);
1909 if (currStatus == NO_ERROR) {
1910 ALOGD("%s", message);
1911 } else {
1912 ALOGE("%s", message);
1913 if (status == NO_ERROR) {
1914 status = currStatus;
1915 }
1916 }
1917 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001918 return status;
1919}
1920
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001921void AudioPolicyManager::releaseMsdOutputPatches(const DeviceVector& devices) {
1922 AudioPatchCollection msdPatches = getMsdOutputPatches();
Michael Chan6fb34492020-12-08 15:44:49 +11001923 for (size_t i = 0; i < msdPatches.size(); i++) {
1924 const auto& patch = msdPatches[i];
1925 for (size_t j = 0; j < patch->mPatch.num_sinks; ++j) {
1926 const struct audio_port_config *sink = &patch->mPatch.sinks[j];
1927 if (sink->type == AUDIO_PORT_TYPE_DEVICE && devices.getDevice(sink->ext.device.type,
1928 String8(sink->ext.device.address), AUDIO_FORMAT_DEFAULT) != nullptr) {
1929 releaseAudioPatch(patch->getHandle(), mUidCached);
1930 break;
1931 }
1932 }
1933 }
1934}
1935
Dorin Drimus94d94412022-02-02 09:05:02 +01001936bool AudioPolicyManager::msdHasPatchesToAllDevices(const AudioDeviceTypeAddrVector& devices) {
Mikhail Naganov68e3f642023-04-28 13:06:32 -07001937 DeviceVector devicesToCheck =
1938 mConfig->getOutputDevices().getDevicesFromDeviceTypeAddrVec(devices);
Dorin Drimus94d94412022-02-02 09:05:02 +01001939 AudioPatchCollection msdPatches = getMsdOutputPatches();
1940 for (size_t i = 0; i < msdPatches.size(); i++) {
1941 const auto& patch = msdPatches[i];
1942 for (size_t j = 0; j < patch->mPatch.num_sinks; ++j) {
1943 const struct audio_port_config *sink = &patch->mPatch.sinks[j];
1944 if (sink->type == AUDIO_PORT_TYPE_DEVICE) {
1945 const auto& foundDevice = devicesToCheck.getDevice(
1946 sink->ext.device.type, String8(sink->ext.device.address), AUDIO_FORMAT_DEFAULT);
1947 if (foundDevice != nullptr) {
1948 devicesToCheck.remove(foundDevice);
1949 if (devicesToCheck.isEmpty()) {
1950 return true;
1951 }
1952 }
1953 }
1954 }
1955 }
1956 return false;
1957}
1958
Eric Laurente0720872014-03-11 09:30:41 -07001959audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
jiabinebb6af42020-06-09 17:31:17 -07001960 audio_output_flags_t flags,
1961 audio_format_t format,
1962 audio_channel_mask_t channelMask,
1963 uint32_t samplingRate,
1964 audio_session_t sessionId)
Eric Laurente552edb2014-03-10 17:42:56 -07001965{
Eric Laurent16c66dd2019-05-01 17:54:10 -07001966 LOG_ALWAYS_FATAL_IF(!(format == AUDIO_FORMAT_INVALID || audio_is_linear_pcm(format)),
1967 "%s called with format %#x", __func__, format);
1968
jiabinebb6af42020-06-09 17:31:17 -07001969 // Return the output that haptic-generating attached to when 1) session id is specified,
1970 // 2) haptic-generating effect exists for given session id and 3) the output that
1971 // haptic-generating effect attached to is in given outputs.
1972 if (sessionId != AUDIO_SESSION_NONE) {
1973 audio_io_handle_t hapticGeneratingOutput = mEffects.getIoForSession(
1974 sessionId, FX_IID_HAPTICGENERATOR);
1975 if (outputs.indexOf(hapticGeneratingOutput) >= 0) {
1976 return hapticGeneratingOutput;
1977 }
1978 }
1979
Eric Laurent16c66dd2019-05-01 17:54:10 -07001980 // Flags disqualifying an output: the match must happen before calling selectOutput()
1981 static const audio_output_flags_t kExcludedFlags = (audio_output_flags_t)
1982 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ | AUDIO_OUTPUT_FLAG_DIRECT);
1983
1984 // Flags expressing a functional request: must be honored in priority over
1985 // other criteria
1986 static const audio_output_flags_t kFunctionalFlags = (audio_output_flags_t)
1987 (AUDIO_OUTPUT_FLAG_VOIP_RX | AUDIO_OUTPUT_FLAG_INCALL_MUSIC |
Eric Laurente28c66d2022-01-21 13:40:41 +01001988 AUDIO_OUTPUT_FLAG_TTS | AUDIO_OUTPUT_FLAG_DIRECT_PCM | AUDIO_OUTPUT_FLAG_ULTRASOUND |
1989 AUDIO_OUTPUT_FLAG_SPATIALIZER);
Eric Laurent16c66dd2019-05-01 17:54:10 -07001990 // Flags expressing a performance request: have lower priority than serving
1991 // requested sampling rate or channel mask
1992 static const audio_output_flags_t kPerformanceFlags = (audio_output_flags_t)
1993 (AUDIO_OUTPUT_FLAG_FAST | AUDIO_OUTPUT_FLAG_DEEP_BUFFER |
1994 AUDIO_OUTPUT_FLAG_RAW | AUDIO_OUTPUT_FLAG_SYNC);
1995
1996 const audio_output_flags_t functionalFlags =
1997 (audio_output_flags_t)(flags & kFunctionalFlags);
1998 const audio_output_flags_t performanceFlags =
1999 (audio_output_flags_t)(flags & kPerformanceFlags);
2000
2001 audio_io_handle_t bestOutput = (outputs.size() == 0) ? AUDIO_IO_HANDLE_NONE : outputs[0];
2002
Eric Laurente552edb2014-03-10 17:42:56 -07002003 // select one output among several that provide a path to a particular device or set of
François Gaffie11d30102018-11-02 16:09:09 +01002004 // devices (the list was previously build by getOutputsForDevices()).
Eric Laurente552edb2014-03-10 17:42:56 -07002005 // The priority is as follows:
jiabin40573322018-11-08 12:08:02 -08002006 // 1: the output supporting haptic playback when requesting haptic playback
Eric Laurent16c66dd2019-05-01 17:54:10 -07002007 // 2: the output with the highest number of requested functional flags
Carter Hsu199f1892021-10-15 15:47:29 +08002008 // with tiebreak preferring the minimum number of extra functional flags
2009 // (see b/200293124, the incorrect selection of AUDIO_OUTPUT_FLAG_VOIP_RX).
Eric Laurent16c66dd2019-05-01 17:54:10 -07002010 // 3: the output supporting the exact channel mask
2011 // 4: the output with a higher channel count than requested
jiabinb12a6da2022-06-03 20:48:18 +00002012 // 5: the output with the highest sampling rate if the requested sample rate is
2013 // greater than default sampling rate
Eric Laurent16c66dd2019-05-01 17:54:10 -07002014 // 6: the output with the highest number of requested performance flags
2015 // 7: the output with the bit depth the closest to the requested one
2016 // 8: the primary output
2017 // 9: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07002018
Eric Laurent16c66dd2019-05-01 17:54:10 -07002019 // matching criteria values in priority order for best matching output so far
2020 std::vector<uint32_t> bestMatchCriteria(8, 0);
Eric Laurente552edb2014-03-10 17:42:56 -07002021
Eric Laurent16c66dd2019-05-01 17:54:10 -07002022 const uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
2023 const uint32_t hapticChannelCount = audio_channel_count_from_out_mask(
2024 channelMask & AUDIO_CHANNEL_HAPTIC_ALL);
Eric Laurente78b6762018-12-19 16:29:01 -08002025
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002026 for (audio_io_handle_t output : outputs) {
2027 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent16c66dd2019-05-01 17:54:10 -07002028 // matching criteria values in priority order for current output
2029 std::vector<uint32_t> currentMatchCriteria(8, 0);
jiabin40573322018-11-08 12:08:02 -08002030
Eric Laurent16c66dd2019-05-01 17:54:10 -07002031 if (outputDesc->isDuplicated()) {
2032 continue;
2033 }
2034 if ((kExcludedFlags & outputDesc->mFlags) != 0) {
2035 continue;
2036 }
Eric Laurent8838a382014-09-08 16:44:28 -07002037
Eric Laurent16c66dd2019-05-01 17:54:10 -07002038 // If haptic channel is specified, use the haptic output if present.
2039 // When using haptic output, same audio format and sample rate are required.
2040 const uint32_t outputHapticChannelCount = audio_channel_count_from_out_mask(
jiabin5740f082019-08-19 15:08:30 -07002041 outputDesc->getChannelMask() & AUDIO_CHANNEL_HAPTIC_ALL);
Eric Laurent16c66dd2019-05-01 17:54:10 -07002042 if ((hapticChannelCount == 0) != (outputHapticChannelCount == 0)) {
2043 continue;
2044 }
2045 if (outputHapticChannelCount >= hapticChannelCount
jiabin5740f082019-08-19 15:08:30 -07002046 && format == outputDesc->getFormat()
2047 && samplingRate == outputDesc->getSamplingRate()) {
Eric Laurent16c66dd2019-05-01 17:54:10 -07002048 currentMatchCriteria[0] = outputHapticChannelCount;
2049 }
2050
2051 // functional flags match
Carter Hsu199f1892021-10-15 15:47:29 +08002052 const int matchingFunctionalFlags =
2053 __builtin_popcount(outputDesc->mFlags & functionalFlags);
2054 const int totalFunctionalFlags =
2055 __builtin_popcount(outputDesc->mFlags & kFunctionalFlags);
2056 // Prefer matching functional flags, but subtract unnecessary functional flags.
2057 currentMatchCriteria[1] = 100 * (matchingFunctionalFlags + 1) - totalFunctionalFlags;
Eric Laurent16c66dd2019-05-01 17:54:10 -07002058
2059 // channel mask and channel count match
jiabin5740f082019-08-19 15:08:30 -07002060 uint32_t outputChannelCount = audio_channel_count_from_out_mask(
2061 outputDesc->getChannelMask());
Eric Laurent16c66dd2019-05-01 17:54:10 -07002062 if (channelMask != AUDIO_CHANNEL_NONE && channelCount > 2 &&
2063 channelCount <= outputChannelCount) {
2064 if ((audio_channel_mask_get_representation(channelMask) ==
jiabin5740f082019-08-19 15:08:30 -07002065 audio_channel_mask_get_representation(outputDesc->getChannelMask())) &&
2066 ((channelMask & outputDesc->getChannelMask()) == channelMask)) {
Eric Laurent16c66dd2019-05-01 17:54:10 -07002067 currentMatchCriteria[2] = outputChannelCount;
Eric Laurente552edb2014-03-10 17:42:56 -07002068 }
Eric Laurent16c66dd2019-05-01 17:54:10 -07002069 currentMatchCriteria[3] = outputChannelCount;
2070 }
2071
2072 // sampling rate match
jiabinb12a6da2022-06-03 20:48:18 +00002073 if (samplingRate > SAMPLE_RATE_HZ_DEFAULT) {
jiabin5740f082019-08-19 15:08:30 -07002074 currentMatchCriteria[4] = outputDesc->getSamplingRate();
Eric Laurent16c66dd2019-05-01 17:54:10 -07002075 }
2076
2077 // performance flags match
2078 currentMatchCriteria[5] = popcount(outputDesc->mFlags & performanceFlags);
2079
2080 // format match
2081 if (format != AUDIO_FORMAT_INVALID) {
2082 currentMatchCriteria[6] =
jiabin4ef93452019-09-10 14:29:54 -07002083 PolicyAudioPort::kFormatDistanceMax -
2084 PolicyAudioPort::formatDistance(format, outputDesc->getFormat());
Eric Laurent16c66dd2019-05-01 17:54:10 -07002085 }
2086
2087 // primary output match
2088 currentMatchCriteria[7] = outputDesc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY;
2089
2090 // compare match criteria by priority then value
2091 if (std::lexicographical_compare(bestMatchCriteria.begin(), bestMatchCriteria.end(),
2092 currentMatchCriteria.begin(), currentMatchCriteria.end())) {
2093 bestMatchCriteria = currentMatchCriteria;
2094 bestOutput = output;
2095
2096 std::stringstream result;
2097 std::copy(bestMatchCriteria.begin(), bestMatchCriteria.end(),
2098 std::ostream_iterator<int>(result, " "));
2099 ALOGV("%s new bestOutput %d criteria %s",
2100 __func__, bestOutput, result.str().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07002101 }
2102 }
2103
Eric Laurent16c66dd2019-05-01 17:54:10 -07002104 return bestOutput;
Eric Laurente552edb2014-03-10 17:42:56 -07002105}
2106
Eric Laurent8fc147b2018-07-22 19:13:55 -07002107status_t AudioPolicyManager::startOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002108{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002109 ALOGV("%s portId %d", __FUNCTION__, portId);
2110
2111 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2112 if (outputDesc == 0) {
2113 ALOGW("startOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002114 return BAD_VALUE;
2115 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002116 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002117
Eric Laurent8fc147b2018-07-22 19:13:55 -07002118 ALOGV("startOutput() output %d, stream %d, session %d",
Eric Laurent97ac8712018-07-27 18:59:02 -07002119 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurentc75307b2015-03-17 15:29:32 -07002120
Eric Laurent733ce942017-12-07 12:18:25 -08002121 status_t status = outputDesc->start();
2122 if (status != NO_ERROR) {
2123 return status;
Eric Laurent3974e3b2017-12-07 17:58:43 -08002124 }
2125
Eric Laurent97ac8712018-07-27 18:59:02 -07002126 uint32_t delayMs;
2127 status = startSource(outputDesc, client, &delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07002128
2129 if (status != NO_ERROR) {
Eric Laurent733ce942017-12-07 12:18:25 -08002130 outputDesc->stop();
jiabin3ff8d7d2022-12-13 06:27:44 +00002131 if (status == DEAD_OBJECT) {
2132 sp<SwAudioOutputDescriptor> desc =
2133 reopenOutput(outputDesc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
2134 if (desc == nullptr) {
2135 // This is not common, it may indicate something wrong with the HAL.
2136 ALOGE("%s unable to open output with default config", __func__);
2137 return status;
2138 }
2139 desc->mUsePreferredMixerAttributes = true;
2140 }
Eric Laurent8c7e6da2015-04-21 17:37:00 -07002141 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07002142 }
jiabina84c3d32022-12-02 18:59:55 +00002143
2144 // If the client is the first one active on preferred mixer parameters, reopen the output
2145 // if the current mixer parameters doesn't match the preferred one.
2146 if (outputDesc->devices().size() == 1) {
2147 sp<PreferredMixerAttributesInfo> info = getPreferredMixerAttributesInfo(
2148 outputDesc->devices()[0]->getId(), client->strategy());
2149 if (info != nullptr && info->getUid() == client->uid()) {
2150 if (info->getActiveClientCount() == 0 && !outputDesc->isConfigurationMatched(
2151 info->getConfigBase(), info->getFlags())) {
2152 stopSource(outputDesc, client);
2153 outputDesc->stop();
2154 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
2155 config.channel_mask = info->getConfigBase().channel_mask;
2156 config.sample_rate = info->getConfigBase().sample_rate;
2157 config.format = info->getConfigBase().format;
jiabin3ff8d7d2022-12-13 06:27:44 +00002158 sp<SwAudioOutputDescriptor> desc =
2159 reopenOutput(outputDesc, &config, info->getFlags(), __func__);
2160 if (desc == nullptr) {
2161 return BAD_VALUE;
jiabina84c3d32022-12-02 18:59:55 +00002162 }
jiabin3ff8d7d2022-12-13 06:27:44 +00002163 desc->mUsePreferredMixerAttributes = true;
jiabina84c3d32022-12-02 18:59:55 +00002164 // Intentionally return error to let the client side resending request for
2165 // creating and starting.
2166 return DEAD_OBJECT;
2167 }
2168 info->increaseActiveClient();
jiabine3d1f552023-06-14 17:42:17 +00002169 if (info->getActiveClientCount() == 1 &&
2170 (info->getFlags() & AUDIO_OUTPUT_FLAG_BIT_PERFECT) != AUDIO_OUTPUT_FLAG_NONE) {
2171 // If it is first bit-perfect client, reroute all clients that will be routed to
2172 // the bit-perfect sink so that it is guaranteed only bit-perfect stream is active.
2173 PortHandleVector clientsToInvalidate;
2174 for (size_t i = 0; i < mOutputs.size(); i++) {
2175 if (mOutputs[i] == outputDesc ||
jiabin98c519c2023-07-05 17:34:21 +00002176 mOutputs[i]->devices().filter(outputDesc->devices()).isEmpty()) {
jiabine3d1f552023-06-14 17:42:17 +00002177 continue;
2178 }
2179 for (const auto& c : mOutputs[i]->getClientIterable()) {
2180 clientsToInvalidate.push_back(c->portId());
2181 }
2182 }
2183 if (!clientsToInvalidate.empty()) {
2184 ALOGD("%s Invalidate clients due to first bit-perfect client started",
2185 __func__);
2186 mpClientInterface->invalidateTracks(clientsToInvalidate);
2187 }
2188 }
jiabina84c3d32022-12-02 18:59:55 +00002189 }
2190 }
2191
Jean-Michel Trivib1f6e642023-02-07 20:49:04 +00002192 if (client->hasPreferredDevice()) {
2193 // playback activity with preferred device impacts routing occurred, inform upper layers
2194 mpClientInterface->onRoutingUpdated();
2195 }
Eric Laurentc75307b2015-03-17 15:29:32 -07002196 if (delayMs != 0) {
2197 usleep(delayMs * 1000);
2198 }
2199
2200 return status;
2201}
2202
Eric Laurent96d1dda2022-03-14 17:14:19 +01002203bool AudioPolicyManager::isLeUnicastActive() const {
2204 if (isInCall()) {
2205 return true;
2206 }
2207 return isAnyDeviceTypeActive(getAudioDeviceOutLeAudioUnicastSet());
2208}
2209
2210bool AudioPolicyManager::isAnyDeviceTypeActive(const DeviceTypeSet& deviceTypes) const {
2211 if (mAvailableOutputDevices.getDevicesFromTypes(deviceTypes).isEmpty()) {
2212 return false;
2213 }
2214 bool active = mOutputs.isAnyDeviceTypeActive(deviceTypes);
2215 ALOGV("%s active %d", __func__, active);
2216 return active;
2217}
2218
Eric Laurent97ac8712018-07-27 18:59:02 -07002219status_t AudioPolicyManager::startSource(const sp<SwAudioOutputDescriptor>& outputDesc,
2220 const sp<TrackClientDescriptor>& client,
2221 uint32_t *delayMs)
Eric Laurentc75307b2015-03-17 15:29:32 -07002222{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002223 // cannot start playback of STREAM_TTS if any other output is being used
2224 uint32_t beaconMuteLatency = 0;
Eric Laurentc75307b2015-03-17 15:29:32 -07002225
2226 *delayMs = 0;
Eric Laurent97ac8712018-07-27 18:59:02 -07002227 audio_stream_type_t stream = client->stream();
François Gaffie1c878552018-11-22 16:53:21 +01002228 auto clientVolSrc = client->volumeSource();
François Gaffiec005e562018-11-06 15:04:49 +01002229 auto clientStrategy = client->strategy();
2230 auto clientAttr = client->attributes();
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002231 if (stream == AUDIO_STREAM_TTS) {
2232 ALOGV("\t found BEACON stream");
François Gaffie1c878552018-11-22 16:53:21 +01002233 if (!mTtsOutputAvailable && mOutputs.isAnyOutputActive(
Francois Gaffie4404ddb2021-02-04 17:03:38 +01002234 toVolumeSource(AUDIO_STREAM_TTS, false) /*sourceToIgnore*/)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002235 return INVALID_OPERATION;
2236 } else {
2237 beaconMuteLatency = handleEventForBeacon(STARTING_BEACON);
2238 }
2239 } else {
2240 // some playback other than beacon starts
2241 beaconMuteLatency = handleEventForBeacon(STARTING_OUTPUT);
2242 }
2243
Eric Laurent77305a62016-07-25 16:39:22 -07002244 // force device change if the output is inactive and no audio patch is already present.
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002245 // check active before incrementing usage count
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02002246 bool force = !outputDesc->isActive() && !outputDesc->isRouted();
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002247
François Gaffie11d30102018-11-02 16:09:09 +01002248 DeviceVector devices;
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002249 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
Eric Laurent97ac8712018-07-27 18:59:02 -07002250 const char *address = NULL;
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002251 if (policyMix != nullptr) {
François Gaffie11d30102018-11-02 16:09:09 +01002252 audio_devices_t newDeviceType;
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00002253 address = policyMix->mDeviceAddress.c_str();
Kevin Rocard153f92d2018-12-18 18:33:28 -08002254 if ((policyMix->mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie11d30102018-11-02 16:09:09 +01002255 newDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Kevin Rocard153f92d2018-12-18 18:33:28 -08002256 } else {
2257 newDeviceType = policyMix->mDeviceType;
Eric Laurent97ac8712018-07-27 18:59:02 -07002258 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08002259 sp device = mAvailableOutputDevices.getDevice(newDeviceType, String8(address),
2260 AUDIO_FORMAT_DEFAULT);
2261 ALOG_ASSERT(device, "%s: no device found t=%u, a=%s", __func__, newDeviceType, address);
2262 devices.add(device);
Eric Laurent97ac8712018-07-27 18:59:02 -07002263 }
2264
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002265 // requiresMuteCheck is false when we can bypass mute strategy.
2266 // It covers a common case when there is no materially active audio
2267 // and muting would result in unnecessary delay and dropped audio.
2268 const uint32_t outputLatencyMs = outputDesc->latency();
2269 bool requiresMuteCheck = outputDesc->isActive(outputLatencyMs * 2); // account for drain
Eric Laurent96d1dda2022-03-14 17:14:19 +01002270 bool wasLeUnicastActive = isLeUnicastActive();
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002271
Eric Laurente552edb2014-03-10 17:42:56 -07002272 // increment usage count for this stream on the requested output:
2273 // NOTE that the usage count is the same for duplicated output and hardware output which is
2274 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
Eric Laurent592dd7b2018-08-05 18:58:48 -07002275 outputDesc->setClientActive(client, true);
Eric Laurent97ac8712018-07-27 18:59:02 -07002276
2277 if (client->hasPreferredDevice(true)) {
Eric Laurent72af8012023-03-15 17:36:22 +01002278 if (outputDesc->sameExclusivePreferredDevicesCount() > 0) {
François Gaffief96e5432019-04-09 17:13:56 +02002279 // Preferred device may be exclusive, use only if no other active clients on this output
2280 devices = DeviceVector(
2281 mAvailableOutputDevices.getDeviceFromId(client->preferredDeviceId()));
2282 } else {
2283 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
2284 }
François Gaffie11d30102018-11-02 16:09:09 +01002285 if (devices != outputDesc->devices()) {
François Gaffiec005e562018-11-06 15:04:49 +01002286 checkStrategyRoute(clientStrategy, outputDesc->mIoHandle);
Eric Laurent97ac8712018-07-27 18:59:02 -07002287 }
2288 }
Eric Laurente552edb2014-03-10 17:42:56 -07002289
François Gaffiec005e562018-11-06 15:04:49 +01002290 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07002291 selectOutputForMusicEffects();
2292 }
2293
François Gaffie1c878552018-11-22 16:53:21 +01002294 if (outputDesc->getActivityCount(clientVolSrc) == 1 || !devices.isEmpty()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08002295 // starting an output being rerouted?
François Gaffie11d30102018-11-02 16:09:09 +01002296 if (devices.isEmpty()) {
2297 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Eric Laurent275e8e92014-11-30 15:14:47 -08002298 }
François Gaffiec005e562018-11-06 15:04:49 +01002299 bool shouldWait =
2300 (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM)) ||
2301 followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_NOTIFICATION)) ||
2302 (beaconMuteLatency > 0));
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002303 uint32_t waitMs = beaconMuteLatency;
Eric Laurente552edb2014-03-10 17:42:56 -07002304 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01002305 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07002306 if (desc != outputDesc) {
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002307 // An output has a shared device if
2308 // - managed by the same hw module
2309 // - supports the currently selected device
2310 const bool sharedDevice = outputDesc->sharesHwModuleWith(desc)
François Gaffie11d30102018-11-02 16:09:09 +01002311 && (!desc->filterSupportedDevices(devices).isEmpty());
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002312
Eric Laurent77305a62016-07-25 16:39:22 -07002313 // force a device change if any other output is:
2314 // - managed by the same hw module
Jean-Michel Trivi4a5b4812018-02-08 17:22:32 +00002315 // - supports currently selected device
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002316 // - has a current device selection that differs from selected device.
Eric Laurent77305a62016-07-25 16:39:22 -07002317 // - has an active audio patch
Eric Laurente552edb2014-03-10 17:42:56 -07002318 // In this case, the audio HAL must receive the new device selection so that it can
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002319 // change the device currently selected by the other output.
2320 if (sharedDevice &&
François Gaffie11d30102018-11-02 16:09:09 +01002321 desc->devices() != devices &&
Eric Laurent77305a62016-07-25 16:39:22 -07002322 desc->getPatchHandle() != AUDIO_PATCH_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07002323 force = true;
2324 }
2325 // wait for audio on other active outputs to be presented when starting
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002326 // a notification so that audio focus effect can propagate, or that a mute/unmute
2327 // event occurred for beacon
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002328 const uint32_t latencyMs = desc->latency();
2329 const bool isActive = desc->isActive(latencyMs * 2); // account for drain
2330
2331 if (shouldWait && isActive && (waitMs < latencyMs)) {
2332 waitMs = latencyMs;
Eric Laurente552edb2014-03-10 17:42:56 -07002333 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002334
2335 // Require mute check if another output is on a shared device
2336 // and currently active to have proper drain and avoid pops.
2337 // Note restoring AudioTracks onto this output needs to invoke
2338 // a volume ramp if there is no mute.
2339 requiresMuteCheck |= sharedDevice && isActive;
Eric Laurente552edb2014-03-10 17:42:56 -07002340 }
2341 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002342
jiabin3ff8d7d2022-12-13 06:27:44 +00002343 if (outputDesc->mUsePreferredMixerAttributes && devices != outputDesc->devices()) {
2344 // If the output is open with preferred mixer attributes, but the routed device is
2345 // changed when calling this function, returning DEAD_OBJECT to indicate routing
2346 // changed.
2347 return DEAD_OBJECT;
2348 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002349 const uint32_t muteWaitMs =
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05302350 setOutputDevices(__func__, outputDesc, devices, force, 0, nullptr,
2351 requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07002352
Eric Laurente552edb2014-03-10 17:42:56 -07002353 // apply volume rules for current stream and device if necessary
François Gaffieaaac0fd2018-11-22 17:56:39 +01002354 auto &curves = getVolumeCurves(client->attributes());
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00002355 if (NO_ERROR != checkAndSetVolume(curves, client->volumeSource(),
François Gaffieaaac0fd2018-11-22 17:56:39 +01002356 curves.getVolumeIndex(outputDesc->devices().types()),
Eric Laurentc75307b2015-03-17 15:29:32 -07002357 outputDesc,
Francois Gaffied11442b2020-04-27 11:51:09 +02002358 outputDesc->devices().types(), 0 /*delay*/,
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00002359 outputDesc->useHwGain() /*force*/)) {
2360 // request AudioService to reinitialize the volume curves asynchronously
2361 ALOGE("checkAndSetVolume failed, requesting volume range init");
2362 mpClientInterface->onVolumeRangeInitRequest();
2363 };
Eric Laurente552edb2014-03-10 17:42:56 -07002364
2365 // update the outputs if starting an output with a stream that can affect notification
2366 // routing
2367 handleNotificationRoutingForStream(stream);
Eric Laurentc722f302014-12-10 11:21:49 -08002368
Eric Laurent2cbe89a2014-12-19 11:49:08 -08002369 // force reevaluating accessibility routing when ringtone or alarm starts
François Gaffiec005e562018-11-06 15:04:49 +01002370 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM))) {
jiabinc44b3462022-12-08 12:52:31 -08002371 invalidateStreams({AUDIO_STREAM_ACCESSIBILITY});
Eric Laurent2cbe89a2014-12-19 11:49:08 -08002372 }
Eric Laurentdc462862016-07-19 12:29:53 -07002373
2374 if (waitMs > muteWaitMs) {
2375 *delayMs = waitMs - muteWaitMs;
2376 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002377
2378 // FIXME: A device change (muteWaitMs > 0) likely introduces a volume change.
2379 // A volume change enacted by APM with 0 delay is not synchronous, as it goes
2380 // via AudioCommandThread to AudioFlinger. Hence it is possible that the volume
2381 // change occurs after the MixerThread starts and causes a stream volume
2382 // glitch.
2383 //
2384 // We do not introduce additional delay here.
Eric Laurente552edb2014-03-10 17:42:56 -07002385 }
Eric Laurentdc462862016-07-19 12:29:53 -07002386
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002387 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
jiabin9a3361e2019-10-01 09:38:30 -07002388 mEngine->getForceUse(
2389 AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
François Gaffiec005e562018-11-06 15:04:49 +01002390 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), true, outputDesc);
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002391 }
2392
Eric Laurent97ac8712018-07-27 18:59:02 -07002393 // Automatically enable the remote submix input when output is started on a re routing mix
2394 // of type MIX_TYPE_RECORDERS
jiabin9a3361e2019-10-01 09:38:30 -07002395 if (isSingleDeviceType(devices.types(), &audio_is_remote_submix_device) &&
2396 policyMix != NULL && policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002397 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2398 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2399 address,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002400 "remote-submix",
2401 AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07002402 }
2403
Eric Laurent96d1dda2022-03-14 17:14:19 +01002404 checkLeBroadcastRoutes(wasLeUnicastActive, outputDesc, *delayMs);
2405
Eric Laurente552edb2014-03-10 17:42:56 -07002406 return NO_ERROR;
2407}
2408
Eric Laurent96d1dda2022-03-14 17:14:19 +01002409void AudioPolicyManager::checkLeBroadcastRoutes(bool wasUnicastActive,
2410 sp<SwAudioOutputDescriptor> ignoredOutput, uint32_t delayMs) {
2411 bool isUnicastActive = isLeUnicastActive();
2412
2413 if (wasUnicastActive != isUnicastActive) {
jiabin3ff8d7d2022-12-13 06:27:44 +00002414 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent96d1dda2022-03-14 17:14:19 +01002415 //reroute all outputs routed to LE broadcast if LE unicast activy changed on any output
2416 for (size_t i = 0; i < mOutputs.size(); i++) {
2417 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
2418 if (desc != ignoredOutput && desc->isActive()
2419 && ((isUnicastActive &&
2420 !desc->devices().
2421 getDevicesFromType(AUDIO_DEVICE_OUT_BLE_BROADCAST).isEmpty())
2422 || (wasUnicastActive &&
2423 !desc->devices().getDevicesFromTypes(
2424 getAudioDeviceOutLeAudioUnicastSet()).isEmpty()))) {
2425 DeviceVector newDevices = getNewOutputDevices(desc, false /*fromCache*/);
2426 bool force = desc->devices() != newDevices;
jiabin3ff8d7d2022-12-13 06:27:44 +00002427 if (desc->mUsePreferredMixerAttributes && force) {
2428 // If the device is using preferred mixer attributes, the output need to reopen
2429 // with default configuration when the new selected devices are different from
2430 // current routing devices.
2431 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices);
2432 continue;
2433 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05302434 setOutputDevices(__func__, desc, newDevices, force, delayMs);
Eric Laurent96d1dda2022-03-14 17:14:19 +01002435 // re-apply device specific volume if not done by setOutputDevice()
2436 if (!force) {
2437 applyStreamVolumes(desc, newDevices.types(), delayMs);
2438 }
2439 }
2440 }
jiabin3ff8d7d2022-12-13 06:27:44 +00002441 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent96d1dda2022-03-14 17:14:19 +01002442 }
2443}
2444
Eric Laurent8fc147b2018-07-22 19:13:55 -07002445status_t AudioPolicyManager::stopOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002446{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002447 ALOGV("%s portId %d", __FUNCTION__, portId);
2448
2449 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2450 if (outputDesc == 0) {
2451 ALOGW("stopOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002452 return BAD_VALUE;
2453 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002454 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002455
Jean-Michel Trivib1f6e642023-02-07 20:49:04 +00002456 if (client->hasPreferredDevice(true)) {
2457 // playback activity with preferred device impacts routing occurred, inform upper layers
2458 mpClientInterface->onRoutingUpdated();
2459 }
2460
Eric Laurent97ac8712018-07-27 18:59:02 -07002461 ALOGV("stopOutput() output %d, stream %d, session %d",
2462 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurente552edb2014-03-10 17:42:56 -07002463
Eric Laurent97ac8712018-07-27 18:59:02 -07002464 status_t status = stopSource(outputDesc, client);
Eric Laurent3974e3b2017-12-07 17:58:43 -08002465
Eric Laurent733ce942017-12-07 12:18:25 -08002466 if (status == NO_ERROR ) {
2467 outputDesc->stop();
jiabina84c3d32022-12-02 18:59:55 +00002468 } else {
2469 return status;
2470 }
2471
2472 if (outputDesc->devices().size() == 1) {
2473 sp<PreferredMixerAttributesInfo> info = getPreferredMixerAttributesInfo(
2474 outputDesc->devices()[0]->getId(), client->strategy());
2475 if (info != nullptr && info->getUid() == client->uid()) {
2476 info->decreaseActiveClient();
2477 if (info->getActiveClientCount() == 0) {
2478 reopenOutput(outputDesc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
2479 }
2480 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002481 }
2482 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07002483}
2484
Eric Laurent97ac8712018-07-27 18:59:02 -07002485status_t AudioPolicyManager::stopSource(const sp<SwAudioOutputDescriptor>& outputDesc,
2486 const sp<TrackClientDescriptor>& client)
Eric Laurentc75307b2015-03-17 15:29:32 -07002487{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002488 // always handle stream stop, check which stream type is stopping
Eric Laurent97ac8712018-07-27 18:59:02 -07002489 audio_stream_type_t stream = client->stream();
François Gaffie1c878552018-11-22 16:53:21 +01002490 auto clientVolSrc = client->volumeSource();
Eric Laurent96d1dda2022-03-14 17:14:19 +01002491 bool wasLeUnicastActive = isLeUnicastActive();
Eric Laurent97ac8712018-07-27 18:59:02 -07002492
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002493 handleEventForBeacon(stream == AUDIO_STREAM_TTS ? STOPPING_BEACON : STOPPING_OUTPUT);
2494
François Gaffie1c878552018-11-22 16:53:21 +01002495 if (outputDesc->getActivityCount(clientVolSrc) > 0) {
2496 if (outputDesc->getActivityCount(clientVolSrc) == 1) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002497 // Automatically disable the remote submix input when output is stopped on a
2498 // re routing mix of type MIX_TYPE_RECORDERS
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002499 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
jiabin9a3361e2019-10-01 09:38:30 -07002500 if (isSingleDeviceType(
2501 outputDesc->devices().types(), &audio_is_remote_submix_device) &&
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002502 policyMix != nullptr &&
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002503 policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002504 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2505 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002506 policyMix->mDeviceAddress,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002507 "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07002508 }
2509 }
2510 bool forceDeviceUpdate = false;
Eric Laurent72af8012023-03-15 17:36:22 +01002511 if (client->hasPreferredDevice(true) &&
2512 outputDesc->sameExclusivePreferredDevicesCount() < 2) {
François Gaffiec005e562018-11-06 15:04:49 +01002513 checkStrategyRoute(client->strategy(), AUDIO_IO_HANDLE_NONE);
Eric Laurent97ac8712018-07-27 18:59:02 -07002514 forceDeviceUpdate = true;
2515 }
2516
Eric Laurente552edb2014-03-10 17:42:56 -07002517 // decrement usage count of this stream on the output
Eric Laurent592dd7b2018-08-05 18:58:48 -07002518 outputDesc->setClientActive(client, false);
Paul McLeanaa981192015-03-21 09:55:15 -07002519
Eric Laurente552edb2014-03-10 17:42:56 -07002520 // store time at which the stream was stopped - see isStreamActive()
François Gaffie1c878552018-11-22 16:53:21 +01002521 if (outputDesc->getActivityCount(clientVolSrc) == 0 || forceDeviceUpdate) {
François Gaffiec005e562018-11-06 15:04:49 +01002522 outputDesc->setStopTime(client, systemTime());
François Gaffie11d30102018-11-02 16:09:09 +01002523 DeviceVector newDevices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Francois Gaffie3523ab32021-06-22 13:24:34 +02002524
2525 // If the routing does not change, if an output is routed on a device using HwGain
2526 // (aka setAudioPortConfig) and there are still active clients following different
2527 // volume group(s), force reapply volume
2528 bool requiresVolumeCheck = outputDesc->getActivityCount(clientVolSrc) == 0 &&
2529 outputDesc->useHwGain() && outputDesc->isAnyActive(VOLUME_SOURCE_NONE);
2530
Eric Laurente552edb2014-03-10 17:42:56 -07002531 // delay the device switch by twice the latency because stopOutput() is executed when
2532 // the track stop() command is received and at that time the audio track buffer can
2533 // still contain data that needs to be drained. The latency only covers the audio HAL
2534 // and kernel buffers. Also the latency does not always include additional delay in the
2535 // audio path (audio DSP, CODEC ...)
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05302536 setOutputDevices(__func__, outputDesc, newDevices, false, outputDesc->latency()*2,
Francois Gaffie3523ab32021-06-22 13:24:34 +02002537 nullptr, true /*requiresMuteCheck*/, requiresVolumeCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07002538
2539 // force restoring the device selection on other active outputs if it differs from the
2540 // one being selected for this output
jiabin3ff8d7d2022-12-13 06:27:44 +00002541 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent57de36c2016-09-28 16:59:11 -07002542 uint32_t delayMs = outputDesc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -07002543 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01002544 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07002545 if (desc != outputDesc &&
Eric Laurente552edb2014-03-10 17:42:56 -07002546 desc->isActive() &&
2547 outputDesc->sharesHwModuleWith(desc) &&
François Gaffie11d30102018-11-02 16:09:09 +01002548 (newDevices != desc->devices())) {
2549 DeviceVector newDevices2 = getNewOutputDevices(desc, false /*fromCache*/);
2550 bool force = desc->devices() != newDevices2;
Eric Laurentf3a5a602018-05-22 18:42:55 -07002551
jiabin3ff8d7d2022-12-13 06:27:44 +00002552 if (desc->mUsePreferredMixerAttributes && force) {
2553 // If the device is using preferred mixer attributes, the output need to
2554 // reopen with default configuration when the new selected devices are
2555 // different from current routing devices.
2556 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices2);
2557 continue;
2558 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05302559 setOutputDevices(__func__, desc, newDevices2, force, delayMs);
François Gaffie11d30102018-11-02 16:09:09 +01002560
Eric Laurent57de36c2016-09-28 16:59:11 -07002561 // re-apply device specific volume if not done by setOutputDevice()
2562 if (!force) {
François Gaffie11d30102018-11-02 16:09:09 +01002563 applyStreamVolumes(desc, newDevices2.types(), delayMs);
Eric Laurent57de36c2016-09-28 16:59:11 -07002564 }
Eric Laurente552edb2014-03-10 17:42:56 -07002565 }
2566 }
jiabin3ff8d7d2022-12-13 06:27:44 +00002567 reopenOutputsWithDevices(outputsToReopen);
Eric Laurente552edb2014-03-10 17:42:56 -07002568 // update the outputs if stopping one with a stream that can affect notification routing
2569 handleNotificationRoutingForStream(stream);
2570 }
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002571
2572 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
2573 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Jean-Michel Trivi74e01fa2019-02-25 12:18:09 -08002574 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), false, outputDesc);
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002575 }
2576
François Gaffiec005e562018-11-06 15:04:49 +01002577 if (followsSameRouting(client->attributes(), attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07002578 selectOutputForMusicEffects();
2579 }
Eric Laurent96d1dda2022-03-14 17:14:19 +01002580
2581 checkLeBroadcastRoutes(wasLeUnicastActive, outputDesc, outputDesc->latency()*2);
2582
Eric Laurente552edb2014-03-10 17:42:56 -07002583 return NO_ERROR;
2584 } else {
Eric Laurentc75307b2015-03-17 15:29:32 -07002585 ALOGW("stopOutput() refcount is already 0");
Eric Laurente552edb2014-03-10 17:42:56 -07002586 return INVALID_OPERATION;
2587 }
2588}
2589
jiabinbce0c1d2020-10-05 11:20:18 -07002590bool AudioPolicyManager::releaseOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002591{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002592 ALOGV("%s portId %d", __FUNCTION__, portId);
2593
2594 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2595 if (outputDesc == 0) {
Andy Hung39efb7a2018-09-26 15:39:28 -07002596 // If an output descriptor is closed due to a device routing change,
2597 // then there are race conditions with releaseOutput from tracks
2598 // that may be destroyed (with no PlaybackThread) or a PlaybackThread
2599 // destroyed shortly thereafter.
2600 //
2601 // Here we just log a warning, instead of a fatal error.
Eric Laurent8fc147b2018-07-22 19:13:55 -07002602 ALOGW("releaseOutput() no output for client %d", portId);
jiabinbce0c1d2020-10-05 11:20:18 -07002603 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002604 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002605
2606 ALOGV("releaseOutput() %d", outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -07002607
Jaideep Sharma7bf382e2020-11-26 17:07:29 +05302608 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
2609 if (outputDesc->isClientActive(client)) {
2610 ALOGW("releaseOutput() inactivates portId %d in good faith", portId);
2611 stopOutput(portId);
2612 }
2613
Eric Laurent8fc147b2018-07-22 19:13:55 -07002614 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
2615 if (outputDesc->mDirectOpenCount <= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07002616 ALOGW("releaseOutput() invalid open count %d for output %d",
Eric Laurent8fc147b2018-07-22 19:13:55 -07002617 outputDesc->mDirectOpenCount, outputDesc->mIoHandle);
jiabinbce0c1d2020-10-05 11:20:18 -07002618 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002619 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002620 if (--outputDesc->mDirectOpenCount == 0) {
2621 closeOutput(outputDesc->mIoHandle);
Eric Laurentb52c1522014-05-20 11:27:36 -07002622 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07002623 }
2624 }
Jaideep Sharma7bf382e2020-11-26 17:07:29 +05302625
Andy Hung39efb7a2018-09-26 15:39:28 -07002626 outputDesc->removeClient(portId);
jiabinbce0c1d2020-10-05 11:20:18 -07002627 if (outputDesc->mPendingReopenToQueryProfiles && outputDesc->getClientCount() == 0) {
2628 // The output is pending reopened to query dynamic profiles and
2629 // there is no active clients
2630 closeOutput(outputDesc->mIoHandle);
2631 sp<SwAudioOutputDescriptor> newOutputDesc = openOutputWithProfileAndDevice(
2632 outputDesc->mProfile, mEngine->getActiveMediaDevices(mAvailableOutputDevices));
2633 if (newOutputDesc == nullptr) {
2634 ALOGE("%s failed to open output", __func__);
2635 }
2636 return true;
2637 }
2638 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002639}
2640
Eric Laurentcaf7f482014-11-25 17:50:47 -08002641status_t AudioPolicyManager::getInputForAttr(const audio_attributes_t *attr,
2642 audio_io_handle_t *input,
Mikhail Naganov2996f672019-04-18 12:29:59 -07002643 audio_unique_id_t riid,
Eric Laurentcaf7f482014-11-25 17:50:47 -08002644 audio_session_t session,
Svet Ganov3e5f14f2021-05-13 22:51:08 +00002645 const AttributionSourceState& attributionSource,
jiabinf1c73972022-04-14 16:28:52 -07002646 audio_config_base_t *config,
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002647 audio_input_flags_t flags,
Eric Laurent2ac76942017-06-22 17:17:09 -07002648 audio_port_handle_t *selectedDeviceId,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002649 input_type_t *inputType,
2650 audio_port_handle_t *portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002651{
François Gaffiec005e562018-11-06 15:04:49 +01002652 ALOGV("%s() source %d, sampling rate %d, format %#x, channel mask %#x, session %d, "
Eric Laurent2f2c1982021-06-02 14:03:11 +02002653 "flags %#x attributes=%s requested device ID %d",
2654 __func__, attr->source, config->sample_rate, config->format, config->channel_mask,
2655 session, flags, toString(*attr).c_str(), *selectedDeviceId);
Eric Laurente552edb2014-03-10 17:42:56 -07002656
Eric Laurentad2e7b92017-09-14 20:06:42 -07002657 status_t status = NO_ERROR;
Francois Gaffie716e1432019-01-14 16:58:59 +01002658 audio_attributes_t attributes = *attr;
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002659 sp<AudioPolicyMix> policyMix;
François Gaffie11d30102018-11-02 16:09:09 +01002660 sp<DeviceDescriptor> device;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002661 sp<AudioInputDescriptor> inputDesc;
François Gaffie1b4753e2023-02-06 10:36:33 +01002662 sp<AudioInputDescriptor> previousInputDesc;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002663 sp<RecordClientDescriptor> clientDesc;
2664 audio_port_handle_t requestedDeviceId = *selectedDeviceId;
Svet Ganov3e5f14f2021-05-13 22:51:08 +00002665 uid_t uid = VALUE_OR_RETURN_STATUS(aidl2legacy_int32_t_uid_t(attributionSource.uid));
Eric Laurent8f42ea12018-08-08 09:08:25 -07002666 bool isSoundTrigger;
Eric Laurent8f42ea12018-08-08 09:08:25 -07002667
2668 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
2669 if (*portId != AUDIO_PORT_HANDLE_NONE) {
2670 return INVALID_OPERATION;
2671 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08002672
Francois Gaffie716e1432019-01-14 16:58:59 +01002673 if (attr->source == AUDIO_SOURCE_DEFAULT) {
2674 attributes.source = AUDIO_SOURCE_MIC;
Eric Laurentfe231122017-11-17 17:48:06 -08002675 }
2676
Paul McLean466dc8e2015-04-17 13:15:36 -06002677 // Explicit routing?
Pattydd807582021-11-04 21:01:03 +08002678 sp<DeviceDescriptor> explicitRoutingDevice =
François Gaffie11d30102018-11-02 16:09:09 +01002679 mAvailableInputDevices.getDeviceFromId(*selectedDeviceId);
Paul McLean466dc8e2015-04-17 13:15:36 -06002680
Eric Laurentad2e7b92017-09-14 20:06:42 -07002681 // special case for mmap capture: if an input IO handle is specified, we reuse this input if
2682 // possible
2683 if ((flags & AUDIO_INPUT_FLAG_MMAP_NOIRQ) == AUDIO_INPUT_FLAG_MMAP_NOIRQ &&
2684 *input != AUDIO_IO_HANDLE_NONE) {
2685 ssize_t index = mInputs.indexOfKey(*input);
2686 if (index < 0) {
2687 ALOGW("getInputForAttr() unknown MMAP input %d", *input);
2688 status = BAD_VALUE;
2689 goto error;
2690 }
2691 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002692 RecordClientVector clients = inputDesc->getClientsForSession(session);
2693 if (clients.size() == 0) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07002694 ALOGW("getInputForAttr() unknown session %d on input %d", session, *input);
2695 status = BAD_VALUE;
2696 goto error;
2697 }
2698 // For MMAP mode, the first call to getInputForAttr() is made on behalf of audioflinger.
2699 // The second call is for the first active client and sets the UID. Any further call
Eric Laurent331679c2018-04-16 17:03:16 -07002700 // corresponds to a new client and is only permitted from the same UID.
2701 // If the first UID is silenced, allow a new UID connection and replace with new UID
Eric Laurent8f42ea12018-08-08 09:08:25 -07002702 if (clients.size() > 1) {
2703 for (const auto& client : clients) {
2704 // The client map is ordered by key values (portId) and portIds are allocated
2705 // incrementaly. So the first client in this list is the one opened by audio flinger
2706 // when the mmap stream is created and should be ignored as it does not correspond
2707 // to an actual client
2708 if (client == *clients.cbegin()) {
2709 continue;
2710 }
2711 if (uid != client->uid() && !client->isSilenced()) {
2712 ALOGW("getInputForAttr() bad uid %d for client %d uid %d",
2713 uid, client->portId(), client->uid());
2714 status = INVALID_OPERATION;
2715 goto error;
2716 }
Eric Laurent331679c2018-04-16 17:03:16 -07002717 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002718 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002719 *inputType = API_INPUT_LEGACY;
François Gaffie11d30102018-11-02 16:09:09 +01002720 device = inputDesc->getDevice();
Eric Laurentad2e7b92017-09-14 20:06:42 -07002721
Eric Laurentfecbceb2021-02-09 14:46:43 +01002722 ALOGV("%s reusing MMAP input %d for session %d", __FUNCTION__, *input, session);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002723 goto exit;
Eric Laurentad2e7b92017-09-14 20:06:42 -07002724 }
2725
2726 *input = AUDIO_IO_HANDLE_NONE;
2727 *inputType = API_INPUT_INVALID;
2728
Francois Gaffie716e1432019-01-14 16:58:59 +01002729 if (attributes.source == AUDIO_SOURCE_REMOTE_SUBMIX &&
Jan Sebechlebskybc56bcd2022-09-26 13:15:19 +02002730 extractAddressFromAudioAttributes(attributes).has_value()) {
Francois Gaffie716e1432019-01-14 16:58:59 +01002731 status = mPolicyMixes.getInputMixForAttr(attributes, &policyMix);
Eric Laurentad2e7b92017-09-14 20:06:42 -07002732 if (status != NO_ERROR) {
jiabinc1de2df2019-05-07 14:26:40 -07002733 ALOGW("%s could not find input mix for attr %s",
2734 __func__, toString(attributes).c_str());
Eric Laurentad2e7b92017-09-14 20:06:42 -07002735 goto error;
François Gaffie036e1e92015-03-19 10:16:24 +01002736 }
jiabinc1de2df2019-05-07 14:26:40 -07002737 device = mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2738 String8(attr->tags + strlen("addr=")),
2739 AUDIO_FORMAT_DEFAULT);
2740 if (device == nullptr) {
Kevin Rocard04ed0462019-05-02 17:53:24 -07002741 ALOGW("%s could not find in Remote Submix device for source %d, tags %s",
jiabinc1de2df2019-05-07 14:26:40 -07002742 __func__, attributes.source, attributes.tags);
2743 status = BAD_VALUE;
2744 goto error;
2745 }
2746
Kevin Rocard25f9b052019-02-27 15:08:54 -08002747 if (is_mix_loopback_render(policyMix->mRouteFlags)) {
2748 *inputType = API_INPUT_MIX_PUBLIC_CAPTURE_PLAYBACK;
2749 } else {
2750 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
2751 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002752 } else {
François Gaffie11d30102018-11-02 16:09:09 +01002753 if (explicitRoutingDevice != nullptr) {
2754 device = explicitRoutingDevice;
Eric Laurent97ac8712018-07-27 18:59:02 -07002755 } else {
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01002756 // Prevent from storing invalid requested device id in clients
2757 requestedDeviceId = AUDIO_PORT_HANDLE_NONE;
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02002758 device = mEngine->getInputDeviceForAttributes(attributes, uid, session, &policyMix);
yuanjiahsu4069d5d2021-04-19 07:54:27 +08002759 ALOGV_IF(device != nullptr, "%s found device type is 0x%X",
2760 __FUNCTION__, device->type());
Eric Laurent97ac8712018-07-27 18:59:02 -07002761 }
François Gaffie11d30102018-11-02 16:09:09 +01002762 if (device == nullptr) {
Francois Gaffie716e1432019-01-14 16:58:59 +01002763 ALOGW("getInputForAttr() could not find device for source %d", attributes.source);
Eric Laurentad2e7b92017-09-14 20:06:42 -07002764 status = BAD_VALUE;
2765 goto error;
Eric Laurent275e8e92014-11-30 15:14:47 -08002766 }
Alden DSouzab7d20782021-02-08 08:51:42 -08002767 if (device->type() == AUDIO_DEVICE_IN_ECHO_REFERENCE) {
2768 *inputType = API_INPUT_MIX_CAPTURE;
2769 } else if (policyMix) {
François Gaffie11d30102018-11-02 16:09:09 +01002770 ALOG_ASSERT(policyMix->mMixType == MIX_TYPE_RECORDERS, "Invalid Mix Type");
2771 // there is an external policy, but this input is attached to a mix of recorders,
2772 // meaning it receives audio injected into the framework, so the recorder doesn't
2773 // know about it and is therefore considered "legacy"
2774 *inputType = API_INPUT_LEGACY;
2775 } else if (audio_is_remote_submix_device(device->type())) {
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002776 *inputType = API_INPUT_MIX_CAPTURE;
François Gaffie11d30102018-11-02 16:09:09 +01002777 } else if (device->type() == AUDIO_DEVICE_IN_TELEPHONY_RX) {
Eric Laurent82db2692015-08-07 13:59:42 -07002778 *inputType = API_INPUT_TELEPHONY_RX;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002779 } else {
2780 *inputType = API_INPUT_LEGACY;
Eric Laurentc722f302014-12-10 11:21:49 -08002781 }
Ravi Kumar Alamandab367f5b2015-08-25 08:21:37 -07002782
Eric Laurent599c7582015-12-07 18:05:55 -08002783 }
2784
François Gaffiec005e562018-11-06 15:04:49 +01002785 *input = getInputForDevice(device, session, attributes, config, flags, policyMix);
Eric Laurent599c7582015-12-07 18:05:55 -08002786 if (*input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07002787 status = INVALID_OPERATION;
jiabinf1c73972022-04-14 16:28:52 -07002788 AudioProfileVector profiles;
2789 status_t ret = getProfilesForDevices(
2790 DeviceVector(device), profiles, flags, true /*isInput*/);
2791 if (ret == NO_ERROR && !profiles.empty()) {
Robert Wub98ff1b2023-06-15 22:53:58 +00002792 const auto channels = profiles[0]->getChannels();
2793 if (!channels.empty() && (channels.find(config->channel_mask) == channels.end())) {
2794 config->channel_mask = *channels.begin();
2795 }
2796 const auto sampleRates = profiles[0]->getSampleRates();
2797 if (!sampleRates.empty() &&
2798 (sampleRates.find(config->sample_rate) == sampleRates.end())) {
2799 config->sample_rate = *sampleRates.begin();
2800 }
jiabinf1c73972022-04-14 16:28:52 -07002801 config->format = profiles[0]->getFormat();
2802 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002803 goto error;
Eric Laurent599c7582015-12-07 18:05:55 -08002804 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08002805
Eric Laurent8f42ea12018-08-08 09:08:25 -07002806exit:
2807
François Gaffiec005e562018-11-06 15:04:49 +01002808 *selectedDeviceId = mAvailableInputDevices.contains(device) ?
2809 device->getId() : AUDIO_PORT_HANDLE_NONE;
Eric Laurent2ac76942017-06-22 17:17:09 -07002810
Francois Gaffie716e1432019-01-14 16:58:59 +01002811 isSoundTrigger = attributes.source == AUDIO_SOURCE_HOTWORD &&
Carter Hsud0cce2e2019-05-03 17:36:28 +08002812 mSoundTriggerSessions.indexOfKey(session) >= 0;
jiabin4ef93452019-09-10 14:29:54 -07002813 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002814
Mikhail Naganov2996f672019-04-18 12:29:59 -07002815 clientDesc = new RecordClientDescriptor(*portId, riid, uid, session, attributes, *config,
Francois Gaffie716e1432019-01-14 16:58:59 +01002816 requestedDeviceId, attributes.source, flags,
2817 isSoundTrigger);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002818 inputDesc = mInputs.valueFor(*input);
François Gaffie1b4753e2023-02-06 10:36:33 +01002819 // Move (if found) effect for the client session to its input
2820 mEffects.moveEffectsForIo(session, *input, &mInputs, mpClientInterface);
Andy Hung39efb7a2018-09-26 15:39:28 -07002821 inputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002822
2823 ALOGV("getInputForAttr() returns input %d type %d selectedDeviceId %d for port ID %d",
2824 *input, *inputType, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07002825
Eric Laurent599c7582015-12-07 18:05:55 -08002826 return NO_ERROR;
Eric Laurentad2e7b92017-09-14 20:06:42 -07002827
2828error:
Eric Laurentad2e7b92017-09-14 20:06:42 -07002829 return status;
Eric Laurent599c7582015-12-07 18:05:55 -08002830}
2831
2832
François Gaffie11d30102018-11-02 16:09:09 +01002833audio_io_handle_t AudioPolicyManager::getInputForDevice(const sp<DeviceDescriptor> &device,
Eric Laurent599c7582015-12-07 18:05:55 -08002834 audio_session_t session,
François Gaffiec005e562018-11-06 15:04:49 +01002835 const audio_attributes_t &attributes,
jiabinf1c73972022-04-14 16:28:52 -07002836 audio_config_base_t *config,
Eric Laurent599c7582015-12-07 18:05:55 -08002837 audio_input_flags_t flags,
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002838 const sp<AudioPolicyMix> &policyMix)
Eric Laurent599c7582015-12-07 18:05:55 -08002839{
2840 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
François Gaffiec005e562018-11-06 15:04:49 +01002841 audio_source_t halInputSource = attributes.source;
Eric Laurent599c7582015-12-07 18:05:55 -08002842 bool isSoundTrigger = false;
2843
François Gaffiec005e562018-11-06 15:04:49 +01002844 if (attributes.source == AUDIO_SOURCE_HOTWORD) {
Eric Laurent599c7582015-12-07 18:05:55 -08002845 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
2846 if (index >= 0) {
2847 input = mSoundTriggerSessions.valueFor(session);
2848 isSoundTrigger = true;
2849 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_HW_HOTWORD);
2850 ALOGV("SoundTrigger capture on session %d input %d", session, input);
2851 } else {
2852 halInputSource = AUDIO_SOURCE_VOICE_RECOGNITION;
Eric Laurent5dbe4712014-09-19 19:04:57 -07002853 }
François Gaffiec005e562018-11-06 15:04:49 +01002854 } else if (attributes.source == AUDIO_SOURCE_VOICE_COMMUNICATION &&
Eric Laurentfe231122017-11-17 17:48:06 -08002855 audio_is_linear_pcm(config->format)) {
Haynes Mathew George851d3ff2017-06-19 20:01:57 -07002856 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_VOIP_TX);
Eric Laurent5dbe4712014-09-19 19:04:57 -07002857 }
2858
Carter Hsua3abb402021-10-26 11:11:20 +08002859 if (attributes.source == AUDIO_SOURCE_ULTRASOUND) {
2860 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_ULTRASOUND);
2861 }
2862
Eric Laurentfe231122017-11-17 17:48:06 -08002863 // sampling rate and flags may be updated by getInputProfile
2864 uint32_t profileSamplingRate = (config->sample_rate == 0) ?
2865 SAMPLE_RATE_HZ_DEFAULT : config->sample_rate;
jiabin2fd710d2022-05-02 23:20:22 +00002866 audio_format_t profileFormat = config->format;
Eric Laurentfe231122017-11-17 17:48:06 -08002867 audio_channel_mask_t profileChannelMask = config->channel_mask;
Andy Hungf129b032015-04-07 13:45:50 -07002868 audio_input_flags_t profileFlags = flags;
jiabin2fd710d2022-05-02 23:20:22 +00002869 // find a compatible input profile (not necessarily identical in parameters)
2870 sp<IOProfile> profile = getInputProfile(
2871 device, profileSamplingRate, profileFormat, profileChannelMask, profileFlags);
2872 if (profile == nullptr) {
2873 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07002874 }
jiabin2fd710d2022-05-02 23:20:22 +00002875
Glenn Kasten05ddca52016-02-11 08:17:12 -08002876 // Pick input sampling rate if not specified by client
Eric Laurentfe231122017-11-17 17:48:06 -08002877 uint32_t samplingRate = config->sample_rate;
Glenn Kasten05ddca52016-02-11 08:17:12 -08002878 if (samplingRate == 0) {
2879 samplingRate = profileSamplingRate;
2880 }
Eric Laurente552edb2014-03-10 17:42:56 -07002881
Eric Laurent322b4d22015-04-03 15:57:54 -07002882 if (profile->getModuleHandle() == 0) {
2883 ALOGE("getInputForAttr(): HW module %s not opened", profile->getModuleName());
Eric Laurent599c7582015-12-07 18:05:55 -08002884 return input;
Eric Laurentcf2c0212014-07-25 16:20:43 -07002885 }
2886
Eric Laurentec376dc2021-04-08 20:41:22 +02002887 // Reuse an already opened input if a client with the same session ID already exists
2888 // on that input
2889 for (size_t i = 0; i < mInputs.size(); i++) {
2890 sp <AudioInputDescriptor> desc = mInputs.valueAt(i);
2891 if (desc->mProfile != profile) {
2892 continue;
2893 }
2894 RecordClientVector clients = desc->clientsList();
2895 for (const auto &client : clients) {
2896 if (session == client->session()) {
2897 return desc->mIoHandle;
2898 }
2899 }
2900 }
2901
Eric Laurent3974e3b2017-12-07 17:58:43 -08002902 if (!profile->canOpenNewIo()) {
Eric Laurent4eb58f12018-12-07 16:41:02 -08002903 for (size_t i = 0; i < mInputs.size(); ) {
Eric Laurentc529cf62020-04-17 18:19:10 -07002904 sp<AudioInputDescriptor> desc = mInputs.valueAt(i);
Eric Laurent4eb58f12018-12-07 16:41:02 -08002905 if (desc->mProfile != profile) {
Carter Hsu9a645a92019-05-15 12:15:32 +08002906 i++;
Eric Laurent4eb58f12018-12-07 16:41:02 -08002907 continue;
2908 }
2909 // if sound trigger, reuse input if used by other sound trigger on same session
2910 // else
2911 // reuse input if active client app is not in IDLE state
2912 //
2913 RecordClientVector clients = desc->clientsList();
2914 bool doClose = false;
2915 for (const auto& client : clients) {
2916 if (isSoundTrigger != client->isSoundTrigger()) {
2917 continue;
2918 }
2919 if (client->isSoundTrigger()) {
2920 if (session == client->session()) {
2921 return desc->mIoHandle;
2922 }
2923 continue;
2924 }
2925 if (client->active() && client->appState() != APP_STATE_IDLE) {
2926 return desc->mIoHandle;
2927 }
2928 doClose = true;
2929 }
2930 if (doClose) {
2931 closeInput(desc->mIoHandle);
2932 } else {
2933 i++;
2934 }
2935 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002936 }
2937
Eric Laurentfe231122017-11-17 17:48:06 -08002938 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07002939
Eric Laurentfe231122017-11-17 17:48:06 -08002940 audio_config_t lConfig = AUDIO_CONFIG_INITIALIZER;
2941 lConfig.sample_rate = profileSamplingRate;
2942 lConfig.channel_mask = profileChannelMask;
2943 lConfig.format = profileFormat;
Eric Laurente3014102017-05-03 11:15:43 -07002944
François Gaffie11d30102018-11-02 16:09:09 +01002945 status_t status = inputDesc->open(&lConfig, device, halInputSource, profileFlags, &input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07002946
2947 // only accept input with the exact requested set of parameters
Eric Laurent599c7582015-12-07 18:05:55 -08002948 if (status != NO_ERROR || input == AUDIO_IO_HANDLE_NONE ||
Eric Laurentfe231122017-11-17 17:48:06 -08002949 (profileSamplingRate != lConfig.sample_rate) ||
2950 !audio_formats_match(profileFormat, lConfig.format) ||
2951 (profileChannelMask != lConfig.channel_mask)) {
2952 ALOGW("getInputForAttr() failed opening input: sampling rate %d"
Glenn Kasten49f36ba2017-12-06 13:02:02 -08002953 ", format %#x, channel mask %#x",
Eric Laurentfe231122017-11-17 17:48:06 -08002954 profileSamplingRate, profileFormat, profileChannelMask);
Eric Laurent599c7582015-12-07 18:05:55 -08002955 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfe231122017-11-17 17:48:06 -08002956 inputDesc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07002957 }
Eric Laurent599c7582015-12-07 18:05:55 -08002958 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07002959 }
2960
Eric Laurentc722f302014-12-10 11:21:49 -08002961 inputDesc->mPolicyMix = policyMix;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002962
Eric Laurent599c7582015-12-07 18:05:55 -08002963 addInput(input, inputDesc);
Eric Laurentb52c1522014-05-20 11:27:36 -07002964 mpClientInterface->onAudioPortListUpdate();
Paul McLean466dc8e2015-04-17 13:15:36 -06002965
Eric Laurent599c7582015-12-07 18:05:55 -08002966 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07002967}
2968
Eric Laurent4eb58f12018-12-07 16:41:02 -08002969status_t AudioPolicyManager::startInput(audio_port_handle_t portId)
Eric Laurentbb948092017-01-23 18:33:30 -08002970{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002971 ALOGV("%s portId %d", __FUNCTION__, portId);
2972
2973 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2974 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002975 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurentd52a28c2020-08-21 17:10:39 -07002976 return DEAD_OBJECT;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002977 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002978 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07002979 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002980 if (client->active()) {
2981 ALOGW("%s input %d client %d already started", __FUNCTION__, input, client->portId());
2982 return INVALID_OPERATION;
Eric Laurent4dc68062014-07-28 17:26:49 -07002983 }
2984
Eric Laurent8f42ea12018-08-08 09:08:25 -07002985 audio_session_t session = client->session();
2986
Eric Laurent4eb58f12018-12-07 16:41:02 -08002987 ALOGV("%s input:%d, session:%d)", __FUNCTION__, input, session);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002988
Eric Laurent4eb58f12018-12-07 16:41:02 -08002989 Vector<sp<AudioInputDescriptor>> activeInputs = mInputs.getActiveInputs();
Eric Laurent74708e72017-04-07 17:13:42 -07002990
Eric Laurent4eb58f12018-12-07 16:41:02 -08002991 status_t status = inputDesc->start();
2992 if (status != NO_ERROR) {
2993 return status;
Eric Laurent74708e72017-04-07 17:13:42 -07002994 }
Eric Laurente552edb2014-03-10 17:42:56 -07002995
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002996 // increment activity count before calling getNewInputDevice() below as only active sessions
Eric Laurent313d1e72016-01-29 09:56:57 -08002997 // are considered for device selection
Eric Laurent8f42ea12018-08-08 09:08:25 -07002998 inputDesc->setClientActive(client, true);
Eric Laurent313d1e72016-01-29 09:56:57 -08002999
Eric Laurent8f42ea12018-08-08 09:08:25 -07003000 // indicate active capture to sound trigger service if starting capture from a mic on
3001 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01003002 sp<DeviceDescriptor> device = getNewInputDevice(inputDesc);
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003003 if (device != nullptr) {
3004 status = setInputDevice(input, device, true /* force */);
3005 } else {
3006 ALOGW("%s no new input device can be found for descriptor %d",
3007 __FUNCTION__, inputDesc->getId());
3008 status = BAD_VALUE;
3009 }
Eric Laurente552edb2014-03-10 17:42:56 -07003010
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003011 if (status == NO_ERROR && inputDesc->activeCount() == 1) {
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003012 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003013 // if input maps to a dynamic policy with an activity listener, notify of state change
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003014 if ((policyMix != nullptr)
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003015 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
3016 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
Eric Laurent8f42ea12018-08-08 09:08:25 -07003017 MIX_STATE_MIXING);
Eric Laurent733ce942017-12-07 12:18:25 -08003018 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08003019
François Gaffie11d30102018-11-02 16:09:09 +01003020 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
3021 if (primaryInputDevices.contains(device) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07003022 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 1) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07003023 mpClientInterface->setSoundTriggerCaptureState(true);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003024 }
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07003025
Eric Laurent8f42ea12018-08-08 09:08:25 -07003026 // automatically enable the remote submix output when input is started if not
3027 // used by a policy mix of type MIX_TYPE_RECORDERS
3028 // For remote submix (a virtual device), we open only one input per capture request.
François Gaffie11d30102018-11-02 16:09:09 +01003029 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003030 String8 address = String8("");
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003031 if (policyMix == nullptr) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003032 address = String8("0");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003033 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
3034 address = policyMix->mDeviceAddress;
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07003035 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07003036 if (address != "") {
3037 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
3038 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08003039 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurentc722f302014-12-10 11:21:49 -08003040 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07003041 }
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003042 } else if (status != NO_ERROR) {
3043 // Restore client activity state.
3044 inputDesc->setClientActive(client, false);
3045 inputDesc->stop();
Eric Laurente552edb2014-03-10 17:42:56 -07003046 }
3047
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003048 ALOGV("%s input %d source = %d status = %d exit",
3049 __FUNCTION__, input, client->source(), status);
Eric Laurente552edb2014-03-10 17:42:56 -07003050
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003051 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07003052}
3053
Eric Laurent8fc147b2018-07-22 19:13:55 -07003054status_t AudioPolicyManager::stopInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07003055{
Eric Laurent8fc147b2018-07-22 19:13:55 -07003056 ALOGV("%s portId %d", __FUNCTION__, portId);
3057
3058 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
3059 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003060 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07003061 return BAD_VALUE;
3062 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07003063 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07003064 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003065 if (!client->active()) {
3066 ALOGW("%s input %d client %d already stopped", __FUNCTION__, input, client->portId());
Eric Laurente552edb2014-03-10 17:42:56 -07003067 return INVALID_OPERATION;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003068 }
Carter Hsue6139d52021-07-08 10:30:20 +08003069 auto old_source = inputDesc->source();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003070 inputDesc->setClientActive(client, false);
Paul McLean466dc8e2015-04-17 13:15:36 -06003071
Eric Laurent8f42ea12018-08-08 09:08:25 -07003072 inputDesc->stop();
3073 if (inputDesc->isActive()) {
Carter Hsue6139d52021-07-08 10:30:20 +08003074 auto current_source = inputDesc->source();
3075 setInputDevice(input, getNewInputDevice(inputDesc),
3076 old_source != current_source /* force */);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003077 } else {
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003078 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003079 // if input maps to a dynamic policy with an activity listener, notify of state change
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003080 if ((policyMix != nullptr)
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003081 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
3082 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
Eric Laurent8f42ea12018-08-08 09:08:25 -07003083 MIX_STATE_IDLE);
Eric Laurent84332aa2016-01-28 22:19:18 +00003084 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07003085
3086 // automatically disable the remote submix output when input is stopped if not
3087 // used by a policy mix of type MIX_TYPE_RECORDERS
François Gaffie11d30102018-11-02 16:09:09 +01003088 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003089 String8 address = String8("");
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003090 if (policyMix == nullptr) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003091 address = String8("0");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003092 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
3093 address = policyMix->mDeviceAddress;
Eric Laurent8f42ea12018-08-08 09:08:25 -07003094 }
3095 if (address != "") {
3096 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
3097 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08003098 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003099 }
3100 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07003101 resetInputDevice(input);
3102
3103 // indicate inactive capture to sound trigger service if stopping capture from a mic on
3104 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01003105 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
3106 if (primaryInputDevices.contains(inputDesc->getDevice()) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07003107 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07003108 mpClientInterface->setSoundTriggerCaptureState(false);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003109 }
3110 inputDesc->clearPreemptedSessions();
Eric Laurente552edb2014-03-10 17:42:56 -07003111 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003112 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07003113}
3114
Eric Laurent8fc147b2018-07-22 19:13:55 -07003115void AudioPolicyManager::releaseInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07003116{
Eric Laurent8fc147b2018-07-22 19:13:55 -07003117 ALOGV("%s portId %d", __FUNCTION__, portId);
3118
3119 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
3120 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003121 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07003122 return;
3123 }
Andy Hung39efb7a2018-09-26 15:39:28 -07003124 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8fc147b2018-07-22 19:13:55 -07003125 audio_io_handle_t input = inputDesc->mIoHandle;
3126
Eric Laurent8f42ea12018-08-08 09:08:25 -07003127 ALOGV("%s %d", __FUNCTION__, input);
Paul McLean466dc8e2015-04-17 13:15:36 -06003128
Andy Hung39efb7a2018-09-26 15:39:28 -07003129 inputDesc->removeClient(portId);
François Gaffie1b4753e2023-02-06 10:36:33 +01003130 mEffects.putOrphanEffects(client->session(), input, &mInputs, mpClientInterface);
Andy Hung39efb7a2018-09-26 15:39:28 -07003131 if (inputDesc->getClientCount() > 0) {
3132 ALOGV("%s(%d) %zu clients remaining", __func__, portId, inputDesc->getClientCount());
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003133 return;
3134 }
3135
Eric Laurent05b90f82014-08-27 15:32:29 -07003136 closeInput(input);
Eric Laurentb52c1522014-05-20 11:27:36 -07003137 mpClientInterface->onAudioPortListUpdate();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003138 ALOGV("%s exit", __FUNCTION__);
Eric Laurente552edb2014-03-10 17:42:56 -07003139}
3140
Eric Laurent8f42ea12018-08-08 09:08:25 -07003141void AudioPolicyManager::closeActiveClients(const sp<AudioInputDescriptor>& input)
Eric Laurent8fc147b2018-07-22 19:13:55 -07003142{
Eric Laurent8f42ea12018-08-08 09:08:25 -07003143 RecordClientVector clients = input->clientsList(true);
Eric Laurent8fc147b2018-07-22 19:13:55 -07003144
3145 for (const auto& client : clients) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003146 closeClient(client->portId());
Eric Laurent8fc147b2018-07-22 19:13:55 -07003147 }
3148}
3149
Eric Laurent8f42ea12018-08-08 09:08:25 -07003150void AudioPolicyManager::closeClient(audio_port_handle_t portId)
3151{
3152 stopInput(portId);
3153 releaseInput(portId);
3154}
Eric Laurent8fc147b2018-07-22 19:13:55 -07003155
Eric Laurent0dd51852019-04-19 18:18:58 -07003156void AudioPolicyManager::checkCloseInputs() {
3157 // After connecting or disconnecting an input device, close input if:
3158 // - it has no client (was just opened to check profile) OR
3159 // - none of its supported devices are connected anymore OR
3160 // - one of its clients cannot be routed to one of its supported
3161 // devices anymore. Otherwise update device selection
3162 std::vector<audio_io_handle_t> inputsToClose;
3163 for (size_t i = 0; i < mInputs.size(); i++) {
3164 const sp<AudioInputDescriptor> input = mInputs.valueAt(i);
3165 if (input->clientsList().size() == 0
Eric Laurent85732f42020-03-19 11:31:10 -07003166 || !mAvailableInputDevices.containsAtLeastOne(input->supportedDevices())) {
Eric Laurent0dd51852019-04-19 18:18:58 -07003167 inputsToClose.push_back(mInputs.keyAt(i));
3168 } else {
3169 bool close = false;
3170 for (const auto& client : input->clientsList()) {
3171 sp<DeviceDescriptor> device =
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02003172 mEngine->getInputDeviceForAttributes(client->attributes(), client->uid(),
3173 client->session());
Eric Laurent0dd51852019-04-19 18:18:58 -07003174 if (!input->supportedDevices().contains(device)) {
3175 close = true;
3176 break;
3177 }
3178 }
3179 if (close) {
3180 inputsToClose.push_back(mInputs.keyAt(i));
3181 } else {
3182 setInputDevice(input->mIoHandle, getNewInputDevice(input));
3183 }
3184 }
3185 }
3186
3187 for (const audio_io_handle_t handle : inputsToClose) {
3188 ALOGV("%s closing input %d", __func__, handle);
3189 closeInput(handle);
Eric Laurent05b90f82014-08-27 15:32:29 -07003190 }
Eric Laurentd4692962014-05-05 18:13:44 -07003191}
3192
François Gaffie251c7f02018-11-07 10:41:08 +01003193void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream, int indexMin, int indexMax)
Eric Laurente552edb2014-03-10 17:42:56 -07003194{
3195 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08003196 if (indexMin < 0 || indexMax < 0) {
3197 ALOGE("%s for stream %d: invalid min %d or max %d", __func__, stream , indexMin, indexMax);
3198 return;
3199 }
Eric Laurentf5aa58d2019-02-22 18:20:11 -08003200 getVolumeCurves(stream).initVolume(indexMin, indexMax);
Eric Laurent28d09f02016-03-08 10:43:05 -08003201
3202 // initialize other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08003203 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
3204 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08003205 continue;
3206 }
Eric Laurentf5aa58d2019-02-22 18:20:11 -08003207 getVolumeCurves((audio_stream_type_t)curStream).initVolume(indexMin, indexMax);
Eric Laurent223fd5c2014-11-11 13:43:36 -08003208 }
Eric Laurente552edb2014-03-10 17:42:56 -07003209}
3210
Eric Laurente0720872014-03-11 09:30:41 -07003211status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
François Gaffie53615e22015-03-19 09:24:12 +01003212 int index,
3213 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07003214{
François Gaffieaaac0fd2018-11-22 17:56:39 +01003215 auto attributes = mEngine->getAttributesForStreamType(stream);
Eric Laurent242a9f82020-03-23 15:57:04 -07003216 if (attributes == AUDIO_ATTRIBUTES_INITIALIZER) {
3217 ALOGW("%s: no group for stream %s, bailing out", __func__, toString(stream).c_str());
3218 return NO_ERROR;
3219 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01003220 ALOGV("%s: stream %s attributes=%s", __func__,
3221 toString(stream).c_str(), toString(attributes).c_str());
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003222 return setVolumeIndexForAttributes(attributes, index, device);
Eric Laurente552edb2014-03-10 17:42:56 -07003223}
3224
Eric Laurente0720872014-03-11 09:30:41 -07003225status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
François Gaffieaaac0fd2018-11-22 17:56:39 +01003226 int *index,
3227 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07003228{
François Gaffiec005e562018-11-06 15:04:49 +01003229 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
3230 // stream by the engine.
jiabin9a3361e2019-10-01 09:38:30 -07003231 DeviceTypeSet deviceTypes = {device};
Eric Laurent5a2b6292016-04-14 18:05:57 -07003232 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
jiabin9a3361e2019-10-01 09:38:30 -07003233 deviceTypes = mEngine->getOutputDevicesForStream(
3234 stream, true /*fromCache*/).types();
Eric Laurente552edb2014-03-10 17:42:56 -07003235 }
jiabin9a3361e2019-10-01 09:38:30 -07003236 return getVolumeIndex(getVolumeCurves(stream), *index, deviceTypes);
Eric Laurente552edb2014-03-10 17:42:56 -07003237}
3238
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003239status_t AudioPolicyManager::setVolumeIndexForAttributes(const audio_attributes_t &attributes,
François Gaffiecfe17322018-11-07 13:41:29 +01003240 int index,
3241 audio_devices_t device)
3242{
3243 // Get Volume group matching the Audio Attributes
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003244 auto group = mEngine->getVolumeGroupForAttributes(attributes);
3245 if (group == VOLUME_GROUP_NONE) {
3246 ALOGD("%s: no group matching with %s", __FUNCTION__, toString(attributes).c_str());
François Gaffiecfe17322018-11-07 13:41:29 +01003247 return BAD_VALUE;
3248 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003249 ALOGV("%s: group %d matching with %s", __FUNCTION__, group, toString(attributes).c_str());
François Gaffiecfe17322018-11-07 13:41:29 +01003250 status_t status = NO_ERROR;
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003251 IVolumeCurves &curves = getVolumeCurves(attributes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01003252 VolumeSource vs = toVolumeSource(group);
Eric Laurentf9cccec2022-11-16 19:12:00 +01003253 // AUDIO_STREAM_BLUETOOTH_SCO is only used for volume control so we remap
3254 // to AUDIO_STREAM_VOICE_CALL to match with relevant playback activity
3255 VolumeSource activityVs = (vs == toVolumeSource(AUDIO_STREAM_BLUETOOTH_SCO, false)) ?
3256 toVolumeSource(AUDIO_STREAM_VOICE_CALL, false) : vs;
François Gaffieaaac0fd2018-11-22 17:56:39 +01003257 product_strategy_t strategy = mEngine->getProductStrategyForAttributes(attributes);
3258
3259 status = setVolumeCurveIndex(index, device, curves);
3260 if (status != NO_ERROR) {
3261 ALOGE("%s failed to set curve index for group %d device 0x%X", __func__, group, device);
3262 return status;
3263 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003264
jiabin9a3361e2019-10-01 09:38:30 -07003265 DeviceTypeSet curSrcDevices;
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003266 auto curCurvAttrs = curves.getAttributes();
3267 if (!curCurvAttrs.empty() && curCurvAttrs.front() != defaultAttr) {
3268 auto attr = curCurvAttrs.front();
jiabin9a3361e2019-10-01 09:38:30 -07003269 curSrcDevices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false).types();
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003270 } else if (!curves.getStreamTypes().empty()) {
3271 auto stream = curves.getStreamTypes().front();
jiabin9a3361e2019-10-01 09:38:30 -07003272 curSrcDevices = mEngine->getOutputDevicesForStream(stream, false).types();
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003273 } else {
3274 ALOGE("%s: Invalid src %d: no valid attributes nor stream",__func__, vs);
3275 return BAD_VALUE;
3276 }
jiabin9a3361e2019-10-01 09:38:30 -07003277 audio_devices_t curSrcDevice = Volume::getDeviceForVolume(curSrcDevices);
3278 resetDeviceTypes(curSrcDevices, curSrcDevice);
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003279
François Gaffiecfe17322018-11-07 13:41:29 +01003280 // update volume on all outputs and streams matching the following:
3281 // - The requested stream (or a stream matching for volume control) is active on the output
3282 // - The device (or devices) selected by the engine for this stream includes
3283 // the requested device
3284 // - For non default requested device, currently selected device on the output is either the
3285 // requested device or one of the devices selected by the engine for this stream
3286 // - For default requested device (AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME), apply volume only if
3287 // no specific device volume value exists for currently selected device.
François Gaffieaaac0fd2018-11-22 17:56:39 +01003288 for (size_t i = 0; i < mOutputs.size(); i++) {
3289 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
jiabin9a3361e2019-10-01 09:38:30 -07003290 DeviceTypeSet curDevices = desc->devices().types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01003291
jiabin9a3361e2019-10-01 09:38:30 -07003292 if (curDevices.erase(AUDIO_DEVICE_OUT_SPEAKER_SAFE)) {
3293 curDevices.insert(AUDIO_DEVICE_OUT_SPEAKER);
Robert Lee5e66e792019-04-03 18:37:15 +08003294 }
Eric Laurentf9cccec2022-11-16 19:12:00 +01003295
3296 if (!(desc->isActive(activityVs) || isInCallOrScreening())) {
François Gaffieed91f582020-01-31 10:35:37 +01003297 continue;
3298 }
3299 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME &&
3300 curDevices.find(device) == curDevices.end()) {
3301 continue;
3302 }
3303 bool applyVolume = false;
3304 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
3305 curSrcDevices.insert(device);
3306 applyVolume = (curSrcDevices.find(
3307 Volume::getDeviceForVolume(curDevices)) != curSrcDevices.end());
3308 } else {
3309 applyVolume = !curves.hasVolumeIndexForDevice(curSrcDevice);
3310 }
3311 if (!applyVolume) {
3312 continue; // next output
3313 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01003314 // Inter / intra volume group priority management: Loop on strategies arranged by priority
3315 // If a higher priority strategy is active, and the output is routed to a device with a
3316 // HW Gain management, do not change the volume
François Gaffieaaac0fd2018-11-22 17:56:39 +01003317 if (desc->useHwGain()) {
François Gaffieed91f582020-01-31 10:35:37 +01003318 applyVolume = false;
Francois Gaffie593634d2021-06-22 13:31:31 +02003319 // If the volume source is active with higher priority source, ensure at least Sw Muted
3320 desc->setSwMute((index == 0), vs, curves.getStreamTypes(), curDevices, 0 /*delayMs*/);
François Gaffieaaac0fd2018-11-22 17:56:39 +01003321 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
3322 auto activeClients = desc->clientsList(true /*activeOnly*/, productStrategy,
3323 false /*preferredDevice*/);
3324 if (activeClients.empty()) {
3325 continue;
3326 }
3327 bool isPreempted = false;
3328 bool isHigherPriority = productStrategy < strategy;
3329 for (const auto &client : activeClients) {
Eric Laurentf9cccec2022-11-16 19:12:00 +01003330 if (isHigherPriority && (client->volumeSource() != activityVs)) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01003331 ALOGV("%s: Strategy=%d (\nrequester:\n"
3332 " group %d, volumeGroup=%d attributes=%s)\n"
3333 " higher priority source active:\n"
3334 " volumeGroup=%d attributes=%s) \n"
3335 " on output %zu, bailing out", __func__, productStrategy,
3336 group, group, toString(attributes).c_str(),
3337 client->volumeSource(), toString(client->attributes()).c_str(), i);
3338 applyVolume = false;
3339 isPreempted = true;
3340 break;
3341 }
3342 // However, continue for loop to ensure no higher prio clients running on output
Eric Laurentf9cccec2022-11-16 19:12:00 +01003343 if (client->volumeSource() == activityVs) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01003344 applyVolume = true;
3345 }
3346 }
3347 if (isPreempted || applyVolume) {
3348 break;
3349 }
3350 }
3351 if (!applyVolume) {
3352 continue; // next output
3353 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01003354 }
François Gaffieed91f582020-01-31 10:35:37 +01003355 //FIXME: workaround for truncated touch sounds
3356 // delayed volume change for system stream to be removed when the problem is
3357 // handled by system UI
3358 status_t volStatus = checkAndSetVolume(
3359 curves, vs, index, desc, curDevices,
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003360 ((vs == toVolumeSource(AUDIO_STREAM_SYSTEM, false))?
François Gaffieed91f582020-01-31 10:35:37 +01003361 TOUCH_SOUND_FIXED_DELAY_MS : 0));
3362 if (volStatus != NO_ERROR) {
3363 status = volStatus;
François Gaffieaaac0fd2018-11-22 17:56:39 +01003364 }
3365 }
François Gaffiecfe17322018-11-07 13:41:29 +01003366 mpClientInterface->onAudioVolumeGroupChanged(group, 0 /*flags*/);
3367 return status;
3368}
3369
François Gaffieaaac0fd2018-11-22 17:56:39 +01003370status_t AudioPolicyManager::setVolumeCurveIndex(int index,
François Gaffiecfe17322018-11-07 13:41:29 +01003371 audio_devices_t device,
3372 IVolumeCurves &volumeCurves)
3373{
3374 // VOICE_CALL stream has minVolumeIndex > 0 but can be muted directly by an
3375 // app that has MODIFY_PHONE_STATE permission.
François Gaffieaaac0fd2018-11-22 17:56:39 +01003376 bool hasVoice = hasVoiceStream(volumeCurves.getStreamTypes());
3377 if (((index < volumeCurves.getVolumeIndexMin()) && !(hasVoice && index == 0)) ||
François Gaffiecfe17322018-11-07 13:41:29 +01003378 (index > volumeCurves.getVolumeIndexMax())) {
3379 ALOGD("%s: wrong index %d min=%d max=%d", __FUNCTION__, index,
3380 volumeCurves.getVolumeIndexMin(), volumeCurves.getVolumeIndexMax());
3381 return BAD_VALUE;
3382 }
3383 if (!audio_is_output_device(device)) {
3384 return BAD_VALUE;
3385 }
3386
3387 // Force max volume if stream cannot be muted
3388 if (!volumeCurves.canBeMuted()) index = volumeCurves.getVolumeIndexMax();
3389
François Gaffieaaac0fd2018-11-22 17:56:39 +01003390 ALOGV("%s device %08x, index %d", __FUNCTION__ , device, index);
François Gaffiecfe17322018-11-07 13:41:29 +01003391 volumeCurves.addCurrentVolumeIndex(device, index);
3392 return NO_ERROR;
3393}
3394
3395status_t AudioPolicyManager::getVolumeIndexForAttributes(const audio_attributes_t &attr,
3396 int &index,
3397 audio_devices_t device)
3398{
3399 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
3400 // stream by the engine.
jiabin9a3361e2019-10-01 09:38:30 -07003401 DeviceTypeSet deviceTypes = {device};
François Gaffiecfe17322018-11-07 13:41:29 +01003402 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
Mikhail Naganovbb990f22022-06-15 00:46:43 +00003403 deviceTypes = mEngine->getOutputDevicesForAttributes(
jiabin9a3361e2019-10-01 09:38:30 -07003404 attr, nullptr, true /*fromCache*/).types();
François Gaffiecfe17322018-11-07 13:41:29 +01003405 }
jiabin9a3361e2019-10-01 09:38:30 -07003406 return getVolumeIndex(getVolumeCurves(attr), index, deviceTypes);
François Gaffiecfe17322018-11-07 13:41:29 +01003407}
3408
3409status_t AudioPolicyManager::getVolumeIndex(const IVolumeCurves &curves,
3410 int &index,
jiabin9a3361e2019-10-01 09:38:30 -07003411 const DeviceTypeSet& deviceTypes) const
François Gaffiecfe17322018-11-07 13:41:29 +01003412{
Mikhail Naganovbb990f22022-06-15 00:46:43 +00003413 if (!isSingleDeviceType(deviceTypes, audio_is_output_device)) {
François Gaffiecfe17322018-11-07 13:41:29 +01003414 return BAD_VALUE;
3415 }
jiabin9a3361e2019-10-01 09:38:30 -07003416 index = curves.getVolumeIndex(deviceTypes);
3417 ALOGV("%s: device %s index %d", __FUNCTION__, dumpDeviceTypes(deviceTypes).c_str(), index);
François Gaffiecfe17322018-11-07 13:41:29 +01003418 return NO_ERROR;
3419}
3420
3421status_t AudioPolicyManager::getMinVolumeIndexForAttributes(const audio_attributes_t &attr,
3422 int &index)
3423{
3424 index = getVolumeCurves(attr).getVolumeIndexMin();
3425 return NO_ERROR;
3426}
3427
3428status_t AudioPolicyManager::getMaxVolumeIndexForAttributes(const audio_attributes_t &attr,
3429 int &index)
3430{
3431 index = getVolumeCurves(attr).getVolumeIndexMax();
3432 return NO_ERROR;
3433}
3434
Eric Laurent36829f92017-04-07 19:04:42 -07003435audio_io_handle_t AudioPolicyManager::selectOutputForMusicEffects()
Eric Laurente552edb2014-03-10 17:42:56 -07003436{
3437 // select one output among several suitable for global effects.
3438 // The priority is as follows:
3439 // 1: An offloaded output. If the effect ends up not being offloadable,
3440 // AudioFlinger will invalidate the track and the offloaded output
3441 // will be closed causing the effect to be moved to a PCM output.
3442 // 2: A deep buffer output
Eric Laurent36829f92017-04-07 19:04:42 -07003443 // 3: The primary output
3444 // 4: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07003445
François Gaffiec005e562018-11-06 15:04:49 +01003446 DeviceVector devices = mEngine->getOutputDevicesForAttributes(
3447 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
François Gaffie11d30102018-11-02 16:09:09 +01003448 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07003449
Eric Laurent36829f92017-04-07 19:04:42 -07003450 if (outputs.size() == 0) {
3451 return AUDIO_IO_HANDLE_NONE;
3452 }
Eric Laurente552edb2014-03-10 17:42:56 -07003453
Eric Laurent36829f92017-04-07 19:04:42 -07003454 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
3455 bool activeOnly = true;
3456
3457 while (output == AUDIO_IO_HANDLE_NONE) {
3458 audio_io_handle_t outputOffloaded = AUDIO_IO_HANDLE_NONE;
3459 audio_io_handle_t outputDeepBuffer = AUDIO_IO_HANDLE_NONE;
3460 audio_io_handle_t outputPrimary = AUDIO_IO_HANDLE_NONE;
3461
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003462 for (audio_io_handle_t output : outputs) {
3463 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
Eric Laurent83d17c22019-04-02 17:10:01 -07003464 if (activeOnly && !desc->isActive(toVolumeSource(AUDIO_STREAM_MUSIC))) {
Eric Laurent36829f92017-04-07 19:04:42 -07003465 continue;
3466 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003467 ALOGV("selectOutputForMusicEffects activeOnly %d output %d flags 0x%08x",
3468 activeOnly, output, desc->mFlags);
Eric Laurent36829f92017-04-07 19:04:42 -07003469 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003470 outputOffloaded = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003471 }
3472 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003473 outputDeepBuffer = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003474 }
3475 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003476 outputPrimary = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003477 }
3478 }
3479 if (outputOffloaded != AUDIO_IO_HANDLE_NONE) {
3480 output = outputOffloaded;
3481 } else if (outputDeepBuffer != AUDIO_IO_HANDLE_NONE) {
3482 output = outputDeepBuffer;
3483 } else if (outputPrimary != AUDIO_IO_HANDLE_NONE) {
3484 output = outputPrimary;
3485 } else {
3486 output = outputs[0];
3487 }
3488 activeOnly = false;
3489 }
3490
3491 if (output != mMusicEffectOutput) {
François Gaffie1b4753e2023-02-06 10:36:33 +01003492 mEffects.moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output,
3493 mpClientInterface);
Eric Laurent36829f92017-04-07 19:04:42 -07003494 mMusicEffectOutput = output;
3495 }
3496
3497 ALOGV("selectOutputForMusicEffects selected output %d", output);
Eric Laurente552edb2014-03-10 17:42:56 -07003498 return output;
3499}
3500
Eric Laurent36829f92017-04-07 19:04:42 -07003501audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc __unused)
3502{
3503 return selectOutputForMusicEffects();
3504}
3505
Eric Laurente0720872014-03-11 09:30:41 -07003506status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07003507 audio_io_handle_t io,
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08003508 product_strategy_t strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07003509 int session,
3510 int id)
3511{
Eric Laurentb82e6b72019-11-22 17:25:04 -08003512 if (session != AUDIO_SESSION_DEVICE) {
3513 ssize_t index = mOutputs.indexOfKey(io);
Eric Laurente552edb2014-03-10 17:42:56 -07003514 if (index < 0) {
Eric Laurentb82e6b72019-11-22 17:25:04 -08003515 index = mInputs.indexOfKey(io);
3516 if (index < 0) {
3517 ALOGW("registerEffect() unknown io %d", io);
3518 return INVALID_OPERATION;
3519 }
Eric Laurente552edb2014-03-10 17:42:56 -07003520 }
3521 }
Eric Laurentbf8f69f2022-03-25 17:48:38 +01003522 bool isMusicEffect = (session != AUDIO_SESSION_OUTPUT_STAGE)
3523 && ((strategy == streamToStrategy(AUDIO_STREAM_MUSIC)
3524 || strategy == PRODUCT_STRATEGY_NONE));
3525 return mEffects.registerEffect(desc, io, session, id, isMusicEffect);
Eric Laurente552edb2014-03-10 17:42:56 -07003526}
3527
Eric Laurentc241b0d2018-11-28 09:08:49 -08003528status_t AudioPolicyManager::unregisterEffect(int id)
3529{
3530 if (mEffects.getEffect(id) == nullptr) {
3531 return INVALID_OPERATION;
3532 }
Eric Laurentc241b0d2018-11-28 09:08:49 -08003533 if (mEffects.isEffectEnabled(id)) {
3534 ALOGW("%s effect %d enabled", __FUNCTION__, id);
3535 setEffectEnabled(id, false);
3536 }
3537 return mEffects.unregisterEffect(id);
3538}
3539
3540status_t AudioPolicyManager::setEffectEnabled(int id, bool enabled)
3541{
3542 sp<EffectDescriptor> effect = mEffects.getEffect(id);
3543 if (effect == nullptr) {
3544 return INVALID_OPERATION;
3545 }
3546
3547 status_t status = mEffects.setEffectEnabled(id, enabled);
3548 if (status == NO_ERROR) {
3549 mInputs.trackEffectEnabled(effect, enabled);
3550 }
3551 return status;
3552}
3553
Eric Laurent6c796322019-04-09 14:13:17 -07003554
3555status_t AudioPolicyManager::moveEffectsToIo(const std::vector<int>& ids, audio_io_handle_t io)
3556{
3557 mEffects.moveEffects(ids, io);
3558 return NO_ERROR;
3559}
3560
Eric Laurentc75307b2015-03-17 15:29:32 -07003561bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
3562{
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003563 auto vs = toVolumeSource(stream, false);
3564 return vs != VOLUME_SOURCE_NONE ? mOutputs.isActive(vs, inPastMs) : false;
Eric Laurentc75307b2015-03-17 15:29:32 -07003565}
3566
3567bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream, uint32_t inPastMs) const
3568{
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003569 auto vs = toVolumeSource(stream, false);
3570 return vs != VOLUME_SOURCE_NONE ? mOutputs.isActiveRemotely(vs, inPastMs) : false;
Eric Laurentc75307b2015-03-17 15:29:32 -07003571}
3572
Eric Laurente0720872014-03-11 09:30:41 -07003573bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07003574{
3575 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003576 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08003577 if (inputDescriptor->isSourceActive(source)) {
Eric Laurente552edb2014-03-10 17:42:56 -07003578 return true;
3579 }
3580 }
3581 return false;
3582}
3583
Eric Laurent275e8e92014-11-30 15:14:47 -08003584// Register a list of custom mixes with their attributes and format.
3585// When a mix is registered, corresponding input and output profiles are
3586// added to the remote submix hw module. The profile contains only the
3587// parameters (sampling rate, format...) specified by the mix.
3588// The corresponding input remote submix device is also connected.
3589//
3590// When a remote submix device is connected, the address is checked to select the
3591// appropriate profile and the corresponding input or output stream is opened.
3592//
3593// When capture starts, getInputForAttr() will:
3594// - 1 look for a mix matching the address passed in attribtutes tags if any
3595// - 2 if none found, getDeviceForInputSource() will:
3596// - 2.1 look for a mix matching the attributes source
3597// - 2.2 if none found, default to device selection by policy rules
3598// At this time, the corresponding output remote submix device is also connected
3599// and active playback use cases can be transferred to this mix if needed when reconnecting
3600// after AudioTracks are invalidated
3601//
3602// When playback starts, getOutputForAttr() will:
3603// - 1 look for a mix matching the address passed in attribtutes tags if any
3604// - 2 if none found, look for a mix matching the attributes usage
3605// - 3 if none found, default to device and output selection by policy rules.
3606
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003607status_t AudioPolicyManager::registerPolicyMixes(const Vector<AudioMix>& mixes)
Eric Laurent275e8e92014-11-30 15:14:47 -08003608{
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003609 ALOGV("registerPolicyMixes() %zu mix(es)", mixes.size());
3610 status_t res = NO_ERROR;
Eric Laurentc209fe42020-06-05 18:11:23 -07003611 bool checkOutputs = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003612 sp<HwModule> rSubmixModule;
3613 // examine each mix's route type
3614 for (size_t i = 0; i < mixes.size(); i++) {
Eric Laurent97ac8712018-07-27 18:59:02 -07003615 AudioMix mix = mixes[i];
Kevin Rocard153f92d2018-12-18 18:33:28 -08003616 // Only capture of playback is allowed in LOOP_BACK & RENDER mode
3617 if (is_mix_loopback_render(mix.mRouteFlags) && mix.mMixType != MIX_TYPE_PLAYERS) {
3618 ALOGE("Unsupported Policy Mix %zu of %zu: "
3619 "Only capture of playback is allowed in LOOP_BACK & RENDER mode",
3620 i, mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003621 res = INVALID_OPERATION;
Eric Laurent275e8e92014-11-30 15:14:47 -08003622 break;
3623 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08003624 // LOOP_BACK and LOOP_BACK | RENDER have the same remote submix backend and are handled
3625 // in the same way.
Eric Laurent97ac8712018-07-27 18:59:02 -07003626 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003627 ALOGV("registerPolicyMixes() mix %zu of %zu is LOOP_BACK %d", i, mixes.size(),
3628 mix.mRouteFlags);
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003629 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003630 rSubmixModule = mHwModules.getModuleFromName(
3631 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
3632 if (rSubmixModule == 0) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003633 ALOGE("Unable to find audio module for submix, aborting mix %zu registration",
Mikhail Naganovd4120142017-12-06 15:49:22 -08003634 i);
3635 res = INVALID_OPERATION;
3636 break;
3637 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003638 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003639
Eric Laurent97ac8712018-07-27 18:59:02 -07003640 String8 address = mix.mDeviceAddress;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003641 audio_devices_t deviceTypeToMakeAvailable;
Eric Laurent97ac8712018-07-27 18:59:02 -07003642 if (mix.mMixType == MIX_TYPE_PLAYERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07003643 mix.mDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003644 deviceTypeToMakeAvailable = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
3645 } else {
3646 mix.mDeviceType = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
3647 deviceTypeToMakeAvailable = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Eric Laurent97ac8712018-07-27 18:59:02 -07003648 }
François Gaffie036e1e92015-03-19 10:16:24 +01003649
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003650 if (mPolicyMixes.registerMix(mix, 0 /*output desc*/) != NO_ERROR) {
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003651 ALOGE("Error registering mix %zu for address %s", i, address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003652 res = INVALID_OPERATION;
3653 break;
3654 }
Eric Laurent97ac8712018-07-27 18:59:02 -07003655 audio_config_t outputConfig = mix.mFormat;
3656 audio_config_t inputConfig = mix.mFormat;
Eric Laurentc529cf62020-04-17 18:19:10 -07003657 // NOTE: audio flinger mixer does not support mono output: configure remote submix HAL
3658 // in stereo and let audio flinger do the channel conversion if needed.
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003659 outputConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
3660 inputConfig.channel_mask = AUDIO_CHANNEL_IN_STEREO;
jiabin5740f082019-08-19 15:08:30 -07003661 rSubmixModule->addOutputProfile(address.c_str(), &outputConfig,
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003662 AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address);
jiabin5740f082019-08-19 15:08:30 -07003663 rSubmixModule->addInputProfile(address.c_str(), &inputConfig,
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003664 AUDIO_DEVICE_IN_REMOTE_SUBMIX, address);
François Gaffie036e1e92015-03-19 10:16:24 +01003665
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003666 if ((res = setDeviceConnectionStateInt(deviceTypeToMakeAvailable,
jiabinc1de2df2019-05-07 14:26:40 -07003667 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003668 address.c_str(), "remote-submix", AUDIO_FORMAT_DEFAULT)) != NO_ERROR) {
jiabinc1de2df2019-05-07 14:26:40 -07003669 ALOGE("Failed to set remote submix device available, type %u, address %s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003670 mix.mDeviceType, address.c_str());
jiabinc1de2df2019-05-07 14:26:40 -07003671 break;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003672 }
Eric Laurent97ac8712018-07-27 18:59:02 -07003673 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
3674 String8 address = mix.mDeviceAddress;
Eric Laurent2c80be02019-01-23 18:06:37 -08003675 audio_devices_t type = mix.mDeviceType;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003676 ALOGV(" registerPolicyMixes() mix %zu of %zu is RENDER, dev=0x%X addr=%s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003677 i, mixes.size(), type, address.c_str());
Eric Laurent2c80be02019-01-23 18:06:37 -08003678
3679 sp<DeviceDescriptor> device = mHwModules.getDeviceDescriptor(
3680 mix.mDeviceType, mix.mDeviceAddress,
3681 String8(), AUDIO_FORMAT_DEFAULT);
3682 if (device == nullptr) {
3683 res = INVALID_OPERATION;
3684 break;
3685 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003686
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003687 bool foundOutput = false;
Eric Laurentc529cf62020-04-17 18:19:10 -07003688 // First try to find an already opened output supporting the device
3689 for (size_t j = 0 ; j < mOutputs.size() && !foundOutput && res == NO_ERROR; j++) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003690 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurent2c80be02019-01-23 18:06:37 -08003691
Eric Laurentc529cf62020-04-17 18:19:10 -07003692 if (!desc->isDuplicated() && desc->supportedDevices().contains(device)) {
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003693 if (mPolicyMixes.registerMix(mix, desc) != NO_ERROR) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003694 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003695 address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003696 res = INVALID_OPERATION;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003697 } else {
3698 foundOutput = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003699 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003700 }
3701 }
Eric Laurentc529cf62020-04-17 18:19:10 -07003702 // If no output found, try to find a direct output profile supporting the device
3703 for (size_t i = 0; i < mHwModules.size() && !foundOutput && res == NO_ERROR; i++) {
3704 sp<HwModule> module = mHwModules[i];
3705 for (size_t j = 0;
3706 j < module->getOutputProfiles().size() && !foundOutput && res == NO_ERROR;
3707 j++) {
3708 sp<IOProfile> profile = module->getOutputProfiles()[j];
3709 if (profile->isDirectOutput() && profile->supportsDevice(device)) {
3710 if (mPolicyMixes.registerMix(mix, nullptr) != NO_ERROR) {
3711 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003712 address.c_str());
Eric Laurentc529cf62020-04-17 18:19:10 -07003713 res = INVALID_OPERATION;
3714 } else {
3715 foundOutput = true;
3716 }
3717 }
3718 }
3719 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003720 if (res != NO_ERROR) {
3721 ALOGE(" Error registering mix %zu for device 0x%X addr %s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003722 i, type, address.c_str());
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003723 res = INVALID_OPERATION;
3724 break;
3725 } else if (!foundOutput) {
3726 ALOGE(" Output not found for mix %zu for device 0x%X addr %s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003727 i, type, address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003728 res = INVALID_OPERATION;
3729 break;
Eric Laurentc209fe42020-06-05 18:11:23 -07003730 } else {
3731 checkOutputs = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003732 }
Eric Laurentc722f302014-12-10 11:21:49 -08003733 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003734 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003735 if (res != NO_ERROR) {
3736 unregisterPolicyMixes(mixes);
Eric Laurentc209fe42020-06-05 18:11:23 -07003737 } else if (checkOutputs) {
3738 checkForDeviceAndOutputChanges();
3739 updateCallAndOutputRouting();
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003740 }
3741 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08003742}
3743
3744status_t AudioPolicyManager::unregisterPolicyMixes(Vector<AudioMix> mixes)
3745{
Eric Laurent7b279bb2015-12-14 10:18:23 -08003746 ALOGV("unregisterPolicyMixes() num mixes %zu", mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003747 status_t res = NO_ERROR;
Eric Laurentc209fe42020-06-05 18:11:23 -07003748 bool checkOutputs = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003749 sp<HwModule> rSubmixModule;
3750 // examine each mix's route type
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003751 for (const auto& mix : mixes) {
3752 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie036e1e92015-03-19 10:16:24 +01003753
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003754 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003755 rSubmixModule = mHwModules.getModuleFromName(
3756 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
3757 if (rSubmixModule == 0) {
3758 res = INVALID_OPERATION;
3759 continue;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003760 }
3761 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003762
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003763 String8 address = mix.mDeviceAddress;
Eric Laurent275e8e92014-11-30 15:14:47 -08003764
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003765 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003766 res = INVALID_OPERATION;
3767 continue;
3768 }
3769
Kevin Rocard04ed0462019-05-02 17:53:24 -07003770 for (auto device : {AUDIO_DEVICE_IN_REMOTE_SUBMIX, AUDIO_DEVICE_OUT_REMOTE_SUBMIX}) {
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003771 if (getDeviceConnectionState(device, address.c_str()) ==
Kevin Rocard04ed0462019-05-02 17:53:24 -07003772 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
3773 res = setDeviceConnectionStateInt(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003774 address.c_str(), "remote-submix",
Kevin Rocard04ed0462019-05-02 17:53:24 -07003775 AUDIO_FORMAT_DEFAULT);
3776 if (res != OK) {
3777 ALOGE("Error making RemoteSubmix device unavailable for mix "
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003778 "with type %d, address %s", device, address.c_str());
Kevin Rocard04ed0462019-05-02 17:53:24 -07003779 }
3780 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003781 }
jiabin5740f082019-08-19 15:08:30 -07003782 rSubmixModule->removeOutputProfile(address.c_str());
3783 rSubmixModule->removeInputProfile(address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003784
Kevin Rocard153f92d2018-12-18 18:33:28 -08003785 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003786 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003787 res = INVALID_OPERATION;
3788 continue;
Eric Laurentc209fe42020-06-05 18:11:23 -07003789 } else {
3790 checkOutputs = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003791 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003792 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003793 }
Eric Laurentc209fe42020-06-05 18:11:23 -07003794 if (res == NO_ERROR && checkOutputs) {
3795 checkForDeviceAndOutputChanges();
3796 updateCallAndOutputRouting();
3797 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003798 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08003799}
3800
Jan Sebechlebsky0af8e872023-08-11 14:45:08 +02003801status_t AudioPolicyManager::updatePolicyMix(
3802 const AudioMix& mix,
3803 const std::vector<AudioMixMatchCriterion>& updatedCriteria) {
3804 status_t res = mPolicyMixes.updateMix(mix, updatedCriteria);
3805 if (res == NO_ERROR) {
3806 checkForDeviceAndOutputChanges();
3807 updateCallAndOutputRouting();
3808 }
3809 return res;
3810}
3811
Mikhail Naganov100f0122018-11-29 11:22:16 -08003812void AudioPolicyManager::dumpManualSurroundFormats(String8 *dst) const
3813{
3814 size_t i = 0;
3815 constexpr size_t audioFormatPrefixLen = sizeof("AUDIO_FORMAT_");
3816 for (const auto& fmt : mManualSurroundFormats) {
3817 if (i++ != 0) dst->append(", ");
3818 std::string sfmt;
3819 FormatConverter::toString(fmt, sfmt);
3820 dst->append(sfmt.size() >= audioFormatPrefixLen ?
3821 sfmt.c_str() + audioFormatPrefixLen - 1 : sfmt.c_str());
3822 }
3823}
3824
Eric Laurentc529cf62020-04-17 18:19:10 -07003825// Returns true if all devices types match the predicate and are supported by one HW module
3826bool AudioPolicyManager::areAllDevicesSupported(
jiabin6a02d532020-08-07 11:56:38 -07003827 const AudioDeviceTypeAddrVector& devices,
Eric Laurentc529cf62020-04-17 18:19:10 -07003828 std::function<bool(audio_devices_t)> predicate,
Eric Laurent78fedbf2023-03-09 14:40:44 +01003829 const char *context,
3830 bool matchAddress) {
Eric Laurentc529cf62020-04-17 18:19:10 -07003831 for (size_t i = 0; i < devices.size(); i++) {
3832 sp<DeviceDescriptor> devDesc = mHwModules.getDeviceDescriptor(
jiabin0a488932020-08-07 17:32:40 -07003833 devices[i].mType, devices[i].getAddress(), String8(),
Eric Laurent78fedbf2023-03-09 14:40:44 +01003834 AUDIO_FORMAT_DEFAULT, false /*allowToCreate*/, matchAddress);
Eric Laurentc529cf62020-04-17 18:19:10 -07003835 if (devDesc == nullptr || (predicate != nullptr && !predicate(devices[i].mType))) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003836 ALOGE("%s: device type %#x address %s not supported or not match predicate",
jiabin0a488932020-08-07 17:32:40 -07003837 context, devices[i].mType, devices[i].getAddress());
Eric Laurentc529cf62020-04-17 18:19:10 -07003838 return false;
3839 }
3840 }
3841 return true;
3842}
3843
Oscar Azucena6acf34b2023-04-27 16:32:09 -07003844void AudioPolicyManager::changeOutputDevicesMuteState(
3845 const AudioDeviceTypeAddrVector& devices) {
3846 ALOGVV("%s() num devices %zu", __func__, devices.size());
3847
3848 std::vector<sp<SwAudioOutputDescriptor>> outputs =
3849 getSoftwareOutputsForDevices(devices);
3850
3851 for (size_t i = 0; i < outputs.size(); i++) {
3852 sp<SwAudioOutputDescriptor> outputDesc = outputs[i];
3853 DeviceVector prevDevices = outputDesc->devices();
3854 checkDeviceMuteStrategies(outputDesc, prevDevices, 0 /* delayMs */);
3855 }
3856}
3857
3858std::vector<sp<SwAudioOutputDescriptor>> AudioPolicyManager::getSoftwareOutputsForDevices(
3859 const AudioDeviceTypeAddrVector& devices) const
3860{
3861 std::vector<sp<SwAudioOutputDescriptor>> outputs;
3862 DeviceVector deviceDescriptors;
3863 for (size_t j = 0; j < devices.size(); j++) {
3864 sp<DeviceDescriptor> desc = mHwModules.getDeviceDescriptor(
3865 devices[j].mType, devices[j].getAddress(), String8(), AUDIO_FORMAT_DEFAULT);
3866 if (desc == nullptr || !audio_is_output_device(devices[j].mType)) {
3867 ALOGE("%s: device type %#x address %s not supported or not an output device",
3868 __func__, devices[j].mType, devices[j].getAddress());
3869 continue;
3870 }
3871 deviceDescriptors.add(desc);
3872 }
3873 for (size_t i = 0; i < mOutputs.size(); i++) {
3874 if (!mOutputs.valueAt(i)->supportsAtLeastOne(deviceDescriptors)) {
3875 continue;
3876 }
3877 outputs.push_back(mOutputs.valueAt(i));
3878 }
3879 return outputs;
3880}
3881
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003882status_t AudioPolicyManager::setUidDeviceAffinities(uid_t uid,
jiabin6a02d532020-08-07 11:56:38 -07003883 const AudioDeviceTypeAddrVector& devices) {
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003884 ALOGV("%s() uid=%d num devices %zu", __FUNCTION__, uid, devices.size());
Eric Laurentc529cf62020-04-17 18:19:10 -07003885 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
3886 return BAD_VALUE;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003887 }
3888 status_t res = mPolicyMixes.setUidDeviceAffinities(uid, devices);
Eric Laurentc529cf62020-04-17 18:19:10 -07003889 if (res != NO_ERROR) {
3890 ALOGE("%s() Could not set all device affinities for uid = %d", __FUNCTION__, uid);
3891 return res;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003892 }
Eric Laurentc529cf62020-04-17 18:19:10 -07003893
3894 checkForDeviceAndOutputChanges();
3895 updateCallAndOutputRouting();
3896
3897 return NO_ERROR;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003898}
3899
3900status_t AudioPolicyManager::removeUidDeviceAffinities(uid_t uid) {
3901 ALOGV("%s() uid=%d", __FUNCTION__, uid);
Oscar Azucena4b2a8212019-04-26 23:48:59 -07003902 status_t res = mPolicyMixes.removeUidDeviceAffinities(uid);
3903 if (res != NO_ERROR) {
Eric Laurentc529cf62020-04-17 18:19:10 -07003904 ALOGE("%s() Could not remove all device affinities for uid = %d",
Oscar Azucena4b2a8212019-04-26 23:48:59 -07003905 __FUNCTION__, uid);
3906 return INVALID_OPERATION;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003907 }
3908
Eric Laurentc529cf62020-04-17 18:19:10 -07003909 checkForDeviceAndOutputChanges();
3910 updateCallAndOutputRouting();
3911
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003912 return res;
3913}
3914
Eric Laurent2517af32020-11-25 15:31:27 +01003915
jiabin0a488932020-08-07 17:32:40 -07003916status_t AudioPolicyManager::setDevicesRoleForStrategy(product_strategy_t strategy,
3917 device_role_t role,
3918 const AudioDeviceTypeAddrVector &devices) {
3919 ALOGV("%s() strategy=%d role=%d %s", __func__, strategy, role,
3920 dumpAudioDeviceTypeAddrVector(devices).c_str());
Eric Laurentc529cf62020-04-17 18:19:10 -07003921
Eric Laurentc529cf62020-04-17 18:19:10 -07003922 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003923 return BAD_VALUE;
3924 }
jiabin0a488932020-08-07 17:32:40 -07003925 status_t status = mEngine->setDevicesRoleForStrategy(strategy, role, devices);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003926 if (status != NO_ERROR) {
jiabin0a488932020-08-07 17:32:40 -07003927 ALOGW("Engine could not set preferred devices %s for strategy %d role %d",
3928 dumpAudioDeviceTypeAddrVector(devices).c_str(), strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003929 return status;
3930 }
3931
3932 checkForDeviceAndOutputChanges();
Eric Laurent2517af32020-11-25 15:31:27 +01003933
3934 bool forceVolumeReeval = false;
3935 // FIXME: workaround for truncated touch sounds
3936 // to be removed when the problem is handled by system UI
3937 uint32_t delayMs = 0;
3938 if (strategy == mCommunnicationStrategy) {
3939 forceVolumeReeval = true;
3940 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
3941 updateInputRouting();
3942 }
3943 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003944
3945 return NO_ERROR;
3946}
3947
Oscar Azucena6acf34b2023-04-27 16:32:09 -07003948void AudioPolicyManager::updateCallAndOutputRouting(bool forceVolumeReeval, uint32_t delayMs,
3949 bool skipDelays)
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003950{
3951 uint32_t waitMs = 0;
Eric Laurent96d1dda2022-03-14 17:14:19 +01003952 bool wasLeUnicastActive = isLeUnicastActive();
Francois Gaffie19fd6c52021-02-04 17:02:59 +01003953 if (updateCallRouting(true /*fromCache*/, delayMs, &waitMs) == NO_ERROR) {
Eric Laurentb36b4ac2020-08-21 12:50:41 -07003954 // Only apply special touch sound delay once
3955 delayMs = 0;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003956 }
jiabin3ff8d7d2022-12-13 06:27:44 +00003957 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003958 for (size_t i = 0; i < mOutputs.size(); i++) {
3959 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
3960 DeviceVector newDevices = getNewOutputDevices(outputDesc, true /*fromCache*/);
Francois Gaffie601801d2021-06-22 13:27:39 +02003961 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) ||
3962 (outputDesc != mPrimaryOutput && !isTelephonyRxOrTx(outputDesc))) {
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003963 // As done in setDeviceConnectionState, we could also fix default device issue by
3964 // preventing the force re-routing in case of default dev that distinguishes on address.
3965 // Let's give back to engine full device choice decision however.
Francois Gaffie601801d2021-06-22 13:27:39 +02003966 bool forceRouting = !newDevices.isEmpty();
jiabin3ff8d7d2022-12-13 06:27:44 +00003967 if (outputDesc->mUsePreferredMixerAttributes && newDevices != outputDesc->devices()) {
3968 // If the device is using preferred mixer attributes, the output need to reopen
3969 // with default configuration when the new selected devices are different from
3970 // current routing devices.
3971 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices);
3972 continue;
3973 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05303974
3975 waitMs = setOutputDevices(__func__, outputDesc, newDevices, forceRouting, delayMs,
3976 nullptr, !skipDelays /*requiresMuteCheck*/,
Oscar Azucena6acf34b2023-04-27 16:32:09 -07003977 !forceRouting /*requiresVolumeCheck*/, skipDelays);
Eric Laurentb36b4ac2020-08-21 12:50:41 -07003978 // Only apply special touch sound delay once
3979 delayMs = 0;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003980 }
3981 if (forceVolumeReeval && !newDevices.isEmpty()) {
3982 applyStreamVolumes(outputDesc, newDevices.types(), waitMs, true);
3983 }
3984 }
jiabin3ff8d7d2022-12-13 06:27:44 +00003985 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent96d1dda2022-03-14 17:14:19 +01003986 checkLeBroadcastRoutes(wasLeUnicastActive, nullptr, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003987}
3988
Eric Laurent2517af32020-11-25 15:31:27 +01003989void AudioPolicyManager::updateInputRouting() {
3990 for (const auto& activeDesc : mInputs.getActiveInputs()) {
Jaideep Sharma408349a2020-11-27 14:47:17 +05303991 // Skip for hotword recording as the input device switch
3992 // is handled within sound trigger HAL
3993 if (activeDesc->isSoundTrigger() && activeDesc->source() == AUDIO_SOURCE_HOTWORD) {
3994 continue;
3995 }
Eric Laurent2517af32020-11-25 15:31:27 +01003996 auto newDevice = getNewInputDevice(activeDesc);
3997 // Force new input selection if the new device can not be reached via current input
3998 if (activeDesc->mProfile->getSupportedDevices().contains(newDevice)) {
3999 setInputDevice(activeDesc->mIoHandle, newDevice);
4000 } else {
4001 closeInput(activeDesc->mIoHandle);
4002 }
4003 }
4004}
4005
Paul Wang5d7cdb52022-11-22 09:45:06 +00004006status_t
4007AudioPolicyManager::removeDevicesRoleForStrategy(product_strategy_t strategy,
4008 device_role_t role,
4009 const AudioDeviceTypeAddrVector &devices) {
4010 ALOGV("%s() strategy=%d role=%d %s", __func__, strategy, role,
4011 dumpAudioDeviceTypeAddrVector(devices).c_str());
4012
Eric Laurent78fedbf2023-03-09 14:40:44 +01004013 if (!areAllDevicesSupported(
4014 devices, audio_is_output_device, __func__, /*matchAddress*/false)) {
Paul Wang5d7cdb52022-11-22 09:45:06 +00004015 return BAD_VALUE;
4016 }
4017 status_t status = mEngine->removeDevicesRoleForStrategy(strategy, role, devices);
4018 if (status != NO_ERROR) {
4019 ALOGW("Engine could not remove devices %s for strategy %d role %d",
4020 dumpAudioDeviceTypeAddrVector(devices).c_str(), strategy, role);
4021 return status;
4022 }
4023
4024 checkForDeviceAndOutputChanges();
4025
4026 bool forceVolumeReeval = false;
4027 // TODO(b/263479999): workaround for truncated touch sounds
4028 // to be removed when the problem is handled by system UI
4029 uint32_t delayMs = 0;
4030 if (strategy == mCommunnicationStrategy) {
4031 forceVolumeReeval = true;
4032 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
4033 updateInputRouting();
4034 }
4035 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
4036
4037 return NO_ERROR;
4038}
4039
4040status_t AudioPolicyManager::clearDevicesRoleForStrategy(product_strategy_t strategy,
4041 device_role_t role)
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004042{
Eric Laurentfecbceb2021-02-09 14:46:43 +01004043 ALOGV("%s() strategy=%d role=%d", __func__, strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004044
Paul Wang5d7cdb52022-11-22 09:45:06 +00004045 status_t status = mEngine->clearDevicesRoleForStrategy(strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004046 if (status != NO_ERROR) {
Eric Laurent9ae44f32022-12-14 16:17:02 +01004047 ALOGW_IF(status != NAME_NOT_FOUND,
4048 "Engine could not remove device role for strategy %d status %d",
Eric Laurent2517af32020-11-25 15:31:27 +01004049 strategy, status);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004050 return status;
4051 }
4052
4053 checkForDeviceAndOutputChanges();
Eric Laurent2517af32020-11-25 15:31:27 +01004054
4055 bool forceVolumeReeval = false;
4056 // FIXME: workaround for truncated touch sounds
4057 // to be removed when the problem is handled by system UI
4058 uint32_t delayMs = 0;
4059 if (strategy == mCommunnicationStrategy) {
4060 forceVolumeReeval = true;
4061 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
4062 updateInputRouting();
4063 }
4064 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004065
4066 return NO_ERROR;
4067}
4068
jiabin0a488932020-08-07 17:32:40 -07004069status_t AudioPolicyManager::getDevicesForRoleAndStrategy(product_strategy_t strategy,
4070 device_role_t role,
4071 AudioDeviceTypeAddrVector &devices) {
4072 return mEngine->getDevicesForRoleAndStrategy(strategy, role, devices);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004073}
4074
Jiabin Huang3b98d322020-09-03 17:54:16 +00004075status_t AudioPolicyManager::setDevicesRoleForCapturePreset(
4076 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices) {
4077 ALOGV("%s() audioSource=%d role=%d %s", __func__, audioSource, role,
4078 dumpAudioDeviceTypeAddrVector(devices).c_str());
4079
Mikhail Naganov55773032020-10-01 15:08:13 -07004080 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00004081 return BAD_VALUE;
4082 }
4083 status_t status = mEngine->setDevicesRoleForCapturePreset(audioSource, role, devices);
4084 ALOGW_IF(status != NO_ERROR,
4085 "Engine could not set preferred devices %s for audio source %d role %d",
4086 dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
4087
4088 return status;
4089}
4090
4091status_t AudioPolicyManager::addDevicesRoleForCapturePreset(
4092 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices) {
4093 ALOGV("%s() audioSource=%d role=%d %s", __func__, audioSource, role,
4094 dumpAudioDeviceTypeAddrVector(devices).c_str());
4095
Mikhail Naganov55773032020-10-01 15:08:13 -07004096 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00004097 return BAD_VALUE;
4098 }
4099 status_t status = mEngine->addDevicesRoleForCapturePreset(audioSource, role, devices);
4100 ALOGW_IF(status != NO_ERROR,
4101 "Engine could not add preferred devices %s for audio source %d role %d",
4102 dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
4103
Eric Laurent2517af32020-11-25 15:31:27 +01004104 updateInputRouting();
Jiabin Huang3b98d322020-09-03 17:54:16 +00004105 return status;
4106}
4107
4108status_t AudioPolicyManager::removeDevicesRoleForCapturePreset(
4109 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector& devices)
4110{
4111 ALOGV("%s() audioSource=%d role=%d devices=%s", __func__, audioSource, role,
4112 dumpAudioDeviceTypeAddrVector(devices).c_str());
4113
Eric Laurent78fedbf2023-03-09 14:40:44 +01004114 if (!areAllDevicesSupported(
4115 devices, audio_call_is_input_device, __func__, /*matchAddress*/false)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00004116 return BAD_VALUE;
4117 }
4118
4119 status_t status = mEngine->removeDevicesRoleForCapturePreset(
4120 audioSource, role, devices);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004121 ALOGW_IF(status != NO_ERROR && status != NAME_NOT_FOUND,
Jiabin Huang3b98d322020-09-03 17:54:16 +00004122 "Engine could not remove devices role (%d) for capture preset %d", role, audioSource);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004123 if (status == NO_ERROR) {
4124 updateInputRouting();
4125 }
Jiabin Huang3b98d322020-09-03 17:54:16 +00004126 return status;
4127}
4128
4129status_t AudioPolicyManager::clearDevicesRoleForCapturePreset(audio_source_t audioSource,
4130 device_role_t role) {
4131 ALOGV("%s() audioSource=%d role=%d", __func__, audioSource, role);
4132
4133 status_t status = mEngine->clearDevicesRoleForCapturePreset(audioSource, role);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004134 ALOGW_IF(status != NO_ERROR && status != NAME_NOT_FOUND,
Jiabin Huang3b98d322020-09-03 17:54:16 +00004135 "Engine could not clear devices role (%d) for capture preset %d", role, audioSource);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004136 if (status == NO_ERROR) {
4137 updateInputRouting();
4138 }
Jiabin Huang3b98d322020-09-03 17:54:16 +00004139 return status;
4140}
4141
4142status_t AudioPolicyManager::getDevicesForRoleAndCapturePreset(
4143 audio_source_t audioSource, device_role_t role, AudioDeviceTypeAddrVector &devices) {
4144 return mEngine->getDevicesForRoleAndCapturePreset(audioSource, role, devices);
4145}
4146
Oscar Azucena90e77632019-11-27 17:12:28 -08004147status_t AudioPolicyManager::setUserIdDeviceAffinities(int userId,
jiabin6a02d532020-08-07 11:56:38 -07004148 const AudioDeviceTypeAddrVector& devices) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01004149 ALOGV("%s() userId=%d num devices %zu", __func__, userId, devices.size());
Eric Laurentc529cf62020-04-17 18:19:10 -07004150 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
4151 return BAD_VALUE;
Oscar Azucena90e77632019-11-27 17:12:28 -08004152 }
Oscar Azucena90e77632019-11-27 17:12:28 -08004153 status_t status = mPolicyMixes.setUserIdDeviceAffinities(userId, devices);
4154 if (status != NO_ERROR) {
4155 ALOGE("%s() could not set device affinity for userId %d",
4156 __FUNCTION__, userId);
4157 return status;
4158 }
4159
4160 // reevaluate outputs for all devices
4161 checkForDeviceAndOutputChanges();
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004162 changeOutputDevicesMuteState(devices);
4163 updateCallAndOutputRouting(false /* forceVolumeReeval */, 0 /* delayMs */,
4164 true /* skipDelays */);
4165 changeOutputDevicesMuteState(devices);
Oscar Azucena90e77632019-11-27 17:12:28 -08004166
4167 return NO_ERROR;
4168}
4169
4170status_t AudioPolicyManager::removeUserIdDeviceAffinities(int userId) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01004171 ALOGV("%s() userId=%d", __FUNCTION__, userId);
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004172 AudioDeviceTypeAddrVector devices;
4173 mPolicyMixes.getDevicesForUserId(userId, devices);
Oscar Azucena90e77632019-11-27 17:12:28 -08004174 status_t status = mPolicyMixes.removeUserIdDeviceAffinities(userId);
4175 if (status != NO_ERROR) {
4176 ALOGE("%s() Could not remove all device affinities fo userId = %d",
4177 __FUNCTION__, userId);
4178 return status;
4179 }
4180
4181 // reevaluate outputs for all devices
4182 checkForDeviceAndOutputChanges();
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004183 changeOutputDevicesMuteState(devices);
4184 updateCallAndOutputRouting(false /* forceVolumeReeval */, 0 /* delayMs */,
4185 true /* skipDelays */);
4186 changeOutputDevicesMuteState(devices);
Oscar Azucena90e77632019-11-27 17:12:28 -08004187
4188 return NO_ERROR;
4189}
4190
Andy Hungc29d82b2018-10-05 12:23:17 -07004191void AudioPolicyManager::dump(String8 *dst) const
Eric Laurente552edb2014-03-10 17:42:56 -07004192{
Andy Hungc29d82b2018-10-05 12:23:17 -07004193 dst->appendFormat("\nAudioPolicyManager Dump: %p\n", this);
Mikhail Naganov0dbe87b2021-12-01 02:03:31 +00004194 dst->appendFormat(" Primary Output I/O handle: %d\n",
Eric Laurent87ffa392015-05-22 10:32:38 -07004195 hasPrimaryOutput() ? mPrimaryOutput->mIoHandle : AUDIO_IO_HANDLE_NONE);
Mikhail Naganov0d6a0332016-04-19 17:12:38 -07004196 std::string stateLiteral;
4197 AudioModeConverter::toString(mEngine->getPhoneState(), stateLiteral);
Andy Hungc29d82b2018-10-05 12:23:17 -07004198 dst->appendFormat(" Phone state: %s\n", stateLiteral.c_str());
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07004199 const char* forceUses[AUDIO_POLICY_FORCE_USE_CNT] = {
4200 "communications", "media", "record", "dock", "system",
4201 "HDMI system audio", "encoded surround output", "vibrate ringing" };
4202 for (audio_policy_force_use_t i = AUDIO_POLICY_FORCE_FOR_COMMUNICATION;
4203 i < AUDIO_POLICY_FORCE_USE_CNT; i = (audio_policy_force_use_t)((int)i + 1)) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08004204 audio_policy_forced_cfg_t forceUseValue = mEngine->getForceUse(i);
4205 dst->appendFormat(" Force use for %s: %d", forceUses[i], forceUseValue);
4206 if (i == AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND &&
4207 forceUseValue == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
4208 dst->append(" (MANUAL: ");
4209 dumpManualSurroundFormats(dst);
4210 dst->append(")");
4211 }
4212 dst->append("\n");
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07004213 }
Andy Hungc29d82b2018-10-05 12:23:17 -07004214 dst->appendFormat(" TTS output %savailable\n", mTtsOutputAvailable ? "" : "not ");
4215 dst->appendFormat(" Master mono: %s\n", mMasterMono ? "on" : "off");
Mikhail Naganovb3bcb4f2022-02-23 23:46:56 +00004216 dst->appendFormat(" Communication Strategy id: %d\n", mCommunnicationStrategy);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07004217 dst->appendFormat(" Config source: %s\n", mConfig->getSource().c_str());
Eric Laurent2517af32020-11-25 15:31:27 +01004218
Mikhail Naganov0f413b22021-12-02 05:29:27 +00004219 dst->append("\n");
4220 mAvailableOutputDevices.dump(dst, String8("Available output"), 1);
4221 dst->append("\n");
4222 mAvailableInputDevices.dump(dst, String8("Available input"), 1);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07004223 mHwModules.dump(dst);
Andy Hungc29d82b2018-10-05 12:23:17 -07004224 mOutputs.dump(dst);
4225 mInputs.dump(dst);
Mikhail Naganov0f413b22021-12-02 05:29:27 +00004226 mEffects.dump(dst, 1);
Andy Hungc29d82b2018-10-05 12:23:17 -07004227 mAudioPatches.dump(dst);
4228 mPolicyMixes.dump(dst);
4229 mAudioSources.dump(dst);
François Gaffiec005e562018-11-06 15:04:49 +01004230
Kevin Rocardb99cc752019-03-21 20:52:24 -07004231 dst->appendFormat(" AllowedCapturePolicies:\n");
4232 for (auto& policy : mAllowedCapturePolicies) {
4233 dst->appendFormat(" - uid=%d flag_mask=%#x\n", policy.first, policy.second);
4234 }
4235
jiabina84c3d32022-12-02 18:59:55 +00004236 dst->appendFormat(" Preferred mixer audio configuration:\n");
4237 for (const auto it : mPreferredMixerAttrInfos) {
4238 dst->appendFormat(" - device port id: %d\n", it.first);
4239 for (const auto preferredMixerInfoIt : it.second) {
4240 dst->appendFormat(" - strategy: %d; ", preferredMixerInfoIt.first);
4241 preferredMixerInfoIt.second->dump(dst);
4242 }
4243 }
4244
François Gaffiec005e562018-11-06 15:04:49 +01004245 dst->appendFormat("\nPolicy Engine dump:\n");
4246 mEngine->dump(dst);
Andy Hungc29d82b2018-10-05 12:23:17 -07004247}
4248
4249status_t AudioPolicyManager::dump(int fd)
4250{
4251 String8 result;
4252 dump(&result);
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004253 write(fd, result.c_str(), result.size());
Eric Laurente552edb2014-03-10 17:42:56 -07004254 return NO_ERROR;
4255}
4256
Kevin Rocardb99cc752019-03-21 20:52:24 -07004257status_t AudioPolicyManager::setAllowedCapturePolicy(uid_t uid, audio_flags_mask_t capturePolicy)
4258{
4259 mAllowedCapturePolicies[uid] = capturePolicy;
4260 return NO_ERROR;
4261}
4262
Eric Laurente552edb2014-03-10 17:42:56 -07004263// This function checks for the parameters which can be offloaded.
4264// This can be enhanced depending on the capability of the DSP and policy
4265// of the system.
Eric Laurent90fe31c2020-11-26 20:06:35 +01004266audio_offload_mode_t AudioPolicyManager::getOffloadSupport(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07004267{
Eric Laurent90fe31c2020-11-26 20:06:35 +01004268 ALOGV("%s: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07004269 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurent90fe31c2020-11-26 20:06:35 +01004270 __func__, offloadInfo.sample_rate, offloadInfo.channel_mask,
Eric Laurente552edb2014-03-10 17:42:56 -07004271 offloadInfo.format,
4272 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
4273 offloadInfo.has_video);
4274
jiabin2b9d5a12021-12-10 01:06:29 +00004275 if (!isOffloadPossible(offloadInfo)) {
Eric Laurent90fe31c2020-11-26 20:06:35 +01004276 return AUDIO_OFFLOAD_NOT_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07004277 }
4278
4279 // See if there is a profile to support this.
4280 // AUDIO_DEVICE_NONE
François Gaffie11d30102018-11-02 16:09:09 +01004281 sp<IOProfile> profile = getProfileForOutput(DeviceVector() /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07004282 offloadInfo.sample_rate,
4283 offloadInfo.format,
4284 offloadInfo.channel_mask,
Michael Chana94fbb22018-04-24 14:31:19 +10004285 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD,
4286 true /* directOnly */);
Eric Laurent94365442021-01-08 18:36:05 +01004287 ALOGV("%s: profile %sfound%s", __func__, profile != nullptr ? "" : "NOT ",
4288 (profile != nullptr && (profile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD) != 0)
4289 ? ", supports gapless" : "");
Eric Laurent90fe31c2020-11-26 20:06:35 +01004290 if (profile == nullptr) {
4291 return AUDIO_OFFLOAD_NOT_SUPPORTED;
4292 }
4293 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD) != 0) {
4294 return AUDIO_OFFLOAD_GAPLESS_SUPPORTED;
4295 }
4296 return AUDIO_OFFLOAD_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07004297}
4298
Michael Chana94fbb22018-04-24 14:31:19 +10004299bool AudioPolicyManager::isDirectOutputSupported(const audio_config_base_t& config,
4300 const audio_attributes_t& attributes) {
4301 audio_output_flags_t output_flags = AUDIO_OUTPUT_FLAG_NONE;
François Gaffie58d4be52018-11-06 15:30:12 +01004302 audio_flags_to_audio_output_flags(attributes.flags, &output_flags);
Dorin Drimus9901eb02022-01-14 11:36:51 +00004303 DeviceVector outputDevices = mEngine->getOutputDevicesForAttributes(attributes);
4304 sp<IOProfile> profile = getProfileForOutput(outputDevices,
Michael Chana94fbb22018-04-24 14:31:19 +10004305 config.sample_rate,
4306 config.format,
4307 config.channel_mask,
4308 output_flags,
4309 true /* directOnly */);
4310 ALOGV("%s() profile %sfound with name: %s, "
4311 "sample rate: %u, format: 0x%x, channel_mask: 0x%x, output flags: 0x%x",
4312 __FUNCTION__, profile != 0 ? "" : "NOT ",
jiabin5740f082019-08-19 15:08:30 -07004313 (profile != 0 ? profile->getTagName().c_str() : "null"),
Michael Chana94fbb22018-04-24 14:31:19 +10004314 config.sample_rate, config.format, config.channel_mask, output_flags);
Dorin Drimusecc9f422022-03-09 17:57:40 +01004315
4316 // also try the MSD module if compatible profile not found
4317 if (profile == nullptr) {
4318 profile = getMsdProfileForOutput(outputDevices,
4319 config.sample_rate,
4320 config.format,
4321 config.channel_mask,
4322 output_flags,
4323 true /* directOnly */);
4324 ALOGV("%s() MSD 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 ",
4327 (profile != 0 ? profile->getTagName().c_str() : "null"),
4328 config.sample_rate, config.format, config.channel_mask, output_flags);
4329 }
4330 return (profile != nullptr);
Michael Chana94fbb22018-04-24 14:31:19 +10004331}
4332
jiabin2b9d5a12021-12-10 01:06:29 +00004333bool AudioPolicyManager::isOffloadPossible(const audio_offload_info_t &offloadInfo,
4334 bool durationIgnored) {
4335 if (mMasterMono) {
4336 return false; // no offloading if mono is set.
4337 }
4338
4339 // Check if offload has been disabled
4340 if (property_get_bool("audio.offload.disable", false /* default_value */)) {
4341 ALOGV("%s: offload disabled by audio.offload.disable", __func__);
4342 return false;
4343 }
4344
4345 // Check if stream type is music, then only allow offload as of now.
4346 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
4347 {
4348 ALOGV("%s: stream_type != MUSIC, returning false", __func__);
4349 return false;
4350 }
4351
4352 //TODO: enable audio offloading with video when ready
4353 const bool allowOffloadWithVideo =
4354 property_get_bool("audio.offload.video", false /* default_value */);
4355 if (offloadInfo.has_video && !allowOffloadWithVideo) {
4356 ALOGV("%s: has_video == true, returning false", __func__);
4357 return false;
4358 }
4359
4360 //If duration is less than minimum value defined in property, return false
4361 const int min_duration_secs = property_get_int32(
4362 "audio.offload.min.duration.secs", -1 /* default_value */);
4363 if (!durationIgnored) {
4364 if (min_duration_secs >= 0) {
4365 if (offloadInfo.duration_us < min_duration_secs * 1000000LL) {
4366 ALOGV("%s: Offload denied by duration < audio.offload.min.duration.secs(=%d)",
4367 __func__, min_duration_secs);
4368 return false;
4369 }
4370 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
4371 ALOGV("%s: Offload denied by duration < default min(=%u)",
4372 __func__, OFFLOAD_DEFAULT_MIN_DURATION_SECS);
4373 return false;
4374 }
4375 }
4376
4377 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
4378 // creating an offloaded track and tearing it down immediately after start when audioflinger
4379 // detects there is an active non offloadable effect.
4380 // FIXME: We should check the audio session here but we do not have it in this context.
4381 // This may prevent offloading in rare situations where effects are left active by apps
4382 // in the background.
4383 if (mEffects.isNonOffloadableEffectEnabled()) {
4384 return false;
4385 }
4386
4387 return true;
4388}
4389
4390audio_direct_mode_t AudioPolicyManager::getDirectPlaybackSupport(const audio_attributes_t *attr,
4391 const audio_config_t *config) {
4392 audio_offload_info_t offloadInfo = AUDIO_INFO_INITIALIZER;
4393 offloadInfo.format = config->format;
4394 offloadInfo.sample_rate = config->sample_rate;
4395 offloadInfo.channel_mask = config->channel_mask;
4396 offloadInfo.stream_type = mEngine->getStreamTypeForAttributes(*attr);
4397 offloadInfo.has_video = false;
4398 offloadInfo.is_streaming = false;
4399 const bool offloadPossible = isOffloadPossible(offloadInfo, true /*durationIgnored*/);
4400
4401 audio_direct_mode_t directMode = AUDIO_DIRECT_NOT_SUPPORTED;
4402 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
4403 audio_flags_to_audio_output_flags(attr->flags, &flags);
4404 // only retain flags that will drive compressed offload or passthrough
4405 uint32_t relevantFlags = AUDIO_OUTPUT_FLAG_HW_AV_SYNC;
4406 if (offloadPossible) {
4407 relevantFlags |= AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD;
4408 }
4409 flags = (audio_output_flags_t)((flags & relevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
4410
Dorin Drimusfae3c642022-03-17 18:36:30 +01004411 DeviceVector engineOutputDevices = mEngine->getOutputDevicesForAttributes(*attr);
jiabin2b9d5a12021-12-10 01:06:29 +00004412 for (const auto& hwModule : mHwModules) {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004413 DeviceVector outputDevices = engineOutputDevices;
4414 // the MSD module checks for different conditions and output devices
4415 if (strcmp(hwModule->getName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0) {
4416 if (!msdHasPatchesToAllDevices(engineOutputDevices.toTypeAddrVector())) {
4417 continue;
4418 }
4419 outputDevices = getMsdAudioOutDevices();
4420 }
jiabin2b9d5a12021-12-10 01:06:29 +00004421 for (const auto& curProfile : hwModule->getOutputProfiles()) {
jiabinc8f7dfc2022-01-06 18:42:08 +00004422 if (!curProfile->isCompatibleProfile(outputDevices,
jiabin2b9d5a12021-12-10 01:06:29 +00004423 config->sample_rate, nullptr /*updatedSamplingRate*/,
4424 config->format, nullptr /*updatedFormat*/,
4425 config->channel_mask, nullptr /*updatedChannelMask*/,
4426 flags)) {
4427 continue;
4428 }
4429 // reject profiles not corresponding to a device currently available
4430 if (!mAvailableOutputDevices.containsAtLeastOne(curProfile->getSupportedDevices())) {
4431 continue;
4432 }
4433 if ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)
4434 != AUDIO_OUTPUT_FLAG_NONE) {
jiabinc6132d62022-01-01 07:36:31 +00004435 if ((directMode & AUDIO_DIRECT_OFFLOAD_GAPLESS_SUPPORTED)
jiabin2b9d5a12021-12-10 01:06:29 +00004436 != AUDIO_DIRECT_NOT_SUPPORTED) {
4437 // Already reports offload gapless supported. No need to report offload support.
4438 continue;
4439 }
4440 if ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD)
4441 != AUDIO_OUTPUT_FLAG_NONE) {
4442 // If offload gapless is reported, no need to report offload support.
4443 directMode = (audio_direct_mode_t) ((directMode &
4444 ~AUDIO_DIRECT_OFFLOAD_SUPPORTED) |
4445 AUDIO_DIRECT_OFFLOAD_GAPLESS_SUPPORTED);
4446 } else {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004447 directMode = (audio_direct_mode_t)(directMode | AUDIO_DIRECT_OFFLOAD_SUPPORTED);
jiabin2b9d5a12021-12-10 01:06:29 +00004448 }
4449 } else {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004450 directMode = (audio_direct_mode_t) (directMode | AUDIO_DIRECT_BITSTREAM_SUPPORTED);
jiabin2b9d5a12021-12-10 01:06:29 +00004451 }
4452 }
4453 }
4454 return directMode;
4455}
4456
Dorin Drimusf2196d82022-01-03 12:11:18 +01004457status_t AudioPolicyManager::getDirectProfilesForAttributes(const audio_attributes_t* attr,
4458 AudioProfileVector& audioProfilesVector) {
Dorin Drimus17112632022-09-23 15:28:51 +00004459 if (mEffects.isNonOffloadableEffectEnabled()) {
4460 return OK;
4461 }
jiabinf1c73972022-04-14 16:28:52 -07004462 DeviceVector devices;
4463 status_t status = getDevicesForAttributes(*attr, devices, false /* forVolume */);
Dorin Drimusf2196d82022-01-03 12:11:18 +01004464 if (status != OK) {
4465 return status;
4466 }
4467 ALOGV("%s: found %zu output devices for attributes.", __func__, devices.size());
4468 if (devices.empty()) {
4469 return OK; // no output devices for the attributes
4470 }
jiabinf1c73972022-04-14 16:28:52 -07004471 return getProfilesForDevices(devices, audioProfilesVector,
4472 AUDIO_OUTPUT_FLAG_DIRECT /*flags*/, false /*isInput*/);
Dorin Drimusf2196d82022-01-03 12:11:18 +01004473}
4474
jiabina84c3d32022-12-02 18:59:55 +00004475status_t AudioPolicyManager::getSupportedMixerAttributes(
4476 audio_port_handle_t portId, std::vector<audio_mixer_attributes_t> &mixerAttrs) {
4477 ALOGV("%s, portId=%d", __func__, portId);
4478 sp<DeviceDescriptor> deviceDescriptor = mAvailableOutputDevices.getDeviceFromId(portId);
4479 if (deviceDescriptor == nullptr) {
4480 ALOGE("%s the requested device is currently unavailable", __func__);
4481 return BAD_VALUE;
4482 }
jiabin96daffc2023-05-11 17:51:55 +00004483 if (!audio_is_usb_out_device(deviceDescriptor->type())) {
4484 ALOGE("%s the requested device(type=%#x) is not usb device", __func__,
4485 deviceDescriptor->type());
4486 return BAD_VALUE;
4487 }
jiabina84c3d32022-12-02 18:59:55 +00004488 for (const auto& hwModule : mHwModules) {
4489 for (const auto& curProfile : hwModule->getOutputProfiles()) {
4490 if (curProfile->supportsDevice(deviceDescriptor)) {
4491 curProfile->toSupportedMixerAttributes(&mixerAttrs);
4492 }
4493 }
4494 }
4495 return NO_ERROR;
4496}
4497
4498status_t AudioPolicyManager::setPreferredMixerAttributes(
4499 const audio_attributes_t *attr,
4500 audio_port_handle_t portId,
4501 uid_t uid,
4502 const audio_mixer_attributes_t *mixerAttributes) {
4503 ALOGV("%s, attr=%s, mixerAttributes={format=%#x, channelMask=%#x, samplingRate=%u, "
4504 "mixerBehavior=%d}, uid=%d, portId=%u",
4505 __func__, toString(*attr).c_str(), mixerAttributes->config.format,
4506 mixerAttributes->config.channel_mask, mixerAttributes->config.sample_rate,
4507 mixerAttributes->mixer_behavior, uid, portId);
4508 if (attr->usage != AUDIO_USAGE_MEDIA) {
4509 ALOGE("%s failed, only media is allowed, the given usage is %d", __func__, attr->usage);
4510 return BAD_VALUE;
4511 }
4512 sp<DeviceDescriptor> deviceDescriptor = mAvailableOutputDevices.getDeviceFromId(portId);
4513 if (deviceDescriptor == nullptr) {
4514 ALOGE("%s the requested device is currently unavailable", __func__);
4515 return BAD_VALUE;
4516 }
4517 if (!audio_is_usb_out_device(deviceDescriptor->type())) {
4518 ALOGE("%s(%d), type=%d, is not a usb output device",
4519 __func__, portId, deviceDescriptor->type());
4520 return BAD_VALUE;
4521 }
4522
4523 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
4524 audio_flags_to_audio_output_flags(attr->flags, &flags);
4525 flags = (audio_output_flags_t) (flags |
4526 audio_output_flags_from_mixer_behavior(mixerAttributes->mixer_behavior));
4527 sp<IOProfile> profile = nullptr;
4528 DeviceVector devices(deviceDescriptor);
4529 for (const auto& hwModule : mHwModules) {
4530 for (const auto& curProfile : hwModule->getOutputProfiles()) {
4531 if (curProfile->hasDynamicAudioProfile()
4532 && curProfile->isCompatibleProfile(devices,
4533 mixerAttributes->config.sample_rate,
4534 nullptr /*updatedSamplingRate*/,
4535 mixerAttributes->config.format,
4536 nullptr /*updatedFormat*/,
4537 mixerAttributes->config.channel_mask,
4538 nullptr /*updatedChannelMask*/,
4539 flags,
4540 false /*exactMatchRequiredForInputFlags*/)) {
4541 profile = curProfile;
4542 break;
4543 }
4544 }
4545 }
4546 if (profile == nullptr) {
4547 ALOGE("%s, there is no compatible profile found", __func__);
4548 return BAD_VALUE;
4549 }
4550
4551 sp<PreferredMixerAttributesInfo> mixerAttrInfo =
4552 sp<PreferredMixerAttributesInfo>::make(
4553 uid, portId, profile, flags, *mixerAttributes);
4554 const product_strategy_t strategy = mEngine->getProductStrategyForAttributes(*attr);
4555 mPreferredMixerAttrInfos[portId][strategy] = mixerAttrInfo;
4556
4557 // If 1) there is any client from the preferred mixer configuration owner that is currently
4558 // active and matches the strategy and 2) current output is on the preferred device and the
4559 // mixer configuration doesn't match the preferred one, reopen output with preferred mixer
4560 // configuration.
4561 std::vector<audio_io_handle_t> outputsToReopen;
4562 for (size_t i = 0; i < mOutputs.size(); i++) {
4563 const auto output = mOutputs.valueAt(i);
jiabin3ff8d7d2022-12-13 06:27:44 +00004564 if (output->mProfile == profile && output->devices().onlyContainsDevice(deviceDescriptor)) {
4565 if (output->isConfigurationMatched(mixerAttributes->config, flags)) {
4566 output->mUsePreferredMixerAttributes = true;
4567 } else {
4568 for (const auto &client: output->getActiveClients()) {
4569 if (client->uid() == uid && client->strategy() == strategy) {
4570 client->setIsInvalid();
4571 outputsToReopen.push_back(output->mIoHandle);
4572 }
jiabina84c3d32022-12-02 18:59:55 +00004573 }
4574 }
4575 }
4576 }
4577 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
4578 config.sample_rate = mixerAttributes->config.sample_rate;
4579 config.channel_mask = mixerAttributes->config.channel_mask;
4580 config.format = mixerAttributes->config.format;
4581 for (const auto output : outputsToReopen) {
jiabin3ff8d7d2022-12-13 06:27:44 +00004582 sp<SwAudioOutputDescriptor> desc =
4583 reopenOutput(mOutputs.valueFor(output), &config, flags, __func__);
4584 if (desc == nullptr) {
4585 ALOGE("%s, failed to reopen output with preferred mixer attributes", __func__);
4586 continue;
4587 }
4588 desc->mUsePreferredMixerAttributes = true;
jiabina84c3d32022-12-02 18:59:55 +00004589 }
4590
4591 return NO_ERROR;
4592}
4593
4594sp<PreferredMixerAttributesInfo> AudioPolicyManager::getPreferredMixerAttributesInfo(
jiabind9a58d32023-06-01 17:57:30 +00004595 audio_port_handle_t devicePortId,
4596 product_strategy_t strategy,
4597 bool activeBitPerfectPreferred) {
jiabina84c3d32022-12-02 18:59:55 +00004598 auto it = mPreferredMixerAttrInfos.find(devicePortId);
4599 if (it == mPreferredMixerAttrInfos.end()) {
4600 return nullptr;
4601 }
jiabind9a58d32023-06-01 17:57:30 +00004602 if (activeBitPerfectPreferred) {
4603 for (auto [strategy, info] : it->second) {
4604 if ((info->getFlags() & AUDIO_OUTPUT_FLAG_BIT_PERFECT) != AUDIO_OUTPUT_FLAG_NONE
4605 && info->getActiveClientCount() != 0) {
4606 return info;
4607 }
4608 }
jiabina84c3d32022-12-02 18:59:55 +00004609 }
jiabind9a58d32023-06-01 17:57:30 +00004610 auto strategyMatchedMixerAttrInfoIt = it->second.find(strategy);
4611 return strategyMatchedMixerAttrInfoIt == it->second.end()
4612 ? nullptr : strategyMatchedMixerAttrInfoIt->second;
jiabina84c3d32022-12-02 18:59:55 +00004613}
4614
4615status_t AudioPolicyManager::getPreferredMixerAttributes(
4616 const audio_attributes_t *attr,
4617 audio_port_handle_t portId,
4618 audio_mixer_attributes_t* mixerAttributes) {
4619 sp<PreferredMixerAttributesInfo> info = getPreferredMixerAttributesInfo(
4620 portId, mEngine->getProductStrategyForAttributes(*attr));
4621 if (info == nullptr) {
4622 return NAME_NOT_FOUND;
4623 }
4624 *mixerAttributes = info->getMixerAttributes();
4625 return NO_ERROR;
4626}
4627
4628status_t AudioPolicyManager::clearPreferredMixerAttributes(const audio_attributes_t *attr,
4629 audio_port_handle_t portId,
4630 uid_t uid) {
4631 const product_strategy_t strategy = mEngine->getProductStrategyForAttributes(*attr);
4632 const auto preferredMixerAttrInfo = getPreferredMixerAttributesInfo(portId, strategy);
4633 if (preferredMixerAttrInfo == nullptr) {
4634 return NAME_NOT_FOUND;
4635 }
4636 if (preferredMixerAttrInfo->getUid() != uid) {
4637 ALOGE("%s, requested uid=%d, owned uid=%d",
4638 __func__, uid, preferredMixerAttrInfo->getUid());
4639 return PERMISSION_DENIED;
4640 }
4641 mPreferredMixerAttrInfos[portId].erase(strategy);
4642 if (mPreferredMixerAttrInfos[portId].empty()) {
4643 mPreferredMixerAttrInfos.erase(portId);
4644 }
4645
4646 // Reconfig existing output
4647 std::vector<audio_io_handle_t> potentialOutputsToReopen;
4648 for (size_t i = 0; i < mOutputs.size(); i++) {
4649 if (mOutputs.valueAt(i)->mProfile == preferredMixerAttrInfo->getProfile()) {
4650 potentialOutputsToReopen.push_back(mOutputs.keyAt(i));
4651 }
4652 }
4653 for (const auto output : potentialOutputsToReopen) {
4654 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
4655 if (desc->isConfigurationMatched(preferredMixerAttrInfo->getConfigBase(),
4656 preferredMixerAttrInfo->getFlags())) {
4657 reopenOutput(desc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
4658 }
4659 }
4660 return NO_ERROR;
4661}
4662
Eric Laurent6a94d692014-05-20 11:18:06 -07004663status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
4664 audio_port_type_t type,
4665 unsigned int *num_ports,
jiabin19cdba52020-11-24 11:28:58 -08004666 struct audio_port_v7 *ports,
Eric Laurent6a94d692014-05-20 11:18:06 -07004667 unsigned int *generation)
4668{
jiabin19cdba52020-11-24 11:28:58 -08004669 if (num_ports == nullptr || (*num_ports != 0 && ports == nullptr) ||
4670 generation == nullptr) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004671 return BAD_VALUE;
4672 }
4673 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
jiabin19cdba52020-11-24 11:28:58 -08004674 if (ports == nullptr) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004675 *num_ports = 0;
4676 }
4677
4678 size_t portsWritten = 0;
4679 size_t portsMax = *num_ports;
4680 *num_ports = 0;
4681 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07004682 // do not report devices with type AUDIO_DEVICE_IN_STUB or AUDIO_DEVICE_OUT_STUB
4683 // as they are used by stub HALs by convention
Eric Laurent6a94d692014-05-20 11:18:06 -07004684 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004685 for (const auto& dev : mAvailableOutputDevices) {
4686 if (dev->type() == AUDIO_DEVICE_OUT_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07004687 continue;
4688 }
4689 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004690 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07004691 }
4692 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07004693 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004694 }
4695 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004696 for (const auto& dev : mAvailableInputDevices) {
4697 if (dev->type() == AUDIO_DEVICE_IN_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07004698 continue;
4699 }
4700 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004701 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07004702 }
4703 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07004704 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004705 }
4706 }
4707 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
4708 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
4709 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
4710 mInputs[i]->toAudioPort(&ports[portsWritten++]);
4711 }
4712 *num_ports += mInputs.size();
4713 }
4714 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent84c70242014-06-23 08:46:27 -07004715 size_t numOutputs = 0;
4716 for (size_t i = 0; i < mOutputs.size(); i++) {
4717 if (!mOutputs[i]->isDuplicated()) {
4718 numOutputs++;
4719 if (portsWritten < portsMax) {
4720 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
4721 }
4722 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004723 }
Eric Laurent84c70242014-06-23 08:46:27 -07004724 *num_ports += numOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07004725 }
4726 }
jiabina84c3d32022-12-02 18:59:55 +00004727
Eric Laurent6a94d692014-05-20 11:18:06 -07004728 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07004729 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
Eric Laurent6a94d692014-05-20 11:18:06 -07004730 return NO_ERROR;
4731}
4732
Mikhail Naganov5edc5ed2023-03-23 14:52:15 -07004733status_t AudioPolicyManager::listDeclaredDevicePorts(media::AudioPortRole role,
4734 std::vector<media::AudioPortFw>* _aidl_return) {
4735 auto pushPort = [&](const sp<DeviceDescriptor>& dev) -> status_t {
4736 audio_port_v7 port;
4737 dev->toAudioPort(&port);
4738 auto aidlPort = VALUE_OR_RETURN_STATUS(legacy2aidl_audio_port_v7_AudioPortFw(port));
4739 _aidl_return->push_back(std::move(aidlPort));
4740 return OK;
4741 };
4742
Mikhail Naganov68e3f642023-04-28 13:06:32 -07004743 for (const auto& module : mHwModules) {
Mikhail Naganov5edc5ed2023-03-23 14:52:15 -07004744 for (const auto& dev : module->getDeclaredDevices()) {
4745 if (role == media::AudioPortRole::NONE ||
4746 ((role == media::AudioPortRole::SOURCE)
4747 == audio_is_input_device(dev->type()))) {
4748 RETURN_STATUS_IF_ERROR(pushPort(dev));
4749 }
4750 }
4751 }
4752 return OK;
4753}
4754
jiabin19cdba52020-11-24 11:28:58 -08004755status_t AudioPolicyManager::getAudioPort(struct audio_port_v7 *port)
Eric Laurent6a94d692014-05-20 11:18:06 -07004756{
Eric Laurent99fcae42018-05-17 16:59:18 -07004757 if (port == nullptr || port->id == AUDIO_PORT_HANDLE_NONE) {
4758 return BAD_VALUE;
4759 }
4760 sp<DeviceDescriptor> dev = mAvailableOutputDevices.getDeviceFromId(port->id);
4761 if (dev != 0) {
4762 dev->toAudioPort(port);
4763 return NO_ERROR;
4764 }
4765 dev = mAvailableInputDevices.getDeviceFromId(port->id);
4766 if (dev != 0) {
4767 dev->toAudioPort(port);
4768 return NO_ERROR;
4769 }
4770 sp<SwAudioOutputDescriptor> out = mOutputs.getOutputFromId(port->id);
4771 if (out != 0) {
4772 out->toAudioPort(port);
4773 return NO_ERROR;
4774 }
4775 sp<AudioInputDescriptor> in = mInputs.getInputFromId(port->id);
4776 if (in != 0) {
4777 in->toAudioPort(port);
4778 return NO_ERROR;
4779 }
4780 return BAD_VALUE;
Eric Laurent6a94d692014-05-20 11:18:06 -07004781}
4782
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004783status_t AudioPolicyManager::createAudioPatch(const struct audio_patch *patch,
4784 audio_patch_handle_t *handle,
4785 uid_t uid)
Eric Laurent6a94d692014-05-20 11:18:06 -07004786{
François Gaffieafd4cea2019-11-18 15:50:22 +01004787 ALOGV("%s", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004788 if (handle == NULL || patch == NULL) {
4789 return BAD_VALUE;
4790 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004791 ALOGV("%s num sources %d num sinks %d", __func__, patch->num_sources, patch->num_sinks);
Mikhail Naganovac9858b2018-06-15 13:12:37 -07004792 if (!audio_patch_is_valid(patch)) {
Eric Laurent874c42872014-08-08 15:13:39 -07004793 return BAD_VALUE;
4794 }
4795 // only one source per audio patch supported for now
4796 if (patch->num_sources > 1) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004797 return INVALID_OPERATION;
4798 }
Eric Laurent874c42872014-08-08 15:13:39 -07004799 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004800 return INVALID_OPERATION;
4801 }
Eric Laurent874c42872014-08-08 15:13:39 -07004802 for (size_t i = 0; i < patch->num_sinks; i++) {
4803 if (patch->sinks[i].role != AUDIO_PORT_ROLE_SINK) {
4804 return INVALID_OPERATION;
4805 }
4806 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004807
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004808 sp<DeviceDescriptor> srcDevice = mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
4809 sp<DeviceDescriptor> sinkDevice = mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id);
4810 if (srcDevice == nullptr || sinkDevice == nullptr) {
4811 ALOGW("%s could not create patch, invalid sink and/or source device(s)", __func__);
4812 return BAD_VALUE;
4813 }
4814 ALOGV("%s between source %s and sink %s", __func__,
4815 srcDevice->toString().c_str(), sinkDevice->toString().c_str());
4816 audio_port_handle_t portId = PolicyAudioPort::getNextUniqueId();
4817 // Default attributes, default volume priority, not to infer with non raw audio patches.
4818 audio_attributes_t attributes = attributes_initializer(AUDIO_USAGE_MEDIA);
4819 const struct audio_port_config *source = &patch->sources[0];
4820 sp<SourceClientDescriptor> sourceDesc =
4821 new InternalSourceClientDescriptor(
4822 portId, uid, attributes, *source, srcDevice, sinkDevice,
4823 mEngine->getProductStrategyForAttributes(attributes), toVolumeSource(attributes));
4824
4825 status_t status =
4826 connectAudioSourceToSink(sourceDesc, sinkDevice, patch, *handle, uid, 0 /* delayMs */);
4827
4828 if (status != NO_ERROR) {
4829 return INVALID_OPERATION;
4830 }
4831 mAudioSources.add(portId, sourceDesc);
4832 return NO_ERROR;
4833}
4834
4835status_t AudioPolicyManager::connectAudioSourceToSink(
4836 const sp<SourceClientDescriptor>& sourceDesc, const sp<DeviceDescriptor> &sinkDevice,
4837 const struct audio_patch *patch,
4838 audio_patch_handle_t &handle,
4839 uid_t uid, uint32_t delayMs)
4840{
4841 status_t status = createAudioPatchInternal(patch, &handle, uid, delayMs, sourceDesc);
4842 if (status != NO_ERROR || mAudioPatches.indexOfKey(handle) < 0) {
4843 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
4844 return INVALID_OPERATION;
4845 }
4846 sourceDesc->connect(handle, sinkDevice);
4847 if (isMsdPatch(handle)) {
4848 return NO_ERROR;
4849 }
4850 // SW Bridge? (@todo: HW bridge, keep track of HwOutput for device selection "reconsideration")
4851 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
4852 ALOG_ASSERT(swOutput != nullptr, "%s: a swOutput shall always be associated", __func__);
4853 if (swOutput->getClient(sourceDesc->portId()) != nullptr) {
4854 ALOGW("%s source portId has already been attached to outputDesc", __func__);
4855 goto FailurePatchAdded;
4856 }
4857 status = swOutput->start();
4858 if (status != NO_ERROR) {
4859 goto FailureSourceAdded;
4860 }
4861 swOutput->addClient(sourceDesc);
4862 status = startSource(swOutput, sourceDesc, &delayMs);
4863 if (status != NO_ERROR) {
4864 ALOGW("%s failed to start source, error %d", __FUNCTION__, status);
4865 goto FailureSourceActive;
4866 }
4867 if (delayMs != 0) {
4868 usleep(delayMs * 1000);
4869 }
4870 return NO_ERROR;
4871
4872FailureSourceActive:
4873 swOutput->stop();
4874 releaseOutput(sourceDesc->portId());
4875FailureSourceAdded:
4876 sourceDesc->setSwOutput(nullptr);
4877FailurePatchAdded:
4878 releaseAudioPatchInternal(handle);
4879 return INVALID_OPERATION;
4880}
4881
4882status_t AudioPolicyManager::createAudioPatchInternal(const struct audio_patch *patch,
4883 audio_patch_handle_t *handle,
4884 uid_t uid, uint32_t delayMs,
4885 const sp<SourceClientDescriptor>& sourceDesc)
4886{
4887 ALOGV("%s num sources %d num sinks %d", __func__, patch->num_sources, patch->num_sinks);
Eric Laurent6a94d692014-05-20 11:18:06 -07004888 sp<AudioPatch> patchDesc;
4889 ssize_t index = mAudioPatches.indexOfKey(*handle);
4890
François Gaffieafd4cea2019-11-18 15:50:22 +01004891 ALOGV("%s source id %d role %d type %d", __func__, patch->sources[0].id,
4892 patch->sources[0].role,
4893 patch->sources[0].type);
Eric Laurent874c42872014-08-08 15:13:39 -07004894#if LOG_NDEBUG == 0
4895 for (size_t i = 0; i < patch->num_sinks; i++) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004896 ALOGV("%s sink %zu: id %d role %d type %d", __func__ ,i, patch->sinks[i].id,
4897 patch->sinks[i].role,
4898 patch->sinks[i].type);
Eric Laurent874c42872014-08-08 15:13:39 -07004899 }
4900#endif
Eric Laurent6a94d692014-05-20 11:18:06 -07004901
4902 if (index >= 0) {
4903 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01004904 ALOGV("%s mUidCached %d patchDesc->mUid %d uid %d",
4905 __func__, mUidCached, patchDesc->getUid(), uid);
4906 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004907 return INVALID_OPERATION;
4908 }
4909 } else {
Glenn Kastena13cde92016-03-28 15:26:02 -07004910 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07004911 }
4912
4913 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004914 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004915 if (outputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004916 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004917 return BAD_VALUE;
4918 }
Eric Laurent84c70242014-06-23 08:46:27 -07004919 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
4920 outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004921 if (patchDesc != 0) {
4922 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004923 ALOGV("%s source id differs for patch current id %d new id %d",
4924 __func__, patchDesc->mPatch.sources[0].id, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004925 return BAD_VALUE;
4926 }
4927 }
Eric Laurent874c42872014-08-08 15:13:39 -07004928 DeviceVector devices;
4929 for (size_t i = 0; i < patch->num_sinks; i++) {
4930 // Only support mix to devices connection
4931 // TODO add support for mix to mix connection
4932 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004933 ALOGV("%s source mix but sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07004934 return INVALID_OPERATION;
4935 }
4936 sp<DeviceDescriptor> devDesc =
4937 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
4938 if (devDesc == 0) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004939 ALOGV("%s out device not found for id %d", __func__, patch->sinks[i].id);
Eric Laurent874c42872014-08-08 15:13:39 -07004940 return BAD_VALUE;
4941 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004942
François Gaffie11d30102018-11-02 16:09:09 +01004943 if (!outputDesc->mProfile->isCompatibleProfile(DeviceVector(devDesc),
Eric Laurent874c42872014-08-08 15:13:39 -07004944 patch->sources[0].sample_rate,
François Gaffie53615e22015-03-19 09:24:12 +01004945 NULL, // updatedSamplingRate
4946 patch->sources[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07004947 NULL, // updatedFormat
François Gaffie53615e22015-03-19 09:24:12 +01004948 patch->sources[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07004949 NULL, // updatedChannelMask
François Gaffie53615e22015-03-19 09:24:12 +01004950 AUDIO_OUTPUT_FLAG_NONE /*FIXME*/)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004951 ALOGV("%s profile not supported for device %08x", __func__, devDesc->type());
Eric Laurent874c42872014-08-08 15:13:39 -07004952 return INVALID_OPERATION;
4953 }
4954 devices.add(devDesc);
4955 }
4956 if (devices.size() == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004957 return INVALID_OPERATION;
4958 }
Eric Laurent874c42872014-08-08 15:13:39 -07004959
Eric Laurent6a94d692014-05-20 11:18:06 -07004960 // TODO: reconfigure output format and channels here
François Gaffieafd4cea2019-11-18 15:50:22 +01004961 ALOGV("%s setting device %s on output %d",
4962 __func__, dumpDeviceTypes(devices.types()).c_str(), outputDesc->mIoHandle);
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05304963 setOutputDevices(__func__, outputDesc, devices, true, 0, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004964 index = mAudioPatches.indexOfKey(*handle);
4965 if (index >= 0) {
4966 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004967 ALOGW("%s setOutputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004968 }
4969 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01004970 patchDesc->setUid(uid);
4971 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004972 } else {
François Gaffieafd4cea2019-11-18 15:50:22 +01004973 ALOGW("%s setOutputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004974 return INVALID_OPERATION;
4975 }
4976 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
4977 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
4978 // input device to input mix connection
Eric Laurent874c42872014-08-08 15:13:39 -07004979 // only one sink supported when connecting an input device to a mix
4980 if (patch->num_sinks > 1) {
4981 return INVALID_OPERATION;
4982 }
François Gaffie53615e22015-03-19 09:24:12 +01004983 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004984 if (inputDesc == NULL) {
4985 return BAD_VALUE;
4986 }
4987 if (patchDesc != 0) {
4988 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
4989 return BAD_VALUE;
4990 }
4991 }
François Gaffie11d30102018-11-02 16:09:09 +01004992 sp<DeviceDescriptor> device =
Eric Laurent6a94d692014-05-20 11:18:06 -07004993 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01004994 if (device == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004995 return BAD_VALUE;
4996 }
4997
François Gaffie11d30102018-11-02 16:09:09 +01004998 if (!inputDesc->mProfile->isCompatibleProfile(DeviceVector(device),
Eric Laurent275e8e92014-11-30 15:14:47 -08004999 patch->sinks[0].sample_rate,
5000 NULL, /*updatedSampleRate*/
5001 patch->sinks[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07005002 NULL, /*updatedFormat*/
Eric Laurent275e8e92014-11-30 15:14:47 -08005003 patch->sinks[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07005004 NULL, /*updatedChannelMask*/
Eric Laurent275e8e92014-11-30 15:14:47 -08005005 // FIXME for the parameter type,
5006 // and the NONE
5007 (audio_output_flags_t)
Glenn Kasten6a8ab052014-07-24 14:08:35 -07005008 AUDIO_INPUT_FLAG_NONE)) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005009 return INVALID_OPERATION;
5010 }
5011 // TODO: reconfigure output format and channels here
François Gaffieafd4cea2019-11-18 15:50:22 +01005012 ALOGV("%s setting device %s on output %d", __func__,
François Gaffie11d30102018-11-02 16:09:09 +01005013 device->toString().c_str(), inputDesc->mIoHandle);
5014 setInputDevice(inputDesc->mIoHandle, device, true, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005015 index = mAudioPatches.indexOfKey(*handle);
5016 if (index >= 0) {
5017 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005018 ALOGW("%s setInputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005019 }
5020 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005021 patchDesc->setUid(uid);
5022 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005023 } else {
François Gaffieafd4cea2019-11-18 15:50:22 +01005024 ALOGW("%s setInputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005025 return INVALID_OPERATION;
5026 }
5027 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
5028 // device to device connection
5029 if (patchDesc != 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07005030 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005031 return BAD_VALUE;
5032 }
5033 }
François Gaffie11d30102018-11-02 16:09:09 +01005034 sp<DeviceDescriptor> srcDevice =
Eric Laurent6a94d692014-05-20 11:18:06 -07005035 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01005036 if (srcDevice == 0) {
Eric Laurent58f8eb72014-09-12 16:19:41 -07005037 return BAD_VALUE;
5038 }
Eric Laurent874c42872014-08-08 15:13:39 -07005039
Eric Laurent6a94d692014-05-20 11:18:06 -07005040 //update source and sink with our own data as the data passed in the patch may
5041 // be incomplete.
François Gaffieafd4cea2019-11-18 15:50:22 +01005042 PatchBuilder patchBuilder;
5043 audio_port_config sourcePortConfig = {};
Dean Wheatley8bee85a2021-02-10 16:02:23 +11005044
5045 // if first sink is to MSD, establish single MSD patch
5046 if (getMsdAudioOutDevices().contains(
5047 mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id))) {
5048 ALOGV("%s patching to MSD", __FUNCTION__);
5049 patchBuilder = buildMsdPatch(false /*msdIsSource*/, srcDevice);
5050 goto installPatch;
5051 }
5052
François Gaffieafd4cea2019-11-18 15:50:22 +01005053 srcDevice->toAudioPortConfig(&sourcePortConfig, &patch->sources[0]);
5054 patchBuilder.addSource(sourcePortConfig);
Eric Laurent6a94d692014-05-20 11:18:06 -07005055
Eric Laurent874c42872014-08-08 15:13:39 -07005056 for (size_t i = 0; i < patch->num_sinks; i++) {
5057 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005058 ALOGV("%s source device but one sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07005059 return INVALID_OPERATION;
5060 }
François Gaffie11d30102018-11-02 16:09:09 +01005061 sp<DeviceDescriptor> sinkDevice =
Eric Laurent874c42872014-08-08 15:13:39 -07005062 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
François Gaffie11d30102018-11-02 16:09:09 +01005063 if (sinkDevice == 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07005064 return BAD_VALUE;
5065 }
François Gaffieafd4cea2019-11-18 15:50:22 +01005066 audio_port_config sinkPortConfig = {};
5067 sinkDevice->toAudioPortConfig(&sinkPortConfig, &patch->sinks[i]);
5068 patchBuilder.addSink(sinkPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07005069
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005070 // Whatever Sw or Hw bridge, we do attach an SwOutput to an Audio Source for
5071 // volume management purpose (tracking activity)
5072 // In case of Hw bridge, it is a Work Around. The mixPort used is the one declared
5073 // in config XML to reach the sink so that is can be declared as available.
5074 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurent78b07302022-10-07 16:20:34 +02005075 sp<SwAudioOutputDescriptor> outputDesc;
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005076 if (!sourceDesc->isInternal()) {
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005077 // take care of dynamic routing for SwOutput selection,
5078 audio_attributes_t attributes = sourceDesc->attributes();
5079 audio_stream_type_t stream = sourceDesc->stream();
5080 audio_attributes_t resultAttr;
5081 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
5082 config.sample_rate = sourceDesc->config().sample_rate;
François Gaffie2a24db42022-04-04 16:45:02 +02005083 audio_channel_mask_t sourceMask = sourceDesc->config().channel_mask;
5084 config.channel_mask =
5085 (audio_channel_mask_get_representation(sourceMask)
5086 == AUDIO_CHANNEL_REPRESENTATION_INDEX) ? sourceMask
5087 : audio_channel_mask_in_to_out(sourceMask);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005088 config.format = sourceDesc->config().format;
5089 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
5090 audio_port_handle_t selectedDeviceId = AUDIO_PORT_HANDLE_NONE;
5091 bool isRequestedDeviceForExclusiveUse = false;
5092 output_type_t outputType;
Eric Laurentb0a7bc92022-04-05 15:06:08 +02005093 bool isSpatialized;
jiabinc658e452022-10-21 20:52:21 +00005094 bool isBitPerfect;
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005095 getOutputForAttrInt(&resultAttr, &output, AUDIO_SESSION_NONE, &attributes,
5096 &stream, sourceDesc->uid(), &config, &flags,
5097 &selectedDeviceId, &isRequestedDeviceForExclusiveUse,
jiabinc658e452022-10-21 20:52:21 +00005098 nullptr, &outputType, &isSpatialized, &isBitPerfect);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005099 if (output == AUDIO_IO_HANDLE_NONE) {
5100 ALOGV("%s no output for device %s",
5101 __FUNCTION__, sinkDevice->toString().c_str());
5102 return INVALID_OPERATION;
5103 }
5104 outputDesc = mOutputs.valueFor(output);
5105 if (outputDesc->isDuplicated()) {
5106 ALOGE("%s output is duplicated", __func__);
5107 return INVALID_OPERATION;
5108 }
François Gaffie7e39df22022-04-26 12:48:49 +02005109 bool closeOutput = outputDesc->mDirectOpenCount != 0;
5110 sourceDesc->setSwOutput(outputDesc, closeOutput);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005111 } else {
5112 // Same for "raw patches" aka created from createAudioPatch API
5113 SortedVector<audio_io_handle_t> outputs =
5114 getOutputsForDevices(DeviceVector(sinkDevice), mOutputs);
5115 // if the sink device is reachable via an opened output stream, request to
5116 // go via this output stream by adding a second source to the patch
5117 // description
5118 output = selectOutput(outputs);
5119 if (output == AUDIO_IO_HANDLE_NONE) {
5120 ALOGE("%s no output available for internal patch sink", __func__);
5121 return INVALID_OPERATION;
5122 }
5123 outputDesc = mOutputs.valueFor(output);
5124 if (outputDesc->isDuplicated()) {
5125 ALOGV("%s output for device %s is duplicated",
5126 __func__, sinkDevice->toString().c_str());
5127 return INVALID_OPERATION;
5128 }
François Gaffie7e39df22022-04-26 12:48:49 +02005129 sourceDesc->setSwOutput(outputDesc, /* closeOutput= */ false);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005130 }
Eric Laurent3bcf8592015-04-03 12:13:24 -07005131 // create a software bridge in PatchPanel if:
Scott Randolphf3172402018-01-23 17:06:53 -08005132 // - source and sink devices are on different HW modules OR
Eric Laurent3bcf8592015-04-03 12:13:24 -07005133 // - audio HAL version is < 3.0
Francois Gaffie99896da2018-04-09 11:05:33 +02005134 // - audio HAL version is >= 3.0 but no route has been declared between devices
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005135 // - called from startAudioSource (aka sourceDesc is not internal) and source device
5136 // does not have a gain controller
François Gaffie11d30102018-11-02 16:09:09 +01005137 if (!srcDevice->hasSameHwModuleAs(sinkDevice) ||
5138 (srcDevice->getModuleVersionMajor() < 3) ||
François Gaffieafd4cea2019-11-18 15:50:22 +01005139 !srcDevice->getModule()->supportsPatch(srcDevice, sinkDevice) ||
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005140 (!sourceDesc->isInternal() &&
François Gaffieafd4cea2019-11-18 15:50:22 +01005141 srcDevice->getAudioPort()->getGains().size() == 0)) {
Eric Laurent3bcf8592015-04-03 12:13:24 -07005142 // support only one sink device for now to simplify output selection logic
Eric Laurent874c42872014-08-08 15:13:39 -07005143 if (patch->num_sinks > 1) {
Eric Laurent83b88082014-06-20 18:31:16 -07005144 return INVALID_OPERATION;
5145 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005146 sourceDesc->setUseSwBridge();
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005147 if (outputDesc != nullptr) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005148 audio_port_config srcMixPortConfig = {};
Ytai Ben-Tsvic9d2a912021-11-22 16:43:09 -08005149 outputDesc->toAudioPortConfig(&srcMixPortConfig, nullptr);
François Gaffieafd4cea2019-11-18 15:50:22 +01005150 // for volume control, we may need a valid stream
Eric Laurent78b07302022-10-07 16:20:34 +02005151 srcMixPortConfig.ext.mix.usecase.stream =
5152 (!sourceDesc->isInternal() || isCallTxAudioSource(sourceDesc)) ?
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005153 mEngine->getStreamTypeForAttributes(sourceDesc->attributes()) :
5154 AUDIO_STREAM_PATCH;
François Gaffieafd4cea2019-11-18 15:50:22 +01005155 patchBuilder.addSource(srcMixPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07005156 }
Eric Laurent83b88082014-06-20 18:31:16 -07005157 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005158 }
5159 // TODO: check from routing capabilities in config file and other conflicting patches
5160
Dean Wheatley8bee85a2021-02-10 16:02:23 +11005161installPatch:
François Gaffieafd4cea2019-11-18 15:50:22 +01005162 status_t status = installPatch(
5163 __func__, index, handle, patchBuilder.patch(), delayMs, uid, &patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07005164 if (status != NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005165 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
Eric Laurent6a94d692014-05-20 11:18:06 -07005166 return INVALID_OPERATION;
5167 }
5168 } else {
5169 return BAD_VALUE;
5170 }
5171 } else {
5172 return BAD_VALUE;
5173 }
5174 return NO_ERROR;
5175}
5176
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005177status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle, uid_t uid)
Eric Laurent6a94d692014-05-20 11:18:06 -07005178{
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005179 ALOGV("%s patch %d", __func__, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005180 ssize_t index = mAudioPatches.indexOfKey(handle);
5181
5182 if (index < 0) {
5183 return BAD_VALUE;
5184 }
5185 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005186 ALOGV("%s() mUidCached %d patchDesc->mUid %d uid %d",
5187 __func__, mUidCached, patchDesc->getUid(), uid);
5188 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005189 return INVALID_OPERATION;
5190 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005191 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
5192 for (size_t i = 0; i < mAudioSources.size(); i++) {
5193 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
5194 if (sourceDesc != nullptr && sourceDesc->getPatchHandle() == handle) {
5195 portId = sourceDesc->portId();
5196 break;
5197 }
5198 }
5199 return portId != AUDIO_PORT_HANDLE_NONE ?
5200 stopAudioSource(portId) : releaseAudioPatchInternal(handle);
François Gaffieafd4cea2019-11-18 15:50:22 +01005201}
Eric Laurent6a94d692014-05-20 11:18:06 -07005202
François Gaffieafd4cea2019-11-18 15:50:22 +01005203status_t AudioPolicyManager::releaseAudioPatchInternal(audio_patch_handle_t handle,
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005204 uint32_t delayMs,
5205 const sp<SourceClientDescriptor>& sourceDesc)
François Gaffieafd4cea2019-11-18 15:50:22 +01005206{
5207 ALOGV("%s patch %d", __func__, handle);
5208 if (mAudioPatches.indexOfKey(handle) < 0) {
5209 ALOGE("%s: no patch found with handle=%d", __func__, handle);
5210 return BAD_VALUE;
5211 }
5212 sp<AudioPatch> patchDesc = mAudioPatches.valueFor(handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005213 struct audio_patch *patch = &patchDesc->mPatch;
François Gaffieafd4cea2019-11-18 15:50:22 +01005214 patchDesc->setUid(mUidCached);
Eric Laurent6a94d692014-05-20 11:18:06 -07005215 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005216 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005217 if (outputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005218 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005219 return BAD_VALUE;
5220 }
5221
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05305222 setOutputDevices(__func__, outputDesc,
François Gaffie11d30102018-11-02 16:09:09 +01005223 getNewOutputDevices(outputDesc, true /*fromCache*/),
5224 true,
5225 0,
5226 NULL);
Eric Laurent6a94d692014-05-20 11:18:06 -07005227 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
5228 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
François Gaffie53615e22015-03-19 09:24:12 +01005229 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005230 if (inputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005231 ALOGV("%s input not found for id %d", __func__, patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005232 return BAD_VALUE;
5233 }
5234 setInputDevice(inputDesc->mIoHandle,
Eric Laurentfb66dd92016-01-28 18:32:03 -08005235 getNewInputDevice(inputDesc),
Eric Laurent6a94d692014-05-20 11:18:06 -07005236 true,
5237 NULL);
5238 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005239 status_t status =
5240 mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
5241 ALOGV("%s patch panel returned %d patchHandle %d",
5242 __func__, status, patchDesc->getAfHandle());
5243 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005244 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005245 mpClientInterface->onAudioPatchListUpdate();
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005246 // SW or HW Bridge
5247 sp<SwAudioOutputDescriptor> outputDesc = nullptr;
5248 audio_patch_handle_t patchHandle = AUDIO_PATCH_HANDLE_NONE;
Francois Gaffie7feb8542020-04-06 17:39:47 +02005249 if (patch->num_sources > 1 && patch->sources[1].type == AUDIO_PORT_TYPE_MIX) {
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005250 outputDesc = mOutputs.getOutputFromId(patch->sources[1].id);
5251 } else if (patch->num_sources == 1 && sourceDesc != nullptr) {
5252 outputDesc = sourceDesc->swOutput().promote();
5253 }
5254 if (outputDesc == nullptr) {
5255 ALOGW("%s no output for id %d", __func__, patch->sources[0].id);
5256 // releaseOutput has already called closeOutput in case of direct output
5257 return NO_ERROR;
5258 }
François Gaffie7e39df22022-04-26 12:48:49 +02005259 patchHandle = outputDesc->getPatchHandle();
François Gaffie7e39df22022-04-26 12:48:49 +02005260 // While using a HwBridge, force reconsidering device only if not reusing an existing
5261 // output and no more activity on output (will force to close).
François Gaffie150fcc62023-09-15 11:02:39 +02005262 const bool force = sourceDesc->canCloseOutput() && !outputDesc->isActive();
François Gaffie7e39df22022-04-26 12:48:49 +02005263 // APM pattern is to have always outputs opened / patch realized for reachable devices.
5264 // Update device may result to NONE (empty), coupled with force, it releases the patch.
5265 // Reconsider device only for cases:
5266 // 1 / Active Output
5267 // 2 / Inactive Output previously hosting HwBridge
5268 // 3 / Inactive Output previously hosting SwBridge that can be closed.
5269 bool updateDevice = outputDesc->isActive() || !sourceDesc->useSwBridge() ||
5270 sourceDesc->canCloseOutput();
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05305271 setOutputDevices(__func__, outputDesc,
François Gaffie7e39df22022-04-26 12:48:49 +02005272 updateDevice ? getNewOutputDevices(outputDesc, true /*fromCache*/) :
5273 outputDesc->devices(),
5274 force,
5275 0,
5276 patchHandle == AUDIO_PATCH_HANDLE_NONE ? nullptr : &patchHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005277 } else {
5278 return BAD_VALUE;
5279 }
5280 } else {
5281 return BAD_VALUE;
5282 }
5283 return NO_ERROR;
5284}
5285
5286status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
5287 struct audio_patch *patches,
5288 unsigned int *generation)
5289{
François Gaffie53615e22015-03-19 09:24:12 +01005290 if (generation == NULL) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005291 return BAD_VALUE;
5292 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005293 *generation = curAudioPortGeneration();
François Gaffie53615e22015-03-19 09:24:12 +01005294 return mAudioPatches.listAudioPatches(num_patches, patches);
Eric Laurent6a94d692014-05-20 11:18:06 -07005295}
5296
Eric Laurente1715a42014-05-20 11:30:42 -07005297status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07005298{
Eric Laurente1715a42014-05-20 11:30:42 -07005299 ALOGV("setAudioPortConfig()");
5300
5301 if (config == NULL) {
5302 return BAD_VALUE;
5303 }
5304 ALOGV("setAudioPortConfig() on port handle %d", config->id);
5305 // Only support gain configuration for now
Eric Laurenta121f902014-06-03 13:32:54 -07005306 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
5307 return INVALID_OPERATION;
Eric Laurente1715a42014-05-20 11:30:42 -07005308 }
5309
Eric Laurenta121f902014-06-03 13:32:54 -07005310 sp<AudioPortConfig> audioPortConfig;
Eric Laurente1715a42014-05-20 11:30:42 -07005311 if (config->type == AUDIO_PORT_TYPE_MIX) {
5312 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005313 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07005314 if (outputDesc == NULL) {
5315 return BAD_VALUE;
5316 }
Eric Laurent84c70242014-06-23 08:46:27 -07005317 ALOG_ASSERT(!outputDesc->isDuplicated(),
5318 "setAudioPortConfig() called on duplicated output %d",
5319 outputDesc->mIoHandle);
Eric Laurenta121f902014-06-03 13:32:54 -07005320 audioPortConfig = outputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07005321 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
François Gaffie53615e22015-03-19 09:24:12 +01005322 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07005323 if (inputDesc == NULL) {
5324 return BAD_VALUE;
5325 }
Eric Laurenta121f902014-06-03 13:32:54 -07005326 audioPortConfig = inputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07005327 } else {
5328 return BAD_VALUE;
5329 }
5330 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
5331 sp<DeviceDescriptor> deviceDesc;
5332 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
5333 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
5334 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
5335 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
5336 } else {
5337 return BAD_VALUE;
5338 }
5339 if (deviceDesc == NULL) {
5340 return BAD_VALUE;
5341 }
Eric Laurenta121f902014-06-03 13:32:54 -07005342 audioPortConfig = deviceDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07005343 } else {
5344 return BAD_VALUE;
5345 }
5346
Mikhail Naganov7be71d22018-05-23 16:51:46 -07005347 struct audio_port_config backupConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07005348 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
5349 if (status == NO_ERROR) {
Mikhail Naganov7be71d22018-05-23 16:51:46 -07005350 struct audio_port_config newConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07005351 audioPortConfig->toAudioPortConfig(&newConfig, config);
5352 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
Eric Laurente1715a42014-05-20 11:30:42 -07005353 }
Eric Laurenta121f902014-06-03 13:32:54 -07005354 if (status != NO_ERROR) {
5355 audioPortConfig->applyAudioPortConfig(&backupConfig);
Eric Laurente1715a42014-05-20 11:30:42 -07005356 }
Eric Laurente1715a42014-05-20 11:30:42 -07005357
5358 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07005359}
5360
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005361void AudioPolicyManager::releaseResourcesForUid(uid_t uid)
5362{
Eric Laurentd60560a2015-04-10 11:31:20 -07005363 clearAudioSources(uid);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005364 clearAudioPatches(uid);
5365 clearSessionRoutes(uid);
5366}
5367
Eric Laurent6a94d692014-05-20 11:18:06 -07005368void AudioPolicyManager::clearAudioPatches(uid_t uid)
5369{
Eric Laurent0add0fd2014-12-04 18:58:14 -08005370 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005371 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
François Gaffieafd4cea2019-11-18 15:50:22 +01005372 if (patchDesc->getUid() == uid) {
Eric Laurent0add0fd2014-12-04 18:58:14 -08005373 releaseAudioPatch(mAudioPatches.keyAt(i), uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07005374 }
5375 }
5376}
5377
François Gaffiec005e562018-11-06 15:04:49 +01005378void AudioPolicyManager::checkStrategyRoute(product_strategy_t ps, audio_io_handle_t ouptutToSkip)
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005379{
François Gaffiec005e562018-11-06 15:04:49 +01005380 // Take the first attributes following the product strategy as it is used to retrieve the routed
5381 // device. All attributes wihin a strategy follows the same "routing strategy"
5382 auto attributes = mEngine->getAllAttributesForProductStrategy(ps).front();
5383 DeviceVector devices = mEngine->getOutputDevicesForAttributes(attributes, nullptr, false);
François Gaffie11d30102018-11-02 16:09:09 +01005384 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
jiabin3ff8d7d2022-12-13 06:27:44 +00005385 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005386 for (size_t j = 0; j < mOutputs.size(); j++) {
5387 if (mOutputs.keyAt(j) == ouptutToSkip) {
5388 continue;
5389 }
5390 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(j);
François Gaffiec005e562018-11-06 15:04:49 +01005391 if (!outputDesc->isStrategyActive(ps)) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005392 continue;
5393 }
5394 // If the default device for this strategy is on another output mix,
5395 // invalidate all tracks in this strategy to force re connection.
5396 // Otherwise select new device on the output mix.
5397 if (outputs.indexOf(mOutputs.keyAt(j)) < 0) {
jiabinc44b3462022-12-08 12:52:31 -08005398 invalidateStreams(mEngine->getStreamTypesForProductStrategy(ps));
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005399 } else {
jiabin3ff8d7d2022-12-13 06:27:44 +00005400 DeviceVector newDevices = getNewOutputDevices(outputDesc, false /*fromCache*/);
5401 if (outputDesc->mUsePreferredMixerAttributes && outputDesc->devices() != newDevices) {
5402 // If the device is using preferred mixer attributes, the output need to reopen
5403 // with default configuration when the new selected devices are different from
5404 // current routing devices.
5405 outputsToReopen.emplace(mOutputs.keyAt(j), newDevices);
5406 continue;
5407 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05305408 setOutputDevices(__func__, outputDesc, newDevices, false);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005409 }
5410 }
jiabin3ff8d7d2022-12-13 06:27:44 +00005411 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005412}
5413
5414void AudioPolicyManager::clearSessionRoutes(uid_t uid)
5415{
5416 // remove output routes associated with this uid
François Gaffiec005e562018-11-06 15:04:49 +01005417 std::vector<product_strategy_t> affectedStrategies;
Eric Laurent97ac8712018-07-27 18:59:02 -07005418 for (size_t i = 0; i < mOutputs.size(); i++) {
5419 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07005420 for (const auto& client : outputDesc->getClientIterable()) {
5421 if (client->hasPreferredDevice() && client->uid() == uid) {
5422 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
François Gaffiec005e562018-11-06 15:04:49 +01005423 auto clientStrategy = client->strategy();
5424 if (std::find(begin(affectedStrategies), end(affectedStrategies), clientStrategy) !=
5425 end(affectedStrategies)) {
5426 continue;
5427 }
5428 affectedStrategies.push_back(client->strategy());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005429 }
5430 }
5431 }
5432 // reroute outputs if necessary
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005433 for (const auto& strategy : affectedStrategies) {
5434 checkStrategyRoute(strategy, AUDIO_IO_HANDLE_NONE);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005435 }
5436
5437 // remove input routes associated with this uid
5438 SortedVector<audio_source_t> affectedSources;
Eric Laurent97ac8712018-07-27 18:59:02 -07005439 for (size_t i = 0; i < mInputs.size(); i++) {
5440 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07005441 for (const auto& client : inputDesc->getClientIterable()) {
5442 if (client->hasPreferredDevice() && client->uid() == uid) {
5443 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
5444 affectedSources.add(client->source());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005445 }
5446 }
5447 }
5448 // reroute inputs if necessary
5449 SortedVector<audio_io_handle_t> inputsToClose;
5450 for (size_t i = 0; i < mInputs.size(); i++) {
5451 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Eric Laurent4eb58f12018-12-07 16:41:02 -08005452 if (affectedSources.indexOf(inputDesc->source()) >= 0) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005453 inputsToClose.add(inputDesc->mIoHandle);
5454 }
5455 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005456 for (const auto& input : inputsToClose) {
5457 closeInput(input);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005458 }
5459}
5460
Eric Laurentd60560a2015-04-10 11:31:20 -07005461void AudioPolicyManager::clearAudioSources(uid_t uid)
5462{
5463 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005464 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
5465 if (sourceDesc->uid() == uid) {
Eric Laurentd60560a2015-04-10 11:31:20 -07005466 stopAudioSource(mAudioSources.keyAt(i));
5467 }
5468 }
5469}
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005470
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005471status_t AudioPolicyManager::acquireSoundTriggerSession(audio_session_t *session,
5472 audio_io_handle_t *ioHandle,
5473 audio_devices_t *device)
5474{
Glenn Kastenf0c6d7d2016-02-26 10:44:04 -08005475 *session = (audio_session_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
5476 *ioHandle = (audio_io_handle_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
Francois Gaffie716e1432019-01-14 16:58:59 +01005477 audio_attributes_t attr = { .source = AUDIO_SOURCE_HOTWORD };
Eric Laurentcedd5b52023-03-22 00:03:31 +00005478 sp<DeviceDescriptor> deviceDesc = mEngine->getInputDeviceForAttributes(attr);
5479 if (deviceDesc == nullptr) {
5480 return INVALID_OPERATION;
5481 }
5482 *device = deviceDesc->type();
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005483
François Gaffiedf372692015-03-19 10:43:27 +01005484 return mSoundTriggerSessions.acquireSession(*session, *ioHandle);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005485}
5486
Eric Laurentd60560a2015-04-10 11:31:20 -07005487status_t AudioPolicyManager::startAudioSource(const struct audio_port_config *source,
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005488 const audio_attributes_t *attributes,
5489 audio_port_handle_t *portId,
5490 uid_t uid)
Eric Laurent554a2772015-04-10 11:29:24 -07005491{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005492 ALOGV("%s", __FUNCTION__);
5493 *portId = AUDIO_PORT_HANDLE_NONE;
5494
5495 if (source == NULL || attributes == NULL || portId == NULL) {
5496 ALOGW("%s invalid argument: source %p attributes %p handle %p",
5497 __FUNCTION__, source, attributes, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005498 return BAD_VALUE;
5499 }
5500
Eric Laurentd60560a2015-04-10 11:31:20 -07005501 if (source->role != AUDIO_PORT_ROLE_SOURCE ||
5502 source->type != AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005503 ALOGW("%s INVALID_OPERATION source->role %d source->type %d",
5504 __FUNCTION__, source->role, source->type);
Eric Laurentd60560a2015-04-10 11:31:20 -07005505 return INVALID_OPERATION;
5506 }
5507
François Gaffie11d30102018-11-02 16:09:09 +01005508 sp<DeviceDescriptor> srcDevice =
Eric Laurentd60560a2015-04-10 11:31:20 -07005509 mAvailableInputDevices.getDevice(source->ext.device.type,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005510 String8(source->ext.device.address),
5511 AUDIO_FORMAT_DEFAULT);
François Gaffie11d30102018-11-02 16:09:09 +01005512 if (srcDevice == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005513 ALOGW("%s source->ext.device.type %08x not found", __FUNCTION__, source->ext.device.type);
Eric Laurentd60560a2015-04-10 11:31:20 -07005514 return BAD_VALUE;
5515 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005516
jiabin4ef93452019-09-10 14:29:54 -07005517 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurentd60560a2015-04-10 11:31:20 -07005518
François Gaffieaaac0fd2018-11-22 17:56:39 +01005519 sp<SourceClientDescriptor> sourceDesc =
François Gaffieafd4cea2019-11-18 15:50:22 +01005520 new SourceClientDescriptor(*portId, uid, *attributes, *source, srcDevice,
François Gaffieaaac0fd2018-11-22 17:56:39 +01005521 mEngine->getStreamTypeForAttributes(*attributes),
5522 mEngine->getProductStrategyForAttributes(*attributes),
5523 toVolumeSource(*attributes));
Eric Laurentd60560a2015-04-10 11:31:20 -07005524
5525 status_t status = connectAudioSource(sourceDesc);
5526 if (status == NO_ERROR) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005527 mAudioSources.add(*portId, sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07005528 }
5529 return status;
5530}
5531
Francois Gaffie601801d2021-06-22 13:27:39 +02005532sp<SourceClientDescriptor> AudioPolicyManager::startAudioSourceInternal(
5533 const struct audio_port_config *source, const audio_attributes_t *attributes, uid_t uid)
5534{
5535 ALOGV("%s", __FUNCTION__);
5536 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
5537
5538 status_t status = startAudioSource(source, attributes, &portId, uid);
5539 ALOGE_IF(status != OK, "%s: failed to start audio source (%d)", __func__, status);
5540 return mAudioSources.valueFor(portId);
5541}
5542
5543
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005544status_t AudioPolicyManager::connectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07005545{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005546 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->portId());
Eric Laurentd60560a2015-04-10 11:31:20 -07005547
5548 // make sure we only have one patch per source.
5549 disconnectAudioSource(sourceDesc);
5550
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005551 audio_attributes_t attributes = sourceDesc->attributes();
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005552 // May the device (dynamic) have been disconnected/reconnected, id has changed.
5553 sp<DeviceDescriptor> srcDevice = mAvailableInputDevices.getDevice(
5554 sourceDesc->srcDevice()->type(),
5555 String8(sourceDesc->srcDevice()->address().c_str()),
5556 AUDIO_FORMAT_DEFAULT);
François Gaffiec005e562018-11-06 15:04:49 +01005557 DeviceVector sinkDevices =
Francois Gaffieff1eb522020-05-06 18:37:04 +02005558 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false /*fromCache*/);
François Gaffiec005e562018-11-06 15:04:49 +01005559 ALOG_ASSERT(!sinkDevices.isEmpty(), "connectAudioSource(): no device found for attributes");
François Gaffie11d30102018-11-02 16:09:09 +01005560 sp<DeviceDescriptor> sinkDevice = sinkDevices.itemAt(0);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005561 if (!mAvailableOutputDevices.contains(sinkDevice)) {
5562 ALOGE("%s Device %s not available", __func__, sinkDevice->toString().c_str());
5563 return INVALID_OPERATION;
5564 }
François Gaffieafd4cea2019-11-18 15:50:22 +01005565 PatchBuilder patchBuilder;
5566 patchBuilder.addSink(sinkDevice).addSource(srcDevice);
5567 audio_patch_handle_t handle = AUDIO_PATCH_HANDLE_NONE;
François Gaffieafd4cea2019-11-18 15:50:22 +01005568
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005569 return connectAudioSourceToSink(
5570 sourceDesc, sinkDevice, patchBuilder.patch(), handle, mUidCached, 0 /*delayMs*/);
Eric Laurent554a2772015-04-10 11:29:24 -07005571}
5572
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005573status_t AudioPolicyManager::stopAudioSource(audio_port_handle_t portId)
Eric Laurent554a2772015-04-10 11:29:24 -07005574{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005575 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueFor(portId);
5576 ALOGV("%s port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005577 if (sourceDesc == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005578 ALOGW("%s unknown source for port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005579 return BAD_VALUE;
5580 }
5581 status_t status = disconnectAudioSource(sourceDesc);
5582
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005583 mAudioSources.removeItem(portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005584 return status;
5585}
5586
Andy Hung2ddee192015-12-18 17:34:44 -08005587status_t AudioPolicyManager::setMasterMono(bool mono)
5588{
5589 if (mMasterMono == mono) {
5590 return NO_ERROR;
5591 }
5592 mMasterMono = mono;
5593 // if enabling mono we close all offloaded devices, which will invalidate the
5594 // corresponding AudioTrack. The AudioTrack client/MediaPlayer is responsible
5595 // for recreating the new AudioTrack as non-offloaded PCM.
5596 //
5597 // If disabling mono, we leave all tracks as is: we don't know which clients
5598 // and tracks are able to be recreated as offloaded. The next "song" should
5599 // play back offloaded.
5600 if (mMasterMono) {
5601 Vector<audio_io_handle_t> offloaded;
5602 for (size_t i = 0; i < mOutputs.size(); ++i) {
5603 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
5604 if (desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
5605 offloaded.push(desc->mIoHandle);
5606 }
5607 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005608 for (const auto& handle : offloaded) {
5609 closeOutput(handle);
Andy Hung2ddee192015-12-18 17:34:44 -08005610 }
5611 }
5612 // update master mono for all remaining outputs
5613 for (size_t i = 0; i < mOutputs.size(); ++i) {
5614 updateMono(mOutputs.keyAt(i));
5615 }
5616 return NO_ERROR;
5617}
5618
5619status_t AudioPolicyManager::getMasterMono(bool *mono)
5620{
5621 *mono = mMasterMono;
5622 return NO_ERROR;
5623}
5624
Eric Laurentac9cef52017-06-09 15:46:26 -07005625float AudioPolicyManager::getStreamVolumeDB(
5626 audio_stream_type_t stream, int index, audio_devices_t device)
5627{
jiabin9a3361e2019-10-01 09:38:30 -07005628 return computeVolume(getVolumeCurves(stream), toVolumeSource(stream), index, {device});
Eric Laurentac9cef52017-06-09 15:46:26 -07005629}
5630
jiabin81772902018-04-02 17:52:27 -07005631status_t AudioPolicyManager::getSurroundFormats(unsigned int *numSurroundFormats,
5632 audio_format_t *surroundFormats,
Kriti Dang6537def2021-03-02 13:46:59 +01005633 bool *surroundFormatsEnabled)
jiabin81772902018-04-02 17:52:27 -07005634{
Kriti Dang6537def2021-03-02 13:46:59 +01005635 if (numSurroundFormats == nullptr || (*numSurroundFormats != 0 &&
5636 (surroundFormats == nullptr || surroundFormatsEnabled == nullptr))) {
jiabin81772902018-04-02 17:52:27 -07005637 return BAD_VALUE;
5638 }
Kriti Dang6537def2021-03-02 13:46:59 +01005639 ALOGV("%s() numSurroundFormats %d surroundFormats %p surroundFormatsEnabled %p",
5640 __func__, *numSurroundFormats, surroundFormats, surroundFormatsEnabled);
jiabin81772902018-04-02 17:52:27 -07005641
5642 size_t formatsWritten = 0;
5643 size_t formatsMax = *numSurroundFormats;
Kriti Dangef6be8f2020-11-05 11:58:19 +01005644
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005645 *numSurroundFormats = mConfig->getSurroundFormats().size();
Mikhail Naganov100f0122018-11-29 11:22:16 -08005646 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
5647 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005648 for (const auto& format: mConfig->getSurroundFormats()) {
jiabin81772902018-04-02 17:52:27 -07005649 if (formatsWritten < formatsMax) {
Kriti Dang6537def2021-03-02 13:46:59 +01005650 surroundFormats[formatsWritten] = format.first;
Mikhail Naganov100f0122018-11-29 11:22:16 -08005651 bool formatEnabled = true;
5652 switch (forceUse) {
5653 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL:
Kriti Dang6537def2021-03-02 13:46:59 +01005654 formatEnabled = mManualSurroundFormats.count(format.first) != 0;
Mikhail Naganov100f0122018-11-29 11:22:16 -08005655 break;
5656 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER:
5657 formatEnabled = false;
5658 break;
5659 default: // AUTO or ALWAYS => true
5660 break;
jiabin81772902018-04-02 17:52:27 -07005661 }
5662 surroundFormatsEnabled[formatsWritten++] = formatEnabled;
5663 }
jiabin81772902018-04-02 17:52:27 -07005664 }
5665 return NO_ERROR;
5666}
5667
Kriti Dang6537def2021-03-02 13:46:59 +01005668status_t AudioPolicyManager::getReportedSurroundFormats(unsigned int *numSurroundFormats,
5669 audio_format_t *surroundFormats) {
5670 if (numSurroundFormats == nullptr || (*numSurroundFormats != 0 && surroundFormats == nullptr)) {
5671 return BAD_VALUE;
5672 }
5673 ALOGV("%s() numSurroundFormats %d surroundFormats %p",
5674 __func__, *numSurroundFormats, surroundFormats);
5675
5676 size_t formatsWritten = 0;
5677 size_t formatsMax = *numSurroundFormats;
5678 std::unordered_set<audio_format_t> formats; // Uses primary surround formats only
5679
5680 // Return formats from all device profiles that have already been resolved by
5681 // checkOutputsForDevice().
5682 for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
5683 sp<DeviceDescriptor> device = mAvailableOutputDevices[i];
5684 audio_devices_t deviceType = device->type();
5685 // Enabling/disabling formats are applied to only HDMI devices. So, this function
5686 // returns formats reported by HDMI devices.
5687 if (deviceType != AUDIO_DEVICE_OUT_HDMI) {
5688 continue;
5689 }
5690 // Formats reported by sink devices
5691 std::unordered_set<audio_format_t> formatset;
5692 if (auto it = mReportedFormatsMap.find(device); it != mReportedFormatsMap.end()) {
5693 formatset.insert(it->second.begin(), it->second.end());
5694 }
5695
5696 // Formats hard-coded in the in policy configuration file (if any).
5697 FormatVector encodedFormats = device->encodedFormats();
5698 formatset.insert(encodedFormats.begin(), encodedFormats.end());
5699 // Filter the formats which are supported by the vendor hardware.
5700 for (auto it = formatset.begin(); it != formatset.end(); ++it) {
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005701 if (mConfig->getSurroundFormats().count(*it) != 0) {
Kriti Dang6537def2021-03-02 13:46:59 +01005702 formats.insert(*it);
5703 } else {
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005704 for (const auto& pair : mConfig->getSurroundFormats()) {
Kriti Dang6537def2021-03-02 13:46:59 +01005705 if (pair.second.count(*it) != 0) {
5706 formats.insert(pair.first);
5707 break;
5708 }
5709 }
5710 }
5711 }
5712 }
5713 *numSurroundFormats = formats.size();
5714 for (const auto& format: formats) {
5715 if (formatsWritten < formatsMax) {
5716 surroundFormats[formatsWritten++] = format;
5717 }
5718 }
5719 return NO_ERROR;
5720}
5721
jiabin81772902018-04-02 17:52:27 -07005722status_t AudioPolicyManager::setSurroundFormatEnabled(audio_format_t audioFormat, bool enabled)
5723{
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005724 ALOGV("%s() format 0x%X enabled %d", __func__, audioFormat, enabled);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005725 const auto& formatIter = mConfig->getSurroundFormats().find(audioFormat);
5726 if (formatIter == mConfig->getSurroundFormats().end()) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005727 ALOGW("%s() format 0x%X is not a known surround format", __func__, audioFormat);
jiabin81772902018-04-02 17:52:27 -07005728 return BAD_VALUE;
5729 }
5730
Mikhail Naganov100f0122018-11-29 11:22:16 -08005731 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND) !=
5732 AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005733 ALOGW("%s() not in manual mode for surround sound format selection", __func__);
jiabin81772902018-04-02 17:52:27 -07005734 return INVALID_OPERATION;
5735 }
5736
Mikhail Naganov100f0122018-11-29 11:22:16 -08005737 if ((mManualSurroundFormats.count(audioFormat) != 0) == enabled) {
jiabin81772902018-04-02 17:52:27 -07005738 return NO_ERROR;
5739 }
5740
Mikhail Naganov100f0122018-11-29 11:22:16 -08005741 std::unordered_set<audio_format_t> surroundFormatsBackup(mManualSurroundFormats);
jiabin81772902018-04-02 17:52:27 -07005742 if (enabled) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005743 mManualSurroundFormats.insert(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07005744 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005745 mManualSurroundFormats.insert(subFormat);
jiabin81772902018-04-02 17:52:27 -07005746 }
5747 } else {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005748 mManualSurroundFormats.erase(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07005749 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005750 mManualSurroundFormats.erase(subFormat);
jiabin81772902018-04-02 17:52:27 -07005751 }
5752 }
5753
5754 sp<SwAudioOutputDescriptor> outputDesc;
5755 bool profileUpdated = false;
jiabin9a3361e2019-10-01 09:38:30 -07005756 DeviceVector hdmiOutputDevices = mAvailableOutputDevices.getDevicesFromType(
5757 AUDIO_DEVICE_OUT_HDMI);
jiabin81772902018-04-02 17:52:27 -07005758 for (size_t i = 0; i < hdmiOutputDevices.size(); i++) {
5759 // Simulate reconnection to update enabled surround sound formats.
jiabince9f20e2019-09-12 16:29:15 -07005760 String8 address = String8(hdmiOutputDevices[i]->address().c_str());
jiabin5740f082019-08-19 15:08:30 -07005761 std::string name = hdmiOutputDevices[i]->getName();
jiabin81772902018-04-02 17:52:27 -07005762 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
5763 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
5764 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005765 name.c_str(),
5766 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005767 if (status != NO_ERROR) {
5768 continue;
5769 }
5770 status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
5771 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
5772 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005773 name.c_str(),
5774 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005775 profileUpdated |= (status == NO_ERROR);
5776 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08005777 // FIXME: Why doing this for input HDMI devices if we don't augment their reported formats?
jiabin9a3361e2019-10-01 09:38:30 -07005778 DeviceVector hdmiInputDevices = mAvailableInputDevices.getDevicesFromType(
jiabin81772902018-04-02 17:52:27 -07005779 AUDIO_DEVICE_IN_HDMI);
5780 for (size_t i = 0; i < hdmiInputDevices.size(); i++) {
5781 // Simulate reconnection to update enabled surround sound formats.
jiabince9f20e2019-09-12 16:29:15 -07005782 String8 address = String8(hdmiInputDevices[i]->address().c_str());
jiabin5740f082019-08-19 15:08:30 -07005783 std::string name = hdmiInputDevices[i]->getName();
jiabin81772902018-04-02 17:52:27 -07005784 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
5785 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
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 if (status != NO_ERROR) {
5790 continue;
5791 }
5792 status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
5793 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
5794 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005795 name.c_str(),
5796 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005797 profileUpdated |= (status == NO_ERROR);
5798 }
5799
jiabin81772902018-04-02 17:52:27 -07005800 if (!profileUpdated) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005801 ALOGW("%s() no audio profiles updated, undoing surround formats change", __func__);
Mikhail Naganov100f0122018-11-29 11:22:16 -08005802 mManualSurroundFormats = std::move(surroundFormatsBackup);
jiabin81772902018-04-02 17:52:27 -07005803 }
5804
5805 return profileUpdated ? NO_ERROR : INVALID_OPERATION;
5806}
5807
Eric Laurent5ada82e2019-08-29 17:53:54 -07005808void AudioPolicyManager::setAppState(audio_port_handle_t portId, app_state_t state)
Svet Ganovf4ddfef2018-01-16 07:37:58 -08005809{
Eric Laurent5ada82e2019-08-29 17:53:54 -07005810 ALOGV("%s(portId:%d, state:%d)", __func__, portId, state);
Eric Laurenta9f86652018-11-28 17:23:11 -08005811 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent5ada82e2019-08-29 17:53:54 -07005812 mInputs.valueAt(i)->setAppState(portId, state);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08005813 }
5814}
5815
jiabin6012f912018-11-02 17:06:30 -07005816bool AudioPolicyManager::isHapticPlaybackSupported()
5817{
5818 for (const auto& hwModule : mHwModules) {
5819 const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
5820 for (const auto &outProfile : outputProfiles) {
5821 struct audio_port audioPort;
5822 outProfile->toAudioPort(&audioPort);
5823 for (size_t i = 0; i < audioPort.num_channel_masks; i++) {
5824 if (audioPort.channel_masks[i] & AUDIO_CHANNEL_HAPTIC_ALL) {
5825 return true;
5826 }
5827 }
5828 }
5829 }
5830 return false;
5831}
5832
Carter Hsu325a8eb2022-01-19 19:56:51 +08005833bool AudioPolicyManager::isUltrasoundSupported()
5834{
5835 bool hasUltrasoundOutput = false;
5836 bool hasUltrasoundInput = false;
5837 for (const auto& hwModule : mHwModules) {
5838 const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
5839 if (!hasUltrasoundOutput) {
5840 for (const auto &outProfile : outputProfiles) {
5841 if (outProfile->getFlags() & AUDIO_OUTPUT_FLAG_ULTRASOUND) {
5842 hasUltrasoundOutput = true;
5843 break;
5844 }
5845 }
5846 }
5847
5848 const InputProfileCollection &inputProfiles = hwModule->getInputProfiles();
5849 if (!hasUltrasoundInput) {
5850 for (const auto &inputProfile : inputProfiles) {
5851 if (inputProfile->getFlags() & AUDIO_INPUT_FLAG_ULTRASOUND) {
5852 hasUltrasoundInput = true;
5853 break;
5854 }
5855 }
5856 }
5857
5858 if (hasUltrasoundOutput && hasUltrasoundInput)
5859 return true;
5860 }
5861 return false;
5862}
5863
Atneya Nair698f5ef2022-12-15 16:15:09 -08005864bool AudioPolicyManager::isHotwordStreamSupported(bool lookbackAudio)
5865{
5866 const auto mask = AUDIO_INPUT_FLAG_HOTWORD_TAP |
5867 (lookbackAudio ? AUDIO_INPUT_FLAG_HW_LOOKBACK : 0);
5868 for (const auto& hwModule : mHwModules) {
5869 const InputProfileCollection &inputProfiles = hwModule->getInputProfiles();
5870 for (const auto &inputProfile : inputProfiles) {
5871 if ((inputProfile->getFlags() & mask) == mask) {
5872 return true;
5873 }
5874 }
5875 }
5876 return false;
5877}
5878
Eric Laurent8340e672019-11-06 11:01:08 -08005879bool AudioPolicyManager::isCallScreenModeSupported()
5880{
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005881 return mConfig->isCallScreenModeSupported();
Eric Laurent8340e672019-11-06 11:01:08 -08005882}
5883
5884
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005885status_t AudioPolicyManager::disconnectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07005886{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005887 ALOGV("%s port Id %d", __FUNCTION__, sourceDesc->portId());
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005888 if (!sourceDesc->isConnected()) {
5889 ALOGV("%s port Id %d already disconnected", __FUNCTION__, sourceDesc->portId());
5890 return NO_ERROR;
5891 }
François Gaffieafd4cea2019-11-18 15:50:22 +01005892 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
5893 if (swOutput != 0) {
5894 status_t status = stopSource(swOutput, sourceDesc);
Eric Laurent733ce942017-12-07 12:18:25 -08005895 if (status == NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005896 swOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08005897 }
jiabinbce0c1d2020-10-05 11:20:18 -07005898 if (releaseOutput(sourceDesc->portId())) {
5899 // The output descriptor is reopened to query dynamic profiles. In that case, there is
5900 // no need to release audio patch here but just return NO_ERROR.
5901 return NO_ERROR;
5902 }
Eric Laurentd60560a2015-04-10 11:31:20 -07005903 } else {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005904 sp<HwAudioOutputDescriptor> hwOutputDesc = sourceDesc->hwOutput().promote();
Eric Laurentd60560a2015-04-10 11:31:20 -07005905 if (hwOutputDesc != 0) {
Eric Laurentd60560a2015-04-10 11:31:20 -07005906 // close Hwoutput and remove from mHwOutputs
5907 } else {
5908 ALOGW("%s source has neither SW nor HW output", __FUNCTION__);
5909 }
5910 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005911 status_t status = releaseAudioPatchInternal(sourceDesc->getPatchHandle(), 0, sourceDesc);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005912 sourceDesc->disconnect();
5913 return status;
Eric Laurentd60560a2015-04-10 11:31:20 -07005914}
5915
François Gaffiec005e562018-11-06 15:04:49 +01005916sp<SourceClientDescriptor> AudioPolicyManager::getSourceForAttributesOnOutput(
5917 audio_io_handle_t output, const audio_attributes_t &attr)
Eric Laurentd60560a2015-04-10 11:31:20 -07005918{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005919 sp<SourceClientDescriptor> source;
Eric Laurentd60560a2015-04-10 11:31:20 -07005920 for (size_t i = 0; i < mAudioSources.size(); i++) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005921 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005922 sp<SwAudioOutputDescriptor> outputDesc = sourceDesc->swOutput().promote();
François Gaffiec005e562018-11-06 15:04:49 +01005923 if (followsSameRouting(attr, sourceDesc->attributes()) &&
5924 outputDesc != 0 && outputDesc->mIoHandle == output) {
Eric Laurentd60560a2015-04-10 11:31:20 -07005925 source = sourceDesc;
5926 break;
5927 }
5928 }
5929 return source;
Eric Laurent554a2772015-04-10 11:29:24 -07005930}
5931
Eric Laurentb4f42a92022-01-17 17:37:31 +01005932bool AudioPolicyManager::canBeSpatializedInt(const audio_attributes_t *attr,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005933 const audio_config_t *config,
Andy Hung9dd1a5b2022-05-10 15:39:39 -07005934 const AudioDeviceTypeAddrVector &devices) const
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005935{
5936 // The caller can have the audio attributes criteria ignored by either passing a null ptr or
5937 // the AUDIO_ATTRIBUTES_INITIALIZER value.
Eric Laurentfa0f6742021-08-17 18:39:44 +02005938 // If attributes are specified, current policy is to only allow spatialization for media
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005939 // and game usages.
Eric Laurent39095982021-08-24 18:29:27 +02005940 if (attr != nullptr && *attr != AUDIO_ATTRIBUTES_INITIALIZER) {
5941 if (attr->usage != AUDIO_USAGE_MEDIA && attr->usage != AUDIO_USAGE_GAME) {
5942 return false;
5943 }
5944 if ((attr->flags & (AUDIO_FLAG_CONTENT_SPATIALIZED | AUDIO_FLAG_NEVER_SPATIALIZE)) != 0) {
5945 return false;
5946 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005947 }
5948
Eric Laurentd332bc82023-08-04 11:45:23 +02005949 // The caller can have the audio config criteria ignored by either passing a null ptr or
5950 // the AUDIO_CONFIG_INITIALIZER value.
5951 // If an audio config is specified, current policy is to only allow spatialization for
5952 // some positional channel masks and PCM format
5953
5954 if (config != nullptr && *config != AUDIO_CONFIG_INITIALIZER) {
5955 if (!audio_is_channel_mask_spatialized(config->channel_mask)) {
5956 return false;
5957 }
5958 if (!audio_is_linear_pcm(config->format)) {
5959 return false;
5960 }
5961 }
5962
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005963 sp<IOProfile> profile =
Eric Laurent39095982021-08-24 18:29:27 +02005964 getSpatializerOutputProfile(config, devices);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005965 if (profile == nullptr) {
5966 return false;
5967 }
5968
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005969 return true;
5970}
5971
5972void AudioPolicyManager::checkVirtualizerClientRoutes() {
5973 std::set<audio_stream_type_t> streamsToInvalidate;
5974 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent39095982021-08-24 18:29:27 +02005975 const sp<SwAudioOutputDescriptor>& desc = mOutputs[i];
5976 for (const sp<TrackClientDescriptor>& client : desc->getClientIterable()) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005977 audio_attributes_t attr = client->attributes();
5978 DeviceVector devices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false);
5979 AudioDeviceTypeAddrVector devicesTypeAddress = devices.toTypeAddrVector();
5980 audio_config_base_t clientConfig = client->config();
5981 audio_config_t config = audio_config_initializer(&clientConfig);
Eric Laurent39095982021-08-24 18:29:27 +02005982 if (desc != mSpatializerOutput
Andy Hung9dd1a5b2022-05-10 15:39:39 -07005983 && canBeSpatializedInt(&attr, &config, devicesTypeAddress)) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005984 streamsToInvalidate.insert(client->stream());
5985 }
5986 }
5987 }
5988
jiabinc44b3462022-12-08 12:52:31 -08005989 invalidateStreams(StreamTypeVector(streamsToInvalidate.begin(), streamsToInvalidate.end()));
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005990}
5991
Eric Laurente191d1b2022-04-15 11:59:25 +02005992
5993bool AudioPolicyManager::isOutputOnlyAvailableRouteToSomeDevice(
5994 const sp<SwAudioOutputDescriptor>& outputDesc) {
5995 if (outputDesc->isDuplicated()) {
5996 return false;
5997 }
5998 DeviceVector devices = outputDesc->supportedDevices();
5999 for (size_t i = 0; i < mOutputs.size(); i++) {
6000 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
6001 if (desc == outputDesc || desc->isDuplicated()) {
6002 continue;
6003 }
6004 DeviceVector sharedDevices = desc->filterSupportedDevices(devices);
6005 if (!sharedDevices.isEmpty()
6006 && (desc->devicesSupportEncodedFormats(sharedDevices.types())
6007 == outputDesc->devicesSupportEncodedFormats(sharedDevices.types()))) {
6008 return false;
6009 }
6010 }
6011 return true;
6012}
6013
6014
Eric Laurentfa0f6742021-08-17 18:39:44 +02006015status_t AudioPolicyManager::getSpatializerOutput(const audio_config_base_t *mixerConfig,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006016 const audio_attributes_t *attr,
6017 audio_io_handle_t *output) {
6018 *output = AUDIO_IO_HANDLE_NONE;
6019
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006020 DeviceVector devices = mEngine->getOutputDevicesForAttributes(*attr, nullptr, false);
6021 AudioDeviceTypeAddrVector devicesTypeAddress = devices.toTypeAddrVector();
6022 audio_config_t *configPtr = nullptr;
6023 audio_config_t config;
6024 if (mixerConfig != nullptr) {
6025 config = audio_config_initializer(mixerConfig);
6026 configPtr = &config;
6027 }
Andy Hung9dd1a5b2022-05-10 15:39:39 -07006028 if (!canBeSpatializedInt(attr, configPtr, devicesTypeAddress)) {
Eric Laurente191d1b2022-04-15 11:59:25 +02006029 ALOGV("%s provided attributes or mixer config cannot be spatialized", __func__);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006030 return BAD_VALUE;
6031 }
6032
6033 sp<IOProfile> profile =
Eric Laurent39095982021-08-24 18:29:27 +02006034 getSpatializerOutputProfile(configPtr, devicesTypeAddress);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006035 if (profile == nullptr) {
Eric Laurente191d1b2022-04-15 11:59:25 +02006036 ALOGV("%s no suitable output profile for provided attributes or mixer config", __func__);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006037 return BAD_VALUE;
6038 }
6039
Eric Laurente191d1b2022-04-15 11:59:25 +02006040 std::vector<sp<SwAudioOutputDescriptor>> spatializerOutputs;
Eric Laurent39095982021-08-24 18:29:27 +02006041 for (size_t i = 0; i < mOutputs.size(); i++) {
6042 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente191d1b2022-04-15 11:59:25 +02006043 if (!desc->isDuplicated()
6044 && (desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0) {
6045 spatializerOutputs.push_back(desc);
6046 ALOGV("%s adding opened spatializer Output %d", __func__, desc->mIoHandle);
Eric Laurent39095982021-08-24 18:29:27 +02006047 }
6048 }
Eric Laurente191d1b2022-04-15 11:59:25 +02006049 mSpatializerOutput.clear();
6050 bool outputsChanged = false;
6051 for (const auto& desc : spatializerOutputs) {
6052 if (desc->mProfile == profile
6053 && (configPtr == nullptr
6054 || configPtr->channel_mask == desc->mMixerChannelMask)) {
6055 mSpatializerOutput = desc;
6056 ALOGV("%s reusing current spatializer output %d", __func__, desc->mIoHandle);
6057 } else {
6058 ALOGV("%s closing spatializerOutput output %d to match channel mask %#x"
6059 " and devices %s", __func__, desc->mIoHandle,
6060 configPtr != nullptr ? configPtr->channel_mask : 0,
6061 devices.toString().c_str());
6062 closeOutput(desc->mIoHandle);
6063 outputsChanged = true;
6064 }
Eric Laurent39095982021-08-24 18:29:27 +02006065 }
6066
Eric Laurente191d1b2022-04-15 11:59:25 +02006067 if (mSpatializerOutput == nullptr) {
Eric Laurentb4f42a92022-01-17 17:37:31 +01006068 sp<SwAudioOutputDescriptor> desc =
6069 openOutputWithProfileAndDevice(profile, devices, mixerConfig);
Eric Laurente191d1b2022-04-15 11:59:25 +02006070 if (desc != nullptr) {
6071 mSpatializerOutput = desc;
6072 outputsChanged = true;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006073 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006074 }
6075
6076 checkVirtualizerClientRoutes();
6077
Eric Laurente191d1b2022-04-15 11:59:25 +02006078 if (outputsChanged) {
6079 mPreviousOutputs = mOutputs;
6080 mpClientInterface->onAudioPortListUpdate();
6081 }
6082
6083 if (mSpatializerOutput == nullptr) {
6084 ALOGV("%s could not open spatializer output with requested config", __func__);
6085 return BAD_VALUE;
6086 }
Eric Laurent39095982021-08-24 18:29:27 +02006087 *output = mSpatializerOutput->mIoHandle;
Eric Laurente191d1b2022-04-15 11:59:25 +02006088 ALOGV("%s returning new spatializer output %d", __func__, *output);
6089 return OK;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006090}
6091
Eric Laurentfa0f6742021-08-17 18:39:44 +02006092status_t AudioPolicyManager::releaseSpatializerOutput(audio_io_handle_t output) {
6093 if (mSpatializerOutput == nullptr) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006094 return INVALID_OPERATION;
6095 }
Eric Laurentfa0f6742021-08-17 18:39:44 +02006096 if (mSpatializerOutput->mIoHandle != output) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006097 return BAD_VALUE;
6098 }
Eric Laurent39095982021-08-24 18:29:27 +02006099
Eric Laurente191d1b2022-04-15 11:59:25 +02006100 if (!isOutputOnlyAvailableRouteToSomeDevice(mSpatializerOutput)) {
6101 ALOGV("%s closing spatializer output %d", __func__, mSpatializerOutput->mIoHandle);
6102 closeOutput(mSpatializerOutput->mIoHandle);
6103 //from now on mSpatializerOutput is null
6104 checkVirtualizerClientRoutes();
6105 }
Eric Laurent39095982021-08-24 18:29:27 +02006106
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006107 return NO_ERROR;
6108}
6109
Eric Laurente552edb2014-03-10 17:42:56 -07006110// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07006111// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07006112// ----------------------------------------------------------------------------
Eric Laurent6a94d692014-05-20 11:18:06 -07006113uint32_t AudioPolicyManager::nextAudioPortGeneration()
6114{
Mikhail Naganov2773dd72017-12-08 10:12:11 -08006115 return mAudioPortGeneration++;
Eric Laurent6a94d692014-05-20 11:18:06 -07006116}
6117
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006118AudioPolicyManager::AudioPolicyManager(const sp<const AudioPolicyConfig>& config,
Mikhail Naganovf1b6d972023-05-02 13:56:01 -07006119 EngineInstance&& engine,
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006120 AudioPolicyClientInterface *clientInterface)
Eric Laurente552edb2014-03-10 17:42:56 -07006121 :
Andy Hung4ef19fa2018-05-15 19:35:29 -07006122 mUidCached(AID_AUDIOSERVER), // no need to call getuid(), there's only one of us running.
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006123 mConfig(config),
Mikhail Naganovf1b6d972023-05-02 13:56:01 -07006124 mEngine(std::move(engine)),
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006125 mpClientInterface(clientInterface),
Eric Laurente552edb2014-03-10 17:42:56 -07006126 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
Eric Laurent3a4311c2014-03-17 12:00:47 -07006127 mA2dpSuspended(false),
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006128 mAudioPortGeneration(1),
6129 mBeaconMuteRefCount(0),
6130 mBeaconPlayingRefCount(0),
Eric Laurent9459fb02015-08-12 18:36:32 -07006131 mBeaconMuted(false),
Andy Hung2ddee192015-12-18 17:34:44 -08006132 mTtsOutputAvailable(false),
Eric Laurent36829f92017-04-07 19:04:42 -07006133 mMasterMono(false),
Eric Laurent4eb58f12018-12-07 16:41:02 -08006134 mMusicEffectOutput(AUDIO_IO_HANDLE_NONE)
Eric Laurente552edb2014-03-10 17:42:56 -07006135{
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006136}
François Gaffied1ab2bd2015-12-02 18:20:06 +01006137
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006138status_t AudioPolicyManager::initialize() {
Mikhail Naganovf1b6d972023-05-02 13:56:01 -07006139 if (mEngine == nullptr) {
6140 return NO_INIT;
François Gaffie2110e042015-03-24 08:41:51 +01006141 }
6142 mEngine->setObserver(this);
6143 status_t status = mEngine->initCheck();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006144 if (status != NO_ERROR) {
6145 LOG_FATAL("Policy engine not initialized(err=%d)", status);
6146 return status;
6147 }
François Gaffie2110e042015-03-24 08:41:51 +01006148
jiabin29230182023-04-04 21:02:36 +00006149 // The actual device selection cache will be updated when calling `updateDevicesAndOutputs`
6150 // at the end of this function.
6151 mEngine->initializeDeviceSelectionCache();
Eric Laurent1d69c872021-01-11 18:53:01 +01006152 mCommunnicationStrategy = mEngine->getProductStrategyForAttributes(
6153 mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL));
6154
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006155 // after parsing the config, mConfig contain all known devices;
Eric Laurente552edb2014-03-10 17:42:56 -07006156 // open all output streams needed to access attached devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006157 onNewAudioModulesAvailableInt(nullptr /*newDevices*/);
François Gaffie11d30102018-11-02 16:09:09 +01006158
Eric Laurent3a4311c2014-03-17 12:00:47 -07006159 // make sure default device is reachable
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006160 if (const auto defaultOutputDevice = mConfig->getDefaultOutputDevice();
6161 defaultOutputDevice == nullptr ||
6162 !mAvailableOutputDevices.contains(defaultOutputDevice)) {
6163 ALOGE_IF(defaultOutputDevice != nullptr, "Default device %s is unreachable",
6164 defaultOutputDevice->toString().c_str());
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006165 status = NO_INIT;
Eric Laurent3a4311c2014-03-17 12:00:47 -07006166 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02006167 ALOGW_IF(mPrimaryOutput == nullptr, "The policy configuration does not declare a primary output");
Eric Laurente552edb2014-03-10 17:42:56 -07006168
Tomoharu Kasahara71c90912018-10-31 09:10:12 +09006169 // Silence ALOGV statements
6170 property_set("log.tag." LOG_TAG, "D");
6171
Eric Laurente552edb2014-03-10 17:42:56 -07006172 updateDevicesAndOutputs();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006173 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07006174}
6175
Eric Laurente0720872014-03-11 09:30:41 -07006176AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07006177{
Eric Laurente552edb2014-03-10 17:42:56 -07006178 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08006179 mOutputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07006180 }
6181 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08006182 mInputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07006183 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07006184 mAvailableOutputDevices.clear();
6185 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07006186 mOutputs.clear();
6187 mInputs.clear();
6188 mHwModules.clear();
Mikhail Naganov100f0122018-11-29 11:22:16 -08006189 mManualSurroundFormats.clear();
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006190 mConfig.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07006191}
6192
Eric Laurente0720872014-03-11 09:30:41 -07006193status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07006194{
Eric Laurent87ffa392015-05-22 10:32:38 -07006195 return hasPrimaryOutput() ? NO_ERROR : NO_INIT;
Eric Laurente552edb2014-03-10 17:42:56 -07006196}
6197
Eric Laurente552edb2014-03-10 17:42:56 -07006198// ---
6199
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006200void AudioPolicyManager::onNewAudioModulesAvailable()
6201{
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006202 DeviceVector newDevices;
6203 onNewAudioModulesAvailableInt(&newDevices);
6204 if (!newDevices.empty()) {
6205 nextAudioPortGeneration();
6206 mpClientInterface->onAudioPortListUpdate();
6207 }
6208}
6209
6210void AudioPolicyManager::onNewAudioModulesAvailableInt(DeviceVector *newDevices)
6211{
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006212 for (const auto& hwModule : mConfig->getHwModules()) {
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006213 if (std::find(mHwModules.begin(), mHwModules.end(), hwModule) != mHwModules.end()) {
6214 continue;
6215 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006216 if (hwModule->getHandle() == AUDIO_MODULE_HANDLE_NONE) {
Mikhail Naganovffd97712023-05-03 17:45:36 -07006217 if (audio_module_handle_t handle = mpClientInterface->loadHwModule(hwModule->getName());
6218 handle != AUDIO_MODULE_HANDLE_NONE) {
6219 hwModule->setHandle(handle);
6220 } else {
6221 ALOGW("could not load HW module %s", hwModule->getName());
6222 continue;
6223 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006224 }
6225 mHwModules.push_back(hwModule);
Dean Wheatley12a87132021-04-16 10:08:49 +10006226 // open all output streams needed to access attached devices.
6227 // direct outputs are closed immediately after checking the availability of attached devices
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006228 // This also validates mAvailableOutputDevices list
6229 for (const auto& outProfile : hwModule->getOutputProfiles()) {
6230 if (!outProfile->canOpenNewIo()) {
6231 ALOGE("Invalid Output profile max open count %u for profile %s",
6232 outProfile->maxOpenCount, outProfile->getTagName().c_str());
6233 continue;
6234 }
6235 if (!outProfile->hasSupportedDevices()) {
6236 ALOGW("Output profile contains no device on module %s", hwModule->getName());
6237 continue;
6238 }
Carter Hsu1a3364a2022-01-21 15:32:56 +08006239 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_TTS) != 0 ||
6240 (outProfile->getFlags() & AUDIO_OUTPUT_FLAG_ULTRASOUND) != 0) {
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006241 mTtsOutputAvailable = true;
6242 }
6243
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006244 const DeviceVector &supportedDevices = outProfile->getSupportedDevices();
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006245 DeviceVector availProfileDevices = supportedDevices.filter(mConfig->getOutputDevices());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006246 sp<DeviceDescriptor> supportedDevice = 0;
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006247 if (supportedDevices.contains(mConfig->getDefaultOutputDevice())) {
6248 supportedDevice = mConfig->getDefaultOutputDevice();
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006249 } else {
6250 // choose first device present in profile's SupportedDevices also part of
6251 // mAvailableOutputDevices.
6252 if (availProfileDevices.isEmpty()) {
6253 continue;
6254 }
6255 supportedDevice = availProfileDevices.itemAt(0);
6256 }
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006257 if (!mConfig->getOutputDevices().contains(supportedDevice)) {
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006258 continue;
6259 }
6260 sp<SwAudioOutputDescriptor> outputDesc = new SwAudioOutputDescriptor(outProfile,
6261 mpClientInterface);
6262 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentf1f22e72021-07-13 14:04:14 +02006263 status_t status = outputDesc->open(nullptr /* halConfig */, nullptr /* mixerConfig */,
6264 DeviceVector(supportedDevice),
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006265 AUDIO_STREAM_DEFAULT,
6266 AUDIO_OUTPUT_FLAG_NONE, &output);
6267 if (status != NO_ERROR) {
6268 ALOGW("Cannot open output stream for devices %s on hw module %s",
6269 supportedDevice->toString().c_str(), hwModule->getName());
6270 continue;
6271 }
6272 for (const auto &device : availProfileDevices) {
6273 // give a valid ID to an attached device once confirmed it is reachable
6274 if (!device->isAttached()) {
6275 device->attach(hwModule);
6276 mAvailableOutputDevices.add(device);
jiabin1c4794b2020-05-05 10:08:05 -07006277 device->setEncapsulationInfoFromHal(mpClientInterface);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006278 if (newDevices) newDevices->add(device);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006279 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
6280 }
6281 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02006282 if (mPrimaryOutput == nullptr &&
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006283 outProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
6284 mPrimaryOutput = outputDesc;
François Gaffiedb1755b2023-09-01 11:50:35 +02006285 mPrimaryModuleHandle = mPrimaryOutput->getModuleHandle();
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006286 }
Eric Laurent39095982021-08-24 18:29:27 +02006287 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
Eric Laurentc529cf62020-04-17 18:19:10 -07006288 outputDesc->close();
6289 } else {
6290 addOutput(output, outputDesc);
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05306291 setOutputDevices(__func__, outputDesc,
Eric Laurentc529cf62020-04-17 18:19:10 -07006292 DeviceVector(supportedDevice),
6293 true,
6294 0,
6295 NULL);
6296 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006297 }
6298 // open input streams needed to access attached devices to validate
6299 // mAvailableInputDevices list
6300 for (const auto& inProfile : hwModule->getInputProfiles()) {
6301 if (!inProfile->canOpenNewIo()) {
6302 ALOGE("Invalid Input profile max open count %u for profile %s",
6303 inProfile->maxOpenCount, inProfile->getTagName().c_str());
6304 continue;
6305 }
6306 if (!inProfile->hasSupportedDevices()) {
6307 ALOGW("Input profile contains no device on module %s", hwModule->getName());
6308 continue;
6309 }
6310 // chose first device present in profile's SupportedDevices also part of
6311 // available input devices
6312 const DeviceVector &supportedDevices = inProfile->getSupportedDevices();
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006313 DeviceVector availProfileDevices = supportedDevices.filter(mConfig->getInputDevices());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006314 if (availProfileDevices.isEmpty()) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01006315 ALOGV("%s: Input device list is empty! for profile %s",
6316 __func__, inProfile->getTagName().c_str());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006317 continue;
6318 }
6319 sp<AudioInputDescriptor> inputDesc =
6320 new AudioInputDescriptor(inProfile, mpClientInterface);
6321
6322 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
6323 status_t status = inputDesc->open(nullptr,
6324 availProfileDevices.itemAt(0),
6325 AUDIO_SOURCE_MIC,
6326 AUDIO_INPUT_FLAG_NONE,
6327 &input);
6328 if (status != NO_ERROR) {
6329 ALOGW("Cannot open input stream for device %s on hw module %s",
6330 availProfileDevices.toString().c_str(),
6331 hwModule->getName());
6332 continue;
6333 }
6334 for (const auto &device : availProfileDevices) {
6335 // give a valid ID to an attached device once confirmed it is reachable
6336 if (!device->isAttached()) {
6337 device->attach(hwModule);
6338 device->importAudioPortAndPickAudioProfile(inProfile, true);
6339 mAvailableInputDevices.add(device);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006340 if (newDevices) newDevices->add(device);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006341 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
6342 }
6343 }
6344 inputDesc->close();
6345 }
6346 }
Eric Laurente191d1b2022-04-15 11:59:25 +02006347
6348 // Check if spatializer outputs can be closed until used.
6349 // mOutputs vector never contains duplicated outputs at this point.
6350 std::vector<audio_io_handle_t> outputsClosed;
6351 for (size_t i = 0; i < mOutputs.size(); i++) {
6352 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
6353 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0
6354 && !isOutputOnlyAvailableRouteToSomeDevice(desc)) {
6355 outputsClosed.push_back(desc->mIoHandle);
6356 desc->close();
6357 }
6358 }
6359 for (auto output : outputsClosed) {
6360 removeOutput(output);
6361 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006362}
6363
Eric Laurent98e38192018-02-15 18:31:53 -08006364void AudioPolicyManager::addOutput(audio_io_handle_t output,
6365 const sp<SwAudioOutputDescriptor>& outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07006366{
Eric Laurent1c333e22014-05-20 10:48:17 -07006367 mOutputs.add(output, outputDesc);
jiabin9a3361e2019-10-01 09:38:30 -07006368 applyStreamVolumes(outputDesc, DeviceTypeSet(), 0 /* delayMs */, true /* force */);
Andy Hung2ddee192015-12-18 17:34:44 -08006369 updateMono(output); // update mono status when adding to output list
Eric Laurent36829f92017-04-07 19:04:42 -07006370 selectOutputForMusicEffects();
Eric Laurent6a94d692014-05-20 11:18:06 -07006371 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07006372}
6373
François Gaffie53615e22015-03-19 09:24:12 +01006374void AudioPolicyManager::removeOutput(audio_io_handle_t output)
6375{
Francois Gaffiebce7cd42020-10-14 16:13:20 +02006376 if (mPrimaryOutput != 0 && mPrimaryOutput == mOutputs.valueFor(output)) {
6377 ALOGV("%s: removing primary output", __func__);
6378 mPrimaryOutput = nullptr;
6379 }
François Gaffie53615e22015-03-19 09:24:12 +01006380 mOutputs.removeItem(output);
Eric Laurent36829f92017-04-07 19:04:42 -07006381 selectOutputForMusicEffects();
François Gaffie53615e22015-03-19 09:24:12 +01006382}
6383
Eric Laurent98e38192018-02-15 18:31:53 -08006384void AudioPolicyManager::addInput(audio_io_handle_t input,
6385 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07006386{
Eric Laurent1c333e22014-05-20 10:48:17 -07006387 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07006388 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07006389}
Eric Laurente552edb2014-03-10 17:42:56 -07006390
François Gaffie11d30102018-11-02 16:09:09 +01006391status_t AudioPolicyManager::checkOutputsForDevice(const sp<DeviceDescriptor>& device,
François Gaffie53615e22015-03-19 09:24:12 +01006392 audio_policy_dev_state_t state,
François Gaffie11d30102018-11-02 16:09:09 +01006393 SortedVector<audio_io_handle_t>& outputs)
Eric Laurente552edb2014-03-10 17:42:56 -07006394{
François Gaffie11d30102018-11-02 16:09:09 +01006395 audio_devices_t deviceType = device->type();
jiabince9f20e2019-09-12 16:29:15 -07006396 const String8 &address = String8(device->address().c_str());
Eric Laurentc75307b2015-03-17 15:29:32 -07006397 sp<SwAudioOutputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07006398
François Gaffie11d30102018-11-02 16:09:09 +01006399 if (audio_device_is_digital(deviceType)) {
Eric Laurentcc750d32015-06-25 11:48:20 -07006400 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01006401 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07006402 }
Eric Laurente552edb2014-03-10 17:42:56 -07006403
Eric Laurent3b73df72014-03-11 09:06:29 -07006404 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
jiabinb4fed192020-09-22 14:45:40 -07006405 // first call getAudioPort to get the supported attributes from the HAL
6406 struct audio_port_v7 port = {};
6407 device->toAudioPort(&port);
6408 status_t status = mpClientInterface->getAudioPort(&port);
6409 if (status == NO_ERROR) {
6410 device->importAudioPort(port);
6411 }
6412
6413 // then list already open outputs that can be routed to this device
Eric Laurente552edb2014-03-10 17:42:56 -07006414 for (size_t i = 0; i < mOutputs.size(); i++) {
6415 desc = mOutputs.valueAt(i);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006416 if (!desc->isDuplicated() && desc->supportsDevice(device)
jiabin9a3361e2019-10-01 09:38:30 -07006417 && desc->devicesSupportEncodedFormats({deviceType})) {
François Gaffie11d30102018-11-02 16:09:09 +01006418 ALOGV("checkOutputsForDevice(): adding opened output %d on device %s",
6419 mOutputs.keyAt(i), device->toString().c_str());
6420 outputs.add(mOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07006421 }
6422 }
6423 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07006424 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006425 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006426 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
6427 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
François Gaffie11d30102018-11-02 16:09:09 +01006428 if (profile->supportsDevice(device)) {
6429 profiles.add(profile);
6430 ALOGV("checkOutputsForDevice(): adding profile %zu from module %s",
6431 j, hwModule->getName());
Eric Laurente552edb2014-03-10 17:42:56 -07006432 }
6433 }
6434 }
6435
Eric Laurent7b279bb2015-12-14 10:18:23 -08006436 ALOGV(" found %zu profiles, %zu outputs", profiles.size(), outputs.size());
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006437
Eric Laurente552edb2014-03-10 17:42:56 -07006438 if (profiles.isEmpty() && outputs.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006439 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07006440 return BAD_VALUE;
6441 }
6442
6443 // open outputs for matching profiles if needed. Direct outputs are also opened to
6444 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
6445 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07006446 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07006447
6448 // nothing to do if one output is already opened for this profile
6449 size_t j;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006450 for (j = 0; j < outputs.size(); j++) {
6451 desc = mOutputs.valueFor(outputs.itemAt(j));
Eric Laurente552edb2014-03-10 17:42:56 -07006452 if (!desc->isDuplicated() && desc->mProfile == profile) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07006453 // matching profile: save the sample rates, format and channel masks supported
6454 // by the profile in our device descriptor
François Gaffie11d30102018-11-02 16:09:09 +01006455 if (audio_device_is_digital(deviceType)) {
jiabin4ef93452019-09-10 14:29:54 -07006456 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006457 }
Eric Laurente552edb2014-03-10 17:42:56 -07006458 break;
6459 }
6460 }
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006461 if (j != outputs.size()) {
Eric Laurente552edb2014-03-10 17:42:56 -07006462 continue;
6463 }
6464
Eric Laurent3974e3b2017-12-07 17:58:43 -08006465 if (!profile->canOpenNewIo()) {
6466 ALOGW("Max Output number %u already opened for this profile %s",
6467 profile->maxOpenCount, profile->getTagName().c_str());
6468 continue;
6469 }
6470
Eric Laurent83efe1c2017-07-09 16:51:08 -07006471 ALOGV("opening output for device %08x with params %s profile %p name %s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00006472 deviceType, address.c_str(), profile.get(), profile->getName().c_str());
jiabinbce0c1d2020-10-05 11:20:18 -07006473 desc = openOutputWithProfileAndDevice(profile, DeviceVector(device));
6474 audio_io_handle_t output = desc == nullptr ? AUDIO_IO_HANDLE_NONE : desc->mIoHandle;
Eric Laurentcf2c0212014-07-25 16:20:43 -07006475 if (output == AUDIO_IO_HANDLE_NONE) {
François Gaffie11d30102018-11-02 16:09:09 +01006476 ALOGW("checkOutputsForDevice() could not open output for device %x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07006477 profiles.removeAt(profile_index);
6478 profile_index--;
6479 } else {
6480 outputs.add(output);
Paul McLean9080a4c2015-06-18 08:24:02 -07006481 // Load digital format info only for digital devices
François Gaffie11d30102018-11-02 16:09:09 +01006482 if (audio_device_is_digital(deviceType)) {
jiabinbce0c1d2020-10-05 11:20:18 -07006483 // TODO: when getAudioPort is ready, it may not be needed to import the audio
6484 // port but just pick audio profile
jiabin4ef93452019-09-10 14:29:54 -07006485 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006486 }
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07006487
François Gaffie11d30102018-11-02 16:09:09 +01006488 if (device_distinguishes_on_address(deviceType)) {
6489 ALOGV("checkOutputsForDevice(): setOutputDevices %s",
6490 device->toString().c_str());
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05306491 setOutputDevices(__func__, desc, DeviceVector(device), true/*force*/,
6492 0/*delay*/, NULL/*patch handle*/);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006493 }
Eric Laurente552edb2014-03-10 17:42:56 -07006494 ALOGV("checkOutputsForDevice(): adding output %d", output);
6495 }
6496 }
6497
6498 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006499 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07006500 return BAD_VALUE;
6501 }
Eric Laurentd4692962014-05-05 18:13:44 -07006502 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07006503 // check if one opened output is not needed any more after disconnecting one device
6504 for (size_t i = 0; i < mOutputs.size(); i++) {
6505 desc = mOutputs.valueAt(i);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006506 if (!desc->isDuplicated()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08006507 // exact match on device
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006508 if (device_distinguishes_on_address(deviceType) && desc->supportsDevice(device)
Francois Gaffiec7d4c222021-12-02 11:12:52 +01006509 && desc->containsSingleDeviceSupportingEncodedFormats(device)) {
François Gaffie11d30102018-11-02 16:09:09 +01006510 outputs.add(mOutputs.keyAt(i));
Francois Gaffie716e1432019-01-14 16:58:59 +01006511 } else if (!mAvailableOutputDevices.containsAtLeastOne(desc->supportedDevices())) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006512 ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
6513 mOutputs.keyAt(i));
6514 outputs.add(mOutputs.keyAt(i));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006515 }
Eric Laurente552edb2014-03-10 17:42:56 -07006516 }
6517 }
Eric Laurentd4692962014-05-05 18:13:44 -07006518 // Clear any profiles associated with the disconnected device.
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006519 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006520 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
6521 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
jiabinbce0c1d2020-10-05 11:20:18 -07006522 if (!profile->supportsDevice(device)) {
6523 continue;
6524 }
6525 ALOGV("checkOutputsForDevice(): "
6526 "clearing direct output profile %zu on module %s",
6527 j, hwModule->getName());
6528 profile->clearAudioProfiles();
6529 if (!profile->hasDynamicAudioProfile()) {
6530 continue;
6531 }
6532 // When a device is disconnected, if there is an IOProfile that contains dynamic
6533 // profiles and supports the disconnected device, call getAudioPort to repopulate
6534 // the capabilities of the devices that is supported by the IOProfile.
6535 for (const auto& supportedDevice : profile->getSupportedDevices()) {
6536 if (supportedDevice == device ||
6537 !mAvailableOutputDevices.contains(supportedDevice)) {
6538 continue;
6539 }
6540 struct audio_port_v7 port;
6541 supportedDevice->toAudioPort(&port);
6542 status_t status = mpClientInterface->getAudioPort(&port);
6543 if (status == NO_ERROR) {
6544 supportedDevice->importAudioPort(port);
6545 }
Eric Laurente552edb2014-03-10 17:42:56 -07006546 }
6547 }
6548 }
6549 }
6550 return NO_ERROR;
6551}
6552
François Gaffie11d30102018-11-02 16:09:09 +01006553status_t AudioPolicyManager::checkInputsForDevice(const sp<DeviceDescriptor>& device,
Eric Laurent0dd51852019-04-19 18:18:58 -07006554 audio_policy_dev_state_t state)
Eric Laurentd4692962014-05-05 18:13:44 -07006555{
Eric Laurent1f2f2232014-06-02 12:01:23 -07006556 sp<AudioInputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07006557
François Gaffie11d30102018-11-02 16:09:09 +01006558 if (audio_device_is_digital(device->type())) {
Eric Laurentcc750d32015-06-25 11:48:20 -07006559 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01006560 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07006561 }
6562
Eric Laurentd4692962014-05-05 18:13:44 -07006563 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
jiabinbf5f4262023-04-12 21:48:34 +00006564 // first call getAudioPort to get the supported attributes from the HAL
6565 struct audio_port_v7 port = {};
6566 device->toAudioPort(&port);
6567 status_t status = mpClientInterface->getAudioPort(&port);
6568 if (status == NO_ERROR) {
6569 device->importAudioPort(port);
6570 }
6571
Eric Laurent0dd51852019-04-19 18:18:58 -07006572 // look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07006573 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006574 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07006575 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006576 profile_index < hwModule->getInputProfiles().size();
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006577 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006578 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Eric Laurent275e8e92014-11-30 15:14:47 -08006579
François Gaffie11d30102018-11-02 16:09:09 +01006580 if (profile->supportsDevice(device)) {
6581 profiles.add(profile);
6582 ALOGV("checkInputsForDevice(): adding profile %zu from module %s",
6583 profile_index, hwModule->getName());
Eric Laurentd4692962014-05-05 18:13:44 -07006584 }
6585 }
6586 }
6587
Eric Laurent0dd51852019-04-19 18:18:58 -07006588 if (profiles.isEmpty()) {
6589 ALOGW("%s: No input profile available for device %s",
6590 __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07006591 return BAD_VALUE;
6592 }
6593
6594 // open inputs for matching profiles if needed. Direct inputs are also opened to
6595 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
6596 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
6597
Eric Laurent1c333e22014-05-20 10:48:17 -07006598 sp<IOProfile> profile = profiles[profile_index];
Eric Laurent3974e3b2017-12-07 17:58:43 -08006599
Eric Laurentd4692962014-05-05 18:13:44 -07006600 // nothing to do if one input is already opened for this profile
6601 size_t input_index;
6602 for (input_index = 0; input_index < mInputs.size(); input_index++) {
6603 desc = mInputs.valueAt(input_index);
6604 if (desc->mProfile == profile) {
François Gaffie11d30102018-11-02 16:09:09 +01006605 if (audio_device_is_digital(device->type())) {
jiabin4ef93452019-09-10 14:29:54 -07006606 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006607 }
Eric Laurentd4692962014-05-05 18:13:44 -07006608 break;
6609 }
6610 }
6611 if (input_index != mInputs.size()) {
6612 continue;
6613 }
6614
Eric Laurent3974e3b2017-12-07 17:58:43 -08006615 if (!profile->canOpenNewIo()) {
6616 ALOGW("Max Input number %u already opened for this profile %s",
6617 profile->maxOpenCount, profile->getTagName().c_str());
6618 continue;
6619 }
6620
Eric Laurentfe231122017-11-17 17:48:06 -08006621 desc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentcf2c0212014-07-25 16:20:43 -07006622 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
jiabinbf5f4262023-04-12 21:48:34 +00006623 status = desc->open(nullptr, device, AUDIO_SOURCE_MIC, AUDIO_INPUT_FLAG_NONE, &input);
Eric Laurentd4692962014-05-05 18:13:44 -07006624
Eric Laurentcf2c0212014-07-25 16:20:43 -07006625 if (status == NO_ERROR) {
jiabince9f20e2019-09-12 16:29:15 -07006626 const String8& address = String8(device->address().c_str());
Tomasz Wasilczykfd9ffd12023-08-14 17:56:22 +00006627 if (!address.empty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006628 char *param = audio_device_address_to_parameter(device->type(), address);
Eric Laurentcf2c0212014-07-25 16:20:43 -07006629 mpClientInterface->setParameters(input, String8(param));
6630 free(param);
Eric Laurentd4692962014-05-05 18:13:44 -07006631 }
jiabin12537fc2023-10-12 17:56:08 +00006632 updateAudioProfiles(device, input, profile);
François Gaffie112b0af2015-11-19 16:13:25 +01006633 if (!profile->hasValidAudioProfile()) {
Eric Laurentd4692962014-05-05 18:13:44 -07006634 ALOGW("checkInputsForDevice() direct input missing param");
Eric Laurentfe231122017-11-17 17:48:06 -08006635 desc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07006636 input = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07006637 }
6638
Eric Laurent0dd51852019-04-19 18:18:58 -07006639 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07006640 addInput(input, desc);
6641 }
6642 } // endif input != 0
6643
Eric Laurentcf2c0212014-07-25 16:20:43 -07006644 if (input == AUDIO_IO_HANDLE_NONE) {
Pattydd807582021-11-04 21:01:03 +08006645 ALOGW("%s could not open input for device %s", __func__,
François Gaffie11d30102018-11-02 16:09:09 +01006646 device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07006647 profiles.removeAt(profile_index);
6648 profile_index--;
6649 } else {
François Gaffie11d30102018-11-02 16:09:09 +01006650 if (audio_device_is_digital(device->type())) {
jiabin4ef93452019-09-10 14:29:54 -07006651 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006652 }
Eric Laurentd4692962014-05-05 18:13:44 -07006653 ALOGV("checkInputsForDevice(): adding input %d", input);
6654 }
6655 } // end scan profiles
6656
6657 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006658 ALOGW("%s: No input available for device %s", __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07006659 return BAD_VALUE;
6660 }
6661 } else {
6662 // Disconnect
Eric Laurentd4692962014-05-05 18:13:44 -07006663 // Clear any profiles associated with the disconnected device.
Mikhail Naganovd4120142017-12-06 15:49:22 -08006664 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07006665 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006666 profile_index < hwModule->getInputProfiles().size();
Eric Laurentd4692962014-05-05 18:13:44 -07006667 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006668 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Francois Gaffie716e1432019-01-14 16:58:59 +01006669 if (profile->supportsDevice(device)) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08006670 ALOGV("checkInputsForDevice(): clearing direct input profile %zu on module %s",
6671 profile_index, hwModule->getName());
François Gaffie112b0af2015-11-19 16:13:25 +01006672 profile->clearAudioProfiles();
Eric Laurentd4692962014-05-05 18:13:44 -07006673 }
6674 }
6675 }
6676 } // end disconnect
6677
6678 return NO_ERROR;
6679}
6680
6681
Eric Laurente0720872014-03-11 09:30:41 -07006682void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07006683{
6684 ALOGV("closeOutput(%d)", output);
6685
François Gaffie1c878552018-11-22 16:53:21 +01006686 sp<SwAudioOutputDescriptor> closingOutput = mOutputs.valueFor(output);
6687 if (closingOutput == NULL) {
Eric Laurente552edb2014-03-10 17:42:56 -07006688 ALOGW("closeOutput() unknown output %d", output);
6689 return;
6690 }
Mikhail Naganov32ebca32019-03-22 15:42:52 -07006691 const bool closingOutputWasActive = closingOutput->isActive();
François Gaffie1c878552018-11-22 16:53:21 +01006692 mPolicyMixes.closeOutput(closingOutput);
Eric Laurent275e8e92014-11-30 15:14:47 -08006693
Eric Laurente552edb2014-03-10 17:42:56 -07006694 // look for duplicated outputs connected to the output being removed.
6695 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie1c878552018-11-22 16:53:21 +01006696 sp<SwAudioOutputDescriptor> dupOutput = mOutputs.valueAt(i);
6697 if (dupOutput->isDuplicated() &&
6698 (dupOutput->mOutput1 == closingOutput || dupOutput->mOutput2 == closingOutput)) {
6699 sp<SwAudioOutputDescriptor> remainingOutput =
6700 dupOutput->mOutput1 == closingOutput ? dupOutput->mOutput2 : dupOutput->mOutput1;
Eric Laurente552edb2014-03-10 17:42:56 -07006701 // As all active tracks on duplicated output will be deleted,
6702 // and as they were also referenced on the other output, the reference
6703 // count for their stream type must be adjusted accordingly on
6704 // the other output.
François Gaffie1c878552018-11-22 16:53:21 +01006705 const bool wasActive = remainingOutput->isActive();
6706 // Note: no-op on the closing output where all clients has already been set inactive
6707 dupOutput->setAllClientsInactive();
Eric Laurent733ce942017-12-07 12:18:25 -08006708 // stop() will be a no op if the output is still active but is needed in case all
6709 // active streams refcounts where cleared above
6710 if (wasActive) {
François Gaffie1c878552018-11-22 16:53:21 +01006711 remainingOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08006712 }
Eric Laurente552edb2014-03-10 17:42:56 -07006713 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
6714 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
6715
6716 mpClientInterface->closeOutput(duplicatedOutput);
François Gaffie53615e22015-03-19 09:24:12 +01006717 removeOutput(duplicatedOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07006718 }
6719 }
6720
Eric Laurent05b90f82014-08-27 15:32:29 -07006721 nextAudioPortGeneration();
6722
François Gaffie1c878552018-11-22 16:53:21 +01006723 ssize_t index = mAudioPatches.indexOfKey(closingOutput->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07006724 if (index >= 0) {
6725 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006726 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
6727 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07006728 mAudioPatches.removeItemsAt(index);
6729 mpClientInterface->onAudioPatchListUpdate();
6730 }
6731
Mikhail Naganov32ebca32019-03-22 15:42:52 -07006732 if (closingOutputWasActive) {
6733 closingOutput->stop();
6734 }
François Gaffie1c878552018-11-22 16:53:21 +01006735 closingOutput->close();
Eric Laurente552edb2014-03-10 17:42:56 -07006736
François Gaffie53615e22015-03-19 09:24:12 +01006737 removeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07006738 mPreviousOutputs = mOutputs;
Eric Laurentb4f42a92022-01-17 17:37:31 +01006739 if (closingOutput == mSpatializerOutput) {
6740 mSpatializerOutput.clear();
6741 }
Dean Wheatley3023b382018-08-09 07:42:40 +10006742
6743 // MSD patches may have been released to support a non-MSD direct output. Reset MSD patch if
6744 // no direct outputs are open.
François Gaffie11d30102018-11-02 16:09:09 +01006745 if (!getMsdAudioOutDevices().isEmpty()) {
Dean Wheatley3023b382018-08-09 07:42:40 +10006746 bool directOutputOpen = false;
6747 for (size_t i = 0; i < mOutputs.size(); i++) {
6748 if (mOutputs[i]->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
6749 directOutputOpen = true;
6750 break;
6751 }
6752 }
6753 if (!directOutputOpen) {
Michael Chan6fb34492020-12-08 15:44:49 +11006754 ALOGV("no direct outputs open, reset MSD patches");
6755 // TODO: The MSD patches to be established here may differ to current MSD patches due to
6756 // how output devices for patching are resolved. Avoid by caching and reusing the
6757 // arguments to mEngine->getOutputDevicesForAttributes() when resolving which output
6758 // devices to patch to. This may be complicated by the fact that devices may become
6759 // unavailable.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11006760 setMsdOutputPatches();
Dean Wheatley3023b382018-08-09 07:42:40 +10006761 }
6762 }
Eric Laurent05b90f82014-08-27 15:32:29 -07006763}
6764
6765void AudioPolicyManager::closeInput(audio_io_handle_t input)
6766{
6767 ALOGV("closeInput(%d)", input);
6768
6769 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
6770 if (inputDesc == NULL) {
6771 ALOGW("closeInput() unknown input %d", input);
6772 return;
6773 }
6774
Eric Laurent6a94d692014-05-20 11:18:06 -07006775 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07006776
François Gaffie11d30102018-11-02 16:09:09 +01006777 sp<DeviceDescriptor> device = inputDesc->getDevice();
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08006778 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07006779 if (index >= 0) {
6780 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006781 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
6782 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07006783 mAudioPatches.removeItemsAt(index);
6784 mpClientInterface->onAudioPatchListUpdate();
6785 }
6786
François Gaffie6ebbce02023-07-19 13:27:53 +02006787 mEffects.putOrphanEffectsForIo(input);
Eric Laurentfe231122017-11-17 17:48:06 -08006788 inputDesc->close();
Eric Laurent05b90f82014-08-27 15:32:29 -07006789 mInputs.removeItem(input);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07006790
François Gaffie11d30102018-11-02 16:09:09 +01006791 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
6792 if (primaryInputDevices.contains(device) &&
Haynes Mathew George1d539d92018-03-16 11:40:49 -07006793 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07006794 mpClientInterface->setSoundTriggerCaptureState(false);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07006795 }
Eric Laurente552edb2014-03-10 17:42:56 -07006796}
6797
François Gaffie11d30102018-11-02 16:09:09 +01006798SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevices(
6799 const DeviceVector &devices,
6800 const SwAudioOutputCollection& openOutputs)
Eric Laurente552edb2014-03-10 17:42:56 -07006801{
6802 SortedVector<audio_io_handle_t> outputs;
6803
François Gaffie11d30102018-11-02 16:09:09 +01006804 ALOGVV("%s() devices %s", __func__, devices.toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07006805 for (size_t i = 0; i < openOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01006806 ALOGVV("output %zu isDuplicated=%d device=%s",
Eric Laurent8c7e6da2015-04-21 17:37:00 -07006807 i, openOutputs.valueAt(i)->isDuplicated(),
François Gaffie11d30102018-11-02 16:09:09 +01006808 openOutputs.valueAt(i)->supportedDevices().toString().c_str());
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006809 if (openOutputs.valueAt(i)->supportsAllDevices(devices)
jiabin9a3361e2019-10-01 09:38:30 -07006810 && openOutputs.valueAt(i)->devicesSupportEncodedFormats(devices.types())) {
François Gaffie11d30102018-11-02 16:09:09 +01006811 ALOGVV("%s() found output %d", __func__, openOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07006812 outputs.add(openOutputs.keyAt(i));
6813 }
6814 }
6815 return outputs;
6816}
6817
Mikhail Naganov37977152018-07-11 15:54:44 -07006818void AudioPolicyManager::checkForDeviceAndOutputChanges(std::function<bool()> onOutputsChecked)
6819{
6820 // checkA2dpSuspend must run before checkOutputForAllStrategies so that A2DP
6821 // output is suspended before any tracks are moved to it
6822 checkA2dpSuspend();
6823 checkOutputForAllStrategies();
Kevin Rocard153f92d2018-12-18 18:33:28 -08006824 checkSecondaryOutputs();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11006825 if (onOutputsChecked != nullptr && onOutputsChecked()) checkA2dpSuspend();
Mikhail Naganov37977152018-07-11 15:54:44 -07006826 updateDevicesAndOutputs();
Mikhail Naganov7bd9b8d2018-11-15 02:09:03 +00006827 if (mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD) != 0) {
Michael Chan6fb34492020-12-08 15:44:49 +11006828 // TODO: The MSD patches to be established here may differ to current MSD patches due to how
6829 // output devices for patching are resolved. Nevertheless, AudioTracks affected by device
6830 // configuration changes will ultimately be rerouted correctly. We can still avoid
6831 // unnecessary rerouting by caching and reusing the arguments to
6832 // mEngine->getOutputDevicesForAttributes() when resolving which output devices to patch to.
6833 // This may be complicated by the fact that devices may become unavailable.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11006834 setMsdOutputPatches();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11006835 }
Jean-Michel Trivi9a6b9ad2020-10-22 16:46:43 -07006836 // an event that changed routing likely occurred, inform upper layers
6837 mpClientInterface->onRoutingUpdated();
Mikhail Naganov37977152018-07-11 15:54:44 -07006838}
6839
François Gaffiec005e562018-11-06 15:04:49 +01006840bool AudioPolicyManager::followsSameRouting(const audio_attributes_t &lAttr,
6841 const audio_attributes_t &rAttr) const
Eric Laurente552edb2014-03-10 17:42:56 -07006842{
François Gaffiec005e562018-11-06 15:04:49 +01006843 return mEngine->getProductStrategyForAttributes(lAttr) ==
6844 mEngine->getProductStrategyForAttributes(rAttr);
6845}
6846
Francois Gaffieff1eb522020-05-06 18:37:04 +02006847void AudioPolicyManager::checkAudioSourceForAttributes(const audio_attributes_t &attr)
6848{
6849 for (size_t i = 0; i < mAudioSources.size(); i++) {
6850 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
6851 if (sourceDesc != nullptr && followsSameRouting(attr, sourceDesc->attributes())
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02006852 && sourceDesc->getPatchHandle() == AUDIO_PATCH_HANDLE_NONE
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02006853 && !isCallRxAudioSource(sourceDesc) && !sourceDesc->isInternal()) {
Francois Gaffieff1eb522020-05-06 18:37:04 +02006854 connectAudioSource(sourceDesc);
6855 }
6856 }
6857}
6858
6859void AudioPolicyManager::clearAudioSourcesForOutput(audio_io_handle_t output)
6860{
6861 for (size_t i = 0; i < mAudioSources.size(); i++) {
6862 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
6863 if (sourceDesc != nullptr && sourceDesc->swOutput().promote() != nullptr
6864 && sourceDesc->swOutput().promote()->mIoHandle == output) {
6865 disconnectAudioSource(sourceDesc);
6866 }
6867 }
6868}
6869
François Gaffiec005e562018-11-06 15:04:49 +01006870void AudioPolicyManager::checkOutputForAttributes(const audio_attributes_t &attr)
6871{
6872 auto psId = mEngine->getProductStrategyForAttributes(attr);
6873
6874 DeviceVector oldDevices = mEngine->getOutputDevicesForAttributes(attr, 0, true /*fromCache*/);
6875 DeviceVector newDevices = mEngine->getOutputDevicesForAttributes(attr, 0, false /*fromCache*/);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07006876
François Gaffie11d30102018-11-02 16:09:09 +01006877 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevices(oldDevices, mPreviousOutputs);
6878 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevices(newDevices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07006879
Eric Laurentc209fe42020-06-05 18:11:23 -07006880 uint32_t maxLatency = 0;
Oscar Azucena873d10f2023-01-12 18:34:42 -08006881 bool unneededUsePrimaryOutputFromPolicyMixes = false;
Eric Laurent56ed8842022-11-15 16:04:41 +01006882 std::vector<sp<SwAudioOutputDescriptor>> invalidatedOutputs;
Eric Laurentc209fe42020-06-05 18:11:23 -07006883 // take into account dynamic audio policies related changes: if a client is now associated
6884 // to a different policy mix than at creation time, invalidate corresponding stream
Eric Laurent56ed8842022-11-15 16:04:41 +01006885 for (size_t i = 0; i < mPreviousOutputs.size(); i++) {
Eric Laurentc209fe42020-06-05 18:11:23 -07006886 const sp<SwAudioOutputDescriptor>& desc = mPreviousOutputs.valueAt(i);
6887 if (desc->isDuplicated()) {
6888 continue;
Jean-Michel Trivife472e22014-12-16 14:23:13 -08006889 }
Eric Laurentc209fe42020-06-05 18:11:23 -07006890 for (const sp<TrackClientDescriptor>& client : desc->getClientIterable()) {
6891 if (mEngine->getProductStrategyForAttributes(client->attributes()) != psId) {
6892 continue;
6893 }
6894 sp<AudioPolicyMix> primaryMix;
Dean Wheatleyd082f472022-02-04 11:10:48 +11006895 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->config(),
Oscar Azucena873d10f2023-01-12 18:34:42 -08006896 client->uid(), client->session(), client->flags(), mAvailableOutputDevices,
6897 nullptr /* requestedDevice */, primaryMix, nullptr /* secondaryMixes */,
6898 unneededUsePrimaryOutputFromPolicyMixes);
Eric Laurentc209fe42020-06-05 18:11:23 -07006899 if (status != OK) {
6900 continue;
6901 }
yucliuf4de36d2020-09-14 14:57:56 -07006902 if (client->getPrimaryMix() != primaryMix || client->hasLostPrimaryMix()) {
Eric Laurent56ed8842022-11-15 16:04:41 +01006903 if (desc->isStrategyActive(psId) && maxLatency < desc->latency()) {
Eric Laurentc209fe42020-06-05 18:11:23 -07006904 maxLatency = desc->latency();
6905 }
Eric Laurent56ed8842022-11-15 16:04:41 +01006906 invalidatedOutputs.push_back(desc);
Eric Laurentc209fe42020-06-05 18:11:23 -07006907 }
Jean-Michel Trivife472e22014-12-16 14:23:13 -08006908 }
6909 }
6910
Eric Laurent56ed8842022-11-15 16:04:41 +01006911 if (srcOutputs != dstOutputs || !invalidatedOutputs.empty()) {
Eric Laurentac3a6902018-05-11 16:39:10 -07006912 // get maximum latency of all source outputs to determine the minimum mute time guaranteeing
6913 // audio from invalidated tracks will be rendered when unmuting
Eric Laurentac3a6902018-05-11 16:39:10 -07006914 for (audio_io_handle_t srcOut : srcOutputs) {
6915 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
Eric Laurentaa02db82019-09-05 17:31:49 -07006916 if (desc == nullptr) continue;
6917
6918 if (desc->isStrategyActive(psId) && maxLatency < desc->latency()) {
Eric Laurentac3a6902018-05-11 16:39:10 -07006919 maxLatency = desc->latency();
6920 }
Eric Laurentaa02db82019-09-05 17:31:49 -07006921
Eric Laurent56ed8842022-11-15 16:04:41 +01006922 bool invalidate = false;
Eric Laurentaa02db82019-09-05 17:31:49 -07006923 for (auto client : desc->clientsList(false /*activeOnly*/)) {
Eric Laurent78aade82019-09-13 18:55:08 -07006924 if (desc->isDuplicated() || !desc->mProfile->isDirectOutput()) {
Eric Laurentaa02db82019-09-05 17:31:49 -07006925 // a client on a non direct outputs has necessarily a linear PCM format
6926 // so we can call selectOutput() safely
6927 const audio_io_handle_t newOutput = selectOutput(dstOutputs,
6928 client->flags(),
6929 client->config().format,
6930 client->config().channel_mask,
jiabinebb6af42020-06-09 17:31:17 -07006931 client->config().sample_rate,
6932 client->session());
Eric Laurentaa02db82019-09-05 17:31:49 -07006933 if (newOutput != srcOut) {
6934 invalidate = true;
6935 break;
6936 }
6937 } else {
6938 sp<IOProfile> profile = getProfileForOutput(newDevices,
6939 client->config().sample_rate,
6940 client->config().format,
6941 client->config().channel_mask,
6942 client->flags(),
6943 true /* directOnly */);
6944 if (profile != desc->mProfile) {
6945 invalidate = true;
6946 break;
6947 }
6948 }
6949 }
Eric Laurent56ed8842022-11-15 16:04:41 +01006950 // mute strategy while moving tracks from one output to another
6951 if (invalidate) {
6952 invalidatedOutputs.push_back(desc);
6953 if (desc->isStrategyActive(psId)) {
6954 setStrategyMute(psId, true, desc);
6955 setStrategyMute(psId, false, desc, maxLatency * LATENCY_MUTE_FACTOR,
6956 newDevices.types());
6957 }
Eric Laurente552edb2014-03-10 17:42:56 -07006958 }
François Gaffiec005e562018-11-06 15:04:49 +01006959 sp<SourceClientDescriptor> source = getSourceForAttributesOnOutput(srcOut, attr);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02006960 if (source != nullptr && !isCallRxAudioSource(source) && !source->isInternal()) {
Eric Laurentd60560a2015-04-10 11:31:20 -07006961 connectAudioSource(source);
6962 }
Eric Laurente552edb2014-03-10 17:42:56 -07006963 }
6964
Eric Laurent56ed8842022-11-15 16:04:41 +01006965 ALOGV_IF(!(srcOutputs.isEmpty() || dstOutputs.isEmpty()),
6966 "%s: strategy %d, moving from output %s to output %s", __func__, psId,
6967 std::to_string(srcOutputs[0]).c_str(),
6968 std::to_string(dstOutputs[0]).c_str());
6969
François Gaffiec005e562018-11-06 15:04:49 +01006970 // Move effects associated to this stream from previous output to new output
6971 if (followsSameRouting(attr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07006972 selectOutputForMusicEffects();
Eric Laurente552edb2014-03-10 17:42:56 -07006973 }
François Gaffiec005e562018-11-06 15:04:49 +01006974 // Move tracks associated to this stream (and linked) from previous output to new output
Eric Laurent56ed8842022-11-15 16:04:41 +01006975 if (!invalidatedOutputs.empty()) {
jiabinc44b3462022-12-08 12:52:31 -08006976 invalidateStreams(mEngine->getStreamTypesForProductStrategy(psId));
Eric Laurent56ed8842022-11-15 16:04:41 +01006977 for (sp<SwAudioOutputDescriptor> desc : invalidatedOutputs) {
jiabin49256852022-03-09 11:21:35 -08006978 desc->setTracksInvalidatedStatusByStrategy(psId);
6979 }
Eric Laurente552edb2014-03-10 17:42:56 -07006980 }
6981 }
6982}
6983
Eric Laurente0720872014-03-11 09:30:41 -07006984void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07006985{
François Gaffiec005e562018-11-06 15:04:49 +01006986 for (const auto &strategy : mEngine->getOrderedProductStrategies()) {
6987 auto attributes = mEngine->getAllAttributesForProductStrategy(strategy).front();
6988 checkOutputForAttributes(attributes);
Francois Gaffieff1eb522020-05-06 18:37:04 +02006989 checkAudioSourceForAttributes(attributes);
François Gaffiec005e562018-11-06 15:04:49 +01006990 }
Eric Laurente552edb2014-03-10 17:42:56 -07006991}
6992
Kevin Rocard153f92d2018-12-18 18:33:28 -08006993void AudioPolicyManager::checkSecondaryOutputs() {
jiabinc44b3462022-12-08 12:52:31 -08006994 PortHandleVector clientsToInvalidate;
jiabin10a03f12021-05-07 23:46:28 +00006995 TrackSecondaryOutputsMap trackSecondaryOutputs;
Oscar Azucena873d10f2023-01-12 18:34:42 -08006996 bool unneededUsePrimaryOutputFromPolicyMixes = false;
Kevin Rocard153f92d2018-12-18 18:33:28 -08006997 for (size_t i = 0; i < mOutputs.size(); i++) {
6998 const sp<SwAudioOutputDescriptor>& outputDescriptor = mOutputs[i];
6999 for (const sp<TrackClientDescriptor>& client : outputDescriptor->getClientIterable()) {
Eric Laurentc529cf62020-04-17 18:19:10 -07007000 sp<AudioPolicyMix> primaryMix;
7001 std::vector<sp<AudioPolicyMix>> secondaryMixes;
Dean Wheatleyd082f472022-02-04 11:10:48 +11007002 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->config(),
Oscar Azucena873d10f2023-01-12 18:34:42 -08007003 client->uid(), client->session(), client->flags(), mAvailableOutputDevices,
7004 nullptr /* requestedDevice */, primaryMix, &secondaryMixes,
7005 unneededUsePrimaryOutputFromPolicyMixes);
Eric Laurentc529cf62020-04-17 18:19:10 -07007006 std::vector<sp<SwAudioOutputDescriptor>> secondaryDescs;
7007 for (auto &secondaryMix : secondaryMixes) {
7008 sp<SwAudioOutputDescriptor> outputDesc = secondaryMix->getOutput();
7009 if (outputDesc != nullptr &&
7010 outputDesc->mIoHandle != AUDIO_IO_HANDLE_NONE) {
7011 secondaryDescs.push_back(outputDesc);
7012 }
7013 }
7014
jiabinc44b3462022-12-08 12:52:31 -08007015 if (status != OK &&
7016 (client->flags() & AUDIO_OUTPUT_FLAG_MMAP_NOIRQ) == AUDIO_OUTPUT_FLAG_NONE) {
7017 // When it failed to query secondary output, only invalidate the client that is not
7018 // MMAP. The reason is that MMAP stream will not support secondary output.
7019 clientsToInvalidate.push_back(client->portId());
jiabin10a03f12021-05-07 23:46:28 +00007020 } else if (!std::equal(
7021 client->getSecondaryOutputs().begin(),
7022 client->getSecondaryOutputs().end(),
7023 secondaryDescs.begin(), secondaryDescs.end())) {
jiabina5281062021-11-23 00:10:23 +00007024 if (!audio_is_linear_pcm(client->config().format)) {
7025 // If the format is not PCM, the tracks should be invalidated to get correct
7026 // behavior when the secondary output is changed.
jiabinc44b3462022-12-08 12:52:31 -08007027 clientsToInvalidate.push_back(client->portId());
jiabina5281062021-11-23 00:10:23 +00007028 } else {
7029 std::vector<wp<SwAudioOutputDescriptor>> weakSecondaryDescs;
7030 std::vector<audio_io_handle_t> secondaryOutputIds;
7031 for (const auto &secondaryDesc: secondaryDescs) {
7032 secondaryOutputIds.push_back(secondaryDesc->mIoHandle);
7033 weakSecondaryDescs.push_back(secondaryDesc);
7034 }
7035 trackSecondaryOutputs.emplace(client->portId(), secondaryOutputIds);
7036 client->setSecondaryOutputs(std::move(weakSecondaryDescs));
jiabin10a03f12021-05-07 23:46:28 +00007037 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08007038 }
7039 }
7040 }
jiabin10a03f12021-05-07 23:46:28 +00007041 if (!trackSecondaryOutputs.empty()) {
7042 mpClientInterface->updateSecondaryOutputs(trackSecondaryOutputs);
7043 }
jiabinc44b3462022-12-08 12:52:31 -08007044 if (!clientsToInvalidate.empty()) {
7045 ALOGD("%s Invalidate clients due to fail getting output for attr", __func__);
7046 mpClientInterface->invalidateTracks(clientsToInvalidate);
Kevin Rocard153f92d2018-12-18 18:33:28 -08007047 }
7048}
7049
Eric Laurent2517af32020-11-25 15:31:27 +01007050bool AudioPolicyManager::isScoRequestedForComm() const {
7051 AudioDeviceTypeAddrVector devices;
7052 mEngine->getDevicesForRoleAndStrategy(mCommunnicationStrategy, DEVICE_ROLE_PREFERRED, devices);
7053 for (const auto &device : devices) {
7054 if (audio_is_bluetooth_out_sco_device(device.mType)) {
7055 return true;
7056 }
7057 }
7058 return false;
7059}
7060
Eric Laurent1a8b45f2022-04-13 16:01:47 +02007061bool AudioPolicyManager::isHearingAidUsedForComm() const {
7062 DeviceVector devices = mEngine->getOutputDevicesForStream(AUDIO_STREAM_VOICE_CALL,
7063 true /*fromCache*/);
7064 for (const auto &device : devices) {
7065 if (device->type() == AUDIO_DEVICE_OUT_HEARING_AID) {
7066 return true;
7067 }
7068 }
7069 return false;
7070}
7071
7072
Eric Laurente0720872014-03-11 09:30:41 -07007073void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07007074{
François Gaffie53615e22015-03-19 09:24:12 +01007075 audio_io_handle_t a2dpOutput = mOutputs.getA2dpOutput();
Aniket Kumar Lataa8ee9962018-01-31 20:24:23 -08007076 if (a2dpOutput == 0 || mOutputs.isA2dpOffloadedOnPrimary()) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07007077 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07007078 return;
7079 }
7080
Eric Laurent3a4311c2014-03-17 12:00:47 -07007081 bool isScoConnected =
jiabin9a3361e2019-10-01 09:38:30 -07007082 (mAvailableInputDevices.types().count(AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) != 0 ||
7083 !Intersection(mAvailableOutputDevices.types(), getAudioDeviceOutAllScoSet()).empty());
Eric Laurent2517af32020-11-25 15:31:27 +01007084 bool isScoRequested = isScoRequestedForComm();
Eric Laurentf732e072016-08-03 19:30:28 -07007085
7086 // if suspended, restore A2DP output if:
7087 // ((SCO device is NOT connected) ||
Eric Laurent2517af32020-11-25 15:31:27 +01007088 // ((SCO is not requested) &&
Eric Laurentf732e072016-08-03 19:30:28 -07007089 // (phone state is NOT in call) && (phone state is NOT ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07007090 //
Eric Laurentf732e072016-08-03 19:30:28 -07007091 // if not suspended, suspend A2DP output if:
7092 // (SCO device is connected) &&
Eric Laurent2517af32020-11-25 15:31:27 +01007093 // ((SCO is requested) ||
Eric Laurentf732e072016-08-03 19:30:28 -07007094 // ((phone state is in call) || (phone state is ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07007095 //
7096 if (mA2dpSuspended) {
Eric Laurentf732e072016-08-03 19:30:28 -07007097 if (!isScoConnected ||
Eric Laurent2517af32020-11-25 15:31:27 +01007098 (!isScoRequested &&
Eric Laurentf732e072016-08-03 19:30:28 -07007099 (mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) &&
François Gaffie2110e042015-03-24 08:41:51 +01007100 (mEngine->getPhoneState() != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07007101
7102 mpClientInterface->restoreOutput(a2dpOutput);
7103 mA2dpSuspended = false;
7104 }
7105 } else {
Eric Laurentf732e072016-08-03 19:30:28 -07007106 if (isScoConnected &&
Eric Laurent2517af32020-11-25 15:31:27 +01007107 (isScoRequested ||
Eric Laurentf732e072016-08-03 19:30:28 -07007108 (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) ||
François Gaffie2110e042015-03-24 08:41:51 +01007109 (mEngine->getPhoneState() == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07007110
7111 mpClientInterface->suspendOutput(a2dpOutput);
7112 mA2dpSuspended = true;
7113 }
7114 }
7115}
7116
François Gaffie11d30102018-11-02 16:09:09 +01007117DeviceVector AudioPolicyManager::getNewOutputDevices(const sp<SwAudioOutputDescriptor>& outputDesc,
7118 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07007119{
François Gaffiedb1755b2023-09-01 11:50:35 +02007120 if (outputDesc == nullptr) {
7121 return DeviceVector{};
7122 }
François Gaffie11d30102018-11-02 16:09:09 +01007123
Jean-Michel Triviff155c62016-02-26 12:07:16 -08007124 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007125 if (index >= 0) {
7126 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007127 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01007128 ALOGV("%s device %s forced by patch %d", __func__,
7129 outputDesc->devices().toString().c_str(), outputDesc->getPatchHandle());
7130 return outputDesc->devices();
Eric Laurent6a94d692014-05-20 11:18:06 -07007131 }
7132 }
7133
Dean Wheatley514b4312020-06-17 21:45:00 +10007134 // Do not retrieve engine device for outputs through MSD
7135 // TODO: support explicit routing requests by resetting MSD patch to engine device.
7136 if (outputDesc->devices() == getMsdAudioOutDevices()) {
7137 return outputDesc->devices();
7138 }
7139
Eric Laurent97ac8712018-07-27 18:59:02 -07007140 // Honor explicit routing requests only if no client using default routing is active on this
7141 // input: a specific app can not force routing for other apps by setting a preferred device.
7142 bool active; // unused
François Gaffie11d30102018-11-02 16:09:09 +01007143 sp<DeviceDescriptor> device =
François Gaffiec005e562018-11-06 15:04:49 +01007144 findPreferredDevice(outputDesc, PRODUCT_STRATEGY_NONE, active, mAvailableOutputDevices);
François Gaffie11d30102018-11-02 16:09:09 +01007145 if (device != nullptr) {
7146 return DeviceVector(device);
Eric Laurentf3a5a602018-05-22 18:42:55 -07007147 }
7148
François Gaffiea807ef92018-11-05 10:44:33 +01007149 // Legacy Engine cannot take care of bus devices and mix, so we need to handle the conflict
7150 // of setForceUse / Default Bus device here
7151 device = mPolicyMixes.getDeviceAndMixForOutput(outputDesc, mAvailableOutputDevices);
7152 if (device != nullptr) {
7153 return DeviceVector(device);
7154 }
7155
François Gaffiedb1755b2023-09-01 11:50:35 +02007156 DeviceVector devices;
François Gaffiec005e562018-11-06 15:04:49 +01007157 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
7158 StreamTypeVector streams = mEngine->getStreamTypesForProductStrategy(productStrategy);
7159 auto attr = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307160 auto hasStreamActive = [&](auto stream) {
7161 return hasStream(streams, stream) && isStreamActive(stream, 0);
7162 };
Eric Laurent484e9272018-06-07 17:29:23 -07007163
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307164 auto doGetOutputDevicesForVoice = [&]() {
7165 return hasVoiceStream(streams) && (outputDesc == mPrimaryOutput ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007166 outputDesc->isActive(toVolumeSource(AUDIO_STREAM_VOICE_CALL, false))) &&
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307167 (isInCall() ||
Henrik Backlund07c654a2021-10-14 15:57:10 +02007168 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc)) &&
7169 !isStreamActive(AUDIO_STREAM_ENFORCED_AUDIBLE, 0);
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307170 };
7171
7172 // With low-latency playing on speaker, music on WFD, when the first low-latency
7173 // output is stopped, getNewOutputDevices checks for a product strategy
7174 // from the list, as STRATEGY_SONIFICATION comes prior to STRATEGY_MEDIA.
Carter Hsucc58a6b2021-07-20 08:44:50 +00007175 // If an ALARM or ENFORCED_AUDIBLE stream is supported by the product strategy,
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307176 // devices are returned for STRATEGY_SONIFICATION without checking whether the
7177 // stream is associated to the output descriptor.
7178 if (doGetOutputDevicesForVoice() || outputDesc->isStrategyActive(productStrategy) ||
7179 ((hasStreamActive(AUDIO_STREAM_ALARM) ||
7180 hasStreamActive(AUDIO_STREAM_ENFORCED_AUDIBLE)) &&
7181 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc))) {
François Gaffiec005e562018-11-06 15:04:49 +01007182 // Retrieval of devices for voice DL is done on primary output profile, cannot
7183 // check the route (would force modifying configuration file for this profile)
7184 devices = mEngine->getOutputDevicesForAttributes(attr, nullptr, fromCache);
7185 break;
7186 }
Eric Laurente552edb2014-03-10 17:42:56 -07007187 }
François Gaffiec005e562018-11-06 15:04:49 +01007188 ALOGV("%s selected devices %s", __func__, devices.toString().c_str());
François Gaffie11d30102018-11-02 16:09:09 +01007189 return devices;
Eric Laurent1c333e22014-05-20 10:48:17 -07007190}
7191
François Gaffie11d30102018-11-02 16:09:09 +01007192sp<DeviceDescriptor> AudioPolicyManager::getNewInputDevice(
7193 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurent1c333e22014-05-20 10:48:17 -07007194{
François Gaffie11d30102018-11-02 16:09:09 +01007195 sp<DeviceDescriptor> device;
Eric Laurent6a94d692014-05-20 11:18:06 -07007196
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08007197 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007198 if (index >= 0) {
7199 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007200 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01007201 ALOGV("getNewInputDevice() device %s forced by patch %d",
7202 inputDesc->getDevice()->toString().c_str(), inputDesc->getPatchHandle());
7203 return inputDesc->getDevice();
Eric Laurent6a94d692014-05-20 11:18:06 -07007204 }
7205 }
7206
Eric Laurent97ac8712018-07-27 18:59:02 -07007207 // Honor explicit routing requests only if no client using default routing is active on this
7208 // input: a specific app can not force routing for other apps by setting a preferred device.
7209 bool active;
François Gaffie11d30102018-11-02 16:09:09 +01007210 device = findPreferredDevice(inputDesc, AUDIO_SOURCE_DEFAULT, active, mAvailableInputDevices);
7211 if (device != nullptr) {
7212 return device;
Eric Laurent97ac8712018-07-27 18:59:02 -07007213 }
7214
Eric Laurentdc95a252018-04-12 12:46:56 -07007215 // If we are not in call and no client is active on this input, this methods returns
Andy Hungf024a9e2019-01-30 16:01:02 -08007216 // a null sp<>, causing the patch on the input stream to be released.
yuanjiahsu0735bf32021-03-18 08:12:54 +08007217 audio_attributes_t attributes;
7218 uid_t uid;
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007219 audio_session_t session;
yuanjiahsu0735bf32021-03-18 08:12:54 +08007220 sp<RecordClientDescriptor> topClient = inputDesc->getHighestPriorityClient();
7221 if (topClient != nullptr) {
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01007222 attributes = topClient->attributes();
7223 uid = topClient->uid();
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007224 session = topClient->session();
yuanjiahsu0735bf32021-03-18 08:12:54 +08007225 } else {
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01007226 attributes = { .source = AUDIO_SOURCE_DEFAULT };
7227 uid = 0;
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007228 session = AUDIO_SESSION_NONE;
yuanjiahsu0735bf32021-03-18 08:12:54 +08007229 }
7230
Francois Gaffie716e1432019-01-14 16:58:59 +01007231 if (attributes.source == AUDIO_SOURCE_DEFAULT && isInCall()) {
7232 attributes.source = AUDIO_SOURCE_VOICE_COMMUNICATION;
Eric Laurentdc95a252018-04-12 12:46:56 -07007233 }
Francois Gaffie716e1432019-01-14 16:58:59 +01007234 if (attributes.source != AUDIO_SOURCE_DEFAULT) {
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007235 device = mEngine->getInputDeviceForAttributes(attributes, uid, session);
Eric Laurentfb66dd92016-01-28 18:32:03 -08007236 }
Eric Laurent1c333e22014-05-20 10:48:17 -07007237
Eric Laurente552edb2014-03-10 17:42:56 -07007238 return device;
7239}
7240
Eric Laurent794fde22016-03-11 09:50:45 -08007241bool AudioPolicyManager::streamsMatchForvolume(audio_stream_type_t stream1,
7242 audio_stream_type_t stream2) {
Jean-Michel Trivi99bb2f92016-11-23 15:52:07 -08007243 return (stream1 == stream2);
Eric Laurent28d09f02016-03-08 10:43:05 -08007244}
7245
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08007246status_t AudioPolicyManager::getDevicesForAttributes(
Andy Hung6d23c0f2022-02-16 09:37:15 -08007247 const audio_attributes_t &attr, AudioDeviceTypeAddrVector *devices, bool forVolume) {
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08007248 if (devices == nullptr) {
7249 return BAD_VALUE;
7250 }
Andy Hung6d23c0f2022-02-16 09:37:15 -08007251
Andy Hung6d23c0f2022-02-16 09:37:15 -08007252 DeviceVector curDevices;
jiabinf1c73972022-04-14 16:28:52 -07007253 if (status_t status = getDevicesForAttributes(attr, curDevices, forVolume); status != OK) {
7254 return status;
Andy Hung6d23c0f2022-02-16 09:37:15 -08007255 }
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08007256 for (const auto& device : curDevices) {
7257 devices->push_back(device->getDeviceTypeAddr());
7258 }
7259 return NO_ERROR;
7260}
7261
Eric Laurente0720872014-03-11 09:30:41 -07007262void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07007263 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07007264 case AUDIO_STREAM_MUSIC:
François Gaffiec005e562018-11-06 15:04:49 +01007265 checkOutputForAttributes(attributes_initializer(AUDIO_USAGE_NOTIFICATION));
Eric Laurente552edb2014-03-10 17:42:56 -07007266 updateDevicesAndOutputs();
7267 break;
7268 default:
7269 break;
7270 }
7271}
7272
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007273uint32_t AudioPolicyManager::handleEventForBeacon(int event) {
Eric Laurent9459fb02015-08-12 18:36:32 -07007274
7275 // skip beacon mute management if a dedicated TTS output is available
7276 if (mTtsOutputAvailable) {
7277 return 0;
7278 }
7279
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007280 switch(event) {
7281 case STARTING_OUTPUT:
7282 mBeaconMuteRefCount++;
7283 break;
7284 case STOPPING_OUTPUT:
7285 if (mBeaconMuteRefCount > 0) {
7286 mBeaconMuteRefCount--;
7287 }
7288 break;
7289 case STARTING_BEACON:
7290 mBeaconPlayingRefCount++;
7291 break;
7292 case STOPPING_BEACON:
7293 if (mBeaconPlayingRefCount > 0) {
7294 mBeaconPlayingRefCount--;
7295 }
7296 break;
7297 }
7298
7299 if (mBeaconMuteRefCount > 0) {
7300 // any playback causes beacon to be muted
7301 return setBeaconMute(true);
7302 } else {
7303 // no other playback: unmute when beacon starts playing, mute when it stops
7304 return setBeaconMute(mBeaconPlayingRefCount == 0);
7305 }
7306}
7307
7308uint32_t AudioPolicyManager::setBeaconMute(bool mute) {
7309 ALOGV("setBeaconMute(%d) mBeaconMuteRefCount=%d mBeaconPlayingRefCount=%d",
7310 mute, mBeaconMuteRefCount, mBeaconPlayingRefCount);
7311 // keep track of muted state to avoid repeating mute/unmute operations
7312 if (mBeaconMuted != mute) {
7313 // mute/unmute AUDIO_STREAM_TTS on all outputs
7314 ALOGV("\t muting %d", mute);
7315 uint32_t maxLatency = 0;
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007316 auto ttsVolumeSource = toVolumeSource(AUDIO_STREAM_TTS, false);
7317 if (ttsVolumeSource == VOLUME_SOURCE_NONE) {
7318 ALOGV("\t no tts volume source available");
7319 return 0;
7320 }
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007321 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07007322 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
jiabin9a3361e2019-10-01 09:38:30 -07007323 setVolumeSourceMute(ttsVolumeSource, mute/*on*/, desc, 0 /*delay*/, DeviceTypeSet());
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007324 const uint32_t latency = desc->latency() * 2;
Eric Laurentcdb2b352020-07-23 10:57:02 -07007325 if (desc->isActive(latency * 2) && latency > maxLatency) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007326 maxLatency = latency;
7327 }
7328 }
7329 mBeaconMuted = mute;
7330 return maxLatency;
7331 }
7332 return 0;
7333}
7334
Eric Laurente0720872014-03-11 09:30:41 -07007335void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07007336{
François Gaffiec005e562018-11-06 15:04:49 +01007337 mEngine->updateDeviceSelectionCache();
Eric Laurente552edb2014-03-10 17:42:56 -07007338 mPreviousOutputs = mOutputs;
7339}
7340
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07007341uint32_t AudioPolicyManager::checkDeviceMuteStrategies(const sp<AudioOutputDescriptor>& outputDesc,
François Gaffiec005e562018-11-06 15:04:49 +01007342 const DeviceVector &prevDevices,
Eric Laurente552edb2014-03-10 17:42:56 -07007343 uint32_t delayMs)
7344{
7345 // mute/unmute strategies using an incompatible device combination
7346 // if muting, wait for the audio in pcm buffer to be drained before proceeding
7347 // if unmuting, unmute only after the specified delay
7348 if (outputDesc->isDuplicated()) {
7349 return 0;
7350 }
7351
7352 uint32_t muteWaitMs = 0;
François Gaffiec005e562018-11-06 15:04:49 +01007353 DeviceVector devices = outputDesc->devices();
7354 bool shouldMute = outputDesc->isActive() && (devices.size() >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07007355
François Gaffiec005e562018-11-06 15:04:49 +01007356 auto productStrategies = mEngine->getOrderedProductStrategies();
7357 for (const auto &productStrategy : productStrategies) {
7358 auto attributes = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
7359 DeviceVector curDevices =
7360 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false/*fromCache*/);
7361 curDevices = curDevices.filter(outputDesc->supportedDevices());
7362 bool mute = shouldMute && curDevices.containsAtLeastOne(devices) && curDevices != devices;
Eric Laurente552edb2014-03-10 17:42:56 -07007363 bool doMute = false;
7364
François Gaffiec005e562018-11-06 15:04:49 +01007365 if (mute && !outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07007366 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01007367 outputDesc->setStrategyMutedByDevice(productStrategy, true);
7368 } else if (!mute && outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07007369 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01007370 outputDesc->setStrategyMutedByDevice(productStrategy, false);
Eric Laurente552edb2014-03-10 17:42:56 -07007371 }
Eric Laurent99401132014-05-07 19:48:15 -07007372 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07007373 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07007374 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07007375 // skip output if it does not share any device with current output
François Gaffie11d30102018-11-02 16:09:09 +01007376 if (!desc->supportedDevices().containsAtLeastOne(outputDesc->supportedDevices())) {
Eric Laurente552edb2014-03-10 17:42:56 -07007377 continue;
7378 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307379 ALOGVV("%s() output %s %s (curDevice %s)", __func__, desc->info().c_str(),
François Gaffiec005e562018-11-06 15:04:49 +01007380 mute ? "muting" : "unmuting", curDevices.toString().c_str());
7381 setStrategyMute(productStrategy, mute, desc, mute ? 0 : delayMs);
7382 if (desc->isStrategyActive(productStrategy)) {
Eric Laurent99401132014-05-07 19:48:15 -07007383 if (mute) {
7384 // FIXME: should not need to double latency if volume could be applied
7385 // immediately by the audioflinger mixer. We must account for the delay
7386 // between now and the next time the audioflinger thread for this output
7387 // will process a buffer (which corresponds to one buffer size,
7388 // usually 1/2 or 1/4 of the latency).
7389 if (muteWaitMs < desc->latency() * 2) {
7390 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07007391 }
7392 }
7393 }
7394 }
7395 }
7396 }
7397
Eric Laurent99401132014-05-07 19:48:15 -07007398 // temporary mute output if device selection changes to avoid volume bursts due to
7399 // different per device volumes
François Gaffiec005e562018-11-06 15:04:49 +01007400 if (outputDesc->isActive() && (devices != prevDevices)) {
Eric Laurentdc462862016-07-19 12:29:53 -07007401 uint32_t tempMuteWaitMs = outputDesc->latency() * 2;
Jasmine Chaf6074fe2021-08-17 13:44:31 +08007402
Eric Laurentdc462862016-07-19 12:29:53 -07007403 if (muteWaitMs < tempMuteWaitMs) {
7404 muteWaitMs = tempMuteWaitMs;
Eric Laurent99401132014-05-07 19:48:15 -07007405 }
Jasmine Chaf6074fe2021-08-17 13:44:31 +08007406
7407 // If recommended duration is defined, replace temporary mute duration to avoid
7408 // truncated notifications at beginning, which depends on duration of changing path in HAL.
7409 // Otherwise, temporary mute duration is conservatively set to 4 times the reported latency.
7410 uint32_t tempRecommendedMuteDuration = outputDesc->getRecommendedMuteDurationMs();
7411 uint32_t tempMuteDurationMs = tempRecommendedMuteDuration > 0 ?
7412 tempRecommendedMuteDuration : outputDesc->latency() * 4;
7413
François Gaffieaaac0fd2018-11-22 17:56:39 +01007414 for (const auto &activeVs : outputDesc->getActiveVolumeSources()) {
7415 // make sure that we do not start the temporary mute period too early in case of
7416 // delayed device change
7417 setVolumeSourceMute(activeVs, true, outputDesc, delayMs);
7418 setVolumeSourceMute(activeVs, false, outputDesc, delayMs + tempMuteDurationMs,
François Gaffiec005e562018-11-06 15:04:49 +01007419 devices.types());
Eric Laurent99401132014-05-07 19:48:15 -07007420 }
7421 }
7422
Eric Laurente552edb2014-03-10 17:42:56 -07007423 // wait for the PCM output buffers to empty before proceeding with the rest of the command
7424 if (muteWaitMs > delayMs) {
7425 muteWaitMs -= delayMs;
7426 usleep(muteWaitMs * 1000);
7427 return muteWaitMs;
7428 }
7429 return 0;
7430}
7431
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307432uint32_t AudioPolicyManager::setOutputDevices(const char *caller,
7433 const sp<SwAudioOutputDescriptor>& outputDesc,
François Gaffie11d30102018-11-02 16:09:09 +01007434 const DeviceVector &devices,
7435 bool force,
7436 int delayMs,
7437 audio_patch_handle_t *patchHandle,
Oscar Azucena6acf34b2023-04-27 16:32:09 -07007438 bool requiresMuteCheck, bool requiresVolumeCheck,
7439 bool skipMuteDelay)
Eric Laurente552edb2014-03-10 17:42:56 -07007440{
jiabin3ff8d7d2022-12-13 06:27:44 +00007441 // TODO(b/262404095): Consider if the output need to be reopened.
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307442 std::string logPrefix = std::string("caller ") + caller + outputDesc->info();
7443 ALOGV("%s %s device %s delayMs %d", __func__, logPrefix.c_str(),
7444 devices.toString().c_str(), delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07007445 uint32_t muteWaitMs;
7446
7447 if (outputDesc->isDuplicated()) {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307448 muteWaitMs = setOutputDevices(__func__, outputDesc->subOutput1(), devices, force, delayMs,
Oscar Azucena6acf34b2023-04-27 16:32:09 -07007449 nullptr /* patchHandle */, requiresMuteCheck, skipMuteDelay);
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307450 muteWaitMs += setOutputDevices(__func__, outputDesc->subOutput2(), devices, force, delayMs,
Oscar Azucena6acf34b2023-04-27 16:32:09 -07007451 nullptr /* patchHandle */, requiresMuteCheck, skipMuteDelay);
Eric Laurente552edb2014-03-10 17:42:56 -07007452 return muteWaitMs;
7453 }
Eric Laurente552edb2014-03-10 17:42:56 -07007454
7455 // filter devices according to output selected
Francois Gaffie716e1432019-01-14 16:58:59 +01007456 DeviceVector filteredDevices = outputDesc->filterSupportedDevices(devices);
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01007457 DeviceVector prevDevices = outputDesc->devices();
Francois Gaffie3523ab32021-06-22 13:24:34 +02007458 DeviceVector availPrevDevices = mAvailableOutputDevices.filter(prevDevices);
Eric Laurente552edb2014-03-10 17:42:56 -07007459
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307460 ALOGV("%s %s prevDevice %s", __func__, logPrefix.c_str(),
7461 prevDevices.toString().c_str());
François Gaffie11d30102018-11-02 16:09:09 +01007462
7463 if (!filteredDevices.isEmpty()) {
7464 outputDesc->setDevices(filteredDevices);
Eric Laurente552edb2014-03-10 17:42:56 -07007465 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00007466
7467 // if the outputs are not materially active, there is no need to mute.
7468 if (requiresMuteCheck) {
François Gaffiec005e562018-11-06 15:04:49 +01007469 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevices, delayMs);
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00007470 } else {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307471 ALOGV("%s: %s suppressing checkDeviceMuteStrategies", __func__,
7472 logPrefix.c_str());
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00007473 muteWaitMs = 0;
7474 }
Eric Laurente552edb2014-03-10 17:42:56 -07007475
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02007476 bool outputRouted = outputDesc->isRouted();
7477
Eric Laurent79ea9582020-06-11 18:49:24 -07007478 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
7479 // output profile or if new device is not supported AND previous device(s) is(are) still
7480 // available (otherwise reset device must be done on the output)
Francois Gaffie3523ab32021-06-22 13:24:34 +02007481 if (!devices.isEmpty() && filteredDevices.isEmpty() && !availPrevDevices.empty()) {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307482 ALOGV("%s: %s unsupported device %s for output", __func__, logPrefix.c_str(),
7483 devices.toString().c_str());
Eric Laurent79ea9582020-06-11 18:49:24 -07007484 // restore previous device after evaluating strategy mute state
7485 outputDesc->setDevices(prevDevices);
7486 return muteWaitMs;
7487 }
7488
Eric Laurente552edb2014-03-10 17:42:56 -07007489 // Do not change the routing if:
Eric Laurentb80a2a82014-10-27 16:07:59 -07007490 // the requested device is AUDIO_DEVICE_NONE
7491 // OR the requested device is the same as current device
7492 // AND force is not specified
7493 // AND the output is connected by a valid audio patch.
François Gaffie11d30102018-11-02 16:09:09 +01007494 // Doing this check here allows the caller to call setOutputDevices() without conditions
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02007495 if ((filteredDevices.isEmpty() || filteredDevices == prevDevices) && !force && outputRouted) {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307496 ALOGV("%s %s setting same device %s or null device, force=%d, patch handle=%d",
7497 __func__, logPrefix.c_str(), filteredDevices.toString().c_str(), force,
7498 outputDesc->getPatchHandle());
Francois Gaffie3523ab32021-06-22 13:24:34 +02007499 if (requiresVolumeCheck && !filteredDevices.isEmpty()) {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307500 ALOGV("%s %s setting same device on routed output, force apply volumes",
7501 __func__, logPrefix.c_str());
Francois Gaffie3523ab32021-06-22 13:24:34 +02007502 applyStreamVolumes(outputDesc, filteredDevices.types(), delayMs, true /*force*/);
7503 }
Eric Laurente552edb2014-03-10 17:42:56 -07007504 return muteWaitMs;
7505 }
7506
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307507 ALOGV("%s %s changing device to %s", __func__, logPrefix.c_str(),
7508 filteredDevices.toString().c_str());
Eric Laurent1c333e22014-05-20 10:48:17 -07007509
Eric Laurente552edb2014-03-10 17:42:56 -07007510 // do the routing
Francois Gaffie3523ab32021-06-22 13:24:34 +02007511 if (filteredDevices.isEmpty() || mAvailableOutputDevices.filter(filteredDevices).empty()) {
Eric Laurentc75307b2015-03-17 15:29:32 -07007512 resetOutputDevice(outputDesc, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07007513 } else {
François Gaffie11d30102018-11-02 16:09:09 +01007514 PatchBuilder patchBuilder;
7515 patchBuilder.addSource(outputDesc);
7516 ALOG_ASSERT(filteredDevices.size() <= AUDIO_PATCH_PORTS_MAX, "Too many sink ports");
7517 for (const auto &filteredDevice : filteredDevices) {
7518 patchBuilder.addSink(filteredDevice);
Eric Laurentc40d9692016-04-13 19:14:13 -07007519 }
7520
Jasmine Cha7f82d1a2020-03-16 13:21:47 +08007521 // Add half reported latency to delayMs when muteWaitMs is null in order
7522 // to avoid disordered sequence of muting volume and changing devices.
Oscar Azucena6acf34b2023-04-27 16:32:09 -07007523 int actualDelayMs = !skipMuteDelay && muteWaitMs == 0
7524 ? (delayMs + (outputDesc->latency() / 2)) : delayMs;
7525 installPatch(__func__, patchHandle, outputDesc.get(), patchBuilder.patch(), actualDelayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07007526 }
Eric Laurente552edb2014-03-10 17:42:56 -07007527
Oscar Azucena6acf34b2023-04-27 16:32:09 -07007528 // Since the mute is skip, also skip the apply stream volume as that will be applied externally
7529 if (!skipMuteDelay) {
7530 // update stream volumes according to new device
7531 applyStreamVolumes(outputDesc, filteredDevices.types(), delayMs);
7532 }
Eric Laurente552edb2014-03-10 17:42:56 -07007533
7534 return muteWaitMs;
7535}
7536
Eric Laurentc75307b2015-03-17 15:29:32 -07007537status_t AudioPolicyManager::resetOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurent6a94d692014-05-20 11:18:06 -07007538 int delayMs,
7539 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07007540{
Eric Laurent6a94d692014-05-20 11:18:06 -07007541 ssize_t index;
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02007542 if (patchHandle == nullptr && !outputDesc->isRouted()) {
7543 return INVALID_OPERATION;
7544 }
Eric Laurent6a94d692014-05-20 11:18:06 -07007545 if (patchHandle) {
7546 index = mAudioPatches.indexOfKey(*patchHandle);
7547 } else {
Jean-Michel Triviff155c62016-02-26 12:07:16 -08007548 index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007549 }
7550 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07007551 return INVALID_OPERATION;
7552 }
Eric Laurent6a94d692014-05-20 11:18:06 -07007553 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007554 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07007555 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07007556 outputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
François Gaffieafd4cea2019-11-18 15:50:22 +01007557 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007558 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07007559 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07007560 return status;
7561}
7562
7563status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
François Gaffie11d30102018-11-02 16:09:09 +01007564 const sp<DeviceDescriptor> &device,
Eric Laurent6a94d692014-05-20 11:18:06 -07007565 bool force,
7566 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07007567{
7568 status_t status = NO_ERROR;
7569
Eric Laurent1f2f2232014-06-02 12:01:23 -07007570 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
François Gaffie11d30102018-11-02 16:09:09 +01007571 if ((device != nullptr) && ((device != inputDesc->getDevice()) || force)) {
7572 inputDesc->setDevice(device);
Eric Laurent1c333e22014-05-20 10:48:17 -07007573
François Gaffie11d30102018-11-02 16:09:09 +01007574 if (mAvailableInputDevices.contains(device)) {
Mikhail Naganovdc769682018-05-04 15:34:08 -07007575 PatchBuilder patchBuilder;
7576 patchBuilder.addSink(inputDesc,
Eric Laurentdaf92cc2014-07-22 15:36:10 -07007577 // AUDIO_SOURCE_HOTWORD is for internal use only:
7578 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
Mikhail Naganovdc769682018-05-04 15:34:08 -07007579 [inputDesc](const PatchBuilder::mix_usecase_t& usecase) {
7580 auto result = usecase;
7581 if (result.source == AUDIO_SOURCE_HOTWORD && !inputDesc->isSoundTrigger()) {
7582 result.source = AUDIO_SOURCE_VOICE_RECOGNITION;
7583 }
7584 return result; }).
Eric Laurent1c333e22014-05-20 10:48:17 -07007585 //only one input device for now
François Gaffie11d30102018-11-02 16:09:09 +01007586 addSource(device);
Mikhail Naganovdc769682018-05-04 15:34:08 -07007587 status = installPatch(__func__, patchHandle, inputDesc.get(), patchBuilder.patch(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07007588 }
7589 }
7590 return status;
7591}
7592
Eric Laurent6a94d692014-05-20 11:18:06 -07007593status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
7594 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07007595{
Eric Laurent1f2f2232014-06-02 12:01:23 -07007596 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07007597 ssize_t index;
7598 if (patchHandle) {
7599 index = mAudioPatches.indexOfKey(*patchHandle);
7600 } else {
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08007601 index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007602 }
7603 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07007604 return INVALID_OPERATION;
7605 }
Eric Laurent6a94d692014-05-20 11:18:06 -07007606 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007607 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07007608 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07007609 inputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
François Gaffieafd4cea2019-11-18 15:50:22 +01007610 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007611 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07007612 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07007613 return status;
7614}
7615
François Gaffie11d30102018-11-02 16:09:09 +01007616sp<IOProfile> AudioPolicyManager::getInputProfile(const sp<DeviceDescriptor> &device,
François Gaffie53615e22015-03-19 09:24:12 +01007617 uint32_t& samplingRate,
Andy Hungf129b032015-04-07 13:45:50 -07007618 audio_format_t& format,
7619 audio_channel_mask_t& channelMask,
François Gaffie53615e22015-03-19 09:24:12 +01007620 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07007621{
7622 // Choose an input profile based on the requested capture parameters: select the first available
7623 // profile supporting all requested parameters.
jiabin2fd710d2022-05-02 23:20:22 +00007624 // The flags can be ignored if it doesn't contain a much match flag.
Andy Hungf129b032015-04-07 13:45:50 -07007625 //
7626 // TODO: perhaps isCompatibleProfile should return a "matching" score so we can return
7627 // the best matching profile, not the first one.
Eric Laurente552edb2014-03-10 17:42:56 -07007628
Atneya Nair0f0a8032022-12-12 16:20:12 -08007629 using underlying_input_flag_t = std::underlying_type_t<audio_input_flags_t>;
7630 const underlying_input_flag_t mustMatchFlag = AUDIO_INPUT_FLAG_MMAP_NOIRQ |
7631 AUDIO_INPUT_FLAG_HOTWORD_TAP | AUDIO_INPUT_FLAG_HW_LOOKBACK;
7632
7633 const underlying_input_flag_t oriFlags = flags;
Glenn Kasten730b9262018-03-29 15:01:26 -07007634
jiabin2fd710d2022-05-02 23:20:22 +00007635 for (;;) {
7636 sp<IOProfile> firstInexact = nullptr;
7637 uint32_t updatedSamplingRate = 0;
7638 audio_format_t updatedFormat = AUDIO_FORMAT_INVALID;
7639 audio_channel_mask_t updatedChannelMask = AUDIO_CHANNEL_INVALID;
7640 for (const auto& hwModule : mHwModules) {
7641 for (const auto& profile : hwModule->getInputProfiles()) {
7642 // profile->log();
7643 //updatedFormat = format;
7644 if (profile->isCompatibleProfile(DeviceVector(device), samplingRate,
7645 &samplingRate /*updatedSamplingRate*/,
7646 format,
7647 &format, /*updatedFormat*/
7648 channelMask,
7649 &channelMask /*updatedChannelMask*/,
7650 // FIXME ugly cast
7651 (audio_output_flags_t) flags,
7652 true /*exactMatchRequiredForInputFlags*/)) {
7653 return profile;
7654 }
7655 if (firstInexact == nullptr && profile->isCompatibleProfile(DeviceVector(device),
7656 samplingRate,
7657 &updatedSamplingRate,
7658 format,
7659 &updatedFormat,
7660 channelMask,
7661 &updatedChannelMask,
7662 // FIXME ugly cast
7663 (audio_output_flags_t) flags,
7664 false /*exactMatchRequiredForInputFlags*/)) {
7665 firstInexact = profile;
7666 }
7667 }
7668 }
7669
7670 if (firstInexact != nullptr) {
7671 samplingRate = updatedSamplingRate;
7672 format = updatedFormat;
7673 channelMask = updatedChannelMask;
7674 return firstInexact;
7675 } else if (flags & AUDIO_INPUT_FLAG_RAW) {
7676 flags = (audio_input_flags_t) (flags & ~AUDIO_INPUT_FLAG_RAW); // retry
7677 } else if ((flags & mustMatchFlag) == AUDIO_INPUT_FLAG_NONE &&
7678 flags != AUDIO_INPUT_FLAG_NONE && audio_is_linear_pcm(format)) {
7679 flags = AUDIO_INPUT_FLAG_NONE;
7680 } else { // fail
7681 ALOGW("%s could not find profile for device %s, sampling rate %u, format %#x, "
7682 "channel mask 0x%X, flags %#x", __func__, device->toString().c_str(),
7683 samplingRate, format, channelMask, oriFlags);
7684 break;
Eric Laurente552edb2014-03-10 17:42:56 -07007685 }
7686 }
jiabin2fd710d2022-05-02 23:20:22 +00007687
7688 return nullptr;
Eric Laurente552edb2014-03-10 17:42:56 -07007689}
7690
François Gaffieaaac0fd2018-11-22 17:56:39 +01007691float AudioPolicyManager::computeVolume(IVolumeCurves &curves,
7692 VolumeSource volumeSource,
François Gaffied1ab2bd2015-12-02 18:20:06 +01007693 int index,
jiabin9a3361e2019-10-01 09:38:30 -07007694 const DeviceTypeSet& deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07007695{
jiabin9a3361e2019-10-01 09:38:30 -07007696 float volumeDb = curves.volIndexToDb(Volume::getDeviceCategory(deviceTypes), index);
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07007697
7698 // handle the case of accessibility active while a ringtone is playing: if the ringtone is much
7699 // louder than the accessibility prompt, the prompt cannot be heard, thus masking the touch
7700 // exploration of the dialer UI. In this situation, bring the accessibility volume closer to
7701 // the ringtone volume
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007702 const auto callVolumeSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL, false);
7703 const auto ringVolumeSrc = toVolumeSource(AUDIO_STREAM_RING, false);
7704 const auto musicVolumeSrc = toVolumeSource(AUDIO_STREAM_MUSIC, false);
7705 const auto alarmVolumeSrc = toVolumeSource(AUDIO_STREAM_ALARM, false);
7706 const auto a11yVolumeSrc = toVolumeSource(AUDIO_STREAM_ACCESSIBILITY, false);
Oscar Azucena437ded52023-08-30 18:45:18 -07007707 // Verify that the current volume source is not the ringer volume to prevent recursively
7708 // calling to compute volume. This could happen in cases where a11y and ringer sounds belong
7709 // to the same volume group.
7710 if (volumeSource != ringVolumeSrc && volumeSource == a11yVolumeSrc
François Gaffieaaac0fd2018-11-22 17:56:39 +01007711 && (AUDIO_MODE_RINGTONE == mEngine->getPhoneState()) &&
7712 mOutputs.isActive(ringVolumeSrc, 0)) {
7713 auto &ringCurves = getVolumeCurves(AUDIO_STREAM_RING);
jiabin9a3361e2019-10-01 09:38:30 -07007714 const float ringVolumeDb = computeVolume(ringCurves, ringVolumeSrc, index, deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007715 return ringVolumeDb - 4 > volumeDb ? ringVolumeDb - 4 : volumeDb;
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07007716 }
7717
Eric Laurentdcd4ab12018-06-29 17:45:13 -07007718 // in-call: always cap volume by voice volume + some low headroom
François Gaffieaaac0fd2018-11-22 17:56:39 +01007719 if ((volumeSource != callVolumeSrc && (isInCall() ||
7720 mOutputs.isActiveLocally(callVolumeSrc))) &&
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007721 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM, false) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01007722 volumeSource == ringVolumeSrc || volumeSource == musicVolumeSrc ||
7723 volumeSource == alarmVolumeSrc ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007724 volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION, false) ||
7725 volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false) ||
7726 volumeSource == toVolumeSource(AUDIO_STREAM_DTMF, false) ||
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07007727 volumeSource == a11yVolumeSrc)) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007728 auto &voiceCurves = getVolumeCurves(callVolumeSrc);
jiabin9a3361e2019-10-01 09:38:30 -07007729 int voiceVolumeIndex = voiceCurves.getVolumeIndex(deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007730 const float maxVoiceVolDb =
jiabin9a3361e2019-10-01 09:38:30 -07007731 computeVolume(voiceCurves, callVolumeSrc, voiceVolumeIndex, deviceTypes)
Eric Laurent7731b5a2018-04-06 15:47:22 -07007732 + IN_CALL_EARPIECE_HEADROOM_DB;
Abhijith Shastry329ddab2019-04-23 11:53:26 -07007733 // FIXME: Workaround for call screening applications until a proper audio mode is defined
7734 // to support this scenario : Exempt the RING stream from the audio cap if the audio was
7735 // programmatically muted.
7736 // VOICE_CALL stream has minVolumeIndex > 0 : Users cannot set the volume of voice calls to
7737 // 0. We don't want to cap volume when the system has programmatically muted the voice call
7738 // stream. See setVolumeCurveIndex() for more information.
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07007739 bool exemptFromCapping =
7740 ((volumeSource == ringVolumeSrc) || (volumeSource == a11yVolumeSrc))
7741 && (voiceVolumeIndex == 0);
Abhijith Shastry329ddab2019-04-23 11:53:26 -07007742 ALOGV_IF(exemptFromCapping, "%s volume source %d at vol=%f not capped", __func__,
7743 volumeSource, volumeDb);
7744 if ((volumeDb > maxVoiceVolDb) && !exemptFromCapping) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007745 ALOGV("%s volume source %d at vol=%f overriden by volume group %d at vol=%f", __func__,
7746 volumeSource, volumeDb, callVolumeSrc, maxVoiceVolDb);
7747 volumeDb = maxVoiceVolDb;
Jean-Michel Trivi719a9872017-08-05 13:51:35 -07007748 }
7749 }
Eric Laurente552edb2014-03-10 17:42:56 -07007750 // if a headset is connected, apply the following rules to ring tones and notifications
7751 // to avoid sound level bursts in user's ears:
Eric Laurent6af1c1d2016-04-14 11:20:44 -07007752 // - always attenuate notifications volume by 6dB
7753 // - attenuate ring tones volume by 6dB unless music is not playing and
7754 // speaker is part of the select devices
Eric Laurente552edb2014-03-10 17:42:56 -07007755 // - if music is playing, always limit the volume to current music volume,
7756 // with a minimum threshold at -36dB so that notification is always perceived.
jiabin9a3361e2019-10-01 09:38:30 -07007757 if (!Intersection(deviceTypes,
7758 {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP, AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES,
7759 AUDIO_DEVICE_OUT_WIRED_HEADSET, AUDIO_DEVICE_OUT_WIRED_HEADPHONE,
Eric Laurentc42df452020-08-07 10:51:53 -07007760 AUDIO_DEVICE_OUT_USB_HEADSET, AUDIO_DEVICE_OUT_HEARING_AID,
7761 AUDIO_DEVICE_OUT_BLE_HEADSET}).empty() &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01007762 ((volumeSource == alarmVolumeSrc ||
7763 volumeSource == ringVolumeSrc) ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007764 (volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION, false)) ||
7765 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM, false)) ||
7766 ((volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false)) &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01007767 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) &&
7768 curves.canBeMuted()) {
7769
Eric Laurente552edb2014-03-10 17:42:56 -07007770 // when the phone is ringing we must consider that music could have been paused just before
7771 // by the music application and behave as if music was active if the last music track was
7772 // just stopped
Oscar Azucena437ded52023-08-30 18:45:18 -07007773 // Verify that the current volume source is not the music volume to prevent recursively
7774 // calling to compute volume. This could happen in cases where music and
7775 // (alarm, ring, notification, system, etc.) sounds belong to the same volume group.
7776 if (volumeSource != musicVolumeSrc &&
7777 (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY)
7778 || mLimitRingtoneVolume)) {
François Gaffie43c73442018-11-08 08:21:55 +01007779 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
jiabin9a3361e2019-10-01 09:38:30 -07007780 DeviceTypeSet musicDevice =
François Gaffiec005e562018-11-06 15:04:49 +01007781 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
7782 nullptr, true /*fromCache*/).types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01007783 auto &musicCurves = getVolumeCurves(AUDIO_STREAM_MUSIC);
jiabin9a3361e2019-10-01 09:38:30 -07007784 float musicVolDb = computeVolume(musicCurves,
7785 musicVolumeSrc,
7786 musicCurves.getVolumeIndex(musicDevice),
7787 musicDevice);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007788 float minVolDb = (musicVolDb > SONIFICATION_HEADSET_VOLUME_MIN_DB) ?
7789 musicVolDb : SONIFICATION_HEADSET_VOLUME_MIN_DB;
7790 if (volumeDb > minVolDb) {
7791 volumeDb = minVolDb;
7792 ALOGV("computeVolume limiting volume to %f musicVol %f", minVolDb, musicVolDb);
Eric Laurente552edb2014-03-10 17:42:56 -07007793 }
Eric Laurent7b6385c2021-05-12 17:55:36 +02007794 if (Volume::getDeviceForVolume(deviceTypes) != AUDIO_DEVICE_OUT_SPEAKER
7795 && !Intersection(deviceTypes, {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP,
7796 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES}).empty()) {
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07007797 // on A2DP, also ensure notification volume is not too low compared to media when
7798 // intended to be played
François Gaffie43c73442018-11-08 08:21:55 +01007799 if ((volumeDb > -96.0f) &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01007800 (musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB > volumeDb)) {
jiabin9a3361e2019-10-01 09:38:30 -07007801 ALOGV("%s increasing volume for volume source=%d device=%s from %f to %f",
7802 __func__, volumeSource, dumpDeviceTypes(deviceTypes).c_str(), volumeDb,
François Gaffieaaac0fd2018-11-22 17:56:39 +01007803 musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB);
7804 volumeDb = musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB;
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07007805 }
7806 }
jiabin9a3361e2019-10-01 09:38:30 -07007807 } else if ((Volume::getDeviceForVolume(deviceTypes) != AUDIO_DEVICE_OUT_SPEAKER) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01007808 (!(volumeSource == alarmVolumeSrc || volumeSource == ringVolumeSrc))) {
François Gaffie43c73442018-11-08 08:21:55 +01007809 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07007810 }
7811 }
7812
François Gaffie43c73442018-11-08 08:21:55 +01007813 return volumeDb;
Eric Laurente552edb2014-03-10 17:42:56 -07007814}
7815
Eric Laurent3839bc02018-07-10 18:33:34 -07007816int AudioPolicyManager::rescaleVolumeIndex(int srcIndex,
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01007817 VolumeSource fromVolumeSource,
7818 VolumeSource toVolumeSource)
Eric Laurent3839bc02018-07-10 18:33:34 -07007819{
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01007820 if (fromVolumeSource == toVolumeSource) {
Eric Laurent3839bc02018-07-10 18:33:34 -07007821 return srcIndex;
7822 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01007823 auto &srcCurves = getVolumeCurves(fromVolumeSource);
7824 auto &dstCurves = getVolumeCurves(toVolumeSource);
Eric Laurentf5aa58d2019-02-22 18:20:11 -08007825 float minSrc = (float)srcCurves.getVolumeIndexMin();
7826 float maxSrc = (float)srcCurves.getVolumeIndexMax();
7827 float minDst = (float)dstCurves.getVolumeIndexMin();
7828 float maxDst = (float)dstCurves.getVolumeIndexMax();
Eric Laurent3839bc02018-07-10 18:33:34 -07007829
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08007830 // preserve mute request or correct range
7831 if (srcIndex < minSrc) {
7832 if (srcIndex == 0) {
7833 return 0;
7834 }
7835 srcIndex = minSrc;
7836 } else if (srcIndex > maxSrc) {
7837 srcIndex = maxSrc;
7838 }
Eric Laurent3839bc02018-07-10 18:33:34 -07007839 return (int)(minDst + ((srcIndex - minSrc) * (maxDst - minDst)) / (maxSrc - minSrc));
7840}
7841
François Gaffieaaac0fd2018-11-22 17:56:39 +01007842status_t AudioPolicyManager::checkAndSetVolume(IVolumeCurves &curves,
7843 VolumeSource volumeSource,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08007844 int index,
7845 const sp<AudioOutputDescriptor>& outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07007846 DeviceTypeSet deviceTypes,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08007847 int delayMs,
7848 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07007849{
François Gaffieaaac0fd2018-11-22 17:56:39 +01007850 // do not change actual attributes volume if the attributes is muted
7851 if (outputDesc->isMuted(volumeSource)) {
7852 ALOGVV("%s: volume source %d muted count %d active=%d", __func__, volumeSource,
7853 outputDesc->getMuteCount(volumeSource), outputDesc->isActive(volumeSource));
Eric Laurente552edb2014-03-10 17:42:56 -07007854 return NO_ERROR;
7855 }
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007856 VolumeSource callVolSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL, false);
7857 VolumeSource btScoVolSrc = toVolumeSource(AUDIO_STREAM_BLUETOOTH_SCO, false);
7858 bool isVoiceVolSrc = (volumeSource != VOLUME_SOURCE_NONE) && (callVolSrc == volumeSource);
7859 bool isBtScoVolSrc = (volumeSource != VOLUME_SOURCE_NONE) && (btScoVolSrc == volumeSource);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007860
Eric Laurent2517af32020-11-25 15:31:27 +01007861 bool isScoRequested = isScoRequestedForComm();
Eric Laurent1a8b45f2022-04-13 16:01:47 +02007862 bool isHAUsed = isHearingAidUsedForComm();
7863
Eric Laurente552edb2014-03-10 17:42:56 -07007864 // do not change in call volume if bluetooth is connected and vice versa
François Gaffieaaac0fd2018-11-22 17:56:39 +01007865 // if sco and call follow same curves, bypass forceUseForComm
7866 if ((callVolSrc != btScoVolSrc) &&
Eric Laurent2517af32020-11-25 15:31:27 +01007867 ((isVoiceVolSrc && isScoRequested) ||
Beibeif660a512023-02-28 17:00:34 +08007868 (isBtScoVolSrc && !(isScoRequested || isHAUsed))) &&
7869 !isSingleDeviceType(deviceTypes, AUDIO_DEVICE_OUT_TELEPHONY_TX)) {
Eric Laurent2517af32020-11-25 15:31:27 +01007870 ALOGV("%s cannot set volume group %d volume when is%srequested for comm", __func__,
Eric Laurent1a8b45f2022-04-13 16:01:47 +02007871 volumeSource, isScoRequested ? " " : " not ");
Eric Laurent571ef962020-07-24 11:43:48 -07007872 // Do not return an error here as AudioService will always set both voice call
7873 // and bluetooth SCO volumes due to stream aliasing.
7874 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07007875 }
jiabin9a3361e2019-10-01 09:38:30 -07007876 if (deviceTypes.empty()) {
7877 deviceTypes = outputDesc->devices().types();
chenxin2080986da2023-07-17 11:45:21 +08007878 index = curves.getVolumeIndex(deviceTypes);
7879 ALOGD("%s if deviceTypes is change from none to device %s, need get index %d",
7880 __func__, dumpDeviceTypes(deviceTypes).c_str(), index);
Eric Laurentc75307b2015-03-17 15:29:32 -07007881 }
Eric Laurent275e8e92014-11-30 15:14:47 -08007882
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00007883 if (curves.getVolumeIndexMin() < 0 || curves.getVolumeIndexMax() < 0) {
7884 ALOGE("invalid volume index range");
7885 return BAD_VALUE;
7886 }
7887
jiabin9a3361e2019-10-01 09:38:30 -07007888 float volumeDb = computeVolume(curves, volumeSource, index, deviceTypes);
7889 if (outputDesc->isFixedVolume(deviceTypes) ||
Eric Laurent9698a4c2020-10-12 17:10:23 -07007890 // Force VoIP volume to max for bluetooth SCO device except if muted
7891 (index != 0 && (isVoiceVolSrc || isBtScoVolSrc) &&
jiabin9a3361e2019-10-01 09:38:30 -07007892 isSingleDeviceType(deviceTypes, audio_is_bluetooth_out_sco_device))) {
Eric Laurentffbc80f2015-03-18 18:30:19 -07007893 volumeDb = 0.0f;
Eric Laurent275e8e92014-11-30 15:14:47 -08007894 }
Francois Gaffie593634d2021-06-22 13:31:31 +02007895 const bool muted = (index == 0) && (volumeDb != 0.0f);
Eric Laurent31a428a2023-08-11 12:16:28 +02007896 outputDesc->setVolume(volumeDb, muted, volumeSource, curves.getStreamTypes(),
7897 deviceTypes, delayMs, force, isVoiceVolSrc);
Eric Laurentc75307b2015-03-17 15:29:32 -07007898
Eric Laurente8f2c0f2021-08-17 11:17:19 +02007899 if (outputDesc == mPrimaryOutput && (isVoiceVolSrc || isBtScoVolSrc)) {
Eric Laurente552edb2014-03-10 17:42:56 -07007900 float voiceVolume;
Eric Laurentfad001d2019-06-11 19:17:57 -07007901 // 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 +01007902 if (isVoiceVolSrc) {
7903 voiceVolume = (float)index/(float)curves.getVolumeIndexMax();
Eric Laurente552edb2014-03-10 17:42:56 -07007904 } else {
Eric Laurentfad001d2019-06-11 19:17:57 -07007905 voiceVolume = index == 0 ? 0.0 : 1.0;
Eric Laurente552edb2014-03-10 17:42:56 -07007906 }
Eric Laurent18fba842016-03-31 14:41:26 -07007907 if (voiceVolume != mLastVoiceVolume) {
Eric Laurente552edb2014-03-10 17:42:56 -07007908 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
7909 mLastVoiceVolume = voiceVolume;
7910 }
7911 }
Eric Laurente552edb2014-03-10 17:42:56 -07007912 return NO_ERROR;
7913}
7914
Eric Laurentc75307b2015-03-17 15:29:32 -07007915void AudioPolicyManager::applyStreamVolumes(const sp<AudioOutputDescriptor>& outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07007916 const DeviceTypeSet& deviceTypes,
7917 int delayMs,
7918 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07007919{
jiabincd510522020-01-22 09:40:55 -08007920 ALOGVV("applyStreamVolumes() for device %s", dumpDeviceTypes(deviceTypes).c_str());
François Gaffieaaac0fd2018-11-22 17:56:39 +01007921 for (const auto &volumeGroup : mEngine->getVolumeGroups()) {
7922 auto &curves = getVolumeCurves(toVolumeSource(volumeGroup));
7923 checkAndSetVolume(curves, toVolumeSource(volumeGroup),
jiabin9a3361e2019-10-01 09:38:30 -07007924 curves.getVolumeIndex(deviceTypes),
7925 outputDesc, deviceTypes, delayMs, force);
Eric Laurente552edb2014-03-10 17:42:56 -07007926 }
7927}
7928
François Gaffiec005e562018-11-06 15:04:49 +01007929void AudioPolicyManager::setStrategyMute(product_strategy_t strategy,
7930 bool on,
7931 const sp<AudioOutputDescriptor>& outputDesc,
7932 int delayMs,
jiabin9a3361e2019-10-01 09:38:30 -07007933 DeviceTypeSet deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07007934{
François Gaffieaaac0fd2018-11-22 17:56:39 +01007935 std::vector<VolumeSource> sourcesToMute;
7936 for (auto attributes: mEngine->getAllAttributesForProductStrategy(strategy)) {
7937 ALOGVV("%s() attributes %s, mute %d, output ID %d", __func__,
7938 toString(attributes).c_str(), on, outputDesc->getId());
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007939 VolumeSource source = toVolumeSource(attributes, false);
7940 if ((source != VOLUME_SOURCE_NONE) &&
7941 (std::find(begin(sourcesToMute), end(sourcesToMute), source)
7942 == end(sourcesToMute))) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007943 sourcesToMute.push_back(source);
7944 }
Eric Laurente552edb2014-03-10 17:42:56 -07007945 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01007946 for (auto source : sourcesToMute) {
jiabin9a3361e2019-10-01 09:38:30 -07007947 setVolumeSourceMute(source, on, outputDesc, delayMs, deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007948 }
7949
Eric Laurente552edb2014-03-10 17:42:56 -07007950}
7951
François Gaffieaaac0fd2018-11-22 17:56:39 +01007952void AudioPolicyManager::setVolumeSourceMute(VolumeSource volumeSource,
7953 bool on,
7954 const sp<AudioOutputDescriptor>& outputDesc,
7955 int delayMs,
jiabin9a3361e2019-10-01 09:38:30 -07007956 DeviceTypeSet deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07007957{
jiabin9a3361e2019-10-01 09:38:30 -07007958 if (deviceTypes.empty()) {
7959 deviceTypes = outputDesc->devices().types();
Eric Laurente552edb2014-03-10 17:42:56 -07007960 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01007961 auto &curves = getVolumeCurves(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07007962 if (on) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007963 if (!outputDesc->isMuted(volumeSource)) {
Eric Laurentf5aa58d2019-02-22 18:20:11 -08007964 if (curves.canBeMuted() &&
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007965 (volumeSource != toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01007966 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) ==
7967 AUDIO_POLICY_FORCE_NONE))) {
jiabin9a3361e2019-10-01 09:38:30 -07007968 checkAndSetVolume(curves, volumeSource, 0, outputDesc, deviceTypes, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07007969 }
7970 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01007971 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not
7972 // ignored
7973 outputDesc->incMuteCount(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07007974 } else {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007975 if (!outputDesc->isMuted(volumeSource)) {
7976 ALOGV("%s unmuting non muted attributes!", __func__);
Eric Laurente552edb2014-03-10 17:42:56 -07007977 return;
7978 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01007979 if (outputDesc->decMuteCount(volumeSource) == 0) {
7980 checkAndSetVolume(curves, volumeSource,
jiabin9a3361e2019-10-01 09:38:30 -07007981 curves.getVolumeIndex(deviceTypes),
Eric Laurentc75307b2015-03-17 15:29:32 -07007982 outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07007983 deviceTypes,
Eric Laurente552edb2014-03-10 17:42:56 -07007984 delayMs);
7985 }
7986 }
7987}
7988
François Gaffie53615e22015-03-19 09:24:12 +01007989bool AudioPolicyManager::isValidAttributes(const audio_attributes_t *paa)
7990{
François Gaffiec005e562018-11-06 15:04:49 +01007991 // has flags that map to a stream type?
Eric Laurente83b55d2014-11-14 10:06:21 -08007992 if ((paa->flags & (AUDIO_FLAG_AUDIBILITY_ENFORCED | AUDIO_FLAG_SCO | AUDIO_FLAG_BEACON)) != 0) {
7993 return true;
7994 }
7995
7996 // has known usage?
7997 switch (paa->usage) {
7998 case AUDIO_USAGE_UNKNOWN:
7999 case AUDIO_USAGE_MEDIA:
8000 case AUDIO_USAGE_VOICE_COMMUNICATION:
8001 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
8002 case AUDIO_USAGE_ALARM:
8003 case AUDIO_USAGE_NOTIFICATION:
8004 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
8005 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
8006 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
8007 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
8008 case AUDIO_USAGE_NOTIFICATION_EVENT:
8009 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
8010 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
8011 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
8012 case AUDIO_USAGE_GAME:
Eric Laurent275e8e92014-11-30 15:14:47 -08008013 case AUDIO_USAGE_VIRTUAL_SOURCE:
Jean-Michel Trivi36867762016-12-29 12:03:28 -08008014 case AUDIO_USAGE_ASSISTANT:
Eric Laurent21777f82019-12-06 18:12:06 -08008015 case AUDIO_USAGE_CALL_ASSISTANT:
Hayden Gomes524159d2019-12-23 14:41:47 -08008016 case AUDIO_USAGE_EMERGENCY:
8017 case AUDIO_USAGE_SAFETY:
8018 case AUDIO_USAGE_VEHICLE_STATUS:
8019 case AUDIO_USAGE_ANNOUNCEMENT:
Eric Laurente83b55d2014-11-14 10:06:21 -08008020 break;
8021 default:
8022 return false;
8023 }
8024 return true;
8025}
8026
François Gaffie2110e042015-03-24 08:41:51 +01008027audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
8028{
8029 return mEngine->getForceUse(usage);
8030}
8031
Eric Laurent96d1dda2022-03-14 17:14:19 +01008032bool AudioPolicyManager::isInCall() const {
François Gaffie2110e042015-03-24 08:41:51 +01008033 return isStateInCall(mEngine->getPhoneState());
8034}
8035
Eric Laurent96d1dda2022-03-14 17:14:19 +01008036bool AudioPolicyManager::isStateInCall(int state) const {
François Gaffie2110e042015-03-24 08:41:51 +01008037 return is_state_in_call(state);
8038}
8039
Eric Laurentf9cccec2022-11-16 19:12:00 +01008040bool AudioPolicyManager::isCallAudioAccessible() const {
Eric Laurent74b71512019-11-06 17:21:57 -08008041 audio_mode_t mode = mEngine->getPhoneState();
8042 return (mode == AUDIO_MODE_IN_CALL)
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01008043 || (mode == AUDIO_MODE_CALL_SCREEN)
8044 || (mode == AUDIO_MODE_CALL_REDIRECT);
Eric Laurent74b71512019-11-06 17:21:57 -08008045}
8046
Eric Laurentf9cccec2022-11-16 19:12:00 +01008047bool AudioPolicyManager::isInCallOrScreening() const {
8048 audio_mode_t mode = mEngine->getPhoneState();
8049 return isStateInCall(mode) || mode == AUDIO_MODE_CALL_SCREEN;
8050}
8051
Eric Laurentd60560a2015-04-10 11:31:20 -07008052void AudioPolicyManager::cleanUpForDevice(const sp<DeviceDescriptor>& deviceDesc)
8053{
8054 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07008055 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008056 if (sourceDesc->isConnected() && (sourceDesc->srcDevice()->equals(deviceDesc) ||
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02008057 sourceDesc->sinkDevice()->equals(deviceDesc))
8058 && !isCallRxAudioSource(sourceDesc)) {
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008059 disconnectAudioSource(sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07008060 }
8061 }
8062
8063 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
8064 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
8065 bool release = false;
8066 for (size_t j = 0; j < patchDesc->mPatch.num_sources && !release; j++) {
8067 const struct audio_port_config *source = &patchDesc->mPatch.sources[j];
8068 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
8069 source->ext.device.type == deviceDesc->type()) {
8070 release = true;
8071 }
8072 }
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008073 const char *address = deviceDesc->address().c_str();
Eric Laurentd60560a2015-04-10 11:31:20 -07008074 for (size_t j = 0; j < patchDesc->mPatch.num_sinks && !release; j++) {
8075 const struct audio_port_config *sink = &patchDesc->mPatch.sinks[j];
8076 if (sink->type == AUDIO_PORT_TYPE_DEVICE &&
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008077 sink->ext.device.type == deviceDesc->type() &&
8078 (strnlen(address, AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0
8079 || strncmp(sink->ext.device.address, address,
8080 AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0)) {
Eric Laurentd60560a2015-04-10 11:31:20 -07008081 release = true;
8082 }
8083 }
8084 if (release) {
François Gaffieafd4cea2019-11-18 15:50:22 +01008085 ALOGV("%s releasing patch %u", __FUNCTION__, patchDesc->getHandle());
8086 releaseAudioPatch(patchDesc->getHandle(), patchDesc->getUid());
Eric Laurentd60560a2015-04-10 11:31:20 -07008087 }
8088 }
Francois Gaffie716e1432019-01-14 16:58:59 +01008089
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01008090 mInputs.clearSessionRoutesForDevice(deviceDesc);
8091
Francois Gaffie716e1432019-01-14 16:58:59 +01008092 mHwModules.cleanUpForDevice(deviceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07008093}
8094
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008095void AudioPolicyManager::modifySurroundFormats(
8096 const sp<DeviceDescriptor>& devDesc, FormatVector *formatsPtr) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008097 std::unordered_set<audio_format_t> enforcedSurround(
8098 devDesc->encodedFormats().begin(), devDesc->encodedFormats().end());
Mikhail Naganov100f0122018-11-29 11:22:16 -08008099 std::unordered_set<audio_format_t> allSurround; // A flat set of all known surround formats
Mikhail Naganov68e3f642023-04-28 13:06:32 -07008100 for (const auto& pair : mConfig->getSurroundFormats()) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008101 allSurround.insert(pair.first);
8102 for (const auto& subformat : pair.second) allSurround.insert(subformat);
8103 }
Phil Burk09bc4612016-02-24 15:58:15 -08008104
8105 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
8106 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Phil Burk0709b0a2016-03-31 12:54:57 -07008107 ALOGD("%s: forced use = %d", __FUNCTION__, forceUse);
Mikhail Naganov100f0122018-11-29 11:22:16 -08008108 // This is the resulting set of formats depending on the surround mode:
8109 // 'all surround' = allSurround
8110 // 'enforced surround' = enforcedSurround [may include IEC69137 which isn't raw surround fmt]
8111 // 'non-surround' = not in 'all surround' and not in 'enforced surround'
8112 // 'manual surround' = mManualSurroundFormats
8113 // AUTO: formats v 'enforced surround'
8114 // ALWAYS: formats v 'all surround' v 'enforced surround'
8115 // NEVER: formats ^ 'non-surround'
8116 // MANUAL: formats ^ ('non-surround' v 'manual surround' v (IEC69137 ^ 'enforced surround'))
Phil Burk09bc4612016-02-24 15:58:15 -08008117
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008118 std::unordered_set<audio_format_t> formatSet;
8119 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL
8120 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008121 // formatSet is (formats ^ 'non-surround')
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008122 for (auto formatIter = formatsPtr->begin(); formatIter != formatsPtr->end(); ++formatIter) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008123 if (allSurround.count(*formatIter) == 0 && enforcedSurround.count(*formatIter) == 0) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008124 formatSet.insert(*formatIter);
8125 }
8126 }
8127 } else {
8128 formatSet.insert(formatsPtr->begin(), formatsPtr->end());
8129 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08008130 formatsPtr->clear(); // Re-filled from the formatSet at the end.
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008131
jiabin81772902018-04-02 17:52:27 -07008132 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008133 formatSet.insert(mManualSurroundFormats.begin(), mManualSurroundFormats.end());
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008134 // Enable IEC61937 when in MANUAL mode if it's enforced for this device.
8135 if (enforcedSurround.count(AUDIO_FORMAT_IEC61937) != 0) {
8136 formatSet.insert(AUDIO_FORMAT_IEC61937);
Phil Burk09bc4612016-02-24 15:58:15 -08008137 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08008138 } else if (forceUse != AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) { // AUTO or ALWAYS
8139 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS) {
8140 formatSet.insert(allSurround.begin(), allSurround.end());
Phil Burk07ac1142016-03-25 13:39:29 -07008141 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08008142 formatSet.insert(enforcedSurround.begin(), enforcedSurround.end());
Phil Burk09bc4612016-02-24 15:58:15 -08008143 }
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008144 for (const auto& format : formatSet) {
jiabin06e4bab2019-07-29 10:13:34 -07008145 formatsPtr->push_back(format);
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008146 }
Phil Burk0709b0a2016-03-31 12:54:57 -07008147}
8148
jiabin06e4bab2019-07-29 10:13:34 -07008149void AudioPolicyManager::modifySurroundChannelMasks(ChannelMaskSet *channelMasksPtr) {
8150 ChannelMaskSet &channelMasks = *channelMasksPtr;
Phil Burk0709b0a2016-03-31 12:54:57 -07008151 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
8152 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
8153
8154 // If NEVER, then remove support for channelMasks > stereo.
8155 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
jiabin06e4bab2019-07-29 10:13:34 -07008156 for (auto it = channelMasks.begin(); it != channelMasks.end();) {
8157 audio_channel_mask_t channelMask = *it;
Phil Burk0709b0a2016-03-31 12:54:57 -07008158 if (channelMask & ~AUDIO_CHANNEL_OUT_STEREO) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01008159 ALOGV("%s: force NEVER, so remove channelMask 0x%08x", __FUNCTION__, channelMask);
jiabin06e4bab2019-07-29 10:13:34 -07008160 it = channelMasks.erase(it);
Phil Burk0709b0a2016-03-31 12:54:57 -07008161 } else {
jiabin06e4bab2019-07-29 10:13:34 -07008162 ++it;
Phil Burk0709b0a2016-03-31 12:54:57 -07008163 }
8164 }
jiabin81772902018-04-02 17:52:27 -07008165 // If ALWAYS or MANUAL, then make sure we at least support 5.1
8166 } else if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS
8167 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Phil Burk0709b0a2016-03-31 12:54:57 -07008168 bool supports5dot1 = false;
8169 // Are there any channel masks that can be considered "surround"?
Mikhail Naganovcf84e592017-12-07 11:25:11 -08008170 for (audio_channel_mask_t channelMask : channelMasks) {
Phil Burk0709b0a2016-03-31 12:54:57 -07008171 if ((channelMask & AUDIO_CHANNEL_OUT_5POINT1) == AUDIO_CHANNEL_OUT_5POINT1) {
8172 supports5dot1 = true;
8173 break;
8174 }
8175 }
8176 // If not then add 5.1 support.
8177 if (!supports5dot1) {
jiabin06e4bab2019-07-29 10:13:34 -07008178 channelMasks.insert(AUDIO_CHANNEL_OUT_5POINT1);
Eric Laurentfecbceb2021-02-09 14:46:43 +01008179 ALOGV("%s: force MANUAL or ALWAYS, so adding channelMask for 5.1 surround", __func__);
Phil Burk0709b0a2016-03-31 12:54:57 -07008180 }
Phil Burk09bc4612016-02-24 15:58:15 -08008181 }
8182}
8183
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008184void AudioPolicyManager::updateAudioProfiles(const sp<DeviceDescriptor>& devDesc,
Phil Burk00eeb322016-03-31 12:41:00 -07008185 audio_io_handle_t ioHandle,
jiabin12537fc2023-10-12 17:56:08 +00008186 const sp<IOProfile>& profile) {
8187 if (!profile->hasDynamicAudioProfile()) {
8188 return;
François Gaffie112b0af2015-11-19 16:13:25 +01008189 }
François Gaffie112b0af2015-11-19 16:13:25 +01008190
jiabin12537fc2023-10-12 17:56:08 +00008191 audio_port_v7 devicePort;
8192 devDesc->toAudioPort(&devicePort);
François Gaffie112b0af2015-11-19 16:13:25 +01008193
jiabin12537fc2023-10-12 17:56:08 +00008194 audio_port_v7 mixPort;
8195 profile->toAudioPort(&mixPort);
8196 mixPort.ext.mix.handle = ioHandle;
8197
8198 status_t status = mpClientInterface->getAudioMixPort(&devicePort, &mixPort);
8199 if (status != NO_ERROR) {
8200 ALOGE("%s failed to query the attributes of the mix port", __func__);
8201 return;
François Gaffie112b0af2015-11-19 16:13:25 +01008202 }
jiabin12537fc2023-10-12 17:56:08 +00008203
8204 std::set<audio_format_t> supportedFormats;
8205 for (size_t i = 0; i < mixPort.num_audio_profiles; ++i) {
8206 supportedFormats.insert(mixPort.audio_profiles[i].format);
8207 }
8208 FormatVector formats(supportedFormats.begin(), supportedFormats.end());
8209 mReportedFormatsMap[devDesc] = formats;
8210
8211 if (devDesc->type() == AUDIO_DEVICE_OUT_HDMI ||
8212 isDeviceOfModule(devDesc,AUDIO_HARDWARE_MODULE_ID_MSD)) {
8213 modifySurroundFormats(devDesc, &formats);
8214 size_t modifiedNumProfiles = 0;
8215 for (size_t i = 0; i < mixPort.num_audio_profiles; ++i) {
8216 if (std::find(formats.begin(), formats.end(), mixPort.audio_profiles[i].format) ==
8217 formats.end()) {
8218 // Skip the format that is not present after modifying surround formats.
8219 continue;
8220 }
8221 memcpy(&mixPort.audio_profiles[modifiedNumProfiles], &mixPort.audio_profiles[i],
8222 sizeof(struct audio_profile));
8223 ChannelMaskSet channels(mixPort.audio_profiles[modifiedNumProfiles].channel_masks,
8224 mixPort.audio_profiles[modifiedNumProfiles].channel_masks +
8225 mixPort.audio_profiles[modifiedNumProfiles].num_channel_masks);
8226 modifySurroundChannelMasks(&channels);
8227 std::copy(channels.begin(), channels.end(),
8228 std::begin(mixPort.audio_profiles[modifiedNumProfiles].channel_masks));
8229 mixPort.audio_profiles[modifiedNumProfiles++].num_channel_masks = channels.size();
8230 }
8231 mixPort.num_audio_profiles = modifiedNumProfiles;
8232 }
8233 profile->importAudioPort(mixPort);
François Gaffie112b0af2015-11-19 16:13:25 +01008234}
Eric Laurentd60560a2015-04-10 11:31:20 -07008235
Mikhail Naganovdc769682018-05-04 15:34:08 -07008236status_t AudioPolicyManager::installPatch(const char *caller,
8237 audio_patch_handle_t *patchHandle,
8238 AudioIODescriptorInterface *ioDescriptor,
8239 const struct audio_patch *patch,
8240 int delayMs)
8241{
8242 ssize_t index = mAudioPatches.indexOfKey(
8243 patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE ?
8244 *patchHandle : ioDescriptor->getPatchHandle());
8245 sp<AudioPatch> patchDesc;
8246 status_t status = installPatch(
8247 caller, index, patchHandle, patch, delayMs, mUidCached, &patchDesc);
8248 if (status == NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01008249 ioDescriptor->setPatchHandle(patchDesc->getHandle());
Mikhail Naganovdc769682018-05-04 15:34:08 -07008250 }
8251 return status;
8252}
8253
8254status_t AudioPolicyManager::installPatch(const char *caller,
8255 ssize_t index,
8256 audio_patch_handle_t *patchHandle,
8257 const struct audio_patch *patch,
8258 int delayMs,
8259 uid_t uid,
8260 sp<AudioPatch> *patchDescPtr)
8261{
8262 sp<AudioPatch> patchDesc;
8263 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
8264 if (index >= 0) {
8265 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01008266 afPatchHandle = patchDesc->getAfHandle();
Mikhail Naganovdc769682018-05-04 15:34:08 -07008267 }
8268
8269 status_t status = mpClientInterface->createAudioPatch(patch, &afPatchHandle, delayMs);
8270 ALOGV("%s() AF::createAudioPatch returned %d patchHandle %d num_sources %d num_sinks %d",
8271 caller, status, afPatchHandle, patch->num_sources, patch->num_sinks);
8272 if (status == NO_ERROR) {
8273 if (index < 0) {
8274 patchDesc = new AudioPatch(patch, uid);
François Gaffieafd4cea2019-11-18 15:50:22 +01008275 addAudioPatch(patchDesc->getHandle(), patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07008276 } else {
8277 patchDesc->mPatch = *patch;
8278 }
François Gaffieafd4cea2019-11-18 15:50:22 +01008279 patchDesc->setAfHandle(afPatchHandle);
Mikhail Naganovdc769682018-05-04 15:34:08 -07008280 if (patchHandle) {
François Gaffieafd4cea2019-11-18 15:50:22 +01008281 *patchHandle = patchDesc->getHandle();
Mikhail Naganovdc769682018-05-04 15:34:08 -07008282 }
8283 nextAudioPortGeneration();
8284 mpClientInterface->onAudioPatchListUpdate();
8285 }
8286 if (patchDescPtr) *patchDescPtr = patchDesc;
8287 return status;
8288}
8289
jiabinbce0c1d2020-10-05 11:20:18 -07008290bool AudioPolicyManager::areAllActiveTracksRerouted(const sp<SwAudioOutputDescriptor>& output)
8291{
8292 const TrackClientVector activeClients = output->getActiveClients();
8293 if (activeClients.empty()) {
8294 return true;
8295 }
8296 ssize_t index = mAudioPatches.indexOfKey(output->getPatchHandle());
8297 if (index < 0) {
8298 ALOGE("%s, no audio patch found while there are active clients on output %d",
8299 __func__, output->getId());
8300 return false;
8301 }
8302 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
8303 DeviceVector routedDevices;
8304 for (int i = 0; i < patchDesc->mPatch.num_sinks; ++i) {
8305 sp<DeviceDescriptor> device = mAvailableOutputDevices.getDeviceFromId(
8306 patchDesc->mPatch.sinks[i].id);
8307 if (device == nullptr) {
8308 ALOGE("%s, no audio device found with id(%d)",
8309 __func__, patchDesc->mPatch.sinks[i].id);
8310 return false;
8311 }
8312 routedDevices.add(device);
8313 }
8314 for (const auto& client : activeClients) {
jiabin49256852022-03-09 11:21:35 -08008315 if (client->isInvalid()) {
8316 // No need to take care about invalidated clients.
8317 continue;
8318 }
jiabinbce0c1d2020-10-05 11:20:18 -07008319 sp<DeviceDescriptor> preferredDevice =
8320 mAvailableOutputDevices.getDeviceFromId(client->preferredDeviceId());
8321 if (mEngine->getOutputDevicesForAttributes(
8322 client->attributes(), preferredDevice, false) == routedDevices) {
8323 return false;
8324 }
8325 }
8326 return true;
8327}
8328
8329sp<SwAudioOutputDescriptor> AudioPolicyManager::openOutputWithProfileAndDevice(
Eric Laurentb4f42a92022-01-17 17:37:31 +01008330 const sp<IOProfile>& profile, const DeviceVector& devices,
jiabina84c3d32022-12-02 18:59:55 +00008331 const audio_config_base_t *mixerConfig, const audio_config_t *halConfig,
8332 audio_output_flags_t flags)
jiabinbce0c1d2020-10-05 11:20:18 -07008333{
8334 for (const auto& device : devices) {
8335 // TODO: This should be checking if the profile supports the device combo.
8336 if (!profile->supportsDevice(device)) {
jiabina84c3d32022-12-02 18:59:55 +00008337 ALOGE("%s profile(%s) doesn't support device %#x", __func__, profile->getName().c_str(),
8338 device->type());
jiabinbce0c1d2020-10-05 11:20:18 -07008339 return nullptr;
8340 }
8341 }
8342 sp<SwAudioOutputDescriptor> desc = new SwAudioOutputDescriptor(profile, mpClientInterface);
8343 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
jiabina84c3d32022-12-02 18:59:55 +00008344 status_t status = desc->open(halConfig, mixerConfig, devices,
8345 AUDIO_STREAM_DEFAULT, flags, &output);
jiabinbce0c1d2020-10-05 11:20:18 -07008346 if (status != NO_ERROR) {
jiabina84c3d32022-12-02 18:59:55 +00008347 ALOGE("%s failed to open output %d", __func__, status);
jiabinbce0c1d2020-10-05 11:20:18 -07008348 return nullptr;
8349 }
8350
8351 // Here is where the out_set_parameters() for card & device gets called
8352 sp<DeviceDescriptor> device = devices.getDeviceForOpening();
8353 const audio_devices_t deviceType = device->type();
8354 const String8 &address = String8(device->address().c_str());
Tomasz Wasilczykfd9ffd12023-08-14 17:56:22 +00008355 if (!address.empty()) {
jiabinbce0c1d2020-10-05 11:20:18 -07008356 char *param = audio_device_address_to_parameter(deviceType, address.c_str());
8357 mpClientInterface->setParameters(output, String8(param));
8358 free(param);
8359 }
jiabin12537fc2023-10-12 17:56:08 +00008360 updateAudioProfiles(device, output, profile);
jiabinbce0c1d2020-10-05 11:20:18 -07008361 if (!profile->hasValidAudioProfile()) {
8362 ALOGW("%s() missing param", __func__);
8363 desc->close();
8364 return nullptr;
jiabina84c3d32022-12-02 18:59:55 +00008365 } else if (profile->hasDynamicAudioProfile() && halConfig == nullptr) {
8366 // Reopen the output with the best audio profile picked by APM when the profile supports
8367 // dynamic audio profile and the hal config is not specified.
jiabinbce0c1d2020-10-05 11:20:18 -07008368 desc->close();
8369 output = AUDIO_IO_HANDLE_NONE;
8370 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
8371 profile->pickAudioProfile(
8372 config.sample_rate, config.channel_mask, config.format);
8373 config.offload_info.sample_rate = config.sample_rate;
8374 config.offload_info.channel_mask = config.channel_mask;
8375 config.offload_info.format = config.format;
8376
jiabina84c3d32022-12-02 18:59:55 +00008377 status = desc->open(&config, mixerConfig, devices, AUDIO_STREAM_DEFAULT, flags, &output);
jiabinbce0c1d2020-10-05 11:20:18 -07008378 if (status != NO_ERROR) {
8379 return nullptr;
8380 }
8381 }
8382
8383 addOutput(output, desc);
Eric Laurentb4f42a92022-01-17 17:37:31 +01008384
baek.kim -61c20122022-07-27 10:05:32 +00008385 sp<DeviceDescriptor> speaker = mAvailableOutputDevices.getDevice(
8386 AUDIO_DEVICE_OUT_SPEAKER, String8(""), AUDIO_FORMAT_DEFAULT);
8387
jiabinbce0c1d2020-10-05 11:20:18 -07008388 if (audio_is_remote_submix_device(deviceType) && address != "0") {
8389 sp<AudioPolicyMix> policyMix;
8390 if (mPolicyMixes.getAudioPolicyMix(deviceType, address, policyMix) == NO_ERROR) {
8391 policyMix->setOutput(desc);
8392 desc->mPolicyMix = policyMix;
8393 } else {
8394 ALOGW("checkOutputsForDevice() cannot find policy for address %s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00008395 address.c_str());
jiabinbce0c1d2020-10-05 11:20:18 -07008396 }
8397
baek.kim -61c20122022-07-27 10:05:32 +00008398 } else if (hasPrimaryOutput() && speaker != nullptr
8399 && mPrimaryOutput->supportsDevice(speaker) && !desc->supportsDevice(speaker)
Eric Laurentb4f42a92022-01-17 17:37:31 +01008400 && ((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0)) {
8401 // no duplicated output for:
8402 // - direct outputs
8403 // - outputs used by dynamic policy mixes
baek.kim -61c20122022-07-27 10:05:32 +00008404 // - outputs that supports SPEAKER while the primary output does not.
jiabinbce0c1d2020-10-05 11:20:18 -07008405 audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE;
8406
8407 //TODO: configure audio effect output stage here
8408
8409 // open a duplicating output thread for the new output and the primary output
8410 sp<SwAudioOutputDescriptor> dupOutputDesc =
8411 new SwAudioOutputDescriptor(nullptr, mpClientInterface);
8412 status = dupOutputDesc->openDuplicating(mPrimaryOutput, desc, &duplicatedOutput);
8413 if (status == NO_ERROR) {
8414 // add duplicated output descriptor
8415 addOutput(duplicatedOutput, dupOutputDesc);
8416 } else {
8417 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
8418 mPrimaryOutput->mIoHandle, output);
8419 desc->close();
8420 removeOutput(output);
8421 nextAudioPortGeneration();
8422 return nullptr;
8423 }
8424 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02008425 if (mPrimaryOutput == nullptr && profile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
8426 ALOGV("%s(): re-assigning mPrimaryOutput", __func__);
8427 mPrimaryOutput = desc;
François Gaffiedb1755b2023-09-01 11:50:35 +02008428 mPrimaryModuleHandle = mPrimaryOutput->getModuleHandle();
Francois Gaffiebce7cd42020-10-14 16:13:20 +02008429 }
jiabinbce0c1d2020-10-05 11:20:18 -07008430 return desc;
8431}
8432
jiabinf1c73972022-04-14 16:28:52 -07008433status_t AudioPolicyManager::getDevicesForAttributes(
8434 const audio_attributes_t &attr, DeviceVector &devices, bool forVolume) {
8435 // Devices are determined in the following precedence:
8436 //
8437 // 1) Devices associated with a dynamic policy matching the attributes. This is often
8438 // a remote submix from MIX_ROUTE_FLAG_LOOP_BACK.
8439 //
8440 // If no such dynamic policy then
8441 // 2) Devices containing an active client using setPreferredDevice
8442 // with same strategy as the attributes.
8443 // (from the default Engine::getOutputDevicesForAttributes() implementation).
8444 //
8445 // If no corresponding active client with setPreferredDevice then
8446 // 3) Devices associated with the strategy determined by the attributes
8447 // (from the default Engine::getOutputDevicesForAttributes() implementation).
8448 //
8449 // See related getOutputForAttrInt().
8450
8451 // check dynamic policies but only for primary descriptors (secondary not used for audible
8452 // audio routing, only used for duplication for playback capture)
8453 sp<AudioPolicyMix> policyMix;
Oscar Azucena873d10f2023-01-12 18:34:42 -08008454 bool unneededUsePrimaryOutputFromPolicyMixes = false;
jiabinf1c73972022-04-14 16:28:52 -07008455 status_t status = mPolicyMixes.getOutputForAttr(attr, AUDIO_CONFIG_BASE_INITIALIZER,
Oscar Azucena873d10f2023-01-12 18:34:42 -08008456 0 /*uid unknown here*/, AUDIO_SESSION_NONE, AUDIO_OUTPUT_FLAG_NONE,
8457 mAvailableOutputDevices, nullptr /* requestedDevice */, policyMix,
8458 nullptr /* secondaryMixes */, unneededUsePrimaryOutputFromPolicyMixes);
jiabinf1c73972022-04-14 16:28:52 -07008459 if (status != OK) {
8460 return status;
8461 }
8462
8463 if (policyMix != nullptr && policyMix->getOutput() != nullptr &&
8464 // For volume control, skip LOOPBACK mixes which use AUDIO_DEVICE_OUT_REMOTE_SUBMIX
8465 // as they are unaffected by device/stream volume
8466 // (per SwAudioOutputDescriptor::isFixedVolume()).
8467 (!forVolume || policyMix->mDeviceType != AUDIO_DEVICE_OUT_REMOTE_SUBMIX)
8468 ) {
8469 sp<DeviceDescriptor> deviceDesc = mAvailableOutputDevices.getDevice(
8470 policyMix->mDeviceType, policyMix->mDeviceAddress, AUDIO_FORMAT_DEFAULT);
8471 devices.add(deviceDesc);
8472 } else {
8473 // The default Engine::getOutputDevicesForAttributes() uses findPreferredDevice()
8474 // which selects setPreferredDevice if active. This means forVolume call
8475 // will take an active setPreferredDevice, if such exists.
8476
8477 devices = mEngine->getOutputDevicesForAttributes(
8478 attr, nullptr /* preferredDevice */, false /* fromCache */);
8479 }
8480
8481 if (forVolume) {
8482 // We alias the device AUDIO_DEVICE_OUT_SPEAKER_SAFE to AUDIO_DEVICE_OUT_SPEAKER
8483 // for single volume control in AudioService (such relationship should exist if
8484 // SPEAKER_SAFE is present).
8485 //
8486 // (This is unrelated to a different device grouping as Volume::getDeviceCategory)
8487 DeviceVector speakerSafeDevices =
8488 devices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER_SAFE);
8489 if (!speakerSafeDevices.isEmpty()) {
8490 devices.merge(mAvailableOutputDevices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER));
8491 devices.remove(speakerSafeDevices);
8492 }
8493 }
8494
8495 return NO_ERROR;
8496}
8497
8498status_t AudioPolicyManager::getProfilesForDevices(const DeviceVector& devices,
8499 AudioProfileVector& audioProfiles,
8500 uint32_t flags,
8501 bool isInput) {
8502 for (const auto& hwModule : mHwModules) {
8503 // the MSD module checks for different conditions
8504 if (strcmp(hwModule->getName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0) {
8505 continue;
8506 }
8507 IOProfileCollection ioProfiles = isInput ? hwModule->getInputProfiles()
8508 : hwModule->getOutputProfiles();
8509 for (const auto& profile : ioProfiles) {
8510 if (!profile->areAllDevicesSupported(devices) ||
8511 !profile->isCompatibleProfileForFlags(
8512 flags, false /*exactMatchRequiredForInputFlags*/)) {
8513 continue;
8514 }
8515 audioProfiles.addAllValidProfiles(profile->asAudioPort()->getAudioProfiles());
8516 }
8517 }
8518
8519 if (!isInput) {
8520 // add the direct profiles from MSD if present and has audio patches to all the output(s)
8521 const auto &msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
8522 if (msdModule != nullptr) {
8523 if (msdHasPatchesToAllDevices(devices.toTypeAddrVector())) {
8524 ALOGV("%s: MSD audio patches set to all output devices.", __func__);
8525 for (const auto &profile: msdModule->getOutputProfiles()) {
8526 if (!profile->asAudioPort()->isDirectOutput()) {
8527 continue;
8528 }
8529 audioProfiles.addAllValidProfiles(profile->asAudioPort()->getAudioProfiles());
8530 }
8531 } else {
8532 ALOGV("%s: MSD audio patches NOT set to all output devices.", __func__);
8533 }
8534 }
8535 }
8536
8537 return NO_ERROR;
8538}
8539
jiabin3ff8d7d2022-12-13 06:27:44 +00008540sp<SwAudioOutputDescriptor> AudioPolicyManager::reopenOutput(sp<SwAudioOutputDescriptor> outputDesc,
8541 const audio_config_t *config,
8542 audio_output_flags_t flags,
8543 const char* caller) {
jiabina84c3d32022-12-02 18:59:55 +00008544 closeOutput(outputDesc->mIoHandle);
8545 sp<SwAudioOutputDescriptor> preferredOutput = openOutputWithProfileAndDevice(
8546 outputDesc->mProfile, outputDesc->devices(), nullptr /*mixerConfig*/, config, flags);
8547 if (preferredOutput == nullptr) {
8548 ALOGE("%s failed to reopen output device=%d, caller=%s",
8549 __func__, outputDesc->devices()[0]->getId(), caller);
jiabina84c3d32022-12-02 18:59:55 +00008550 }
jiabin3ff8d7d2022-12-13 06:27:44 +00008551 return preferredOutput;
8552}
8553
8554void AudioPolicyManager::reopenOutputsWithDevices(
8555 const std::map<audio_io_handle_t, DeviceVector> &outputsToReopen) {
8556 for (const auto& [output, devices] : outputsToReopen) {
8557 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
8558 closeOutput(output);
8559 openOutputWithProfileAndDevice(desc->mProfile, devices);
8560 }
jiabina84c3d32022-12-02 18:59:55 +00008561}
8562
jiabinc44b3462022-12-08 12:52:31 -08008563PortHandleVector AudioPolicyManager::getClientsForStream(
8564 audio_stream_type_t streamType) const {
8565 PortHandleVector clients;
8566 for (size_t i = 0; i < mOutputs.size(); ++i) {
8567 PortHandleVector clientsForStream = mOutputs.valueAt(i)->getClientsForStream(streamType);
8568 clients.insert(clients.end(), clientsForStream.begin(), clientsForStream.end());
8569 }
8570 return clients;
8571}
8572
8573void AudioPolicyManager::invalidateStreams(StreamTypeVector streams) const {
8574 PortHandleVector clients;
8575 for (auto stream : streams) {
8576 PortHandleVector clientsForStream = getClientsForStream(stream);
8577 clients.insert(clients.end(), clientsForStream.begin(), clientsForStream.end());
8578 }
8579 mpClientInterface->invalidateTracks(clients);
8580}
8581
Mikhail Naganov1b2a7942017-12-08 10:18:09 -08008582} // namespace android