blob: ac15b49bc322301320b2a26b9528d44738cfbdb5 [file] [log] [blame]
Eric Laurente552edb2014-03-10 17:42:56 -07001/*
2 * Copyright (C) 2009 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Jan Sebechlebsky0af8e872023-08-11 14:45:08 +020017#include "utils/Errors.h"
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -070018#define LOG_TAG "APM_AudioPolicyManager"
Tomoharu Kasahara71c90912018-10-31 09:10:12 +090019
20// Need to keep the log statements even in production builds
21// to enable VERBOSE logging dynamically.
22// You can enable VERBOSE logging as follows:
23// adb shell setprop log.tag.APM_AudioPolicyManager V
24#define LOG_NDEBUG 0
Eric Laurente552edb2014-03-10 17:42:56 -070025
26//#define VERY_VERBOSE_LOGGING
27#ifdef VERY_VERBOSE_LOGGING
28#define ALOGVV ALOGV
29#else
30#define ALOGVV(a...) do { } while(0)
31#endif
32
Eric Laurent16c66dd2019-05-01 17:54:10 -070033#include <algorithm>
Eric Laurentd4692962014-05-05 18:13:44 -070034#include <inttypes.h>
jiabin10a03f12021-05-07 23:46:28 +000035#include <map>
Eric Laurente552edb2014-03-10 17:42:56 -070036#include <math.h>
Kevin Rocard153f92d2018-12-18 18:33:28 -080037#include <set>
Atneya Nair0f0a8032022-12-12 16:20:12 -080038#include <type_traits>
Mikhail Naganovd5e18052018-11-30 14:55:45 -080039#include <unordered_set>
Mikhail Naganov15be9d22017-11-08 14:18:13 +110040#include <vector>
Mikhail Naganov946c0032020-10-21 13:04:58 -070041
42#include <Serializer.h>
Nathalie Le Clair88fa2752021-11-23 13:03:41 +010043#include <android/media/audio/common/AudioPort.h>
Glenn Kasten76a13442020-07-01 12:10:59 -070044#include <cutils/bitops.h>
Eric Laurente552edb2014-03-10 17:42:56 -070045#include <cutils/properties.h>
Eric Laurent3b73df72014-03-11 09:06:29 -070046#include <media/AudioParameter.h>
Mikhail Naganov946c0032020-10-21 13:04:58 -070047#include <policy.h>
Andy Hung4ef19fa2018-05-15 19:35:29 -070048#include <private/android_filesystem_config.h>
Mikhail Naganovcbc8f612016-10-11 18:05:13 -070049#include <system/audio.h>
Mikhail Naganov27cf37c2020-04-14 14:47:01 -070050#include <system/audio_config.h>
jiabinebb6af42020-06-09 17:31:17 -070051#include <system/audio_effects/effect_hapticgenerator.h>
Mikhail Naganov946c0032020-10-21 13:04:58 -070052#include <utils/Log.h>
53
Eric Laurentd4692962014-05-05 18:13:44 -070054#include "AudioPolicyManager.h"
François Gaffiea8ecc2c2015-11-09 16:10:40 +010055#include "TypeConverter.h"
Eric Laurente552edb2014-03-10 17:42:56 -070056
Eric Laurent3b73df72014-03-11 09:06:29 -070057namespace android {
Eric Laurente552edb2014-03-10 17:42:56 -070058
Nathalie Le Clair88fa2752021-11-23 13:03:41 +010059using android::media::audio::common::AudioDevice;
60using android::media::audio::common::AudioDeviceAddress;
61using android::media::audio::common::AudioPortDeviceExt;
62using android::media::audio::common::AudioPortExt;
Svet Ganov3e5f14f2021-05-13 22:51:08 +000063using content::AttributionSourceState;
Philip P. Moltmannbda45752020-07-17 16:41:18 -070064
Eric Laurentdc462862016-07-19 12:29:53 -070065//FIXME: workaround for truncated touch sounds
66// to be removed when the problem is handled by system UI
67#define TOUCH_SOUND_FIXED_DELAY_MS 100
Jean-Michel Trivi719a9872017-08-05 13:51:35 -070068
69// Largest difference in dB on earpiece in call between the voice volume and another
70// media / notification / system volume.
71constexpr float IN_CALL_EARPIECE_HEADROOM_DB = 3.f;
72
jiabin06e4bab2019-07-29 10:13:34 -070073template <typename T>
74bool operator== (const SortedVector<T> &left, const SortedVector<T> &right)
75{
76 if (left.size() != right.size()) {
77 return false;
78 }
79 for (size_t index = 0; index < right.size(); index++) {
80 if (left[index] != right[index]) {
81 return false;
82 }
83 }
84 return true;
85}
86
87template <typename T>
88bool operator!= (const SortedVector<T> &left, const SortedVector<T> &right)
89{
90 return !(left == right);
91}
92
Eric Laurente552edb2014-03-10 17:42:56 -070093// ----------------------------------------------------------------------------
94// AudioPolicyInterface implementation
95// ----------------------------------------------------------------------------
96
Nathalie Le Clair88fa2752021-11-23 13:03:41 +010097status_t AudioPolicyManager::setDeviceConnectionState(audio_policy_dev_state_t state,
98 const android::media::audio::common::AudioPort& port, audio_format_t encodedFormat) {
99 status_t status = setDeviceConnectionStateInt(state, port, encodedFormat);
jiabina7b43792018-02-15 16:04:46 -0800100 nextAudioPortGeneration();
101 return status;
Eric Laurentc73ca6e2014-12-12 14:34:22 -0800102}
103
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100104status_t AudioPolicyManager::setDeviceConnectionState(audio_devices_t device,
105 audio_policy_dev_state_t state,
106 const char* device_address,
107 const char* device_name,
108 audio_format_t encodedFormat) {
Atneya Nair638a6e42022-12-18 16:45:15 -0800109 media::AudioPortFw aidlPort;
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100110 if (status_t status = deviceToAudioPort(device, device_address, device_name, &aidlPort);
111 status == OK) {
112 return setDeviceConnectionState(state, aidlPort.hal, encodedFormat);
113 } else {
114 ALOGE("Failed to convert to AudioPort Parcelable: %s", statusToString(status).c_str());
115 return status;
116 }
117}
118
François Gaffie11d30102018-11-02 16:09:09 +0100119void AudioPolicyManager::broadcastDeviceConnectionState(const sp<DeviceDescriptor> &device,
jiabinc0048632023-04-27 22:04:31 +0000120 media::DeviceConnectedState state)
François Gaffie44481e72016-04-20 07:49:57 +0200121{
Mikhail Naganov516d3982022-02-01 23:53:59 +0000122 audio_port_v7 devicePort;
123 device->toAudioPort(&devicePort);
jiabinc0048632023-04-27 22:04:31 +0000124 if (status_t status = mpClientInterface->setDeviceConnectedState(&devicePort, state);
Mikhail Naganov516d3982022-02-01 23:53:59 +0000125 status != OK) {
jiabinc0048632023-04-27 22:04:31 +0000126 ALOGE("Error %d while setting connected state for device %s", state,
Mikhail Naganov516d3982022-02-01 23:53:59 +0000127 device->getDeviceTypeAddr().toString(false).c_str());
128 }
François Gaffie44481e72016-04-20 07:49:57 +0200129}
130
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100131status_t AudioPolicyManager::setDeviceConnectionStateInt(
132 audio_policy_dev_state_t state, const android::media::audio::common::AudioPort& port,
133 audio_format_t encodedFormat) {
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100134 if (port.ext.getTag() != AudioPortExt::device) {
135 return BAD_VALUE;
136 }
137 audio_devices_t device_type;
138 std::string device_address;
139 if (status_t status = aidl2legacy_AudioDevice_audio_device(
140 port.ext.get<AudioPortExt::device>().device, &device_type, &device_address);
141 status != OK) {
142 return status;
143 };
144 const char* device_name = port.name.c_str();
145 // connect/disconnect only 1 device at a time
146 if (!audio_is_output_device(device_type) && !audio_is_input_device(device_type))
147 return BAD_VALUE;
148
149 sp<DeviceDescriptor> device = mHwModules.getDeviceDescriptor(
150 device_type, device_address.c_str(), device_name, encodedFormat,
151 state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
Mikhail Naganovddc5f312022-06-11 00:47:52 +0000152 if (device == nullptr) {
153 return INVALID_OPERATION;
154 }
155 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
156 device->setExtraAudioDescriptors(port.extraAudioDescriptors);
157 }
158 return setDeviceConnectionStateInt(device, state);
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100159}
160
François Gaffie11d30102018-11-02 16:09:09 +0100161status_t AudioPolicyManager::setDeviceConnectionStateInt(audio_devices_t deviceType,
Eric Laurenta1d525f2015-01-29 13:36:45 -0800162 audio_policy_dev_state_t state,
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100163 const char* device_address,
164 const char* device_name,
165 audio_format_t encodedFormat) {
Atneya Nair638a6e42022-12-18 16:45:15 -0800166 media::AudioPortFw aidlPort;
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100167 if (status_t status = deviceToAudioPort(deviceType, device_address, device_name, &aidlPort);
168 status == OK) {
169 return setDeviceConnectionStateInt(state, aidlPort.hal, encodedFormat);
170 } else {
171 ALOGE("Failed to convert to AudioPort Parcelable: %s", statusToString(status).c_str());
172 return status;
173 }
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700174}
Paul McLeane743a472015-01-28 11:07:31 -0800175
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700176status_t AudioPolicyManager::setDeviceConnectionStateInt(const sp<DeviceDescriptor> &device,
177 audio_policy_dev_state_t state)
178{
Eric Laurente552edb2014-03-10 17:42:56 -0700179 // handle output devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700180 if (audio_is_output_device(device->type())) {
Eric Laurentd4692962014-05-05 18:13:44 -0700181 SortedVector <audio_io_handle_t> outputs;
182
François Gaffie11d30102018-11-02 16:09:09 +0100183 ssize_t index = mAvailableOutputDevices.indexOf(device);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700184
Eric Laurente552edb2014-03-10 17:42:56 -0700185 // save a copy of the opened output descriptors before any output is opened or closed
186 // by checkOutputsForDevice(). This will be needed by checkOutputForAllStrategies()
187 mPreviousOutputs = mOutputs;
Eric Laurent96d1dda2022-03-14 17:14:19 +0100188
189 bool wasLeUnicastActive = isLeUnicastActive();
190
Eric Laurente552edb2014-03-10 17:42:56 -0700191 switch (state)
192 {
193 // handle output device connection
Eric Laurent3ae5f312015-02-03 17:12:08 -0800194 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700195 if (index >= 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100196 ALOGW("%s() device already connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700197 return INVALID_OPERATION;
198 }
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800199 ALOGV("%s() connecting device %s format %x",
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700200 __func__, device->toString().c_str(), device->getEncodedFormat());
Eric Laurente552edb2014-03-10 17:42:56 -0700201
Eric Laurente552edb2014-03-10 17:42:56 -0700202 // register new device as available
Francois Gaffie993f3902019-04-10 15:39:27 +0200203 if (mAvailableOutputDevices.add(device) < 0) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700204 return NO_MEMORY;
Eric Laurente552edb2014-03-10 17:42:56 -0700205 }
206
François Gaffie44481e72016-04-20 07:49:57 +0200207 // Before checking outputs, broadcast connect event to allow HAL to retrieve dynamic
208 // parameters on newly connected devices (instead of opening the outputs...)
jiabinc0048632023-04-27 22:04:31 +0000209 broadcastDeviceConnectionState(device, media::DeviceConnectedState::CONNECTED);
François Gaffie44481e72016-04-20 07:49:57 +0200210
François Gaffie11d30102018-11-02 16:09:09 +0100211 if (checkOutputsForDevice(device, state, outputs) != NO_ERROR) {
212 mAvailableOutputDevices.remove(device);
François Gaffie44481e72016-04-20 07:49:57 +0200213
Francois Gaffie716e1432019-01-14 16:58:59 +0100214 mHwModules.cleanUpForDevice(device);
215
jiabinc0048632023-04-27 22:04:31 +0000216 broadcastDeviceConnectionState(device, media::DeviceConnectedState::DISCONNECTED);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700217 return INVALID_OPERATION;
218 }
François Gaffie2110e042015-03-24 08:41:51 +0100219
jiabin1c4794b2020-05-05 10:08:05 -0700220 // Populate encapsulation information when a output device is connected.
221 device->setEncapsulationInfoFromHal(mpClientInterface);
222
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700223 // outputs should never be empty here
224 ALOG_ASSERT(outputs.size() != 0, "setDeviceConnectionState():"
225 "checkOutputsForDevice() returned no outputs but status OK");
François Gaffie11d30102018-11-02 16:09:09 +0100226 ALOGV("%s() checkOutputsForDevice() returned %zu outputs", __func__, outputs.size());
Eric Laurent3ae5f312015-02-03 17:12:08 -0800227
Eric Laurent3ae5f312015-02-03 17:12:08 -0800228 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700229 // handle output device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700230 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700231 if (index < 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100232 ALOGW("%s() device not connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700233 return INVALID_OPERATION;
234 }
235
François Gaffie11d30102018-11-02 16:09:09 +0100236 ALOGV("%s() disconnecting output device %s", __func__, device->toString().c_str());
Paul McLean5c477aa2014-08-20 16:47:57 -0700237
jiabinc0048632023-04-27 22:04:31 +0000238 // Notify the HAL to prepare to disconnect device
239 broadcastDeviceConnectionState(
240 device, media::DeviceConnectedState::PREPARE_TO_DISCONNECT);
Paul McLean5c477aa2014-08-20 16:47:57 -0700241
Eric Laurente552edb2014-03-10 17:42:56 -0700242 // remove device from available output devices
François Gaffie11d30102018-11-02 16:09:09 +0100243 mAvailableOutputDevices.remove(device);
Eric Laurente552edb2014-03-10 17:42:56 -0700244
Francois Gaffieba2cf0f2018-12-12 16:40:25 +0100245 mOutputs.clearSessionRoutesForDevice(device);
246
François Gaffie11d30102018-11-02 16:09:09 +0100247 checkOutputsForDevice(device, state, outputs);
François Gaffie2110e042015-03-24 08:41:51 +0100248
jiabinc0048632023-04-27 22:04:31 +0000249 // Send Disconnect to HALs
250 broadcastDeviceConnectionState(device, media::DeviceConnectedState::DISCONNECTED);
251
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800252 // Reset active device codec
253 device->setEncodedFormat(AUDIO_FORMAT_DEFAULT);
254
Kriti Dangef6be8f2020-11-05 11:58:19 +0100255 // remove device from mReportedFormatsMap cache
256 mReportedFormatsMap.erase(device);
257
jiabina84c3d32022-12-02 18:59:55 +0000258 // remove preferred mixer configurations
259 mPreferredMixerAttrInfos.erase(device->getId());
260
Eric Laurente552edb2014-03-10 17:42:56 -0700261 } break;
262
263 default:
François Gaffie11d30102018-11-02 16:09:09 +0100264 ALOGE("%s() invalid state: %x", __func__, state);
Eric Laurente552edb2014-03-10 17:42:56 -0700265 return BAD_VALUE;
266 }
267
Eric Laurent736a1022019-03-27 18:28:46 -0700268 // Propagate device availability to Engine
269 setEngineDeviceConnectionState(device, state);
270
Eric Laurentae970022019-01-29 14:25:04 -0800271 // No need to evaluate playback routing when connecting a remote submix
272 // output device used by a dynamic policy of type recorder as no
273 // playback use case is affected.
274 bool doCheckForDeviceAndOutputChanges = true;
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700275 if (device->type() == AUDIO_DEVICE_OUT_REMOTE_SUBMIX && device->address() != "0") {
Eric Laurentae970022019-01-29 14:25:04 -0800276 for (audio_io_handle_t output : outputs) {
277 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
Mikhail Naganovbfac5832019-03-05 16:55:28 -0800278 sp<AudioPolicyMix> policyMix = desc->mPolicyMix.promote();
279 if (policyMix != nullptr
280 && policyMix->mMixType == MIX_TYPE_RECORDERS
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +0000281 && device->address() == policyMix->mDeviceAddress.c_str()) {
Eric Laurentae970022019-01-29 14:25:04 -0800282 doCheckForDeviceAndOutputChanges = false;
283 break;
284 }
285 }
286 }
287
288 auto checkCloseOutputs = [&]() {
Mikhail Naganov37977152018-07-11 15:54:44 -0700289 // outputs must be closed after checkOutputForAllStrategies() is executed
290 if (!outputs.isEmpty()) {
291 for (audio_io_handle_t output : outputs) {
292 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
François Gaffie11d30102018-11-02 16:09:09 +0100293 // close unused outputs after device disconnection or direct outputs that have
294 // been opened by checkOutputsForDevice() to query dynamic parameters
Eric Laurente191d1b2022-04-15 11:59:25 +0200295 // "outputs" vector never contains duplicated outputs
Eric Laurentcad6c0d2021-07-13 15:12:39 +0200296 if ((state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE)
297 || (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != 0) &&
Eric Laurente191d1b2022-04-15 11:59:25 +0200298 (desc->mDirectOpenCount == 0))
299 || (((desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0) &&
300 !isOutputOnlyAvailableRouteToSomeDevice(desc))) {
Francois Gaffieff1eb522020-05-06 18:37:04 +0200301 clearAudioSourcesForOutput(output);
Mikhail Naganov37977152018-07-11 15:54:44 -0700302 closeOutput(output);
303 }
Eric Laurente552edb2014-03-10 17:42:56 -0700304 }
Mikhail Naganov37977152018-07-11 15:54:44 -0700305 // check A2DP again after closing A2DP output to reset mA2dpSuspended if needed
306 return true;
Eric Laurente552edb2014-03-10 17:42:56 -0700307 }
Mikhail Naganov37977152018-07-11 15:54:44 -0700308 return false;
Eric Laurentae970022019-01-29 14:25:04 -0800309 };
310
311 if (doCheckForDeviceAndOutputChanges) {
312 checkForDeviceAndOutputChanges(checkCloseOutputs);
313 } else {
314 checkCloseOutputs();
315 }
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100316 (void)updateCallRouting(false /*fromCache*/);
François Gaffie11d30102018-11-02 16:09:09 +0100317 const DeviceVector msdOutDevices = getMsdAudioOutDevices();
jiabinbce0c1d2020-10-05 11:20:18 -0700318 const DeviceVector activeMediaDevices =
319 mEngine->getActiveMediaDevices(mAvailableOutputDevices);
jiabin3ff8d7d2022-12-13 06:27:44 +0000320 std::map<audio_io_handle_t, DeviceVector> outputsToReopenWithDevices;
Eric Laurente552edb2014-03-10 17:42:56 -0700321 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700322 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Jaideep Sharma89b5b852020-11-23 16:41:33 +0530323 if (desc->isActive() && ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) ||
324 (desc != mPrimaryOutput))) {
François Gaffie11d30102018-11-02 16:09:09 +0100325 DeviceVector newDevices = getNewOutputDevices(desc, true /*fromCache*/);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700326 // do not force device change on duplicated output because if device is 0, it will
327 // also force a device 0 for the two outputs it is duplicated to which may override
328 // a valid device selection on those outputs.
François Gaffie11d30102018-11-02 16:09:09 +0100329 bool force = (msdOutDevices.isEmpty() || msdOutDevices != desc->devices())
Mikhail Naganov15be9d22017-11-08 14:18:13 +1100330 && !desc->isDuplicated()
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700331 && (!device_distinguishes_on_address(device->type())
Eric Laurentc2730ba2014-07-20 15:47:07 -0700332 // always force when disconnecting (a non-duplicated device)
333 || (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE));
jiabin3ff8d7d2022-12-13 06:27:44 +0000334 if (desc->mUsePreferredMixerAttributes && newDevices != desc->devices()) {
335 // If the device is using preferred mixer attributes, the output need to reopen
336 // with default configuration when the new selected devices are different from
337 // current routing devices
338 outputsToReopenWithDevices.emplace(mOutputs.keyAt(i), newDevices);
339 continue;
340 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +0530341 setOutputDevices(__func__, desc, newDevices, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700342 }
jiabinbce0c1d2020-10-05 11:20:18 -0700343 if (!desc->isDuplicated() && desc->mProfile->hasDynamicAudioProfile() &&
jiabin498d2152021-04-02 00:26:46 +0000344 !activeMediaDevices.empty() && desc->devices() != activeMediaDevices &&
jiabinbce0c1d2020-10-05 11:20:18 -0700345 desc->supportsDevicesForPlayback(activeMediaDevices)) {
346 // Reopen the output to query the dynamic profiles when there is not active
347 // clients or all active clients will be rerouted. Otherwise, set the flag
348 // `mPendingReopenToQueryProfiles` in the SwOutputDescriptor so that the output
349 // can be reopened to query dynamic profiles when all clients are inactive.
350 if (areAllActiveTracksRerouted(desc)) {
jiabin3ff8d7d2022-12-13 06:27:44 +0000351 outputsToReopenWithDevices.emplace(mOutputs.keyAt(i), activeMediaDevices);
jiabinbce0c1d2020-10-05 11:20:18 -0700352 } else {
353 desc->mPendingReopenToQueryProfiles = true;
354 }
355 }
356 if (!desc->supportsDevicesForPlayback(activeMediaDevices)) {
357 // Clear the flag that previously set for re-querying profiles.
358 desc->mPendingReopenToQueryProfiles = false;
359 }
360 }
jiabin3ff8d7d2022-12-13 06:27:44 +0000361 reopenOutputsWithDevices(outputsToReopenWithDevices);
Eric Laurente552edb2014-03-10 17:42:56 -0700362
Eric Laurentd60560a2015-04-10 11:31:20 -0700363 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
François Gaffie11d30102018-11-02 16:09:09 +0100364 cleanUpForDevice(device);
Eric Laurentd60560a2015-04-10 11:31:20 -0700365 }
366
Eric Laurent96d1dda2022-03-14 17:14:19 +0100367 checkLeBroadcastRoutes(wasLeUnicastActive, nullptr, 0);
368
Eric Laurent72aa32f2014-05-30 18:51:48 -0700369 mpClientInterface->onAudioPortListUpdate();
Eric Laurentb71e58b2014-05-29 16:08:11 -0700370 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700371 } // end if is output device
372
Eric Laurente552edb2014-03-10 17:42:56 -0700373 // handle input devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700374 if (audio_is_input_device(device->type())) {
François Gaffie11d30102018-11-02 16:09:09 +0100375 ssize_t index = mAvailableInputDevices.indexOf(device);
Eric Laurente552edb2014-03-10 17:42:56 -0700376 switch (state)
377 {
378 // handle input device connection
Eric Laurent3b73df72014-03-11 09:06:29 -0700379 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700380 if (index >= 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100381 ALOGW("%s() device already connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700382 return INVALID_OPERATION;
383 }
Eric Laurent0dd51852019-04-19 18:18:58 -0700384
385 if (mAvailableInputDevices.add(device) < 0) {
386 return NO_MEMORY;
387 }
388
François Gaffie44481e72016-04-20 07:49:57 +0200389 // Before checking intputs, broadcast connect event to allow HAL to retrieve dynamic
390 // parameters on newly connected devices (instead of opening the inputs...)
jiabinc0048632023-04-27 22:04:31 +0000391 broadcastDeviceConnectionState(device, media::DeviceConnectedState::CONNECTED);
François Gaffie44481e72016-04-20 07:49:57 +0200392
Eric Laurent0dd51852019-04-19 18:18:58 -0700393 if (checkInputsForDevice(device, state) != NO_ERROR) {
394 mAvailableInputDevices.remove(device);
395
jiabinc0048632023-04-27 22:04:31 +0000396 broadcastDeviceConnectionState(device, media::DeviceConnectedState::DISCONNECTED);
Francois Gaffie716e1432019-01-14 16:58:59 +0100397
398 mHwModules.cleanUpForDevice(device);
399
Eric Laurentd4692962014-05-05 18:13:44 -0700400 return INVALID_OPERATION;
401 }
402
Eric Laurentd4692962014-05-05 18:13:44 -0700403 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700404
405 // handle input device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700406 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700407 if (index < 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100408 ALOGW("%s() device not connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700409 return INVALID_OPERATION;
410 }
Paul McLean5c477aa2014-08-20 16:47:57 -0700411
François Gaffie11d30102018-11-02 16:09:09 +0100412 ALOGV("%s() disconnecting input device %s", __func__, device->toString().c_str());
Paul McLean5c477aa2014-08-20 16:47:57 -0700413
jiabinc0048632023-04-27 22:04:31 +0000414 // Notify the HAL to prepare to disconnect device
415 broadcastDeviceConnectionState(
416 device, media::DeviceConnectedState::PREPARE_TO_DISCONNECT);
Paul McLean5c477aa2014-08-20 16:47:57 -0700417
François Gaffie11d30102018-11-02 16:09:09 +0100418 mAvailableInputDevices.remove(device);
Eric Laurent0dd51852019-04-19 18:18:58 -0700419
420 checkInputsForDevice(device, state);
Kriti Dangef6be8f2020-11-05 11:58:19 +0100421
jiabinc0048632023-04-27 22:04:31 +0000422 // Set Disconnect to HALs
423 broadcastDeviceConnectionState(device, media::DeviceConnectedState::DISCONNECTED);
424
Kriti Dangef6be8f2020-11-05 11:58:19 +0100425 // remove device from mReportedFormatsMap cache
426 mReportedFormatsMap.erase(device);
Eric Laurentd4692962014-05-05 18:13:44 -0700427 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700428
429 default:
François Gaffie11d30102018-11-02 16:09:09 +0100430 ALOGE("%s() invalid state: %x", __func__, state);
Eric Laurente552edb2014-03-10 17:42:56 -0700431 return BAD_VALUE;
432 }
433
Eric Laurent736a1022019-03-27 18:28:46 -0700434 // Propagate device availability to Engine
435 setEngineDeviceConnectionState(device, state);
436
Eric Laurent0dd51852019-04-19 18:18:58 -0700437 checkCloseInputs();
Eric Laurent5f5fca52016-08-04 11:48:57 -0700438 // As the input device list can impact the output device selection, update
439 // getDeviceForStrategy() cache
440 updateDevicesAndOutputs();
Eric Laurente552edb2014-03-10 17:42:56 -0700441
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100442 (void)updateCallRouting(false /*fromCache*/);
Francois Gaffiea0e5c992020-09-29 16:05:07 +0200443 // Reconnect Audio Source
444 for (const auto &strategy : mEngine->getOrderedProductStrategies()) {
445 auto attributes = mEngine->getAllAttributesForProductStrategy(strategy).front();
446 checkAudioSourceForAttributes(attributes);
447 }
Eric Laurentd60560a2015-04-10 11:31:20 -0700448 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
François Gaffie11d30102018-11-02 16:09:09 +0100449 cleanUpForDevice(device);
Eric Laurentd60560a2015-04-10 11:31:20 -0700450 }
451
Eric Laurentb52c1522014-05-20 11:27:36 -0700452 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -0700453 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700454 } // end if is input device
Eric Laurente552edb2014-03-10 17:42:56 -0700455
François Gaffie11d30102018-11-02 16:09:09 +0100456 ALOGW("%s() invalid device: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700457 return BAD_VALUE;
458}
459
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100460status_t AudioPolicyManager::deviceToAudioPort(audio_devices_t device, const char* device_address,
461 const char* device_name,
Atneya Nair638a6e42022-12-18 16:45:15 -0800462 media::AudioPortFw* aidlPort) {
Andy Hung5b9a6112023-08-09 19:56:57 -0700463 const auto devDescr = sp<DeviceDescriptorBase>::make(device, device_address);
464 devDescr->setName(device_name);
465 return devDescr->writeToParcelable(aidlPort);
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100466}
467
Eric Laurent736a1022019-03-27 18:28:46 -0700468void AudioPolicyManager::setEngineDeviceConnectionState(const sp<DeviceDescriptor> device,
469 audio_policy_dev_state_t state) {
470
471 // the Engine does not have to know about remote submix devices used by dynamic audio policies
472 if (audio_is_remote_submix_device(device->type()) && device->address() != "0") {
473 return;
474 }
475 mEngine->setDeviceConnectionState(device, state);
476}
477
478
Eric Laurente0720872014-03-11 09:30:41 -0700479audio_policy_dev_state_t AudioPolicyManager::getDeviceConnectionState(audio_devices_t device,
François Gaffie53615e22015-03-19 09:24:12 +0100480 const char *device_address)
Eric Laurente552edb2014-03-10 17:42:56 -0700481{
Eric Laurent634b7142016-04-20 13:48:02 -0700482 sp<DeviceDescriptor> devDesc =
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800483 mHwModules.getDeviceDescriptor(device, device_address, "", AUDIO_FORMAT_DEFAULT,
484 false /* allowToCreate */,
Eric Laurent634b7142016-04-20 13:48:02 -0700485 (strlen(device_address) != 0)/*matchAddress*/);
486
487 if (devDesc == 0) {
François Gaffie251c7f02018-11-07 10:41:08 +0100488 ALOGV("getDeviceConnectionState() undeclared device, type %08x, address: %s",
Eric Laurent634b7142016-04-20 13:48:02 -0700489 device, device_address);
490 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
491 }
François Gaffie53615e22015-03-19 09:24:12 +0100492
Eric Laurent3a4311c2014-03-17 12:00:47 -0700493 DeviceVector *deviceVector;
494
Eric Laurente552edb2014-03-10 17:42:56 -0700495 if (audio_is_output_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700496 deviceVector = &mAvailableOutputDevices;
Eric Laurente552edb2014-03-10 17:42:56 -0700497 } else if (audio_is_input_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700498 deviceVector = &mAvailableInputDevices;
499 } else {
François Gaffie11d30102018-11-02 16:09:09 +0100500 ALOGW("%s() invalid device type %08x", __func__, device);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700501 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurente552edb2014-03-10 17:42:56 -0700502 }
Eric Laurent634b7142016-04-20 13:48:02 -0700503
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800504 return (deviceVector->getDevice(
505 device, String8(device_address), AUDIO_FORMAT_DEFAULT) != 0) ?
Eric Laurent634b7142016-04-20 13:48:02 -0700506 AUDIO_POLICY_DEVICE_STATE_AVAILABLE : AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurenta1d525f2015-01-29 13:36:45 -0800507}
508
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800509status_t AudioPolicyManager::handleDeviceConfigChange(audio_devices_t device,
510 const char *device_address,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800511 const char *device_name,
512 audio_format_t encodedFormat)
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800513{
514 status_t status;
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700515 String8 reply;
516 AudioParameter param;
517 int isReconfigA2dpSupported = 0;
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800518
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800519 ALOGV("handleDeviceConfigChange(() device: 0x%X, address %s name %s encodedFormat: 0x%X",
520 device, device_address, device_name, encodedFormat);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800521
Pavlin Radoslavovc694ff42017-01-09 23:27:29 -0800522 // connect/disconnect only 1 device at a time
523 if (!audio_is_output_device(device) && !audio_is_input_device(device)) return BAD_VALUE;
524
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800525 // Check if the device is currently connected
jiabin9a3361e2019-10-01 09:38:30 -0700526 DeviceVector deviceList = mAvailableOutputDevices.getDevicesFromType(device);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800527 if (deviceList.empty()) {
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800528 // Nothing to do: device is not connected
529 return NO_ERROR;
530 }
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800531 sp<DeviceDescriptor> devDesc = deviceList.itemAt(0);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800532
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700533 // For offloaded A2DP, Hw modules may have the capability to
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800534 // configure codecs.
535 // Handle two specific cases by sending a set parameter to
536 // configure A2DP codecs. No need to toggle device state.
537 // Case 1: A2DP active device switches from primary to primary
538 // module
539 // Case 2: A2DP device config changes on primary module.
Francois Gaffiebce7cd42020-10-14 16:13:20 +0200540 if (audio_is_a2dp_out_device(device) && hasPrimaryOutput()) {
jiabin9a3361e2019-10-01 09:38:30 -0700541 sp<HwModule> module = mHwModules.getModuleForDeviceType(device, encodedFormat);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800542 audio_module_handle_t primaryHandle = mPrimaryOutput->getModuleHandle();
543 if (availablePrimaryOutputDevices().contains(devDesc) &&
544 (module != 0 && module->getHandle() == primaryHandle)) {
545 reply = mpClientInterface->getParameters(
546 AUDIO_IO_HANDLE_NONE,
547 String8(AudioParameter::keyReconfigA2dpSupported));
548 AudioParameter repliedParameters(reply);
549 repliedParameters.getInt(
550 String8(AudioParameter::keyReconfigA2dpSupported), isReconfigA2dpSupported);
551 if (isReconfigA2dpSupported) {
552 const String8 key(AudioParameter::keyReconfigA2dp);
553 param.add(key, String8("true"));
554 mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString());
555 devDesc->setEncodedFormat(encodedFormat);
556 return NO_ERROR;
557 }
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700558 }
559 }
cnx421bd2dcc42020-07-11 14:58:44 +0800560 auto musicStrategy = streamToStrategy(AUDIO_STREAM_MUSIC);
561 for (size_t i = 0; i < mOutputs.size(); i++) {
562 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
563 // mute media strategies and delay device switch by the largest
564 // This avoid sending the music tail into the earpiece or headset.
565 setStrategyMute(musicStrategy, true, desc);
566 setStrategyMute(musicStrategy, false, desc, MUTE_TIME_MS,
567 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
568 nullptr, true /*fromCache*/).types());
569 }
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800570 // Toggle the device state: UNAVAILABLE -> AVAILABLE
571 // This will force reading again the device configuration
572 status = setDeviceConnectionState(device,
573 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800574 device_address, device_name,
575 devDesc->getEncodedFormat());
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800576 if (status != NO_ERROR) {
577 ALOGW("handleDeviceConfigChange() error disabling connection state: %d",
578 status);
579 return status;
580 }
581
582 status = setDeviceConnectionState(device,
583 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800584 device_address, device_name, encodedFormat);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800585 if (status != NO_ERROR) {
586 ALOGW("handleDeviceConfigChange() error enabling connection state: %d",
587 status);
588 return status;
589 }
590
591 return NO_ERROR;
592}
593
Pattydd807582021-11-04 21:01:03 +0800594status_t AudioPolicyManager::getHwOffloadFormatsSupportedForBluetoothMedia(
595 audio_devices_t device, std::vector<audio_format_t> *formats)
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800596{
Pattydd807582021-11-04 21:01:03 +0800597 ALOGV("getHwOffloadFormatsSupportedForBluetoothMedia()");
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800598 status_t status = NO_ERROR;
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800599 std::unordered_set<audio_format_t> formatSet;
600 sp<HwModule> primaryModule =
601 mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_PRIMARY);
Aniket Kumar Latafedb5982019-07-03 11:20:36 -0700602 if (primaryModule == nullptr) {
603 ALOGE("%s() unable to get primary module", __func__);
604 return NO_INIT;
605 }
Pattydd807582021-11-04 21:01:03 +0800606
607 DeviceTypeSet audioDeviceSet;
608
609 switch(device) {
610 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP:
611 audioDeviceSet = getAudioDeviceOutAllA2dpSet();
612 break;
613 case AUDIO_DEVICE_OUT_BLE_HEADSET:
Patty Huang36028df2022-07-06 00:14:12 +0800614 audioDeviceSet = getAudioDeviceOutLeAudioUnicastSet();
615 break;
616 case AUDIO_DEVICE_OUT_BLE_BROADCAST:
617 audioDeviceSet = getAudioDeviceOutLeAudioBroadcastSet();
Pattydd807582021-11-04 21:01:03 +0800618 break;
619 default:
620 ALOGE("%s() device type 0x%08x not supported", __func__, device);
621 return BAD_VALUE;
622 }
623
jiabin9a3361e2019-10-01 09:38:30 -0700624 DeviceVector declaredDevices = primaryModule->getDeclaredDevices().getDevicesFromTypes(
Pattydd807582021-11-04 21:01:03 +0800625 audioDeviceSet);
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800626 for (const auto& device : declaredDevices) {
627 formatSet.insert(device->encodedFormats().begin(), device->encodedFormats().end());
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800628 }
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800629 formats->assign(formatSet.begin(), formatSet.end());
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800630 return status;
631}
632
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100633DeviceVector AudioPolicyManager::selectBestRxSinkDevicesForCall(bool fromCache)
634{
635 DeviceVector rxSinkdevices{};
636 rxSinkdevices = mEngine->getOutputDevicesForAttributes(
637 attributes_initializer(AUDIO_USAGE_VOICE_COMMUNICATION), nullptr, fromCache);
638 if (!rxSinkdevices.isEmpty() && mAvailableOutputDevices.contains(rxSinkdevices.itemAt(0))) {
639 auto rxSinkDevice = rxSinkdevices.itemAt(0);
640 auto telephonyRxModule = mHwModules.getModuleForDeviceType(
641 AUDIO_DEVICE_IN_TELEPHONY_RX, AUDIO_FORMAT_DEFAULT);
642 // retrieve Rx Source device descriptor
643 sp<DeviceDescriptor> rxSourceDevice = mAvailableInputDevices.getDevice(
644 AUDIO_DEVICE_IN_TELEPHONY_RX, String8(), AUDIO_FORMAT_DEFAULT);
645
646 // RX Telephony and Rx sink devices are declared by Primary Audio HAL
647 if (isPrimaryModule(telephonyRxModule) && (telephonyRxModule->getHalVersionMajor() >= 3) &&
648 telephonyRxModule->supportsPatch(rxSourceDevice, rxSinkDevice)) {
649 ALOGW("%s() device %s using HW Bridge", __func__, rxSinkDevice->toString().c_str());
650 return DeviceVector(rxSinkDevice);
651 }
652 }
653 // Note that despite the fact that getNewOutputDevices() is called on the primary output,
654 // the device returned is not necessarily reachable via this output
655 // (filter later by setOutputDevices())
656 return getNewOutputDevices(mPrimaryOutput, fromCache);
657}
658
659status_t AudioPolicyManager::updateCallRouting(bool fromCache, uint32_t delayMs, uint32_t *waitMs)
660{
François Gaffiedb1755b2023-09-01 11:50:35 +0200661 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) {
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100662 DeviceVector rxDevices = selectBestRxSinkDevicesForCall(fromCache);
663 return updateCallRoutingInternal(rxDevices, delayMs, waitMs);
664 }
665 return INVALID_OPERATION;
666}
667
668status_t AudioPolicyManager::updateCallRoutingInternal(
669 const DeviceVector &rxDevices, uint32_t delayMs, uint32_t *waitMs)
Eric Laurentc2730ba2014-07-20 15:47:07 -0700670{
671 bool createTxPatch = false;
François Gaffie9eb18552018-11-05 10:33:26 +0100672 bool createRxPatch = false;
Eric Laurentdc462862016-07-19 12:29:53 -0700673 uint32_t muteWaitMs = 0;
François Gaffiedb1755b2023-09-01 11:50:35 +0200674 if (hasPrimaryOutput() &&
jiabin9a3361e2019-10-01 09:38:30 -0700675 mPrimaryOutput->devices().onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_STUB)) {
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100676 return INVALID_OPERATION;
Eric Laurent87ffa392015-05-22 10:32:38 -0700677 }
François Gaffie11d30102018-11-02 16:09:09 +0100678
Francois Gaffie716e1432019-01-14 16:58:59 +0100679 audio_attributes_t attr = { .source = AUDIO_SOURCE_VOICE_COMMUNICATION };
François Gaffiec005e562018-11-06 15:04:49 +0100680 auto txSourceDevice = mEngine->getInputDeviceForAttributes(attr);
François Gaffiedb1755b2023-09-01 11:50:35 +0200681
682 disconnectTelephonyAudioSource(mCallRxSourceClient);
683 disconnectTelephonyAudioSource(mCallTxSourceClient);
684
685 if (rxDevices.isEmpty()) {
686 ALOGW("%s() no selected output device", __func__);
687 return INVALID_OPERATION;
688 }
Eric Laurentcedd5b52023-03-22 00:03:31 +0000689 if (txSourceDevice == nullptr) {
690 ALOGE("%s() selected input device not available", __func__);
691 return INVALID_OPERATION;
692 }
François Gaffiec005e562018-11-06 15:04:49 +0100693
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100694 ALOGV("%s device rxDevice %s txDevice %s", __func__,
François Gaffie9eb18552018-11-05 10:33:26 +0100695 rxDevices.itemAt(0)->toString().c_str(), txSourceDevice->toString().c_str());
Eric Laurentc2730ba2014-07-20 15:47:07 -0700696
François Gaffie9eb18552018-11-05 10:33:26 +0100697 auto telephonyRxModule =
jiabin9a3361e2019-10-01 09:38:30 -0700698 mHwModules.getModuleForDeviceType(AUDIO_DEVICE_IN_TELEPHONY_RX, AUDIO_FORMAT_DEFAULT);
François Gaffie9eb18552018-11-05 10:33:26 +0100699 auto telephonyTxModule =
jiabin9a3361e2019-10-01 09:38:30 -0700700 mHwModules.getModuleForDeviceType(AUDIO_DEVICE_OUT_TELEPHONY_TX, AUDIO_FORMAT_DEFAULT);
François Gaffie9eb18552018-11-05 10:33:26 +0100701 // retrieve Rx Source and Tx Sink device descriptors
702 sp<DeviceDescriptor> rxSourceDevice =
703 mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_TELEPHONY_RX,
704 String8(),
705 AUDIO_FORMAT_DEFAULT);
706 sp<DeviceDescriptor> txSinkDevice =
707 mAvailableOutputDevices.getDevice(AUDIO_DEVICE_OUT_TELEPHONY_TX,
708 String8(),
709 AUDIO_FORMAT_DEFAULT);
710
711 // RX and TX Telephony device are declared by Primary Audio HAL
712 if (isPrimaryModule(telephonyRxModule) && isPrimaryModule(telephonyTxModule) &&
713 (telephonyRxModule->getHalVersionMajor() >= 3)) {
714 if (rxSourceDevice == 0 || txSinkDevice == 0) {
715 // RX / TX Telephony device(s) is(are) not currently available
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100716 ALOGE("%s() no telephony Tx and/or RX device", __func__);
717 return INVALID_OPERATION;
François Gaffie9eb18552018-11-05 10:33:26 +0100718 }
François Gaffieafd4cea2019-11-18 15:50:22 +0100719 // createAudioPatchInternal now supports both HW / SW bridging
720 createRxPatch = true;
721 createTxPatch = true;
François Gaffie9eb18552018-11-05 10:33:26 +0100722 } else {
723 // If the RX device is on the primary HW module, then use legacy routing method for
724 // voice calls via setOutputDevice() on primary output.
725 // Otherwise, create two audio patches for TX and RX path.
726 createRxPatch = !(availablePrimaryOutputDevices().contains(rxDevices.itemAt(0))) &&
727 (rxSourceDevice != 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700728 // If the TX device is also on the primary HW module, setOutputDevice() will take care
729 // of it due to legacy implementation. If not, create a patch.
François Gaffie9eb18552018-11-05 10:33:26 +0100730 createTxPatch = !(availablePrimaryModuleInputDevices().contains(txSourceDevice)) &&
731 (txSinkDevice != 0);
732 }
733 // Use legacy routing method for voice calls via setOutputDevice() on primary output.
734 // Otherwise, create two audio patches for TX and RX path.
735 if (!createRxPatch) {
François Gaffiedb1755b2023-09-01 11:50:35 +0200736 if (!hasPrimaryOutput()) {
737 ALOGW("%s() no primary output available", __func__);
738 return INVALID_OPERATION;
739 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +0530740 muteWaitMs = setOutputDevices(__func__, mPrimaryOutput, rxDevices, true, delayMs);
Eric Laurent8ae73122016-04-12 10:13:29 -0700741 } else { // create RX path audio patch
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200742 connectTelephonyRxAudioSource();
juyuchen2224c5a2019-01-21 12:00:58 +0800743 // If the TX device is on the primary HW module but RX device is
744 // on other HW module, SinkMetaData of telephony input should handle it
745 // assuming the device uses audio HAL V5.0 and above
Eric Laurentc2730ba2014-07-20 15:47:07 -0700746 }
Eric Laurent8ae73122016-04-12 10:13:29 -0700747 if (createTxPatch) { // create TX path audio patch
François Gaffieafd4cea2019-11-18 15:50:22 +0100748 // terminate active capture if on the same HW module as the call TX source device
749 // FIXME: would be better to refine to only inputs whose profile connects to the
750 // call TX device but this information is not in the audio patch and logic here must be
751 // symmetric to the one in startInput()
752 for (const auto& activeDesc : mInputs.getActiveInputs()) {
753 if (activeDesc->hasSameHwModuleAs(txSourceDevice)) {
754 closeActiveClients(activeDesc);
755 }
756 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200757 connectTelephonyTxAudioSource(txSourceDevice, txSinkDevice, delayMs);
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800758 }
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100759 if (waitMs != nullptr) {
760 *waitMs = muteWaitMs;
761 }
762 return NO_ERROR;
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800763}
Eric Laurentc2730ba2014-07-20 15:47:07 -0700764
Mikhail Naganov100f0122018-11-29 11:22:16 -0800765bool AudioPolicyManager::isDeviceOfModule(
766 const sp<DeviceDescriptor>& devDesc, const char *moduleId) const {
767 sp<HwModule> module = mHwModules.getModuleFromName(moduleId);
768 if (module != 0) {
769 return mAvailableOutputDevices.getDevicesFromHwModule(module->getHandle())
770 .indexOf(devDesc) != NAME_NOT_FOUND
771 || mAvailableInputDevices.getDevicesFromHwModule(module->getHandle())
772 .indexOf(devDesc) != NAME_NOT_FOUND;
773 }
774 return false;
775}
776
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200777void AudioPolicyManager::connectTelephonyRxAudioSource()
778{
Francois Gaffie601801d2021-06-22 13:27:39 +0200779 disconnectTelephonyAudioSource(mCallRxSourceClient);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200780 const struct audio_port_config source = {
781 .role = AUDIO_PORT_ROLE_SOURCE, .type = AUDIO_PORT_TYPE_DEVICE,
782 .ext.device.type = AUDIO_DEVICE_IN_TELEPHONY_RX, .ext.device.address = ""
783 };
784 const auto aa = mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL);
Francois Gaffie601801d2021-06-22 13:27:39 +0200785 mCallRxSourceClient = startAudioSourceInternal(&source, &aa, 0/*uid*/);
786 ALOGE_IF(mCallRxSourceClient == nullptr,
787 "%s failed to start Telephony Rx AudioSource", __func__);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200788}
789
Francois Gaffie601801d2021-06-22 13:27:39 +0200790void AudioPolicyManager::disconnectTelephonyAudioSource(sp<SourceClientDescriptor> &clientDesc)
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200791{
Francois Gaffie601801d2021-06-22 13:27:39 +0200792 if (clientDesc == nullptr) {
793 return;
794 }
795 ALOGW_IF(stopAudioSource(clientDesc->portId()) != NO_ERROR,
796 "%s error stopping audio source", __func__);
797 clientDesc.clear();
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200798}
799
800void AudioPolicyManager::connectTelephonyTxAudioSource(
801 const sp<DeviceDescriptor> &srcDevice, const sp<DeviceDescriptor> &sinkDevice,
802 uint32_t delayMs)
803{
Francois Gaffie601801d2021-06-22 13:27:39 +0200804 disconnectTelephonyAudioSource(mCallTxSourceClient);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200805 if (srcDevice == nullptr || sinkDevice == nullptr) {
806 ALOGW("%s could not create patch, invalid sink and/or source device(s)", __func__);
807 return;
808 }
809 PatchBuilder patchBuilder;
810 patchBuilder.addSource(srcDevice).addSink(sinkDevice);
811 ALOGV("%s between source %s and sink %s", __func__,
812 srcDevice->toString().c_str(), sinkDevice->toString().c_str());
Francois Gaffie601801d2021-06-22 13:27:39 +0200813 auto callTxSourceClientPortId = PolicyAudioPort::getNextUniqueId();
Eric Laurent78b07302022-10-07 16:20:34 +0200814 const auto aa = mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL);
815
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200816 struct audio_port_config source = {};
817 srcDevice->toAudioPortConfig(&source);
Francois Gaffie601801d2021-06-22 13:27:39 +0200818 mCallTxSourceClient = new InternalSourceClientDescriptor(
819 callTxSourceClientPortId, mUidCached, aa, source, srcDevice, sinkDevice,
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200820 mCommunnicationStrategy, toVolumeSource(aa));
821 audio_patch_handle_t patchHandle = AUDIO_PATCH_HANDLE_NONE;
822 status_t status = connectAudioSourceToSink(
Francois Gaffie601801d2021-06-22 13:27:39 +0200823 mCallTxSourceClient, sinkDevice, patchBuilder.patch(), patchHandle, mUidCached,
824 delayMs);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200825 ALOGE_IF(status != NO_ERROR, "%s() error %d creating TX audio patch", __func__, status);
826 if (status == NO_ERROR) {
Francois Gaffie601801d2021-06-22 13:27:39 +0200827 mAudioSources.add(callTxSourceClientPortId, mCallTxSourceClient);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200828 }
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200829}
830
Eric Laurente0720872014-03-11 09:30:41 -0700831void AudioPolicyManager::setPhoneState(audio_mode_t state)
Eric Laurente552edb2014-03-10 17:42:56 -0700832{
833 ALOGV("setPhoneState() state %d", state);
François Gaffie2110e042015-03-24 08:41:51 +0100834 // store previous phone state for management of sonification strategy below
835 int oldState = mEngine->getPhoneState();
Eric Laurent96d1dda2022-03-14 17:14:19 +0100836 bool wasLeUnicastActive = isLeUnicastActive();
François Gaffie2110e042015-03-24 08:41:51 +0100837
838 if (mEngine->setPhoneState(state) != NO_ERROR) {
839 ALOGW("setPhoneState() invalid or same state %d", state);
Eric Laurente552edb2014-03-10 17:42:56 -0700840 return;
841 }
François Gaffie2110e042015-03-24 08:41:51 +0100842 /// Opens: can these line be executed after the switch of volume curves???
Eric Laurent63dea1d2015-07-02 17:10:28 -0700843 if (isStateInCall(oldState)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700844 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent63dea1d2015-07-02 17:10:28 -0700845 // force reevaluating accessibility routing when call stops
jiabinc44b3462022-12-08 12:52:31 -0800846 invalidateStreams({AUDIO_STREAM_ACCESSIBILITY});
Eric Laurente552edb2014-03-10 17:42:56 -0700847 }
848
François Gaffie2110e042015-03-24 08:41:51 +0100849 /**
850 * Switching to or from incall state or switching between telephony and VoIP lead to force
851 * routing command.
852 */
Eric Laurent74b71512019-11-06 17:21:57 -0800853 bool force = ((isStateInCall(oldState) != isStateInCall(state))
854 || (isStateInCall(state) && (state != oldState)));
Eric Laurente552edb2014-03-10 17:42:56 -0700855
856 // check for device and output changes triggered by new phone state
Mikhail Naganov37977152018-07-11 15:54:44 -0700857 checkForDeviceAndOutputChanges();
Eric Laurente552edb2014-03-10 17:42:56 -0700858
Eric Laurente552edb2014-03-10 17:42:56 -0700859 int delayMs = 0;
860 if (isStateInCall(state)) {
861 nsecs_t sysTime = systemTime();
François Gaffiec005e562018-11-06 15:04:49 +0100862 auto musicStrategy = streamToStrategy(AUDIO_STREAM_MUSIC);
863 auto sonificationStrategy = streamToStrategy(AUDIO_STREAM_ALARM);
Eric Laurente552edb2014-03-10 17:42:56 -0700864 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700865 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700866 // mute media and sonification strategies and delay device switch by the largest
867 // latency of any output where either strategy is active.
868 // This avoid sending the ring tone or music tail into the earpiece or headset.
François Gaffiec005e562018-11-06 15:04:49 +0100869 if ((desc->isStrategyActive(musicStrategy, SONIFICATION_HEADSET_MUSIC_DELAY, sysTime) ||
870 desc->isStrategyActive(sonificationStrategy, SONIFICATION_HEADSET_MUSIC_DELAY,
871 sysTime)) &&
Eric Laurentc75307b2015-03-17 15:29:32 -0700872 (delayMs < (int)desc->latency()*2)) {
873 delayMs = desc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -0700874 }
François Gaffiec005e562018-11-06 15:04:49 +0100875 setStrategyMute(musicStrategy, true, desc);
876 setStrategyMute(musicStrategy, false, desc, MUTE_TIME_MS,
877 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
878 nullptr, true /*fromCache*/).types());
879 setStrategyMute(sonificationStrategy, true, desc);
880 setStrategyMute(sonificationStrategy, false, desc, MUTE_TIME_MS,
881 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_ALARM),
882 nullptr, true /*fromCache*/).types());
Eric Laurente552edb2014-03-10 17:42:56 -0700883 }
884 }
885
François Gaffiedb1755b2023-09-01 11:50:35 +0200886 if (state == AUDIO_MODE_IN_CALL) {
887 (void)updateCallRouting(false /*fromCache*/, delayMs);
888 } else {
889 if (oldState == AUDIO_MODE_IN_CALL) {
890 disconnectTelephonyAudioSource(mCallRxSourceClient);
891 disconnectTelephonyAudioSource(mCallTxSourceClient);
892 }
893 if (hasPrimaryOutput()) {
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100894 DeviceVector rxDevices = getNewOutputDevices(mPrimaryOutput, false /*fromCache*/);
895 // force routing command to audio hardware when ending call
896 // even if no device change is needed
897 if (isStateInCall(oldState) && rxDevices.isEmpty()) {
898 rxDevices = mPrimaryOutput->devices();
899 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +0530900 setOutputDevices(__func__, mPrimaryOutput, rxDevices, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700901 }
Eric Laurentc2730ba2014-07-20 15:47:07 -0700902 }
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700903
jiabin3ff8d7d2022-12-13 06:27:44 +0000904 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700905 // reevaluate routing on all outputs in case tracks have been started during the call
906 for (size_t i = 0; i < mOutputs.size(); i++) {
907 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
François Gaffie11d30102018-11-02 16:09:09 +0100908 DeviceVector newDevices = getNewOutputDevices(desc, true /*fromCache*/);
Francois Gaffie601801d2021-06-22 13:27:39 +0200909 if (state != AUDIO_MODE_IN_CALL || (desc != mPrimaryOutput && !isTelephonyRxOrTx(desc))) {
910 bool forceRouting = !newDevices.isEmpty();
jiabin3ff8d7d2022-12-13 06:27:44 +0000911 if (desc->mUsePreferredMixerAttributes && newDevices != desc->devices()) {
912 // If the device is using preferred mixer attributes, the output need to reopen
913 // with default configuration when the new selected devices are different from
914 // current routing devices.
915 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices);
916 continue;
917 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +0530918 setOutputDevices(__func__, desc, newDevices, forceRouting, 0 /*delayMs*/, nullptr,
Francois Gaffie601801d2021-06-22 13:27:39 +0200919 true /*requiresMuteCheck*/, !forceRouting /*requiresVolumeCheck*/);
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700920 }
921 }
jiabin3ff8d7d2022-12-13 06:27:44 +0000922 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700923
Eric Laurent96d1dda2022-03-14 17:14:19 +0100924 checkLeBroadcastRoutes(wasLeUnicastActive, nullptr, delayMs);
925
Eric Laurente552edb2014-03-10 17:42:56 -0700926 if (isStateInCall(state)) {
927 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent63dea1d2015-07-02 17:10:28 -0700928 // force reevaluating accessibility routing when call starts
jiabinc44b3462022-12-08 12:52:31 -0800929 invalidateStreams({AUDIO_STREAM_ACCESSIBILITY});
Eric Laurente552edb2014-03-10 17:42:56 -0700930 }
931
932 // Flag that ringtone volume must be limited to music volume until we exit MODE_RINGTONE
François Gaffiec005e562018-11-06 15:04:49 +0100933 mLimitRingtoneVolume = (state == AUDIO_MODE_RINGTONE &&
934 isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY));
Eric Laurente552edb2014-03-10 17:42:56 -0700935}
936
Jean-Michel Trivi887a9ed2015-03-31 18:02:24 -0700937audio_mode_t AudioPolicyManager::getPhoneState() {
938 return mEngine->getPhoneState();
939}
940
Eric Laurente0720872014-03-11 09:30:41 -0700941void AudioPolicyManager::setForceUse(audio_policy_force_use_t usage,
François Gaffie11d30102018-11-02 16:09:09 +0100942 audio_policy_forced_cfg_t config)
Eric Laurente552edb2014-03-10 17:42:56 -0700943{
François Gaffie2110e042015-03-24 08:41:51 +0100944 ALOGV("setForceUse() usage %d, config %d, mPhoneState %d", usage, config, mEngine->getPhoneState());
Eric Laurent8dc87a62017-05-16 19:00:40 -0700945 if (config == mEngine->getForceUse(usage)) {
946 return;
947 }
Eric Laurente552edb2014-03-10 17:42:56 -0700948
François Gaffie2110e042015-03-24 08:41:51 +0100949 if (mEngine->setForceUse(usage, config) != NO_ERROR) {
950 ALOGW("setForceUse() could not set force cfg %d for usage %d", config, usage);
951 return;
Eric Laurente552edb2014-03-10 17:42:56 -0700952 }
François Gaffie2110e042015-03-24 08:41:51 +0100953 bool forceVolumeReeval = (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) ||
954 (usage == AUDIO_POLICY_FORCE_FOR_DOCK) ||
955 (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM);
Eric Laurente552edb2014-03-10 17:42:56 -0700956
957 // check for device and output changes triggered by new force usage
Mikhail Naganov37977152018-07-11 15:54:44 -0700958 checkForDeviceAndOutputChanges();
Phil Burk09bc4612016-02-24 15:58:15 -0800959
Eric Laurent22fcda22019-05-17 16:28:47 -0700960 // force client reconnection to reevaluate flag AUDIO_FLAG_AUDIBILITY_ENFORCED
961 if (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM) {
jiabinc44b3462022-12-08 12:52:31 -0800962 invalidateStreams({AUDIO_STREAM_SYSTEM, AUDIO_STREAM_ENFORCED_AUDIBLE});
Eric Laurent22fcda22019-05-17 16:28:47 -0700963 }
964
Eric Laurentdc462862016-07-19 12:29:53 -0700965 //FIXME: workaround for truncated touch sounds
966 // to be removed when the problem is handled by system UI
967 uint32_t delayMs = 0;
Eric Laurentdc462862016-07-19 12:29:53 -0700968 if (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) {
969 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
970 }
Jean-Michel Trivi30857152019-11-01 11:04:15 -0700971
972 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Eric Laurent2517af32020-11-25 15:31:27 +0100973 updateInputRouting();
Eric Laurente552edb2014-03-10 17:42:56 -0700974}
975
Eric Laurente0720872014-03-11 09:30:41 -0700976void AudioPolicyManager::setSystemProperty(const char* property, const char* value)
Eric Laurente552edb2014-03-10 17:42:56 -0700977{
978 ALOGV("setSystemProperty() property %s, value %s", property, value);
979}
980
Dorin Drimusecc9f422022-03-09 17:57:40 +0100981// Find an MSD output profile compatible with the parameters passed.
982// When "directOnly" is set, restrict search to profiles for direct outputs.
983sp<IOProfile> AudioPolicyManager::getMsdProfileForOutput(
984 const DeviceVector& devices,
985 uint32_t samplingRate,
986 audio_format_t format,
987 audio_channel_mask_t channelMask,
988 audio_output_flags_t flags,
989 bool directOnly)
990{
991 flags = getRelevantFlags(flags, directOnly);
992
993 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
994 if (msdModule != nullptr) {
995 // for the msd module check if there are patches to the output devices
996 if (msdHasPatchesToAllDevices(devices.toTypeAddrVector())) {
997 HwModuleCollection modules;
998 modules.add(msdModule);
999 return searchCompatibleProfileHwModules(
1000 modules, getMsdAudioOutDevices(), samplingRate, format, channelMask,
1001 flags, directOnly);
1002 }
1003 }
1004 return nullptr;
1005}
1006
Michael Chana94fbb22018-04-24 14:31:19 +10001007// Find an output profile compatible with the parameters passed. When "directOnly" is set, restrict
1008// search to profiles for direct outputs.
1009sp<IOProfile> AudioPolicyManager::getProfileForOutput(
François Gaffie11d30102018-11-02 16:09:09 +01001010 const DeviceVector& devices,
Michael Chana94fbb22018-04-24 14:31:19 +10001011 uint32_t samplingRate,
1012 audio_format_t format,
1013 audio_channel_mask_t channelMask,
1014 audio_output_flags_t flags,
1015 bool directOnly)
Eric Laurente552edb2014-03-10 17:42:56 -07001016{
Dorin Drimusecc9f422022-03-09 17:57:40 +01001017 flags = getRelevantFlags(flags, directOnly);
1018
1019 return searchCompatibleProfileHwModules(
1020 mHwModules, devices, samplingRate, format, channelMask, flags, directOnly);
1021}
1022
1023audio_output_flags_t AudioPolicyManager::getRelevantFlags (
1024 audio_output_flags_t flags, bool directOnly) {
Michael Chana94fbb22018-04-24 14:31:19 +10001025 if (directOnly) {
Dorin Drimusecc9f422022-03-09 17:57:40 +01001026 // only retain flags that will drive the direct output profile selection
1027 // if explicitly requested
1028 static const uint32_t kRelevantFlags =
Michael Chana94fbb22018-04-24 14:31:19 +10001029 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD |
Dorin Drimusecc9f422022-03-09 17:57:40 +01001030 AUDIO_OUTPUT_FLAG_VOIP_RX | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ);
1031 flags = (audio_output_flags_t)((flags & kRelevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
Michael Chana94fbb22018-04-24 14:31:19 +10001032 }
Dorin Drimusecc9f422022-03-09 17:57:40 +01001033 return flags;
1034}
Eric Laurent861a6282015-05-18 15:40:16 -07001035
Dorin Drimusecc9f422022-03-09 17:57:40 +01001036sp<IOProfile> AudioPolicyManager::searchCompatibleProfileHwModules (
1037 const HwModuleCollection& hwModules,
1038 const DeviceVector& devices,
1039 uint32_t samplingRate,
1040 audio_format_t format,
1041 audio_channel_mask_t channelMask,
1042 audio_output_flags_t flags,
1043 bool directOnly) {
Eric Laurent861a6282015-05-18 15:40:16 -07001044 sp<IOProfile> profile;
Dorin Drimusecc9f422022-03-09 17:57:40 +01001045 for (const auto& hwModule : hwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08001046 for (const auto& curProfile : hwModule->getOutputProfiles()) {
Dorin Drimusecc9f422022-03-09 17:57:40 +01001047 if (!curProfile->isCompatibleProfile(devices,
1048 samplingRate, NULL /*updatedSamplingRate*/,
1049 format, NULL /*updatedFormat*/,
1050 channelMask, NULL /*updatedChannelMask*/,
1051 flags)) {
1052 continue;
1053 }
1054 // reject profiles not corresponding to a device currently available
1055 if (!mAvailableOutputDevices.containsAtLeastOne(curProfile->getSupportedDevices())) {
1056 continue;
1057 }
1058 // reject profiles if connected device does not support codec
1059 if (!curProfile->devicesSupportEncodedFormats(devices.types())) {
1060 continue;
1061 }
1062 if (!directOnly) {
1063 return curProfile;
1064 }
1065
1066 // when searching for direct outputs, if several profiles are compatible, give priority
1067 // to one with offload capability
Patty Huang36028df2022-07-06 00:14:12 +08001068 if (profile != 0 &&
Dorin Drimusecc9f422022-03-09 17:57:40 +01001069 ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0)) {
Eric Laurent861a6282015-05-18 15:40:16 -07001070 continue;
Dorin Drimusecc9f422022-03-09 17:57:40 +01001071 }
1072 profile = curProfile;
1073 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1074 break;
1075 }
Eric Laurente552edb2014-03-10 17:42:56 -07001076 }
1077 }
Eric Laurent861a6282015-05-18 15:40:16 -07001078 return profile;
Eric Laurente552edb2014-03-10 17:42:56 -07001079}
1080
Eric Laurentfa0f6742021-08-17 18:39:44 +02001081sp<IOProfile> AudioPolicyManager::getSpatializerOutputProfile(
Eric Laurent39095982021-08-24 18:29:27 +02001082 const audio_config_t *config __unused, const AudioDeviceTypeAddrVector &devices) const
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001083{
1084 for (const auto& hwModule : mHwModules) {
1085 for (const auto& curProfile : hwModule->getOutputProfiles()) {
Eric Laurent1c5e2e32021-08-18 18:50:28 +02001086 if (curProfile->getFlags() != AUDIO_OUTPUT_FLAG_SPATIALIZER) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001087 continue;
1088 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001089 if (!devices.empty()) {
Eric Laurent0c8f7cc2022-06-24 14:32:36 +02001090 // reject profiles not corresponding to a device currently available
1091 DeviceVector supportedDevices = curProfile->getSupportedDevices();
1092 if (!mAvailableOutputDevices.containsAtLeastOne(supportedDevices)) {
1093 continue;
1094 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001095 if (supportedDevices.getDevicesFromDeviceTypeAddrVec(devices).size()
1096 != devices.size()) {
1097 continue;
1098 }
1099 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001100 ALOGV("%s found profile %s", __func__, curProfile->getName().c_str());
1101 return curProfile;
1102 }
1103 }
1104 return nullptr;
1105}
1106
Eric Laurentf4e63452017-11-06 19:31:46 +00001107audio_io_handle_t AudioPolicyManager::getOutput(audio_stream_type_t stream)
Eric Laurente552edb2014-03-10 17:42:56 -07001108{
François Gaffiec005e562018-11-06 15:04:49 +01001109 DeviceVector devices = mEngine->getOutputDevicesForStream(stream, false /*fromCache*/);
Andy Hungc9901522017-11-10 20:07:54 -08001110
1111 // Note that related method getOutputForAttr() uses getOutputForDevice() not selectOutput().
1112 // We use selectOutput() here since we don't have the desired AudioTrack sample rate,
1113 // format, flags, etc. This may result in some discrepancy for functions that utilize
1114 // getOutput() solely on audio_stream_type such as AudioSystem::getOutputFrameCount()
1115 // and AudioSystem::getOutputSamplingRate().
1116
François Gaffie11d30102018-11-02 16:09:09 +01001117 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Mingyu Shih75563d32023-05-24 04:47:40 +08001118 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
1119 if (stream == AUDIO_STREAM_MUSIC &&
1120 property_get_bool("audio.deep_buffer.media", false /* default_value */)) {
1121 flags = AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
1122 }
1123 const audio_io_handle_t output = selectOutput(outputs, flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001124
François Gaffie11d30102018-11-02 16:09:09 +01001125 ALOGV("getOutput() stream %d selected devices %s, output %d", stream,
1126 devices.toString().c_str(), output);
Eric Laurentf4e63452017-11-06 19:31:46 +00001127 return output;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001128}
1129
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001130status_t AudioPolicyManager::getAudioAttributes(audio_attributes_t *dstAttr,
1131 const audio_attributes_t *srcAttr,
1132 audio_stream_type_t srcStream)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001133{
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001134 if (srcAttr != NULL) {
1135 if (!isValidAttributes(srcAttr)) {
1136 ALOGE("%s invalid attributes: usage=%d content=%d flags=0x%x tags=[%s]",
1137 __func__,
1138 srcAttr->usage, srcAttr->content_type, srcAttr->flags,
1139 srcAttr->tags);
1140 return BAD_VALUE;
1141 }
1142 *dstAttr = *srcAttr;
1143 } else {
1144 if (srcStream < AUDIO_STREAM_MIN || srcStream >= AUDIO_STREAM_PUBLIC_CNT) {
1145 ALOGE("%s: invalid stream type", __func__);
1146 return BAD_VALUE;
1147 }
François Gaffiec005e562018-11-06 15:04:49 +01001148 *dstAttr = mEngine->getAttributesForStreamType(srcStream);
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001149 }
Eric Laurent22fcda22019-05-17 16:28:47 -07001150
1151 // Only honor audibility enforced when required. The client will be
1152 // forced to reconnect if the forced usage changes.
1153 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Mikhail Naganov55773032020-10-01 15:08:13 -07001154 dstAttr->flags = static_cast<audio_flags_mask_t>(
1155 dstAttr->flags & ~AUDIO_FLAG_AUDIBILITY_ENFORCED);
Eric Laurent22fcda22019-05-17 16:28:47 -07001156 }
1157
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001158 return NO_ERROR;
1159}
1160
Kevin Rocard153f92d2018-12-18 18:33:28 -08001161status_t AudioPolicyManager::getOutputForAttrInt(
1162 audio_attributes_t *resultAttr,
1163 audio_io_handle_t *output,
1164 audio_session_t session,
1165 const audio_attributes_t *attr,
1166 audio_stream_type_t *stream,
1167 uid_t uid,
jiabinf1c73972022-04-14 16:28:52 -07001168 audio_config_t *config,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001169 audio_output_flags_t *flags,
1170 audio_port_handle_t *selectedDeviceId,
1171 bool *isRequestedDeviceForExclusiveUse,
Eric Laurentc529cf62020-04-17 18:19:10 -07001172 std::vector<sp<AudioPolicyMix>> *secondaryMixes,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001173 output_type_t *outputType,
jiabinc658e452022-10-21 20:52:21 +00001174 bool *isSpatialized,
1175 bool *isBitPerfect)
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001176{
François Gaffiec005e562018-11-06 15:04:49 +01001177 DeviceVector outputDevices;
Francois Gaffie716e1432019-01-14 16:58:59 +01001178 const audio_port_handle_t requestedPortId = *selectedDeviceId;
François Gaffie11d30102018-11-02 16:09:09 +01001179 DeviceVector msdDevices = getMsdAudioOutDevices();
François Gaffiec005e562018-11-06 15:04:49 +01001180 const sp<DeviceDescriptor> requestedDevice =
1181 mAvailableOutputDevices.getDeviceFromId(requestedPortId);
1182
Eric Laurent8a1095a2019-11-08 14:44:16 -08001183 *outputType = API_OUTPUT_INVALID;
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001184 *isSpatialized = false;
1185
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001186 status_t status = getAudioAttributes(resultAttr, attr, *stream);
1187 if (status != NO_ERROR) {
1188 return status;
Eric Laurent8f42ea12018-08-08 09:08:25 -07001189 }
Kevin Rocardb99cc752019-03-21 20:52:24 -07001190 if (auto it = mAllowedCapturePolicies.find(uid); it != end(mAllowedCapturePolicies)) {
Mikhail Naganov55773032020-10-01 15:08:13 -07001191 resultAttr->flags = static_cast<audio_flags_mask_t>(resultAttr->flags | it->second);
Kevin Rocardb99cc752019-03-21 20:52:24 -07001192 }
François Gaffiec005e562018-11-06 15:04:49 +01001193 *stream = mEngine->getStreamTypeForAttributes(*resultAttr);
Eric Laurent8f42ea12018-08-08 09:08:25 -07001194
François Gaffiec005e562018-11-06 15:04:49 +01001195 ALOGV("%s() attributes=%s stream=%s session %d selectedDeviceId %d", __func__,
1196 toString(*resultAttr).c_str(), toString(*stream).c_str(), session, requestedPortId);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001197
Oscar Azucena873d10f2023-01-12 18:34:42 -08001198 bool usePrimaryOutputFromPolicyMixes = false;
1199
Kevin Rocard153f92d2018-12-18 18:33:28 -08001200 // The primary output is the explicit routing (eg. setPreferredDevice) if specified,
1201 // otherwise, fallback to the dynamic policies, if none match, query the engine.
1202 // Secondary outputs are always found by dynamic policies as the engine do not support them
Eric Laurentc529cf62020-04-17 18:19:10 -07001203 sp<AudioPolicyMix> primaryMix;
Dean Wheatleyd082f472022-02-04 11:10:48 +11001204 const audio_config_base_t clientConfig = {.sample_rate = config->sample_rate,
1205 .channel_mask = config->channel_mask,
1206 .format = config->format,
1207 };
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02001208 status = mPolicyMixes.getOutputForAttr(*resultAttr, clientConfig, uid, session, *flags,
Oscar Azucena873d10f2023-01-12 18:34:42 -08001209 mAvailableOutputDevices, requestedDevice, primaryMix,
1210 secondaryMixes, usePrimaryOutputFromPolicyMixes);
Kevin Rocard94114a22019-04-01 19:38:23 -07001211 if (status != OK) {
1212 return status;
Kevin Rocard153f92d2018-12-18 18:33:28 -08001213 }
Kevin Rocard94114a22019-04-01 19:38:23 -07001214
Kevin Rocard153f92d2018-12-18 18:33:28 -08001215 // FIXME: in case of RENDER policy, the output capabilities should be checked
Dean Wheatleyd082f472022-02-04 11:10:48 +11001216 if ((secondaryMixes != nullptr && !secondaryMixes->empty())
1217 && !audio_is_linear_pcm(config->format)) {
1218 ALOGD("%s: rejecting request as secondary mixes only support pcm", __func__);
Kevin Rocard153f92d2018-12-18 18:33:28 -08001219 return BAD_VALUE;
1220 }
1221 if (usePrimaryOutputFromPolicyMixes) {
jiabin24ff57a2023-11-27 21:06:51 +00001222 sp<DeviceDescriptor> policyMixDevice =
Eric Laurentc529cf62020-04-17 18:19:10 -07001223 mAvailableOutputDevices.getDevice(primaryMix->mDeviceType,
1224 primaryMix->mDeviceAddress,
1225 AUDIO_FORMAT_DEFAULT);
1226 sp<SwAudioOutputDescriptor> policyDesc = primaryMix->getOutput();
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001227 bool tryDirectForFlags = policyDesc == nullptr ||
jiabin24ff57a2023-11-27 21:06:51 +00001228 (policyDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) ||
1229 (*flags & (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ));
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001230 // if a direct output can be opened to deliver the track's multi-channel content to the
1231 // output rather than being downmixed by the primary output, then use this direct
1232 // output by by-passing the primary mix if possible, otherwise fall-through to primary
1233 // mix.
1234 bool tryDirectForChannelMask = policyDesc != nullptr
1235 && (audio_channel_count_from_out_mask(policyDesc->getConfig().channel_mask) <
1236 audio_channel_count_from_out_mask(config->channel_mask));
jiabin24ff57a2023-11-27 21:06:51 +00001237 if (policyMixDevice != nullptr && (tryDirectForFlags || tryDirectForChannelMask)) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001238 audio_io_handle_t newOutput;
1239 status = openDirectOutput(
1240 *stream, session, config,
1241 (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT),
jiabin24ff57a2023-11-27 21:06:51 +00001242 DeviceVector(policyMixDevice), &newOutput);
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001243 if (status == NO_ERROR) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001244 policyDesc = mOutputs.valueFor(newOutput);
1245 primaryMix->setOutput(policyDesc);
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001246 } else if (tryDirectForFlags) {
jiabin24ff57a2023-11-27 21:06:51 +00001247 ALOGW("%s, failed open direct, status: %d", __func__, status);
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001248 policyDesc = nullptr;
1249 } // otherwise use primary if available.
Eric Laurentc529cf62020-04-17 18:19:10 -07001250 }
1251 if (policyDesc != nullptr) {
1252 policyDesc->mPolicyMix = primaryMix;
1253 *output = policyDesc->mIoHandle;
jiabin24ff57a2023-11-27 21:06:51 +00001254 *selectedDeviceId = policyMixDevice != nullptr ? policyMixDevice->getId()
1255 : AUDIO_PORT_HANDLE_NONE;
1256 if ((policyDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != AUDIO_OUTPUT_FLAG_DIRECT) {
1257 // Remove direct flag as it is not on a direct output.
1258 *flags = (audio_output_flags_t) (*flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
1259 }
Eric Laurent8a1095a2019-11-08 14:44:16 -08001260
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08001261 ALOGV("getOutputForAttr() returns output %d", *output);
1262 if (resultAttr->usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
1263 *outputType = API_OUT_MIX_PLAYBACK;
1264 } else {
1265 *outputType = API_OUTPUT_LEGACY;
1266 }
1267 return NO_ERROR;
jiabin24ff57a2023-11-27 21:06:51 +00001268 } else {
1269 if (policyMixDevice != nullptr) {
1270 ALOGE("%s, try to use primary mix but no output found", __func__);
1271 return INVALID_OPERATION;
1272 }
1273 // Fallback to default engine selection as the selected primary mix device is not
1274 // available.
Eric Laurent8a1095a2019-11-08 14:44:16 -08001275 }
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001276 }
François Gaffiec005e562018-11-06 15:04:49 +01001277 // Virtual sources must always be dynamicaly or explicitly routed
1278 if (resultAttr->usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
1279 ALOGW("getOutputForAttr() no policy mix found for usage AUDIO_USAGE_VIRTUAL_SOURCE");
1280 return BAD_VALUE;
1281 }
1282 // explicit routing managed by getDeviceForStrategy in APM is now handled by engine
1283 // in order to let the choice of the order to future vendor engine
1284 outputDevices = mEngine->getOutputDevicesForAttributes(*resultAttr, requestedDevice, false);
Scott Randolph7b1fd232018-06-18 15:33:03 -07001285
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001286 if ((resultAttr->flags & AUDIO_FLAG_HW_AV_SYNC) != 0) {
Nadav Bar766fb022018-01-07 12:18:03 +02001287 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
Eric Laurent93c3d412014-08-01 14:48:35 -07001288 }
1289
Nadav Barb2f18162018-07-18 13:01:53 +03001290 // Set incall music only if device was explicitly set, and fallback to the device which is
1291 // chosen by the engine if not.
1292 // FIXME: provide a more generic approach which is not device specific and move this back
1293 // to getOutputForDevice.
Nadav Bar20919492018-11-20 10:20:51 +02001294 // TODO: Remove check of AUDIO_STREAM_MUSIC once migration is completed on the app side.
jiabin9a3361e2019-10-01 09:38:30 -07001295 if (outputDevices.onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_TELEPHONY_TX) &&
François Gaffiec005e562018-11-06 15:04:49 +01001296 (*stream == AUDIO_STREAM_MUSIC || resultAttr->usage == AUDIO_USAGE_VOICE_COMMUNICATION) &&
Nadav Barb2f18162018-07-18 13:01:53 +03001297 audio_is_linear_pcm(config->format) &&
Eric Laurent74b71512019-11-06 17:21:57 -08001298 isCallAudioAccessible()) {
Francois Gaffie716e1432019-01-14 16:58:59 +01001299 if (requestedPortId != AUDIO_PORT_HANDLE_NONE) {
Nadav Barb2f18162018-07-18 13:01:53 +03001300 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_INCALL_MUSIC;
François Gaffief579db52018-11-13 11:25:16 +01001301 *isRequestedDeviceForExclusiveUse = true;
Nadav Barb2f18162018-07-18 13:01:53 +03001302 }
1303 }
1304
François Gaffiec005e562018-11-06 15:04:49 +01001305 ALOGV("%s() device %s, sampling rate %d, format %#x, channel mask %#x, flags %#x stream %s",
1306 __func__, outputDevices.toString().c_str(), config->sample_rate, config->format,
1307 config->channel_mask, *flags, toString(*stream).c_str());
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001308
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001309 *output = AUDIO_IO_HANDLE_NONE;
François Gaffie11d30102018-11-02 16:09:09 +01001310 if (!msdDevices.isEmpty()) {
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001311 *output = getOutputForDevices(msdDevices, session, resultAttr, config, flags, isSpatialized);
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001312 if (*output != AUDIO_IO_HANDLE_NONE && setMsdOutputPatches(&outputDevices) == NO_ERROR) {
François Gaffiec005e562018-11-06 15:04:49 +01001313 ALOGV("%s() Using MSD devices %s instead of devices %s",
1314 __func__, msdDevices.toString().c_str(), outputDevices.toString().c_str());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001315 } else {
1316 *output = AUDIO_IO_HANDLE_NONE;
1317 }
1318 }
1319 if (*output == AUDIO_IO_HANDLE_NONE) {
jiabina84c3d32022-12-02 18:59:55 +00001320 sp<PreferredMixerAttributesInfo> info = nullptr;
1321 if (outputDevices.size() == 1) {
1322 info = getPreferredMixerAttributesInfo(
1323 outputDevices.itemAt(0)->getId(),
jiabind9a58d32023-06-01 17:57:30 +00001324 mEngine->getProductStrategyForAttributes(*resultAttr),
1325 true /*activeBitPerfectPreferred*/);
jiabin5eaf0962022-12-20 20:11:38 +00001326 // Only use preferred mixer if the uid matches or the preferred mixer is bit-perfect
1327 // and it is currently active.
1328 if (info != nullptr && info->getUid() != uid &&
1329 ((info->getFlags() & AUDIO_OUTPUT_FLAG_BIT_PERFECT) == AUDIO_OUTPUT_FLAG_NONE ||
1330 info->getActiveClientCount() == 0)) {
jiabina84c3d32022-12-02 18:59:55 +00001331 info = nullptr;
1332 }
1333 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001334 *output = getOutputForDevices(outputDevices, session, resultAttr, config,
jiabina84c3d32022-12-02 18:59:55 +00001335 flags, isSpatialized, info, resultAttr->flags & AUDIO_FLAG_MUTE_HAPTIC);
jiabin5eaf0962022-12-20 20:11:38 +00001336 // The client will be active if the client is currently preferred mixer owner and the
1337 // requested configuration matches the preferred mixer configuration.
jiabinc658e452022-10-21 20:52:21 +00001338 *isBitPerfect = (info != nullptr
1339 && (info->getFlags() & AUDIO_OUTPUT_FLAG_BIT_PERFECT) != AUDIO_OUTPUT_FLAG_NONE
jiabin5eaf0962022-12-20 20:11:38 +00001340 && info->getUid() == uid
1341 && *output != AUDIO_IO_HANDLE_NONE
1342 // When bit-perfect output is selected for the preferred mixer attributes owner,
1343 // only need to consider the config matches.
1344 && mOutputs.valueFor(*output)->isConfigurationMatched(
1345 clientConfig, AUDIO_OUTPUT_FLAG_NONE));
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001346 }
Eric Laurente83b55d2014-11-14 10:06:21 -08001347 if (*output == AUDIO_IO_HANDLE_NONE) {
jiabinf1c73972022-04-14 16:28:52 -07001348 AudioProfileVector profiles;
1349 status_t ret = getProfilesForDevices(outputDevices, profiles, *flags, false /*isInput*/);
1350 if (ret == NO_ERROR && !profiles.empty()) {
Robert Wub98ff1b2023-06-15 22:53:58 +00001351 const auto channels = profiles[0]->getChannels();
1352 if (!channels.empty() && (channels.find(config->channel_mask) == channels.end())) {
1353 config->channel_mask = *channels.begin();
1354 }
1355 const auto sampleRates = profiles[0]->getSampleRates();
1356 if (!sampleRates.empty() &&
1357 (sampleRates.find(config->sample_rate) == sampleRates.end())) {
1358 config->sample_rate = *sampleRates.begin();
1359 }
jiabinf1c73972022-04-14 16:28:52 -07001360 config->format = profiles[0]->getFormat();
1361 }
Eric Laurente83b55d2014-11-14 10:06:21 -08001362 return INVALID_OPERATION;
1363 }
Paul McLeanaa981192015-03-21 09:55:15 -07001364
François Gaffiec005e562018-11-06 15:04:49 +01001365 *selectedDeviceId = getFirstDeviceId(outputDevices);
Michael Chan6fb34492020-12-08 15:44:49 +11001366 for (auto &outputDevice : outputDevices) {
Mikhail Naganov68e3f642023-04-28 13:06:32 -07001367 if (outputDevice->getId() == mConfig->getDefaultOutputDevice()->getId()) {
Michael Chan6fb34492020-12-08 15:44:49 +11001368 *selectedDeviceId = outputDevice->getId();
1369 break;
1370 }
1371 }
Eric Laurent2ac76942017-06-22 17:17:09 -07001372
Eric Laurent8a1095a2019-11-08 14:44:16 -08001373 if (outputDevices.onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_TELEPHONY_TX)) {
1374 *outputType = API_OUTPUT_TELEPHONY_TX;
1375 } else {
1376 *outputType = API_OUTPUT_LEGACY;
1377 }
1378
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001379 ALOGV("%s returns output %d selectedDeviceId %d", __func__, *output, *selectedDeviceId);
1380
1381 return NO_ERROR;
1382}
1383
1384status_t AudioPolicyManager::getOutputForAttr(const audio_attributes_t *attr,
1385 audio_io_handle_t *output,
1386 audio_session_t session,
1387 audio_stream_type_t *stream,
Svet Ganov3e5f14f2021-05-13 22:51:08 +00001388 const AttributionSourceState& attributionSource,
jiabinf1c73972022-04-14 16:28:52 -07001389 audio_config_t *config,
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001390 audio_output_flags_t *flags,
1391 audio_port_handle_t *selectedDeviceId,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001392 audio_port_handle_t *portId,
Eric Laurent8a1095a2019-11-08 14:44:16 -08001393 std::vector<audio_io_handle_t> *secondaryOutputs,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001394 output_type_t *outputType,
jiabinc658e452022-10-21 20:52:21 +00001395 bool *isSpatialized,
1396 bool *isBitPerfect)
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001397{
1398 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
1399 if (*portId != AUDIO_PORT_HANDLE_NONE) {
1400 return INVALID_OPERATION;
1401 }
Philip P. Moltmannbda45752020-07-17 16:41:18 -07001402 const uid_t uid = VALUE_OR_RETURN_STATUS(
Svet Ganov3e5f14f2021-05-13 22:51:08 +00001403 aidl2legacy_int32_t_uid_t(attributionSource.uid));
Francois Gaffie716e1432019-01-14 16:58:59 +01001404 const audio_port_handle_t requestedPortId = *selectedDeviceId;
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001405 audio_attributes_t resultAttr;
François Gaffief579db52018-11-13 11:25:16 +01001406 bool isRequestedDeviceForExclusiveUse = false;
Eric Laurentc529cf62020-04-17 18:19:10 -07001407 std::vector<sp<AudioPolicyMix>> secondaryMixes;
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001408 const sp<DeviceDescriptor> requestedDevice =
1409 mAvailableOutputDevices.getDeviceFromId(requestedPortId);
1410
1411 // Prevent from storing invalid requested device id in clients
1412 const audio_port_handle_t sanitizedRequestedPortId =
1413 requestedDevice != nullptr ? requestedPortId : AUDIO_PORT_HANDLE_NONE;
1414 *selectedDeviceId = sanitizedRequestedPortId;
1415
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001416 status_t status = getOutputForAttrInt(&resultAttr, output, session, attr, stream, uid,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001417 config, flags, selectedDeviceId, &isRequestedDeviceForExclusiveUse,
jiabinc658e452022-10-21 20:52:21 +00001418 secondaryOutputs != nullptr ? &secondaryMixes : nullptr, outputType, isSpatialized,
1419 isBitPerfect);
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001420 if (status != NO_ERROR) {
1421 return status;
1422 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001423 std::vector<wp<SwAudioOutputDescriptor>> weakSecondaryOutputDescs;
Eric Laurentc529cf62020-04-17 18:19:10 -07001424 if (secondaryOutputs != nullptr) {
1425 for (auto &secondaryMix : secondaryMixes) {
1426 sp<SwAudioOutputDescriptor> outputDesc = secondaryMix->getOutput();
1427 if (outputDesc != nullptr &&
1428 outputDesc->mIoHandle != AUDIO_IO_HANDLE_NONE) {
1429 secondaryOutputs->push_back(outputDesc->mIoHandle);
1430 weakSecondaryOutputDescs.push_back(outputDesc);
1431 }
1432 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001433 }
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001434
Eric Laurent8fc147b2018-07-22 19:13:55 -07001435 audio_config_base_t clientConfig = {.sample_rate = config->sample_rate,
Nick Desaulniersa30e3202019-10-18 13:38:23 -07001436 .channel_mask = config->channel_mask,
Eric Laurent8fc147b2018-07-22 19:13:55 -07001437 .format = config->format,
Nick Desaulniersa30e3202019-10-18 13:38:23 -07001438 };
jiabin4ef93452019-09-10 14:29:54 -07001439 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurent8f42ea12018-08-08 09:08:25 -07001440
Eric Laurentc209fe42020-06-05 18:11:23 -07001441 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(*output);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001442 sp<TrackClientDescriptor> clientDesc =
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001443 new TrackClientDescriptor(*portId, uid, session, resultAttr, clientConfig,
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001444 sanitizedRequestedPortId, *stream,
François Gaffiec005e562018-11-06 15:04:49 +01001445 mEngine->getProductStrategyForAttributes(resultAttr),
François Gaffieaaac0fd2018-11-22 17:56:39 +01001446 toVolumeSource(resultAttr),
Kevin Rocard153f92d2018-12-18 18:33:28 -08001447 *flags, isRequestedDeviceForExclusiveUse,
Eric Laurentc209fe42020-06-05 18:11:23 -07001448 std::move(weakSecondaryOutputDescs),
1449 outputDesc->mPolicyMix);
Andy Hung39efb7a2018-09-26 15:39:28 -07001450 outputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001451
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001452 ALOGV("%s() returns output %d requestedPortId %d selectedDeviceId %d for port ID %d", __func__,
1453 *output, requestedPortId, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07001454
Eric Laurente83b55d2014-11-14 10:06:21 -08001455 return NO_ERROR;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001456}
1457
Eric Laurentc529cf62020-04-17 18:19:10 -07001458status_t AudioPolicyManager::openDirectOutput(audio_stream_type_t stream,
1459 audio_session_t session,
1460 const audio_config_t *config,
1461 audio_output_flags_t flags,
1462 const DeviceVector &devices,
1463 audio_io_handle_t *output) {
1464
1465 *output = AUDIO_IO_HANDLE_NONE;
1466
1467 // skip direct output selection if the request can obviously be attached to a mixed output
1468 // and not explicitly requested
1469 if (((flags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
1470 audio_is_linear_pcm(config->format) && config->sample_rate <= SAMPLE_RATE_HZ_MAX &&
1471 audio_channel_count_from_out_mask(config->channel_mask) <= 2) {
1472 return NAME_NOT_FOUND;
1473 }
1474
1475 // Do not allow offloading if one non offloadable effect is enabled or MasterMono is enabled.
1476 // This prevents creating an offloaded track and tearing it down immediately after start
1477 // when audioflinger detects there is an active non offloadable effect.
1478 // FIXME: We should check the audio session here but we do not have it in this context.
1479 // This may prevent offloading in rare situations where effects are left active by apps
1480 // in the background.
1481 sp<IOProfile> profile;
1482 if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) ||
1483 !(mEffects.isNonOffloadableEffectEnabled() || mMasterMono)) {
1484 profile = getProfileForOutput(
1485 devices, config->sample_rate, config->format, config->channel_mask,
1486 flags, true /* directOnly */);
1487 }
1488
1489 if (profile == nullptr) {
1490 return NAME_NOT_FOUND;
1491 }
1492
1493 // exclusive outputs for MMAP and Offload are enforced by different session ids.
1494 for (size_t i = 0; i < mOutputs.size(); i++) {
1495 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
1496 if (!desc->isDuplicated() && (profile == desc->mProfile)) {
1497 // reuse direct output if currently open by the same client
1498 // and configured with same parameters
1499 if ((config->sample_rate == desc->getSamplingRate()) &&
1500 (config->format == desc->getFormat()) &&
1501 (config->channel_mask == desc->getChannelMask()) &&
1502 (session == desc->mDirectClientSession)) {
1503 desc->mDirectOpenCount++;
Eric Laurentfecbceb2021-02-09 14:46:43 +01001504 ALOGV("%s reusing direct output %d for session %d", __func__,
Eric Laurentc529cf62020-04-17 18:19:10 -07001505 mOutputs.keyAt(i), session);
1506 *output = mOutputs.keyAt(i);
1507 return NO_ERROR;
1508 }
1509 }
1510 }
1511
1512 if (!profile->canOpenNewIo()) {
1513 return NAME_NOT_FOUND;
1514 }
1515
1516 sp<SwAudioOutputDescriptor> outputDesc =
1517 new SwAudioOutputDescriptor(profile, mpClientInterface);
1518
Michael Chan6fb34492020-12-08 15:44:49 +11001519 // An MSD patch may be using the only output stream that can service this request. Release
1520 // all MSD patches to prioritize this request over any active output on MSD.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001521 releaseMsdOutputPatches(devices);
Eric Laurentc529cf62020-04-17 18:19:10 -07001522
Eric Laurentf1f22e72021-07-13 14:04:14 +02001523 status_t status =
1524 outputDesc->open(config, nullptr /* mixerConfig */, devices, stream, flags, output);
Eric Laurentc529cf62020-04-17 18:19:10 -07001525
1526 // only accept an output with the requested parameters
1527 if (status != NO_ERROR ||
1528 (config->sample_rate != 0 && config->sample_rate != outputDesc->getSamplingRate()) ||
1529 (config->format != AUDIO_FORMAT_DEFAULT && config->format != outputDesc->getFormat()) ||
1530 (config->channel_mask != 0 && config->channel_mask != outputDesc->getChannelMask())) {
1531 ALOGV("%s failed opening direct output: output %d sample rate %d %d,"
1532 "format %d %d, channel mask %04x %04x", __func__, *output, config->sample_rate,
1533 outputDesc->getSamplingRate(), config->format, outputDesc->getFormat(),
1534 config->channel_mask, outputDesc->getChannelMask());
1535 if (*output != AUDIO_IO_HANDLE_NONE) {
1536 outputDesc->close();
1537 }
1538 // fall back to mixer output if possible when the direct output could not be open
1539 if (audio_is_linear_pcm(config->format) &&
1540 config->sample_rate <= SAMPLE_RATE_HZ_MAX) {
1541 return NAME_NOT_FOUND;
1542 }
1543 *output = AUDIO_IO_HANDLE_NONE;
1544 return BAD_VALUE;
1545 }
1546 outputDesc->mDirectOpenCount = 1;
1547 outputDesc->mDirectClientSession = session;
1548
1549 addOutput(*output, outputDesc);
1550 mPreviousOutputs = mOutputs;
1551 ALOGV("%s returns new direct output %d", __func__, *output);
1552 mpClientInterface->onAudioPortListUpdate();
1553 return NO_ERROR;
1554}
1555
François Gaffie11d30102018-11-02 16:09:09 +01001556audio_io_handle_t AudioPolicyManager::getOutputForDevices(
1557 const DeviceVector &devices,
Kevin Rocard169753c2017-03-06 14:18:23 -08001558 audio_session_t session,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001559 const audio_attributes_t *attr,
Eric Laurentfe231122017-11-17 17:48:06 -08001560 const audio_config_t *config,
jiabine375d412019-02-26 12:54:53 -08001561 audio_output_flags_t *flags,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001562 bool *isSpatialized,
jiabina84c3d32022-12-02 18:59:55 +00001563 sp<PreferredMixerAttributesInfo> prefMixerConfigInfo,
jiabine375d412019-02-26 12:54:53 -08001564 bool forceMutingHaptic)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001565{
Andy Hungc88b0642018-04-27 15:42:35 -07001566 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001567
jiabine375d412019-02-26 12:54:53 -08001568 // Discard haptic channel mask when forcing muting haptic channels.
1569 audio_channel_mask_t channelMask = forceMutingHaptic
Mikhail Naganov55773032020-10-01 15:08:13 -07001570 ? static_cast<audio_channel_mask_t>(config->channel_mask & ~AUDIO_CHANNEL_HAPTIC_ALL)
1571 : config->channel_mask;
jiabine375d412019-02-26 12:54:53 -08001572
Eric Laurente552edb2014-03-10 17:42:56 -07001573 // open a direct output if required by specified parameters
1574 //force direct flag if offload flag is set: offloading implies a direct output stream
1575 // and all common behaviors are driven by checking only the direct flag
1576 // this should normally be set appropriately in the policy configuration file
Nadav Bar766fb022018-01-07 12:18:03 +02001577 if ((*flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1578 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurente552edb2014-03-10 17:42:56 -07001579 }
Nadav Bar766fb022018-01-07 12:18:03 +02001580 if ((*flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
1581 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent93c3d412014-08-01 14:48:35 -07001582 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001583
1584 audio_stream_type_t stream = mEngine->getStreamTypeForAttributes(*attr);
1585
Eric Laurente83b55d2014-11-14 10:06:21 -08001586 // only allow deep buffering for music stream type
1587 if (stream != AUDIO_STREAM_MUSIC) {
Nadav Bar766fb022018-01-07 12:18:03 +02001588 *flags = (audio_output_flags_t)(*flags &~AUDIO_OUTPUT_FLAG_DEEP_BUFFER);
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -07001589 } else if (/* stream == AUDIO_STREAM_MUSIC && */
Nadav Bar766fb022018-01-07 12:18:03 +02001590 *flags == AUDIO_OUTPUT_FLAG_NONE &&
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -07001591 property_get_bool("audio.deep_buffer.media", false /* default_value */)) {
1592 // use DEEP_BUFFER as default output for music stream type
Nadav Bar766fb022018-01-07 12:18:03 +02001593 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
Eric Laurente83b55d2014-11-14 10:06:21 -08001594 }
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -07001595 if (stream == AUDIO_STREAM_TTS) {
Nadav Bar766fb022018-01-07 12:18:03 +02001596 *flags = AUDIO_OUTPUT_FLAG_TTS;
Haynes Mathew George84c621e2017-04-25 11:41:50 -07001597 } else if (stream == AUDIO_STREAM_VOICE_CALL &&
Nadav Bar20919492018-11-20 10:20:51 +02001598 audio_is_linear_pcm(config->format) &&
1599 (*flags & AUDIO_OUTPUT_FLAG_INCALL_MUSIC) == 0) {
Nadav Bar766fb022018-01-07 12:18:03 +02001600 *flags = (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_VOIP_RX |
Haynes Mathew George84c621e2017-04-25 11:41:50 -07001601 AUDIO_OUTPUT_FLAG_DIRECT);
1602 ALOGV("Set VoIP and Direct output flags for PCM format");
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -07001603 }
Eric Laurente552edb2014-03-10 17:42:56 -07001604
Carter Hsua3abb402021-10-26 11:11:20 +08001605 // Attach the Ultrasound flag for the AUDIO_CONTENT_TYPE_ULTRASOUND
1606 if (attr->content_type == AUDIO_CONTENT_TYPE_ULTRASOUND) {
1607 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_ULTRASOUND);
1608 }
1609
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001610 *isSpatialized = false;
Eric Laurentfa0f6742021-08-17 18:39:44 +02001611 if (mSpatializerOutput != nullptr
Andy Hung9dd1a5b2022-05-10 15:39:39 -07001612 && canBeSpatializedInt(attr, config, devices.toTypeAddrVector())) {
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001613 *isSpatialized = true;
Eric Laurentfa0f6742021-08-17 18:39:44 +02001614 return mSpatializerOutput->mIoHandle;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001615 }
1616
Eric Laurentc529cf62020-04-17 18:19:10 -07001617 audio_config_t directConfig = *config;
1618 directConfig.channel_mask = channelMask;
1619 status_t status = openDirectOutput(stream, session, &directConfig, *flags, devices, &output);
1620 if (status != NAME_NOT_FOUND) {
Eric Laurente552edb2014-03-10 17:42:56 -07001621 return output;
1622 }
1623
Eric Laurent14cbfca2016-03-17 09:42:16 -07001624 // A request for HW A/V sync cannot fallback to a mixed output because time
1625 // stamps are embedded in audio data
Phil Burk2d059932018-02-15 15:55:11 -08001626 if ((*flags & (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ)) != 0) {
Eric Laurent14cbfca2016-03-17 09:42:16 -07001627 return AUDIO_IO_HANDLE_NONE;
1628 }
Pierre Couillaude73496b2023-03-06 16:19:05 +00001629 // A request for Tuner cannot fallback to a mixed output
1630 if ((directConfig.offload_info.content_id || directConfig.offload_info.sync_id)) {
1631 return AUDIO_IO_HANDLE_NONE;
1632 }
Eric Laurent14cbfca2016-03-17 09:42:16 -07001633
Eric Laurente552edb2014-03-10 17:42:56 -07001634 // ignoring channel mask due to downmix capability in mixer
1635
1636 // open a non direct output
1637
1638 // for non direct outputs, only PCM is supported
Eric Laurentfe231122017-11-17 17:48:06 -08001639 if (audio_is_linear_pcm(config->format)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001640 // get which output is suitable for the specified stream. The actual
1641 // routing change will happen when startOutput() will be called
François Gaffie11d30102018-11-02 16:09:09 +01001642 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
jiabina84c3d32022-12-02 18:59:55 +00001643 if (prefMixerConfigInfo != nullptr) {
1644 for (audio_io_handle_t outputHandle : outputs) {
1645 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(outputHandle);
1646 if (outputDesc->mProfile == prefMixerConfigInfo->getProfile()) {
1647 output = outputHandle;
1648 break;
1649 }
1650 }
1651 if (output == AUDIO_IO_HANDLE_NONE) {
1652 // No output open with the preferred profile. Open a new one.
1653 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
1654 config.channel_mask = prefMixerConfigInfo->getConfigBase().channel_mask;
1655 config.sample_rate = prefMixerConfigInfo->getConfigBase().sample_rate;
1656 config.format = prefMixerConfigInfo->getConfigBase().format;
1657 sp<SwAudioOutputDescriptor> preferredOutput = openOutputWithProfileAndDevice(
1658 prefMixerConfigInfo->getProfile(), devices, nullptr /*mixerConfig*/,
1659 &config, prefMixerConfigInfo->getFlags());
1660 if (preferredOutput == nullptr) {
1661 ALOGE("%s failed to open output with preferred mixer config", __func__);
1662 } else {
1663 output = preferredOutput->mIoHandle;
1664 }
1665 }
1666 } else {
1667 // at this stage we should ignore the DIRECT flag as no direct output could be
1668 // found earlier
1669 *flags = (audio_output_flags_t) (*flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
1670 output = selectOutput(
1671 outputs, *flags, config->format, channelMask, config->sample_rate, session);
1672 }
Eric Laurente552edb2014-03-10 17:42:56 -07001673 }
François Gaffie11d30102018-11-02 16:09:09 +01001674 ALOGW_IF((output == 0), "getOutputForDevices() could not find output for stream %d, "
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001675 "sampling rate %d, format %#x, channels %#x, flags %#x",
jiabine375d412019-02-26 12:54:53 -08001676 stream, config->sample_rate, config->format, channelMask, *flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001677
Eric Laurente552edb2014-03-10 17:42:56 -07001678 return output;
1679}
1680
Mikhail Naganovf02f3672018-11-09 12:44:16 -08001681sp<DeviceDescriptor> AudioPolicyManager::getMsdAudioInDevice() const {
François Gaffie11d30102018-11-02 16:09:09 +01001682 auto msdInDevices = mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1683 mAvailableInputDevices);
1684 return msdInDevices.isEmpty()? nullptr : msdInDevices.itemAt(0);
1685}
1686
1687DeviceVector AudioPolicyManager::getMsdAudioOutDevices() const {
1688 return mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1689 mAvailableOutputDevices);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001690}
1691
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001692const AudioPatchCollection AudioPolicyManager::getMsdOutputPatches() const {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001693 AudioPatchCollection msdPatches;
Mikhail Naganov86112352018-10-04 09:02:49 -07001694 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1695 if (msdModule != 0) {
1696 for (size_t i = 0; i < mAudioPatches.size(); ++i) {
1697 sp<AudioPatch> patch = mAudioPatches.valueAt(i);
1698 for (size_t j = 0; j < patch->mPatch.num_sources; ++j) {
1699 const struct audio_port_config *source = &patch->mPatch.sources[j];
1700 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
1701 source->ext.device.hw_module == msdModule->getHandle()) {
François Gaffieafd4cea2019-11-18 15:50:22 +01001702 msdPatches.addAudioPatch(patch->getHandle(), patch);
Mikhail Naganov86112352018-10-04 09:02:49 -07001703 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001704 }
1705 }
1706 }
1707 return msdPatches;
1708}
1709
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02001710bool AudioPolicyManager::isMsdPatch(const audio_patch_handle_t &handle) const {
1711 ssize_t index = mAudioPatches.indexOfKey(handle);
1712 if (index < 0) {
1713 return false;
1714 }
1715 const sp<AudioPatch> patch = mAudioPatches.valueAt(index);
1716 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1717 if (msdModule == nullptr) {
1718 return false;
1719 }
1720 const struct audio_port_config *sink = &patch->mPatch.sinks[0];
1721 if (getMsdAudioOutDevices().contains(mAvailableOutputDevices.getDeviceFromId(sink->id))) {
1722 return true;
1723 }
1724 index = getMsdOutputPatches().indexOfKey(handle);
1725 if (index < 0) {
1726 return false;
1727 }
1728 return true;
1729}
1730
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001731status_t AudioPolicyManager::getMsdProfiles(bool hwAvSync,
1732 const InputProfileCollection &inputProfiles,
1733 const OutputProfileCollection &outputProfiles,
1734 const sp<DeviceDescriptor> &sourceDevice,
1735 const sp<DeviceDescriptor> &sinkDevice,
1736 AudioProfileVector& sourceProfiles,
1737 AudioProfileVector& sinkProfiles) const {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001738 if (inputProfiles.isEmpty()) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001739 ALOGE("%s() no input profiles for source module", __func__);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001740 return NO_INIT;
1741 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001742 if (outputProfiles.isEmpty()) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001743 ALOGE("%s() no output profiles for sink module", __func__);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001744 return NO_INIT;
1745 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001746 for (const auto &inProfile : inputProfiles) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001747 if (hwAvSync == ((inProfile->getFlags() & AUDIO_INPUT_FLAG_HW_AV_SYNC) != 0) &&
1748 inProfile->supportsDevice(sourceDevice)) {
1749 appendAudioProfiles(sourceProfiles, inProfile->getAudioProfiles());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001750 }
1751 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001752 for (const auto &outProfile : outputProfiles) {
Michael Chan6fb34492020-12-08 15:44:49 +11001753 if (hwAvSync == ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) &&
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001754 outProfile->supportsDevice(sinkDevice)) {
1755 appendAudioProfiles(sinkProfiles, outProfile->getAudioProfiles());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001756 }
1757 }
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001758 return NO_ERROR;
1759}
1760
1761status_t AudioPolicyManager::getBestMsdConfig(bool hwAvSync,
1762 const AudioProfileVector &sourceProfiles, const AudioProfileVector &sinkProfiles,
1763 audio_port_config *sourceConfig, audio_port_config *sinkConfig) const
1764{
Dean Wheatley16809da2022-12-09 14:55:46 +11001765 // Compressed formats for MSD module, ordered from most preferred to least preferred.
1766 static const std::vector<audio_format_t> formatsOrder = {{
1767 AUDIO_FORMAT_IEC60958, AUDIO_FORMAT_MAT_2_1, AUDIO_FORMAT_MAT_2_0, AUDIO_FORMAT_E_AC3,
Dean Wheatley0f27c602023-08-23 13:57:21 +10001768 AUDIO_FORMAT_AC3, AUDIO_FORMAT_PCM_FLOAT, AUDIO_FORMAT_PCM_32_BIT,
1769 AUDIO_FORMAT_PCM_8_24_BIT, AUDIO_FORMAT_PCM_24_BIT_PACKED, AUDIO_FORMAT_PCM_16_BIT }};
Dean Wheatley16809da2022-12-09 14:55:46 +11001770 static const std::vector<audio_channel_mask_t> channelMasksOrder = [](){
1771 // Channel position masks for MSD module, 3D > 2D > 1D ordering (most preferred to least
1772 // preferred).
1773 std::vector<audio_channel_mask_t> masks = {{
1774 AUDIO_CHANNEL_OUT_3POINT1POINT2, AUDIO_CHANNEL_OUT_3POINT0POINT2,
1775 AUDIO_CHANNEL_OUT_2POINT1POINT2, AUDIO_CHANNEL_OUT_2POINT0POINT2,
1776 AUDIO_CHANNEL_OUT_5POINT1, AUDIO_CHANNEL_OUT_STEREO }};
1777 // insert index masks (higher counts most preferred) as preferred over position masks
1778 for (int i = 1; i <= AUDIO_CHANNEL_COUNT_MAX; i++) {
1779 masks.insert(
1780 masks.begin(), audio_channel_mask_for_index_assignment_from_count(i));
1781 }
1782 return masks;
1783 }();
1784
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001785 struct audio_config_base bestSinkConfig;
Dean Wheatley16809da2022-12-09 14:55:46 +11001786 status_t result = findBestMatchingOutputConfig(sourceProfiles, sinkProfiles, formatsOrder,
1787 channelMasksOrder, true /*preferHigherSamplingRates*/, bestSinkConfig);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001788 if (result != NO_ERROR) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001789 ALOGD("%s() no matching config found for sink, hwAvSync: %d",
1790 __func__, hwAvSync);
Greg Kaiser83289652018-07-30 06:13:57 -07001791 return result;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001792 }
1793 sinkConfig->sample_rate = bestSinkConfig.sample_rate;
1794 sinkConfig->channel_mask = bestSinkConfig.channel_mask;
1795 sinkConfig->format = bestSinkConfig.format;
1796 // For encoded streams force direct flag to prevent downstream mixing.
1797 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1798 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_DIRECT);
Dean Wheatley5c9f0832019-11-21 13:39:31 +11001799 if (audio_is_iec61937_compatible(sinkConfig->format)) {
1800 // For formats compatible with IEC61937 encapsulation, assume that
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001801 // the input is IEC61937 framed (for proportional buffer sizing).
Dean Wheatley5c9f0832019-11-21 13:39:31 +11001802 // Add the AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO flag so downstream HAL can distinguish between
1803 // raw and IEC61937 framed streams.
1804 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1805 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO);
1806 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001807 sourceConfig->sample_rate = bestSinkConfig.sample_rate;
1808 // Specify exact channel mask to prevent guessing by bit count in PatchPanel.
Dean Wheatley16809da2022-12-09 14:55:46 +11001809 sourceConfig->channel_mask =
1810 audio_channel_mask_get_representation(bestSinkConfig.channel_mask)
1811 == AUDIO_CHANNEL_REPRESENTATION_INDEX ?
1812 bestSinkConfig.channel_mask : audio_channel_mask_out_to_in(bestSinkConfig.channel_mask);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001813 sourceConfig->format = bestSinkConfig.format;
1814 // Copy input stream directly without any processing (e.g. resampling).
1815 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1816 sourceConfig->flags.input | AUDIO_INPUT_FLAG_DIRECT);
1817 if (hwAvSync) {
1818 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1819 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
1820 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1821 sourceConfig->flags.input | AUDIO_INPUT_FLAG_HW_AV_SYNC);
1822 }
1823 const unsigned int config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE |
1824 AUDIO_PORT_CONFIG_CHANNEL_MASK | AUDIO_PORT_CONFIG_FORMAT | AUDIO_PORT_CONFIG_FLAGS;
1825 sinkConfig->config_mask |= config_mask;
1826 sourceConfig->config_mask |= config_mask;
1827 return NO_ERROR;
1828}
1829
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001830PatchBuilder AudioPolicyManager::buildMsdPatch(bool msdIsSource,
1831 const sp<DeviceDescriptor> &device) const
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001832{
1833 PatchBuilder patchBuilder;
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001834 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1835 ALOG_ASSERT(msdModule != nullptr, "MSD module not available");
1836 sp<HwModule> deviceModule = mHwModules.getModuleForDevice(device, AUDIO_FORMAT_DEFAULT);
1837 if (deviceModule == nullptr) {
1838 ALOGE("%s() unable to get module for %s", __func__, device->toString().c_str());
1839 return patchBuilder;
1840 }
1841 const InputProfileCollection inputProfiles = msdIsSource ?
1842 msdModule->getInputProfiles() : deviceModule->getInputProfiles();
1843 const OutputProfileCollection outputProfiles = msdIsSource ?
1844 deviceModule->getOutputProfiles() : msdModule->getOutputProfiles();
1845
1846 const sp<DeviceDescriptor> sourceDevice = msdIsSource ? getMsdAudioInDevice() : device;
1847 const sp<DeviceDescriptor> sinkDevice = msdIsSource ?
1848 device : getMsdAudioOutDevices().itemAt(0);
1849 patchBuilder.addSource(sourceDevice).addSink(sinkDevice);
1850
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001851 audio_port_config sourceConfig = patchBuilder.patch()->sources[0];
1852 audio_port_config sinkConfig = patchBuilder.patch()->sinks[0];
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001853 AudioProfileVector sourceProfiles;
1854 AudioProfileVector sinkProfiles;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001855 // TODO: Figure out whether MSD module has HW_AV_SYNC flag set in the AP config file.
1856 // For now, we just forcefully try with HwAvSync first.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001857 for (auto hwAvSync : { true, false }) {
1858 if (getMsdProfiles(hwAvSync, inputProfiles, outputProfiles, sourceDevice, sinkDevice,
1859 sourceProfiles, sinkProfiles) != NO_ERROR) {
1860 continue;
1861 }
1862 if (getBestMsdConfig(hwAvSync, sourceProfiles, sinkProfiles, &sourceConfig,
1863 &sinkConfig) == NO_ERROR) {
1864 // Found a matching config. Re-create PatchBuilder with this config.
1865 return (PatchBuilder()).addSource(sourceConfig).addSink(sinkConfig);
1866 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001867 }
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001868 ALOGV("%s() no matching config found. Fall through to default PCM patch"
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001869 " supporting PCM format conversion.", __func__);
1870 return patchBuilder;
1871}
1872
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001873status_t AudioPolicyManager::setMsdOutputPatches(const DeviceVector *outputDevices) {
Michael Chan6fb34492020-12-08 15:44:49 +11001874 DeviceVector devices;
1875 if (outputDevices != nullptr && outputDevices->size() > 0) {
1876 devices.add(*outputDevices);
1877 } else {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001878 // Use media strategy for unspecified output device. This should only
1879 // occur on checkForDeviceAndOutputChanges(). Device connection events may
1880 // therefore invalidate explicit routing requests.
Michael Chan6fb34492020-12-08 15:44:49 +11001881 devices = mEngine->getOutputDevicesForAttributes(
François Gaffiec005e562018-11-06 15:04:49 +01001882 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
Michael Chan6fb34492020-12-08 15:44:49 +11001883 LOG_ALWAYS_FATAL_IF(devices.isEmpty(), "no output device to set MSD patch");
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001884 }
Michael Chan6fb34492020-12-08 15:44:49 +11001885 std::vector<PatchBuilder> patchesToCreate;
1886 for (auto i = 0u; i < devices.size(); ++i) {
1887 ALOGV("%s() for device %s", __func__, devices[i]->toString().c_str());
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001888 patchesToCreate.push_back(buildMsdPatch(true /*msdIsSource*/, devices[i]));
Michael Chan6fb34492020-12-08 15:44:49 +11001889 }
1890 // Retain only the MSD patches associated with outputDevices request.
1891 // Tear down the others, and create new ones as needed.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001892 AudioPatchCollection patchesToRemove = getMsdOutputPatches();
Michael Chan6fb34492020-12-08 15:44:49 +11001893 for (auto it = patchesToCreate.begin(); it != patchesToCreate.end(); ) {
1894 auto retainedPatch = false;
1895 for (auto i = 0u; i < patchesToRemove.size(); ++i) {
1896 if (audio_patches_are_equal(it->patch(), &patchesToRemove[i]->mPatch)) {
1897 patchesToRemove.removeItemsAt(i);
1898 retainedPatch = true;
1899 break;
1900 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001901 }
Michael Chan6fb34492020-12-08 15:44:49 +11001902 if (retainedPatch) {
1903 it = patchesToCreate.erase(it);
1904 continue;
1905 }
1906 ++it;
1907 }
1908 if (patchesToCreate.size() == 0 && patchesToRemove.size() == 0) {
1909 return NO_ERROR;
1910 }
1911 for (auto i = 0u; i < patchesToRemove.size(); ++i) {
1912 auto &currentPatch = patchesToRemove.valueAt(i);
François Gaffieafd4cea2019-11-18 15:50:22 +01001913 releaseAudioPatch(currentPatch->getHandle(), mUidCached);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001914 }
Michael Chan6fb34492020-12-08 15:44:49 +11001915 status_t status = NO_ERROR;
1916 for (const auto &p : patchesToCreate) {
1917 auto currStatus = installPatch(__func__, -1 /*index*/, nullptr /*patchHandle*/,
1918 p.patch(), 0 /*delayMs*/, mUidCached, nullptr /*patchDescPtr*/);
1919 char message[256];
1920 snprintf(message, sizeof(message), "%s() %s: creating MSD patch from device:IN_BUS to "
1921 "device:%#x (format:%#x channels:%#x samplerate:%d)", __func__,
1922 currStatus == NO_ERROR ? "Success" : "Error",
1923 p.patch()->sinks[0].ext.device.type, p.patch()->sources[0].format,
1924 p.patch()->sources[0].channel_mask, p.patch()->sources[0].sample_rate);
1925 if (currStatus == NO_ERROR) {
1926 ALOGD("%s", message);
1927 } else {
1928 ALOGE("%s", message);
1929 if (status == NO_ERROR) {
1930 status = currStatus;
1931 }
1932 }
1933 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001934 return status;
1935}
1936
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001937void AudioPolicyManager::releaseMsdOutputPatches(const DeviceVector& devices) {
1938 AudioPatchCollection msdPatches = getMsdOutputPatches();
Michael Chan6fb34492020-12-08 15:44:49 +11001939 for (size_t i = 0; i < msdPatches.size(); i++) {
1940 const auto& patch = msdPatches[i];
1941 for (size_t j = 0; j < patch->mPatch.num_sinks; ++j) {
1942 const struct audio_port_config *sink = &patch->mPatch.sinks[j];
1943 if (sink->type == AUDIO_PORT_TYPE_DEVICE && devices.getDevice(sink->ext.device.type,
1944 String8(sink->ext.device.address), AUDIO_FORMAT_DEFAULT) != nullptr) {
1945 releaseAudioPatch(patch->getHandle(), mUidCached);
1946 break;
1947 }
1948 }
1949 }
1950}
1951
Dorin Drimus94d94412022-02-02 09:05:02 +01001952bool AudioPolicyManager::msdHasPatchesToAllDevices(const AudioDeviceTypeAddrVector& devices) {
Mikhail Naganov68e3f642023-04-28 13:06:32 -07001953 DeviceVector devicesToCheck =
1954 mConfig->getOutputDevices().getDevicesFromDeviceTypeAddrVec(devices);
Dorin Drimus94d94412022-02-02 09:05:02 +01001955 AudioPatchCollection msdPatches = getMsdOutputPatches();
1956 for (size_t i = 0; i < msdPatches.size(); i++) {
1957 const auto& patch = msdPatches[i];
1958 for (size_t j = 0; j < patch->mPatch.num_sinks; ++j) {
1959 const struct audio_port_config *sink = &patch->mPatch.sinks[j];
1960 if (sink->type == AUDIO_PORT_TYPE_DEVICE) {
1961 const auto& foundDevice = devicesToCheck.getDevice(
1962 sink->ext.device.type, String8(sink->ext.device.address), AUDIO_FORMAT_DEFAULT);
1963 if (foundDevice != nullptr) {
1964 devicesToCheck.remove(foundDevice);
1965 if (devicesToCheck.isEmpty()) {
1966 return true;
1967 }
1968 }
1969 }
1970 }
1971 }
1972 return false;
1973}
1974
Eric Laurente0720872014-03-11 09:30:41 -07001975audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
jiabinebb6af42020-06-09 17:31:17 -07001976 audio_output_flags_t flags,
1977 audio_format_t format,
1978 audio_channel_mask_t channelMask,
1979 uint32_t samplingRate,
1980 audio_session_t sessionId)
Eric Laurente552edb2014-03-10 17:42:56 -07001981{
Eric Laurent16c66dd2019-05-01 17:54:10 -07001982 LOG_ALWAYS_FATAL_IF(!(format == AUDIO_FORMAT_INVALID || audio_is_linear_pcm(format)),
1983 "%s called with format %#x", __func__, format);
1984
jiabinebb6af42020-06-09 17:31:17 -07001985 // Return the output that haptic-generating attached to when 1) session id is specified,
1986 // 2) haptic-generating effect exists for given session id and 3) the output that
1987 // haptic-generating effect attached to is in given outputs.
1988 if (sessionId != AUDIO_SESSION_NONE) {
1989 audio_io_handle_t hapticGeneratingOutput = mEffects.getIoForSession(
1990 sessionId, FX_IID_HAPTICGENERATOR);
1991 if (outputs.indexOf(hapticGeneratingOutput) >= 0) {
1992 return hapticGeneratingOutput;
1993 }
1994 }
1995
Eric Laurent16c66dd2019-05-01 17:54:10 -07001996 // Flags disqualifying an output: the match must happen before calling selectOutput()
1997 static const audio_output_flags_t kExcludedFlags = (audio_output_flags_t)
1998 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ | AUDIO_OUTPUT_FLAG_DIRECT);
1999
2000 // Flags expressing a functional request: must be honored in priority over
2001 // other criteria
2002 static const audio_output_flags_t kFunctionalFlags = (audio_output_flags_t)
2003 (AUDIO_OUTPUT_FLAG_VOIP_RX | AUDIO_OUTPUT_FLAG_INCALL_MUSIC |
Eric Laurente28c66d2022-01-21 13:40:41 +01002004 AUDIO_OUTPUT_FLAG_TTS | AUDIO_OUTPUT_FLAG_DIRECT_PCM | AUDIO_OUTPUT_FLAG_ULTRASOUND |
2005 AUDIO_OUTPUT_FLAG_SPATIALIZER);
Eric Laurent16c66dd2019-05-01 17:54:10 -07002006 // Flags expressing a performance request: have lower priority than serving
2007 // requested sampling rate or channel mask
2008 static const audio_output_flags_t kPerformanceFlags = (audio_output_flags_t)
2009 (AUDIO_OUTPUT_FLAG_FAST | AUDIO_OUTPUT_FLAG_DEEP_BUFFER |
2010 AUDIO_OUTPUT_FLAG_RAW | AUDIO_OUTPUT_FLAG_SYNC);
2011
2012 const audio_output_flags_t functionalFlags =
2013 (audio_output_flags_t)(flags & kFunctionalFlags);
2014 const audio_output_flags_t performanceFlags =
2015 (audio_output_flags_t)(flags & kPerformanceFlags);
2016
2017 audio_io_handle_t bestOutput = (outputs.size() == 0) ? AUDIO_IO_HANDLE_NONE : outputs[0];
2018
Eric Laurente552edb2014-03-10 17:42:56 -07002019 // select one output among several that provide a path to a particular device or set of
François Gaffie11d30102018-11-02 16:09:09 +01002020 // devices (the list was previously build by getOutputsForDevices()).
Eric Laurente552edb2014-03-10 17:42:56 -07002021 // The priority is as follows:
jiabin40573322018-11-08 12:08:02 -08002022 // 1: the output supporting haptic playback when requesting haptic playback
Eric Laurent16c66dd2019-05-01 17:54:10 -07002023 // 2: the output with the highest number of requested functional flags
Carter Hsu199f1892021-10-15 15:47:29 +08002024 // with tiebreak preferring the minimum number of extra functional flags
2025 // (see b/200293124, the incorrect selection of AUDIO_OUTPUT_FLAG_VOIP_RX).
Eric Laurent16c66dd2019-05-01 17:54:10 -07002026 // 3: the output supporting the exact channel mask
2027 // 4: the output with a higher channel count than requested
jiabinb12a6da2022-06-03 20:48:18 +00002028 // 5: the output with the highest sampling rate if the requested sample rate is
2029 // greater than default sampling rate
Eric Laurent16c66dd2019-05-01 17:54:10 -07002030 // 6: the output with the highest number of requested performance flags
2031 // 7: the output with the bit depth the closest to the requested one
2032 // 8: the primary output
2033 // 9: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07002034
Eric Laurent16c66dd2019-05-01 17:54:10 -07002035 // matching criteria values in priority order for best matching output so far
2036 std::vector<uint32_t> bestMatchCriteria(8, 0);
Eric Laurente552edb2014-03-10 17:42:56 -07002037
Eric Laurent16c66dd2019-05-01 17:54:10 -07002038 const uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
2039 const uint32_t hapticChannelCount = audio_channel_count_from_out_mask(
2040 channelMask & AUDIO_CHANNEL_HAPTIC_ALL);
Eric Laurente78b6762018-12-19 16:29:01 -08002041
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002042 for (audio_io_handle_t output : outputs) {
2043 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent16c66dd2019-05-01 17:54:10 -07002044 // matching criteria values in priority order for current output
2045 std::vector<uint32_t> currentMatchCriteria(8, 0);
jiabin40573322018-11-08 12:08:02 -08002046
Eric Laurent16c66dd2019-05-01 17:54:10 -07002047 if (outputDesc->isDuplicated()) {
2048 continue;
2049 }
2050 if ((kExcludedFlags & outputDesc->mFlags) != 0) {
2051 continue;
2052 }
Eric Laurent8838a382014-09-08 16:44:28 -07002053
Eric Laurent16c66dd2019-05-01 17:54:10 -07002054 // If haptic channel is specified, use the haptic output if present.
2055 // When using haptic output, same audio format and sample rate are required.
2056 const uint32_t outputHapticChannelCount = audio_channel_count_from_out_mask(
jiabin5740f082019-08-19 15:08:30 -07002057 outputDesc->getChannelMask() & AUDIO_CHANNEL_HAPTIC_ALL);
Eric Laurent16c66dd2019-05-01 17:54:10 -07002058 if ((hapticChannelCount == 0) != (outputHapticChannelCount == 0)) {
2059 continue;
2060 }
2061 if (outputHapticChannelCount >= hapticChannelCount
jiabin5740f082019-08-19 15:08:30 -07002062 && format == outputDesc->getFormat()
2063 && samplingRate == outputDesc->getSamplingRate()) {
Eric Laurent16c66dd2019-05-01 17:54:10 -07002064 currentMatchCriteria[0] = outputHapticChannelCount;
2065 }
2066
2067 // functional flags match
Carter Hsu199f1892021-10-15 15:47:29 +08002068 const int matchingFunctionalFlags =
2069 __builtin_popcount(outputDesc->mFlags & functionalFlags);
2070 const int totalFunctionalFlags =
2071 __builtin_popcount(outputDesc->mFlags & kFunctionalFlags);
2072 // Prefer matching functional flags, but subtract unnecessary functional flags.
2073 currentMatchCriteria[1] = 100 * (matchingFunctionalFlags + 1) - totalFunctionalFlags;
Eric Laurent16c66dd2019-05-01 17:54:10 -07002074
2075 // channel mask and channel count match
jiabin5740f082019-08-19 15:08:30 -07002076 uint32_t outputChannelCount = audio_channel_count_from_out_mask(
2077 outputDesc->getChannelMask());
Eric Laurent16c66dd2019-05-01 17:54:10 -07002078 if (channelMask != AUDIO_CHANNEL_NONE && channelCount > 2 &&
2079 channelCount <= outputChannelCount) {
2080 if ((audio_channel_mask_get_representation(channelMask) ==
jiabin5740f082019-08-19 15:08:30 -07002081 audio_channel_mask_get_representation(outputDesc->getChannelMask())) &&
2082 ((channelMask & outputDesc->getChannelMask()) == channelMask)) {
Eric Laurent16c66dd2019-05-01 17:54:10 -07002083 currentMatchCriteria[2] = outputChannelCount;
Eric Laurente552edb2014-03-10 17:42:56 -07002084 }
Eric Laurent16c66dd2019-05-01 17:54:10 -07002085 currentMatchCriteria[3] = outputChannelCount;
2086 }
2087
2088 // sampling rate match
jiabinb12a6da2022-06-03 20:48:18 +00002089 if (samplingRate > SAMPLE_RATE_HZ_DEFAULT) {
jiabin5740f082019-08-19 15:08:30 -07002090 currentMatchCriteria[4] = outputDesc->getSamplingRate();
Eric Laurent16c66dd2019-05-01 17:54:10 -07002091 }
2092
2093 // performance flags match
2094 currentMatchCriteria[5] = popcount(outputDesc->mFlags & performanceFlags);
2095
2096 // format match
2097 if (format != AUDIO_FORMAT_INVALID) {
2098 currentMatchCriteria[6] =
jiabin4ef93452019-09-10 14:29:54 -07002099 PolicyAudioPort::kFormatDistanceMax -
2100 PolicyAudioPort::formatDistance(format, outputDesc->getFormat());
Eric Laurent16c66dd2019-05-01 17:54:10 -07002101 }
2102
2103 // primary output match
2104 currentMatchCriteria[7] = outputDesc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY;
2105
2106 // compare match criteria by priority then value
2107 if (std::lexicographical_compare(bestMatchCriteria.begin(), bestMatchCriteria.end(),
2108 currentMatchCriteria.begin(), currentMatchCriteria.end())) {
2109 bestMatchCriteria = currentMatchCriteria;
2110 bestOutput = output;
2111
2112 std::stringstream result;
2113 std::copy(bestMatchCriteria.begin(), bestMatchCriteria.end(),
2114 std::ostream_iterator<int>(result, " "));
2115 ALOGV("%s new bestOutput %d criteria %s",
2116 __func__, bestOutput, result.str().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07002117 }
2118 }
2119
Eric Laurent16c66dd2019-05-01 17:54:10 -07002120 return bestOutput;
Eric Laurente552edb2014-03-10 17:42:56 -07002121}
2122
Eric Laurent8fc147b2018-07-22 19:13:55 -07002123status_t AudioPolicyManager::startOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002124{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002125 ALOGV("%s portId %d", __FUNCTION__, portId);
2126
2127 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2128 if (outputDesc == 0) {
2129 ALOGW("startOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002130 return BAD_VALUE;
2131 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002132 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002133
Eric Laurent8fc147b2018-07-22 19:13:55 -07002134 ALOGV("startOutput() output %d, stream %d, session %d",
Eric Laurent97ac8712018-07-27 18:59:02 -07002135 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurentc75307b2015-03-17 15:29:32 -07002136
Eric Laurent733ce942017-12-07 12:18:25 -08002137 status_t status = outputDesc->start();
2138 if (status != NO_ERROR) {
2139 return status;
Eric Laurent3974e3b2017-12-07 17:58:43 -08002140 }
2141
Eric Laurent97ac8712018-07-27 18:59:02 -07002142 uint32_t delayMs;
2143 status = startSource(outputDesc, client, &delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07002144
2145 if (status != NO_ERROR) {
Eric Laurent733ce942017-12-07 12:18:25 -08002146 outputDesc->stop();
jiabin3ff8d7d2022-12-13 06:27:44 +00002147 if (status == DEAD_OBJECT) {
2148 sp<SwAudioOutputDescriptor> desc =
2149 reopenOutput(outputDesc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
2150 if (desc == nullptr) {
2151 // This is not common, it may indicate something wrong with the HAL.
2152 ALOGE("%s unable to open output with default config", __func__);
2153 return status;
2154 }
2155 desc->mUsePreferredMixerAttributes = true;
2156 }
Eric Laurent8c7e6da2015-04-21 17:37:00 -07002157 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07002158 }
jiabina84c3d32022-12-02 18:59:55 +00002159
2160 // If the client is the first one active on preferred mixer parameters, reopen the output
2161 // if the current mixer parameters doesn't match the preferred one.
2162 if (outputDesc->devices().size() == 1) {
2163 sp<PreferredMixerAttributesInfo> info = getPreferredMixerAttributesInfo(
2164 outputDesc->devices()[0]->getId(), client->strategy());
2165 if (info != nullptr && info->getUid() == client->uid()) {
2166 if (info->getActiveClientCount() == 0 && !outputDesc->isConfigurationMatched(
2167 info->getConfigBase(), info->getFlags())) {
2168 stopSource(outputDesc, client);
2169 outputDesc->stop();
2170 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
2171 config.channel_mask = info->getConfigBase().channel_mask;
2172 config.sample_rate = info->getConfigBase().sample_rate;
2173 config.format = info->getConfigBase().format;
jiabin3ff8d7d2022-12-13 06:27:44 +00002174 sp<SwAudioOutputDescriptor> desc =
2175 reopenOutput(outputDesc, &config, info->getFlags(), __func__);
2176 if (desc == nullptr) {
2177 return BAD_VALUE;
jiabina84c3d32022-12-02 18:59:55 +00002178 }
jiabin3ff8d7d2022-12-13 06:27:44 +00002179 desc->mUsePreferredMixerAttributes = true;
jiabina84c3d32022-12-02 18:59:55 +00002180 // Intentionally return error to let the client side resending request for
2181 // creating and starting.
2182 return DEAD_OBJECT;
2183 }
2184 info->increaseActiveClient();
jiabine3d1f552023-06-14 17:42:17 +00002185 if (info->getActiveClientCount() == 1 &&
2186 (info->getFlags() & AUDIO_OUTPUT_FLAG_BIT_PERFECT) != AUDIO_OUTPUT_FLAG_NONE) {
2187 // If it is first bit-perfect client, reroute all clients that will be routed to
2188 // the bit-perfect sink so that it is guaranteed only bit-perfect stream is active.
2189 PortHandleVector clientsToInvalidate;
2190 for (size_t i = 0; i < mOutputs.size(); i++) {
2191 if (mOutputs[i] == outputDesc ||
jiabin98c519c2023-07-05 17:34:21 +00002192 mOutputs[i]->devices().filter(outputDesc->devices()).isEmpty()) {
jiabine3d1f552023-06-14 17:42:17 +00002193 continue;
2194 }
2195 for (const auto& c : mOutputs[i]->getClientIterable()) {
2196 clientsToInvalidate.push_back(c->portId());
2197 }
2198 }
2199 if (!clientsToInvalidate.empty()) {
2200 ALOGD("%s Invalidate clients due to first bit-perfect client started",
2201 __func__);
2202 mpClientInterface->invalidateTracks(clientsToInvalidate);
2203 }
2204 }
jiabina84c3d32022-12-02 18:59:55 +00002205 }
2206 }
2207
Jean-Michel Trivib1f6e642023-02-07 20:49:04 +00002208 if (client->hasPreferredDevice()) {
2209 // playback activity with preferred device impacts routing occurred, inform upper layers
2210 mpClientInterface->onRoutingUpdated();
2211 }
Eric Laurentc75307b2015-03-17 15:29:32 -07002212 if (delayMs != 0) {
2213 usleep(delayMs * 1000);
2214 }
2215
2216 return status;
2217}
2218
Eric Laurent96d1dda2022-03-14 17:14:19 +01002219bool AudioPolicyManager::isLeUnicastActive() const {
2220 if (isInCall()) {
2221 return true;
2222 }
2223 return isAnyDeviceTypeActive(getAudioDeviceOutLeAudioUnicastSet());
2224}
2225
2226bool AudioPolicyManager::isAnyDeviceTypeActive(const DeviceTypeSet& deviceTypes) const {
2227 if (mAvailableOutputDevices.getDevicesFromTypes(deviceTypes).isEmpty()) {
2228 return false;
2229 }
2230 bool active = mOutputs.isAnyDeviceTypeActive(deviceTypes);
2231 ALOGV("%s active %d", __func__, active);
2232 return active;
2233}
2234
Eric Laurent97ac8712018-07-27 18:59:02 -07002235status_t AudioPolicyManager::startSource(const sp<SwAudioOutputDescriptor>& outputDesc,
2236 const sp<TrackClientDescriptor>& client,
2237 uint32_t *delayMs)
Eric Laurentc75307b2015-03-17 15:29:32 -07002238{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002239 // cannot start playback of STREAM_TTS if any other output is being used
2240 uint32_t beaconMuteLatency = 0;
Eric Laurentc75307b2015-03-17 15:29:32 -07002241
2242 *delayMs = 0;
Eric Laurent97ac8712018-07-27 18:59:02 -07002243 audio_stream_type_t stream = client->stream();
François Gaffie1c878552018-11-22 16:53:21 +01002244 auto clientVolSrc = client->volumeSource();
François Gaffiec005e562018-11-06 15:04:49 +01002245 auto clientStrategy = client->strategy();
2246 auto clientAttr = client->attributes();
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002247 if (stream == AUDIO_STREAM_TTS) {
2248 ALOGV("\t found BEACON stream");
François Gaffie1c878552018-11-22 16:53:21 +01002249 if (!mTtsOutputAvailable && mOutputs.isAnyOutputActive(
Francois Gaffie4404ddb2021-02-04 17:03:38 +01002250 toVolumeSource(AUDIO_STREAM_TTS, false) /*sourceToIgnore*/)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002251 return INVALID_OPERATION;
2252 } else {
2253 beaconMuteLatency = handleEventForBeacon(STARTING_BEACON);
2254 }
2255 } else {
2256 // some playback other than beacon starts
2257 beaconMuteLatency = handleEventForBeacon(STARTING_OUTPUT);
2258 }
2259
Eric Laurent77305a62016-07-25 16:39:22 -07002260 // force device change if the output is inactive and no audio patch is already present.
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002261 // check active before incrementing usage count
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02002262 bool force = !outputDesc->isActive() && !outputDesc->isRouted();
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002263
François Gaffie11d30102018-11-02 16:09:09 +01002264 DeviceVector devices;
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002265 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
Eric Laurent97ac8712018-07-27 18:59:02 -07002266 const char *address = NULL;
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002267 if (policyMix != nullptr) {
François Gaffie11d30102018-11-02 16:09:09 +01002268 audio_devices_t newDeviceType;
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00002269 address = policyMix->mDeviceAddress.c_str();
Kevin Rocard153f92d2018-12-18 18:33:28 -08002270 if ((policyMix->mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie11d30102018-11-02 16:09:09 +01002271 newDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Kevin Rocard153f92d2018-12-18 18:33:28 -08002272 } else {
2273 newDeviceType = policyMix->mDeviceType;
Eric Laurent97ac8712018-07-27 18:59:02 -07002274 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08002275 sp device = mAvailableOutputDevices.getDevice(newDeviceType, String8(address),
2276 AUDIO_FORMAT_DEFAULT);
2277 ALOG_ASSERT(device, "%s: no device found t=%u, a=%s", __func__, newDeviceType, address);
2278 devices.add(device);
Eric Laurent97ac8712018-07-27 18:59:02 -07002279 }
2280
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002281 // requiresMuteCheck is false when we can bypass mute strategy.
2282 // It covers a common case when there is no materially active audio
2283 // and muting would result in unnecessary delay and dropped audio.
2284 const uint32_t outputLatencyMs = outputDesc->latency();
2285 bool requiresMuteCheck = outputDesc->isActive(outputLatencyMs * 2); // account for drain
Eric Laurent96d1dda2022-03-14 17:14:19 +01002286 bool wasLeUnicastActive = isLeUnicastActive();
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002287
Eric Laurente552edb2014-03-10 17:42:56 -07002288 // increment usage count for this stream on the requested output:
2289 // NOTE that the usage count is the same for duplicated output and hardware output which is
2290 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
Eric Laurent592dd7b2018-08-05 18:58:48 -07002291 outputDesc->setClientActive(client, true);
Eric Laurent97ac8712018-07-27 18:59:02 -07002292
2293 if (client->hasPreferredDevice(true)) {
Eric Laurent72af8012023-03-15 17:36:22 +01002294 if (outputDesc->sameExclusivePreferredDevicesCount() > 0) {
François Gaffief96e5432019-04-09 17:13:56 +02002295 // Preferred device may be exclusive, use only if no other active clients on this output
2296 devices = DeviceVector(
2297 mAvailableOutputDevices.getDeviceFromId(client->preferredDeviceId()));
2298 } else {
2299 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
2300 }
François Gaffie11d30102018-11-02 16:09:09 +01002301 if (devices != outputDesc->devices()) {
François Gaffiec005e562018-11-06 15:04:49 +01002302 checkStrategyRoute(clientStrategy, outputDesc->mIoHandle);
Eric Laurent97ac8712018-07-27 18:59:02 -07002303 }
2304 }
Eric Laurente552edb2014-03-10 17:42:56 -07002305
François Gaffiec005e562018-11-06 15:04:49 +01002306 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07002307 selectOutputForMusicEffects();
2308 }
2309
François Gaffie1c878552018-11-22 16:53:21 +01002310 if (outputDesc->getActivityCount(clientVolSrc) == 1 || !devices.isEmpty()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08002311 // starting an output being rerouted?
François Gaffie11d30102018-11-02 16:09:09 +01002312 if (devices.isEmpty()) {
2313 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Eric Laurent275e8e92014-11-30 15:14:47 -08002314 }
François Gaffiec005e562018-11-06 15:04:49 +01002315 bool shouldWait =
2316 (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM)) ||
2317 followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_NOTIFICATION)) ||
2318 (beaconMuteLatency > 0));
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002319 uint32_t waitMs = beaconMuteLatency;
Eric Laurente552edb2014-03-10 17:42:56 -07002320 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01002321 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07002322 if (desc != outputDesc) {
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002323 // An output has a shared device if
2324 // - managed by the same hw module
2325 // - supports the currently selected device
2326 const bool sharedDevice = outputDesc->sharesHwModuleWith(desc)
François Gaffie11d30102018-11-02 16:09:09 +01002327 && (!desc->filterSupportedDevices(devices).isEmpty());
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002328
Eric Laurent77305a62016-07-25 16:39:22 -07002329 // force a device change if any other output is:
2330 // - managed by the same hw module
Jean-Michel Trivi4a5b4812018-02-08 17:22:32 +00002331 // - supports currently selected device
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002332 // - has a current device selection that differs from selected device.
Eric Laurent77305a62016-07-25 16:39:22 -07002333 // - has an active audio patch
Eric Laurente552edb2014-03-10 17:42:56 -07002334 // In this case, the audio HAL must receive the new device selection so that it can
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002335 // change the device currently selected by the other output.
2336 if (sharedDevice &&
François Gaffie11d30102018-11-02 16:09:09 +01002337 desc->devices() != devices &&
Eric Laurent77305a62016-07-25 16:39:22 -07002338 desc->getPatchHandle() != AUDIO_PATCH_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07002339 force = true;
2340 }
2341 // wait for audio on other active outputs to be presented when starting
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002342 // a notification so that audio focus effect can propagate, or that a mute/unmute
2343 // event occurred for beacon
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002344 const uint32_t latencyMs = desc->latency();
2345 const bool isActive = desc->isActive(latencyMs * 2); // account for drain
2346
2347 if (shouldWait && isActive && (waitMs < latencyMs)) {
2348 waitMs = latencyMs;
Eric Laurente552edb2014-03-10 17:42:56 -07002349 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002350
2351 // Require mute check if another output is on a shared device
2352 // and currently active to have proper drain and avoid pops.
2353 // Note restoring AudioTracks onto this output needs to invoke
2354 // a volume ramp if there is no mute.
2355 requiresMuteCheck |= sharedDevice && isActive;
Eric Laurente552edb2014-03-10 17:42:56 -07002356 }
2357 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002358
jiabin3ff8d7d2022-12-13 06:27:44 +00002359 if (outputDesc->mUsePreferredMixerAttributes && devices != outputDesc->devices()) {
2360 // If the output is open with preferred mixer attributes, but the routed device is
2361 // changed when calling this function, returning DEAD_OBJECT to indicate routing
2362 // changed.
2363 return DEAD_OBJECT;
2364 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002365 const uint32_t muteWaitMs =
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05302366 setOutputDevices(__func__, outputDesc, devices, force, 0, nullptr,
2367 requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07002368
Eric Laurente552edb2014-03-10 17:42:56 -07002369 // apply volume rules for current stream and device if necessary
François Gaffieaaac0fd2018-11-22 17:56:39 +01002370 auto &curves = getVolumeCurves(client->attributes());
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00002371 if (NO_ERROR != checkAndSetVolume(curves, client->volumeSource(),
François Gaffieaaac0fd2018-11-22 17:56:39 +01002372 curves.getVolumeIndex(outputDesc->devices().types()),
Eric Laurentc75307b2015-03-17 15:29:32 -07002373 outputDesc,
Francois Gaffied11442b2020-04-27 11:51:09 +02002374 outputDesc->devices().types(), 0 /*delay*/,
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00002375 outputDesc->useHwGain() /*force*/)) {
2376 // request AudioService to reinitialize the volume curves asynchronously
2377 ALOGE("checkAndSetVolume failed, requesting volume range init");
2378 mpClientInterface->onVolumeRangeInitRequest();
2379 };
Eric Laurente552edb2014-03-10 17:42:56 -07002380
2381 // update the outputs if starting an output with a stream that can affect notification
2382 // routing
2383 handleNotificationRoutingForStream(stream);
Eric Laurentc722f302014-12-10 11:21:49 -08002384
Eric Laurent2cbe89a2014-12-19 11:49:08 -08002385 // force reevaluating accessibility routing when ringtone or alarm starts
François Gaffiec005e562018-11-06 15:04:49 +01002386 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM))) {
jiabinc44b3462022-12-08 12:52:31 -08002387 invalidateStreams({AUDIO_STREAM_ACCESSIBILITY});
Eric Laurent2cbe89a2014-12-19 11:49:08 -08002388 }
Eric Laurentdc462862016-07-19 12:29:53 -07002389
2390 if (waitMs > muteWaitMs) {
2391 *delayMs = waitMs - muteWaitMs;
2392 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002393
2394 // FIXME: A device change (muteWaitMs > 0) likely introduces a volume change.
2395 // A volume change enacted by APM with 0 delay is not synchronous, as it goes
2396 // via AudioCommandThread to AudioFlinger. Hence it is possible that the volume
2397 // change occurs after the MixerThread starts and causes a stream volume
2398 // glitch.
2399 //
2400 // We do not introduce additional delay here.
Eric Laurente552edb2014-03-10 17:42:56 -07002401 }
Eric Laurentdc462862016-07-19 12:29:53 -07002402
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002403 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
jiabin9a3361e2019-10-01 09:38:30 -07002404 mEngine->getForceUse(
2405 AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
François Gaffiec005e562018-11-06 15:04:49 +01002406 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), true, outputDesc);
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002407 }
2408
Eric Laurent97ac8712018-07-27 18:59:02 -07002409 // Automatically enable the remote submix input when output is started on a re routing mix
2410 // of type MIX_TYPE_RECORDERS
jiabin9a3361e2019-10-01 09:38:30 -07002411 if (isSingleDeviceType(devices.types(), &audio_is_remote_submix_device) &&
2412 policyMix != NULL && policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002413 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2414 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2415 address,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002416 "remote-submix",
2417 AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07002418 }
2419
Eric Laurent96d1dda2022-03-14 17:14:19 +01002420 checkLeBroadcastRoutes(wasLeUnicastActive, outputDesc, *delayMs);
2421
Eric Laurente552edb2014-03-10 17:42:56 -07002422 return NO_ERROR;
2423}
2424
Eric Laurent96d1dda2022-03-14 17:14:19 +01002425void AudioPolicyManager::checkLeBroadcastRoutes(bool wasUnicastActive,
2426 sp<SwAudioOutputDescriptor> ignoredOutput, uint32_t delayMs) {
2427 bool isUnicastActive = isLeUnicastActive();
2428
2429 if (wasUnicastActive != isUnicastActive) {
jiabin3ff8d7d2022-12-13 06:27:44 +00002430 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent96d1dda2022-03-14 17:14:19 +01002431 //reroute all outputs routed to LE broadcast if LE unicast activy changed on any output
2432 for (size_t i = 0; i < mOutputs.size(); i++) {
2433 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
2434 if (desc != ignoredOutput && desc->isActive()
2435 && ((isUnicastActive &&
2436 !desc->devices().
2437 getDevicesFromType(AUDIO_DEVICE_OUT_BLE_BROADCAST).isEmpty())
2438 || (wasUnicastActive &&
2439 !desc->devices().getDevicesFromTypes(
2440 getAudioDeviceOutLeAudioUnicastSet()).isEmpty()))) {
2441 DeviceVector newDevices = getNewOutputDevices(desc, false /*fromCache*/);
2442 bool force = desc->devices() != newDevices;
jiabin3ff8d7d2022-12-13 06:27:44 +00002443 if (desc->mUsePreferredMixerAttributes && force) {
2444 // If the device is using preferred mixer attributes, the output need to reopen
2445 // with default configuration when the new selected devices are different from
2446 // current routing devices.
2447 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices);
2448 continue;
2449 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05302450 setOutputDevices(__func__, desc, newDevices, force, delayMs);
Eric Laurent96d1dda2022-03-14 17:14:19 +01002451 // re-apply device specific volume if not done by setOutputDevice()
2452 if (!force) {
2453 applyStreamVolumes(desc, newDevices.types(), delayMs);
2454 }
2455 }
2456 }
jiabin3ff8d7d2022-12-13 06:27:44 +00002457 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent96d1dda2022-03-14 17:14:19 +01002458 }
2459}
2460
Eric Laurent8fc147b2018-07-22 19:13:55 -07002461status_t AudioPolicyManager::stopOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002462{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002463 ALOGV("%s portId %d", __FUNCTION__, portId);
2464
2465 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2466 if (outputDesc == 0) {
2467 ALOGW("stopOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002468 return BAD_VALUE;
2469 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002470 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002471
Jean-Michel Trivib1f6e642023-02-07 20:49:04 +00002472 if (client->hasPreferredDevice(true)) {
2473 // playback activity with preferred device impacts routing occurred, inform upper layers
2474 mpClientInterface->onRoutingUpdated();
2475 }
2476
Eric Laurent97ac8712018-07-27 18:59:02 -07002477 ALOGV("stopOutput() output %d, stream %d, session %d",
2478 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurente552edb2014-03-10 17:42:56 -07002479
Eric Laurent97ac8712018-07-27 18:59:02 -07002480 status_t status = stopSource(outputDesc, client);
Eric Laurent3974e3b2017-12-07 17:58:43 -08002481
Eric Laurent733ce942017-12-07 12:18:25 -08002482 if (status == NO_ERROR ) {
2483 outputDesc->stop();
jiabina84c3d32022-12-02 18:59:55 +00002484 } else {
2485 return status;
2486 }
2487
2488 if (outputDesc->devices().size() == 1) {
2489 sp<PreferredMixerAttributesInfo> info = getPreferredMixerAttributesInfo(
2490 outputDesc->devices()[0]->getId(), client->strategy());
2491 if (info != nullptr && info->getUid() == client->uid()) {
2492 info->decreaseActiveClient();
2493 if (info->getActiveClientCount() == 0) {
2494 reopenOutput(outputDesc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
2495 }
2496 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002497 }
2498 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07002499}
2500
Eric Laurent97ac8712018-07-27 18:59:02 -07002501status_t AudioPolicyManager::stopSource(const sp<SwAudioOutputDescriptor>& outputDesc,
2502 const sp<TrackClientDescriptor>& client)
Eric Laurentc75307b2015-03-17 15:29:32 -07002503{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002504 // always handle stream stop, check which stream type is stopping
Eric Laurent97ac8712018-07-27 18:59:02 -07002505 audio_stream_type_t stream = client->stream();
François Gaffie1c878552018-11-22 16:53:21 +01002506 auto clientVolSrc = client->volumeSource();
Eric Laurent96d1dda2022-03-14 17:14:19 +01002507 bool wasLeUnicastActive = isLeUnicastActive();
Eric Laurent97ac8712018-07-27 18:59:02 -07002508
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002509 handleEventForBeacon(stream == AUDIO_STREAM_TTS ? STOPPING_BEACON : STOPPING_OUTPUT);
2510
François Gaffie1c878552018-11-22 16:53:21 +01002511 if (outputDesc->getActivityCount(clientVolSrc) > 0) {
2512 if (outputDesc->getActivityCount(clientVolSrc) == 1) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002513 // Automatically disable the remote submix input when output is stopped on a
2514 // re routing mix of type MIX_TYPE_RECORDERS
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002515 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
jiabin9a3361e2019-10-01 09:38:30 -07002516 if (isSingleDeviceType(
2517 outputDesc->devices().types(), &audio_is_remote_submix_device) &&
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002518 policyMix != nullptr &&
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002519 policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002520 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2521 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002522 policyMix->mDeviceAddress,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002523 "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07002524 }
2525 }
2526 bool forceDeviceUpdate = false;
Eric Laurent72af8012023-03-15 17:36:22 +01002527 if (client->hasPreferredDevice(true) &&
2528 outputDesc->sameExclusivePreferredDevicesCount() < 2) {
François Gaffiec005e562018-11-06 15:04:49 +01002529 checkStrategyRoute(client->strategy(), AUDIO_IO_HANDLE_NONE);
Eric Laurent97ac8712018-07-27 18:59:02 -07002530 forceDeviceUpdate = true;
2531 }
2532
Eric Laurente552edb2014-03-10 17:42:56 -07002533 // decrement usage count of this stream on the output
Eric Laurent592dd7b2018-08-05 18:58:48 -07002534 outputDesc->setClientActive(client, false);
Paul McLeanaa981192015-03-21 09:55:15 -07002535
Eric Laurente552edb2014-03-10 17:42:56 -07002536 // store time at which the stream was stopped - see isStreamActive()
François Gaffie1c878552018-11-22 16:53:21 +01002537 if (outputDesc->getActivityCount(clientVolSrc) == 0 || forceDeviceUpdate) {
François Gaffiec005e562018-11-06 15:04:49 +01002538 outputDesc->setStopTime(client, systemTime());
François Gaffie11d30102018-11-02 16:09:09 +01002539 DeviceVector newDevices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Francois Gaffie3523ab32021-06-22 13:24:34 +02002540
2541 // If the routing does not change, if an output is routed on a device using HwGain
2542 // (aka setAudioPortConfig) and there are still active clients following different
2543 // volume group(s), force reapply volume
2544 bool requiresVolumeCheck = outputDesc->getActivityCount(clientVolSrc) == 0 &&
2545 outputDesc->useHwGain() && outputDesc->isAnyActive(VOLUME_SOURCE_NONE);
2546
Eric Laurente552edb2014-03-10 17:42:56 -07002547 // delay the device switch by twice the latency because stopOutput() is executed when
2548 // the track stop() command is received and at that time the audio track buffer can
2549 // still contain data that needs to be drained. The latency only covers the audio HAL
2550 // and kernel buffers. Also the latency does not always include additional delay in the
2551 // audio path (audio DSP, CODEC ...)
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05302552 setOutputDevices(__func__, outputDesc, newDevices, false, outputDesc->latency()*2,
Francois Gaffie3523ab32021-06-22 13:24:34 +02002553 nullptr, true /*requiresMuteCheck*/, requiresVolumeCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07002554
2555 // force restoring the device selection on other active outputs if it differs from the
2556 // one being selected for this output
jiabin3ff8d7d2022-12-13 06:27:44 +00002557 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent57de36c2016-09-28 16:59:11 -07002558 uint32_t delayMs = outputDesc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -07002559 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01002560 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07002561 if (desc != outputDesc &&
Eric Laurente552edb2014-03-10 17:42:56 -07002562 desc->isActive() &&
2563 outputDesc->sharesHwModuleWith(desc) &&
François Gaffie11d30102018-11-02 16:09:09 +01002564 (newDevices != desc->devices())) {
2565 DeviceVector newDevices2 = getNewOutputDevices(desc, false /*fromCache*/);
2566 bool force = desc->devices() != newDevices2;
Eric Laurentf3a5a602018-05-22 18:42:55 -07002567
jiabin3ff8d7d2022-12-13 06:27:44 +00002568 if (desc->mUsePreferredMixerAttributes && force) {
2569 // If the device is using preferred mixer attributes, the output need to
2570 // reopen with default configuration when the new selected devices are
2571 // different from current routing devices.
2572 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices2);
2573 continue;
2574 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05302575 setOutputDevices(__func__, desc, newDevices2, force, delayMs);
François Gaffie11d30102018-11-02 16:09:09 +01002576
Eric Laurent57de36c2016-09-28 16:59:11 -07002577 // re-apply device specific volume if not done by setOutputDevice()
2578 if (!force) {
François Gaffie11d30102018-11-02 16:09:09 +01002579 applyStreamVolumes(desc, newDevices2.types(), delayMs);
Eric Laurent57de36c2016-09-28 16:59:11 -07002580 }
Eric Laurente552edb2014-03-10 17:42:56 -07002581 }
2582 }
jiabin3ff8d7d2022-12-13 06:27:44 +00002583 reopenOutputsWithDevices(outputsToReopen);
Eric Laurente552edb2014-03-10 17:42:56 -07002584 // update the outputs if stopping one with a stream that can affect notification routing
2585 handleNotificationRoutingForStream(stream);
2586 }
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002587
2588 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
2589 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Jean-Michel Trivi74e01fa2019-02-25 12:18:09 -08002590 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), false, outputDesc);
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002591 }
2592
François Gaffiec005e562018-11-06 15:04:49 +01002593 if (followsSameRouting(client->attributes(), attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07002594 selectOutputForMusicEffects();
2595 }
Eric Laurent96d1dda2022-03-14 17:14:19 +01002596
2597 checkLeBroadcastRoutes(wasLeUnicastActive, outputDesc, outputDesc->latency()*2);
2598
Eric Laurente552edb2014-03-10 17:42:56 -07002599 return NO_ERROR;
2600 } else {
Eric Laurentc75307b2015-03-17 15:29:32 -07002601 ALOGW("stopOutput() refcount is already 0");
Eric Laurente552edb2014-03-10 17:42:56 -07002602 return INVALID_OPERATION;
2603 }
2604}
2605
jiabinbce0c1d2020-10-05 11:20:18 -07002606bool AudioPolicyManager::releaseOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002607{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002608 ALOGV("%s portId %d", __FUNCTION__, portId);
2609
2610 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2611 if (outputDesc == 0) {
Andy Hung39efb7a2018-09-26 15:39:28 -07002612 // If an output descriptor is closed due to a device routing change,
2613 // then there are race conditions with releaseOutput from tracks
2614 // that may be destroyed (with no PlaybackThread) or a PlaybackThread
2615 // destroyed shortly thereafter.
2616 //
2617 // Here we just log a warning, instead of a fatal error.
Eric Laurent8fc147b2018-07-22 19:13:55 -07002618 ALOGW("releaseOutput() no output for client %d", portId);
jiabinbce0c1d2020-10-05 11:20:18 -07002619 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002620 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002621
2622 ALOGV("releaseOutput() %d", outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -07002623
Jaideep Sharma7bf382e2020-11-26 17:07:29 +05302624 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
2625 if (outputDesc->isClientActive(client)) {
2626 ALOGW("releaseOutput() inactivates portId %d in good faith", portId);
2627 stopOutput(portId);
2628 }
2629
Eric Laurent8fc147b2018-07-22 19:13:55 -07002630 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
2631 if (outputDesc->mDirectOpenCount <= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07002632 ALOGW("releaseOutput() invalid open count %d for output %d",
Eric Laurent8fc147b2018-07-22 19:13:55 -07002633 outputDesc->mDirectOpenCount, outputDesc->mIoHandle);
jiabinbce0c1d2020-10-05 11:20:18 -07002634 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002635 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002636 if (--outputDesc->mDirectOpenCount == 0) {
2637 closeOutput(outputDesc->mIoHandle);
Eric Laurentb52c1522014-05-20 11:27:36 -07002638 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07002639 }
2640 }
Jaideep Sharma7bf382e2020-11-26 17:07:29 +05302641
Andy Hung39efb7a2018-09-26 15:39:28 -07002642 outputDesc->removeClient(portId);
jiabinbce0c1d2020-10-05 11:20:18 -07002643 if (outputDesc->mPendingReopenToQueryProfiles && outputDesc->getClientCount() == 0) {
2644 // The output is pending reopened to query dynamic profiles and
2645 // there is no active clients
2646 closeOutput(outputDesc->mIoHandle);
2647 sp<SwAudioOutputDescriptor> newOutputDesc = openOutputWithProfileAndDevice(
2648 outputDesc->mProfile, mEngine->getActiveMediaDevices(mAvailableOutputDevices));
2649 if (newOutputDesc == nullptr) {
2650 ALOGE("%s failed to open output", __func__);
2651 }
2652 return true;
2653 }
2654 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002655}
2656
Eric Laurentcaf7f482014-11-25 17:50:47 -08002657status_t AudioPolicyManager::getInputForAttr(const audio_attributes_t *attr,
2658 audio_io_handle_t *input,
Mikhail Naganov2996f672019-04-18 12:29:59 -07002659 audio_unique_id_t riid,
Eric Laurentcaf7f482014-11-25 17:50:47 -08002660 audio_session_t session,
Svet Ganov3e5f14f2021-05-13 22:51:08 +00002661 const AttributionSourceState& attributionSource,
jiabinf1c73972022-04-14 16:28:52 -07002662 audio_config_base_t *config,
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002663 audio_input_flags_t flags,
Eric Laurent2ac76942017-06-22 17:17:09 -07002664 audio_port_handle_t *selectedDeviceId,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002665 input_type_t *inputType,
2666 audio_port_handle_t *portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002667{
François Gaffiec005e562018-11-06 15:04:49 +01002668 ALOGV("%s() source %d, sampling rate %d, format %#x, channel mask %#x, session %d, "
Eric Laurent2f2c1982021-06-02 14:03:11 +02002669 "flags %#x attributes=%s requested device ID %d",
2670 __func__, attr->source, config->sample_rate, config->format, config->channel_mask,
2671 session, flags, toString(*attr).c_str(), *selectedDeviceId);
Eric Laurente552edb2014-03-10 17:42:56 -07002672
Eric Laurentad2e7b92017-09-14 20:06:42 -07002673 status_t status = NO_ERROR;
Francois Gaffie716e1432019-01-14 16:58:59 +01002674 audio_attributes_t attributes = *attr;
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002675 sp<AudioPolicyMix> policyMix;
François Gaffie11d30102018-11-02 16:09:09 +01002676 sp<DeviceDescriptor> device;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002677 sp<AudioInputDescriptor> inputDesc;
François Gaffie1b4753e2023-02-06 10:36:33 +01002678 sp<AudioInputDescriptor> previousInputDesc;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002679 sp<RecordClientDescriptor> clientDesc;
2680 audio_port_handle_t requestedDeviceId = *selectedDeviceId;
Svet Ganov3e5f14f2021-05-13 22:51:08 +00002681 uid_t uid = VALUE_OR_RETURN_STATUS(aidl2legacy_int32_t_uid_t(attributionSource.uid));
Eric Laurent8f42ea12018-08-08 09:08:25 -07002682 bool isSoundTrigger;
Eric Laurent8f42ea12018-08-08 09:08:25 -07002683
2684 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
2685 if (*portId != AUDIO_PORT_HANDLE_NONE) {
2686 return INVALID_OPERATION;
2687 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08002688
Francois Gaffie716e1432019-01-14 16:58:59 +01002689 if (attr->source == AUDIO_SOURCE_DEFAULT) {
2690 attributes.source = AUDIO_SOURCE_MIC;
Eric Laurentfe231122017-11-17 17:48:06 -08002691 }
2692
Paul McLean466dc8e2015-04-17 13:15:36 -06002693 // Explicit routing?
Pattydd807582021-11-04 21:01:03 +08002694 sp<DeviceDescriptor> explicitRoutingDevice =
François Gaffie11d30102018-11-02 16:09:09 +01002695 mAvailableInputDevices.getDeviceFromId(*selectedDeviceId);
Paul McLean466dc8e2015-04-17 13:15:36 -06002696
Eric Laurentad2e7b92017-09-14 20:06:42 -07002697 // special case for mmap capture: if an input IO handle is specified, we reuse this input if
2698 // possible
2699 if ((flags & AUDIO_INPUT_FLAG_MMAP_NOIRQ) == AUDIO_INPUT_FLAG_MMAP_NOIRQ &&
2700 *input != AUDIO_IO_HANDLE_NONE) {
2701 ssize_t index = mInputs.indexOfKey(*input);
2702 if (index < 0) {
2703 ALOGW("getInputForAttr() unknown MMAP input %d", *input);
2704 status = BAD_VALUE;
2705 goto error;
2706 }
2707 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002708 RecordClientVector clients = inputDesc->getClientsForSession(session);
2709 if (clients.size() == 0) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07002710 ALOGW("getInputForAttr() unknown session %d on input %d", session, *input);
2711 status = BAD_VALUE;
2712 goto error;
2713 }
2714 // For MMAP mode, the first call to getInputForAttr() is made on behalf of audioflinger.
2715 // The second call is for the first active client and sets the UID. Any further call
Eric Laurent331679c2018-04-16 17:03:16 -07002716 // corresponds to a new client and is only permitted from the same UID.
2717 // If the first UID is silenced, allow a new UID connection and replace with new UID
Eric Laurent8f42ea12018-08-08 09:08:25 -07002718 if (clients.size() > 1) {
2719 for (const auto& client : clients) {
2720 // The client map is ordered by key values (portId) and portIds are allocated
2721 // incrementaly. So the first client in this list is the one opened by audio flinger
2722 // when the mmap stream is created and should be ignored as it does not correspond
2723 // to an actual client
2724 if (client == *clients.cbegin()) {
2725 continue;
2726 }
2727 if (uid != client->uid() && !client->isSilenced()) {
2728 ALOGW("getInputForAttr() bad uid %d for client %d uid %d",
2729 uid, client->portId(), client->uid());
2730 status = INVALID_OPERATION;
2731 goto error;
2732 }
Eric Laurent331679c2018-04-16 17:03:16 -07002733 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002734 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002735 *inputType = API_INPUT_LEGACY;
François Gaffie11d30102018-11-02 16:09:09 +01002736 device = inputDesc->getDevice();
Eric Laurentad2e7b92017-09-14 20:06:42 -07002737
Eric Laurentfecbceb2021-02-09 14:46:43 +01002738 ALOGV("%s reusing MMAP input %d for session %d", __FUNCTION__, *input, session);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002739 goto exit;
Eric Laurentad2e7b92017-09-14 20:06:42 -07002740 }
2741
2742 *input = AUDIO_IO_HANDLE_NONE;
2743 *inputType = API_INPUT_INVALID;
2744
Francois Gaffie716e1432019-01-14 16:58:59 +01002745 if (attributes.source == AUDIO_SOURCE_REMOTE_SUBMIX &&
Jan Sebechlebskybc56bcd2022-09-26 13:15:19 +02002746 extractAddressFromAudioAttributes(attributes).has_value()) {
Francois Gaffie716e1432019-01-14 16:58:59 +01002747 status = mPolicyMixes.getInputMixForAttr(attributes, &policyMix);
Eric Laurentad2e7b92017-09-14 20:06:42 -07002748 if (status != NO_ERROR) {
jiabinc1de2df2019-05-07 14:26:40 -07002749 ALOGW("%s could not find input mix for attr %s",
2750 __func__, toString(attributes).c_str());
Eric Laurentad2e7b92017-09-14 20:06:42 -07002751 goto error;
François Gaffie036e1e92015-03-19 10:16:24 +01002752 }
jiabinc1de2df2019-05-07 14:26:40 -07002753 device = mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2754 String8(attr->tags + strlen("addr=")),
2755 AUDIO_FORMAT_DEFAULT);
2756 if (device == nullptr) {
Kevin Rocard04ed0462019-05-02 17:53:24 -07002757 ALOGW("%s could not find in Remote Submix device for source %d, tags %s",
jiabinc1de2df2019-05-07 14:26:40 -07002758 __func__, attributes.source, attributes.tags);
2759 status = BAD_VALUE;
2760 goto error;
2761 }
2762
Kevin Rocard25f9b052019-02-27 15:08:54 -08002763 if (is_mix_loopback_render(policyMix->mRouteFlags)) {
2764 *inputType = API_INPUT_MIX_PUBLIC_CAPTURE_PLAYBACK;
2765 } else {
2766 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
2767 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002768 } else {
François Gaffie11d30102018-11-02 16:09:09 +01002769 if (explicitRoutingDevice != nullptr) {
2770 device = explicitRoutingDevice;
Eric Laurent97ac8712018-07-27 18:59:02 -07002771 } else {
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01002772 // Prevent from storing invalid requested device id in clients
2773 requestedDeviceId = AUDIO_PORT_HANDLE_NONE;
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02002774 device = mEngine->getInputDeviceForAttributes(attributes, uid, session, &policyMix);
yuanjiahsu4069d5d2021-04-19 07:54:27 +08002775 ALOGV_IF(device != nullptr, "%s found device type is 0x%X",
2776 __FUNCTION__, device->type());
Eric Laurent97ac8712018-07-27 18:59:02 -07002777 }
François Gaffie11d30102018-11-02 16:09:09 +01002778 if (device == nullptr) {
Francois Gaffie716e1432019-01-14 16:58:59 +01002779 ALOGW("getInputForAttr() could not find device for source %d", attributes.source);
Eric Laurentad2e7b92017-09-14 20:06:42 -07002780 status = BAD_VALUE;
2781 goto error;
Eric Laurent275e8e92014-11-30 15:14:47 -08002782 }
Alden DSouzab7d20782021-02-08 08:51:42 -08002783 if (device->type() == AUDIO_DEVICE_IN_ECHO_REFERENCE) {
2784 *inputType = API_INPUT_MIX_CAPTURE;
2785 } else if (policyMix) {
François Gaffie11d30102018-11-02 16:09:09 +01002786 ALOG_ASSERT(policyMix->mMixType == MIX_TYPE_RECORDERS, "Invalid Mix Type");
2787 // there is an external policy, but this input is attached to a mix of recorders,
2788 // meaning it receives audio injected into the framework, so the recorder doesn't
2789 // know about it and is therefore considered "legacy"
2790 *inputType = API_INPUT_LEGACY;
2791 } else if (audio_is_remote_submix_device(device->type())) {
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002792 *inputType = API_INPUT_MIX_CAPTURE;
François Gaffie11d30102018-11-02 16:09:09 +01002793 } else if (device->type() == AUDIO_DEVICE_IN_TELEPHONY_RX) {
Eric Laurent82db2692015-08-07 13:59:42 -07002794 *inputType = API_INPUT_TELEPHONY_RX;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002795 } else {
2796 *inputType = API_INPUT_LEGACY;
Eric Laurentc722f302014-12-10 11:21:49 -08002797 }
Ravi Kumar Alamandab367f5b2015-08-25 08:21:37 -07002798
Eric Laurent599c7582015-12-07 18:05:55 -08002799 }
2800
François Gaffiec005e562018-11-06 15:04:49 +01002801 *input = getInputForDevice(device, session, attributes, config, flags, policyMix);
Eric Laurent599c7582015-12-07 18:05:55 -08002802 if (*input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07002803 status = INVALID_OPERATION;
jiabinf1c73972022-04-14 16:28:52 -07002804 AudioProfileVector profiles;
2805 status_t ret = getProfilesForDevices(
2806 DeviceVector(device), profiles, flags, true /*isInput*/);
2807 if (ret == NO_ERROR && !profiles.empty()) {
Robert Wub98ff1b2023-06-15 22:53:58 +00002808 const auto channels = profiles[0]->getChannels();
2809 if (!channels.empty() && (channels.find(config->channel_mask) == channels.end())) {
2810 config->channel_mask = *channels.begin();
2811 }
2812 const auto sampleRates = profiles[0]->getSampleRates();
2813 if (!sampleRates.empty() &&
2814 (sampleRates.find(config->sample_rate) == sampleRates.end())) {
2815 config->sample_rate = *sampleRates.begin();
2816 }
jiabinf1c73972022-04-14 16:28:52 -07002817 config->format = profiles[0]->getFormat();
2818 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002819 goto error;
Eric Laurent599c7582015-12-07 18:05:55 -08002820 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08002821
Eric Laurent8f42ea12018-08-08 09:08:25 -07002822exit:
2823
François Gaffiec005e562018-11-06 15:04:49 +01002824 *selectedDeviceId = mAvailableInputDevices.contains(device) ?
2825 device->getId() : AUDIO_PORT_HANDLE_NONE;
Eric Laurent2ac76942017-06-22 17:17:09 -07002826
Francois Gaffie716e1432019-01-14 16:58:59 +01002827 isSoundTrigger = attributes.source == AUDIO_SOURCE_HOTWORD &&
Carter Hsud0cce2e2019-05-03 17:36:28 +08002828 mSoundTriggerSessions.indexOfKey(session) >= 0;
jiabin4ef93452019-09-10 14:29:54 -07002829 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002830
Mikhail Naganov2996f672019-04-18 12:29:59 -07002831 clientDesc = new RecordClientDescriptor(*portId, riid, uid, session, attributes, *config,
Francois Gaffie716e1432019-01-14 16:58:59 +01002832 requestedDeviceId, attributes.source, flags,
2833 isSoundTrigger);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002834 inputDesc = mInputs.valueFor(*input);
François Gaffie1b4753e2023-02-06 10:36:33 +01002835 // Move (if found) effect for the client session to its input
2836 mEffects.moveEffectsForIo(session, *input, &mInputs, mpClientInterface);
Andy Hung39efb7a2018-09-26 15:39:28 -07002837 inputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002838
2839 ALOGV("getInputForAttr() returns input %d type %d selectedDeviceId %d for port ID %d",
2840 *input, *inputType, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07002841
Eric Laurent599c7582015-12-07 18:05:55 -08002842 return NO_ERROR;
Eric Laurentad2e7b92017-09-14 20:06:42 -07002843
2844error:
Eric Laurentad2e7b92017-09-14 20:06:42 -07002845 return status;
Eric Laurent599c7582015-12-07 18:05:55 -08002846}
2847
2848
François Gaffie11d30102018-11-02 16:09:09 +01002849audio_io_handle_t AudioPolicyManager::getInputForDevice(const sp<DeviceDescriptor> &device,
Eric Laurent599c7582015-12-07 18:05:55 -08002850 audio_session_t session,
François Gaffiec005e562018-11-06 15:04:49 +01002851 const audio_attributes_t &attributes,
jiabinf1c73972022-04-14 16:28:52 -07002852 audio_config_base_t *config,
Eric Laurent599c7582015-12-07 18:05:55 -08002853 audio_input_flags_t flags,
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002854 const sp<AudioPolicyMix> &policyMix)
Eric Laurent599c7582015-12-07 18:05:55 -08002855{
2856 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
François Gaffiec005e562018-11-06 15:04:49 +01002857 audio_source_t halInputSource = attributes.source;
Eric Laurent599c7582015-12-07 18:05:55 -08002858 bool isSoundTrigger = false;
2859
François Gaffiec005e562018-11-06 15:04:49 +01002860 if (attributes.source == AUDIO_SOURCE_HOTWORD) {
Eric Laurent599c7582015-12-07 18:05:55 -08002861 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
2862 if (index >= 0) {
2863 input = mSoundTriggerSessions.valueFor(session);
2864 isSoundTrigger = true;
2865 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_HW_HOTWORD);
2866 ALOGV("SoundTrigger capture on session %d input %d", session, input);
2867 } else {
2868 halInputSource = AUDIO_SOURCE_VOICE_RECOGNITION;
Eric Laurent5dbe4712014-09-19 19:04:57 -07002869 }
François Gaffiec005e562018-11-06 15:04:49 +01002870 } else if (attributes.source == AUDIO_SOURCE_VOICE_COMMUNICATION &&
Eric Laurentfe231122017-11-17 17:48:06 -08002871 audio_is_linear_pcm(config->format)) {
Haynes Mathew George851d3ff2017-06-19 20:01:57 -07002872 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_VOIP_TX);
Eric Laurent5dbe4712014-09-19 19:04:57 -07002873 }
2874
Carter Hsua3abb402021-10-26 11:11:20 +08002875 if (attributes.source == AUDIO_SOURCE_ULTRASOUND) {
2876 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_ULTRASOUND);
2877 }
2878
Eric Laurentfe231122017-11-17 17:48:06 -08002879 // sampling rate and flags may be updated by getInputProfile
2880 uint32_t profileSamplingRate = (config->sample_rate == 0) ?
2881 SAMPLE_RATE_HZ_DEFAULT : config->sample_rate;
jiabin2fd710d2022-05-02 23:20:22 +00002882 audio_format_t profileFormat = config->format;
Eric Laurentfe231122017-11-17 17:48:06 -08002883 audio_channel_mask_t profileChannelMask = config->channel_mask;
Andy Hungf129b032015-04-07 13:45:50 -07002884 audio_input_flags_t profileFlags = flags;
jiabin2fd710d2022-05-02 23:20:22 +00002885 // find a compatible input profile (not necessarily identical in parameters)
2886 sp<IOProfile> profile = getInputProfile(
2887 device, profileSamplingRate, profileFormat, profileChannelMask, profileFlags);
2888 if (profile == nullptr) {
2889 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07002890 }
jiabin2fd710d2022-05-02 23:20:22 +00002891
Glenn Kasten05ddca52016-02-11 08:17:12 -08002892 // Pick input sampling rate if not specified by client
Eric Laurentfe231122017-11-17 17:48:06 -08002893 uint32_t samplingRate = config->sample_rate;
Glenn Kasten05ddca52016-02-11 08:17:12 -08002894 if (samplingRate == 0) {
2895 samplingRate = profileSamplingRate;
2896 }
Eric Laurente552edb2014-03-10 17:42:56 -07002897
Eric Laurent322b4d22015-04-03 15:57:54 -07002898 if (profile->getModuleHandle() == 0) {
2899 ALOGE("getInputForAttr(): HW module %s not opened", profile->getModuleName());
Eric Laurent599c7582015-12-07 18:05:55 -08002900 return input;
Eric Laurentcf2c0212014-07-25 16:20:43 -07002901 }
2902
Eric Laurentec376dc2021-04-08 20:41:22 +02002903 // Reuse an already opened input if a client with the same session ID already exists
2904 // on that input
2905 for (size_t i = 0; i < mInputs.size(); i++) {
2906 sp <AudioInputDescriptor> desc = mInputs.valueAt(i);
2907 if (desc->mProfile != profile) {
2908 continue;
2909 }
2910 RecordClientVector clients = desc->clientsList();
2911 for (const auto &client : clients) {
2912 if (session == client->session()) {
2913 return desc->mIoHandle;
2914 }
2915 }
2916 }
2917
Eric Laurent3974e3b2017-12-07 17:58:43 -08002918 if (!profile->canOpenNewIo()) {
Eric Laurent4eb58f12018-12-07 16:41:02 -08002919 for (size_t i = 0; i < mInputs.size(); ) {
Eric Laurentc529cf62020-04-17 18:19:10 -07002920 sp<AudioInputDescriptor> desc = mInputs.valueAt(i);
Eric Laurent4eb58f12018-12-07 16:41:02 -08002921 if (desc->mProfile != profile) {
Carter Hsu9a645a92019-05-15 12:15:32 +08002922 i++;
Eric Laurent4eb58f12018-12-07 16:41:02 -08002923 continue;
2924 }
2925 // if sound trigger, reuse input if used by other sound trigger on same session
2926 // else
2927 // reuse input if active client app is not in IDLE state
2928 //
2929 RecordClientVector clients = desc->clientsList();
2930 bool doClose = false;
2931 for (const auto& client : clients) {
2932 if (isSoundTrigger != client->isSoundTrigger()) {
2933 continue;
2934 }
2935 if (client->isSoundTrigger()) {
2936 if (session == client->session()) {
2937 return desc->mIoHandle;
2938 }
2939 continue;
2940 }
2941 if (client->active() && client->appState() != APP_STATE_IDLE) {
2942 return desc->mIoHandle;
2943 }
2944 doClose = true;
2945 }
2946 if (doClose) {
2947 closeInput(desc->mIoHandle);
2948 } else {
2949 i++;
2950 }
2951 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002952 }
2953
Eric Laurentfe231122017-11-17 17:48:06 -08002954 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07002955
Eric Laurentfe231122017-11-17 17:48:06 -08002956 audio_config_t lConfig = AUDIO_CONFIG_INITIALIZER;
2957 lConfig.sample_rate = profileSamplingRate;
2958 lConfig.channel_mask = profileChannelMask;
2959 lConfig.format = profileFormat;
Eric Laurente3014102017-05-03 11:15:43 -07002960
François Gaffie11d30102018-11-02 16:09:09 +01002961 status_t status = inputDesc->open(&lConfig, device, halInputSource, profileFlags, &input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07002962
2963 // only accept input with the exact requested set of parameters
Eric Laurent599c7582015-12-07 18:05:55 -08002964 if (status != NO_ERROR || input == AUDIO_IO_HANDLE_NONE ||
Eric Laurentfe231122017-11-17 17:48:06 -08002965 (profileSamplingRate != lConfig.sample_rate) ||
2966 !audio_formats_match(profileFormat, lConfig.format) ||
2967 (profileChannelMask != lConfig.channel_mask)) {
2968 ALOGW("getInputForAttr() failed opening input: sampling rate %d"
Glenn Kasten49f36ba2017-12-06 13:02:02 -08002969 ", format %#x, channel mask %#x",
Eric Laurentfe231122017-11-17 17:48:06 -08002970 profileSamplingRate, profileFormat, profileChannelMask);
Eric Laurent599c7582015-12-07 18:05:55 -08002971 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfe231122017-11-17 17:48:06 -08002972 inputDesc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07002973 }
Eric Laurent599c7582015-12-07 18:05:55 -08002974 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07002975 }
2976
Eric Laurentc722f302014-12-10 11:21:49 -08002977 inputDesc->mPolicyMix = policyMix;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002978
Eric Laurent599c7582015-12-07 18:05:55 -08002979 addInput(input, inputDesc);
Eric Laurentb52c1522014-05-20 11:27:36 -07002980 mpClientInterface->onAudioPortListUpdate();
Paul McLean466dc8e2015-04-17 13:15:36 -06002981
Eric Laurent599c7582015-12-07 18:05:55 -08002982 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07002983}
2984
Eric Laurent4eb58f12018-12-07 16:41:02 -08002985status_t AudioPolicyManager::startInput(audio_port_handle_t portId)
Eric Laurentbb948092017-01-23 18:33:30 -08002986{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002987 ALOGV("%s portId %d", __FUNCTION__, portId);
2988
2989 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2990 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002991 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurentd52a28c2020-08-21 17:10:39 -07002992 return DEAD_OBJECT;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002993 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002994 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07002995 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002996 if (client->active()) {
2997 ALOGW("%s input %d client %d already started", __FUNCTION__, input, client->portId());
2998 return INVALID_OPERATION;
Eric Laurent4dc68062014-07-28 17:26:49 -07002999 }
3000
Eric Laurent8f42ea12018-08-08 09:08:25 -07003001 audio_session_t session = client->session();
3002
Eric Laurent4eb58f12018-12-07 16:41:02 -08003003 ALOGV("%s input:%d, session:%d)", __FUNCTION__, input, session);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003004
Eric Laurent4eb58f12018-12-07 16:41:02 -08003005 Vector<sp<AudioInputDescriptor>> activeInputs = mInputs.getActiveInputs();
Eric Laurent74708e72017-04-07 17:13:42 -07003006
Eric Laurent4eb58f12018-12-07 16:41:02 -08003007 status_t status = inputDesc->start();
3008 if (status != NO_ERROR) {
3009 return status;
Eric Laurent74708e72017-04-07 17:13:42 -07003010 }
Eric Laurente552edb2014-03-10 17:42:56 -07003011
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003012 // increment activity count before calling getNewInputDevice() below as only active sessions
Eric Laurent313d1e72016-01-29 09:56:57 -08003013 // are considered for device selection
Eric Laurent8f42ea12018-08-08 09:08:25 -07003014 inputDesc->setClientActive(client, true);
Eric Laurent313d1e72016-01-29 09:56:57 -08003015
Eric Laurent8f42ea12018-08-08 09:08:25 -07003016 // indicate active capture to sound trigger service if starting capture from a mic on
3017 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01003018 sp<DeviceDescriptor> device = getNewInputDevice(inputDesc);
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003019 if (device != nullptr) {
3020 status = setInputDevice(input, device, true /* force */);
3021 } else {
3022 ALOGW("%s no new input device can be found for descriptor %d",
3023 __FUNCTION__, inputDesc->getId());
3024 status = BAD_VALUE;
3025 }
Eric Laurente552edb2014-03-10 17:42:56 -07003026
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003027 if (status == NO_ERROR && inputDesc->activeCount() == 1) {
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003028 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003029 // if input maps to a dynamic policy with an activity listener, notify of state change
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003030 if ((policyMix != nullptr)
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003031 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
3032 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
Eric Laurent8f42ea12018-08-08 09:08:25 -07003033 MIX_STATE_MIXING);
Eric Laurent733ce942017-12-07 12:18:25 -08003034 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08003035
François Gaffie11d30102018-11-02 16:09:09 +01003036 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
3037 if (primaryInputDevices.contains(device) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07003038 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 1) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07003039 mpClientInterface->setSoundTriggerCaptureState(true);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003040 }
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07003041
Eric Laurent8f42ea12018-08-08 09:08:25 -07003042 // automatically enable the remote submix output when input is started if not
3043 // used by a policy mix of type MIX_TYPE_RECORDERS
3044 // For remote submix (a virtual device), we open only one input per capture request.
François Gaffie11d30102018-11-02 16:09:09 +01003045 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003046 String8 address = String8("");
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003047 if (policyMix == nullptr) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003048 address = String8("0");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003049 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
3050 address = policyMix->mDeviceAddress;
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07003051 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07003052 if (address != "") {
3053 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
3054 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08003055 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurentc722f302014-12-10 11:21:49 -08003056 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07003057 }
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003058 } else if (status != NO_ERROR) {
3059 // Restore client activity state.
3060 inputDesc->setClientActive(client, false);
3061 inputDesc->stop();
Eric Laurente552edb2014-03-10 17:42:56 -07003062 }
3063
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003064 ALOGV("%s input %d source = %d status = %d exit",
3065 __FUNCTION__, input, client->source(), status);
Eric Laurente552edb2014-03-10 17:42:56 -07003066
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003067 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07003068}
3069
Eric Laurent8fc147b2018-07-22 19:13:55 -07003070status_t AudioPolicyManager::stopInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07003071{
Eric Laurent8fc147b2018-07-22 19:13:55 -07003072 ALOGV("%s portId %d", __FUNCTION__, portId);
3073
3074 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
3075 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003076 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07003077 return BAD_VALUE;
3078 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07003079 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07003080 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003081 if (!client->active()) {
3082 ALOGW("%s input %d client %d already stopped", __FUNCTION__, input, client->portId());
Eric Laurente552edb2014-03-10 17:42:56 -07003083 return INVALID_OPERATION;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003084 }
Carter Hsue6139d52021-07-08 10:30:20 +08003085 auto old_source = inputDesc->source();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003086 inputDesc->setClientActive(client, false);
Paul McLean466dc8e2015-04-17 13:15:36 -06003087
Eric Laurent8f42ea12018-08-08 09:08:25 -07003088 inputDesc->stop();
3089 if (inputDesc->isActive()) {
Carter Hsue6139d52021-07-08 10:30:20 +08003090 auto current_source = inputDesc->source();
3091 setInputDevice(input, getNewInputDevice(inputDesc),
3092 old_source != current_source /* force */);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003093 } else {
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003094 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003095 // if input maps to a dynamic policy with an activity listener, notify of state change
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003096 if ((policyMix != nullptr)
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003097 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
3098 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
Eric Laurent8f42ea12018-08-08 09:08:25 -07003099 MIX_STATE_IDLE);
Eric Laurent84332aa2016-01-28 22:19:18 +00003100 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07003101
3102 // automatically disable the remote submix output when input is stopped if not
3103 // used by a policy mix of type MIX_TYPE_RECORDERS
François Gaffie11d30102018-11-02 16:09:09 +01003104 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003105 String8 address = String8("");
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003106 if (policyMix == nullptr) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003107 address = String8("0");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003108 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
3109 address = policyMix->mDeviceAddress;
Eric Laurent8f42ea12018-08-08 09:08:25 -07003110 }
3111 if (address != "") {
3112 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
3113 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08003114 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003115 }
3116 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07003117 resetInputDevice(input);
3118
3119 // indicate inactive capture to sound trigger service if stopping capture from a mic on
3120 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01003121 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
3122 if (primaryInputDevices.contains(inputDesc->getDevice()) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07003123 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07003124 mpClientInterface->setSoundTriggerCaptureState(false);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003125 }
3126 inputDesc->clearPreemptedSessions();
Eric Laurente552edb2014-03-10 17:42:56 -07003127 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003128 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07003129}
3130
Eric Laurent8fc147b2018-07-22 19:13:55 -07003131void AudioPolicyManager::releaseInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07003132{
Eric Laurent8fc147b2018-07-22 19:13:55 -07003133 ALOGV("%s portId %d", __FUNCTION__, portId);
3134
3135 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
3136 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003137 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07003138 return;
3139 }
Andy Hung39efb7a2018-09-26 15:39:28 -07003140 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8fc147b2018-07-22 19:13:55 -07003141 audio_io_handle_t input = inputDesc->mIoHandle;
3142
Eric Laurent8f42ea12018-08-08 09:08:25 -07003143 ALOGV("%s %d", __FUNCTION__, input);
Paul McLean466dc8e2015-04-17 13:15:36 -06003144
Andy Hung39efb7a2018-09-26 15:39:28 -07003145 inputDesc->removeClient(portId);
François Gaffie1b4753e2023-02-06 10:36:33 +01003146 mEffects.putOrphanEffects(client->session(), input, &mInputs, mpClientInterface);
Andy Hung39efb7a2018-09-26 15:39:28 -07003147 if (inputDesc->getClientCount() > 0) {
3148 ALOGV("%s(%d) %zu clients remaining", __func__, portId, inputDesc->getClientCount());
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003149 return;
3150 }
3151
Eric Laurent05b90f82014-08-27 15:32:29 -07003152 closeInput(input);
Eric Laurentb52c1522014-05-20 11:27:36 -07003153 mpClientInterface->onAudioPortListUpdate();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003154 ALOGV("%s exit", __FUNCTION__);
Eric Laurente552edb2014-03-10 17:42:56 -07003155}
3156
Eric Laurent8f42ea12018-08-08 09:08:25 -07003157void AudioPolicyManager::closeActiveClients(const sp<AudioInputDescriptor>& input)
Eric Laurent8fc147b2018-07-22 19:13:55 -07003158{
Eric Laurent8f42ea12018-08-08 09:08:25 -07003159 RecordClientVector clients = input->clientsList(true);
Eric Laurent8fc147b2018-07-22 19:13:55 -07003160
3161 for (const auto& client : clients) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003162 closeClient(client->portId());
Eric Laurent8fc147b2018-07-22 19:13:55 -07003163 }
3164}
3165
Eric Laurent8f42ea12018-08-08 09:08:25 -07003166void AudioPolicyManager::closeClient(audio_port_handle_t portId)
3167{
3168 stopInput(portId);
3169 releaseInput(portId);
3170}
Eric Laurent8fc147b2018-07-22 19:13:55 -07003171
Eric Laurent0dd51852019-04-19 18:18:58 -07003172void AudioPolicyManager::checkCloseInputs() {
3173 // After connecting or disconnecting an input device, close input if:
3174 // - it has no client (was just opened to check profile) OR
3175 // - none of its supported devices are connected anymore OR
3176 // - one of its clients cannot be routed to one of its supported
3177 // devices anymore. Otherwise update device selection
3178 std::vector<audio_io_handle_t> inputsToClose;
3179 for (size_t i = 0; i < mInputs.size(); i++) {
3180 const sp<AudioInputDescriptor> input = mInputs.valueAt(i);
3181 if (input->clientsList().size() == 0
Eric Laurent85732f42020-03-19 11:31:10 -07003182 || !mAvailableInputDevices.containsAtLeastOne(input->supportedDevices())) {
Eric Laurent0dd51852019-04-19 18:18:58 -07003183 inputsToClose.push_back(mInputs.keyAt(i));
3184 } else {
3185 bool close = false;
3186 for (const auto& client : input->clientsList()) {
3187 sp<DeviceDescriptor> device =
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02003188 mEngine->getInputDeviceForAttributes(client->attributes(), client->uid(),
3189 client->session());
Eric Laurent0dd51852019-04-19 18:18:58 -07003190 if (!input->supportedDevices().contains(device)) {
3191 close = true;
3192 break;
3193 }
3194 }
3195 if (close) {
3196 inputsToClose.push_back(mInputs.keyAt(i));
3197 } else {
3198 setInputDevice(input->mIoHandle, getNewInputDevice(input));
3199 }
3200 }
3201 }
3202
3203 for (const audio_io_handle_t handle : inputsToClose) {
3204 ALOGV("%s closing input %d", __func__, handle);
3205 closeInput(handle);
Eric Laurent05b90f82014-08-27 15:32:29 -07003206 }
Eric Laurentd4692962014-05-05 18:13:44 -07003207}
3208
François Gaffie251c7f02018-11-07 10:41:08 +01003209void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream, int indexMin, int indexMax)
Eric Laurente552edb2014-03-10 17:42:56 -07003210{
3211 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08003212 if (indexMin < 0 || indexMax < 0) {
3213 ALOGE("%s for stream %d: invalid min %d or max %d", __func__, stream , indexMin, indexMax);
3214 return;
3215 }
Eric Laurentf5aa58d2019-02-22 18:20:11 -08003216 getVolumeCurves(stream).initVolume(indexMin, indexMax);
Eric Laurent28d09f02016-03-08 10:43:05 -08003217
3218 // initialize other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08003219 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
3220 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08003221 continue;
3222 }
Eric Laurentf5aa58d2019-02-22 18:20:11 -08003223 getVolumeCurves((audio_stream_type_t)curStream).initVolume(indexMin, indexMax);
Eric Laurent223fd5c2014-11-11 13:43:36 -08003224 }
Eric Laurente552edb2014-03-10 17:42:56 -07003225}
3226
Eric Laurente0720872014-03-11 09:30:41 -07003227status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
François Gaffie53615e22015-03-19 09:24:12 +01003228 int index,
3229 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07003230{
François Gaffieaaac0fd2018-11-22 17:56:39 +01003231 auto attributes = mEngine->getAttributesForStreamType(stream);
Eric Laurent242a9f82020-03-23 15:57:04 -07003232 if (attributes == AUDIO_ATTRIBUTES_INITIALIZER) {
3233 ALOGW("%s: no group for stream %s, bailing out", __func__, toString(stream).c_str());
3234 return NO_ERROR;
3235 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01003236 ALOGV("%s: stream %s attributes=%s", __func__,
3237 toString(stream).c_str(), toString(attributes).c_str());
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003238 return setVolumeIndexForAttributes(attributes, index, device);
Eric Laurente552edb2014-03-10 17:42:56 -07003239}
3240
Eric Laurente0720872014-03-11 09:30:41 -07003241status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
François Gaffieaaac0fd2018-11-22 17:56:39 +01003242 int *index,
3243 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07003244{
François Gaffiec005e562018-11-06 15:04:49 +01003245 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
3246 // stream by the engine.
jiabin9a3361e2019-10-01 09:38:30 -07003247 DeviceTypeSet deviceTypes = {device};
Eric Laurent5a2b6292016-04-14 18:05:57 -07003248 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
jiabin9a3361e2019-10-01 09:38:30 -07003249 deviceTypes = mEngine->getOutputDevicesForStream(
3250 stream, true /*fromCache*/).types();
Eric Laurente552edb2014-03-10 17:42:56 -07003251 }
jiabin9a3361e2019-10-01 09:38:30 -07003252 return getVolumeIndex(getVolumeCurves(stream), *index, deviceTypes);
Eric Laurente552edb2014-03-10 17:42:56 -07003253}
3254
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003255status_t AudioPolicyManager::setVolumeIndexForAttributes(const audio_attributes_t &attributes,
François Gaffiecfe17322018-11-07 13:41:29 +01003256 int index,
3257 audio_devices_t device)
3258{
3259 // Get Volume group matching the Audio Attributes
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003260 auto group = mEngine->getVolumeGroupForAttributes(attributes);
3261 if (group == VOLUME_GROUP_NONE) {
3262 ALOGD("%s: no group matching with %s", __FUNCTION__, toString(attributes).c_str());
François Gaffiecfe17322018-11-07 13:41:29 +01003263 return BAD_VALUE;
3264 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003265 ALOGV("%s: group %d matching with %s", __FUNCTION__, group, toString(attributes).c_str());
François Gaffiecfe17322018-11-07 13:41:29 +01003266 status_t status = NO_ERROR;
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003267 IVolumeCurves &curves = getVolumeCurves(attributes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01003268 VolumeSource vs = toVolumeSource(group);
Eric Laurentf9cccec2022-11-16 19:12:00 +01003269 // AUDIO_STREAM_BLUETOOTH_SCO is only used for volume control so we remap
3270 // to AUDIO_STREAM_VOICE_CALL to match with relevant playback activity
3271 VolumeSource activityVs = (vs == toVolumeSource(AUDIO_STREAM_BLUETOOTH_SCO, false)) ?
3272 toVolumeSource(AUDIO_STREAM_VOICE_CALL, false) : vs;
François Gaffieaaac0fd2018-11-22 17:56:39 +01003273 product_strategy_t strategy = mEngine->getProductStrategyForAttributes(attributes);
3274
3275 status = setVolumeCurveIndex(index, device, curves);
3276 if (status != NO_ERROR) {
3277 ALOGE("%s failed to set curve index for group %d device 0x%X", __func__, group, device);
3278 return status;
3279 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003280
jiabin9a3361e2019-10-01 09:38:30 -07003281 DeviceTypeSet curSrcDevices;
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003282 auto curCurvAttrs = curves.getAttributes();
3283 if (!curCurvAttrs.empty() && curCurvAttrs.front() != defaultAttr) {
3284 auto attr = curCurvAttrs.front();
jiabin9a3361e2019-10-01 09:38:30 -07003285 curSrcDevices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false).types();
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003286 } else if (!curves.getStreamTypes().empty()) {
3287 auto stream = curves.getStreamTypes().front();
jiabin9a3361e2019-10-01 09:38:30 -07003288 curSrcDevices = mEngine->getOutputDevicesForStream(stream, false).types();
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003289 } else {
3290 ALOGE("%s: Invalid src %d: no valid attributes nor stream",__func__, vs);
3291 return BAD_VALUE;
3292 }
jiabin9a3361e2019-10-01 09:38:30 -07003293 audio_devices_t curSrcDevice = Volume::getDeviceForVolume(curSrcDevices);
3294 resetDeviceTypes(curSrcDevices, curSrcDevice);
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003295
François Gaffiecfe17322018-11-07 13:41:29 +01003296 // update volume on all outputs and streams matching the following:
3297 // - The requested stream (or a stream matching for volume control) is active on the output
3298 // - The device (or devices) selected by the engine for this stream includes
3299 // the requested device
3300 // - For non default requested device, currently selected device on the output is either the
3301 // requested device or one of the devices selected by the engine for this stream
3302 // - For default requested device (AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME), apply volume only if
3303 // no specific device volume value exists for currently selected device.
François Gaffieaaac0fd2018-11-22 17:56:39 +01003304 for (size_t i = 0; i < mOutputs.size(); i++) {
3305 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
jiabin9a3361e2019-10-01 09:38:30 -07003306 DeviceTypeSet curDevices = desc->devices().types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01003307
jiabin9a3361e2019-10-01 09:38:30 -07003308 if (curDevices.erase(AUDIO_DEVICE_OUT_SPEAKER_SAFE)) {
3309 curDevices.insert(AUDIO_DEVICE_OUT_SPEAKER);
Robert Lee5e66e792019-04-03 18:37:15 +08003310 }
Eric Laurentf9cccec2022-11-16 19:12:00 +01003311
3312 if (!(desc->isActive(activityVs) || isInCallOrScreening())) {
François Gaffieed91f582020-01-31 10:35:37 +01003313 continue;
3314 }
3315 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME &&
3316 curDevices.find(device) == curDevices.end()) {
3317 continue;
3318 }
3319 bool applyVolume = false;
3320 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
3321 curSrcDevices.insert(device);
3322 applyVolume = (curSrcDevices.find(
3323 Volume::getDeviceForVolume(curDevices)) != curSrcDevices.end());
3324 } else {
3325 applyVolume = !curves.hasVolumeIndexForDevice(curSrcDevice);
3326 }
3327 if (!applyVolume) {
3328 continue; // next output
3329 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01003330 // Inter / intra volume group priority management: Loop on strategies arranged by priority
3331 // If a higher priority strategy is active, and the output is routed to a device with a
3332 // HW Gain management, do not change the volume
François Gaffieaaac0fd2018-11-22 17:56:39 +01003333 if (desc->useHwGain()) {
François Gaffieed91f582020-01-31 10:35:37 +01003334 applyVolume = false;
Francois Gaffie593634d2021-06-22 13:31:31 +02003335 // If the volume source is active with higher priority source, ensure at least Sw Muted
3336 desc->setSwMute((index == 0), vs, curves.getStreamTypes(), curDevices, 0 /*delayMs*/);
François Gaffieaaac0fd2018-11-22 17:56:39 +01003337 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
3338 auto activeClients = desc->clientsList(true /*activeOnly*/, productStrategy,
3339 false /*preferredDevice*/);
3340 if (activeClients.empty()) {
3341 continue;
3342 }
3343 bool isPreempted = false;
3344 bool isHigherPriority = productStrategy < strategy;
3345 for (const auto &client : activeClients) {
Eric Laurentf9cccec2022-11-16 19:12:00 +01003346 if (isHigherPriority && (client->volumeSource() != activityVs)) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01003347 ALOGV("%s: Strategy=%d (\nrequester:\n"
3348 " group %d, volumeGroup=%d attributes=%s)\n"
3349 " higher priority source active:\n"
3350 " volumeGroup=%d attributes=%s) \n"
3351 " on output %zu, bailing out", __func__, productStrategy,
3352 group, group, toString(attributes).c_str(),
3353 client->volumeSource(), toString(client->attributes()).c_str(), i);
3354 applyVolume = false;
3355 isPreempted = true;
3356 break;
3357 }
3358 // However, continue for loop to ensure no higher prio clients running on output
Eric Laurentf9cccec2022-11-16 19:12:00 +01003359 if (client->volumeSource() == activityVs) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01003360 applyVolume = true;
3361 }
3362 }
3363 if (isPreempted || applyVolume) {
3364 break;
3365 }
3366 }
3367 if (!applyVolume) {
3368 continue; // next output
3369 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01003370 }
François Gaffieed91f582020-01-31 10:35:37 +01003371 //FIXME: workaround for truncated touch sounds
3372 // delayed volume change for system stream to be removed when the problem is
3373 // handled by system UI
3374 status_t volStatus = checkAndSetVolume(
3375 curves, vs, index, desc, curDevices,
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003376 ((vs == toVolumeSource(AUDIO_STREAM_SYSTEM, false))?
François Gaffieed91f582020-01-31 10:35:37 +01003377 TOUCH_SOUND_FIXED_DELAY_MS : 0));
3378 if (volStatus != NO_ERROR) {
3379 status = volStatus;
François Gaffieaaac0fd2018-11-22 17:56:39 +01003380 }
3381 }
François Gaffiecfe17322018-11-07 13:41:29 +01003382 mpClientInterface->onAudioVolumeGroupChanged(group, 0 /*flags*/);
3383 return status;
3384}
3385
François Gaffieaaac0fd2018-11-22 17:56:39 +01003386status_t AudioPolicyManager::setVolumeCurveIndex(int index,
François Gaffiecfe17322018-11-07 13:41:29 +01003387 audio_devices_t device,
3388 IVolumeCurves &volumeCurves)
3389{
3390 // VOICE_CALL stream has minVolumeIndex > 0 but can be muted directly by an
3391 // app that has MODIFY_PHONE_STATE permission.
François Gaffieaaac0fd2018-11-22 17:56:39 +01003392 bool hasVoice = hasVoiceStream(volumeCurves.getStreamTypes());
3393 if (((index < volumeCurves.getVolumeIndexMin()) && !(hasVoice && index == 0)) ||
François Gaffiecfe17322018-11-07 13:41:29 +01003394 (index > volumeCurves.getVolumeIndexMax())) {
3395 ALOGD("%s: wrong index %d min=%d max=%d", __FUNCTION__, index,
3396 volumeCurves.getVolumeIndexMin(), volumeCurves.getVolumeIndexMax());
3397 return BAD_VALUE;
3398 }
3399 if (!audio_is_output_device(device)) {
3400 return BAD_VALUE;
3401 }
3402
3403 // Force max volume if stream cannot be muted
3404 if (!volumeCurves.canBeMuted()) index = volumeCurves.getVolumeIndexMax();
3405
François Gaffieaaac0fd2018-11-22 17:56:39 +01003406 ALOGV("%s device %08x, index %d", __FUNCTION__ , device, index);
François Gaffiecfe17322018-11-07 13:41:29 +01003407 volumeCurves.addCurrentVolumeIndex(device, index);
3408 return NO_ERROR;
3409}
3410
3411status_t AudioPolicyManager::getVolumeIndexForAttributes(const audio_attributes_t &attr,
3412 int &index,
3413 audio_devices_t device)
3414{
3415 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
3416 // stream by the engine.
jiabin9a3361e2019-10-01 09:38:30 -07003417 DeviceTypeSet deviceTypes = {device};
François Gaffiecfe17322018-11-07 13:41:29 +01003418 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
Mikhail Naganovbb990f22022-06-15 00:46:43 +00003419 deviceTypes = mEngine->getOutputDevicesForAttributes(
jiabin9a3361e2019-10-01 09:38:30 -07003420 attr, nullptr, true /*fromCache*/).types();
François Gaffiecfe17322018-11-07 13:41:29 +01003421 }
jiabin9a3361e2019-10-01 09:38:30 -07003422 return getVolumeIndex(getVolumeCurves(attr), index, deviceTypes);
François Gaffiecfe17322018-11-07 13:41:29 +01003423}
3424
3425status_t AudioPolicyManager::getVolumeIndex(const IVolumeCurves &curves,
3426 int &index,
jiabin9a3361e2019-10-01 09:38:30 -07003427 const DeviceTypeSet& deviceTypes) const
François Gaffiecfe17322018-11-07 13:41:29 +01003428{
Mikhail Naganovbb990f22022-06-15 00:46:43 +00003429 if (!isSingleDeviceType(deviceTypes, audio_is_output_device)) {
François Gaffiecfe17322018-11-07 13:41:29 +01003430 return BAD_VALUE;
3431 }
jiabin9a3361e2019-10-01 09:38:30 -07003432 index = curves.getVolumeIndex(deviceTypes);
3433 ALOGV("%s: device %s index %d", __FUNCTION__, dumpDeviceTypes(deviceTypes).c_str(), index);
François Gaffiecfe17322018-11-07 13:41:29 +01003434 return NO_ERROR;
3435}
3436
3437status_t AudioPolicyManager::getMinVolumeIndexForAttributes(const audio_attributes_t &attr,
3438 int &index)
3439{
3440 index = getVolumeCurves(attr).getVolumeIndexMin();
3441 return NO_ERROR;
3442}
3443
3444status_t AudioPolicyManager::getMaxVolumeIndexForAttributes(const audio_attributes_t &attr,
3445 int &index)
3446{
3447 index = getVolumeCurves(attr).getVolumeIndexMax();
3448 return NO_ERROR;
3449}
3450
Eric Laurent36829f92017-04-07 19:04:42 -07003451audio_io_handle_t AudioPolicyManager::selectOutputForMusicEffects()
Eric Laurente552edb2014-03-10 17:42:56 -07003452{
3453 // select one output among several suitable for global effects.
3454 // The priority is as follows:
3455 // 1: An offloaded output. If the effect ends up not being offloadable,
3456 // AudioFlinger will invalidate the track and the offloaded output
3457 // will be closed causing the effect to be moved to a PCM output.
3458 // 2: A deep buffer output
Eric Laurent36829f92017-04-07 19:04:42 -07003459 // 3: The primary output
3460 // 4: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07003461
François Gaffiec005e562018-11-06 15:04:49 +01003462 DeviceVector devices = mEngine->getOutputDevicesForAttributes(
3463 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
François Gaffie11d30102018-11-02 16:09:09 +01003464 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07003465
Eric Laurent36829f92017-04-07 19:04:42 -07003466 if (outputs.size() == 0) {
3467 return AUDIO_IO_HANDLE_NONE;
3468 }
Eric Laurente552edb2014-03-10 17:42:56 -07003469
Eric Laurent36829f92017-04-07 19:04:42 -07003470 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
3471 bool activeOnly = true;
3472
3473 while (output == AUDIO_IO_HANDLE_NONE) {
3474 audio_io_handle_t outputOffloaded = AUDIO_IO_HANDLE_NONE;
3475 audio_io_handle_t outputDeepBuffer = AUDIO_IO_HANDLE_NONE;
3476 audio_io_handle_t outputPrimary = AUDIO_IO_HANDLE_NONE;
3477
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003478 for (audio_io_handle_t output : outputs) {
3479 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
Eric Laurent83d17c22019-04-02 17:10:01 -07003480 if (activeOnly && !desc->isActive(toVolumeSource(AUDIO_STREAM_MUSIC))) {
Eric Laurent36829f92017-04-07 19:04:42 -07003481 continue;
3482 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003483 ALOGV("selectOutputForMusicEffects activeOnly %d output %d flags 0x%08x",
3484 activeOnly, output, desc->mFlags);
Eric Laurent36829f92017-04-07 19:04:42 -07003485 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003486 outputOffloaded = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003487 }
3488 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003489 outputDeepBuffer = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003490 }
3491 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003492 outputPrimary = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003493 }
3494 }
3495 if (outputOffloaded != AUDIO_IO_HANDLE_NONE) {
3496 output = outputOffloaded;
3497 } else if (outputDeepBuffer != AUDIO_IO_HANDLE_NONE) {
3498 output = outputDeepBuffer;
3499 } else if (outputPrimary != AUDIO_IO_HANDLE_NONE) {
3500 output = outputPrimary;
3501 } else {
3502 output = outputs[0];
3503 }
3504 activeOnly = false;
3505 }
3506
3507 if (output != mMusicEffectOutput) {
François Gaffie1b4753e2023-02-06 10:36:33 +01003508 mEffects.moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output,
3509 mpClientInterface);
Eric Laurent36829f92017-04-07 19:04:42 -07003510 mMusicEffectOutput = output;
3511 }
3512
3513 ALOGV("selectOutputForMusicEffects selected output %d", output);
Eric Laurente552edb2014-03-10 17:42:56 -07003514 return output;
3515}
3516
Eric Laurent36829f92017-04-07 19:04:42 -07003517audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc __unused)
3518{
3519 return selectOutputForMusicEffects();
3520}
3521
Eric Laurente0720872014-03-11 09:30:41 -07003522status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07003523 audio_io_handle_t io,
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08003524 product_strategy_t strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07003525 int session,
3526 int id)
3527{
Eric Laurentb82e6b72019-11-22 17:25:04 -08003528 if (session != AUDIO_SESSION_DEVICE) {
3529 ssize_t index = mOutputs.indexOfKey(io);
Eric Laurente552edb2014-03-10 17:42:56 -07003530 if (index < 0) {
Eric Laurentb82e6b72019-11-22 17:25:04 -08003531 index = mInputs.indexOfKey(io);
3532 if (index < 0) {
3533 ALOGW("registerEffect() unknown io %d", io);
3534 return INVALID_OPERATION;
3535 }
Eric Laurente552edb2014-03-10 17:42:56 -07003536 }
3537 }
Eric Laurentbf8f69f2022-03-25 17:48:38 +01003538 bool isMusicEffect = (session != AUDIO_SESSION_OUTPUT_STAGE)
3539 && ((strategy == streamToStrategy(AUDIO_STREAM_MUSIC)
3540 || strategy == PRODUCT_STRATEGY_NONE));
3541 return mEffects.registerEffect(desc, io, session, id, isMusicEffect);
Eric Laurente552edb2014-03-10 17:42:56 -07003542}
3543
Eric Laurentc241b0d2018-11-28 09:08:49 -08003544status_t AudioPolicyManager::unregisterEffect(int id)
3545{
3546 if (mEffects.getEffect(id) == nullptr) {
3547 return INVALID_OPERATION;
3548 }
Eric Laurentc241b0d2018-11-28 09:08:49 -08003549 if (mEffects.isEffectEnabled(id)) {
3550 ALOGW("%s effect %d enabled", __FUNCTION__, id);
3551 setEffectEnabled(id, false);
3552 }
3553 return mEffects.unregisterEffect(id);
3554}
3555
3556status_t AudioPolicyManager::setEffectEnabled(int id, bool enabled)
3557{
3558 sp<EffectDescriptor> effect = mEffects.getEffect(id);
3559 if (effect == nullptr) {
3560 return INVALID_OPERATION;
3561 }
3562
3563 status_t status = mEffects.setEffectEnabled(id, enabled);
3564 if (status == NO_ERROR) {
3565 mInputs.trackEffectEnabled(effect, enabled);
3566 }
3567 return status;
3568}
3569
Eric Laurent6c796322019-04-09 14:13:17 -07003570
3571status_t AudioPolicyManager::moveEffectsToIo(const std::vector<int>& ids, audio_io_handle_t io)
3572{
3573 mEffects.moveEffects(ids, io);
3574 return NO_ERROR;
3575}
3576
Eric Laurentc75307b2015-03-17 15:29:32 -07003577bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
3578{
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003579 auto vs = toVolumeSource(stream, false);
3580 return vs != VOLUME_SOURCE_NONE ? mOutputs.isActive(vs, inPastMs) : false;
Eric Laurentc75307b2015-03-17 15:29:32 -07003581}
3582
3583bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream, uint32_t inPastMs) const
3584{
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003585 auto vs = toVolumeSource(stream, false);
3586 return vs != VOLUME_SOURCE_NONE ? mOutputs.isActiveRemotely(vs, inPastMs) : false;
Eric Laurentc75307b2015-03-17 15:29:32 -07003587}
3588
Eric Laurente0720872014-03-11 09:30:41 -07003589bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07003590{
3591 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003592 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08003593 if (inputDescriptor->isSourceActive(source)) {
Eric Laurente552edb2014-03-10 17:42:56 -07003594 return true;
3595 }
3596 }
3597 return false;
3598}
3599
Eric Laurent275e8e92014-11-30 15:14:47 -08003600// Register a list of custom mixes with their attributes and format.
3601// When a mix is registered, corresponding input and output profiles are
3602// added to the remote submix hw module. The profile contains only the
3603// parameters (sampling rate, format...) specified by the mix.
3604// The corresponding input remote submix device is also connected.
3605//
3606// When a remote submix device is connected, the address is checked to select the
3607// appropriate profile and the corresponding input or output stream is opened.
3608//
3609// When capture starts, getInputForAttr() will:
3610// - 1 look for a mix matching the address passed in attribtutes tags if any
3611// - 2 if none found, getDeviceForInputSource() will:
3612// - 2.1 look for a mix matching the attributes source
3613// - 2.2 if none found, default to device selection by policy rules
3614// At this time, the corresponding output remote submix device is also connected
3615// and active playback use cases can be transferred to this mix if needed when reconnecting
3616// after AudioTracks are invalidated
3617//
3618// When playback starts, getOutputForAttr() will:
3619// - 1 look for a mix matching the address passed in attribtutes tags if any
3620// - 2 if none found, look for a mix matching the attributes usage
3621// - 3 if none found, default to device and output selection by policy rules.
3622
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003623status_t AudioPolicyManager::registerPolicyMixes(const Vector<AudioMix>& mixes)
Eric Laurent275e8e92014-11-30 15:14:47 -08003624{
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003625 ALOGV("registerPolicyMixes() %zu mix(es)", mixes.size());
3626 status_t res = NO_ERROR;
Eric Laurentc209fe42020-06-05 18:11:23 -07003627 bool checkOutputs = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003628 sp<HwModule> rSubmixModule;
3629 // examine each mix's route type
3630 for (size_t i = 0; i < mixes.size(); i++) {
Eric Laurent97ac8712018-07-27 18:59:02 -07003631 AudioMix mix = mixes[i];
Kevin Rocard153f92d2018-12-18 18:33:28 -08003632 // Only capture of playback is allowed in LOOP_BACK & RENDER mode
3633 if (is_mix_loopback_render(mix.mRouteFlags) && mix.mMixType != MIX_TYPE_PLAYERS) {
3634 ALOGE("Unsupported Policy Mix %zu of %zu: "
3635 "Only capture of playback is allowed in LOOP_BACK & RENDER mode",
3636 i, mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003637 res = INVALID_OPERATION;
Eric Laurent275e8e92014-11-30 15:14:47 -08003638 break;
3639 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08003640 // LOOP_BACK and LOOP_BACK | RENDER have the same remote submix backend and are handled
3641 // in the same way.
Eric Laurent97ac8712018-07-27 18:59:02 -07003642 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003643 ALOGV("registerPolicyMixes() mix %zu of %zu is LOOP_BACK %d", i, mixes.size(),
3644 mix.mRouteFlags);
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003645 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003646 rSubmixModule = mHwModules.getModuleFromName(
3647 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
3648 if (rSubmixModule == 0) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003649 ALOGE("Unable to find audio module for submix, aborting mix %zu registration",
Mikhail Naganovd4120142017-12-06 15:49:22 -08003650 i);
3651 res = INVALID_OPERATION;
3652 break;
3653 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003654 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003655
Eric Laurent97ac8712018-07-27 18:59:02 -07003656 String8 address = mix.mDeviceAddress;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003657 audio_devices_t deviceTypeToMakeAvailable;
Eric Laurent97ac8712018-07-27 18:59:02 -07003658 if (mix.mMixType == MIX_TYPE_PLAYERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07003659 mix.mDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003660 deviceTypeToMakeAvailable = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
3661 } else {
3662 mix.mDeviceType = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
3663 deviceTypeToMakeAvailable = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Eric Laurent97ac8712018-07-27 18:59:02 -07003664 }
François Gaffie036e1e92015-03-19 10:16:24 +01003665
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003666 if (mPolicyMixes.registerMix(mix, 0 /*output desc*/) != NO_ERROR) {
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003667 ALOGE("Error registering mix %zu for address %s", i, address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003668 res = INVALID_OPERATION;
3669 break;
3670 }
Eric Laurent97ac8712018-07-27 18:59:02 -07003671 audio_config_t outputConfig = mix.mFormat;
3672 audio_config_t inputConfig = mix.mFormat;
Eric Laurentc529cf62020-04-17 18:19:10 -07003673 // NOTE: audio flinger mixer does not support mono output: configure remote submix HAL
3674 // in stereo and let audio flinger do the channel conversion if needed.
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003675 outputConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
3676 inputConfig.channel_mask = AUDIO_CHANNEL_IN_STEREO;
jiabin5740f082019-08-19 15:08:30 -07003677 rSubmixModule->addOutputProfile(address.c_str(), &outputConfig,
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003678 AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address);
jiabin5740f082019-08-19 15:08:30 -07003679 rSubmixModule->addInputProfile(address.c_str(), &inputConfig,
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003680 AUDIO_DEVICE_IN_REMOTE_SUBMIX, address);
François Gaffie036e1e92015-03-19 10:16:24 +01003681
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003682 if ((res = setDeviceConnectionStateInt(deviceTypeToMakeAvailable,
jiabinc1de2df2019-05-07 14:26:40 -07003683 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003684 address.c_str(), "remote-submix", AUDIO_FORMAT_DEFAULT)) != NO_ERROR) {
jiabinc1de2df2019-05-07 14:26:40 -07003685 ALOGE("Failed to set remote submix device available, type %u, address %s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003686 mix.mDeviceType, address.c_str());
jiabinc1de2df2019-05-07 14:26:40 -07003687 break;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003688 }
Eric Laurent97ac8712018-07-27 18:59:02 -07003689 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
3690 String8 address = mix.mDeviceAddress;
Eric Laurent2c80be02019-01-23 18:06:37 -08003691 audio_devices_t type = mix.mDeviceType;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003692 ALOGV(" registerPolicyMixes() mix %zu of %zu is RENDER, dev=0x%X addr=%s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003693 i, mixes.size(), type, address.c_str());
Eric Laurent2c80be02019-01-23 18:06:37 -08003694
3695 sp<DeviceDescriptor> device = mHwModules.getDeviceDescriptor(
3696 mix.mDeviceType, mix.mDeviceAddress,
3697 String8(), AUDIO_FORMAT_DEFAULT);
3698 if (device == nullptr) {
3699 res = INVALID_OPERATION;
3700 break;
3701 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003702
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003703 bool foundOutput = false;
Eric Laurentc529cf62020-04-17 18:19:10 -07003704 // First try to find an already opened output supporting the device
3705 for (size_t j = 0 ; j < mOutputs.size() && !foundOutput && res == NO_ERROR; j++) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003706 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurent2c80be02019-01-23 18:06:37 -08003707
Eric Laurentc529cf62020-04-17 18:19:10 -07003708 if (!desc->isDuplicated() && desc->supportedDevices().contains(device)) {
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003709 if (mPolicyMixes.registerMix(mix, desc) != NO_ERROR) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003710 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003711 address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003712 res = INVALID_OPERATION;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003713 } else {
3714 foundOutput = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003715 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003716 }
3717 }
Eric Laurentc529cf62020-04-17 18:19:10 -07003718 // If no output found, try to find a direct output profile supporting the device
3719 for (size_t i = 0; i < mHwModules.size() && !foundOutput && res == NO_ERROR; i++) {
3720 sp<HwModule> module = mHwModules[i];
3721 for (size_t j = 0;
3722 j < module->getOutputProfiles().size() && !foundOutput && res == NO_ERROR;
3723 j++) {
3724 sp<IOProfile> profile = module->getOutputProfiles()[j];
3725 if (profile->isDirectOutput() && profile->supportsDevice(device)) {
3726 if (mPolicyMixes.registerMix(mix, nullptr) != NO_ERROR) {
3727 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003728 address.c_str());
Eric Laurentc529cf62020-04-17 18:19:10 -07003729 res = INVALID_OPERATION;
3730 } else {
3731 foundOutput = true;
3732 }
3733 }
3734 }
3735 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003736 if (res != NO_ERROR) {
3737 ALOGE(" Error registering mix %zu for device 0x%X addr %s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003738 i, type, address.c_str());
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003739 res = INVALID_OPERATION;
3740 break;
3741 } else if (!foundOutput) {
3742 ALOGE(" Output not found for mix %zu for device 0x%X addr %s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003743 i, type, address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003744 res = INVALID_OPERATION;
3745 break;
Eric Laurentc209fe42020-06-05 18:11:23 -07003746 } else {
3747 checkOutputs = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003748 }
Eric Laurentc722f302014-12-10 11:21:49 -08003749 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003750 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003751 if (res != NO_ERROR) {
3752 unregisterPolicyMixes(mixes);
Eric Laurentc209fe42020-06-05 18:11:23 -07003753 } else if (checkOutputs) {
3754 checkForDeviceAndOutputChanges();
3755 updateCallAndOutputRouting();
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003756 }
3757 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08003758}
3759
3760status_t AudioPolicyManager::unregisterPolicyMixes(Vector<AudioMix> mixes)
3761{
Eric Laurent7b279bb2015-12-14 10:18:23 -08003762 ALOGV("unregisterPolicyMixes() num mixes %zu", mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003763 status_t res = NO_ERROR;
Eric Laurentc209fe42020-06-05 18:11:23 -07003764 bool checkOutputs = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003765 sp<HwModule> rSubmixModule;
3766 // examine each mix's route type
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003767 for (const auto& mix : mixes) {
3768 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie036e1e92015-03-19 10:16:24 +01003769
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003770 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003771 rSubmixModule = mHwModules.getModuleFromName(
3772 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
3773 if (rSubmixModule == 0) {
3774 res = INVALID_OPERATION;
3775 continue;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003776 }
3777 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003778
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003779 String8 address = mix.mDeviceAddress;
Eric Laurent275e8e92014-11-30 15:14:47 -08003780
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003781 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003782 res = INVALID_OPERATION;
3783 continue;
3784 }
3785
Kevin Rocard04ed0462019-05-02 17:53:24 -07003786 for (auto device : {AUDIO_DEVICE_IN_REMOTE_SUBMIX, AUDIO_DEVICE_OUT_REMOTE_SUBMIX}) {
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003787 if (getDeviceConnectionState(device, address.c_str()) ==
Kevin Rocard04ed0462019-05-02 17:53:24 -07003788 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
3789 res = setDeviceConnectionStateInt(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003790 address.c_str(), "remote-submix",
Kevin Rocard04ed0462019-05-02 17:53:24 -07003791 AUDIO_FORMAT_DEFAULT);
3792 if (res != OK) {
3793 ALOGE("Error making RemoteSubmix device unavailable for mix "
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003794 "with type %d, address %s", device, address.c_str());
Kevin Rocard04ed0462019-05-02 17:53:24 -07003795 }
3796 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003797 }
jiabin5740f082019-08-19 15:08:30 -07003798 rSubmixModule->removeOutputProfile(address.c_str());
3799 rSubmixModule->removeInputProfile(address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003800
Kevin Rocard153f92d2018-12-18 18:33:28 -08003801 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003802 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003803 res = INVALID_OPERATION;
3804 continue;
Eric Laurentc209fe42020-06-05 18:11:23 -07003805 } else {
3806 checkOutputs = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003807 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003808 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003809 }
Eric Laurentc209fe42020-06-05 18:11:23 -07003810 if (res == NO_ERROR && checkOutputs) {
3811 checkForDeviceAndOutputChanges();
3812 updateCallAndOutputRouting();
3813 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003814 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08003815}
3816
Jan Sebechlebsky0af8e872023-08-11 14:45:08 +02003817status_t AudioPolicyManager::updatePolicyMix(
3818 const AudioMix& mix,
3819 const std::vector<AudioMixMatchCriterion>& updatedCriteria) {
3820 status_t res = mPolicyMixes.updateMix(mix, updatedCriteria);
3821 if (res == NO_ERROR) {
3822 checkForDeviceAndOutputChanges();
3823 updateCallAndOutputRouting();
3824 }
3825 return res;
3826}
3827
Mikhail Naganov100f0122018-11-29 11:22:16 -08003828void AudioPolicyManager::dumpManualSurroundFormats(String8 *dst) const
3829{
3830 size_t i = 0;
3831 constexpr size_t audioFormatPrefixLen = sizeof("AUDIO_FORMAT_");
3832 for (const auto& fmt : mManualSurroundFormats) {
3833 if (i++ != 0) dst->append(", ");
3834 std::string sfmt;
3835 FormatConverter::toString(fmt, sfmt);
3836 dst->append(sfmt.size() >= audioFormatPrefixLen ?
3837 sfmt.c_str() + audioFormatPrefixLen - 1 : sfmt.c_str());
3838 }
3839}
3840
Eric Laurentc529cf62020-04-17 18:19:10 -07003841// Returns true if all devices types match the predicate and are supported by one HW module
3842bool AudioPolicyManager::areAllDevicesSupported(
jiabin6a02d532020-08-07 11:56:38 -07003843 const AudioDeviceTypeAddrVector& devices,
Eric Laurentc529cf62020-04-17 18:19:10 -07003844 std::function<bool(audio_devices_t)> predicate,
Eric Laurent78fedbf2023-03-09 14:40:44 +01003845 const char *context,
3846 bool matchAddress) {
Eric Laurentc529cf62020-04-17 18:19:10 -07003847 for (size_t i = 0; i < devices.size(); i++) {
3848 sp<DeviceDescriptor> devDesc = mHwModules.getDeviceDescriptor(
jiabin0a488932020-08-07 17:32:40 -07003849 devices[i].mType, devices[i].getAddress(), String8(),
Eric Laurent78fedbf2023-03-09 14:40:44 +01003850 AUDIO_FORMAT_DEFAULT, false /*allowToCreate*/, matchAddress);
Eric Laurentc529cf62020-04-17 18:19:10 -07003851 if (devDesc == nullptr || (predicate != nullptr && !predicate(devices[i].mType))) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003852 ALOGE("%s: device type %#x address %s not supported or not match predicate",
jiabin0a488932020-08-07 17:32:40 -07003853 context, devices[i].mType, devices[i].getAddress());
Eric Laurentc529cf62020-04-17 18:19:10 -07003854 return false;
3855 }
3856 }
3857 return true;
3858}
3859
Oscar Azucena6acf34b2023-04-27 16:32:09 -07003860void AudioPolicyManager::changeOutputDevicesMuteState(
3861 const AudioDeviceTypeAddrVector& devices) {
3862 ALOGVV("%s() num devices %zu", __func__, devices.size());
3863
3864 std::vector<sp<SwAudioOutputDescriptor>> outputs =
3865 getSoftwareOutputsForDevices(devices);
3866
3867 for (size_t i = 0; i < outputs.size(); i++) {
3868 sp<SwAudioOutputDescriptor> outputDesc = outputs[i];
3869 DeviceVector prevDevices = outputDesc->devices();
3870 checkDeviceMuteStrategies(outputDesc, prevDevices, 0 /* delayMs */);
3871 }
3872}
3873
3874std::vector<sp<SwAudioOutputDescriptor>> AudioPolicyManager::getSoftwareOutputsForDevices(
3875 const AudioDeviceTypeAddrVector& devices) const
3876{
3877 std::vector<sp<SwAudioOutputDescriptor>> outputs;
3878 DeviceVector deviceDescriptors;
3879 for (size_t j = 0; j < devices.size(); j++) {
3880 sp<DeviceDescriptor> desc = mHwModules.getDeviceDescriptor(
3881 devices[j].mType, devices[j].getAddress(), String8(), AUDIO_FORMAT_DEFAULT);
3882 if (desc == nullptr || !audio_is_output_device(devices[j].mType)) {
3883 ALOGE("%s: device type %#x address %s not supported or not an output device",
3884 __func__, devices[j].mType, devices[j].getAddress());
3885 continue;
3886 }
3887 deviceDescriptors.add(desc);
3888 }
3889 for (size_t i = 0; i < mOutputs.size(); i++) {
3890 if (!mOutputs.valueAt(i)->supportsAtLeastOne(deviceDescriptors)) {
3891 continue;
3892 }
3893 outputs.push_back(mOutputs.valueAt(i));
3894 }
3895 return outputs;
3896}
3897
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003898status_t AudioPolicyManager::setUidDeviceAffinities(uid_t uid,
jiabin6a02d532020-08-07 11:56:38 -07003899 const AudioDeviceTypeAddrVector& devices) {
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003900 ALOGV("%s() uid=%d num devices %zu", __FUNCTION__, uid, devices.size());
Eric Laurentc529cf62020-04-17 18:19:10 -07003901 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
3902 return BAD_VALUE;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003903 }
3904 status_t res = mPolicyMixes.setUidDeviceAffinities(uid, devices);
Eric Laurentc529cf62020-04-17 18:19:10 -07003905 if (res != NO_ERROR) {
3906 ALOGE("%s() Could not set all device affinities for uid = %d", __FUNCTION__, uid);
3907 return res;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003908 }
Eric Laurentc529cf62020-04-17 18:19:10 -07003909
3910 checkForDeviceAndOutputChanges();
3911 updateCallAndOutputRouting();
3912
3913 return NO_ERROR;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003914}
3915
3916status_t AudioPolicyManager::removeUidDeviceAffinities(uid_t uid) {
3917 ALOGV("%s() uid=%d", __FUNCTION__, uid);
Oscar Azucena4b2a8212019-04-26 23:48:59 -07003918 status_t res = mPolicyMixes.removeUidDeviceAffinities(uid);
3919 if (res != NO_ERROR) {
Eric Laurentc529cf62020-04-17 18:19:10 -07003920 ALOGE("%s() Could not remove all device affinities for uid = %d",
Oscar Azucena4b2a8212019-04-26 23:48:59 -07003921 __FUNCTION__, uid);
3922 return INVALID_OPERATION;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003923 }
3924
Eric Laurentc529cf62020-04-17 18:19:10 -07003925 checkForDeviceAndOutputChanges();
3926 updateCallAndOutputRouting();
3927
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003928 return res;
3929}
3930
Eric Laurent2517af32020-11-25 15:31:27 +01003931
jiabin0a488932020-08-07 17:32:40 -07003932status_t AudioPolicyManager::setDevicesRoleForStrategy(product_strategy_t strategy,
3933 device_role_t role,
3934 const AudioDeviceTypeAddrVector &devices) {
3935 ALOGV("%s() strategy=%d role=%d %s", __func__, strategy, role,
3936 dumpAudioDeviceTypeAddrVector(devices).c_str());
Eric Laurentc529cf62020-04-17 18:19:10 -07003937
Eric Laurentc529cf62020-04-17 18:19:10 -07003938 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003939 return BAD_VALUE;
3940 }
jiabin0a488932020-08-07 17:32:40 -07003941 status_t status = mEngine->setDevicesRoleForStrategy(strategy, role, devices);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003942 if (status != NO_ERROR) {
jiabin0a488932020-08-07 17:32:40 -07003943 ALOGW("Engine could not set preferred devices %s for strategy %d role %d",
3944 dumpAudioDeviceTypeAddrVector(devices).c_str(), strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003945 return status;
3946 }
3947
3948 checkForDeviceAndOutputChanges();
Eric Laurent2517af32020-11-25 15:31:27 +01003949
3950 bool forceVolumeReeval = false;
3951 // FIXME: workaround for truncated touch sounds
3952 // to be removed when the problem is handled by system UI
3953 uint32_t delayMs = 0;
3954 if (strategy == mCommunnicationStrategy) {
3955 forceVolumeReeval = true;
3956 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
3957 updateInputRouting();
3958 }
3959 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003960
3961 return NO_ERROR;
3962}
3963
Oscar Azucena6acf34b2023-04-27 16:32:09 -07003964void AudioPolicyManager::updateCallAndOutputRouting(bool forceVolumeReeval, uint32_t delayMs,
3965 bool skipDelays)
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003966{
3967 uint32_t waitMs = 0;
Eric Laurent96d1dda2022-03-14 17:14:19 +01003968 bool wasLeUnicastActive = isLeUnicastActive();
Francois Gaffie19fd6c52021-02-04 17:02:59 +01003969 if (updateCallRouting(true /*fromCache*/, delayMs, &waitMs) == NO_ERROR) {
Eric Laurentb36b4ac2020-08-21 12:50:41 -07003970 // Only apply special touch sound delay once
3971 delayMs = 0;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003972 }
jiabin3ff8d7d2022-12-13 06:27:44 +00003973 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003974 for (size_t i = 0; i < mOutputs.size(); i++) {
3975 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
3976 DeviceVector newDevices = getNewOutputDevices(outputDesc, true /*fromCache*/);
Francois Gaffie601801d2021-06-22 13:27:39 +02003977 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) ||
3978 (outputDesc != mPrimaryOutput && !isTelephonyRxOrTx(outputDesc))) {
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003979 // As done in setDeviceConnectionState, we could also fix default device issue by
3980 // preventing the force re-routing in case of default dev that distinguishes on address.
3981 // Let's give back to engine full device choice decision however.
Francois Gaffie601801d2021-06-22 13:27:39 +02003982 bool forceRouting = !newDevices.isEmpty();
jiabin3ff8d7d2022-12-13 06:27:44 +00003983 if (outputDesc->mUsePreferredMixerAttributes && newDevices != outputDesc->devices()) {
3984 // If the device is using preferred mixer attributes, the output need to reopen
3985 // with default configuration when the new selected devices are different from
3986 // current routing devices.
3987 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices);
3988 continue;
3989 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05303990
3991 waitMs = setOutputDevices(__func__, outputDesc, newDevices, forceRouting, delayMs,
3992 nullptr, !skipDelays /*requiresMuteCheck*/,
Oscar Azucena6acf34b2023-04-27 16:32:09 -07003993 !forceRouting /*requiresVolumeCheck*/, skipDelays);
Eric Laurentb36b4ac2020-08-21 12:50:41 -07003994 // Only apply special touch sound delay once
3995 delayMs = 0;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003996 }
3997 if (forceVolumeReeval && !newDevices.isEmpty()) {
3998 applyStreamVolumes(outputDesc, newDevices.types(), waitMs, true);
3999 }
4000 }
jiabin3ff8d7d2022-12-13 06:27:44 +00004001 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent96d1dda2022-03-14 17:14:19 +01004002 checkLeBroadcastRoutes(wasLeUnicastActive, nullptr, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004003}
4004
Eric Laurent2517af32020-11-25 15:31:27 +01004005void AudioPolicyManager::updateInputRouting() {
4006 for (const auto& activeDesc : mInputs.getActiveInputs()) {
Jaideep Sharma408349a2020-11-27 14:47:17 +05304007 // Skip for hotword recording as the input device switch
4008 // is handled within sound trigger HAL
4009 if (activeDesc->isSoundTrigger() && activeDesc->source() == AUDIO_SOURCE_HOTWORD) {
4010 continue;
4011 }
Eric Laurent2517af32020-11-25 15:31:27 +01004012 auto newDevice = getNewInputDevice(activeDesc);
4013 // Force new input selection if the new device can not be reached via current input
4014 if (activeDesc->mProfile->getSupportedDevices().contains(newDevice)) {
4015 setInputDevice(activeDesc->mIoHandle, newDevice);
4016 } else {
4017 closeInput(activeDesc->mIoHandle);
4018 }
4019 }
4020}
4021
Paul Wang5d7cdb52022-11-22 09:45:06 +00004022status_t
4023AudioPolicyManager::removeDevicesRoleForStrategy(product_strategy_t strategy,
4024 device_role_t role,
4025 const AudioDeviceTypeAddrVector &devices) {
4026 ALOGV("%s() strategy=%d role=%d %s", __func__, strategy, role,
4027 dumpAudioDeviceTypeAddrVector(devices).c_str());
4028
Eric Laurent78fedbf2023-03-09 14:40:44 +01004029 if (!areAllDevicesSupported(
4030 devices, audio_is_output_device, __func__, /*matchAddress*/false)) {
Paul Wang5d7cdb52022-11-22 09:45:06 +00004031 return BAD_VALUE;
4032 }
4033 status_t status = mEngine->removeDevicesRoleForStrategy(strategy, role, devices);
4034 if (status != NO_ERROR) {
4035 ALOGW("Engine could not remove devices %s for strategy %d role %d",
4036 dumpAudioDeviceTypeAddrVector(devices).c_str(), strategy, role);
4037 return status;
4038 }
4039
4040 checkForDeviceAndOutputChanges();
4041
4042 bool forceVolumeReeval = false;
4043 // TODO(b/263479999): workaround for truncated touch sounds
4044 // to be removed when the problem is handled by system UI
4045 uint32_t delayMs = 0;
4046 if (strategy == mCommunnicationStrategy) {
4047 forceVolumeReeval = true;
4048 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
4049 updateInputRouting();
4050 }
4051 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
4052
4053 return NO_ERROR;
4054}
4055
4056status_t AudioPolicyManager::clearDevicesRoleForStrategy(product_strategy_t strategy,
4057 device_role_t role)
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004058{
Eric Laurentfecbceb2021-02-09 14:46:43 +01004059 ALOGV("%s() strategy=%d role=%d", __func__, strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004060
Paul Wang5d7cdb52022-11-22 09:45:06 +00004061 status_t status = mEngine->clearDevicesRoleForStrategy(strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004062 if (status != NO_ERROR) {
Eric Laurent9ae44f32022-12-14 16:17:02 +01004063 ALOGW_IF(status != NAME_NOT_FOUND,
4064 "Engine could not remove device role for strategy %d status %d",
Eric Laurent2517af32020-11-25 15:31:27 +01004065 strategy, status);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004066 return status;
4067 }
4068
4069 checkForDeviceAndOutputChanges();
Eric Laurent2517af32020-11-25 15:31:27 +01004070
4071 bool forceVolumeReeval = false;
4072 // FIXME: workaround for truncated touch sounds
4073 // to be removed when the problem is handled by system UI
4074 uint32_t delayMs = 0;
4075 if (strategy == mCommunnicationStrategy) {
4076 forceVolumeReeval = true;
4077 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
4078 updateInputRouting();
4079 }
4080 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004081
4082 return NO_ERROR;
4083}
4084
jiabin0a488932020-08-07 17:32:40 -07004085status_t AudioPolicyManager::getDevicesForRoleAndStrategy(product_strategy_t strategy,
4086 device_role_t role,
4087 AudioDeviceTypeAddrVector &devices) {
4088 return mEngine->getDevicesForRoleAndStrategy(strategy, role, devices);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004089}
4090
Jiabin Huang3b98d322020-09-03 17:54:16 +00004091status_t AudioPolicyManager::setDevicesRoleForCapturePreset(
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->setDevicesRoleForCapturePreset(audioSource, role, devices);
4100 ALOGW_IF(status != NO_ERROR,
4101 "Engine could not set preferred devices %s for audio source %d role %d",
4102 dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
4103
4104 return status;
4105}
4106
4107status_t AudioPolicyManager::addDevicesRoleForCapturePreset(
4108 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices) {
4109 ALOGV("%s() audioSource=%d role=%d %s", __func__, audioSource, role,
4110 dumpAudioDeviceTypeAddrVector(devices).c_str());
4111
Mikhail Naganov55773032020-10-01 15:08:13 -07004112 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00004113 return BAD_VALUE;
4114 }
4115 status_t status = mEngine->addDevicesRoleForCapturePreset(audioSource, role, devices);
4116 ALOGW_IF(status != NO_ERROR,
4117 "Engine could not add preferred devices %s for audio source %d role %d",
4118 dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
4119
Eric Laurent2517af32020-11-25 15:31:27 +01004120 updateInputRouting();
Jiabin Huang3b98d322020-09-03 17:54:16 +00004121 return status;
4122}
4123
4124status_t AudioPolicyManager::removeDevicesRoleForCapturePreset(
4125 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector& devices)
4126{
4127 ALOGV("%s() audioSource=%d role=%d devices=%s", __func__, audioSource, role,
4128 dumpAudioDeviceTypeAddrVector(devices).c_str());
4129
Eric Laurent78fedbf2023-03-09 14:40:44 +01004130 if (!areAllDevicesSupported(
4131 devices, audio_call_is_input_device, __func__, /*matchAddress*/false)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00004132 return BAD_VALUE;
4133 }
4134
4135 status_t status = mEngine->removeDevicesRoleForCapturePreset(
4136 audioSource, role, devices);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004137 ALOGW_IF(status != NO_ERROR && status != NAME_NOT_FOUND,
Jiabin Huang3b98d322020-09-03 17:54:16 +00004138 "Engine could not remove devices role (%d) for capture preset %d", role, audioSource);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004139 if (status == NO_ERROR) {
4140 updateInputRouting();
4141 }
Jiabin Huang3b98d322020-09-03 17:54:16 +00004142 return status;
4143}
4144
4145status_t AudioPolicyManager::clearDevicesRoleForCapturePreset(audio_source_t audioSource,
4146 device_role_t role) {
4147 ALOGV("%s() audioSource=%d role=%d", __func__, audioSource, role);
4148
4149 status_t status = mEngine->clearDevicesRoleForCapturePreset(audioSource, role);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004150 ALOGW_IF(status != NO_ERROR && status != NAME_NOT_FOUND,
Jiabin Huang3b98d322020-09-03 17:54:16 +00004151 "Engine could not clear devices role (%d) for capture preset %d", role, audioSource);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004152 if (status == NO_ERROR) {
4153 updateInputRouting();
4154 }
Jiabin Huang3b98d322020-09-03 17:54:16 +00004155 return status;
4156}
4157
4158status_t AudioPolicyManager::getDevicesForRoleAndCapturePreset(
4159 audio_source_t audioSource, device_role_t role, AudioDeviceTypeAddrVector &devices) {
4160 return mEngine->getDevicesForRoleAndCapturePreset(audioSource, role, devices);
4161}
4162
Oscar Azucena90e77632019-11-27 17:12:28 -08004163status_t AudioPolicyManager::setUserIdDeviceAffinities(int userId,
jiabin6a02d532020-08-07 11:56:38 -07004164 const AudioDeviceTypeAddrVector& devices) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01004165 ALOGV("%s() userId=%d num devices %zu", __func__, userId, devices.size());
Eric Laurentc529cf62020-04-17 18:19:10 -07004166 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
4167 return BAD_VALUE;
Oscar Azucena90e77632019-11-27 17:12:28 -08004168 }
Oscar Azucena90e77632019-11-27 17:12:28 -08004169 status_t status = mPolicyMixes.setUserIdDeviceAffinities(userId, devices);
4170 if (status != NO_ERROR) {
4171 ALOGE("%s() could not set device affinity for userId %d",
4172 __FUNCTION__, userId);
4173 return status;
4174 }
4175
4176 // reevaluate outputs for all devices
4177 checkForDeviceAndOutputChanges();
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004178 changeOutputDevicesMuteState(devices);
4179 updateCallAndOutputRouting(false /* forceVolumeReeval */, 0 /* delayMs */,
4180 true /* skipDelays */);
4181 changeOutputDevicesMuteState(devices);
Oscar Azucena90e77632019-11-27 17:12:28 -08004182
4183 return NO_ERROR;
4184}
4185
4186status_t AudioPolicyManager::removeUserIdDeviceAffinities(int userId) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01004187 ALOGV("%s() userId=%d", __FUNCTION__, userId);
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004188 AudioDeviceTypeAddrVector devices;
4189 mPolicyMixes.getDevicesForUserId(userId, devices);
Oscar Azucena90e77632019-11-27 17:12:28 -08004190 status_t status = mPolicyMixes.removeUserIdDeviceAffinities(userId);
4191 if (status != NO_ERROR) {
4192 ALOGE("%s() Could not remove all device affinities fo userId = %d",
4193 __FUNCTION__, userId);
4194 return status;
4195 }
4196
4197 // reevaluate outputs for all devices
4198 checkForDeviceAndOutputChanges();
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004199 changeOutputDevicesMuteState(devices);
4200 updateCallAndOutputRouting(false /* forceVolumeReeval */, 0 /* delayMs */,
4201 true /* skipDelays */);
4202 changeOutputDevicesMuteState(devices);
Oscar Azucena90e77632019-11-27 17:12:28 -08004203
4204 return NO_ERROR;
4205}
4206
Andy Hungc29d82b2018-10-05 12:23:17 -07004207void AudioPolicyManager::dump(String8 *dst) const
Eric Laurente552edb2014-03-10 17:42:56 -07004208{
Andy Hungc29d82b2018-10-05 12:23:17 -07004209 dst->appendFormat("\nAudioPolicyManager Dump: %p\n", this);
Mikhail Naganov0dbe87b2021-12-01 02:03:31 +00004210 dst->appendFormat(" Primary Output I/O handle: %d\n",
Eric Laurent87ffa392015-05-22 10:32:38 -07004211 hasPrimaryOutput() ? mPrimaryOutput->mIoHandle : AUDIO_IO_HANDLE_NONE);
Mikhail Naganov0d6a0332016-04-19 17:12:38 -07004212 std::string stateLiteral;
4213 AudioModeConverter::toString(mEngine->getPhoneState(), stateLiteral);
Andy Hungc29d82b2018-10-05 12:23:17 -07004214 dst->appendFormat(" Phone state: %s\n", stateLiteral.c_str());
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07004215 const char* forceUses[AUDIO_POLICY_FORCE_USE_CNT] = {
4216 "communications", "media", "record", "dock", "system",
4217 "HDMI system audio", "encoded surround output", "vibrate ringing" };
4218 for (audio_policy_force_use_t i = AUDIO_POLICY_FORCE_FOR_COMMUNICATION;
4219 i < AUDIO_POLICY_FORCE_USE_CNT; i = (audio_policy_force_use_t)((int)i + 1)) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08004220 audio_policy_forced_cfg_t forceUseValue = mEngine->getForceUse(i);
4221 dst->appendFormat(" Force use for %s: %d", forceUses[i], forceUseValue);
4222 if (i == AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND &&
4223 forceUseValue == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
4224 dst->append(" (MANUAL: ");
4225 dumpManualSurroundFormats(dst);
4226 dst->append(")");
4227 }
4228 dst->append("\n");
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07004229 }
Andy Hungc29d82b2018-10-05 12:23:17 -07004230 dst->appendFormat(" TTS output %savailable\n", mTtsOutputAvailable ? "" : "not ");
4231 dst->appendFormat(" Master mono: %s\n", mMasterMono ? "on" : "off");
Mikhail Naganovb3bcb4f2022-02-23 23:46:56 +00004232 dst->appendFormat(" Communication Strategy id: %d\n", mCommunnicationStrategy);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07004233 dst->appendFormat(" Config source: %s\n", mConfig->getSource().c_str());
Eric Laurent2517af32020-11-25 15:31:27 +01004234
Mikhail Naganov0f413b22021-12-02 05:29:27 +00004235 dst->append("\n");
4236 mAvailableOutputDevices.dump(dst, String8("Available output"), 1);
4237 dst->append("\n");
4238 mAvailableInputDevices.dump(dst, String8("Available input"), 1);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07004239 mHwModules.dump(dst);
Andy Hungc29d82b2018-10-05 12:23:17 -07004240 mOutputs.dump(dst);
4241 mInputs.dump(dst);
Mikhail Naganov0f413b22021-12-02 05:29:27 +00004242 mEffects.dump(dst, 1);
Andy Hungc29d82b2018-10-05 12:23:17 -07004243 mAudioPatches.dump(dst);
4244 mPolicyMixes.dump(dst);
4245 mAudioSources.dump(dst);
François Gaffiec005e562018-11-06 15:04:49 +01004246
Kevin Rocardb99cc752019-03-21 20:52:24 -07004247 dst->appendFormat(" AllowedCapturePolicies:\n");
4248 for (auto& policy : mAllowedCapturePolicies) {
4249 dst->appendFormat(" - uid=%d flag_mask=%#x\n", policy.first, policy.second);
4250 }
4251
jiabina84c3d32022-12-02 18:59:55 +00004252 dst->appendFormat(" Preferred mixer audio configuration:\n");
4253 for (const auto it : mPreferredMixerAttrInfos) {
4254 dst->appendFormat(" - device port id: %d\n", it.first);
4255 for (const auto preferredMixerInfoIt : it.second) {
4256 dst->appendFormat(" - strategy: %d; ", preferredMixerInfoIt.first);
4257 preferredMixerInfoIt.second->dump(dst);
4258 }
4259 }
4260
François Gaffiec005e562018-11-06 15:04:49 +01004261 dst->appendFormat("\nPolicy Engine dump:\n");
4262 mEngine->dump(dst);
Andy Hungc29d82b2018-10-05 12:23:17 -07004263}
4264
4265status_t AudioPolicyManager::dump(int fd)
4266{
4267 String8 result;
4268 dump(&result);
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004269 write(fd, result.c_str(), result.size());
Eric Laurente552edb2014-03-10 17:42:56 -07004270 return NO_ERROR;
4271}
4272
Kevin Rocardb99cc752019-03-21 20:52:24 -07004273status_t AudioPolicyManager::setAllowedCapturePolicy(uid_t uid, audio_flags_mask_t capturePolicy)
4274{
4275 mAllowedCapturePolicies[uid] = capturePolicy;
4276 return NO_ERROR;
4277}
4278
Eric Laurente552edb2014-03-10 17:42:56 -07004279// This function checks for the parameters which can be offloaded.
4280// This can be enhanced depending on the capability of the DSP and policy
4281// of the system.
Eric Laurent90fe31c2020-11-26 20:06:35 +01004282audio_offload_mode_t AudioPolicyManager::getOffloadSupport(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07004283{
Eric Laurent90fe31c2020-11-26 20:06:35 +01004284 ALOGV("%s: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07004285 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurent90fe31c2020-11-26 20:06:35 +01004286 __func__, offloadInfo.sample_rate, offloadInfo.channel_mask,
Eric Laurente552edb2014-03-10 17:42:56 -07004287 offloadInfo.format,
4288 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
4289 offloadInfo.has_video);
4290
jiabin2b9d5a12021-12-10 01:06:29 +00004291 if (!isOffloadPossible(offloadInfo)) {
Eric Laurent90fe31c2020-11-26 20:06:35 +01004292 return AUDIO_OFFLOAD_NOT_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07004293 }
4294
4295 // See if there is a profile to support this.
4296 // AUDIO_DEVICE_NONE
François Gaffie11d30102018-11-02 16:09:09 +01004297 sp<IOProfile> profile = getProfileForOutput(DeviceVector() /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07004298 offloadInfo.sample_rate,
4299 offloadInfo.format,
4300 offloadInfo.channel_mask,
Michael Chana94fbb22018-04-24 14:31:19 +10004301 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD,
4302 true /* directOnly */);
Eric Laurent94365442021-01-08 18:36:05 +01004303 ALOGV("%s: profile %sfound%s", __func__, profile != nullptr ? "" : "NOT ",
4304 (profile != nullptr && (profile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD) != 0)
4305 ? ", supports gapless" : "");
Eric Laurent90fe31c2020-11-26 20:06:35 +01004306 if (profile == nullptr) {
4307 return AUDIO_OFFLOAD_NOT_SUPPORTED;
4308 }
4309 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD) != 0) {
4310 return AUDIO_OFFLOAD_GAPLESS_SUPPORTED;
4311 }
4312 return AUDIO_OFFLOAD_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07004313}
4314
Michael Chana94fbb22018-04-24 14:31:19 +10004315bool AudioPolicyManager::isDirectOutputSupported(const audio_config_base_t& config,
4316 const audio_attributes_t& attributes) {
4317 audio_output_flags_t output_flags = AUDIO_OUTPUT_FLAG_NONE;
François Gaffie58d4be52018-11-06 15:30:12 +01004318 audio_flags_to_audio_output_flags(attributes.flags, &output_flags);
Dorin Drimus9901eb02022-01-14 11:36:51 +00004319 DeviceVector outputDevices = mEngine->getOutputDevicesForAttributes(attributes);
4320 sp<IOProfile> profile = getProfileForOutput(outputDevices,
Michael Chana94fbb22018-04-24 14:31:19 +10004321 config.sample_rate,
4322 config.format,
4323 config.channel_mask,
4324 output_flags,
4325 true /* directOnly */);
4326 ALOGV("%s() profile %sfound with name: %s, "
4327 "sample rate: %u, format: 0x%x, channel_mask: 0x%x, output flags: 0x%x",
4328 __FUNCTION__, profile != 0 ? "" : "NOT ",
jiabin5740f082019-08-19 15:08:30 -07004329 (profile != 0 ? profile->getTagName().c_str() : "null"),
Michael Chana94fbb22018-04-24 14:31:19 +10004330 config.sample_rate, config.format, config.channel_mask, output_flags);
Dorin Drimusecc9f422022-03-09 17:57:40 +01004331
4332 // also try the MSD module if compatible profile not found
4333 if (profile == nullptr) {
4334 profile = getMsdProfileForOutput(outputDevices,
4335 config.sample_rate,
4336 config.format,
4337 config.channel_mask,
4338 output_flags,
4339 true /* directOnly */);
4340 ALOGV("%s() MSD profile %sfound with name: %s, "
4341 "sample rate: %u, format: 0x%x, channel_mask: 0x%x, output flags: 0x%x",
4342 __FUNCTION__, profile != 0 ? "" : "NOT ",
4343 (profile != 0 ? profile->getTagName().c_str() : "null"),
4344 config.sample_rate, config.format, config.channel_mask, output_flags);
4345 }
4346 return (profile != nullptr);
Michael Chana94fbb22018-04-24 14:31:19 +10004347}
4348
jiabin2b9d5a12021-12-10 01:06:29 +00004349bool AudioPolicyManager::isOffloadPossible(const audio_offload_info_t &offloadInfo,
4350 bool durationIgnored) {
4351 if (mMasterMono) {
4352 return false; // no offloading if mono is set.
4353 }
4354
4355 // Check if offload has been disabled
4356 if (property_get_bool("audio.offload.disable", false /* default_value */)) {
4357 ALOGV("%s: offload disabled by audio.offload.disable", __func__);
4358 return false;
4359 }
4360
4361 // Check if stream type is music, then only allow offload as of now.
4362 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
4363 {
4364 ALOGV("%s: stream_type != MUSIC, returning false", __func__);
4365 return false;
4366 }
4367
4368 //TODO: enable audio offloading with video when ready
4369 const bool allowOffloadWithVideo =
4370 property_get_bool("audio.offload.video", false /* default_value */);
4371 if (offloadInfo.has_video && !allowOffloadWithVideo) {
4372 ALOGV("%s: has_video == true, returning false", __func__);
4373 return false;
4374 }
4375
4376 //If duration is less than minimum value defined in property, return false
4377 const int min_duration_secs = property_get_int32(
4378 "audio.offload.min.duration.secs", -1 /* default_value */);
4379 if (!durationIgnored) {
4380 if (min_duration_secs >= 0) {
4381 if (offloadInfo.duration_us < min_duration_secs * 1000000LL) {
4382 ALOGV("%s: Offload denied by duration < audio.offload.min.duration.secs(=%d)",
4383 __func__, min_duration_secs);
4384 return false;
4385 }
4386 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
4387 ALOGV("%s: Offload denied by duration < default min(=%u)",
4388 __func__, OFFLOAD_DEFAULT_MIN_DURATION_SECS);
4389 return false;
4390 }
4391 }
4392
4393 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
4394 // creating an offloaded track and tearing it down immediately after start when audioflinger
4395 // detects there is an active non offloadable effect.
4396 // FIXME: We should check the audio session here but we do not have it in this context.
4397 // This may prevent offloading in rare situations where effects are left active by apps
4398 // in the background.
4399 if (mEffects.isNonOffloadableEffectEnabled()) {
4400 return false;
4401 }
4402
4403 return true;
4404}
4405
4406audio_direct_mode_t AudioPolicyManager::getDirectPlaybackSupport(const audio_attributes_t *attr,
4407 const audio_config_t *config) {
4408 audio_offload_info_t offloadInfo = AUDIO_INFO_INITIALIZER;
4409 offloadInfo.format = config->format;
4410 offloadInfo.sample_rate = config->sample_rate;
4411 offloadInfo.channel_mask = config->channel_mask;
4412 offloadInfo.stream_type = mEngine->getStreamTypeForAttributes(*attr);
4413 offloadInfo.has_video = false;
4414 offloadInfo.is_streaming = false;
4415 const bool offloadPossible = isOffloadPossible(offloadInfo, true /*durationIgnored*/);
4416
4417 audio_direct_mode_t directMode = AUDIO_DIRECT_NOT_SUPPORTED;
4418 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
4419 audio_flags_to_audio_output_flags(attr->flags, &flags);
4420 // only retain flags that will drive compressed offload or passthrough
4421 uint32_t relevantFlags = AUDIO_OUTPUT_FLAG_HW_AV_SYNC;
4422 if (offloadPossible) {
4423 relevantFlags |= AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD;
4424 }
4425 flags = (audio_output_flags_t)((flags & relevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
4426
Dorin Drimusfae3c642022-03-17 18:36:30 +01004427 DeviceVector engineOutputDevices = mEngine->getOutputDevicesForAttributes(*attr);
jiabin2b9d5a12021-12-10 01:06:29 +00004428 for (const auto& hwModule : mHwModules) {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004429 DeviceVector outputDevices = engineOutputDevices;
4430 // the MSD module checks for different conditions and output devices
4431 if (strcmp(hwModule->getName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0) {
4432 if (!msdHasPatchesToAllDevices(engineOutputDevices.toTypeAddrVector())) {
4433 continue;
4434 }
4435 outputDevices = getMsdAudioOutDevices();
4436 }
jiabin2b9d5a12021-12-10 01:06:29 +00004437 for (const auto& curProfile : hwModule->getOutputProfiles()) {
jiabinc8f7dfc2022-01-06 18:42:08 +00004438 if (!curProfile->isCompatibleProfile(outputDevices,
jiabin2b9d5a12021-12-10 01:06:29 +00004439 config->sample_rate, nullptr /*updatedSamplingRate*/,
4440 config->format, nullptr /*updatedFormat*/,
4441 config->channel_mask, nullptr /*updatedChannelMask*/,
4442 flags)) {
4443 continue;
4444 }
4445 // reject profiles not corresponding to a device currently available
4446 if (!mAvailableOutputDevices.containsAtLeastOne(curProfile->getSupportedDevices())) {
4447 continue;
4448 }
4449 if ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)
4450 != AUDIO_OUTPUT_FLAG_NONE) {
jiabinc6132d62022-01-01 07:36:31 +00004451 if ((directMode & AUDIO_DIRECT_OFFLOAD_GAPLESS_SUPPORTED)
jiabin2b9d5a12021-12-10 01:06:29 +00004452 != AUDIO_DIRECT_NOT_SUPPORTED) {
4453 // Already reports offload gapless supported. No need to report offload support.
4454 continue;
4455 }
4456 if ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD)
4457 != AUDIO_OUTPUT_FLAG_NONE) {
4458 // If offload gapless is reported, no need to report offload support.
4459 directMode = (audio_direct_mode_t) ((directMode &
4460 ~AUDIO_DIRECT_OFFLOAD_SUPPORTED) |
4461 AUDIO_DIRECT_OFFLOAD_GAPLESS_SUPPORTED);
4462 } else {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004463 directMode = (audio_direct_mode_t)(directMode | AUDIO_DIRECT_OFFLOAD_SUPPORTED);
jiabin2b9d5a12021-12-10 01:06:29 +00004464 }
4465 } else {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004466 directMode = (audio_direct_mode_t) (directMode | AUDIO_DIRECT_BITSTREAM_SUPPORTED);
jiabin2b9d5a12021-12-10 01:06:29 +00004467 }
4468 }
4469 }
4470 return directMode;
4471}
4472
Dorin Drimusf2196d82022-01-03 12:11:18 +01004473status_t AudioPolicyManager::getDirectProfilesForAttributes(const audio_attributes_t* attr,
4474 AudioProfileVector& audioProfilesVector) {
Dorin Drimus17112632022-09-23 15:28:51 +00004475 if (mEffects.isNonOffloadableEffectEnabled()) {
4476 return OK;
4477 }
jiabinf1c73972022-04-14 16:28:52 -07004478 DeviceVector devices;
4479 status_t status = getDevicesForAttributes(*attr, devices, false /* forVolume */);
Dorin Drimusf2196d82022-01-03 12:11:18 +01004480 if (status != OK) {
4481 return status;
4482 }
4483 ALOGV("%s: found %zu output devices for attributes.", __func__, devices.size());
4484 if (devices.empty()) {
4485 return OK; // no output devices for the attributes
4486 }
jiabinf1c73972022-04-14 16:28:52 -07004487 return getProfilesForDevices(devices, audioProfilesVector,
4488 AUDIO_OUTPUT_FLAG_DIRECT /*flags*/, false /*isInput*/);
Dorin Drimusf2196d82022-01-03 12:11:18 +01004489}
4490
jiabina84c3d32022-12-02 18:59:55 +00004491status_t AudioPolicyManager::getSupportedMixerAttributes(
4492 audio_port_handle_t portId, std::vector<audio_mixer_attributes_t> &mixerAttrs) {
4493 ALOGV("%s, portId=%d", __func__, portId);
4494 sp<DeviceDescriptor> deviceDescriptor = mAvailableOutputDevices.getDeviceFromId(portId);
4495 if (deviceDescriptor == nullptr) {
4496 ALOGE("%s the requested device is currently unavailable", __func__);
4497 return BAD_VALUE;
4498 }
jiabin96daffc2023-05-11 17:51:55 +00004499 if (!audio_is_usb_out_device(deviceDescriptor->type())) {
4500 ALOGE("%s the requested device(type=%#x) is not usb device", __func__,
4501 deviceDescriptor->type());
4502 return BAD_VALUE;
4503 }
jiabina84c3d32022-12-02 18:59:55 +00004504 for (const auto& hwModule : mHwModules) {
4505 for (const auto& curProfile : hwModule->getOutputProfiles()) {
4506 if (curProfile->supportsDevice(deviceDescriptor)) {
4507 curProfile->toSupportedMixerAttributes(&mixerAttrs);
4508 }
4509 }
4510 }
4511 return NO_ERROR;
4512}
4513
4514status_t AudioPolicyManager::setPreferredMixerAttributes(
4515 const audio_attributes_t *attr,
4516 audio_port_handle_t portId,
4517 uid_t uid,
4518 const audio_mixer_attributes_t *mixerAttributes) {
4519 ALOGV("%s, attr=%s, mixerAttributes={format=%#x, channelMask=%#x, samplingRate=%u, "
4520 "mixerBehavior=%d}, uid=%d, portId=%u",
4521 __func__, toString(*attr).c_str(), mixerAttributes->config.format,
4522 mixerAttributes->config.channel_mask, mixerAttributes->config.sample_rate,
4523 mixerAttributes->mixer_behavior, uid, portId);
4524 if (attr->usage != AUDIO_USAGE_MEDIA) {
4525 ALOGE("%s failed, only media is allowed, the given usage is %d", __func__, attr->usage);
4526 return BAD_VALUE;
4527 }
4528 sp<DeviceDescriptor> deviceDescriptor = mAvailableOutputDevices.getDeviceFromId(portId);
4529 if (deviceDescriptor == nullptr) {
4530 ALOGE("%s the requested device is currently unavailable", __func__);
4531 return BAD_VALUE;
4532 }
4533 if (!audio_is_usb_out_device(deviceDescriptor->type())) {
4534 ALOGE("%s(%d), type=%d, is not a usb output device",
4535 __func__, portId, deviceDescriptor->type());
4536 return BAD_VALUE;
4537 }
4538
4539 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
4540 audio_flags_to_audio_output_flags(attr->flags, &flags);
4541 flags = (audio_output_flags_t) (flags |
4542 audio_output_flags_from_mixer_behavior(mixerAttributes->mixer_behavior));
4543 sp<IOProfile> profile = nullptr;
4544 DeviceVector devices(deviceDescriptor);
4545 for (const auto& hwModule : mHwModules) {
4546 for (const auto& curProfile : hwModule->getOutputProfiles()) {
4547 if (curProfile->hasDynamicAudioProfile()
4548 && curProfile->isCompatibleProfile(devices,
4549 mixerAttributes->config.sample_rate,
4550 nullptr /*updatedSamplingRate*/,
4551 mixerAttributes->config.format,
4552 nullptr /*updatedFormat*/,
4553 mixerAttributes->config.channel_mask,
4554 nullptr /*updatedChannelMask*/,
4555 flags,
4556 false /*exactMatchRequiredForInputFlags*/)) {
4557 profile = curProfile;
4558 break;
4559 }
4560 }
4561 }
4562 if (profile == nullptr) {
4563 ALOGE("%s, there is no compatible profile found", __func__);
4564 return BAD_VALUE;
4565 }
4566
4567 sp<PreferredMixerAttributesInfo> mixerAttrInfo =
4568 sp<PreferredMixerAttributesInfo>::make(
4569 uid, portId, profile, flags, *mixerAttributes);
4570 const product_strategy_t strategy = mEngine->getProductStrategyForAttributes(*attr);
4571 mPreferredMixerAttrInfos[portId][strategy] = mixerAttrInfo;
4572
4573 // If 1) there is any client from the preferred mixer configuration owner that is currently
4574 // active and matches the strategy and 2) current output is on the preferred device and the
4575 // mixer configuration doesn't match the preferred one, reopen output with preferred mixer
4576 // configuration.
4577 std::vector<audio_io_handle_t> outputsToReopen;
4578 for (size_t i = 0; i < mOutputs.size(); i++) {
4579 const auto output = mOutputs.valueAt(i);
jiabin3ff8d7d2022-12-13 06:27:44 +00004580 if (output->mProfile == profile && output->devices().onlyContainsDevice(deviceDescriptor)) {
4581 if (output->isConfigurationMatched(mixerAttributes->config, flags)) {
4582 output->mUsePreferredMixerAttributes = true;
4583 } else {
4584 for (const auto &client: output->getActiveClients()) {
4585 if (client->uid() == uid && client->strategy() == strategy) {
4586 client->setIsInvalid();
4587 outputsToReopen.push_back(output->mIoHandle);
4588 }
jiabina84c3d32022-12-02 18:59:55 +00004589 }
4590 }
4591 }
4592 }
4593 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
4594 config.sample_rate = mixerAttributes->config.sample_rate;
4595 config.channel_mask = mixerAttributes->config.channel_mask;
4596 config.format = mixerAttributes->config.format;
4597 for (const auto output : outputsToReopen) {
jiabin3ff8d7d2022-12-13 06:27:44 +00004598 sp<SwAudioOutputDescriptor> desc =
4599 reopenOutput(mOutputs.valueFor(output), &config, flags, __func__);
4600 if (desc == nullptr) {
4601 ALOGE("%s, failed to reopen output with preferred mixer attributes", __func__);
4602 continue;
4603 }
4604 desc->mUsePreferredMixerAttributes = true;
jiabina84c3d32022-12-02 18:59:55 +00004605 }
4606
4607 return NO_ERROR;
4608}
4609
4610sp<PreferredMixerAttributesInfo> AudioPolicyManager::getPreferredMixerAttributesInfo(
jiabind9a58d32023-06-01 17:57:30 +00004611 audio_port_handle_t devicePortId,
4612 product_strategy_t strategy,
4613 bool activeBitPerfectPreferred) {
jiabina84c3d32022-12-02 18:59:55 +00004614 auto it = mPreferredMixerAttrInfos.find(devicePortId);
4615 if (it == mPreferredMixerAttrInfos.end()) {
4616 return nullptr;
4617 }
jiabind9a58d32023-06-01 17:57:30 +00004618 if (activeBitPerfectPreferred) {
4619 for (auto [strategy, info] : it->second) {
4620 if ((info->getFlags() & AUDIO_OUTPUT_FLAG_BIT_PERFECT) != AUDIO_OUTPUT_FLAG_NONE
4621 && info->getActiveClientCount() != 0) {
4622 return info;
4623 }
4624 }
jiabina84c3d32022-12-02 18:59:55 +00004625 }
jiabind9a58d32023-06-01 17:57:30 +00004626 auto strategyMatchedMixerAttrInfoIt = it->second.find(strategy);
4627 return strategyMatchedMixerAttrInfoIt == it->second.end()
4628 ? nullptr : strategyMatchedMixerAttrInfoIt->second;
jiabina84c3d32022-12-02 18:59:55 +00004629}
4630
4631status_t AudioPolicyManager::getPreferredMixerAttributes(
4632 const audio_attributes_t *attr,
4633 audio_port_handle_t portId,
4634 audio_mixer_attributes_t* mixerAttributes) {
4635 sp<PreferredMixerAttributesInfo> info = getPreferredMixerAttributesInfo(
4636 portId, mEngine->getProductStrategyForAttributes(*attr));
4637 if (info == nullptr) {
4638 return NAME_NOT_FOUND;
4639 }
4640 *mixerAttributes = info->getMixerAttributes();
4641 return NO_ERROR;
4642}
4643
4644status_t AudioPolicyManager::clearPreferredMixerAttributes(const audio_attributes_t *attr,
4645 audio_port_handle_t portId,
4646 uid_t uid) {
4647 const product_strategy_t strategy = mEngine->getProductStrategyForAttributes(*attr);
4648 const auto preferredMixerAttrInfo = getPreferredMixerAttributesInfo(portId, strategy);
4649 if (preferredMixerAttrInfo == nullptr) {
4650 return NAME_NOT_FOUND;
4651 }
4652 if (preferredMixerAttrInfo->getUid() != uid) {
4653 ALOGE("%s, requested uid=%d, owned uid=%d",
4654 __func__, uid, preferredMixerAttrInfo->getUid());
4655 return PERMISSION_DENIED;
4656 }
4657 mPreferredMixerAttrInfos[portId].erase(strategy);
4658 if (mPreferredMixerAttrInfos[portId].empty()) {
4659 mPreferredMixerAttrInfos.erase(portId);
4660 }
4661
4662 // Reconfig existing output
4663 std::vector<audio_io_handle_t> potentialOutputsToReopen;
4664 for (size_t i = 0; i < mOutputs.size(); i++) {
4665 if (mOutputs.valueAt(i)->mProfile == preferredMixerAttrInfo->getProfile()) {
4666 potentialOutputsToReopen.push_back(mOutputs.keyAt(i));
4667 }
4668 }
4669 for (const auto output : potentialOutputsToReopen) {
4670 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
4671 if (desc->isConfigurationMatched(preferredMixerAttrInfo->getConfigBase(),
4672 preferredMixerAttrInfo->getFlags())) {
4673 reopenOutput(desc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
4674 }
4675 }
4676 return NO_ERROR;
4677}
4678
Eric Laurent6a94d692014-05-20 11:18:06 -07004679status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
4680 audio_port_type_t type,
4681 unsigned int *num_ports,
jiabin19cdba52020-11-24 11:28:58 -08004682 struct audio_port_v7 *ports,
Eric Laurent6a94d692014-05-20 11:18:06 -07004683 unsigned int *generation)
4684{
jiabin19cdba52020-11-24 11:28:58 -08004685 if (num_ports == nullptr || (*num_ports != 0 && ports == nullptr) ||
4686 generation == nullptr) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004687 return BAD_VALUE;
4688 }
4689 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
jiabin19cdba52020-11-24 11:28:58 -08004690 if (ports == nullptr) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004691 *num_ports = 0;
4692 }
4693
4694 size_t portsWritten = 0;
4695 size_t portsMax = *num_ports;
4696 *num_ports = 0;
4697 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07004698 // do not report devices with type AUDIO_DEVICE_IN_STUB or AUDIO_DEVICE_OUT_STUB
4699 // as they are used by stub HALs by convention
Eric Laurent6a94d692014-05-20 11:18:06 -07004700 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004701 for (const auto& dev : mAvailableOutputDevices) {
4702 if (dev->type() == AUDIO_DEVICE_OUT_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07004703 continue;
4704 }
4705 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004706 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07004707 }
4708 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07004709 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004710 }
4711 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004712 for (const auto& dev : mAvailableInputDevices) {
4713 if (dev->type() == AUDIO_DEVICE_IN_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07004714 continue;
4715 }
4716 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004717 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07004718 }
4719 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07004720 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004721 }
4722 }
4723 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
4724 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
4725 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
4726 mInputs[i]->toAudioPort(&ports[portsWritten++]);
4727 }
4728 *num_ports += mInputs.size();
4729 }
4730 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent84c70242014-06-23 08:46:27 -07004731 size_t numOutputs = 0;
4732 for (size_t i = 0; i < mOutputs.size(); i++) {
4733 if (!mOutputs[i]->isDuplicated()) {
4734 numOutputs++;
4735 if (portsWritten < portsMax) {
4736 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
4737 }
4738 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004739 }
Eric Laurent84c70242014-06-23 08:46:27 -07004740 *num_ports += numOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07004741 }
4742 }
jiabina84c3d32022-12-02 18:59:55 +00004743
Eric Laurent6a94d692014-05-20 11:18:06 -07004744 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07004745 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
Eric Laurent6a94d692014-05-20 11:18:06 -07004746 return NO_ERROR;
4747}
4748
Mikhail Naganov5edc5ed2023-03-23 14:52:15 -07004749status_t AudioPolicyManager::listDeclaredDevicePorts(media::AudioPortRole role,
4750 std::vector<media::AudioPortFw>* _aidl_return) {
4751 auto pushPort = [&](const sp<DeviceDescriptor>& dev) -> status_t {
4752 audio_port_v7 port;
4753 dev->toAudioPort(&port);
4754 auto aidlPort = VALUE_OR_RETURN_STATUS(legacy2aidl_audio_port_v7_AudioPortFw(port));
4755 _aidl_return->push_back(std::move(aidlPort));
4756 return OK;
4757 };
4758
Mikhail Naganov68e3f642023-04-28 13:06:32 -07004759 for (const auto& module : mHwModules) {
Mikhail Naganov5edc5ed2023-03-23 14:52:15 -07004760 for (const auto& dev : module->getDeclaredDevices()) {
4761 if (role == media::AudioPortRole::NONE ||
4762 ((role == media::AudioPortRole::SOURCE)
4763 == audio_is_input_device(dev->type()))) {
4764 RETURN_STATUS_IF_ERROR(pushPort(dev));
4765 }
4766 }
4767 }
4768 return OK;
4769}
4770
jiabin19cdba52020-11-24 11:28:58 -08004771status_t AudioPolicyManager::getAudioPort(struct audio_port_v7 *port)
Eric Laurent6a94d692014-05-20 11:18:06 -07004772{
Eric Laurent99fcae42018-05-17 16:59:18 -07004773 if (port == nullptr || port->id == AUDIO_PORT_HANDLE_NONE) {
4774 return BAD_VALUE;
4775 }
4776 sp<DeviceDescriptor> dev = mAvailableOutputDevices.getDeviceFromId(port->id);
4777 if (dev != 0) {
4778 dev->toAudioPort(port);
4779 return NO_ERROR;
4780 }
4781 dev = mAvailableInputDevices.getDeviceFromId(port->id);
4782 if (dev != 0) {
4783 dev->toAudioPort(port);
4784 return NO_ERROR;
4785 }
4786 sp<SwAudioOutputDescriptor> out = mOutputs.getOutputFromId(port->id);
4787 if (out != 0) {
4788 out->toAudioPort(port);
4789 return NO_ERROR;
4790 }
4791 sp<AudioInputDescriptor> in = mInputs.getInputFromId(port->id);
4792 if (in != 0) {
4793 in->toAudioPort(port);
4794 return NO_ERROR;
4795 }
4796 return BAD_VALUE;
Eric Laurent6a94d692014-05-20 11:18:06 -07004797}
4798
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004799status_t AudioPolicyManager::createAudioPatch(const struct audio_patch *patch,
4800 audio_patch_handle_t *handle,
4801 uid_t uid)
Eric Laurent6a94d692014-05-20 11:18:06 -07004802{
François Gaffieafd4cea2019-11-18 15:50:22 +01004803 ALOGV("%s", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004804 if (handle == NULL || patch == NULL) {
4805 return BAD_VALUE;
4806 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004807 ALOGV("%s num sources %d num sinks %d", __func__, patch->num_sources, patch->num_sinks);
Mikhail Naganovac9858b2018-06-15 13:12:37 -07004808 if (!audio_patch_is_valid(patch)) {
Eric Laurent874c42872014-08-08 15:13:39 -07004809 return BAD_VALUE;
4810 }
4811 // only one source per audio patch supported for now
4812 if (patch->num_sources > 1) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004813 return INVALID_OPERATION;
4814 }
Eric Laurent874c42872014-08-08 15:13:39 -07004815 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004816 return INVALID_OPERATION;
4817 }
Eric Laurent874c42872014-08-08 15:13:39 -07004818 for (size_t i = 0; i < patch->num_sinks; i++) {
4819 if (patch->sinks[i].role != AUDIO_PORT_ROLE_SINK) {
4820 return INVALID_OPERATION;
4821 }
4822 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004823
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004824 sp<DeviceDescriptor> srcDevice = mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
4825 sp<DeviceDescriptor> sinkDevice = mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id);
4826 if (srcDevice == nullptr || sinkDevice == nullptr) {
4827 ALOGW("%s could not create patch, invalid sink and/or source device(s)", __func__);
4828 return BAD_VALUE;
4829 }
4830 ALOGV("%s between source %s and sink %s", __func__,
4831 srcDevice->toString().c_str(), sinkDevice->toString().c_str());
4832 audio_port_handle_t portId = PolicyAudioPort::getNextUniqueId();
4833 // Default attributes, default volume priority, not to infer with non raw audio patches.
4834 audio_attributes_t attributes = attributes_initializer(AUDIO_USAGE_MEDIA);
4835 const struct audio_port_config *source = &patch->sources[0];
4836 sp<SourceClientDescriptor> sourceDesc =
4837 new InternalSourceClientDescriptor(
4838 portId, uid, attributes, *source, srcDevice, sinkDevice,
4839 mEngine->getProductStrategyForAttributes(attributes), toVolumeSource(attributes));
4840
4841 status_t status =
4842 connectAudioSourceToSink(sourceDesc, sinkDevice, patch, *handle, uid, 0 /* delayMs */);
4843
4844 if (status != NO_ERROR) {
4845 return INVALID_OPERATION;
4846 }
4847 mAudioSources.add(portId, sourceDesc);
4848 return NO_ERROR;
4849}
4850
4851status_t AudioPolicyManager::connectAudioSourceToSink(
4852 const sp<SourceClientDescriptor>& sourceDesc, const sp<DeviceDescriptor> &sinkDevice,
4853 const struct audio_patch *patch,
4854 audio_patch_handle_t &handle,
4855 uid_t uid, uint32_t delayMs)
4856{
4857 status_t status = createAudioPatchInternal(patch, &handle, uid, delayMs, sourceDesc);
4858 if (status != NO_ERROR || mAudioPatches.indexOfKey(handle) < 0) {
4859 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
4860 return INVALID_OPERATION;
4861 }
4862 sourceDesc->connect(handle, sinkDevice);
4863 if (isMsdPatch(handle)) {
4864 return NO_ERROR;
4865 }
4866 // SW Bridge? (@todo: HW bridge, keep track of HwOutput for device selection "reconsideration")
4867 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
4868 ALOG_ASSERT(swOutput != nullptr, "%s: a swOutput shall always be associated", __func__);
4869 if (swOutput->getClient(sourceDesc->portId()) != nullptr) {
4870 ALOGW("%s source portId has already been attached to outputDesc", __func__);
4871 goto FailurePatchAdded;
4872 }
4873 status = swOutput->start();
4874 if (status != NO_ERROR) {
4875 goto FailureSourceAdded;
4876 }
4877 swOutput->addClient(sourceDesc);
4878 status = startSource(swOutput, sourceDesc, &delayMs);
4879 if (status != NO_ERROR) {
4880 ALOGW("%s failed to start source, error %d", __FUNCTION__, status);
4881 goto FailureSourceActive;
4882 }
4883 if (delayMs != 0) {
4884 usleep(delayMs * 1000);
4885 }
4886 return NO_ERROR;
4887
4888FailureSourceActive:
4889 swOutput->stop();
4890 releaseOutput(sourceDesc->portId());
4891FailureSourceAdded:
4892 sourceDesc->setSwOutput(nullptr);
4893FailurePatchAdded:
4894 releaseAudioPatchInternal(handle);
4895 return INVALID_OPERATION;
4896}
4897
4898status_t AudioPolicyManager::createAudioPatchInternal(const struct audio_patch *patch,
4899 audio_patch_handle_t *handle,
4900 uid_t uid, uint32_t delayMs,
4901 const sp<SourceClientDescriptor>& sourceDesc)
4902{
4903 ALOGV("%s num sources %d num sinks %d", __func__, patch->num_sources, patch->num_sinks);
Eric Laurent6a94d692014-05-20 11:18:06 -07004904 sp<AudioPatch> patchDesc;
4905 ssize_t index = mAudioPatches.indexOfKey(*handle);
4906
François Gaffieafd4cea2019-11-18 15:50:22 +01004907 ALOGV("%s source id %d role %d type %d", __func__, patch->sources[0].id,
4908 patch->sources[0].role,
4909 patch->sources[0].type);
Eric Laurent874c42872014-08-08 15:13:39 -07004910#if LOG_NDEBUG == 0
4911 for (size_t i = 0; i < patch->num_sinks; i++) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004912 ALOGV("%s sink %zu: id %d role %d type %d", __func__ ,i, patch->sinks[i].id,
4913 patch->sinks[i].role,
4914 patch->sinks[i].type);
Eric Laurent874c42872014-08-08 15:13:39 -07004915 }
4916#endif
Eric Laurent6a94d692014-05-20 11:18:06 -07004917
4918 if (index >= 0) {
4919 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01004920 ALOGV("%s mUidCached %d patchDesc->mUid %d uid %d",
4921 __func__, mUidCached, patchDesc->getUid(), uid);
4922 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004923 return INVALID_OPERATION;
4924 }
4925 } else {
Glenn Kastena13cde92016-03-28 15:26:02 -07004926 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07004927 }
4928
4929 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004930 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004931 if (outputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004932 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004933 return BAD_VALUE;
4934 }
Eric Laurent84c70242014-06-23 08:46:27 -07004935 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
4936 outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004937 if (patchDesc != 0) {
4938 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004939 ALOGV("%s source id differs for patch current id %d new id %d",
4940 __func__, patchDesc->mPatch.sources[0].id, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004941 return BAD_VALUE;
4942 }
4943 }
Eric Laurent874c42872014-08-08 15:13:39 -07004944 DeviceVector devices;
4945 for (size_t i = 0; i < patch->num_sinks; i++) {
4946 // Only support mix to devices connection
4947 // TODO add support for mix to mix connection
4948 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004949 ALOGV("%s source mix but sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07004950 return INVALID_OPERATION;
4951 }
4952 sp<DeviceDescriptor> devDesc =
4953 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
4954 if (devDesc == 0) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004955 ALOGV("%s out device not found for id %d", __func__, patch->sinks[i].id);
Eric Laurent874c42872014-08-08 15:13:39 -07004956 return BAD_VALUE;
4957 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004958
François Gaffie11d30102018-11-02 16:09:09 +01004959 if (!outputDesc->mProfile->isCompatibleProfile(DeviceVector(devDesc),
Eric Laurent874c42872014-08-08 15:13:39 -07004960 patch->sources[0].sample_rate,
François Gaffie53615e22015-03-19 09:24:12 +01004961 NULL, // updatedSamplingRate
4962 patch->sources[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07004963 NULL, // updatedFormat
François Gaffie53615e22015-03-19 09:24:12 +01004964 patch->sources[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07004965 NULL, // updatedChannelMask
François Gaffie53615e22015-03-19 09:24:12 +01004966 AUDIO_OUTPUT_FLAG_NONE /*FIXME*/)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004967 ALOGV("%s profile not supported for device %08x", __func__, devDesc->type());
Eric Laurent874c42872014-08-08 15:13:39 -07004968 return INVALID_OPERATION;
4969 }
4970 devices.add(devDesc);
4971 }
4972 if (devices.size() == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004973 return INVALID_OPERATION;
4974 }
Eric Laurent874c42872014-08-08 15:13:39 -07004975
Eric Laurent6a94d692014-05-20 11:18:06 -07004976 // TODO: reconfigure output format and channels here
François Gaffieafd4cea2019-11-18 15:50:22 +01004977 ALOGV("%s setting device %s on output %d",
4978 __func__, dumpDeviceTypes(devices.types()).c_str(), outputDesc->mIoHandle);
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05304979 setOutputDevices(__func__, outputDesc, devices, true, 0, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004980 index = mAudioPatches.indexOfKey(*handle);
4981 if (index >= 0) {
4982 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004983 ALOGW("%s setOutputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004984 }
4985 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01004986 patchDesc->setUid(uid);
4987 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004988 } else {
François Gaffieafd4cea2019-11-18 15:50:22 +01004989 ALOGW("%s setOutputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004990 return INVALID_OPERATION;
4991 }
4992 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
4993 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
4994 // input device to input mix connection
Eric Laurent874c42872014-08-08 15:13:39 -07004995 // only one sink supported when connecting an input device to a mix
4996 if (patch->num_sinks > 1) {
4997 return INVALID_OPERATION;
4998 }
François Gaffie53615e22015-03-19 09:24:12 +01004999 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005000 if (inputDesc == NULL) {
5001 return BAD_VALUE;
5002 }
5003 if (patchDesc != 0) {
5004 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
5005 return BAD_VALUE;
5006 }
5007 }
François Gaffie11d30102018-11-02 16:09:09 +01005008 sp<DeviceDescriptor> device =
Eric Laurent6a94d692014-05-20 11:18:06 -07005009 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01005010 if (device == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005011 return BAD_VALUE;
5012 }
5013
François Gaffie11d30102018-11-02 16:09:09 +01005014 if (!inputDesc->mProfile->isCompatibleProfile(DeviceVector(device),
Eric Laurent275e8e92014-11-30 15:14:47 -08005015 patch->sinks[0].sample_rate,
5016 NULL, /*updatedSampleRate*/
5017 patch->sinks[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07005018 NULL, /*updatedFormat*/
Eric Laurent275e8e92014-11-30 15:14:47 -08005019 patch->sinks[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07005020 NULL, /*updatedChannelMask*/
Eric Laurent275e8e92014-11-30 15:14:47 -08005021 // FIXME for the parameter type,
5022 // and the NONE
5023 (audio_output_flags_t)
Glenn Kasten6a8ab052014-07-24 14:08:35 -07005024 AUDIO_INPUT_FLAG_NONE)) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005025 return INVALID_OPERATION;
5026 }
5027 // TODO: reconfigure output format and channels here
François Gaffieafd4cea2019-11-18 15:50:22 +01005028 ALOGV("%s setting device %s on output %d", __func__,
François Gaffie11d30102018-11-02 16:09:09 +01005029 device->toString().c_str(), inputDesc->mIoHandle);
5030 setInputDevice(inputDesc->mIoHandle, device, true, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005031 index = mAudioPatches.indexOfKey(*handle);
5032 if (index >= 0) {
5033 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005034 ALOGW("%s setInputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005035 }
5036 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005037 patchDesc->setUid(uid);
5038 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005039 } else {
François Gaffieafd4cea2019-11-18 15:50:22 +01005040 ALOGW("%s setInputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005041 return INVALID_OPERATION;
5042 }
5043 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
5044 // device to device connection
5045 if (patchDesc != 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07005046 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005047 return BAD_VALUE;
5048 }
5049 }
François Gaffie11d30102018-11-02 16:09:09 +01005050 sp<DeviceDescriptor> srcDevice =
Eric Laurent6a94d692014-05-20 11:18:06 -07005051 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01005052 if (srcDevice == 0) {
Eric Laurent58f8eb72014-09-12 16:19:41 -07005053 return BAD_VALUE;
5054 }
Eric Laurent874c42872014-08-08 15:13:39 -07005055
Eric Laurent6a94d692014-05-20 11:18:06 -07005056 //update source and sink with our own data as the data passed in the patch may
5057 // be incomplete.
François Gaffieafd4cea2019-11-18 15:50:22 +01005058 PatchBuilder patchBuilder;
5059 audio_port_config sourcePortConfig = {};
Dean Wheatley8bee85a2021-02-10 16:02:23 +11005060
5061 // if first sink is to MSD, establish single MSD patch
5062 if (getMsdAudioOutDevices().contains(
5063 mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id))) {
5064 ALOGV("%s patching to MSD", __FUNCTION__);
5065 patchBuilder = buildMsdPatch(false /*msdIsSource*/, srcDevice);
5066 goto installPatch;
5067 }
5068
François Gaffieafd4cea2019-11-18 15:50:22 +01005069 srcDevice->toAudioPortConfig(&sourcePortConfig, &patch->sources[0]);
5070 patchBuilder.addSource(sourcePortConfig);
Eric Laurent6a94d692014-05-20 11:18:06 -07005071
Eric Laurent874c42872014-08-08 15:13:39 -07005072 for (size_t i = 0; i < patch->num_sinks; i++) {
5073 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005074 ALOGV("%s source device but one sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07005075 return INVALID_OPERATION;
5076 }
François Gaffie11d30102018-11-02 16:09:09 +01005077 sp<DeviceDescriptor> sinkDevice =
Eric Laurent874c42872014-08-08 15:13:39 -07005078 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
François Gaffie11d30102018-11-02 16:09:09 +01005079 if (sinkDevice == 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07005080 return BAD_VALUE;
5081 }
François Gaffieafd4cea2019-11-18 15:50:22 +01005082 audio_port_config sinkPortConfig = {};
5083 sinkDevice->toAudioPortConfig(&sinkPortConfig, &patch->sinks[i]);
5084 patchBuilder.addSink(sinkPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07005085
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005086 // Whatever Sw or Hw bridge, we do attach an SwOutput to an Audio Source for
5087 // volume management purpose (tracking activity)
5088 // In case of Hw bridge, it is a Work Around. The mixPort used is the one declared
5089 // in config XML to reach the sink so that is can be declared as available.
5090 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurent78b07302022-10-07 16:20:34 +02005091 sp<SwAudioOutputDescriptor> outputDesc;
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005092 if (!sourceDesc->isInternal()) {
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005093 // take care of dynamic routing for SwOutput selection,
5094 audio_attributes_t attributes = sourceDesc->attributes();
5095 audio_stream_type_t stream = sourceDesc->stream();
5096 audio_attributes_t resultAttr;
5097 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
5098 config.sample_rate = sourceDesc->config().sample_rate;
François Gaffie2a24db42022-04-04 16:45:02 +02005099 audio_channel_mask_t sourceMask = sourceDesc->config().channel_mask;
5100 config.channel_mask =
5101 (audio_channel_mask_get_representation(sourceMask)
5102 == AUDIO_CHANNEL_REPRESENTATION_INDEX) ? sourceMask
5103 : audio_channel_mask_in_to_out(sourceMask);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005104 config.format = sourceDesc->config().format;
5105 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
5106 audio_port_handle_t selectedDeviceId = AUDIO_PORT_HANDLE_NONE;
5107 bool isRequestedDeviceForExclusiveUse = false;
5108 output_type_t outputType;
Eric Laurentb0a7bc92022-04-05 15:06:08 +02005109 bool isSpatialized;
jiabinc658e452022-10-21 20:52:21 +00005110 bool isBitPerfect;
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005111 getOutputForAttrInt(&resultAttr, &output, AUDIO_SESSION_NONE, &attributes,
5112 &stream, sourceDesc->uid(), &config, &flags,
5113 &selectedDeviceId, &isRequestedDeviceForExclusiveUse,
jiabinc658e452022-10-21 20:52:21 +00005114 nullptr, &outputType, &isSpatialized, &isBitPerfect);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005115 if (output == AUDIO_IO_HANDLE_NONE) {
5116 ALOGV("%s no output for device %s",
5117 __FUNCTION__, sinkDevice->toString().c_str());
5118 return INVALID_OPERATION;
5119 }
5120 outputDesc = mOutputs.valueFor(output);
5121 if (outputDesc->isDuplicated()) {
5122 ALOGE("%s output is duplicated", __func__);
5123 return INVALID_OPERATION;
5124 }
François Gaffie7e39df22022-04-26 12:48:49 +02005125 bool closeOutput = outputDesc->mDirectOpenCount != 0;
5126 sourceDesc->setSwOutput(outputDesc, closeOutput);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005127 } else {
5128 // Same for "raw patches" aka created from createAudioPatch API
5129 SortedVector<audio_io_handle_t> outputs =
5130 getOutputsForDevices(DeviceVector(sinkDevice), mOutputs);
5131 // if the sink device is reachable via an opened output stream, request to
5132 // go via this output stream by adding a second source to the patch
5133 // description
5134 output = selectOutput(outputs);
5135 if (output == AUDIO_IO_HANDLE_NONE) {
5136 ALOGE("%s no output available for internal patch sink", __func__);
5137 return INVALID_OPERATION;
5138 }
5139 outputDesc = mOutputs.valueFor(output);
5140 if (outputDesc->isDuplicated()) {
5141 ALOGV("%s output for device %s is duplicated",
5142 __func__, sinkDevice->toString().c_str());
5143 return INVALID_OPERATION;
5144 }
François Gaffie7e39df22022-04-26 12:48:49 +02005145 sourceDesc->setSwOutput(outputDesc, /* closeOutput= */ false);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005146 }
Eric Laurent3bcf8592015-04-03 12:13:24 -07005147 // create a software bridge in PatchPanel if:
Scott Randolphf3172402018-01-23 17:06:53 -08005148 // - source and sink devices are on different HW modules OR
Eric Laurent3bcf8592015-04-03 12:13:24 -07005149 // - audio HAL version is < 3.0
Francois Gaffie99896da2018-04-09 11:05:33 +02005150 // - audio HAL version is >= 3.0 but no route has been declared between devices
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005151 // - called from startAudioSource (aka sourceDesc is not internal) and source device
5152 // does not have a gain controller
François Gaffie11d30102018-11-02 16:09:09 +01005153 if (!srcDevice->hasSameHwModuleAs(sinkDevice) ||
5154 (srcDevice->getModuleVersionMajor() < 3) ||
François Gaffieafd4cea2019-11-18 15:50:22 +01005155 !srcDevice->getModule()->supportsPatch(srcDevice, sinkDevice) ||
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005156 (!sourceDesc->isInternal() &&
François Gaffieafd4cea2019-11-18 15:50:22 +01005157 srcDevice->getAudioPort()->getGains().size() == 0)) {
Eric Laurent3bcf8592015-04-03 12:13:24 -07005158 // support only one sink device for now to simplify output selection logic
Eric Laurent874c42872014-08-08 15:13:39 -07005159 if (patch->num_sinks > 1) {
Eric Laurent83b88082014-06-20 18:31:16 -07005160 return INVALID_OPERATION;
5161 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005162 sourceDesc->setUseSwBridge();
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005163 if (outputDesc != nullptr) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005164 audio_port_config srcMixPortConfig = {};
Ytai Ben-Tsvic9d2a912021-11-22 16:43:09 -08005165 outputDesc->toAudioPortConfig(&srcMixPortConfig, nullptr);
François Gaffieafd4cea2019-11-18 15:50:22 +01005166 // for volume control, we may need a valid stream
Eric Laurent78b07302022-10-07 16:20:34 +02005167 srcMixPortConfig.ext.mix.usecase.stream =
5168 (!sourceDesc->isInternal() || isCallTxAudioSource(sourceDesc)) ?
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005169 mEngine->getStreamTypeForAttributes(sourceDesc->attributes()) :
5170 AUDIO_STREAM_PATCH;
François Gaffieafd4cea2019-11-18 15:50:22 +01005171 patchBuilder.addSource(srcMixPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07005172 }
Eric Laurent83b88082014-06-20 18:31:16 -07005173 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005174 }
5175 // TODO: check from routing capabilities in config file and other conflicting patches
5176
Dean Wheatley8bee85a2021-02-10 16:02:23 +11005177installPatch:
François Gaffieafd4cea2019-11-18 15:50:22 +01005178 status_t status = installPatch(
5179 __func__, index, handle, patchBuilder.patch(), delayMs, uid, &patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07005180 if (status != NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005181 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
Eric Laurent6a94d692014-05-20 11:18:06 -07005182 return INVALID_OPERATION;
5183 }
5184 } else {
5185 return BAD_VALUE;
5186 }
5187 } else {
5188 return BAD_VALUE;
5189 }
5190 return NO_ERROR;
5191}
5192
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005193status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle, uid_t uid)
Eric Laurent6a94d692014-05-20 11:18:06 -07005194{
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005195 ALOGV("%s patch %d", __func__, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005196 ssize_t index = mAudioPatches.indexOfKey(handle);
5197
5198 if (index < 0) {
5199 return BAD_VALUE;
5200 }
5201 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005202 ALOGV("%s() mUidCached %d patchDesc->mUid %d uid %d",
5203 __func__, mUidCached, patchDesc->getUid(), uid);
5204 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005205 return INVALID_OPERATION;
5206 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005207 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
5208 for (size_t i = 0; i < mAudioSources.size(); i++) {
5209 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
5210 if (sourceDesc != nullptr && sourceDesc->getPatchHandle() == handle) {
5211 portId = sourceDesc->portId();
5212 break;
5213 }
5214 }
5215 return portId != AUDIO_PORT_HANDLE_NONE ?
5216 stopAudioSource(portId) : releaseAudioPatchInternal(handle);
François Gaffieafd4cea2019-11-18 15:50:22 +01005217}
Eric Laurent6a94d692014-05-20 11:18:06 -07005218
François Gaffieafd4cea2019-11-18 15:50:22 +01005219status_t AudioPolicyManager::releaseAudioPatchInternal(audio_patch_handle_t handle,
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005220 uint32_t delayMs,
5221 const sp<SourceClientDescriptor>& sourceDesc)
François Gaffieafd4cea2019-11-18 15:50:22 +01005222{
5223 ALOGV("%s patch %d", __func__, handle);
5224 if (mAudioPatches.indexOfKey(handle) < 0) {
5225 ALOGE("%s: no patch found with handle=%d", __func__, handle);
5226 return BAD_VALUE;
5227 }
5228 sp<AudioPatch> patchDesc = mAudioPatches.valueFor(handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005229 struct audio_patch *patch = &patchDesc->mPatch;
François Gaffieafd4cea2019-11-18 15:50:22 +01005230 patchDesc->setUid(mUidCached);
Eric Laurent6a94d692014-05-20 11:18:06 -07005231 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005232 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005233 if (outputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005234 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005235 return BAD_VALUE;
5236 }
5237
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05305238 setOutputDevices(__func__, outputDesc,
François Gaffie11d30102018-11-02 16:09:09 +01005239 getNewOutputDevices(outputDesc, true /*fromCache*/),
5240 true,
5241 0,
5242 NULL);
Eric Laurent6a94d692014-05-20 11:18:06 -07005243 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
5244 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
François Gaffie53615e22015-03-19 09:24:12 +01005245 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005246 if (inputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005247 ALOGV("%s input not found for id %d", __func__, patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005248 return BAD_VALUE;
5249 }
5250 setInputDevice(inputDesc->mIoHandle,
Eric Laurentfb66dd92016-01-28 18:32:03 -08005251 getNewInputDevice(inputDesc),
Eric Laurent6a94d692014-05-20 11:18:06 -07005252 true,
5253 NULL);
5254 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005255 status_t status =
5256 mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
5257 ALOGV("%s patch panel returned %d patchHandle %d",
5258 __func__, status, patchDesc->getAfHandle());
5259 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005260 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005261 mpClientInterface->onAudioPatchListUpdate();
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005262 // SW or HW Bridge
5263 sp<SwAudioOutputDescriptor> outputDesc = nullptr;
5264 audio_patch_handle_t patchHandle = AUDIO_PATCH_HANDLE_NONE;
Francois Gaffie7feb8542020-04-06 17:39:47 +02005265 if (patch->num_sources > 1 && patch->sources[1].type == AUDIO_PORT_TYPE_MIX) {
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005266 outputDesc = mOutputs.getOutputFromId(patch->sources[1].id);
5267 } else if (patch->num_sources == 1 && sourceDesc != nullptr) {
5268 outputDesc = sourceDesc->swOutput().promote();
5269 }
5270 if (outputDesc == nullptr) {
5271 ALOGW("%s no output for id %d", __func__, patch->sources[0].id);
5272 // releaseOutput has already called closeOutput in case of direct output
5273 return NO_ERROR;
5274 }
François Gaffie7e39df22022-04-26 12:48:49 +02005275 patchHandle = outputDesc->getPatchHandle();
François Gaffie7e39df22022-04-26 12:48:49 +02005276 // While using a HwBridge, force reconsidering device only if not reusing an existing
5277 // output and no more activity on output (will force to close).
François Gaffie150fcc62023-09-15 11:02:39 +02005278 const bool force = sourceDesc->canCloseOutput() && !outputDesc->isActive();
François Gaffie7e39df22022-04-26 12:48:49 +02005279 // APM pattern is to have always outputs opened / patch realized for reachable devices.
5280 // Update device may result to NONE (empty), coupled with force, it releases the patch.
5281 // Reconsider device only for cases:
5282 // 1 / Active Output
5283 // 2 / Inactive Output previously hosting HwBridge
5284 // 3 / Inactive Output previously hosting SwBridge that can be closed.
5285 bool updateDevice = outputDesc->isActive() || !sourceDesc->useSwBridge() ||
5286 sourceDesc->canCloseOutput();
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05305287 setOutputDevices(__func__, outputDesc,
François Gaffie7e39df22022-04-26 12:48:49 +02005288 updateDevice ? getNewOutputDevices(outputDesc, true /*fromCache*/) :
5289 outputDesc->devices(),
5290 force,
5291 0,
5292 patchHandle == AUDIO_PATCH_HANDLE_NONE ? nullptr : &patchHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005293 } else {
5294 return BAD_VALUE;
5295 }
5296 } else {
5297 return BAD_VALUE;
5298 }
5299 return NO_ERROR;
5300}
5301
5302status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
5303 struct audio_patch *patches,
5304 unsigned int *generation)
5305{
François Gaffie53615e22015-03-19 09:24:12 +01005306 if (generation == NULL) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005307 return BAD_VALUE;
5308 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005309 *generation = curAudioPortGeneration();
François Gaffie53615e22015-03-19 09:24:12 +01005310 return mAudioPatches.listAudioPatches(num_patches, patches);
Eric Laurent6a94d692014-05-20 11:18:06 -07005311}
5312
Eric Laurente1715a42014-05-20 11:30:42 -07005313status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07005314{
Eric Laurente1715a42014-05-20 11:30:42 -07005315 ALOGV("setAudioPortConfig()");
5316
5317 if (config == NULL) {
5318 return BAD_VALUE;
5319 }
5320 ALOGV("setAudioPortConfig() on port handle %d", config->id);
5321 // Only support gain configuration for now
Eric Laurenta121f902014-06-03 13:32:54 -07005322 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
5323 return INVALID_OPERATION;
Eric Laurente1715a42014-05-20 11:30:42 -07005324 }
5325
Eric Laurenta121f902014-06-03 13:32:54 -07005326 sp<AudioPortConfig> audioPortConfig;
Eric Laurente1715a42014-05-20 11:30:42 -07005327 if (config->type == AUDIO_PORT_TYPE_MIX) {
5328 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005329 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07005330 if (outputDesc == NULL) {
5331 return BAD_VALUE;
5332 }
Eric Laurent84c70242014-06-23 08:46:27 -07005333 ALOG_ASSERT(!outputDesc->isDuplicated(),
5334 "setAudioPortConfig() called on duplicated output %d",
5335 outputDesc->mIoHandle);
Eric Laurenta121f902014-06-03 13:32:54 -07005336 audioPortConfig = outputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07005337 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
François Gaffie53615e22015-03-19 09:24:12 +01005338 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07005339 if (inputDesc == NULL) {
5340 return BAD_VALUE;
5341 }
Eric Laurenta121f902014-06-03 13:32:54 -07005342 audioPortConfig = inputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07005343 } else {
5344 return BAD_VALUE;
5345 }
5346 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
5347 sp<DeviceDescriptor> deviceDesc;
5348 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
5349 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
5350 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
5351 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
5352 } else {
5353 return BAD_VALUE;
5354 }
5355 if (deviceDesc == NULL) {
5356 return BAD_VALUE;
5357 }
Eric Laurenta121f902014-06-03 13:32:54 -07005358 audioPortConfig = deviceDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07005359 } else {
5360 return BAD_VALUE;
5361 }
5362
Mikhail Naganov7be71d22018-05-23 16:51:46 -07005363 struct audio_port_config backupConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07005364 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
5365 if (status == NO_ERROR) {
Mikhail Naganov7be71d22018-05-23 16:51:46 -07005366 struct audio_port_config newConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07005367 audioPortConfig->toAudioPortConfig(&newConfig, config);
5368 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
Eric Laurente1715a42014-05-20 11:30:42 -07005369 }
Eric Laurenta121f902014-06-03 13:32:54 -07005370 if (status != NO_ERROR) {
5371 audioPortConfig->applyAudioPortConfig(&backupConfig);
Eric Laurente1715a42014-05-20 11:30:42 -07005372 }
Eric Laurente1715a42014-05-20 11:30:42 -07005373
5374 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07005375}
5376
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005377void AudioPolicyManager::releaseResourcesForUid(uid_t uid)
5378{
Eric Laurentd60560a2015-04-10 11:31:20 -07005379 clearAudioSources(uid);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005380 clearAudioPatches(uid);
5381 clearSessionRoutes(uid);
5382}
5383
Eric Laurent6a94d692014-05-20 11:18:06 -07005384void AudioPolicyManager::clearAudioPatches(uid_t uid)
5385{
Eric Laurent0add0fd2014-12-04 18:58:14 -08005386 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005387 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
François Gaffieafd4cea2019-11-18 15:50:22 +01005388 if (patchDesc->getUid() == uid) {
Eric Laurent0add0fd2014-12-04 18:58:14 -08005389 releaseAudioPatch(mAudioPatches.keyAt(i), uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07005390 }
5391 }
5392}
5393
François Gaffiec005e562018-11-06 15:04:49 +01005394void AudioPolicyManager::checkStrategyRoute(product_strategy_t ps, audio_io_handle_t ouptutToSkip)
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005395{
François Gaffiec005e562018-11-06 15:04:49 +01005396 // Take the first attributes following the product strategy as it is used to retrieve the routed
5397 // device. All attributes wihin a strategy follows the same "routing strategy"
5398 auto attributes = mEngine->getAllAttributesForProductStrategy(ps).front();
5399 DeviceVector devices = mEngine->getOutputDevicesForAttributes(attributes, nullptr, false);
François Gaffie11d30102018-11-02 16:09:09 +01005400 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
jiabin3ff8d7d2022-12-13 06:27:44 +00005401 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005402 for (size_t j = 0; j < mOutputs.size(); j++) {
5403 if (mOutputs.keyAt(j) == ouptutToSkip) {
5404 continue;
5405 }
5406 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(j);
François Gaffiec005e562018-11-06 15:04:49 +01005407 if (!outputDesc->isStrategyActive(ps)) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005408 continue;
5409 }
5410 // If the default device for this strategy is on another output mix,
5411 // invalidate all tracks in this strategy to force re connection.
5412 // Otherwise select new device on the output mix.
5413 if (outputs.indexOf(mOutputs.keyAt(j)) < 0) {
jiabinc44b3462022-12-08 12:52:31 -08005414 invalidateStreams(mEngine->getStreamTypesForProductStrategy(ps));
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005415 } else {
jiabin3ff8d7d2022-12-13 06:27:44 +00005416 DeviceVector newDevices = getNewOutputDevices(outputDesc, false /*fromCache*/);
5417 if (outputDesc->mUsePreferredMixerAttributes && outputDesc->devices() != newDevices) {
5418 // If the device is using preferred mixer attributes, the output need to reopen
5419 // with default configuration when the new selected devices are different from
5420 // current routing devices.
5421 outputsToReopen.emplace(mOutputs.keyAt(j), newDevices);
5422 continue;
5423 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05305424 setOutputDevices(__func__, outputDesc, newDevices, false);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005425 }
5426 }
jiabin3ff8d7d2022-12-13 06:27:44 +00005427 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005428}
5429
5430void AudioPolicyManager::clearSessionRoutes(uid_t uid)
5431{
5432 // remove output routes associated with this uid
François Gaffiec005e562018-11-06 15:04:49 +01005433 std::vector<product_strategy_t> affectedStrategies;
Eric Laurent97ac8712018-07-27 18:59:02 -07005434 for (size_t i = 0; i < mOutputs.size(); i++) {
5435 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07005436 for (const auto& client : outputDesc->getClientIterable()) {
5437 if (client->hasPreferredDevice() && client->uid() == uid) {
5438 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
François Gaffiec005e562018-11-06 15:04:49 +01005439 auto clientStrategy = client->strategy();
5440 if (std::find(begin(affectedStrategies), end(affectedStrategies), clientStrategy) !=
5441 end(affectedStrategies)) {
5442 continue;
5443 }
5444 affectedStrategies.push_back(client->strategy());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005445 }
5446 }
5447 }
5448 // reroute outputs if necessary
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005449 for (const auto& strategy : affectedStrategies) {
5450 checkStrategyRoute(strategy, AUDIO_IO_HANDLE_NONE);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005451 }
5452
5453 // remove input routes associated with this uid
5454 SortedVector<audio_source_t> affectedSources;
Eric Laurent97ac8712018-07-27 18:59:02 -07005455 for (size_t i = 0; i < mInputs.size(); i++) {
5456 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07005457 for (const auto& client : inputDesc->getClientIterable()) {
5458 if (client->hasPreferredDevice() && client->uid() == uid) {
5459 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
5460 affectedSources.add(client->source());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005461 }
5462 }
5463 }
5464 // reroute inputs if necessary
5465 SortedVector<audio_io_handle_t> inputsToClose;
5466 for (size_t i = 0; i < mInputs.size(); i++) {
5467 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Eric Laurent4eb58f12018-12-07 16:41:02 -08005468 if (affectedSources.indexOf(inputDesc->source()) >= 0) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005469 inputsToClose.add(inputDesc->mIoHandle);
5470 }
5471 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005472 for (const auto& input : inputsToClose) {
5473 closeInput(input);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005474 }
5475}
5476
Eric Laurentd60560a2015-04-10 11:31:20 -07005477void AudioPolicyManager::clearAudioSources(uid_t uid)
5478{
5479 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005480 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
5481 if (sourceDesc->uid() == uid) {
Eric Laurentd60560a2015-04-10 11:31:20 -07005482 stopAudioSource(mAudioSources.keyAt(i));
5483 }
5484 }
5485}
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005486
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005487status_t AudioPolicyManager::acquireSoundTriggerSession(audio_session_t *session,
5488 audio_io_handle_t *ioHandle,
5489 audio_devices_t *device)
5490{
Glenn Kastenf0c6d7d2016-02-26 10:44:04 -08005491 *session = (audio_session_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
5492 *ioHandle = (audio_io_handle_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
Francois Gaffie716e1432019-01-14 16:58:59 +01005493 audio_attributes_t attr = { .source = AUDIO_SOURCE_HOTWORD };
Eric Laurentcedd5b52023-03-22 00:03:31 +00005494 sp<DeviceDescriptor> deviceDesc = mEngine->getInputDeviceForAttributes(attr);
5495 if (deviceDesc == nullptr) {
5496 return INVALID_OPERATION;
5497 }
5498 *device = deviceDesc->type();
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005499
François Gaffiedf372692015-03-19 10:43:27 +01005500 return mSoundTriggerSessions.acquireSession(*session, *ioHandle);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005501}
5502
Eric Laurentd60560a2015-04-10 11:31:20 -07005503status_t AudioPolicyManager::startAudioSource(const struct audio_port_config *source,
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005504 const audio_attributes_t *attributes,
5505 audio_port_handle_t *portId,
5506 uid_t uid)
Eric Laurent554a2772015-04-10 11:29:24 -07005507{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005508 ALOGV("%s", __FUNCTION__);
5509 *portId = AUDIO_PORT_HANDLE_NONE;
5510
5511 if (source == NULL || attributes == NULL || portId == NULL) {
5512 ALOGW("%s invalid argument: source %p attributes %p handle %p",
5513 __FUNCTION__, source, attributes, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005514 return BAD_VALUE;
5515 }
5516
Eric Laurentd60560a2015-04-10 11:31:20 -07005517 if (source->role != AUDIO_PORT_ROLE_SOURCE ||
5518 source->type != AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005519 ALOGW("%s INVALID_OPERATION source->role %d source->type %d",
5520 __FUNCTION__, source->role, source->type);
Eric Laurentd60560a2015-04-10 11:31:20 -07005521 return INVALID_OPERATION;
5522 }
5523
François Gaffie11d30102018-11-02 16:09:09 +01005524 sp<DeviceDescriptor> srcDevice =
Eric Laurentd60560a2015-04-10 11:31:20 -07005525 mAvailableInputDevices.getDevice(source->ext.device.type,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005526 String8(source->ext.device.address),
5527 AUDIO_FORMAT_DEFAULT);
François Gaffie11d30102018-11-02 16:09:09 +01005528 if (srcDevice == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005529 ALOGW("%s source->ext.device.type %08x not found", __FUNCTION__, source->ext.device.type);
Eric Laurentd60560a2015-04-10 11:31:20 -07005530 return BAD_VALUE;
5531 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005532
jiabin4ef93452019-09-10 14:29:54 -07005533 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurentd60560a2015-04-10 11:31:20 -07005534
François Gaffieaaac0fd2018-11-22 17:56:39 +01005535 sp<SourceClientDescriptor> sourceDesc =
François Gaffieafd4cea2019-11-18 15:50:22 +01005536 new SourceClientDescriptor(*portId, uid, *attributes, *source, srcDevice,
François Gaffieaaac0fd2018-11-22 17:56:39 +01005537 mEngine->getStreamTypeForAttributes(*attributes),
5538 mEngine->getProductStrategyForAttributes(*attributes),
5539 toVolumeSource(*attributes));
Eric Laurentd60560a2015-04-10 11:31:20 -07005540
5541 status_t status = connectAudioSource(sourceDesc);
5542 if (status == NO_ERROR) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005543 mAudioSources.add(*portId, sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07005544 }
5545 return status;
5546}
5547
Francois Gaffie601801d2021-06-22 13:27:39 +02005548sp<SourceClientDescriptor> AudioPolicyManager::startAudioSourceInternal(
5549 const struct audio_port_config *source, const audio_attributes_t *attributes, uid_t uid)
5550{
5551 ALOGV("%s", __FUNCTION__);
5552 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
5553
5554 status_t status = startAudioSource(source, attributes, &portId, uid);
5555 ALOGE_IF(status != OK, "%s: failed to start audio source (%d)", __func__, status);
5556 return mAudioSources.valueFor(portId);
5557}
5558
5559
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005560status_t AudioPolicyManager::connectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07005561{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005562 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->portId());
Eric Laurentd60560a2015-04-10 11:31:20 -07005563
5564 // make sure we only have one patch per source.
5565 disconnectAudioSource(sourceDesc);
5566
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005567 audio_attributes_t attributes = sourceDesc->attributes();
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005568 // May the device (dynamic) have been disconnected/reconnected, id has changed.
5569 sp<DeviceDescriptor> srcDevice = mAvailableInputDevices.getDevice(
5570 sourceDesc->srcDevice()->type(),
5571 String8(sourceDesc->srcDevice()->address().c_str()),
5572 AUDIO_FORMAT_DEFAULT);
François Gaffiec005e562018-11-06 15:04:49 +01005573 DeviceVector sinkDevices =
Francois Gaffieff1eb522020-05-06 18:37:04 +02005574 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false /*fromCache*/);
François Gaffiec005e562018-11-06 15:04:49 +01005575 ALOG_ASSERT(!sinkDevices.isEmpty(), "connectAudioSource(): no device found for attributes");
François Gaffie11d30102018-11-02 16:09:09 +01005576 sp<DeviceDescriptor> sinkDevice = sinkDevices.itemAt(0);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005577 if (!mAvailableOutputDevices.contains(sinkDevice)) {
5578 ALOGE("%s Device %s not available", __func__, sinkDevice->toString().c_str());
5579 return INVALID_OPERATION;
5580 }
François Gaffieafd4cea2019-11-18 15:50:22 +01005581 PatchBuilder patchBuilder;
5582 patchBuilder.addSink(sinkDevice).addSource(srcDevice);
5583 audio_patch_handle_t handle = AUDIO_PATCH_HANDLE_NONE;
François Gaffieafd4cea2019-11-18 15:50:22 +01005584
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005585 return connectAudioSourceToSink(
5586 sourceDesc, sinkDevice, patchBuilder.patch(), handle, mUidCached, 0 /*delayMs*/);
Eric Laurent554a2772015-04-10 11:29:24 -07005587}
5588
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005589status_t AudioPolicyManager::stopAudioSource(audio_port_handle_t portId)
Eric Laurent554a2772015-04-10 11:29:24 -07005590{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005591 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueFor(portId);
5592 ALOGV("%s port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005593 if (sourceDesc == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005594 ALOGW("%s unknown source for port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005595 return BAD_VALUE;
5596 }
5597 status_t status = disconnectAudioSource(sourceDesc);
5598
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005599 mAudioSources.removeItem(portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005600 return status;
5601}
5602
Andy Hung2ddee192015-12-18 17:34:44 -08005603status_t AudioPolicyManager::setMasterMono(bool mono)
5604{
5605 if (mMasterMono == mono) {
5606 return NO_ERROR;
5607 }
5608 mMasterMono = mono;
5609 // if enabling mono we close all offloaded devices, which will invalidate the
5610 // corresponding AudioTrack. The AudioTrack client/MediaPlayer is responsible
5611 // for recreating the new AudioTrack as non-offloaded PCM.
5612 //
5613 // If disabling mono, we leave all tracks as is: we don't know which clients
5614 // and tracks are able to be recreated as offloaded. The next "song" should
5615 // play back offloaded.
5616 if (mMasterMono) {
5617 Vector<audio_io_handle_t> offloaded;
5618 for (size_t i = 0; i < mOutputs.size(); ++i) {
5619 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
5620 if (desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
5621 offloaded.push(desc->mIoHandle);
5622 }
5623 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005624 for (const auto& handle : offloaded) {
5625 closeOutput(handle);
Andy Hung2ddee192015-12-18 17:34:44 -08005626 }
5627 }
5628 // update master mono for all remaining outputs
5629 for (size_t i = 0; i < mOutputs.size(); ++i) {
5630 updateMono(mOutputs.keyAt(i));
5631 }
5632 return NO_ERROR;
5633}
5634
5635status_t AudioPolicyManager::getMasterMono(bool *mono)
5636{
5637 *mono = mMasterMono;
5638 return NO_ERROR;
5639}
5640
Eric Laurentac9cef52017-06-09 15:46:26 -07005641float AudioPolicyManager::getStreamVolumeDB(
5642 audio_stream_type_t stream, int index, audio_devices_t device)
5643{
jiabin9a3361e2019-10-01 09:38:30 -07005644 return computeVolume(getVolumeCurves(stream), toVolumeSource(stream), index, {device});
Eric Laurentac9cef52017-06-09 15:46:26 -07005645}
5646
jiabin81772902018-04-02 17:52:27 -07005647status_t AudioPolicyManager::getSurroundFormats(unsigned int *numSurroundFormats,
5648 audio_format_t *surroundFormats,
Kriti Dang6537def2021-03-02 13:46:59 +01005649 bool *surroundFormatsEnabled)
jiabin81772902018-04-02 17:52:27 -07005650{
Kriti Dang6537def2021-03-02 13:46:59 +01005651 if (numSurroundFormats == nullptr || (*numSurroundFormats != 0 &&
5652 (surroundFormats == nullptr || surroundFormatsEnabled == nullptr))) {
jiabin81772902018-04-02 17:52:27 -07005653 return BAD_VALUE;
5654 }
Kriti Dang6537def2021-03-02 13:46:59 +01005655 ALOGV("%s() numSurroundFormats %d surroundFormats %p surroundFormatsEnabled %p",
5656 __func__, *numSurroundFormats, surroundFormats, surroundFormatsEnabled);
jiabin81772902018-04-02 17:52:27 -07005657
5658 size_t formatsWritten = 0;
5659 size_t formatsMax = *numSurroundFormats;
Kriti Dangef6be8f2020-11-05 11:58:19 +01005660
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005661 *numSurroundFormats = mConfig->getSurroundFormats().size();
Mikhail Naganov100f0122018-11-29 11:22:16 -08005662 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
5663 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005664 for (const auto& format: mConfig->getSurroundFormats()) {
jiabin81772902018-04-02 17:52:27 -07005665 if (formatsWritten < formatsMax) {
Kriti Dang6537def2021-03-02 13:46:59 +01005666 surroundFormats[formatsWritten] = format.first;
Mikhail Naganov100f0122018-11-29 11:22:16 -08005667 bool formatEnabled = true;
5668 switch (forceUse) {
5669 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL:
Kriti Dang6537def2021-03-02 13:46:59 +01005670 formatEnabled = mManualSurroundFormats.count(format.first) != 0;
Mikhail Naganov100f0122018-11-29 11:22:16 -08005671 break;
5672 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER:
5673 formatEnabled = false;
5674 break;
5675 default: // AUTO or ALWAYS => true
5676 break;
jiabin81772902018-04-02 17:52:27 -07005677 }
5678 surroundFormatsEnabled[formatsWritten++] = formatEnabled;
5679 }
jiabin81772902018-04-02 17:52:27 -07005680 }
5681 return NO_ERROR;
5682}
5683
Kriti Dang6537def2021-03-02 13:46:59 +01005684status_t AudioPolicyManager::getReportedSurroundFormats(unsigned int *numSurroundFormats,
5685 audio_format_t *surroundFormats) {
5686 if (numSurroundFormats == nullptr || (*numSurroundFormats != 0 && surroundFormats == nullptr)) {
5687 return BAD_VALUE;
5688 }
5689 ALOGV("%s() numSurroundFormats %d surroundFormats %p",
5690 __func__, *numSurroundFormats, surroundFormats);
5691
5692 size_t formatsWritten = 0;
5693 size_t formatsMax = *numSurroundFormats;
5694 std::unordered_set<audio_format_t> formats; // Uses primary surround formats only
5695
5696 // Return formats from all device profiles that have already been resolved by
5697 // checkOutputsForDevice().
5698 for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
5699 sp<DeviceDescriptor> device = mAvailableOutputDevices[i];
5700 audio_devices_t deviceType = device->type();
5701 // Enabling/disabling formats are applied to only HDMI devices. So, this function
5702 // returns formats reported by HDMI devices.
5703 if (deviceType != AUDIO_DEVICE_OUT_HDMI) {
5704 continue;
5705 }
5706 // Formats reported by sink devices
5707 std::unordered_set<audio_format_t> formatset;
5708 if (auto it = mReportedFormatsMap.find(device); it != mReportedFormatsMap.end()) {
5709 formatset.insert(it->second.begin(), it->second.end());
5710 }
5711
5712 // Formats hard-coded in the in policy configuration file (if any).
5713 FormatVector encodedFormats = device->encodedFormats();
5714 formatset.insert(encodedFormats.begin(), encodedFormats.end());
5715 // Filter the formats which are supported by the vendor hardware.
5716 for (auto it = formatset.begin(); it != formatset.end(); ++it) {
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005717 if (mConfig->getSurroundFormats().count(*it) != 0) {
Kriti Dang6537def2021-03-02 13:46:59 +01005718 formats.insert(*it);
5719 } else {
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005720 for (const auto& pair : mConfig->getSurroundFormats()) {
Kriti Dang6537def2021-03-02 13:46:59 +01005721 if (pair.second.count(*it) != 0) {
5722 formats.insert(pair.first);
5723 break;
5724 }
5725 }
5726 }
5727 }
5728 }
5729 *numSurroundFormats = formats.size();
5730 for (const auto& format: formats) {
5731 if (formatsWritten < formatsMax) {
5732 surroundFormats[formatsWritten++] = format;
5733 }
5734 }
5735 return NO_ERROR;
5736}
5737
jiabin81772902018-04-02 17:52:27 -07005738status_t AudioPolicyManager::setSurroundFormatEnabled(audio_format_t audioFormat, bool enabled)
5739{
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005740 ALOGV("%s() format 0x%X enabled %d", __func__, audioFormat, enabled);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005741 const auto& formatIter = mConfig->getSurroundFormats().find(audioFormat);
5742 if (formatIter == mConfig->getSurroundFormats().end()) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005743 ALOGW("%s() format 0x%X is not a known surround format", __func__, audioFormat);
jiabin81772902018-04-02 17:52:27 -07005744 return BAD_VALUE;
5745 }
5746
Mikhail Naganov100f0122018-11-29 11:22:16 -08005747 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND) !=
5748 AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005749 ALOGW("%s() not in manual mode for surround sound format selection", __func__);
jiabin81772902018-04-02 17:52:27 -07005750 return INVALID_OPERATION;
5751 }
5752
Mikhail Naganov100f0122018-11-29 11:22:16 -08005753 if ((mManualSurroundFormats.count(audioFormat) != 0) == enabled) {
jiabin81772902018-04-02 17:52:27 -07005754 return NO_ERROR;
5755 }
5756
Mikhail Naganov100f0122018-11-29 11:22:16 -08005757 std::unordered_set<audio_format_t> surroundFormatsBackup(mManualSurroundFormats);
jiabin81772902018-04-02 17:52:27 -07005758 if (enabled) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005759 mManualSurroundFormats.insert(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07005760 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005761 mManualSurroundFormats.insert(subFormat);
jiabin81772902018-04-02 17:52:27 -07005762 }
5763 } else {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005764 mManualSurroundFormats.erase(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07005765 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005766 mManualSurroundFormats.erase(subFormat);
jiabin81772902018-04-02 17:52:27 -07005767 }
5768 }
5769
5770 sp<SwAudioOutputDescriptor> outputDesc;
5771 bool profileUpdated = false;
jiabin9a3361e2019-10-01 09:38:30 -07005772 DeviceVector hdmiOutputDevices = mAvailableOutputDevices.getDevicesFromType(
5773 AUDIO_DEVICE_OUT_HDMI);
jiabin81772902018-04-02 17:52:27 -07005774 for (size_t i = 0; i < hdmiOutputDevices.size(); i++) {
5775 // Simulate reconnection to update enabled surround sound formats.
jiabince9f20e2019-09-12 16:29:15 -07005776 String8 address = String8(hdmiOutputDevices[i]->address().c_str());
jiabin5740f082019-08-19 15:08:30 -07005777 std::string name = hdmiOutputDevices[i]->getName();
jiabin81772902018-04-02 17:52:27 -07005778 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
5779 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
5780 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005781 name.c_str(),
5782 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005783 if (status != NO_ERROR) {
5784 continue;
5785 }
5786 status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
5787 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
5788 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005789 name.c_str(),
5790 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005791 profileUpdated |= (status == NO_ERROR);
5792 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08005793 // FIXME: Why doing this for input HDMI devices if we don't augment their reported formats?
jiabin9a3361e2019-10-01 09:38:30 -07005794 DeviceVector hdmiInputDevices = mAvailableInputDevices.getDevicesFromType(
jiabin81772902018-04-02 17:52:27 -07005795 AUDIO_DEVICE_IN_HDMI);
5796 for (size_t i = 0; i < hdmiInputDevices.size(); i++) {
5797 // Simulate reconnection to update enabled surround sound formats.
jiabince9f20e2019-09-12 16:29:15 -07005798 String8 address = String8(hdmiInputDevices[i]->address().c_str());
jiabin5740f082019-08-19 15:08:30 -07005799 std::string name = hdmiInputDevices[i]->getName();
jiabin81772902018-04-02 17:52:27 -07005800 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
5801 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
5802 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005803 name.c_str(),
5804 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005805 if (status != NO_ERROR) {
5806 continue;
5807 }
5808 status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
5809 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
5810 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005811 name.c_str(),
5812 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005813 profileUpdated |= (status == NO_ERROR);
5814 }
5815
jiabin81772902018-04-02 17:52:27 -07005816 if (!profileUpdated) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005817 ALOGW("%s() no audio profiles updated, undoing surround formats change", __func__);
Mikhail Naganov100f0122018-11-29 11:22:16 -08005818 mManualSurroundFormats = std::move(surroundFormatsBackup);
jiabin81772902018-04-02 17:52:27 -07005819 }
5820
5821 return profileUpdated ? NO_ERROR : INVALID_OPERATION;
5822}
5823
Eric Laurent5ada82e2019-08-29 17:53:54 -07005824void AudioPolicyManager::setAppState(audio_port_handle_t portId, app_state_t state)
Svet Ganovf4ddfef2018-01-16 07:37:58 -08005825{
Eric Laurent5ada82e2019-08-29 17:53:54 -07005826 ALOGV("%s(portId:%d, state:%d)", __func__, portId, state);
Eric Laurenta9f86652018-11-28 17:23:11 -08005827 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent5ada82e2019-08-29 17:53:54 -07005828 mInputs.valueAt(i)->setAppState(portId, state);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08005829 }
5830}
5831
jiabin6012f912018-11-02 17:06:30 -07005832bool AudioPolicyManager::isHapticPlaybackSupported()
5833{
5834 for (const auto& hwModule : mHwModules) {
5835 const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
5836 for (const auto &outProfile : outputProfiles) {
5837 struct audio_port audioPort;
5838 outProfile->toAudioPort(&audioPort);
5839 for (size_t i = 0; i < audioPort.num_channel_masks; i++) {
5840 if (audioPort.channel_masks[i] & AUDIO_CHANNEL_HAPTIC_ALL) {
5841 return true;
5842 }
5843 }
5844 }
5845 }
5846 return false;
5847}
5848
Carter Hsu325a8eb2022-01-19 19:56:51 +08005849bool AudioPolicyManager::isUltrasoundSupported()
5850{
5851 bool hasUltrasoundOutput = false;
5852 bool hasUltrasoundInput = false;
5853 for (const auto& hwModule : mHwModules) {
5854 const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
5855 if (!hasUltrasoundOutput) {
5856 for (const auto &outProfile : outputProfiles) {
5857 if (outProfile->getFlags() & AUDIO_OUTPUT_FLAG_ULTRASOUND) {
5858 hasUltrasoundOutput = true;
5859 break;
5860 }
5861 }
5862 }
5863
5864 const InputProfileCollection &inputProfiles = hwModule->getInputProfiles();
5865 if (!hasUltrasoundInput) {
5866 for (const auto &inputProfile : inputProfiles) {
5867 if (inputProfile->getFlags() & AUDIO_INPUT_FLAG_ULTRASOUND) {
5868 hasUltrasoundInput = true;
5869 break;
5870 }
5871 }
5872 }
5873
5874 if (hasUltrasoundOutput && hasUltrasoundInput)
5875 return true;
5876 }
5877 return false;
5878}
5879
Atneya Nair698f5ef2022-12-15 16:15:09 -08005880bool AudioPolicyManager::isHotwordStreamSupported(bool lookbackAudio)
5881{
5882 const auto mask = AUDIO_INPUT_FLAG_HOTWORD_TAP |
5883 (lookbackAudio ? AUDIO_INPUT_FLAG_HW_LOOKBACK : 0);
5884 for (const auto& hwModule : mHwModules) {
5885 const InputProfileCollection &inputProfiles = hwModule->getInputProfiles();
5886 for (const auto &inputProfile : inputProfiles) {
5887 if ((inputProfile->getFlags() & mask) == mask) {
5888 return true;
5889 }
5890 }
5891 }
5892 return false;
5893}
5894
Eric Laurent8340e672019-11-06 11:01:08 -08005895bool AudioPolicyManager::isCallScreenModeSupported()
5896{
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005897 return mConfig->isCallScreenModeSupported();
Eric Laurent8340e672019-11-06 11:01:08 -08005898}
5899
5900
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005901status_t AudioPolicyManager::disconnectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07005902{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005903 ALOGV("%s port Id %d", __FUNCTION__, sourceDesc->portId());
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005904 if (!sourceDesc->isConnected()) {
5905 ALOGV("%s port Id %d already disconnected", __FUNCTION__, sourceDesc->portId());
5906 return NO_ERROR;
5907 }
François Gaffieafd4cea2019-11-18 15:50:22 +01005908 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
5909 if (swOutput != 0) {
5910 status_t status = stopSource(swOutput, sourceDesc);
Eric Laurent733ce942017-12-07 12:18:25 -08005911 if (status == NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005912 swOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08005913 }
jiabinbce0c1d2020-10-05 11:20:18 -07005914 if (releaseOutput(sourceDesc->portId())) {
5915 // The output descriptor is reopened to query dynamic profiles. In that case, there is
5916 // no need to release audio patch here but just return NO_ERROR.
5917 return NO_ERROR;
5918 }
Eric Laurentd60560a2015-04-10 11:31:20 -07005919 } else {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005920 sp<HwAudioOutputDescriptor> hwOutputDesc = sourceDesc->hwOutput().promote();
Eric Laurentd60560a2015-04-10 11:31:20 -07005921 if (hwOutputDesc != 0) {
Eric Laurentd60560a2015-04-10 11:31:20 -07005922 // close Hwoutput and remove from mHwOutputs
5923 } else {
5924 ALOGW("%s source has neither SW nor HW output", __FUNCTION__);
5925 }
5926 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005927 status_t status = releaseAudioPatchInternal(sourceDesc->getPatchHandle(), 0, sourceDesc);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005928 sourceDesc->disconnect();
5929 return status;
Eric Laurentd60560a2015-04-10 11:31:20 -07005930}
5931
François Gaffiec005e562018-11-06 15:04:49 +01005932sp<SourceClientDescriptor> AudioPolicyManager::getSourceForAttributesOnOutput(
5933 audio_io_handle_t output, const audio_attributes_t &attr)
Eric Laurentd60560a2015-04-10 11:31:20 -07005934{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005935 sp<SourceClientDescriptor> source;
Eric Laurentd60560a2015-04-10 11:31:20 -07005936 for (size_t i = 0; i < mAudioSources.size(); i++) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005937 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005938 sp<SwAudioOutputDescriptor> outputDesc = sourceDesc->swOutput().promote();
François Gaffiec005e562018-11-06 15:04:49 +01005939 if (followsSameRouting(attr, sourceDesc->attributes()) &&
5940 outputDesc != 0 && outputDesc->mIoHandle == output) {
Eric Laurentd60560a2015-04-10 11:31:20 -07005941 source = sourceDesc;
5942 break;
5943 }
5944 }
5945 return source;
Eric Laurent554a2772015-04-10 11:29:24 -07005946}
5947
Eric Laurentb4f42a92022-01-17 17:37:31 +01005948bool AudioPolicyManager::canBeSpatializedInt(const audio_attributes_t *attr,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005949 const audio_config_t *config,
Andy Hung9dd1a5b2022-05-10 15:39:39 -07005950 const AudioDeviceTypeAddrVector &devices) const
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005951{
5952 // The caller can have the audio attributes criteria ignored by either passing a null ptr or
5953 // the AUDIO_ATTRIBUTES_INITIALIZER value.
Eric Laurentfa0f6742021-08-17 18:39:44 +02005954 // If attributes are specified, current policy is to only allow spatialization for media
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005955 // and game usages.
Eric Laurent39095982021-08-24 18:29:27 +02005956 if (attr != nullptr && *attr != AUDIO_ATTRIBUTES_INITIALIZER) {
5957 if (attr->usage != AUDIO_USAGE_MEDIA && attr->usage != AUDIO_USAGE_GAME) {
5958 return false;
5959 }
5960 if ((attr->flags & (AUDIO_FLAG_CONTENT_SPATIALIZED | AUDIO_FLAG_NEVER_SPATIALIZE)) != 0) {
5961 return false;
5962 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005963 }
5964
Eric Laurentd332bc82023-08-04 11:45:23 +02005965 // The caller can have the audio config criteria ignored by either passing a null ptr or
5966 // the AUDIO_CONFIG_INITIALIZER value.
5967 // If an audio config is specified, current policy is to only allow spatialization for
5968 // some positional channel masks and PCM format
5969
5970 if (config != nullptr && *config != AUDIO_CONFIG_INITIALIZER) {
5971 if (!audio_is_channel_mask_spatialized(config->channel_mask)) {
5972 return false;
5973 }
5974 if (!audio_is_linear_pcm(config->format)) {
5975 return false;
5976 }
5977 }
5978
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005979 sp<IOProfile> profile =
Eric Laurent39095982021-08-24 18:29:27 +02005980 getSpatializerOutputProfile(config, devices);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005981 if (profile == nullptr) {
5982 return false;
5983 }
5984
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005985 return true;
5986}
5987
5988void AudioPolicyManager::checkVirtualizerClientRoutes() {
5989 std::set<audio_stream_type_t> streamsToInvalidate;
5990 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent39095982021-08-24 18:29:27 +02005991 const sp<SwAudioOutputDescriptor>& desc = mOutputs[i];
5992 for (const sp<TrackClientDescriptor>& client : desc->getClientIterable()) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005993 audio_attributes_t attr = client->attributes();
5994 DeviceVector devices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false);
5995 AudioDeviceTypeAddrVector devicesTypeAddress = devices.toTypeAddrVector();
5996 audio_config_base_t clientConfig = client->config();
5997 audio_config_t config = audio_config_initializer(&clientConfig);
Eric Laurent39095982021-08-24 18:29:27 +02005998 if (desc != mSpatializerOutput
Andy Hung9dd1a5b2022-05-10 15:39:39 -07005999 && canBeSpatializedInt(&attr, &config, devicesTypeAddress)) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006000 streamsToInvalidate.insert(client->stream());
6001 }
6002 }
6003 }
6004
jiabinc44b3462022-12-08 12:52:31 -08006005 invalidateStreams(StreamTypeVector(streamsToInvalidate.begin(), streamsToInvalidate.end()));
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006006}
6007
Eric Laurente191d1b2022-04-15 11:59:25 +02006008
6009bool AudioPolicyManager::isOutputOnlyAvailableRouteToSomeDevice(
6010 const sp<SwAudioOutputDescriptor>& outputDesc) {
6011 if (outputDesc->isDuplicated()) {
6012 return false;
6013 }
6014 DeviceVector devices = outputDesc->supportedDevices();
6015 for (size_t i = 0; i < mOutputs.size(); i++) {
6016 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
6017 if (desc == outputDesc || desc->isDuplicated()) {
6018 continue;
6019 }
6020 DeviceVector sharedDevices = desc->filterSupportedDevices(devices);
6021 if (!sharedDevices.isEmpty()
6022 && (desc->devicesSupportEncodedFormats(sharedDevices.types())
6023 == outputDesc->devicesSupportEncodedFormats(sharedDevices.types()))) {
6024 return false;
6025 }
6026 }
6027 return true;
6028}
6029
6030
Eric Laurentfa0f6742021-08-17 18:39:44 +02006031status_t AudioPolicyManager::getSpatializerOutput(const audio_config_base_t *mixerConfig,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006032 const audio_attributes_t *attr,
6033 audio_io_handle_t *output) {
6034 *output = AUDIO_IO_HANDLE_NONE;
6035
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006036 DeviceVector devices = mEngine->getOutputDevicesForAttributes(*attr, nullptr, false);
6037 AudioDeviceTypeAddrVector devicesTypeAddress = devices.toTypeAddrVector();
6038 audio_config_t *configPtr = nullptr;
6039 audio_config_t config;
6040 if (mixerConfig != nullptr) {
6041 config = audio_config_initializer(mixerConfig);
6042 configPtr = &config;
6043 }
Andy Hung9dd1a5b2022-05-10 15:39:39 -07006044 if (!canBeSpatializedInt(attr, configPtr, devicesTypeAddress)) {
Eric Laurente191d1b2022-04-15 11:59:25 +02006045 ALOGV("%s provided attributes or mixer config cannot be spatialized", __func__);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006046 return BAD_VALUE;
6047 }
6048
6049 sp<IOProfile> profile =
Eric Laurent39095982021-08-24 18:29:27 +02006050 getSpatializerOutputProfile(configPtr, devicesTypeAddress);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006051 if (profile == nullptr) {
Eric Laurente191d1b2022-04-15 11:59:25 +02006052 ALOGV("%s no suitable output profile for provided attributes or mixer config", __func__);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006053 return BAD_VALUE;
6054 }
6055
Eric Laurente191d1b2022-04-15 11:59:25 +02006056 std::vector<sp<SwAudioOutputDescriptor>> spatializerOutputs;
Eric Laurent39095982021-08-24 18:29:27 +02006057 for (size_t i = 0; i < mOutputs.size(); i++) {
6058 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente191d1b2022-04-15 11:59:25 +02006059 if (!desc->isDuplicated()
6060 && (desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0) {
6061 spatializerOutputs.push_back(desc);
6062 ALOGV("%s adding opened spatializer Output %d", __func__, desc->mIoHandle);
Eric Laurent39095982021-08-24 18:29:27 +02006063 }
6064 }
Eric Laurente191d1b2022-04-15 11:59:25 +02006065 mSpatializerOutput.clear();
6066 bool outputsChanged = false;
6067 for (const auto& desc : spatializerOutputs) {
6068 if (desc->mProfile == profile
6069 && (configPtr == nullptr
6070 || configPtr->channel_mask == desc->mMixerChannelMask)) {
6071 mSpatializerOutput = desc;
6072 ALOGV("%s reusing current spatializer output %d", __func__, desc->mIoHandle);
6073 } else {
6074 ALOGV("%s closing spatializerOutput output %d to match channel mask %#x"
6075 " and devices %s", __func__, desc->mIoHandle,
6076 configPtr != nullptr ? configPtr->channel_mask : 0,
6077 devices.toString().c_str());
6078 closeOutput(desc->mIoHandle);
6079 outputsChanged = true;
6080 }
Eric Laurent39095982021-08-24 18:29:27 +02006081 }
6082
Eric Laurente191d1b2022-04-15 11:59:25 +02006083 if (mSpatializerOutput == nullptr) {
Eric Laurentb4f42a92022-01-17 17:37:31 +01006084 sp<SwAudioOutputDescriptor> desc =
6085 openOutputWithProfileAndDevice(profile, devices, mixerConfig);
Eric Laurente191d1b2022-04-15 11:59:25 +02006086 if (desc != nullptr) {
6087 mSpatializerOutput = desc;
6088 outputsChanged = true;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006089 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006090 }
6091
6092 checkVirtualizerClientRoutes();
6093
Eric Laurente191d1b2022-04-15 11:59:25 +02006094 if (outputsChanged) {
6095 mPreviousOutputs = mOutputs;
6096 mpClientInterface->onAudioPortListUpdate();
6097 }
6098
6099 if (mSpatializerOutput == nullptr) {
6100 ALOGV("%s could not open spatializer output with requested config", __func__);
6101 return BAD_VALUE;
6102 }
Eric Laurent39095982021-08-24 18:29:27 +02006103 *output = mSpatializerOutput->mIoHandle;
Eric Laurente191d1b2022-04-15 11:59:25 +02006104 ALOGV("%s returning new spatializer output %d", __func__, *output);
6105 return OK;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006106}
6107
Eric Laurentfa0f6742021-08-17 18:39:44 +02006108status_t AudioPolicyManager::releaseSpatializerOutput(audio_io_handle_t output) {
6109 if (mSpatializerOutput == nullptr) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006110 return INVALID_OPERATION;
6111 }
Eric Laurentfa0f6742021-08-17 18:39:44 +02006112 if (mSpatializerOutput->mIoHandle != output) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006113 return BAD_VALUE;
6114 }
Eric Laurent39095982021-08-24 18:29:27 +02006115
Eric Laurente191d1b2022-04-15 11:59:25 +02006116 if (!isOutputOnlyAvailableRouteToSomeDevice(mSpatializerOutput)) {
6117 ALOGV("%s closing spatializer output %d", __func__, mSpatializerOutput->mIoHandle);
6118 closeOutput(mSpatializerOutput->mIoHandle);
6119 //from now on mSpatializerOutput is null
6120 checkVirtualizerClientRoutes();
6121 }
Eric Laurent39095982021-08-24 18:29:27 +02006122
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006123 return NO_ERROR;
6124}
6125
Eric Laurente552edb2014-03-10 17:42:56 -07006126// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07006127// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07006128// ----------------------------------------------------------------------------
Eric Laurent6a94d692014-05-20 11:18:06 -07006129uint32_t AudioPolicyManager::nextAudioPortGeneration()
6130{
Mikhail Naganov2773dd72017-12-08 10:12:11 -08006131 return mAudioPortGeneration++;
Eric Laurent6a94d692014-05-20 11:18:06 -07006132}
6133
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006134AudioPolicyManager::AudioPolicyManager(const sp<const AudioPolicyConfig>& config,
Mikhail Naganovf1b6d972023-05-02 13:56:01 -07006135 EngineInstance&& engine,
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006136 AudioPolicyClientInterface *clientInterface)
Eric Laurente552edb2014-03-10 17:42:56 -07006137 :
Andy Hung4ef19fa2018-05-15 19:35:29 -07006138 mUidCached(AID_AUDIOSERVER), // no need to call getuid(), there's only one of us running.
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006139 mConfig(config),
Mikhail Naganovf1b6d972023-05-02 13:56:01 -07006140 mEngine(std::move(engine)),
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006141 mpClientInterface(clientInterface),
Eric Laurente552edb2014-03-10 17:42:56 -07006142 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
Eric Laurent3a4311c2014-03-17 12:00:47 -07006143 mA2dpSuspended(false),
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006144 mAudioPortGeneration(1),
6145 mBeaconMuteRefCount(0),
6146 mBeaconPlayingRefCount(0),
Eric Laurent9459fb02015-08-12 18:36:32 -07006147 mBeaconMuted(false),
Andy Hung2ddee192015-12-18 17:34:44 -08006148 mTtsOutputAvailable(false),
Eric Laurent36829f92017-04-07 19:04:42 -07006149 mMasterMono(false),
Eric Laurent4eb58f12018-12-07 16:41:02 -08006150 mMusicEffectOutput(AUDIO_IO_HANDLE_NONE)
Eric Laurente552edb2014-03-10 17:42:56 -07006151{
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006152}
François Gaffied1ab2bd2015-12-02 18:20:06 +01006153
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006154status_t AudioPolicyManager::initialize() {
Mikhail Naganovf1b6d972023-05-02 13:56:01 -07006155 if (mEngine == nullptr) {
6156 return NO_INIT;
François Gaffie2110e042015-03-24 08:41:51 +01006157 }
6158 mEngine->setObserver(this);
6159 status_t status = mEngine->initCheck();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006160 if (status != NO_ERROR) {
6161 LOG_FATAL("Policy engine not initialized(err=%d)", status);
6162 return status;
6163 }
François Gaffie2110e042015-03-24 08:41:51 +01006164
jiabin29230182023-04-04 21:02:36 +00006165 // The actual device selection cache will be updated when calling `updateDevicesAndOutputs`
6166 // at the end of this function.
6167 mEngine->initializeDeviceSelectionCache();
Eric Laurent1d69c872021-01-11 18:53:01 +01006168 mCommunnicationStrategy = mEngine->getProductStrategyForAttributes(
6169 mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL));
6170
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006171 // after parsing the config, mConfig contain all known devices;
Eric Laurente552edb2014-03-10 17:42:56 -07006172 // open all output streams needed to access attached devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006173 onNewAudioModulesAvailableInt(nullptr /*newDevices*/);
François Gaffie11d30102018-11-02 16:09:09 +01006174
Eric Laurent3a4311c2014-03-17 12:00:47 -07006175 // make sure default device is reachable
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006176 if (const auto defaultOutputDevice = mConfig->getDefaultOutputDevice();
6177 defaultOutputDevice == nullptr ||
6178 !mAvailableOutputDevices.contains(defaultOutputDevice)) {
6179 ALOGE_IF(defaultOutputDevice != nullptr, "Default device %s is unreachable",
6180 defaultOutputDevice->toString().c_str());
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006181 status = NO_INIT;
Eric Laurent3a4311c2014-03-17 12:00:47 -07006182 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02006183 ALOGW_IF(mPrimaryOutput == nullptr, "The policy configuration does not declare a primary output");
Eric Laurente552edb2014-03-10 17:42:56 -07006184
Tomoharu Kasahara71c90912018-10-31 09:10:12 +09006185 // Silence ALOGV statements
6186 property_set("log.tag." LOG_TAG, "D");
6187
Eric Laurente552edb2014-03-10 17:42:56 -07006188 updateDevicesAndOutputs();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006189 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07006190}
6191
Eric Laurente0720872014-03-11 09:30:41 -07006192AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07006193{
Eric Laurente552edb2014-03-10 17:42:56 -07006194 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08006195 mOutputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07006196 }
6197 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08006198 mInputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07006199 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07006200 mAvailableOutputDevices.clear();
6201 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07006202 mOutputs.clear();
6203 mInputs.clear();
6204 mHwModules.clear();
Mikhail Naganov100f0122018-11-29 11:22:16 -08006205 mManualSurroundFormats.clear();
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006206 mConfig.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07006207}
6208
Eric Laurente0720872014-03-11 09:30:41 -07006209status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07006210{
Eric Laurent87ffa392015-05-22 10:32:38 -07006211 return hasPrimaryOutput() ? NO_ERROR : NO_INIT;
Eric Laurente552edb2014-03-10 17:42:56 -07006212}
6213
Eric Laurente552edb2014-03-10 17:42:56 -07006214// ---
6215
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006216void AudioPolicyManager::onNewAudioModulesAvailable()
6217{
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006218 DeviceVector newDevices;
6219 onNewAudioModulesAvailableInt(&newDevices);
6220 if (!newDevices.empty()) {
6221 nextAudioPortGeneration();
6222 mpClientInterface->onAudioPortListUpdate();
6223 }
6224}
6225
6226void AudioPolicyManager::onNewAudioModulesAvailableInt(DeviceVector *newDevices)
6227{
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006228 for (const auto& hwModule : mConfig->getHwModules()) {
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006229 if (std::find(mHwModules.begin(), mHwModules.end(), hwModule) != mHwModules.end()) {
6230 continue;
6231 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006232 if (hwModule->getHandle() == AUDIO_MODULE_HANDLE_NONE) {
Mikhail Naganovffd97712023-05-03 17:45:36 -07006233 if (audio_module_handle_t handle = mpClientInterface->loadHwModule(hwModule->getName());
6234 handle != AUDIO_MODULE_HANDLE_NONE) {
6235 hwModule->setHandle(handle);
6236 } else {
6237 ALOGW("could not load HW module %s", hwModule->getName());
6238 continue;
6239 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006240 }
6241 mHwModules.push_back(hwModule);
Dean Wheatley12a87132021-04-16 10:08:49 +10006242 // open all output streams needed to access attached devices.
6243 // direct outputs are closed immediately after checking the availability of attached devices
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006244 // This also validates mAvailableOutputDevices list
6245 for (const auto& outProfile : hwModule->getOutputProfiles()) {
6246 if (!outProfile->canOpenNewIo()) {
6247 ALOGE("Invalid Output profile max open count %u for profile %s",
6248 outProfile->maxOpenCount, outProfile->getTagName().c_str());
6249 continue;
6250 }
6251 if (!outProfile->hasSupportedDevices()) {
6252 ALOGW("Output profile contains no device on module %s", hwModule->getName());
6253 continue;
6254 }
Carter Hsu1a3364a2022-01-21 15:32:56 +08006255 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_TTS) != 0 ||
6256 (outProfile->getFlags() & AUDIO_OUTPUT_FLAG_ULTRASOUND) != 0) {
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006257 mTtsOutputAvailable = true;
6258 }
6259
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006260 const DeviceVector &supportedDevices = outProfile->getSupportedDevices();
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006261 DeviceVector availProfileDevices = supportedDevices.filter(mConfig->getOutputDevices());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006262 sp<DeviceDescriptor> supportedDevice = 0;
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006263 if (supportedDevices.contains(mConfig->getDefaultOutputDevice())) {
6264 supportedDevice = mConfig->getDefaultOutputDevice();
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006265 } else {
6266 // choose first device present in profile's SupportedDevices also part of
6267 // mAvailableOutputDevices.
6268 if (availProfileDevices.isEmpty()) {
6269 continue;
6270 }
6271 supportedDevice = availProfileDevices.itemAt(0);
6272 }
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006273 if (!mConfig->getOutputDevices().contains(supportedDevice)) {
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006274 continue;
6275 }
6276 sp<SwAudioOutputDescriptor> outputDesc = new SwAudioOutputDescriptor(outProfile,
6277 mpClientInterface);
6278 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentf1f22e72021-07-13 14:04:14 +02006279 status_t status = outputDesc->open(nullptr /* halConfig */, nullptr /* mixerConfig */,
6280 DeviceVector(supportedDevice),
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006281 AUDIO_STREAM_DEFAULT,
6282 AUDIO_OUTPUT_FLAG_NONE, &output);
6283 if (status != NO_ERROR) {
6284 ALOGW("Cannot open output stream for devices %s on hw module %s",
6285 supportedDevice->toString().c_str(), hwModule->getName());
6286 continue;
6287 }
6288 for (const auto &device : availProfileDevices) {
6289 // give a valid ID to an attached device once confirmed it is reachable
6290 if (!device->isAttached()) {
6291 device->attach(hwModule);
6292 mAvailableOutputDevices.add(device);
jiabin1c4794b2020-05-05 10:08:05 -07006293 device->setEncapsulationInfoFromHal(mpClientInterface);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006294 if (newDevices) newDevices->add(device);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006295 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
6296 }
6297 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02006298 if (mPrimaryOutput == nullptr &&
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006299 outProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
6300 mPrimaryOutput = outputDesc;
François Gaffiedb1755b2023-09-01 11:50:35 +02006301 mPrimaryModuleHandle = mPrimaryOutput->getModuleHandle();
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006302 }
Eric Laurent39095982021-08-24 18:29:27 +02006303 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
Eric Laurentc529cf62020-04-17 18:19:10 -07006304 outputDesc->close();
6305 } else {
6306 addOutput(output, outputDesc);
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05306307 setOutputDevices(__func__, outputDesc,
Eric Laurentc529cf62020-04-17 18:19:10 -07006308 DeviceVector(supportedDevice),
6309 true,
6310 0,
6311 NULL);
6312 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006313 }
6314 // open input streams needed to access attached devices to validate
6315 // mAvailableInputDevices list
6316 for (const auto& inProfile : hwModule->getInputProfiles()) {
6317 if (!inProfile->canOpenNewIo()) {
6318 ALOGE("Invalid Input profile max open count %u for profile %s",
6319 inProfile->maxOpenCount, inProfile->getTagName().c_str());
6320 continue;
6321 }
6322 if (!inProfile->hasSupportedDevices()) {
6323 ALOGW("Input profile contains no device on module %s", hwModule->getName());
6324 continue;
6325 }
6326 // chose first device present in profile's SupportedDevices also part of
6327 // available input devices
6328 const DeviceVector &supportedDevices = inProfile->getSupportedDevices();
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006329 DeviceVector availProfileDevices = supportedDevices.filter(mConfig->getInputDevices());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006330 if (availProfileDevices.isEmpty()) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01006331 ALOGV("%s: Input device list is empty! for profile %s",
6332 __func__, inProfile->getTagName().c_str());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006333 continue;
6334 }
6335 sp<AudioInputDescriptor> inputDesc =
6336 new AudioInputDescriptor(inProfile, mpClientInterface);
6337
6338 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
6339 status_t status = inputDesc->open(nullptr,
6340 availProfileDevices.itemAt(0),
6341 AUDIO_SOURCE_MIC,
6342 AUDIO_INPUT_FLAG_NONE,
6343 &input);
6344 if (status != NO_ERROR) {
6345 ALOGW("Cannot open input stream for device %s on hw module %s",
6346 availProfileDevices.toString().c_str(),
6347 hwModule->getName());
6348 continue;
6349 }
6350 for (const auto &device : availProfileDevices) {
6351 // give a valid ID to an attached device once confirmed it is reachable
6352 if (!device->isAttached()) {
6353 device->attach(hwModule);
6354 device->importAudioPortAndPickAudioProfile(inProfile, true);
6355 mAvailableInputDevices.add(device);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006356 if (newDevices) newDevices->add(device);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006357 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
6358 }
6359 }
6360 inputDesc->close();
6361 }
6362 }
Eric Laurente191d1b2022-04-15 11:59:25 +02006363
6364 // Check if spatializer outputs can be closed until used.
6365 // mOutputs vector never contains duplicated outputs at this point.
6366 std::vector<audio_io_handle_t> outputsClosed;
6367 for (size_t i = 0; i < mOutputs.size(); i++) {
6368 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
6369 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0
6370 && !isOutputOnlyAvailableRouteToSomeDevice(desc)) {
6371 outputsClosed.push_back(desc->mIoHandle);
6372 desc->close();
6373 }
6374 }
6375 for (auto output : outputsClosed) {
6376 removeOutput(output);
6377 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006378}
6379
Eric Laurent98e38192018-02-15 18:31:53 -08006380void AudioPolicyManager::addOutput(audio_io_handle_t output,
6381 const sp<SwAudioOutputDescriptor>& outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07006382{
Eric Laurent1c333e22014-05-20 10:48:17 -07006383 mOutputs.add(output, outputDesc);
jiabin9a3361e2019-10-01 09:38:30 -07006384 applyStreamVolumes(outputDesc, DeviceTypeSet(), 0 /* delayMs */, true /* force */);
Andy Hung2ddee192015-12-18 17:34:44 -08006385 updateMono(output); // update mono status when adding to output list
Eric Laurent36829f92017-04-07 19:04:42 -07006386 selectOutputForMusicEffects();
Eric Laurent6a94d692014-05-20 11:18:06 -07006387 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07006388}
6389
François Gaffie53615e22015-03-19 09:24:12 +01006390void AudioPolicyManager::removeOutput(audio_io_handle_t output)
6391{
Francois Gaffiebce7cd42020-10-14 16:13:20 +02006392 if (mPrimaryOutput != 0 && mPrimaryOutput == mOutputs.valueFor(output)) {
6393 ALOGV("%s: removing primary output", __func__);
6394 mPrimaryOutput = nullptr;
6395 }
François Gaffie53615e22015-03-19 09:24:12 +01006396 mOutputs.removeItem(output);
Eric Laurent36829f92017-04-07 19:04:42 -07006397 selectOutputForMusicEffects();
François Gaffie53615e22015-03-19 09:24:12 +01006398}
6399
Eric Laurent98e38192018-02-15 18:31:53 -08006400void AudioPolicyManager::addInput(audio_io_handle_t input,
6401 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07006402{
Eric Laurent1c333e22014-05-20 10:48:17 -07006403 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07006404 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07006405}
Eric Laurente552edb2014-03-10 17:42:56 -07006406
François Gaffie11d30102018-11-02 16:09:09 +01006407status_t AudioPolicyManager::checkOutputsForDevice(const sp<DeviceDescriptor>& device,
François Gaffie53615e22015-03-19 09:24:12 +01006408 audio_policy_dev_state_t state,
François Gaffie11d30102018-11-02 16:09:09 +01006409 SortedVector<audio_io_handle_t>& outputs)
Eric Laurente552edb2014-03-10 17:42:56 -07006410{
François Gaffie11d30102018-11-02 16:09:09 +01006411 audio_devices_t deviceType = device->type();
jiabince9f20e2019-09-12 16:29:15 -07006412 const String8 &address = String8(device->address().c_str());
Eric Laurentc75307b2015-03-17 15:29:32 -07006413 sp<SwAudioOutputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07006414
François Gaffie11d30102018-11-02 16:09:09 +01006415 if (audio_device_is_digital(deviceType)) {
Eric Laurentcc750d32015-06-25 11:48:20 -07006416 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01006417 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07006418 }
Eric Laurente552edb2014-03-10 17:42:56 -07006419
Eric Laurent3b73df72014-03-11 09:06:29 -07006420 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
jiabinb4fed192020-09-22 14:45:40 -07006421 // first call getAudioPort to get the supported attributes from the HAL
6422 struct audio_port_v7 port = {};
6423 device->toAudioPort(&port);
6424 status_t status = mpClientInterface->getAudioPort(&port);
6425 if (status == NO_ERROR) {
6426 device->importAudioPort(port);
6427 }
6428
6429 // then list already open outputs that can be routed to this device
Eric Laurente552edb2014-03-10 17:42:56 -07006430 for (size_t i = 0; i < mOutputs.size(); i++) {
6431 desc = mOutputs.valueAt(i);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006432 if (!desc->isDuplicated() && desc->supportsDevice(device)
jiabin9a3361e2019-10-01 09:38:30 -07006433 && desc->devicesSupportEncodedFormats({deviceType})) {
François Gaffie11d30102018-11-02 16:09:09 +01006434 ALOGV("checkOutputsForDevice(): adding opened output %d on device %s",
6435 mOutputs.keyAt(i), device->toString().c_str());
6436 outputs.add(mOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07006437 }
6438 }
6439 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07006440 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006441 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006442 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
6443 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
François Gaffie11d30102018-11-02 16:09:09 +01006444 if (profile->supportsDevice(device)) {
6445 profiles.add(profile);
6446 ALOGV("checkOutputsForDevice(): adding profile %zu from module %s",
6447 j, hwModule->getName());
Eric Laurente552edb2014-03-10 17:42:56 -07006448 }
6449 }
6450 }
6451
Eric Laurent7b279bb2015-12-14 10:18:23 -08006452 ALOGV(" found %zu profiles, %zu outputs", profiles.size(), outputs.size());
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006453
Eric Laurente552edb2014-03-10 17:42:56 -07006454 if (profiles.isEmpty() && outputs.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006455 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07006456 return BAD_VALUE;
6457 }
6458
6459 // open outputs for matching profiles if needed. Direct outputs are also opened to
6460 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
6461 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07006462 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07006463
6464 // nothing to do if one output is already opened for this profile
6465 size_t j;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006466 for (j = 0; j < outputs.size(); j++) {
6467 desc = mOutputs.valueFor(outputs.itemAt(j));
Eric Laurente552edb2014-03-10 17:42:56 -07006468 if (!desc->isDuplicated() && desc->mProfile == profile) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07006469 // matching profile: save the sample rates, format and channel masks supported
6470 // by the profile in our device descriptor
François Gaffie11d30102018-11-02 16:09:09 +01006471 if (audio_device_is_digital(deviceType)) {
jiabin4ef93452019-09-10 14:29:54 -07006472 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006473 }
Eric Laurente552edb2014-03-10 17:42:56 -07006474 break;
6475 }
6476 }
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006477 if (j != outputs.size()) {
Eric Laurente552edb2014-03-10 17:42:56 -07006478 continue;
6479 }
6480
Eric Laurent3974e3b2017-12-07 17:58:43 -08006481 if (!profile->canOpenNewIo()) {
6482 ALOGW("Max Output number %u already opened for this profile %s",
6483 profile->maxOpenCount, profile->getTagName().c_str());
6484 continue;
6485 }
6486
Eric Laurent83efe1c2017-07-09 16:51:08 -07006487 ALOGV("opening output for device %08x with params %s profile %p name %s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00006488 deviceType, address.c_str(), profile.get(), profile->getName().c_str());
jiabinbce0c1d2020-10-05 11:20:18 -07006489 desc = openOutputWithProfileAndDevice(profile, DeviceVector(device));
6490 audio_io_handle_t output = desc == nullptr ? AUDIO_IO_HANDLE_NONE : desc->mIoHandle;
Eric Laurentcf2c0212014-07-25 16:20:43 -07006491 if (output == AUDIO_IO_HANDLE_NONE) {
François Gaffie11d30102018-11-02 16:09:09 +01006492 ALOGW("checkOutputsForDevice() could not open output for device %x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07006493 profiles.removeAt(profile_index);
6494 profile_index--;
6495 } else {
6496 outputs.add(output);
Paul McLean9080a4c2015-06-18 08:24:02 -07006497 // Load digital format info only for digital devices
François Gaffie11d30102018-11-02 16:09:09 +01006498 if (audio_device_is_digital(deviceType)) {
jiabinbce0c1d2020-10-05 11:20:18 -07006499 // TODO: when getAudioPort is ready, it may not be needed to import the audio
6500 // port but just pick audio profile
jiabin4ef93452019-09-10 14:29:54 -07006501 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006502 }
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07006503
François Gaffie11d30102018-11-02 16:09:09 +01006504 if (device_distinguishes_on_address(deviceType)) {
6505 ALOGV("checkOutputsForDevice(): setOutputDevices %s",
6506 device->toString().c_str());
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05306507 setOutputDevices(__func__, desc, DeviceVector(device), true/*force*/,
6508 0/*delay*/, NULL/*patch handle*/);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006509 }
Eric Laurente552edb2014-03-10 17:42:56 -07006510 ALOGV("checkOutputsForDevice(): adding output %d", output);
6511 }
6512 }
6513
6514 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006515 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07006516 return BAD_VALUE;
6517 }
Eric Laurentd4692962014-05-05 18:13:44 -07006518 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07006519 // check if one opened output is not needed any more after disconnecting one device
6520 for (size_t i = 0; i < mOutputs.size(); i++) {
6521 desc = mOutputs.valueAt(i);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006522 if (!desc->isDuplicated()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08006523 // exact match on device
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006524 if (device_distinguishes_on_address(deviceType) && desc->supportsDevice(device)
Francois Gaffiec7d4c222021-12-02 11:12:52 +01006525 && desc->containsSingleDeviceSupportingEncodedFormats(device)) {
François Gaffie11d30102018-11-02 16:09:09 +01006526 outputs.add(mOutputs.keyAt(i));
Francois Gaffie716e1432019-01-14 16:58:59 +01006527 } else if (!mAvailableOutputDevices.containsAtLeastOne(desc->supportedDevices())) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006528 ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
6529 mOutputs.keyAt(i));
6530 outputs.add(mOutputs.keyAt(i));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006531 }
Eric Laurente552edb2014-03-10 17:42:56 -07006532 }
6533 }
Eric Laurentd4692962014-05-05 18:13:44 -07006534 // Clear any profiles associated with the disconnected device.
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006535 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006536 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
6537 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
jiabinbce0c1d2020-10-05 11:20:18 -07006538 if (!profile->supportsDevice(device)) {
6539 continue;
6540 }
6541 ALOGV("checkOutputsForDevice(): "
6542 "clearing direct output profile %zu on module %s",
6543 j, hwModule->getName());
6544 profile->clearAudioProfiles();
6545 if (!profile->hasDynamicAudioProfile()) {
6546 continue;
6547 }
6548 // When a device is disconnected, if there is an IOProfile that contains dynamic
6549 // profiles and supports the disconnected device, call getAudioPort to repopulate
6550 // the capabilities of the devices that is supported by the IOProfile.
6551 for (const auto& supportedDevice : profile->getSupportedDevices()) {
6552 if (supportedDevice == device ||
6553 !mAvailableOutputDevices.contains(supportedDevice)) {
6554 continue;
6555 }
6556 struct audio_port_v7 port;
6557 supportedDevice->toAudioPort(&port);
6558 status_t status = mpClientInterface->getAudioPort(&port);
6559 if (status == NO_ERROR) {
6560 supportedDevice->importAudioPort(port);
6561 }
Eric Laurente552edb2014-03-10 17:42:56 -07006562 }
6563 }
6564 }
6565 }
6566 return NO_ERROR;
6567}
6568
François Gaffie11d30102018-11-02 16:09:09 +01006569status_t AudioPolicyManager::checkInputsForDevice(const sp<DeviceDescriptor>& device,
Eric Laurent0dd51852019-04-19 18:18:58 -07006570 audio_policy_dev_state_t state)
Eric Laurentd4692962014-05-05 18:13:44 -07006571{
Eric Laurent1f2f2232014-06-02 12:01:23 -07006572 sp<AudioInputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07006573
François Gaffie11d30102018-11-02 16:09:09 +01006574 if (audio_device_is_digital(device->type())) {
Eric Laurentcc750d32015-06-25 11:48:20 -07006575 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01006576 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07006577 }
6578
Eric Laurentd4692962014-05-05 18:13:44 -07006579 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
jiabinbf5f4262023-04-12 21:48:34 +00006580 // first call getAudioPort to get the supported attributes from the HAL
6581 struct audio_port_v7 port = {};
6582 device->toAudioPort(&port);
6583 status_t status = mpClientInterface->getAudioPort(&port);
6584 if (status == NO_ERROR) {
6585 device->importAudioPort(port);
6586 }
6587
Eric Laurent0dd51852019-04-19 18:18:58 -07006588 // look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07006589 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006590 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07006591 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006592 profile_index < hwModule->getInputProfiles().size();
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006593 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006594 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Eric Laurent275e8e92014-11-30 15:14:47 -08006595
François Gaffie11d30102018-11-02 16:09:09 +01006596 if (profile->supportsDevice(device)) {
6597 profiles.add(profile);
6598 ALOGV("checkInputsForDevice(): adding profile %zu from module %s",
6599 profile_index, hwModule->getName());
Eric Laurentd4692962014-05-05 18:13:44 -07006600 }
6601 }
6602 }
6603
Eric Laurent0dd51852019-04-19 18:18:58 -07006604 if (profiles.isEmpty()) {
6605 ALOGW("%s: No input profile available for device %s",
6606 __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07006607 return BAD_VALUE;
6608 }
6609
6610 // open inputs for matching profiles if needed. Direct inputs are also opened to
6611 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
6612 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
6613
Eric Laurent1c333e22014-05-20 10:48:17 -07006614 sp<IOProfile> profile = profiles[profile_index];
Eric Laurent3974e3b2017-12-07 17:58:43 -08006615
Eric Laurentd4692962014-05-05 18:13:44 -07006616 // nothing to do if one input is already opened for this profile
6617 size_t input_index;
6618 for (input_index = 0; input_index < mInputs.size(); input_index++) {
6619 desc = mInputs.valueAt(input_index);
6620 if (desc->mProfile == profile) {
François Gaffie11d30102018-11-02 16:09:09 +01006621 if (audio_device_is_digital(device->type())) {
jiabin4ef93452019-09-10 14:29:54 -07006622 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006623 }
Eric Laurentd4692962014-05-05 18:13:44 -07006624 break;
6625 }
6626 }
6627 if (input_index != mInputs.size()) {
6628 continue;
6629 }
6630
Eric Laurent3974e3b2017-12-07 17:58:43 -08006631 if (!profile->canOpenNewIo()) {
6632 ALOGW("Max Input number %u already opened for this profile %s",
6633 profile->maxOpenCount, profile->getTagName().c_str());
6634 continue;
6635 }
6636
Eric Laurentfe231122017-11-17 17:48:06 -08006637 desc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentcf2c0212014-07-25 16:20:43 -07006638 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
jiabinbf5f4262023-04-12 21:48:34 +00006639 status = desc->open(nullptr, device, AUDIO_SOURCE_MIC, AUDIO_INPUT_FLAG_NONE, &input);
Eric Laurentd4692962014-05-05 18:13:44 -07006640
Eric Laurentcf2c0212014-07-25 16:20:43 -07006641 if (status == NO_ERROR) {
jiabince9f20e2019-09-12 16:29:15 -07006642 const String8& address = String8(device->address().c_str());
Tomasz Wasilczykfd9ffd12023-08-14 17:56:22 +00006643 if (!address.empty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006644 char *param = audio_device_address_to_parameter(device->type(), address);
Eric Laurentcf2c0212014-07-25 16:20:43 -07006645 mpClientInterface->setParameters(input, String8(param));
6646 free(param);
Eric Laurentd4692962014-05-05 18:13:44 -07006647 }
jiabin12537fc2023-10-12 17:56:08 +00006648 updateAudioProfiles(device, input, profile);
François Gaffie112b0af2015-11-19 16:13:25 +01006649 if (!profile->hasValidAudioProfile()) {
Eric Laurentd4692962014-05-05 18:13:44 -07006650 ALOGW("checkInputsForDevice() direct input missing param");
Eric Laurentfe231122017-11-17 17:48:06 -08006651 desc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07006652 input = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07006653 }
6654
Eric Laurent0dd51852019-04-19 18:18:58 -07006655 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07006656 addInput(input, desc);
6657 }
6658 } // endif input != 0
6659
Eric Laurentcf2c0212014-07-25 16:20:43 -07006660 if (input == AUDIO_IO_HANDLE_NONE) {
Pattydd807582021-11-04 21:01:03 +08006661 ALOGW("%s could not open input for device %s", __func__,
François Gaffie11d30102018-11-02 16:09:09 +01006662 device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07006663 profiles.removeAt(profile_index);
6664 profile_index--;
6665 } else {
François Gaffie11d30102018-11-02 16:09:09 +01006666 if (audio_device_is_digital(device->type())) {
jiabin4ef93452019-09-10 14:29:54 -07006667 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006668 }
Eric Laurentd4692962014-05-05 18:13:44 -07006669 ALOGV("checkInputsForDevice(): adding input %d", input);
6670 }
6671 } // end scan profiles
6672
6673 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006674 ALOGW("%s: No input available for device %s", __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07006675 return BAD_VALUE;
6676 }
6677 } else {
6678 // Disconnect
Eric Laurentd4692962014-05-05 18:13:44 -07006679 // Clear any profiles associated with the disconnected device.
Mikhail Naganovd4120142017-12-06 15:49:22 -08006680 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07006681 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006682 profile_index < hwModule->getInputProfiles().size();
Eric Laurentd4692962014-05-05 18:13:44 -07006683 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006684 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Francois Gaffie716e1432019-01-14 16:58:59 +01006685 if (profile->supportsDevice(device)) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08006686 ALOGV("checkInputsForDevice(): clearing direct input profile %zu on module %s",
6687 profile_index, hwModule->getName());
François Gaffie112b0af2015-11-19 16:13:25 +01006688 profile->clearAudioProfiles();
Eric Laurentd4692962014-05-05 18:13:44 -07006689 }
6690 }
6691 }
6692 } // end disconnect
6693
6694 return NO_ERROR;
6695}
6696
6697
Eric Laurente0720872014-03-11 09:30:41 -07006698void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07006699{
6700 ALOGV("closeOutput(%d)", output);
6701
François Gaffie1c878552018-11-22 16:53:21 +01006702 sp<SwAudioOutputDescriptor> closingOutput = mOutputs.valueFor(output);
6703 if (closingOutput == NULL) {
Eric Laurente552edb2014-03-10 17:42:56 -07006704 ALOGW("closeOutput() unknown output %d", output);
6705 return;
6706 }
Mikhail Naganov32ebca32019-03-22 15:42:52 -07006707 const bool closingOutputWasActive = closingOutput->isActive();
jiabin24ff57a2023-11-27 21:06:51 +00006708 mPolicyMixes.closeOutput(closingOutput, mOutputs);
Eric Laurent275e8e92014-11-30 15:14:47 -08006709
Eric Laurente552edb2014-03-10 17:42:56 -07006710 // look for duplicated outputs connected to the output being removed.
6711 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie1c878552018-11-22 16:53:21 +01006712 sp<SwAudioOutputDescriptor> dupOutput = mOutputs.valueAt(i);
6713 if (dupOutput->isDuplicated() &&
6714 (dupOutput->mOutput1 == closingOutput || dupOutput->mOutput2 == closingOutput)) {
6715 sp<SwAudioOutputDescriptor> remainingOutput =
6716 dupOutput->mOutput1 == closingOutput ? dupOutput->mOutput2 : dupOutput->mOutput1;
Eric Laurente552edb2014-03-10 17:42:56 -07006717 // As all active tracks on duplicated output will be deleted,
6718 // and as they were also referenced on the other output, the reference
6719 // count for their stream type must be adjusted accordingly on
6720 // the other output.
François Gaffie1c878552018-11-22 16:53:21 +01006721 const bool wasActive = remainingOutput->isActive();
6722 // Note: no-op on the closing output where all clients has already been set inactive
6723 dupOutput->setAllClientsInactive();
Eric Laurent733ce942017-12-07 12:18:25 -08006724 // stop() will be a no op if the output is still active but is needed in case all
6725 // active streams refcounts where cleared above
6726 if (wasActive) {
François Gaffie1c878552018-11-22 16:53:21 +01006727 remainingOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08006728 }
Eric Laurente552edb2014-03-10 17:42:56 -07006729 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
6730 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
6731
6732 mpClientInterface->closeOutput(duplicatedOutput);
François Gaffie53615e22015-03-19 09:24:12 +01006733 removeOutput(duplicatedOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07006734 }
6735 }
6736
Eric Laurent05b90f82014-08-27 15:32:29 -07006737 nextAudioPortGeneration();
6738
François Gaffie1c878552018-11-22 16:53:21 +01006739 ssize_t index = mAudioPatches.indexOfKey(closingOutput->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07006740 if (index >= 0) {
6741 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006742 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
6743 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07006744 mAudioPatches.removeItemsAt(index);
6745 mpClientInterface->onAudioPatchListUpdate();
6746 }
6747
Mikhail Naganov32ebca32019-03-22 15:42:52 -07006748 if (closingOutputWasActive) {
6749 closingOutput->stop();
6750 }
François Gaffie1c878552018-11-22 16:53:21 +01006751 closingOutput->close();
Eric Laurente552edb2014-03-10 17:42:56 -07006752
François Gaffie53615e22015-03-19 09:24:12 +01006753 removeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07006754 mPreviousOutputs = mOutputs;
Eric Laurentb4f42a92022-01-17 17:37:31 +01006755 if (closingOutput == mSpatializerOutput) {
6756 mSpatializerOutput.clear();
6757 }
Dean Wheatley3023b382018-08-09 07:42:40 +10006758
6759 // MSD patches may have been released to support a non-MSD direct output. Reset MSD patch if
6760 // no direct outputs are open.
François Gaffie11d30102018-11-02 16:09:09 +01006761 if (!getMsdAudioOutDevices().isEmpty()) {
Dean Wheatley3023b382018-08-09 07:42:40 +10006762 bool directOutputOpen = false;
6763 for (size_t i = 0; i < mOutputs.size(); i++) {
6764 if (mOutputs[i]->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
6765 directOutputOpen = true;
6766 break;
6767 }
6768 }
6769 if (!directOutputOpen) {
Michael Chan6fb34492020-12-08 15:44:49 +11006770 ALOGV("no direct outputs open, reset MSD patches");
6771 // TODO: The MSD patches to be established here may differ to current MSD patches due to
6772 // how output devices for patching are resolved. Avoid by caching and reusing the
6773 // arguments to mEngine->getOutputDevicesForAttributes() when resolving which output
6774 // devices to patch to. This may be complicated by the fact that devices may become
6775 // unavailable.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11006776 setMsdOutputPatches();
Dean Wheatley3023b382018-08-09 07:42:40 +10006777 }
6778 }
Eric Laurent05b90f82014-08-27 15:32:29 -07006779}
6780
6781void AudioPolicyManager::closeInput(audio_io_handle_t input)
6782{
6783 ALOGV("closeInput(%d)", input);
6784
6785 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
6786 if (inputDesc == NULL) {
6787 ALOGW("closeInput() unknown input %d", input);
6788 return;
6789 }
6790
Eric Laurent6a94d692014-05-20 11:18:06 -07006791 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07006792
François Gaffie11d30102018-11-02 16:09:09 +01006793 sp<DeviceDescriptor> device = inputDesc->getDevice();
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08006794 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07006795 if (index >= 0) {
6796 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006797 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
6798 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07006799 mAudioPatches.removeItemsAt(index);
6800 mpClientInterface->onAudioPatchListUpdate();
6801 }
6802
François Gaffie6ebbce02023-07-19 13:27:53 +02006803 mEffects.putOrphanEffectsForIo(input);
Eric Laurentfe231122017-11-17 17:48:06 -08006804 inputDesc->close();
Eric Laurent05b90f82014-08-27 15:32:29 -07006805 mInputs.removeItem(input);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07006806
François Gaffie11d30102018-11-02 16:09:09 +01006807 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
6808 if (primaryInputDevices.contains(device) &&
Haynes Mathew George1d539d92018-03-16 11:40:49 -07006809 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07006810 mpClientInterface->setSoundTriggerCaptureState(false);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07006811 }
Eric Laurente552edb2014-03-10 17:42:56 -07006812}
6813
François Gaffie11d30102018-11-02 16:09:09 +01006814SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevices(
6815 const DeviceVector &devices,
6816 const SwAudioOutputCollection& openOutputs)
Eric Laurente552edb2014-03-10 17:42:56 -07006817{
6818 SortedVector<audio_io_handle_t> outputs;
6819
François Gaffie11d30102018-11-02 16:09:09 +01006820 ALOGVV("%s() devices %s", __func__, devices.toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07006821 for (size_t i = 0; i < openOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01006822 ALOGVV("output %zu isDuplicated=%d device=%s",
Eric Laurent8c7e6da2015-04-21 17:37:00 -07006823 i, openOutputs.valueAt(i)->isDuplicated(),
François Gaffie11d30102018-11-02 16:09:09 +01006824 openOutputs.valueAt(i)->supportedDevices().toString().c_str());
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006825 if (openOutputs.valueAt(i)->supportsAllDevices(devices)
jiabin9a3361e2019-10-01 09:38:30 -07006826 && openOutputs.valueAt(i)->devicesSupportEncodedFormats(devices.types())) {
François Gaffie11d30102018-11-02 16:09:09 +01006827 ALOGVV("%s() found output %d", __func__, openOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07006828 outputs.add(openOutputs.keyAt(i));
6829 }
6830 }
6831 return outputs;
6832}
6833
Mikhail Naganov37977152018-07-11 15:54:44 -07006834void AudioPolicyManager::checkForDeviceAndOutputChanges(std::function<bool()> onOutputsChecked)
6835{
6836 // checkA2dpSuspend must run before checkOutputForAllStrategies so that A2DP
6837 // output is suspended before any tracks are moved to it
6838 checkA2dpSuspend();
6839 checkOutputForAllStrategies();
Kevin Rocard153f92d2018-12-18 18:33:28 -08006840 checkSecondaryOutputs();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11006841 if (onOutputsChecked != nullptr && onOutputsChecked()) checkA2dpSuspend();
Mikhail Naganov37977152018-07-11 15:54:44 -07006842 updateDevicesAndOutputs();
Mikhail Naganov7bd9b8d2018-11-15 02:09:03 +00006843 if (mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD) != 0) {
Michael Chan6fb34492020-12-08 15:44:49 +11006844 // TODO: The MSD patches to be established here may differ to current MSD patches due to how
6845 // output devices for patching are resolved. Nevertheless, AudioTracks affected by device
6846 // configuration changes will ultimately be rerouted correctly. We can still avoid
6847 // unnecessary rerouting by caching and reusing the arguments to
6848 // mEngine->getOutputDevicesForAttributes() when resolving which output devices to patch to.
6849 // This may be complicated by the fact that devices may become unavailable.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11006850 setMsdOutputPatches();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11006851 }
Jean-Michel Trivi9a6b9ad2020-10-22 16:46:43 -07006852 // an event that changed routing likely occurred, inform upper layers
6853 mpClientInterface->onRoutingUpdated();
Mikhail Naganov37977152018-07-11 15:54:44 -07006854}
6855
François Gaffiec005e562018-11-06 15:04:49 +01006856bool AudioPolicyManager::followsSameRouting(const audio_attributes_t &lAttr,
6857 const audio_attributes_t &rAttr) const
Eric Laurente552edb2014-03-10 17:42:56 -07006858{
François Gaffiec005e562018-11-06 15:04:49 +01006859 return mEngine->getProductStrategyForAttributes(lAttr) ==
6860 mEngine->getProductStrategyForAttributes(rAttr);
6861}
6862
Francois Gaffieff1eb522020-05-06 18:37:04 +02006863void AudioPolicyManager::checkAudioSourceForAttributes(const audio_attributes_t &attr)
6864{
6865 for (size_t i = 0; i < mAudioSources.size(); i++) {
6866 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
6867 if (sourceDesc != nullptr && followsSameRouting(attr, sourceDesc->attributes())
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02006868 && sourceDesc->getPatchHandle() == AUDIO_PATCH_HANDLE_NONE
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02006869 && !isCallRxAudioSource(sourceDesc) && !sourceDesc->isInternal()) {
Francois Gaffieff1eb522020-05-06 18:37:04 +02006870 connectAudioSource(sourceDesc);
6871 }
6872 }
6873}
6874
6875void AudioPolicyManager::clearAudioSourcesForOutput(audio_io_handle_t output)
6876{
6877 for (size_t i = 0; i < mAudioSources.size(); i++) {
6878 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
6879 if (sourceDesc != nullptr && sourceDesc->swOutput().promote() != nullptr
6880 && sourceDesc->swOutput().promote()->mIoHandle == output) {
6881 disconnectAudioSource(sourceDesc);
6882 }
6883 }
6884}
6885
François Gaffiec005e562018-11-06 15:04:49 +01006886void AudioPolicyManager::checkOutputForAttributes(const audio_attributes_t &attr)
6887{
6888 auto psId = mEngine->getProductStrategyForAttributes(attr);
6889
6890 DeviceVector oldDevices = mEngine->getOutputDevicesForAttributes(attr, 0, true /*fromCache*/);
6891 DeviceVector newDevices = mEngine->getOutputDevicesForAttributes(attr, 0, false /*fromCache*/);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07006892
François Gaffie11d30102018-11-02 16:09:09 +01006893 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevices(oldDevices, mPreviousOutputs);
6894 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevices(newDevices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07006895
Eric Laurentc209fe42020-06-05 18:11:23 -07006896 uint32_t maxLatency = 0;
Oscar Azucena873d10f2023-01-12 18:34:42 -08006897 bool unneededUsePrimaryOutputFromPolicyMixes = false;
Eric Laurent56ed8842022-11-15 16:04:41 +01006898 std::vector<sp<SwAudioOutputDescriptor>> invalidatedOutputs;
Eric Laurentc209fe42020-06-05 18:11:23 -07006899 // take into account dynamic audio policies related changes: if a client is now associated
6900 // to a different policy mix than at creation time, invalidate corresponding stream
Eric Laurent56ed8842022-11-15 16:04:41 +01006901 for (size_t i = 0; i < mPreviousOutputs.size(); i++) {
Eric Laurentc209fe42020-06-05 18:11:23 -07006902 const sp<SwAudioOutputDescriptor>& desc = mPreviousOutputs.valueAt(i);
6903 if (desc->isDuplicated()) {
6904 continue;
Jean-Michel Trivife472e22014-12-16 14:23:13 -08006905 }
Eric Laurentc209fe42020-06-05 18:11:23 -07006906 for (const sp<TrackClientDescriptor>& client : desc->getClientIterable()) {
6907 if (mEngine->getProductStrategyForAttributes(client->attributes()) != psId) {
6908 continue;
6909 }
6910 sp<AudioPolicyMix> primaryMix;
Dean Wheatleyd082f472022-02-04 11:10:48 +11006911 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->config(),
Oscar Azucena873d10f2023-01-12 18:34:42 -08006912 client->uid(), client->session(), client->flags(), mAvailableOutputDevices,
6913 nullptr /* requestedDevice */, primaryMix, nullptr /* secondaryMixes */,
6914 unneededUsePrimaryOutputFromPolicyMixes);
Eric Laurentc209fe42020-06-05 18:11:23 -07006915 if (status != OK) {
6916 continue;
6917 }
yucliuf4de36d2020-09-14 14:57:56 -07006918 if (client->getPrimaryMix() != primaryMix || client->hasLostPrimaryMix()) {
Eric Laurent56ed8842022-11-15 16:04:41 +01006919 if (desc->isStrategyActive(psId) && maxLatency < desc->latency()) {
Eric Laurentc209fe42020-06-05 18:11:23 -07006920 maxLatency = desc->latency();
6921 }
Eric Laurent56ed8842022-11-15 16:04:41 +01006922 invalidatedOutputs.push_back(desc);
Eric Laurentc209fe42020-06-05 18:11:23 -07006923 }
Jean-Michel Trivife472e22014-12-16 14:23:13 -08006924 }
6925 }
6926
Eric Laurent56ed8842022-11-15 16:04:41 +01006927 if (srcOutputs != dstOutputs || !invalidatedOutputs.empty()) {
Eric Laurentac3a6902018-05-11 16:39:10 -07006928 // get maximum latency of all source outputs to determine the minimum mute time guaranteeing
6929 // audio from invalidated tracks will be rendered when unmuting
Eric Laurentac3a6902018-05-11 16:39:10 -07006930 for (audio_io_handle_t srcOut : srcOutputs) {
6931 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
Eric Laurentaa02db82019-09-05 17:31:49 -07006932 if (desc == nullptr) continue;
6933
6934 if (desc->isStrategyActive(psId) && maxLatency < desc->latency()) {
Eric Laurentac3a6902018-05-11 16:39:10 -07006935 maxLatency = desc->latency();
6936 }
Eric Laurentaa02db82019-09-05 17:31:49 -07006937
Eric Laurent56ed8842022-11-15 16:04:41 +01006938 bool invalidate = false;
Eric Laurentaa02db82019-09-05 17:31:49 -07006939 for (auto client : desc->clientsList(false /*activeOnly*/)) {
Eric Laurent78aade82019-09-13 18:55:08 -07006940 if (desc->isDuplicated() || !desc->mProfile->isDirectOutput()) {
Eric Laurentaa02db82019-09-05 17:31:49 -07006941 // a client on a non direct outputs has necessarily a linear PCM format
6942 // so we can call selectOutput() safely
6943 const audio_io_handle_t newOutput = selectOutput(dstOutputs,
6944 client->flags(),
6945 client->config().format,
6946 client->config().channel_mask,
jiabinebb6af42020-06-09 17:31:17 -07006947 client->config().sample_rate,
6948 client->session());
Eric Laurentaa02db82019-09-05 17:31:49 -07006949 if (newOutput != srcOut) {
6950 invalidate = true;
6951 break;
6952 }
6953 } else {
6954 sp<IOProfile> profile = getProfileForOutput(newDevices,
6955 client->config().sample_rate,
6956 client->config().format,
6957 client->config().channel_mask,
6958 client->flags(),
6959 true /* directOnly */);
6960 if (profile != desc->mProfile) {
6961 invalidate = true;
6962 break;
6963 }
6964 }
6965 }
Eric Laurent56ed8842022-11-15 16:04:41 +01006966 // mute strategy while moving tracks from one output to another
6967 if (invalidate) {
6968 invalidatedOutputs.push_back(desc);
6969 if (desc->isStrategyActive(psId)) {
6970 setStrategyMute(psId, true, desc);
6971 setStrategyMute(psId, false, desc, maxLatency * LATENCY_MUTE_FACTOR,
6972 newDevices.types());
6973 }
Eric Laurente552edb2014-03-10 17:42:56 -07006974 }
François Gaffiec005e562018-11-06 15:04:49 +01006975 sp<SourceClientDescriptor> source = getSourceForAttributesOnOutput(srcOut, attr);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02006976 if (source != nullptr && !isCallRxAudioSource(source) && !source->isInternal()) {
Eric Laurentd60560a2015-04-10 11:31:20 -07006977 connectAudioSource(source);
6978 }
Eric Laurente552edb2014-03-10 17:42:56 -07006979 }
6980
Eric Laurent56ed8842022-11-15 16:04:41 +01006981 ALOGV_IF(!(srcOutputs.isEmpty() || dstOutputs.isEmpty()),
6982 "%s: strategy %d, moving from output %s to output %s", __func__, psId,
6983 std::to_string(srcOutputs[0]).c_str(),
6984 std::to_string(dstOutputs[0]).c_str());
6985
François Gaffiec005e562018-11-06 15:04:49 +01006986 // Move effects associated to this stream from previous output to new output
6987 if (followsSameRouting(attr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07006988 selectOutputForMusicEffects();
Eric Laurente552edb2014-03-10 17:42:56 -07006989 }
François Gaffiec005e562018-11-06 15:04:49 +01006990 // Move tracks associated to this stream (and linked) from previous output to new output
Eric Laurent56ed8842022-11-15 16:04:41 +01006991 if (!invalidatedOutputs.empty()) {
jiabinc44b3462022-12-08 12:52:31 -08006992 invalidateStreams(mEngine->getStreamTypesForProductStrategy(psId));
Eric Laurent56ed8842022-11-15 16:04:41 +01006993 for (sp<SwAudioOutputDescriptor> desc : invalidatedOutputs) {
jiabin49256852022-03-09 11:21:35 -08006994 desc->setTracksInvalidatedStatusByStrategy(psId);
6995 }
Eric Laurente552edb2014-03-10 17:42:56 -07006996 }
6997 }
6998}
6999
Eric Laurente0720872014-03-11 09:30:41 -07007000void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07007001{
François Gaffiec005e562018-11-06 15:04:49 +01007002 for (const auto &strategy : mEngine->getOrderedProductStrategies()) {
7003 auto attributes = mEngine->getAllAttributesForProductStrategy(strategy).front();
7004 checkOutputForAttributes(attributes);
Francois Gaffieff1eb522020-05-06 18:37:04 +02007005 checkAudioSourceForAttributes(attributes);
François Gaffiec005e562018-11-06 15:04:49 +01007006 }
Eric Laurente552edb2014-03-10 17:42:56 -07007007}
7008
Kevin Rocard153f92d2018-12-18 18:33:28 -08007009void AudioPolicyManager::checkSecondaryOutputs() {
jiabinc44b3462022-12-08 12:52:31 -08007010 PortHandleVector clientsToInvalidate;
jiabin10a03f12021-05-07 23:46:28 +00007011 TrackSecondaryOutputsMap trackSecondaryOutputs;
Oscar Azucena873d10f2023-01-12 18:34:42 -08007012 bool unneededUsePrimaryOutputFromPolicyMixes = false;
Kevin Rocard153f92d2018-12-18 18:33:28 -08007013 for (size_t i = 0; i < mOutputs.size(); i++) {
7014 const sp<SwAudioOutputDescriptor>& outputDescriptor = mOutputs[i];
7015 for (const sp<TrackClientDescriptor>& client : outputDescriptor->getClientIterable()) {
Eric Laurentc529cf62020-04-17 18:19:10 -07007016 sp<AudioPolicyMix> primaryMix;
7017 std::vector<sp<AudioPolicyMix>> secondaryMixes;
Dean Wheatleyd082f472022-02-04 11:10:48 +11007018 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->config(),
Oscar Azucena873d10f2023-01-12 18:34:42 -08007019 client->uid(), client->session(), client->flags(), mAvailableOutputDevices,
7020 nullptr /* requestedDevice */, primaryMix, &secondaryMixes,
7021 unneededUsePrimaryOutputFromPolicyMixes);
Eric Laurentc529cf62020-04-17 18:19:10 -07007022 std::vector<sp<SwAudioOutputDescriptor>> secondaryDescs;
7023 for (auto &secondaryMix : secondaryMixes) {
7024 sp<SwAudioOutputDescriptor> outputDesc = secondaryMix->getOutput();
7025 if (outputDesc != nullptr &&
7026 outputDesc->mIoHandle != AUDIO_IO_HANDLE_NONE) {
7027 secondaryDescs.push_back(outputDesc);
7028 }
7029 }
7030
jiabinc44b3462022-12-08 12:52:31 -08007031 if (status != OK &&
7032 (client->flags() & AUDIO_OUTPUT_FLAG_MMAP_NOIRQ) == AUDIO_OUTPUT_FLAG_NONE) {
7033 // When it failed to query secondary output, only invalidate the client that is not
7034 // MMAP. The reason is that MMAP stream will not support secondary output.
7035 clientsToInvalidate.push_back(client->portId());
jiabin10a03f12021-05-07 23:46:28 +00007036 } else if (!std::equal(
7037 client->getSecondaryOutputs().begin(),
7038 client->getSecondaryOutputs().end(),
7039 secondaryDescs.begin(), secondaryDescs.end())) {
jiabina5281062021-11-23 00:10:23 +00007040 if (!audio_is_linear_pcm(client->config().format)) {
7041 // If the format is not PCM, the tracks should be invalidated to get correct
7042 // behavior when the secondary output is changed.
jiabinc44b3462022-12-08 12:52:31 -08007043 clientsToInvalidate.push_back(client->portId());
jiabina5281062021-11-23 00:10:23 +00007044 } else {
7045 std::vector<wp<SwAudioOutputDescriptor>> weakSecondaryDescs;
7046 std::vector<audio_io_handle_t> secondaryOutputIds;
7047 for (const auto &secondaryDesc: secondaryDescs) {
7048 secondaryOutputIds.push_back(secondaryDesc->mIoHandle);
7049 weakSecondaryDescs.push_back(secondaryDesc);
7050 }
7051 trackSecondaryOutputs.emplace(client->portId(), secondaryOutputIds);
7052 client->setSecondaryOutputs(std::move(weakSecondaryDescs));
jiabin10a03f12021-05-07 23:46:28 +00007053 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08007054 }
7055 }
7056 }
jiabin10a03f12021-05-07 23:46:28 +00007057 if (!trackSecondaryOutputs.empty()) {
7058 mpClientInterface->updateSecondaryOutputs(trackSecondaryOutputs);
7059 }
jiabinc44b3462022-12-08 12:52:31 -08007060 if (!clientsToInvalidate.empty()) {
7061 ALOGD("%s Invalidate clients due to fail getting output for attr", __func__);
7062 mpClientInterface->invalidateTracks(clientsToInvalidate);
Kevin Rocard153f92d2018-12-18 18:33:28 -08007063 }
7064}
7065
Eric Laurent2517af32020-11-25 15:31:27 +01007066bool AudioPolicyManager::isScoRequestedForComm() const {
7067 AudioDeviceTypeAddrVector devices;
7068 mEngine->getDevicesForRoleAndStrategy(mCommunnicationStrategy, DEVICE_ROLE_PREFERRED, devices);
7069 for (const auto &device : devices) {
7070 if (audio_is_bluetooth_out_sco_device(device.mType)) {
7071 return true;
7072 }
7073 }
7074 return false;
7075}
7076
Eric Laurent1a8b45f2022-04-13 16:01:47 +02007077bool AudioPolicyManager::isHearingAidUsedForComm() const {
7078 DeviceVector devices = mEngine->getOutputDevicesForStream(AUDIO_STREAM_VOICE_CALL,
7079 true /*fromCache*/);
7080 for (const auto &device : devices) {
7081 if (device->type() == AUDIO_DEVICE_OUT_HEARING_AID) {
7082 return true;
7083 }
7084 }
7085 return false;
7086}
7087
7088
Eric Laurente0720872014-03-11 09:30:41 -07007089void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07007090{
François Gaffie53615e22015-03-19 09:24:12 +01007091 audio_io_handle_t a2dpOutput = mOutputs.getA2dpOutput();
Aniket Kumar Lataa8ee9962018-01-31 20:24:23 -08007092 if (a2dpOutput == 0 || mOutputs.isA2dpOffloadedOnPrimary()) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07007093 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07007094 return;
7095 }
7096
Eric Laurent3a4311c2014-03-17 12:00:47 -07007097 bool isScoConnected =
jiabin9a3361e2019-10-01 09:38:30 -07007098 (mAvailableInputDevices.types().count(AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) != 0 ||
7099 !Intersection(mAvailableOutputDevices.types(), getAudioDeviceOutAllScoSet()).empty());
Eric Laurent2517af32020-11-25 15:31:27 +01007100 bool isScoRequested = isScoRequestedForComm();
Eric Laurentf732e072016-08-03 19:30:28 -07007101
7102 // if suspended, restore A2DP output if:
7103 // ((SCO device is NOT connected) ||
Eric Laurent2517af32020-11-25 15:31:27 +01007104 // ((SCO is not requested) &&
Eric Laurentf732e072016-08-03 19:30:28 -07007105 // (phone state is NOT in call) && (phone state is NOT ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07007106 //
Eric Laurentf732e072016-08-03 19:30:28 -07007107 // if not suspended, suspend A2DP output if:
7108 // (SCO device is connected) &&
Eric Laurent2517af32020-11-25 15:31:27 +01007109 // ((SCO is requested) ||
Eric Laurentf732e072016-08-03 19:30:28 -07007110 // ((phone state is in call) || (phone state is ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07007111 //
7112 if (mA2dpSuspended) {
Eric Laurentf732e072016-08-03 19:30:28 -07007113 if (!isScoConnected ||
Eric Laurent2517af32020-11-25 15:31:27 +01007114 (!isScoRequested &&
Eric Laurentf732e072016-08-03 19:30:28 -07007115 (mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) &&
François Gaffie2110e042015-03-24 08:41:51 +01007116 (mEngine->getPhoneState() != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07007117
7118 mpClientInterface->restoreOutput(a2dpOutput);
7119 mA2dpSuspended = false;
7120 }
7121 } else {
Eric Laurentf732e072016-08-03 19:30:28 -07007122 if (isScoConnected &&
Eric Laurent2517af32020-11-25 15:31:27 +01007123 (isScoRequested ||
Eric Laurentf732e072016-08-03 19:30:28 -07007124 (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) ||
François Gaffie2110e042015-03-24 08:41:51 +01007125 (mEngine->getPhoneState() == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07007126
7127 mpClientInterface->suspendOutput(a2dpOutput);
7128 mA2dpSuspended = true;
7129 }
7130 }
7131}
7132
François Gaffie11d30102018-11-02 16:09:09 +01007133DeviceVector AudioPolicyManager::getNewOutputDevices(const sp<SwAudioOutputDescriptor>& outputDesc,
7134 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07007135{
François Gaffiedb1755b2023-09-01 11:50:35 +02007136 if (outputDesc == nullptr) {
7137 return DeviceVector{};
7138 }
François Gaffie11d30102018-11-02 16:09:09 +01007139
Jean-Michel Triviff155c62016-02-26 12:07:16 -08007140 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007141 if (index >= 0) {
7142 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007143 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01007144 ALOGV("%s device %s forced by patch %d", __func__,
7145 outputDesc->devices().toString().c_str(), outputDesc->getPatchHandle());
7146 return outputDesc->devices();
Eric Laurent6a94d692014-05-20 11:18:06 -07007147 }
7148 }
7149
Dean Wheatley514b4312020-06-17 21:45:00 +10007150 // Do not retrieve engine device for outputs through MSD
7151 // TODO: support explicit routing requests by resetting MSD patch to engine device.
7152 if (outputDesc->devices() == getMsdAudioOutDevices()) {
7153 return outputDesc->devices();
7154 }
7155
Eric Laurent97ac8712018-07-27 18:59:02 -07007156 // Honor explicit routing requests only if no client using default routing is active on this
7157 // input: a specific app can not force routing for other apps by setting a preferred device.
7158 bool active; // unused
François Gaffie11d30102018-11-02 16:09:09 +01007159 sp<DeviceDescriptor> device =
François Gaffiec005e562018-11-06 15:04:49 +01007160 findPreferredDevice(outputDesc, PRODUCT_STRATEGY_NONE, active, mAvailableOutputDevices);
François Gaffie11d30102018-11-02 16:09:09 +01007161 if (device != nullptr) {
7162 return DeviceVector(device);
Eric Laurentf3a5a602018-05-22 18:42:55 -07007163 }
7164
François Gaffiea807ef92018-11-05 10:44:33 +01007165 // Legacy Engine cannot take care of bus devices and mix, so we need to handle the conflict
7166 // of setForceUse / Default Bus device here
7167 device = mPolicyMixes.getDeviceAndMixForOutput(outputDesc, mAvailableOutputDevices);
7168 if (device != nullptr) {
7169 return DeviceVector(device);
7170 }
7171
François Gaffiedb1755b2023-09-01 11:50:35 +02007172 DeviceVector devices;
François Gaffiec005e562018-11-06 15:04:49 +01007173 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
7174 StreamTypeVector streams = mEngine->getStreamTypesForProductStrategy(productStrategy);
7175 auto attr = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307176 auto hasStreamActive = [&](auto stream) {
7177 return hasStream(streams, stream) && isStreamActive(stream, 0);
7178 };
Eric Laurent484e9272018-06-07 17:29:23 -07007179
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307180 auto doGetOutputDevicesForVoice = [&]() {
7181 return hasVoiceStream(streams) && (outputDesc == mPrimaryOutput ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007182 outputDesc->isActive(toVolumeSource(AUDIO_STREAM_VOICE_CALL, false))) &&
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307183 (isInCall() ||
Henrik Backlund07c654a2021-10-14 15:57:10 +02007184 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc)) &&
7185 !isStreamActive(AUDIO_STREAM_ENFORCED_AUDIBLE, 0);
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307186 };
7187
7188 // With low-latency playing on speaker, music on WFD, when the first low-latency
7189 // output is stopped, getNewOutputDevices checks for a product strategy
7190 // from the list, as STRATEGY_SONIFICATION comes prior to STRATEGY_MEDIA.
Carter Hsucc58a6b2021-07-20 08:44:50 +00007191 // If an ALARM or ENFORCED_AUDIBLE stream is supported by the product strategy,
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307192 // devices are returned for STRATEGY_SONIFICATION without checking whether the
7193 // stream is associated to the output descriptor.
7194 if (doGetOutputDevicesForVoice() || outputDesc->isStrategyActive(productStrategy) ||
7195 ((hasStreamActive(AUDIO_STREAM_ALARM) ||
7196 hasStreamActive(AUDIO_STREAM_ENFORCED_AUDIBLE)) &&
7197 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc))) {
François Gaffiec005e562018-11-06 15:04:49 +01007198 // Retrieval of devices for voice DL is done on primary output profile, cannot
7199 // check the route (would force modifying configuration file for this profile)
7200 devices = mEngine->getOutputDevicesForAttributes(attr, nullptr, fromCache);
7201 break;
7202 }
Eric Laurente552edb2014-03-10 17:42:56 -07007203 }
François Gaffiec005e562018-11-06 15:04:49 +01007204 ALOGV("%s selected devices %s", __func__, devices.toString().c_str());
François Gaffie11d30102018-11-02 16:09:09 +01007205 return devices;
Eric Laurent1c333e22014-05-20 10:48:17 -07007206}
7207
François Gaffie11d30102018-11-02 16:09:09 +01007208sp<DeviceDescriptor> AudioPolicyManager::getNewInputDevice(
7209 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurent1c333e22014-05-20 10:48:17 -07007210{
François Gaffie11d30102018-11-02 16:09:09 +01007211 sp<DeviceDescriptor> device;
Eric Laurent6a94d692014-05-20 11:18:06 -07007212
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08007213 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007214 if (index >= 0) {
7215 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007216 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01007217 ALOGV("getNewInputDevice() device %s forced by patch %d",
7218 inputDesc->getDevice()->toString().c_str(), inputDesc->getPatchHandle());
7219 return inputDesc->getDevice();
Eric Laurent6a94d692014-05-20 11:18:06 -07007220 }
7221 }
7222
Eric Laurent97ac8712018-07-27 18:59:02 -07007223 // Honor explicit routing requests only if no client using default routing is active on this
7224 // input: a specific app can not force routing for other apps by setting a preferred device.
7225 bool active;
François Gaffie11d30102018-11-02 16:09:09 +01007226 device = findPreferredDevice(inputDesc, AUDIO_SOURCE_DEFAULT, active, mAvailableInputDevices);
7227 if (device != nullptr) {
7228 return device;
Eric Laurent97ac8712018-07-27 18:59:02 -07007229 }
7230
Eric Laurentdc95a252018-04-12 12:46:56 -07007231 // If we are not in call and no client is active on this input, this methods returns
Andy Hungf024a9e2019-01-30 16:01:02 -08007232 // a null sp<>, causing the patch on the input stream to be released.
yuanjiahsu0735bf32021-03-18 08:12:54 +08007233 audio_attributes_t attributes;
7234 uid_t uid;
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007235 audio_session_t session;
yuanjiahsu0735bf32021-03-18 08:12:54 +08007236 sp<RecordClientDescriptor> topClient = inputDesc->getHighestPriorityClient();
7237 if (topClient != nullptr) {
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01007238 attributes = topClient->attributes();
7239 uid = topClient->uid();
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007240 session = topClient->session();
yuanjiahsu0735bf32021-03-18 08:12:54 +08007241 } else {
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01007242 attributes = { .source = AUDIO_SOURCE_DEFAULT };
7243 uid = 0;
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007244 session = AUDIO_SESSION_NONE;
yuanjiahsu0735bf32021-03-18 08:12:54 +08007245 }
7246
Francois Gaffie716e1432019-01-14 16:58:59 +01007247 if (attributes.source == AUDIO_SOURCE_DEFAULT && isInCall()) {
7248 attributes.source = AUDIO_SOURCE_VOICE_COMMUNICATION;
Eric Laurentdc95a252018-04-12 12:46:56 -07007249 }
Francois Gaffie716e1432019-01-14 16:58:59 +01007250 if (attributes.source != AUDIO_SOURCE_DEFAULT) {
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007251 device = mEngine->getInputDeviceForAttributes(attributes, uid, session);
Eric Laurentfb66dd92016-01-28 18:32:03 -08007252 }
Eric Laurent1c333e22014-05-20 10:48:17 -07007253
Eric Laurente552edb2014-03-10 17:42:56 -07007254 return device;
7255}
7256
Eric Laurent794fde22016-03-11 09:50:45 -08007257bool AudioPolicyManager::streamsMatchForvolume(audio_stream_type_t stream1,
7258 audio_stream_type_t stream2) {
Jean-Michel Trivi99bb2f92016-11-23 15:52:07 -08007259 return (stream1 == stream2);
Eric Laurent28d09f02016-03-08 10:43:05 -08007260}
7261
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08007262status_t AudioPolicyManager::getDevicesForAttributes(
Andy Hung6d23c0f2022-02-16 09:37:15 -08007263 const audio_attributes_t &attr, AudioDeviceTypeAddrVector *devices, bool forVolume) {
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08007264 if (devices == nullptr) {
7265 return BAD_VALUE;
7266 }
Andy Hung6d23c0f2022-02-16 09:37:15 -08007267
Andy Hung6d23c0f2022-02-16 09:37:15 -08007268 DeviceVector curDevices;
jiabinf1c73972022-04-14 16:28:52 -07007269 if (status_t status = getDevicesForAttributes(attr, curDevices, forVolume); status != OK) {
7270 return status;
Andy Hung6d23c0f2022-02-16 09:37:15 -08007271 }
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08007272 for (const auto& device : curDevices) {
7273 devices->push_back(device->getDeviceTypeAddr());
7274 }
7275 return NO_ERROR;
7276}
7277
Eric Laurente0720872014-03-11 09:30:41 -07007278void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07007279 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07007280 case AUDIO_STREAM_MUSIC:
François Gaffiec005e562018-11-06 15:04:49 +01007281 checkOutputForAttributes(attributes_initializer(AUDIO_USAGE_NOTIFICATION));
Eric Laurente552edb2014-03-10 17:42:56 -07007282 updateDevicesAndOutputs();
7283 break;
7284 default:
7285 break;
7286 }
7287}
7288
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007289uint32_t AudioPolicyManager::handleEventForBeacon(int event) {
Eric Laurent9459fb02015-08-12 18:36:32 -07007290
7291 // skip beacon mute management if a dedicated TTS output is available
7292 if (mTtsOutputAvailable) {
7293 return 0;
7294 }
7295
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007296 switch(event) {
7297 case STARTING_OUTPUT:
7298 mBeaconMuteRefCount++;
7299 break;
7300 case STOPPING_OUTPUT:
7301 if (mBeaconMuteRefCount > 0) {
7302 mBeaconMuteRefCount--;
7303 }
7304 break;
7305 case STARTING_BEACON:
7306 mBeaconPlayingRefCount++;
7307 break;
7308 case STOPPING_BEACON:
7309 if (mBeaconPlayingRefCount > 0) {
7310 mBeaconPlayingRefCount--;
7311 }
7312 break;
7313 }
7314
7315 if (mBeaconMuteRefCount > 0) {
7316 // any playback causes beacon to be muted
7317 return setBeaconMute(true);
7318 } else {
7319 // no other playback: unmute when beacon starts playing, mute when it stops
7320 return setBeaconMute(mBeaconPlayingRefCount == 0);
7321 }
7322}
7323
7324uint32_t AudioPolicyManager::setBeaconMute(bool mute) {
7325 ALOGV("setBeaconMute(%d) mBeaconMuteRefCount=%d mBeaconPlayingRefCount=%d",
7326 mute, mBeaconMuteRefCount, mBeaconPlayingRefCount);
7327 // keep track of muted state to avoid repeating mute/unmute operations
7328 if (mBeaconMuted != mute) {
7329 // mute/unmute AUDIO_STREAM_TTS on all outputs
7330 ALOGV("\t muting %d", mute);
7331 uint32_t maxLatency = 0;
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007332 auto ttsVolumeSource = toVolumeSource(AUDIO_STREAM_TTS, false);
7333 if (ttsVolumeSource == VOLUME_SOURCE_NONE) {
7334 ALOGV("\t no tts volume source available");
7335 return 0;
7336 }
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007337 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07007338 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
jiabin9a3361e2019-10-01 09:38:30 -07007339 setVolumeSourceMute(ttsVolumeSource, mute/*on*/, desc, 0 /*delay*/, DeviceTypeSet());
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007340 const uint32_t latency = desc->latency() * 2;
Eric Laurentcdb2b352020-07-23 10:57:02 -07007341 if (desc->isActive(latency * 2) && latency > maxLatency) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007342 maxLatency = latency;
7343 }
7344 }
7345 mBeaconMuted = mute;
7346 return maxLatency;
7347 }
7348 return 0;
7349}
7350
Eric Laurente0720872014-03-11 09:30:41 -07007351void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07007352{
François Gaffiec005e562018-11-06 15:04:49 +01007353 mEngine->updateDeviceSelectionCache();
Eric Laurente552edb2014-03-10 17:42:56 -07007354 mPreviousOutputs = mOutputs;
7355}
7356
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07007357uint32_t AudioPolicyManager::checkDeviceMuteStrategies(const sp<AudioOutputDescriptor>& outputDesc,
François Gaffiec005e562018-11-06 15:04:49 +01007358 const DeviceVector &prevDevices,
Eric Laurente552edb2014-03-10 17:42:56 -07007359 uint32_t delayMs)
7360{
7361 // mute/unmute strategies using an incompatible device combination
7362 // if muting, wait for the audio in pcm buffer to be drained before proceeding
7363 // if unmuting, unmute only after the specified delay
7364 if (outputDesc->isDuplicated()) {
7365 return 0;
7366 }
7367
7368 uint32_t muteWaitMs = 0;
François Gaffiec005e562018-11-06 15:04:49 +01007369 DeviceVector devices = outputDesc->devices();
7370 bool shouldMute = outputDesc->isActive() && (devices.size() >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07007371
François Gaffiec005e562018-11-06 15:04:49 +01007372 auto productStrategies = mEngine->getOrderedProductStrategies();
7373 for (const auto &productStrategy : productStrategies) {
7374 auto attributes = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
7375 DeviceVector curDevices =
7376 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false/*fromCache*/);
7377 curDevices = curDevices.filter(outputDesc->supportedDevices());
7378 bool mute = shouldMute && curDevices.containsAtLeastOne(devices) && curDevices != devices;
Eric Laurente552edb2014-03-10 17:42:56 -07007379 bool doMute = false;
7380
François Gaffiec005e562018-11-06 15:04:49 +01007381 if (mute && !outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07007382 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01007383 outputDesc->setStrategyMutedByDevice(productStrategy, true);
7384 } else if (!mute && outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07007385 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01007386 outputDesc->setStrategyMutedByDevice(productStrategy, false);
Eric Laurente552edb2014-03-10 17:42:56 -07007387 }
Eric Laurent99401132014-05-07 19:48:15 -07007388 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07007389 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07007390 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07007391 // skip output if it does not share any device with current output
François Gaffie11d30102018-11-02 16:09:09 +01007392 if (!desc->supportedDevices().containsAtLeastOne(outputDesc->supportedDevices())) {
Eric Laurente552edb2014-03-10 17:42:56 -07007393 continue;
7394 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307395 ALOGVV("%s() output %s %s (curDevice %s)", __func__, desc->info().c_str(),
François Gaffiec005e562018-11-06 15:04:49 +01007396 mute ? "muting" : "unmuting", curDevices.toString().c_str());
7397 setStrategyMute(productStrategy, mute, desc, mute ? 0 : delayMs);
7398 if (desc->isStrategyActive(productStrategy)) {
Eric Laurent99401132014-05-07 19:48:15 -07007399 if (mute) {
7400 // FIXME: should not need to double latency if volume could be applied
7401 // immediately by the audioflinger mixer. We must account for the delay
7402 // between now and the next time the audioflinger thread for this output
7403 // will process a buffer (which corresponds to one buffer size,
7404 // usually 1/2 or 1/4 of the latency).
7405 if (muteWaitMs < desc->latency() * 2) {
7406 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07007407 }
7408 }
7409 }
7410 }
7411 }
7412 }
7413
Eric Laurent99401132014-05-07 19:48:15 -07007414 // temporary mute output if device selection changes to avoid volume bursts due to
7415 // different per device volumes
François Gaffiec005e562018-11-06 15:04:49 +01007416 if (outputDesc->isActive() && (devices != prevDevices)) {
Eric Laurentdc462862016-07-19 12:29:53 -07007417 uint32_t tempMuteWaitMs = outputDesc->latency() * 2;
Jasmine Chaf6074fe2021-08-17 13:44:31 +08007418
Eric Laurentdc462862016-07-19 12:29:53 -07007419 if (muteWaitMs < tempMuteWaitMs) {
7420 muteWaitMs = tempMuteWaitMs;
Eric Laurent99401132014-05-07 19:48:15 -07007421 }
Jasmine Chaf6074fe2021-08-17 13:44:31 +08007422
7423 // If recommended duration is defined, replace temporary mute duration to avoid
7424 // truncated notifications at beginning, which depends on duration of changing path in HAL.
7425 // Otherwise, temporary mute duration is conservatively set to 4 times the reported latency.
7426 uint32_t tempRecommendedMuteDuration = outputDesc->getRecommendedMuteDurationMs();
7427 uint32_t tempMuteDurationMs = tempRecommendedMuteDuration > 0 ?
7428 tempRecommendedMuteDuration : outputDesc->latency() * 4;
7429
François Gaffieaaac0fd2018-11-22 17:56:39 +01007430 for (const auto &activeVs : outputDesc->getActiveVolumeSources()) {
7431 // make sure that we do not start the temporary mute period too early in case of
7432 // delayed device change
7433 setVolumeSourceMute(activeVs, true, outputDesc, delayMs);
7434 setVolumeSourceMute(activeVs, false, outputDesc, delayMs + tempMuteDurationMs,
François Gaffiec005e562018-11-06 15:04:49 +01007435 devices.types());
Eric Laurent99401132014-05-07 19:48:15 -07007436 }
7437 }
7438
Eric Laurente552edb2014-03-10 17:42:56 -07007439 // wait for the PCM output buffers to empty before proceeding with the rest of the command
7440 if (muteWaitMs > delayMs) {
7441 muteWaitMs -= delayMs;
7442 usleep(muteWaitMs * 1000);
7443 return muteWaitMs;
7444 }
7445 return 0;
7446}
7447
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307448uint32_t AudioPolicyManager::setOutputDevices(const char *caller,
7449 const sp<SwAudioOutputDescriptor>& outputDesc,
François Gaffie11d30102018-11-02 16:09:09 +01007450 const DeviceVector &devices,
7451 bool force,
7452 int delayMs,
7453 audio_patch_handle_t *patchHandle,
Oscar Azucena6acf34b2023-04-27 16:32:09 -07007454 bool requiresMuteCheck, bool requiresVolumeCheck,
7455 bool skipMuteDelay)
Eric Laurente552edb2014-03-10 17:42:56 -07007456{
jiabin3ff8d7d2022-12-13 06:27:44 +00007457 // TODO(b/262404095): Consider if the output need to be reopened.
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307458 std::string logPrefix = std::string("caller ") + caller + outputDesc->info();
7459 ALOGV("%s %s device %s delayMs %d", __func__, logPrefix.c_str(),
7460 devices.toString().c_str(), delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07007461 uint32_t muteWaitMs;
7462
7463 if (outputDesc->isDuplicated()) {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307464 muteWaitMs = setOutputDevices(__func__, outputDesc->subOutput1(), devices, force, delayMs,
Oscar Azucena6acf34b2023-04-27 16:32:09 -07007465 nullptr /* patchHandle */, requiresMuteCheck, skipMuteDelay);
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307466 muteWaitMs += setOutputDevices(__func__, outputDesc->subOutput2(), devices, force, delayMs,
Oscar Azucena6acf34b2023-04-27 16:32:09 -07007467 nullptr /* patchHandle */, requiresMuteCheck, skipMuteDelay);
Eric Laurente552edb2014-03-10 17:42:56 -07007468 return muteWaitMs;
7469 }
Eric Laurente552edb2014-03-10 17:42:56 -07007470
7471 // filter devices according to output selected
Francois Gaffie716e1432019-01-14 16:58:59 +01007472 DeviceVector filteredDevices = outputDesc->filterSupportedDevices(devices);
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01007473 DeviceVector prevDevices = outputDesc->devices();
Francois Gaffie3523ab32021-06-22 13:24:34 +02007474 DeviceVector availPrevDevices = mAvailableOutputDevices.filter(prevDevices);
Eric Laurente552edb2014-03-10 17:42:56 -07007475
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307476 ALOGV("%s %s prevDevice %s", __func__, logPrefix.c_str(),
7477 prevDevices.toString().c_str());
François Gaffie11d30102018-11-02 16:09:09 +01007478
7479 if (!filteredDevices.isEmpty()) {
7480 outputDesc->setDevices(filteredDevices);
Eric Laurente552edb2014-03-10 17:42:56 -07007481 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00007482
7483 // if the outputs are not materially active, there is no need to mute.
7484 if (requiresMuteCheck) {
François Gaffiec005e562018-11-06 15:04:49 +01007485 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevices, delayMs);
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00007486 } else {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307487 ALOGV("%s: %s suppressing checkDeviceMuteStrategies", __func__,
7488 logPrefix.c_str());
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00007489 muteWaitMs = 0;
7490 }
Eric Laurente552edb2014-03-10 17:42:56 -07007491
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02007492 bool outputRouted = outputDesc->isRouted();
7493
Eric Laurent79ea9582020-06-11 18:49:24 -07007494 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
7495 // output profile or if new device is not supported AND previous device(s) is(are) still
7496 // available (otherwise reset device must be done on the output)
Francois Gaffie3523ab32021-06-22 13:24:34 +02007497 if (!devices.isEmpty() && filteredDevices.isEmpty() && !availPrevDevices.empty()) {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307498 ALOGV("%s: %s unsupported device %s for output", __func__, logPrefix.c_str(),
7499 devices.toString().c_str());
Eric Laurent79ea9582020-06-11 18:49:24 -07007500 // restore previous device after evaluating strategy mute state
7501 outputDesc->setDevices(prevDevices);
7502 return muteWaitMs;
7503 }
7504
Eric Laurente552edb2014-03-10 17:42:56 -07007505 // Do not change the routing if:
Eric Laurentb80a2a82014-10-27 16:07:59 -07007506 // the requested device is AUDIO_DEVICE_NONE
7507 // OR the requested device is the same as current device
7508 // AND force is not specified
7509 // AND the output is connected by a valid audio patch.
François Gaffie11d30102018-11-02 16:09:09 +01007510 // Doing this check here allows the caller to call setOutputDevices() without conditions
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02007511 if ((filteredDevices.isEmpty() || filteredDevices == prevDevices) && !force && outputRouted) {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307512 ALOGV("%s %s setting same device %s or null device, force=%d, patch handle=%d",
7513 __func__, logPrefix.c_str(), filteredDevices.toString().c_str(), force,
7514 outputDesc->getPatchHandle());
Francois Gaffie3523ab32021-06-22 13:24:34 +02007515 if (requiresVolumeCheck && !filteredDevices.isEmpty()) {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307516 ALOGV("%s %s setting same device on routed output, force apply volumes",
7517 __func__, logPrefix.c_str());
Francois Gaffie3523ab32021-06-22 13:24:34 +02007518 applyStreamVolumes(outputDesc, filteredDevices.types(), delayMs, true /*force*/);
7519 }
Eric Laurente552edb2014-03-10 17:42:56 -07007520 return muteWaitMs;
7521 }
7522
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307523 ALOGV("%s %s changing device to %s", __func__, logPrefix.c_str(),
7524 filteredDevices.toString().c_str());
Eric Laurent1c333e22014-05-20 10:48:17 -07007525
Eric Laurente552edb2014-03-10 17:42:56 -07007526 // do the routing
Francois Gaffie3523ab32021-06-22 13:24:34 +02007527 if (filteredDevices.isEmpty() || mAvailableOutputDevices.filter(filteredDevices).empty()) {
Eric Laurentc75307b2015-03-17 15:29:32 -07007528 resetOutputDevice(outputDesc, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07007529 } else {
François Gaffie11d30102018-11-02 16:09:09 +01007530 PatchBuilder patchBuilder;
7531 patchBuilder.addSource(outputDesc);
7532 ALOG_ASSERT(filteredDevices.size() <= AUDIO_PATCH_PORTS_MAX, "Too many sink ports");
7533 for (const auto &filteredDevice : filteredDevices) {
7534 patchBuilder.addSink(filteredDevice);
Eric Laurentc40d9692016-04-13 19:14:13 -07007535 }
7536
Jasmine Cha7f82d1a2020-03-16 13:21:47 +08007537 // Add half reported latency to delayMs when muteWaitMs is null in order
7538 // to avoid disordered sequence of muting volume and changing devices.
Oscar Azucena6acf34b2023-04-27 16:32:09 -07007539 int actualDelayMs = !skipMuteDelay && muteWaitMs == 0
7540 ? (delayMs + (outputDesc->latency() / 2)) : delayMs;
7541 installPatch(__func__, patchHandle, outputDesc.get(), patchBuilder.patch(), actualDelayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07007542 }
Eric Laurente552edb2014-03-10 17:42:56 -07007543
Oscar Azucena6acf34b2023-04-27 16:32:09 -07007544 // Since the mute is skip, also skip the apply stream volume as that will be applied externally
7545 if (!skipMuteDelay) {
7546 // update stream volumes according to new device
7547 applyStreamVolumes(outputDesc, filteredDevices.types(), delayMs);
7548 }
Eric Laurente552edb2014-03-10 17:42:56 -07007549
7550 return muteWaitMs;
7551}
7552
Eric Laurentc75307b2015-03-17 15:29:32 -07007553status_t AudioPolicyManager::resetOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurent6a94d692014-05-20 11:18:06 -07007554 int delayMs,
7555 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07007556{
Eric Laurent6a94d692014-05-20 11:18:06 -07007557 ssize_t index;
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02007558 if (patchHandle == nullptr && !outputDesc->isRouted()) {
7559 return INVALID_OPERATION;
7560 }
Eric Laurent6a94d692014-05-20 11:18:06 -07007561 if (patchHandle) {
7562 index = mAudioPatches.indexOfKey(*patchHandle);
7563 } else {
Jean-Michel Triviff155c62016-02-26 12:07:16 -08007564 index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007565 }
7566 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07007567 return INVALID_OPERATION;
7568 }
Eric Laurent6a94d692014-05-20 11:18:06 -07007569 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007570 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07007571 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07007572 outputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
François Gaffieafd4cea2019-11-18 15:50:22 +01007573 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007574 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07007575 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07007576 return status;
7577}
7578
7579status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
François Gaffie11d30102018-11-02 16:09:09 +01007580 const sp<DeviceDescriptor> &device,
Eric Laurent6a94d692014-05-20 11:18:06 -07007581 bool force,
7582 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07007583{
7584 status_t status = NO_ERROR;
7585
Eric Laurent1f2f2232014-06-02 12:01:23 -07007586 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
François Gaffie11d30102018-11-02 16:09:09 +01007587 if ((device != nullptr) && ((device != inputDesc->getDevice()) || force)) {
7588 inputDesc->setDevice(device);
Eric Laurent1c333e22014-05-20 10:48:17 -07007589
François Gaffie11d30102018-11-02 16:09:09 +01007590 if (mAvailableInputDevices.contains(device)) {
Mikhail Naganovdc769682018-05-04 15:34:08 -07007591 PatchBuilder patchBuilder;
7592 patchBuilder.addSink(inputDesc,
Eric Laurentdaf92cc2014-07-22 15:36:10 -07007593 // AUDIO_SOURCE_HOTWORD is for internal use only:
7594 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
Mikhail Naganovdc769682018-05-04 15:34:08 -07007595 [inputDesc](const PatchBuilder::mix_usecase_t& usecase) {
7596 auto result = usecase;
7597 if (result.source == AUDIO_SOURCE_HOTWORD && !inputDesc->isSoundTrigger()) {
7598 result.source = AUDIO_SOURCE_VOICE_RECOGNITION;
7599 }
7600 return result; }).
Eric Laurent1c333e22014-05-20 10:48:17 -07007601 //only one input device for now
François Gaffie11d30102018-11-02 16:09:09 +01007602 addSource(device);
Mikhail Naganovdc769682018-05-04 15:34:08 -07007603 status = installPatch(__func__, patchHandle, inputDesc.get(), patchBuilder.patch(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07007604 }
7605 }
7606 return status;
7607}
7608
Eric Laurent6a94d692014-05-20 11:18:06 -07007609status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
7610 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07007611{
Eric Laurent1f2f2232014-06-02 12:01:23 -07007612 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07007613 ssize_t index;
7614 if (patchHandle) {
7615 index = mAudioPatches.indexOfKey(*patchHandle);
7616 } else {
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08007617 index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007618 }
7619 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07007620 return INVALID_OPERATION;
7621 }
Eric Laurent6a94d692014-05-20 11:18:06 -07007622 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007623 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07007624 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07007625 inputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
François Gaffieafd4cea2019-11-18 15:50:22 +01007626 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007627 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07007628 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07007629 return status;
7630}
7631
François Gaffie11d30102018-11-02 16:09:09 +01007632sp<IOProfile> AudioPolicyManager::getInputProfile(const sp<DeviceDescriptor> &device,
François Gaffie53615e22015-03-19 09:24:12 +01007633 uint32_t& samplingRate,
Andy Hungf129b032015-04-07 13:45:50 -07007634 audio_format_t& format,
7635 audio_channel_mask_t& channelMask,
François Gaffie53615e22015-03-19 09:24:12 +01007636 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07007637{
7638 // Choose an input profile based on the requested capture parameters: select the first available
7639 // profile supporting all requested parameters.
jiabin2fd710d2022-05-02 23:20:22 +00007640 // The flags can be ignored if it doesn't contain a much match flag.
Andy Hungf129b032015-04-07 13:45:50 -07007641 //
7642 // TODO: perhaps isCompatibleProfile should return a "matching" score so we can return
7643 // the best matching profile, not the first one.
Eric Laurente552edb2014-03-10 17:42:56 -07007644
Atneya Nair0f0a8032022-12-12 16:20:12 -08007645 using underlying_input_flag_t = std::underlying_type_t<audio_input_flags_t>;
7646 const underlying_input_flag_t mustMatchFlag = AUDIO_INPUT_FLAG_MMAP_NOIRQ |
7647 AUDIO_INPUT_FLAG_HOTWORD_TAP | AUDIO_INPUT_FLAG_HW_LOOKBACK;
7648
7649 const underlying_input_flag_t oriFlags = flags;
Glenn Kasten730b9262018-03-29 15:01:26 -07007650
jiabin2fd710d2022-05-02 23:20:22 +00007651 for (;;) {
7652 sp<IOProfile> firstInexact = nullptr;
7653 uint32_t updatedSamplingRate = 0;
7654 audio_format_t updatedFormat = AUDIO_FORMAT_INVALID;
7655 audio_channel_mask_t updatedChannelMask = AUDIO_CHANNEL_INVALID;
7656 for (const auto& hwModule : mHwModules) {
7657 for (const auto& profile : hwModule->getInputProfiles()) {
7658 // profile->log();
7659 //updatedFormat = format;
7660 if (profile->isCompatibleProfile(DeviceVector(device), samplingRate,
7661 &samplingRate /*updatedSamplingRate*/,
7662 format,
7663 &format, /*updatedFormat*/
7664 channelMask,
7665 &channelMask /*updatedChannelMask*/,
7666 // FIXME ugly cast
7667 (audio_output_flags_t) flags,
7668 true /*exactMatchRequiredForInputFlags*/)) {
7669 return profile;
7670 }
7671 if (firstInexact == nullptr && profile->isCompatibleProfile(DeviceVector(device),
7672 samplingRate,
7673 &updatedSamplingRate,
7674 format,
7675 &updatedFormat,
7676 channelMask,
7677 &updatedChannelMask,
7678 // FIXME ugly cast
7679 (audio_output_flags_t) flags,
7680 false /*exactMatchRequiredForInputFlags*/)) {
7681 firstInexact = profile;
7682 }
7683 }
7684 }
7685
7686 if (firstInexact != nullptr) {
7687 samplingRate = updatedSamplingRate;
7688 format = updatedFormat;
7689 channelMask = updatedChannelMask;
7690 return firstInexact;
7691 } else if (flags & AUDIO_INPUT_FLAG_RAW) {
7692 flags = (audio_input_flags_t) (flags & ~AUDIO_INPUT_FLAG_RAW); // retry
7693 } else if ((flags & mustMatchFlag) == AUDIO_INPUT_FLAG_NONE &&
7694 flags != AUDIO_INPUT_FLAG_NONE && audio_is_linear_pcm(format)) {
7695 flags = AUDIO_INPUT_FLAG_NONE;
7696 } else { // fail
7697 ALOGW("%s could not find profile for device %s, sampling rate %u, format %#x, "
7698 "channel mask 0x%X, flags %#x", __func__, device->toString().c_str(),
7699 samplingRate, format, channelMask, oriFlags);
7700 break;
Eric Laurente552edb2014-03-10 17:42:56 -07007701 }
7702 }
jiabin2fd710d2022-05-02 23:20:22 +00007703
7704 return nullptr;
Eric Laurente552edb2014-03-10 17:42:56 -07007705}
7706
François Gaffieaaac0fd2018-11-22 17:56:39 +01007707float AudioPolicyManager::computeVolume(IVolumeCurves &curves,
7708 VolumeSource volumeSource,
François Gaffied1ab2bd2015-12-02 18:20:06 +01007709 int index,
jiabin9a3361e2019-10-01 09:38:30 -07007710 const DeviceTypeSet& deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07007711{
jiabin9a3361e2019-10-01 09:38:30 -07007712 float volumeDb = curves.volIndexToDb(Volume::getDeviceCategory(deviceTypes), index);
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07007713
7714 // handle the case of accessibility active while a ringtone is playing: if the ringtone is much
7715 // louder than the accessibility prompt, the prompt cannot be heard, thus masking the touch
7716 // exploration of the dialer UI. In this situation, bring the accessibility volume closer to
7717 // the ringtone volume
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007718 const auto callVolumeSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL, false);
7719 const auto ringVolumeSrc = toVolumeSource(AUDIO_STREAM_RING, false);
7720 const auto musicVolumeSrc = toVolumeSource(AUDIO_STREAM_MUSIC, false);
7721 const auto alarmVolumeSrc = toVolumeSource(AUDIO_STREAM_ALARM, false);
7722 const auto a11yVolumeSrc = toVolumeSource(AUDIO_STREAM_ACCESSIBILITY, false);
Oscar Azucena437ded52023-08-30 18:45:18 -07007723 // Verify that the current volume source is not the ringer volume to prevent recursively
7724 // calling to compute volume. This could happen in cases where a11y and ringer sounds belong
7725 // to the same volume group.
7726 if (volumeSource != ringVolumeSrc && volumeSource == a11yVolumeSrc
François Gaffieaaac0fd2018-11-22 17:56:39 +01007727 && (AUDIO_MODE_RINGTONE == mEngine->getPhoneState()) &&
7728 mOutputs.isActive(ringVolumeSrc, 0)) {
7729 auto &ringCurves = getVolumeCurves(AUDIO_STREAM_RING);
jiabin9a3361e2019-10-01 09:38:30 -07007730 const float ringVolumeDb = computeVolume(ringCurves, ringVolumeSrc, index, deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007731 return ringVolumeDb - 4 > volumeDb ? ringVolumeDb - 4 : volumeDb;
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07007732 }
7733
Eric Laurentdcd4ab12018-06-29 17:45:13 -07007734 // in-call: always cap volume by voice volume + some low headroom
François Gaffieaaac0fd2018-11-22 17:56:39 +01007735 if ((volumeSource != callVolumeSrc && (isInCall() ||
7736 mOutputs.isActiveLocally(callVolumeSrc))) &&
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007737 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM, false) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01007738 volumeSource == ringVolumeSrc || volumeSource == musicVolumeSrc ||
7739 volumeSource == alarmVolumeSrc ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007740 volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION, false) ||
7741 volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false) ||
7742 volumeSource == toVolumeSource(AUDIO_STREAM_DTMF, false) ||
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07007743 volumeSource == a11yVolumeSrc)) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007744 auto &voiceCurves = getVolumeCurves(callVolumeSrc);
jiabin9a3361e2019-10-01 09:38:30 -07007745 int voiceVolumeIndex = voiceCurves.getVolumeIndex(deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007746 const float maxVoiceVolDb =
jiabin9a3361e2019-10-01 09:38:30 -07007747 computeVolume(voiceCurves, callVolumeSrc, voiceVolumeIndex, deviceTypes)
Eric Laurent7731b5a2018-04-06 15:47:22 -07007748 + IN_CALL_EARPIECE_HEADROOM_DB;
Abhijith Shastry329ddab2019-04-23 11:53:26 -07007749 // FIXME: Workaround for call screening applications until a proper audio mode is defined
7750 // to support this scenario : Exempt the RING stream from the audio cap if the audio was
7751 // programmatically muted.
7752 // VOICE_CALL stream has minVolumeIndex > 0 : Users cannot set the volume of voice calls to
7753 // 0. We don't want to cap volume when the system has programmatically muted the voice call
7754 // stream. See setVolumeCurveIndex() for more information.
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07007755 bool exemptFromCapping =
7756 ((volumeSource == ringVolumeSrc) || (volumeSource == a11yVolumeSrc))
7757 && (voiceVolumeIndex == 0);
Abhijith Shastry329ddab2019-04-23 11:53:26 -07007758 ALOGV_IF(exemptFromCapping, "%s volume source %d at vol=%f not capped", __func__,
7759 volumeSource, volumeDb);
7760 if ((volumeDb > maxVoiceVolDb) && !exemptFromCapping) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007761 ALOGV("%s volume source %d at vol=%f overriden by volume group %d at vol=%f", __func__,
7762 volumeSource, volumeDb, callVolumeSrc, maxVoiceVolDb);
7763 volumeDb = maxVoiceVolDb;
Jean-Michel Trivi719a9872017-08-05 13:51:35 -07007764 }
7765 }
Eric Laurente552edb2014-03-10 17:42:56 -07007766 // if a headset is connected, apply the following rules to ring tones and notifications
7767 // to avoid sound level bursts in user's ears:
Eric Laurent6af1c1d2016-04-14 11:20:44 -07007768 // - always attenuate notifications volume by 6dB
7769 // - attenuate ring tones volume by 6dB unless music is not playing and
7770 // speaker is part of the select devices
Eric Laurente552edb2014-03-10 17:42:56 -07007771 // - if music is playing, always limit the volume to current music volume,
7772 // with a minimum threshold at -36dB so that notification is always perceived.
jiabin9a3361e2019-10-01 09:38:30 -07007773 if (!Intersection(deviceTypes,
7774 {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP, AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES,
7775 AUDIO_DEVICE_OUT_WIRED_HEADSET, AUDIO_DEVICE_OUT_WIRED_HEADPHONE,
Eric Laurentc42df452020-08-07 10:51:53 -07007776 AUDIO_DEVICE_OUT_USB_HEADSET, AUDIO_DEVICE_OUT_HEARING_AID,
7777 AUDIO_DEVICE_OUT_BLE_HEADSET}).empty() &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01007778 ((volumeSource == alarmVolumeSrc ||
7779 volumeSource == ringVolumeSrc) ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007780 (volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION, false)) ||
7781 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM, false)) ||
7782 ((volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false)) &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01007783 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) &&
7784 curves.canBeMuted()) {
7785
Eric Laurente552edb2014-03-10 17:42:56 -07007786 // when the phone is ringing we must consider that music could have been paused just before
7787 // by the music application and behave as if music was active if the last music track was
7788 // just stopped
Oscar Azucena437ded52023-08-30 18:45:18 -07007789 // Verify that the current volume source is not the music volume to prevent recursively
7790 // calling to compute volume. This could happen in cases where music and
7791 // (alarm, ring, notification, system, etc.) sounds belong to the same volume group.
7792 if (volumeSource != musicVolumeSrc &&
7793 (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY)
7794 || mLimitRingtoneVolume)) {
François Gaffie43c73442018-11-08 08:21:55 +01007795 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
jiabin9a3361e2019-10-01 09:38:30 -07007796 DeviceTypeSet musicDevice =
François Gaffiec005e562018-11-06 15:04:49 +01007797 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
7798 nullptr, true /*fromCache*/).types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01007799 auto &musicCurves = getVolumeCurves(AUDIO_STREAM_MUSIC);
jiabin9a3361e2019-10-01 09:38:30 -07007800 float musicVolDb = computeVolume(musicCurves,
7801 musicVolumeSrc,
7802 musicCurves.getVolumeIndex(musicDevice),
7803 musicDevice);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007804 float minVolDb = (musicVolDb > SONIFICATION_HEADSET_VOLUME_MIN_DB) ?
7805 musicVolDb : SONIFICATION_HEADSET_VOLUME_MIN_DB;
7806 if (volumeDb > minVolDb) {
7807 volumeDb = minVolDb;
7808 ALOGV("computeVolume limiting volume to %f musicVol %f", minVolDb, musicVolDb);
Eric Laurente552edb2014-03-10 17:42:56 -07007809 }
Eric Laurent7b6385c2021-05-12 17:55:36 +02007810 if (Volume::getDeviceForVolume(deviceTypes) != AUDIO_DEVICE_OUT_SPEAKER
7811 && !Intersection(deviceTypes, {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP,
7812 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES}).empty()) {
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07007813 // on A2DP, also ensure notification volume is not too low compared to media when
7814 // intended to be played
François Gaffie43c73442018-11-08 08:21:55 +01007815 if ((volumeDb > -96.0f) &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01007816 (musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB > volumeDb)) {
jiabin9a3361e2019-10-01 09:38:30 -07007817 ALOGV("%s increasing volume for volume source=%d device=%s from %f to %f",
7818 __func__, volumeSource, dumpDeviceTypes(deviceTypes).c_str(), volumeDb,
François Gaffieaaac0fd2018-11-22 17:56:39 +01007819 musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB);
7820 volumeDb = musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB;
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07007821 }
7822 }
jiabin9a3361e2019-10-01 09:38:30 -07007823 } else if ((Volume::getDeviceForVolume(deviceTypes) != AUDIO_DEVICE_OUT_SPEAKER) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01007824 (!(volumeSource == alarmVolumeSrc || volumeSource == ringVolumeSrc))) {
François Gaffie43c73442018-11-08 08:21:55 +01007825 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07007826 }
7827 }
7828
François Gaffie43c73442018-11-08 08:21:55 +01007829 return volumeDb;
Eric Laurente552edb2014-03-10 17:42:56 -07007830}
7831
Eric Laurent3839bc02018-07-10 18:33:34 -07007832int AudioPolicyManager::rescaleVolumeIndex(int srcIndex,
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01007833 VolumeSource fromVolumeSource,
7834 VolumeSource toVolumeSource)
Eric Laurent3839bc02018-07-10 18:33:34 -07007835{
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01007836 if (fromVolumeSource == toVolumeSource) {
Eric Laurent3839bc02018-07-10 18:33:34 -07007837 return srcIndex;
7838 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01007839 auto &srcCurves = getVolumeCurves(fromVolumeSource);
7840 auto &dstCurves = getVolumeCurves(toVolumeSource);
Eric Laurentf5aa58d2019-02-22 18:20:11 -08007841 float minSrc = (float)srcCurves.getVolumeIndexMin();
7842 float maxSrc = (float)srcCurves.getVolumeIndexMax();
7843 float minDst = (float)dstCurves.getVolumeIndexMin();
7844 float maxDst = (float)dstCurves.getVolumeIndexMax();
Eric Laurent3839bc02018-07-10 18:33:34 -07007845
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08007846 // preserve mute request or correct range
7847 if (srcIndex < minSrc) {
7848 if (srcIndex == 0) {
7849 return 0;
7850 }
7851 srcIndex = minSrc;
7852 } else if (srcIndex > maxSrc) {
7853 srcIndex = maxSrc;
7854 }
Eric Laurent3839bc02018-07-10 18:33:34 -07007855 return (int)(minDst + ((srcIndex - minSrc) * (maxDst - minDst)) / (maxSrc - minSrc));
7856}
7857
François Gaffieaaac0fd2018-11-22 17:56:39 +01007858status_t AudioPolicyManager::checkAndSetVolume(IVolumeCurves &curves,
7859 VolumeSource volumeSource,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08007860 int index,
7861 const sp<AudioOutputDescriptor>& outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07007862 DeviceTypeSet deviceTypes,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08007863 int delayMs,
7864 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07007865{
François Gaffieaaac0fd2018-11-22 17:56:39 +01007866 // do not change actual attributes volume if the attributes is muted
7867 if (outputDesc->isMuted(volumeSource)) {
7868 ALOGVV("%s: volume source %d muted count %d active=%d", __func__, volumeSource,
7869 outputDesc->getMuteCount(volumeSource), outputDesc->isActive(volumeSource));
Eric Laurente552edb2014-03-10 17:42:56 -07007870 return NO_ERROR;
7871 }
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007872 VolumeSource callVolSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL, false);
7873 VolumeSource btScoVolSrc = toVolumeSource(AUDIO_STREAM_BLUETOOTH_SCO, false);
7874 bool isVoiceVolSrc = (volumeSource != VOLUME_SOURCE_NONE) && (callVolSrc == volumeSource);
7875 bool isBtScoVolSrc = (volumeSource != VOLUME_SOURCE_NONE) && (btScoVolSrc == volumeSource);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007876
Eric Laurent2517af32020-11-25 15:31:27 +01007877 bool isScoRequested = isScoRequestedForComm();
Eric Laurent1a8b45f2022-04-13 16:01:47 +02007878 bool isHAUsed = isHearingAidUsedForComm();
7879
Eric Laurente552edb2014-03-10 17:42:56 -07007880 // do not change in call volume if bluetooth is connected and vice versa
François Gaffieaaac0fd2018-11-22 17:56:39 +01007881 // if sco and call follow same curves, bypass forceUseForComm
7882 if ((callVolSrc != btScoVolSrc) &&
Eric Laurent2517af32020-11-25 15:31:27 +01007883 ((isVoiceVolSrc && isScoRequested) ||
Beibeif660a512023-02-28 17:00:34 +08007884 (isBtScoVolSrc && !(isScoRequested || isHAUsed))) &&
7885 !isSingleDeviceType(deviceTypes, AUDIO_DEVICE_OUT_TELEPHONY_TX)) {
Eric Laurent2517af32020-11-25 15:31:27 +01007886 ALOGV("%s cannot set volume group %d volume when is%srequested for comm", __func__,
Eric Laurent1a8b45f2022-04-13 16:01:47 +02007887 volumeSource, isScoRequested ? " " : " not ");
Eric Laurent571ef962020-07-24 11:43:48 -07007888 // Do not return an error here as AudioService will always set both voice call
7889 // and bluetooth SCO volumes due to stream aliasing.
7890 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07007891 }
jiabin9a3361e2019-10-01 09:38:30 -07007892 if (deviceTypes.empty()) {
7893 deviceTypes = outputDesc->devices().types();
chenxin2080986da2023-07-17 11:45:21 +08007894 index = curves.getVolumeIndex(deviceTypes);
7895 ALOGD("%s if deviceTypes is change from none to device %s, need get index %d",
7896 __func__, dumpDeviceTypes(deviceTypes).c_str(), index);
Eric Laurentc75307b2015-03-17 15:29:32 -07007897 }
Eric Laurent275e8e92014-11-30 15:14:47 -08007898
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00007899 if (curves.getVolumeIndexMin() < 0 || curves.getVolumeIndexMax() < 0) {
7900 ALOGE("invalid volume index range");
7901 return BAD_VALUE;
7902 }
7903
jiabin9a3361e2019-10-01 09:38:30 -07007904 float volumeDb = computeVolume(curves, volumeSource, index, deviceTypes);
7905 if (outputDesc->isFixedVolume(deviceTypes) ||
Eric Laurent9698a4c2020-10-12 17:10:23 -07007906 // Force VoIP volume to max for bluetooth SCO device except if muted
7907 (index != 0 && (isVoiceVolSrc || isBtScoVolSrc) &&
jiabin9a3361e2019-10-01 09:38:30 -07007908 isSingleDeviceType(deviceTypes, audio_is_bluetooth_out_sco_device))) {
Eric Laurentffbc80f2015-03-18 18:30:19 -07007909 volumeDb = 0.0f;
Eric Laurent275e8e92014-11-30 15:14:47 -08007910 }
Francois Gaffie593634d2021-06-22 13:31:31 +02007911 const bool muted = (index == 0) && (volumeDb != 0.0f);
Eric Laurent31a428a2023-08-11 12:16:28 +02007912 outputDesc->setVolume(volumeDb, muted, volumeSource, curves.getStreamTypes(),
7913 deviceTypes, delayMs, force, isVoiceVolSrc);
Eric Laurentc75307b2015-03-17 15:29:32 -07007914
Eric Laurente8f2c0f2021-08-17 11:17:19 +02007915 if (outputDesc == mPrimaryOutput && (isVoiceVolSrc || isBtScoVolSrc)) {
Eric Laurente552edb2014-03-10 17:42:56 -07007916 float voiceVolume;
Eric Laurentfad001d2019-06-11 19:17:57 -07007917 // 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 +01007918 if (isVoiceVolSrc) {
7919 voiceVolume = (float)index/(float)curves.getVolumeIndexMax();
Eric Laurente552edb2014-03-10 17:42:56 -07007920 } else {
Eric Laurentfad001d2019-06-11 19:17:57 -07007921 voiceVolume = index == 0 ? 0.0 : 1.0;
Eric Laurente552edb2014-03-10 17:42:56 -07007922 }
Eric Laurent18fba842016-03-31 14:41:26 -07007923 if (voiceVolume != mLastVoiceVolume) {
Eric Laurente552edb2014-03-10 17:42:56 -07007924 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
7925 mLastVoiceVolume = voiceVolume;
7926 }
7927 }
Eric Laurente552edb2014-03-10 17:42:56 -07007928 return NO_ERROR;
7929}
7930
Eric Laurentc75307b2015-03-17 15:29:32 -07007931void AudioPolicyManager::applyStreamVolumes(const sp<AudioOutputDescriptor>& outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07007932 const DeviceTypeSet& deviceTypes,
7933 int delayMs,
7934 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07007935{
jiabincd510522020-01-22 09:40:55 -08007936 ALOGVV("applyStreamVolumes() for device %s", dumpDeviceTypes(deviceTypes).c_str());
François Gaffieaaac0fd2018-11-22 17:56:39 +01007937 for (const auto &volumeGroup : mEngine->getVolumeGroups()) {
7938 auto &curves = getVolumeCurves(toVolumeSource(volumeGroup));
7939 checkAndSetVolume(curves, toVolumeSource(volumeGroup),
jiabin9a3361e2019-10-01 09:38:30 -07007940 curves.getVolumeIndex(deviceTypes),
7941 outputDesc, deviceTypes, delayMs, force);
Eric Laurente552edb2014-03-10 17:42:56 -07007942 }
7943}
7944
François Gaffiec005e562018-11-06 15:04:49 +01007945void AudioPolicyManager::setStrategyMute(product_strategy_t strategy,
7946 bool on,
7947 const sp<AudioOutputDescriptor>& outputDesc,
7948 int delayMs,
jiabin9a3361e2019-10-01 09:38:30 -07007949 DeviceTypeSet deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07007950{
François Gaffieaaac0fd2018-11-22 17:56:39 +01007951 std::vector<VolumeSource> sourcesToMute;
7952 for (auto attributes: mEngine->getAllAttributesForProductStrategy(strategy)) {
7953 ALOGVV("%s() attributes %s, mute %d, output ID %d", __func__,
7954 toString(attributes).c_str(), on, outputDesc->getId());
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007955 VolumeSource source = toVolumeSource(attributes, false);
7956 if ((source != VOLUME_SOURCE_NONE) &&
7957 (std::find(begin(sourcesToMute), end(sourcesToMute), source)
7958 == end(sourcesToMute))) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007959 sourcesToMute.push_back(source);
7960 }
Eric Laurente552edb2014-03-10 17:42:56 -07007961 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01007962 for (auto source : sourcesToMute) {
jiabin9a3361e2019-10-01 09:38:30 -07007963 setVolumeSourceMute(source, on, outputDesc, delayMs, deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007964 }
7965
Eric Laurente552edb2014-03-10 17:42:56 -07007966}
7967
François Gaffieaaac0fd2018-11-22 17:56:39 +01007968void AudioPolicyManager::setVolumeSourceMute(VolumeSource volumeSource,
7969 bool on,
7970 const sp<AudioOutputDescriptor>& outputDesc,
7971 int delayMs,
jiabin9a3361e2019-10-01 09:38:30 -07007972 DeviceTypeSet deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07007973{
jiabin9a3361e2019-10-01 09:38:30 -07007974 if (deviceTypes.empty()) {
7975 deviceTypes = outputDesc->devices().types();
Eric Laurente552edb2014-03-10 17:42:56 -07007976 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01007977 auto &curves = getVolumeCurves(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07007978 if (on) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007979 if (!outputDesc->isMuted(volumeSource)) {
Eric Laurentf5aa58d2019-02-22 18:20:11 -08007980 if (curves.canBeMuted() &&
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007981 (volumeSource != toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01007982 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) ==
7983 AUDIO_POLICY_FORCE_NONE))) {
jiabin9a3361e2019-10-01 09:38:30 -07007984 checkAndSetVolume(curves, volumeSource, 0, outputDesc, deviceTypes, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07007985 }
7986 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01007987 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not
7988 // ignored
7989 outputDesc->incMuteCount(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07007990 } else {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007991 if (!outputDesc->isMuted(volumeSource)) {
7992 ALOGV("%s unmuting non muted attributes!", __func__);
Eric Laurente552edb2014-03-10 17:42:56 -07007993 return;
7994 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01007995 if (outputDesc->decMuteCount(volumeSource) == 0) {
7996 checkAndSetVolume(curves, volumeSource,
jiabin9a3361e2019-10-01 09:38:30 -07007997 curves.getVolumeIndex(deviceTypes),
Eric Laurentc75307b2015-03-17 15:29:32 -07007998 outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07007999 deviceTypes,
Eric Laurente552edb2014-03-10 17:42:56 -07008000 delayMs);
8001 }
8002 }
8003}
8004
François Gaffie53615e22015-03-19 09:24:12 +01008005bool AudioPolicyManager::isValidAttributes(const audio_attributes_t *paa)
8006{
François Gaffiec005e562018-11-06 15:04:49 +01008007 // has flags that map to a stream type?
Eric Laurente83b55d2014-11-14 10:06:21 -08008008 if ((paa->flags & (AUDIO_FLAG_AUDIBILITY_ENFORCED | AUDIO_FLAG_SCO | AUDIO_FLAG_BEACON)) != 0) {
8009 return true;
8010 }
8011
8012 // has known usage?
8013 switch (paa->usage) {
8014 case AUDIO_USAGE_UNKNOWN:
8015 case AUDIO_USAGE_MEDIA:
8016 case AUDIO_USAGE_VOICE_COMMUNICATION:
8017 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
8018 case AUDIO_USAGE_ALARM:
8019 case AUDIO_USAGE_NOTIFICATION:
8020 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
8021 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
8022 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
8023 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
8024 case AUDIO_USAGE_NOTIFICATION_EVENT:
8025 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
8026 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
8027 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
8028 case AUDIO_USAGE_GAME:
Eric Laurent275e8e92014-11-30 15:14:47 -08008029 case AUDIO_USAGE_VIRTUAL_SOURCE:
Jean-Michel Trivi36867762016-12-29 12:03:28 -08008030 case AUDIO_USAGE_ASSISTANT:
Eric Laurent21777f82019-12-06 18:12:06 -08008031 case AUDIO_USAGE_CALL_ASSISTANT:
Hayden Gomes524159d2019-12-23 14:41:47 -08008032 case AUDIO_USAGE_EMERGENCY:
8033 case AUDIO_USAGE_SAFETY:
8034 case AUDIO_USAGE_VEHICLE_STATUS:
8035 case AUDIO_USAGE_ANNOUNCEMENT:
Eric Laurente83b55d2014-11-14 10:06:21 -08008036 break;
8037 default:
8038 return false;
8039 }
8040 return true;
8041}
8042
François Gaffie2110e042015-03-24 08:41:51 +01008043audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
8044{
8045 return mEngine->getForceUse(usage);
8046}
8047
Eric Laurent96d1dda2022-03-14 17:14:19 +01008048bool AudioPolicyManager::isInCall() const {
François Gaffie2110e042015-03-24 08:41:51 +01008049 return isStateInCall(mEngine->getPhoneState());
8050}
8051
Eric Laurent96d1dda2022-03-14 17:14:19 +01008052bool AudioPolicyManager::isStateInCall(int state) const {
François Gaffie2110e042015-03-24 08:41:51 +01008053 return is_state_in_call(state);
8054}
8055
Eric Laurentf9cccec2022-11-16 19:12:00 +01008056bool AudioPolicyManager::isCallAudioAccessible() const {
Eric Laurent74b71512019-11-06 17:21:57 -08008057 audio_mode_t mode = mEngine->getPhoneState();
8058 return (mode == AUDIO_MODE_IN_CALL)
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01008059 || (mode == AUDIO_MODE_CALL_SCREEN)
8060 || (mode == AUDIO_MODE_CALL_REDIRECT);
Eric Laurent74b71512019-11-06 17:21:57 -08008061}
8062
Eric Laurentf9cccec2022-11-16 19:12:00 +01008063bool AudioPolicyManager::isInCallOrScreening() const {
8064 audio_mode_t mode = mEngine->getPhoneState();
8065 return isStateInCall(mode) || mode == AUDIO_MODE_CALL_SCREEN;
8066}
8067
Eric Laurentd60560a2015-04-10 11:31:20 -07008068void AudioPolicyManager::cleanUpForDevice(const sp<DeviceDescriptor>& deviceDesc)
8069{
8070 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07008071 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008072 if (sourceDesc->isConnected() && (sourceDesc->srcDevice()->equals(deviceDesc) ||
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02008073 sourceDesc->sinkDevice()->equals(deviceDesc))
8074 && !isCallRxAudioSource(sourceDesc)) {
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008075 disconnectAudioSource(sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07008076 }
8077 }
8078
8079 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
8080 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
8081 bool release = false;
8082 for (size_t j = 0; j < patchDesc->mPatch.num_sources && !release; j++) {
8083 const struct audio_port_config *source = &patchDesc->mPatch.sources[j];
8084 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
8085 source->ext.device.type == deviceDesc->type()) {
8086 release = true;
8087 }
8088 }
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008089 const char *address = deviceDesc->address().c_str();
Eric Laurentd60560a2015-04-10 11:31:20 -07008090 for (size_t j = 0; j < patchDesc->mPatch.num_sinks && !release; j++) {
8091 const struct audio_port_config *sink = &patchDesc->mPatch.sinks[j];
8092 if (sink->type == AUDIO_PORT_TYPE_DEVICE &&
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008093 sink->ext.device.type == deviceDesc->type() &&
8094 (strnlen(address, AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0
8095 || strncmp(sink->ext.device.address, address,
8096 AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0)) {
Eric Laurentd60560a2015-04-10 11:31:20 -07008097 release = true;
8098 }
8099 }
8100 if (release) {
François Gaffieafd4cea2019-11-18 15:50:22 +01008101 ALOGV("%s releasing patch %u", __FUNCTION__, patchDesc->getHandle());
8102 releaseAudioPatch(patchDesc->getHandle(), patchDesc->getUid());
Eric Laurentd60560a2015-04-10 11:31:20 -07008103 }
8104 }
Francois Gaffie716e1432019-01-14 16:58:59 +01008105
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01008106 mInputs.clearSessionRoutesForDevice(deviceDesc);
8107
Francois Gaffie716e1432019-01-14 16:58:59 +01008108 mHwModules.cleanUpForDevice(deviceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07008109}
8110
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008111void AudioPolicyManager::modifySurroundFormats(
8112 const sp<DeviceDescriptor>& devDesc, FormatVector *formatsPtr) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008113 std::unordered_set<audio_format_t> enforcedSurround(
8114 devDesc->encodedFormats().begin(), devDesc->encodedFormats().end());
Mikhail Naganov100f0122018-11-29 11:22:16 -08008115 std::unordered_set<audio_format_t> allSurround; // A flat set of all known surround formats
Mikhail Naganov68e3f642023-04-28 13:06:32 -07008116 for (const auto& pair : mConfig->getSurroundFormats()) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008117 allSurround.insert(pair.first);
8118 for (const auto& subformat : pair.second) allSurround.insert(subformat);
8119 }
Phil Burk09bc4612016-02-24 15:58:15 -08008120
8121 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
8122 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Phil Burk0709b0a2016-03-31 12:54:57 -07008123 ALOGD("%s: forced use = %d", __FUNCTION__, forceUse);
Mikhail Naganov100f0122018-11-29 11:22:16 -08008124 // This is the resulting set of formats depending on the surround mode:
8125 // 'all surround' = allSurround
8126 // 'enforced surround' = enforcedSurround [may include IEC69137 which isn't raw surround fmt]
8127 // 'non-surround' = not in 'all surround' and not in 'enforced surround'
8128 // 'manual surround' = mManualSurroundFormats
8129 // AUTO: formats v 'enforced surround'
8130 // ALWAYS: formats v 'all surround' v 'enforced surround'
8131 // NEVER: formats ^ 'non-surround'
8132 // MANUAL: formats ^ ('non-surround' v 'manual surround' v (IEC69137 ^ 'enforced surround'))
Phil Burk09bc4612016-02-24 15:58:15 -08008133
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008134 std::unordered_set<audio_format_t> formatSet;
8135 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL
8136 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008137 // formatSet is (formats ^ 'non-surround')
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008138 for (auto formatIter = formatsPtr->begin(); formatIter != formatsPtr->end(); ++formatIter) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008139 if (allSurround.count(*formatIter) == 0 && enforcedSurround.count(*formatIter) == 0) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008140 formatSet.insert(*formatIter);
8141 }
8142 }
8143 } else {
8144 formatSet.insert(formatsPtr->begin(), formatsPtr->end());
8145 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08008146 formatsPtr->clear(); // Re-filled from the formatSet at the end.
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008147
jiabin81772902018-04-02 17:52:27 -07008148 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008149 formatSet.insert(mManualSurroundFormats.begin(), mManualSurroundFormats.end());
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008150 // Enable IEC61937 when in MANUAL mode if it's enforced for this device.
8151 if (enforcedSurround.count(AUDIO_FORMAT_IEC61937) != 0) {
8152 formatSet.insert(AUDIO_FORMAT_IEC61937);
Phil Burk09bc4612016-02-24 15:58:15 -08008153 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08008154 } else if (forceUse != AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) { // AUTO or ALWAYS
8155 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS) {
8156 formatSet.insert(allSurround.begin(), allSurround.end());
Phil Burk07ac1142016-03-25 13:39:29 -07008157 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08008158 formatSet.insert(enforcedSurround.begin(), enforcedSurround.end());
Phil Burk09bc4612016-02-24 15:58:15 -08008159 }
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008160 for (const auto& format : formatSet) {
jiabin06e4bab2019-07-29 10:13:34 -07008161 formatsPtr->push_back(format);
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008162 }
Phil Burk0709b0a2016-03-31 12:54:57 -07008163}
8164
jiabin06e4bab2019-07-29 10:13:34 -07008165void AudioPolicyManager::modifySurroundChannelMasks(ChannelMaskSet *channelMasksPtr) {
8166 ChannelMaskSet &channelMasks = *channelMasksPtr;
Phil Burk0709b0a2016-03-31 12:54:57 -07008167 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
8168 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
8169
8170 // If NEVER, then remove support for channelMasks > stereo.
8171 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
jiabin06e4bab2019-07-29 10:13:34 -07008172 for (auto it = channelMasks.begin(); it != channelMasks.end();) {
8173 audio_channel_mask_t channelMask = *it;
Phil Burk0709b0a2016-03-31 12:54:57 -07008174 if (channelMask & ~AUDIO_CHANNEL_OUT_STEREO) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01008175 ALOGV("%s: force NEVER, so remove channelMask 0x%08x", __FUNCTION__, channelMask);
jiabin06e4bab2019-07-29 10:13:34 -07008176 it = channelMasks.erase(it);
Phil Burk0709b0a2016-03-31 12:54:57 -07008177 } else {
jiabin06e4bab2019-07-29 10:13:34 -07008178 ++it;
Phil Burk0709b0a2016-03-31 12:54:57 -07008179 }
8180 }
jiabin81772902018-04-02 17:52:27 -07008181 // If ALWAYS or MANUAL, then make sure we at least support 5.1
8182 } else if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS
8183 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Phil Burk0709b0a2016-03-31 12:54:57 -07008184 bool supports5dot1 = false;
8185 // Are there any channel masks that can be considered "surround"?
Mikhail Naganovcf84e592017-12-07 11:25:11 -08008186 for (audio_channel_mask_t channelMask : channelMasks) {
Phil Burk0709b0a2016-03-31 12:54:57 -07008187 if ((channelMask & AUDIO_CHANNEL_OUT_5POINT1) == AUDIO_CHANNEL_OUT_5POINT1) {
8188 supports5dot1 = true;
8189 break;
8190 }
8191 }
8192 // If not then add 5.1 support.
8193 if (!supports5dot1) {
jiabin06e4bab2019-07-29 10:13:34 -07008194 channelMasks.insert(AUDIO_CHANNEL_OUT_5POINT1);
Eric Laurentfecbceb2021-02-09 14:46:43 +01008195 ALOGV("%s: force MANUAL or ALWAYS, so adding channelMask for 5.1 surround", __func__);
Phil Burk0709b0a2016-03-31 12:54:57 -07008196 }
Phil Burk09bc4612016-02-24 15:58:15 -08008197 }
8198}
8199
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008200void AudioPolicyManager::updateAudioProfiles(const sp<DeviceDescriptor>& devDesc,
Phil Burk00eeb322016-03-31 12:41:00 -07008201 audio_io_handle_t ioHandle,
jiabin12537fc2023-10-12 17:56:08 +00008202 const sp<IOProfile>& profile) {
8203 if (!profile->hasDynamicAudioProfile()) {
8204 return;
François Gaffie112b0af2015-11-19 16:13:25 +01008205 }
François Gaffie112b0af2015-11-19 16:13:25 +01008206
jiabin12537fc2023-10-12 17:56:08 +00008207 audio_port_v7 devicePort;
8208 devDesc->toAudioPort(&devicePort);
François Gaffie112b0af2015-11-19 16:13:25 +01008209
jiabin12537fc2023-10-12 17:56:08 +00008210 audio_port_v7 mixPort;
8211 profile->toAudioPort(&mixPort);
8212 mixPort.ext.mix.handle = ioHandle;
8213
8214 status_t status = mpClientInterface->getAudioMixPort(&devicePort, &mixPort);
8215 if (status != NO_ERROR) {
8216 ALOGE("%s failed to query the attributes of the mix port", __func__);
8217 return;
François Gaffie112b0af2015-11-19 16:13:25 +01008218 }
jiabin12537fc2023-10-12 17:56:08 +00008219
8220 std::set<audio_format_t> supportedFormats;
8221 for (size_t i = 0; i < mixPort.num_audio_profiles; ++i) {
8222 supportedFormats.insert(mixPort.audio_profiles[i].format);
8223 }
8224 FormatVector formats(supportedFormats.begin(), supportedFormats.end());
8225 mReportedFormatsMap[devDesc] = formats;
8226
8227 if (devDesc->type() == AUDIO_DEVICE_OUT_HDMI ||
8228 isDeviceOfModule(devDesc,AUDIO_HARDWARE_MODULE_ID_MSD)) {
8229 modifySurroundFormats(devDesc, &formats);
8230 size_t modifiedNumProfiles = 0;
8231 for (size_t i = 0; i < mixPort.num_audio_profiles; ++i) {
8232 if (std::find(formats.begin(), formats.end(), mixPort.audio_profiles[i].format) ==
8233 formats.end()) {
8234 // Skip the format that is not present after modifying surround formats.
8235 continue;
8236 }
8237 memcpy(&mixPort.audio_profiles[modifiedNumProfiles], &mixPort.audio_profiles[i],
8238 sizeof(struct audio_profile));
8239 ChannelMaskSet channels(mixPort.audio_profiles[modifiedNumProfiles].channel_masks,
8240 mixPort.audio_profiles[modifiedNumProfiles].channel_masks +
8241 mixPort.audio_profiles[modifiedNumProfiles].num_channel_masks);
8242 modifySurroundChannelMasks(&channels);
8243 std::copy(channels.begin(), channels.end(),
8244 std::begin(mixPort.audio_profiles[modifiedNumProfiles].channel_masks));
8245 mixPort.audio_profiles[modifiedNumProfiles++].num_channel_masks = channels.size();
8246 }
8247 mixPort.num_audio_profiles = modifiedNumProfiles;
8248 }
8249 profile->importAudioPort(mixPort);
François Gaffie112b0af2015-11-19 16:13:25 +01008250}
Eric Laurentd60560a2015-04-10 11:31:20 -07008251
Mikhail Naganovdc769682018-05-04 15:34:08 -07008252status_t AudioPolicyManager::installPatch(const char *caller,
8253 audio_patch_handle_t *patchHandle,
8254 AudioIODescriptorInterface *ioDescriptor,
8255 const struct audio_patch *patch,
8256 int delayMs)
8257{
8258 ssize_t index = mAudioPatches.indexOfKey(
8259 patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE ?
8260 *patchHandle : ioDescriptor->getPatchHandle());
8261 sp<AudioPatch> patchDesc;
8262 status_t status = installPatch(
8263 caller, index, patchHandle, patch, delayMs, mUidCached, &patchDesc);
8264 if (status == NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01008265 ioDescriptor->setPatchHandle(patchDesc->getHandle());
Mikhail Naganovdc769682018-05-04 15:34:08 -07008266 }
8267 return status;
8268}
8269
8270status_t AudioPolicyManager::installPatch(const char *caller,
8271 ssize_t index,
8272 audio_patch_handle_t *patchHandle,
8273 const struct audio_patch *patch,
8274 int delayMs,
8275 uid_t uid,
8276 sp<AudioPatch> *patchDescPtr)
8277{
8278 sp<AudioPatch> patchDesc;
8279 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
8280 if (index >= 0) {
8281 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01008282 afPatchHandle = patchDesc->getAfHandle();
Mikhail Naganovdc769682018-05-04 15:34:08 -07008283 }
8284
8285 status_t status = mpClientInterface->createAudioPatch(patch, &afPatchHandle, delayMs);
8286 ALOGV("%s() AF::createAudioPatch returned %d patchHandle %d num_sources %d num_sinks %d",
8287 caller, status, afPatchHandle, patch->num_sources, patch->num_sinks);
8288 if (status == NO_ERROR) {
8289 if (index < 0) {
8290 patchDesc = new AudioPatch(patch, uid);
François Gaffieafd4cea2019-11-18 15:50:22 +01008291 addAudioPatch(patchDesc->getHandle(), patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07008292 } else {
8293 patchDesc->mPatch = *patch;
8294 }
François Gaffieafd4cea2019-11-18 15:50:22 +01008295 patchDesc->setAfHandle(afPatchHandle);
Mikhail Naganovdc769682018-05-04 15:34:08 -07008296 if (patchHandle) {
François Gaffieafd4cea2019-11-18 15:50:22 +01008297 *patchHandle = patchDesc->getHandle();
Mikhail Naganovdc769682018-05-04 15:34:08 -07008298 }
8299 nextAudioPortGeneration();
8300 mpClientInterface->onAudioPatchListUpdate();
8301 }
8302 if (patchDescPtr) *patchDescPtr = patchDesc;
8303 return status;
8304}
8305
jiabinbce0c1d2020-10-05 11:20:18 -07008306bool AudioPolicyManager::areAllActiveTracksRerouted(const sp<SwAudioOutputDescriptor>& output)
8307{
8308 const TrackClientVector activeClients = output->getActiveClients();
8309 if (activeClients.empty()) {
8310 return true;
8311 }
8312 ssize_t index = mAudioPatches.indexOfKey(output->getPatchHandle());
8313 if (index < 0) {
8314 ALOGE("%s, no audio patch found while there are active clients on output %d",
8315 __func__, output->getId());
8316 return false;
8317 }
8318 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
8319 DeviceVector routedDevices;
8320 for (int i = 0; i < patchDesc->mPatch.num_sinks; ++i) {
8321 sp<DeviceDescriptor> device = mAvailableOutputDevices.getDeviceFromId(
8322 patchDesc->mPatch.sinks[i].id);
8323 if (device == nullptr) {
8324 ALOGE("%s, no audio device found with id(%d)",
8325 __func__, patchDesc->mPatch.sinks[i].id);
8326 return false;
8327 }
8328 routedDevices.add(device);
8329 }
8330 for (const auto& client : activeClients) {
jiabin49256852022-03-09 11:21:35 -08008331 if (client->isInvalid()) {
8332 // No need to take care about invalidated clients.
8333 continue;
8334 }
jiabinbce0c1d2020-10-05 11:20:18 -07008335 sp<DeviceDescriptor> preferredDevice =
8336 mAvailableOutputDevices.getDeviceFromId(client->preferredDeviceId());
8337 if (mEngine->getOutputDevicesForAttributes(
8338 client->attributes(), preferredDevice, false) == routedDevices) {
8339 return false;
8340 }
8341 }
8342 return true;
8343}
8344
8345sp<SwAudioOutputDescriptor> AudioPolicyManager::openOutputWithProfileAndDevice(
Eric Laurentb4f42a92022-01-17 17:37:31 +01008346 const sp<IOProfile>& profile, const DeviceVector& devices,
jiabina84c3d32022-12-02 18:59:55 +00008347 const audio_config_base_t *mixerConfig, const audio_config_t *halConfig,
8348 audio_output_flags_t flags)
jiabinbce0c1d2020-10-05 11:20:18 -07008349{
8350 for (const auto& device : devices) {
8351 // TODO: This should be checking if the profile supports the device combo.
8352 if (!profile->supportsDevice(device)) {
jiabina84c3d32022-12-02 18:59:55 +00008353 ALOGE("%s profile(%s) doesn't support device %#x", __func__, profile->getName().c_str(),
8354 device->type());
jiabinbce0c1d2020-10-05 11:20:18 -07008355 return nullptr;
8356 }
8357 }
8358 sp<SwAudioOutputDescriptor> desc = new SwAudioOutputDescriptor(profile, mpClientInterface);
8359 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
jiabina84c3d32022-12-02 18:59:55 +00008360 status_t status = desc->open(halConfig, mixerConfig, devices,
8361 AUDIO_STREAM_DEFAULT, flags, &output);
jiabinbce0c1d2020-10-05 11:20:18 -07008362 if (status != NO_ERROR) {
jiabina84c3d32022-12-02 18:59:55 +00008363 ALOGE("%s failed to open output %d", __func__, status);
jiabinbce0c1d2020-10-05 11:20:18 -07008364 return nullptr;
8365 }
8366
8367 // Here is where the out_set_parameters() for card & device gets called
8368 sp<DeviceDescriptor> device = devices.getDeviceForOpening();
8369 const audio_devices_t deviceType = device->type();
8370 const String8 &address = String8(device->address().c_str());
Tomasz Wasilczykfd9ffd12023-08-14 17:56:22 +00008371 if (!address.empty()) {
jiabinbce0c1d2020-10-05 11:20:18 -07008372 char *param = audio_device_address_to_parameter(deviceType, address.c_str());
8373 mpClientInterface->setParameters(output, String8(param));
8374 free(param);
8375 }
jiabin12537fc2023-10-12 17:56:08 +00008376 updateAudioProfiles(device, output, profile);
jiabinbce0c1d2020-10-05 11:20:18 -07008377 if (!profile->hasValidAudioProfile()) {
8378 ALOGW("%s() missing param", __func__);
8379 desc->close();
8380 return nullptr;
jiabina84c3d32022-12-02 18:59:55 +00008381 } else if (profile->hasDynamicAudioProfile() && halConfig == nullptr) {
8382 // Reopen the output with the best audio profile picked by APM when the profile supports
8383 // dynamic audio profile and the hal config is not specified.
jiabinbce0c1d2020-10-05 11:20:18 -07008384 desc->close();
8385 output = AUDIO_IO_HANDLE_NONE;
8386 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
8387 profile->pickAudioProfile(
8388 config.sample_rate, config.channel_mask, config.format);
8389 config.offload_info.sample_rate = config.sample_rate;
8390 config.offload_info.channel_mask = config.channel_mask;
8391 config.offload_info.format = config.format;
8392
jiabina84c3d32022-12-02 18:59:55 +00008393 status = desc->open(&config, mixerConfig, devices, AUDIO_STREAM_DEFAULT, flags, &output);
jiabinbce0c1d2020-10-05 11:20:18 -07008394 if (status != NO_ERROR) {
8395 return nullptr;
8396 }
8397 }
8398
8399 addOutput(output, desc);
Eric Laurentb4f42a92022-01-17 17:37:31 +01008400
baek.kim -61c20122022-07-27 10:05:32 +00008401 sp<DeviceDescriptor> speaker = mAvailableOutputDevices.getDevice(
8402 AUDIO_DEVICE_OUT_SPEAKER, String8(""), AUDIO_FORMAT_DEFAULT);
8403
jiabinbce0c1d2020-10-05 11:20:18 -07008404 if (audio_is_remote_submix_device(deviceType) && address != "0") {
8405 sp<AudioPolicyMix> policyMix;
8406 if (mPolicyMixes.getAudioPolicyMix(deviceType, address, policyMix) == NO_ERROR) {
8407 policyMix->setOutput(desc);
8408 desc->mPolicyMix = policyMix;
8409 } else {
8410 ALOGW("checkOutputsForDevice() cannot find policy for address %s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00008411 address.c_str());
jiabinbce0c1d2020-10-05 11:20:18 -07008412 }
8413
baek.kim -61c20122022-07-27 10:05:32 +00008414 } else if (hasPrimaryOutput() && speaker != nullptr
8415 && mPrimaryOutput->supportsDevice(speaker) && !desc->supportsDevice(speaker)
Eric Laurentb4f42a92022-01-17 17:37:31 +01008416 && ((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0)) {
8417 // no duplicated output for:
8418 // - direct outputs
8419 // - outputs used by dynamic policy mixes
baek.kim -61c20122022-07-27 10:05:32 +00008420 // - outputs that supports SPEAKER while the primary output does not.
jiabinbce0c1d2020-10-05 11:20:18 -07008421 audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE;
8422
8423 //TODO: configure audio effect output stage here
8424
8425 // open a duplicating output thread for the new output and the primary output
8426 sp<SwAudioOutputDescriptor> dupOutputDesc =
8427 new SwAudioOutputDescriptor(nullptr, mpClientInterface);
8428 status = dupOutputDesc->openDuplicating(mPrimaryOutput, desc, &duplicatedOutput);
8429 if (status == NO_ERROR) {
8430 // add duplicated output descriptor
8431 addOutput(duplicatedOutput, dupOutputDesc);
8432 } else {
8433 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
8434 mPrimaryOutput->mIoHandle, output);
8435 desc->close();
8436 removeOutput(output);
8437 nextAudioPortGeneration();
8438 return nullptr;
8439 }
8440 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02008441 if (mPrimaryOutput == nullptr && profile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
8442 ALOGV("%s(): re-assigning mPrimaryOutput", __func__);
8443 mPrimaryOutput = desc;
François Gaffiedb1755b2023-09-01 11:50:35 +02008444 mPrimaryModuleHandle = mPrimaryOutput->getModuleHandle();
Francois Gaffiebce7cd42020-10-14 16:13:20 +02008445 }
jiabinbce0c1d2020-10-05 11:20:18 -07008446 return desc;
8447}
8448
jiabinf1c73972022-04-14 16:28:52 -07008449status_t AudioPolicyManager::getDevicesForAttributes(
8450 const audio_attributes_t &attr, DeviceVector &devices, bool forVolume) {
8451 // Devices are determined in the following precedence:
8452 //
8453 // 1) Devices associated with a dynamic policy matching the attributes. This is often
8454 // a remote submix from MIX_ROUTE_FLAG_LOOP_BACK.
8455 //
8456 // If no such dynamic policy then
8457 // 2) Devices containing an active client using setPreferredDevice
8458 // with same strategy as the attributes.
8459 // (from the default Engine::getOutputDevicesForAttributes() implementation).
8460 //
8461 // If no corresponding active client with setPreferredDevice then
8462 // 3) Devices associated with the strategy determined by the attributes
8463 // (from the default Engine::getOutputDevicesForAttributes() implementation).
8464 //
8465 // See related getOutputForAttrInt().
8466
8467 // check dynamic policies but only for primary descriptors (secondary not used for audible
8468 // audio routing, only used for duplication for playback capture)
8469 sp<AudioPolicyMix> policyMix;
Oscar Azucena873d10f2023-01-12 18:34:42 -08008470 bool unneededUsePrimaryOutputFromPolicyMixes = false;
jiabinf1c73972022-04-14 16:28:52 -07008471 status_t status = mPolicyMixes.getOutputForAttr(attr, AUDIO_CONFIG_BASE_INITIALIZER,
Oscar Azucena873d10f2023-01-12 18:34:42 -08008472 0 /*uid unknown here*/, AUDIO_SESSION_NONE, AUDIO_OUTPUT_FLAG_NONE,
8473 mAvailableOutputDevices, nullptr /* requestedDevice */, policyMix,
8474 nullptr /* secondaryMixes */, unneededUsePrimaryOutputFromPolicyMixes);
jiabinf1c73972022-04-14 16:28:52 -07008475 if (status != OK) {
8476 return status;
8477 }
8478
8479 if (policyMix != nullptr && policyMix->getOutput() != nullptr &&
8480 // For volume control, skip LOOPBACK mixes which use AUDIO_DEVICE_OUT_REMOTE_SUBMIX
8481 // as they are unaffected by device/stream volume
8482 // (per SwAudioOutputDescriptor::isFixedVolume()).
8483 (!forVolume || policyMix->mDeviceType != AUDIO_DEVICE_OUT_REMOTE_SUBMIX)
8484 ) {
8485 sp<DeviceDescriptor> deviceDesc = mAvailableOutputDevices.getDevice(
8486 policyMix->mDeviceType, policyMix->mDeviceAddress, AUDIO_FORMAT_DEFAULT);
8487 devices.add(deviceDesc);
8488 } else {
8489 // The default Engine::getOutputDevicesForAttributes() uses findPreferredDevice()
8490 // which selects setPreferredDevice if active. This means forVolume call
8491 // will take an active setPreferredDevice, if such exists.
8492
8493 devices = mEngine->getOutputDevicesForAttributes(
8494 attr, nullptr /* preferredDevice */, false /* fromCache */);
8495 }
8496
8497 if (forVolume) {
8498 // We alias the device AUDIO_DEVICE_OUT_SPEAKER_SAFE to AUDIO_DEVICE_OUT_SPEAKER
8499 // for single volume control in AudioService (such relationship should exist if
8500 // SPEAKER_SAFE is present).
8501 //
8502 // (This is unrelated to a different device grouping as Volume::getDeviceCategory)
8503 DeviceVector speakerSafeDevices =
8504 devices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER_SAFE);
8505 if (!speakerSafeDevices.isEmpty()) {
8506 devices.merge(mAvailableOutputDevices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER));
8507 devices.remove(speakerSafeDevices);
8508 }
8509 }
8510
8511 return NO_ERROR;
8512}
8513
8514status_t AudioPolicyManager::getProfilesForDevices(const DeviceVector& devices,
8515 AudioProfileVector& audioProfiles,
8516 uint32_t flags,
8517 bool isInput) {
8518 for (const auto& hwModule : mHwModules) {
8519 // the MSD module checks for different conditions
8520 if (strcmp(hwModule->getName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0) {
8521 continue;
8522 }
8523 IOProfileCollection ioProfiles = isInput ? hwModule->getInputProfiles()
8524 : hwModule->getOutputProfiles();
8525 for (const auto& profile : ioProfiles) {
8526 if (!profile->areAllDevicesSupported(devices) ||
8527 !profile->isCompatibleProfileForFlags(
8528 flags, false /*exactMatchRequiredForInputFlags*/)) {
8529 continue;
8530 }
8531 audioProfiles.addAllValidProfiles(profile->asAudioPort()->getAudioProfiles());
8532 }
8533 }
8534
8535 if (!isInput) {
8536 // add the direct profiles from MSD if present and has audio patches to all the output(s)
8537 const auto &msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
8538 if (msdModule != nullptr) {
8539 if (msdHasPatchesToAllDevices(devices.toTypeAddrVector())) {
8540 ALOGV("%s: MSD audio patches set to all output devices.", __func__);
8541 for (const auto &profile: msdModule->getOutputProfiles()) {
8542 if (!profile->asAudioPort()->isDirectOutput()) {
8543 continue;
8544 }
8545 audioProfiles.addAllValidProfiles(profile->asAudioPort()->getAudioProfiles());
8546 }
8547 } else {
8548 ALOGV("%s: MSD audio patches NOT set to all output devices.", __func__);
8549 }
8550 }
8551 }
8552
8553 return NO_ERROR;
8554}
8555
jiabin3ff8d7d2022-12-13 06:27:44 +00008556sp<SwAudioOutputDescriptor> AudioPolicyManager::reopenOutput(sp<SwAudioOutputDescriptor> outputDesc,
8557 const audio_config_t *config,
8558 audio_output_flags_t flags,
8559 const char* caller) {
jiabina84c3d32022-12-02 18:59:55 +00008560 closeOutput(outputDesc->mIoHandle);
8561 sp<SwAudioOutputDescriptor> preferredOutput = openOutputWithProfileAndDevice(
8562 outputDesc->mProfile, outputDesc->devices(), nullptr /*mixerConfig*/, config, flags);
8563 if (preferredOutput == nullptr) {
8564 ALOGE("%s failed to reopen output device=%d, caller=%s",
8565 __func__, outputDesc->devices()[0]->getId(), caller);
jiabina84c3d32022-12-02 18:59:55 +00008566 }
jiabin3ff8d7d2022-12-13 06:27:44 +00008567 return preferredOutput;
8568}
8569
8570void AudioPolicyManager::reopenOutputsWithDevices(
8571 const std::map<audio_io_handle_t, DeviceVector> &outputsToReopen) {
8572 for (const auto& [output, devices] : outputsToReopen) {
8573 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
8574 closeOutput(output);
8575 openOutputWithProfileAndDevice(desc->mProfile, devices);
8576 }
jiabina84c3d32022-12-02 18:59:55 +00008577}
8578
jiabinc44b3462022-12-08 12:52:31 -08008579PortHandleVector AudioPolicyManager::getClientsForStream(
8580 audio_stream_type_t streamType) const {
8581 PortHandleVector clients;
8582 for (size_t i = 0; i < mOutputs.size(); ++i) {
8583 PortHandleVector clientsForStream = mOutputs.valueAt(i)->getClientsForStream(streamType);
8584 clients.insert(clients.end(), clientsForStream.begin(), clientsForStream.end());
8585 }
8586 return clients;
8587}
8588
8589void AudioPolicyManager::invalidateStreams(StreamTypeVector streams) const {
8590 PortHandleVector clients;
8591 for (auto stream : streams) {
8592 PortHandleVector clientsForStream = getClientsForStream(stream);
8593 clients.insert(clients.end(), clientsForStream.begin(), clientsForStream.end());
8594 }
8595 mpClientInterface->invalidateTracks(clients);
8596}
8597
Mikhail Naganov1b2a7942017-12-08 10:18:09 -08008598} // namespace android