blob: 52208e46555e13840b3c2e08e3ebde262dae625d [file] [log] [blame]
Eric Laurente552edb2014-03-10 17:42:56 -07001/*
2 * Copyright (C) 2009 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -070017#define LOG_TAG "APM_AudioPolicyManager"
Tomoharu Kasahara71c90912018-10-31 09:10:12 +090018
19// Need to keep the log statements even in production builds
20// to enable VERBOSE logging dynamically.
21// You can enable VERBOSE logging as follows:
22// adb shell setprop log.tag.APM_AudioPolicyManager V
23#define LOG_NDEBUG 0
Eric Laurente552edb2014-03-10 17:42:56 -070024
25//#define VERY_VERBOSE_LOGGING
26#ifdef VERY_VERBOSE_LOGGING
27#define ALOGVV ALOGV
28#else
29#define ALOGVV(a...) do { } while(0)
30#endif
31
Eric Laurent16c66dd2019-05-01 17:54:10 -070032#include <algorithm>
Eric Laurentd4692962014-05-05 18:13:44 -070033#include <inttypes.h>
jiabin10a03f12021-05-07 23:46:28 +000034#include <map>
Eric Laurente552edb2014-03-10 17:42:56 -070035#include <math.h>
Kevin Rocard153f92d2018-12-18 18:33:28 -080036#include <set>
Atneya Nair0f0a8032022-12-12 16:20:12 -080037#include <type_traits>
Mikhail Naganovd5e18052018-11-30 14:55:45 -080038#include <unordered_set>
Mikhail Naganov15be9d22017-11-08 14:18:13 +110039#include <vector>
Mikhail Naganov946c0032020-10-21 13:04:58 -070040
41#include <Serializer.h>
Nathalie Le Clair88fa2752021-11-23 13:03:41 +010042#include <android/media/audio/common/AudioPort.h>
Glenn Kasten76a13442020-07-01 12:10:59 -070043#include <cutils/bitops.h>
Eric Laurente552edb2014-03-10 17:42:56 -070044#include <cutils/properties.h>
Eric Laurent3b73df72014-03-11 09:06:29 -070045#include <media/AudioParameter.h>
Mikhail Naganov946c0032020-10-21 13:04:58 -070046#include <policy.h>
Andy Hung4ef19fa2018-05-15 19:35:29 -070047#include <private/android_filesystem_config.h>
Mikhail Naganovcbc8f612016-10-11 18:05:13 -070048#include <system/audio.h>
Mikhail Naganov27cf37c2020-04-14 14:47:01 -070049#include <system/audio_config.h>
jiabinebb6af42020-06-09 17:31:17 -070050#include <system/audio_effects/effect_hapticgenerator.h>
Mikhail Naganov946c0032020-10-21 13:04:58 -070051#include <utils/Log.h>
52
Eric Laurentd4692962014-05-05 18:13:44 -070053#include "AudioPolicyManager.h"
François Gaffiea8ecc2c2015-11-09 16:10:40 +010054#include "TypeConverter.h"
Eric Laurente552edb2014-03-10 17:42:56 -070055
Eric Laurent3b73df72014-03-11 09:06:29 -070056namespace android {
Eric Laurente552edb2014-03-10 17:42:56 -070057
Nathalie Le Clair88fa2752021-11-23 13:03:41 +010058using android::media::audio::common::AudioDevice;
59using android::media::audio::common::AudioDeviceAddress;
60using android::media::audio::common::AudioPortDeviceExt;
61using android::media::audio::common::AudioPortExt;
Svet Ganov3e5f14f2021-05-13 22:51:08 +000062using content::AttributionSourceState;
Philip P. Moltmannbda45752020-07-17 16:41:18 -070063
Eric Laurentdc462862016-07-19 12:29:53 -070064//FIXME: workaround for truncated touch sounds
65// to be removed when the problem is handled by system UI
66#define TOUCH_SOUND_FIXED_DELAY_MS 100
Jean-Michel Trivi719a9872017-08-05 13:51:35 -070067
68// Largest difference in dB on earpiece in call between the voice volume and another
69// media / notification / system volume.
70constexpr float IN_CALL_EARPIECE_HEADROOM_DB = 3.f;
71
jiabin06e4bab2019-07-29 10:13:34 -070072template <typename T>
73bool operator== (const SortedVector<T> &left, const SortedVector<T> &right)
74{
75 if (left.size() != right.size()) {
76 return false;
77 }
78 for (size_t index = 0; index < right.size(); index++) {
79 if (left[index] != right[index]) {
80 return false;
81 }
82 }
83 return true;
84}
85
86template <typename T>
87bool operator!= (const SortedVector<T> &left, const SortedVector<T> &right)
88{
89 return !(left == right);
90}
91
Eric Laurente552edb2014-03-10 17:42:56 -070092// ----------------------------------------------------------------------------
93// AudioPolicyInterface implementation
94// ----------------------------------------------------------------------------
95
Nathalie Le Clair88fa2752021-11-23 13:03:41 +010096status_t AudioPolicyManager::setDeviceConnectionState(audio_policy_dev_state_t state,
97 const android::media::audio::common::AudioPort& port, audio_format_t encodedFormat) {
98 status_t status = setDeviceConnectionStateInt(state, port, encodedFormat);
jiabina7b43792018-02-15 16:04:46 -080099 nextAudioPortGeneration();
100 return status;
Eric Laurentc73ca6e2014-12-12 14:34:22 -0800101}
102
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100103status_t AudioPolicyManager::setDeviceConnectionState(audio_devices_t device,
104 audio_policy_dev_state_t state,
105 const char* device_address,
106 const char* device_name,
107 audio_format_t encodedFormat) {
Atneya Nair638a6e42022-12-18 16:45:15 -0800108 media::AudioPortFw aidlPort;
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100109 if (status_t status = deviceToAudioPort(device, device_address, device_name, &aidlPort);
110 status == OK) {
111 return setDeviceConnectionState(state, aidlPort.hal, encodedFormat);
112 } else {
113 ALOGE("Failed to convert to AudioPort Parcelable: %s", statusToString(status).c_str());
114 return status;
115 }
116}
117
François Gaffie11d30102018-11-02 16:09:09 +0100118void AudioPolicyManager::broadcastDeviceConnectionState(const sp<DeviceDescriptor> &device,
jiabinc0048632023-04-27 22:04:31 +0000119 media::DeviceConnectedState state)
François Gaffie44481e72016-04-20 07:49:57 +0200120{
Mikhail Naganov516d3982022-02-01 23:53:59 +0000121 audio_port_v7 devicePort;
122 device->toAudioPort(&devicePort);
jiabinc0048632023-04-27 22:04:31 +0000123 if (status_t status = mpClientInterface->setDeviceConnectedState(&devicePort, state);
Mikhail Naganov516d3982022-02-01 23:53:59 +0000124 status != OK) {
jiabinc0048632023-04-27 22:04:31 +0000125 ALOGE("Error %d while setting connected state for device %s", state,
Mikhail Naganov516d3982022-02-01 23:53:59 +0000126 device->getDeviceTypeAddr().toString(false).c_str());
127 }
François Gaffie44481e72016-04-20 07:49:57 +0200128}
129
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100130status_t AudioPolicyManager::setDeviceConnectionStateInt(
131 audio_policy_dev_state_t state, const android::media::audio::common::AudioPort& port,
132 audio_format_t encodedFormat) {
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100133 if (port.ext.getTag() != AudioPortExt::device) {
134 return BAD_VALUE;
135 }
136 audio_devices_t device_type;
137 std::string device_address;
138 if (status_t status = aidl2legacy_AudioDevice_audio_device(
139 port.ext.get<AudioPortExt::device>().device, &device_type, &device_address);
140 status != OK) {
141 return status;
142 };
143 const char* device_name = port.name.c_str();
144 // connect/disconnect only 1 device at a time
145 if (!audio_is_output_device(device_type) && !audio_is_input_device(device_type))
146 return BAD_VALUE;
147
148 sp<DeviceDescriptor> device = mHwModules.getDeviceDescriptor(
149 device_type, device_address.c_str(), device_name, encodedFormat,
150 state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
Mikhail Naganovddc5f312022-06-11 00:47:52 +0000151 if (device == nullptr) {
152 return INVALID_OPERATION;
153 }
154 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
155 device->setExtraAudioDescriptors(port.extraAudioDescriptors);
156 }
157 return setDeviceConnectionStateInt(device, state);
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100158}
159
François Gaffie11d30102018-11-02 16:09:09 +0100160status_t AudioPolicyManager::setDeviceConnectionStateInt(audio_devices_t deviceType,
Eric Laurenta1d525f2015-01-29 13:36:45 -0800161 audio_policy_dev_state_t state,
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100162 const char* device_address,
163 const char* device_name,
164 audio_format_t encodedFormat) {
Atneya Nair638a6e42022-12-18 16:45:15 -0800165 media::AudioPortFw aidlPort;
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100166 if (status_t status = deviceToAudioPort(deviceType, device_address, device_name, &aidlPort);
167 status == OK) {
168 return setDeviceConnectionStateInt(state, aidlPort.hal, encodedFormat);
169 } else {
170 ALOGE("Failed to convert to AudioPort Parcelable: %s", statusToString(status).c_str());
171 return status;
172 }
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700173}
Paul McLeane743a472015-01-28 11:07:31 -0800174
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700175status_t AudioPolicyManager::setDeviceConnectionStateInt(const sp<DeviceDescriptor> &device,
176 audio_policy_dev_state_t state)
177{
Eric Laurente552edb2014-03-10 17:42:56 -0700178 // handle output devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700179 if (audio_is_output_device(device->type())) {
Eric Laurentd4692962014-05-05 18:13:44 -0700180 SortedVector <audio_io_handle_t> outputs;
181
François Gaffie11d30102018-11-02 16:09:09 +0100182 ssize_t index = mAvailableOutputDevices.indexOf(device);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700183
Eric Laurente552edb2014-03-10 17:42:56 -0700184 // save a copy of the opened output descriptors before any output is opened or closed
185 // by checkOutputsForDevice(). This will be needed by checkOutputForAllStrategies()
186 mPreviousOutputs = mOutputs;
Eric Laurent96d1dda2022-03-14 17:14:19 +0100187
188 bool wasLeUnicastActive = isLeUnicastActive();
189
Eric Laurente552edb2014-03-10 17:42:56 -0700190 switch (state)
191 {
192 // handle output device connection
Eric Laurent3ae5f312015-02-03 17:12:08 -0800193 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700194 if (index >= 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100195 ALOGW("%s() device already connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700196 return INVALID_OPERATION;
197 }
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800198 ALOGV("%s() connecting device %s format %x",
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700199 __func__, device->toString().c_str(), device->getEncodedFormat());
Eric Laurente552edb2014-03-10 17:42:56 -0700200
Eric Laurente552edb2014-03-10 17:42:56 -0700201 // register new device as available
Francois Gaffie993f3902019-04-10 15:39:27 +0200202 if (mAvailableOutputDevices.add(device) < 0) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700203 return NO_MEMORY;
Eric Laurente552edb2014-03-10 17:42:56 -0700204 }
205
François Gaffie44481e72016-04-20 07:49:57 +0200206 // Before checking outputs, broadcast connect event to allow HAL to retrieve dynamic
207 // parameters on newly connected devices (instead of opening the outputs...)
jiabinc0048632023-04-27 22:04:31 +0000208 broadcastDeviceConnectionState(device, media::DeviceConnectedState::CONNECTED);
François Gaffie44481e72016-04-20 07:49:57 +0200209
François Gaffie11d30102018-11-02 16:09:09 +0100210 if (checkOutputsForDevice(device, state, outputs) != NO_ERROR) {
211 mAvailableOutputDevices.remove(device);
François Gaffie44481e72016-04-20 07:49:57 +0200212
Francois Gaffie716e1432019-01-14 16:58:59 +0100213 mHwModules.cleanUpForDevice(device);
214
jiabinc0048632023-04-27 22:04:31 +0000215 broadcastDeviceConnectionState(device, media::DeviceConnectedState::DISCONNECTED);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700216 return INVALID_OPERATION;
217 }
François Gaffie2110e042015-03-24 08:41:51 +0100218
jiabin1c4794b2020-05-05 10:08:05 -0700219 // Populate encapsulation information when a output device is connected.
220 device->setEncapsulationInfoFromHal(mpClientInterface);
221
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700222 // outputs should never be empty here
223 ALOG_ASSERT(outputs.size() != 0, "setDeviceConnectionState():"
224 "checkOutputsForDevice() returned no outputs but status OK");
François Gaffie11d30102018-11-02 16:09:09 +0100225 ALOGV("%s() checkOutputsForDevice() returned %zu outputs", __func__, outputs.size());
Eric Laurent3ae5f312015-02-03 17:12:08 -0800226
Eric Laurent3ae5f312015-02-03 17:12:08 -0800227 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700228 // handle output device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700229 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700230 if (index < 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100231 ALOGW("%s() device not connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700232 return INVALID_OPERATION;
233 }
234
François Gaffie11d30102018-11-02 16:09:09 +0100235 ALOGV("%s() disconnecting output device %s", __func__, device->toString().c_str());
Paul McLean5c477aa2014-08-20 16:47:57 -0700236
jiabinc0048632023-04-27 22:04:31 +0000237 // Notify the HAL to prepare to disconnect device
238 broadcastDeviceConnectionState(
239 device, media::DeviceConnectedState::PREPARE_TO_DISCONNECT);
Paul McLean5c477aa2014-08-20 16:47:57 -0700240
Eric Laurente552edb2014-03-10 17:42:56 -0700241 // remove device from available output devices
François Gaffie11d30102018-11-02 16:09:09 +0100242 mAvailableOutputDevices.remove(device);
Eric Laurente552edb2014-03-10 17:42:56 -0700243
Francois Gaffieba2cf0f2018-12-12 16:40:25 +0100244 mOutputs.clearSessionRoutesForDevice(device);
245
François Gaffie11d30102018-11-02 16:09:09 +0100246 checkOutputsForDevice(device, state, outputs);
François Gaffie2110e042015-03-24 08:41:51 +0100247
jiabinc0048632023-04-27 22:04:31 +0000248 // Send Disconnect to HALs
249 broadcastDeviceConnectionState(device, media::DeviceConnectedState::DISCONNECTED);
250
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800251 // Reset active device codec
252 device->setEncodedFormat(AUDIO_FORMAT_DEFAULT);
253
Kriti Dangef6be8f2020-11-05 11:58:19 +0100254 // remove device from mReportedFormatsMap cache
255 mReportedFormatsMap.erase(device);
256
jiabina84c3d32022-12-02 18:59:55 +0000257 // remove preferred mixer configurations
258 mPreferredMixerAttrInfos.erase(device->getId());
259
Eric Laurente552edb2014-03-10 17:42:56 -0700260 } break;
261
262 default:
François Gaffie11d30102018-11-02 16:09:09 +0100263 ALOGE("%s() invalid state: %x", __func__, state);
Eric Laurente552edb2014-03-10 17:42:56 -0700264 return BAD_VALUE;
265 }
266
Eric Laurent736a1022019-03-27 18:28:46 -0700267 // Propagate device availability to Engine
268 setEngineDeviceConnectionState(device, state);
269
Eric Laurentae970022019-01-29 14:25:04 -0800270 // No need to evaluate playback routing when connecting a remote submix
271 // output device used by a dynamic policy of type recorder as no
272 // playback use case is affected.
273 bool doCheckForDeviceAndOutputChanges = true;
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700274 if (device->type() == AUDIO_DEVICE_OUT_REMOTE_SUBMIX && device->address() != "0") {
Eric Laurentae970022019-01-29 14:25:04 -0800275 for (audio_io_handle_t output : outputs) {
276 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
Mikhail Naganovbfac5832019-03-05 16:55:28 -0800277 sp<AudioPolicyMix> policyMix = desc->mPolicyMix.promote();
278 if (policyMix != nullptr
279 && policyMix->mMixType == MIX_TYPE_RECORDERS
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700280 && device->address() == policyMix->mDeviceAddress.string()) {
Eric Laurentae970022019-01-29 14:25:04 -0800281 doCheckForDeviceAndOutputChanges = false;
282 break;
283 }
284 }
285 }
286
287 auto checkCloseOutputs = [&]() {
Mikhail Naganov37977152018-07-11 15:54:44 -0700288 // outputs must be closed after checkOutputForAllStrategies() is executed
289 if (!outputs.isEmpty()) {
290 for (audio_io_handle_t output : outputs) {
291 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
François Gaffie11d30102018-11-02 16:09:09 +0100292 // close unused outputs after device disconnection or direct outputs that have
293 // been opened by checkOutputsForDevice() to query dynamic parameters
Eric Laurente191d1b2022-04-15 11:59:25 +0200294 // "outputs" vector never contains duplicated outputs
Eric Laurentcad6c0d2021-07-13 15:12:39 +0200295 if ((state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE)
296 || (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != 0) &&
Eric Laurente191d1b2022-04-15 11:59:25 +0200297 (desc->mDirectOpenCount == 0))
298 || (((desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0) &&
299 !isOutputOnlyAvailableRouteToSomeDevice(desc))) {
Francois Gaffieff1eb522020-05-06 18:37:04 +0200300 clearAudioSourcesForOutput(output);
Mikhail Naganov37977152018-07-11 15:54:44 -0700301 closeOutput(output);
302 }
Eric Laurente552edb2014-03-10 17:42:56 -0700303 }
Mikhail Naganov37977152018-07-11 15:54:44 -0700304 // check A2DP again after closing A2DP output to reset mA2dpSuspended if needed
305 return true;
Eric Laurente552edb2014-03-10 17:42:56 -0700306 }
Mikhail Naganov37977152018-07-11 15:54:44 -0700307 return false;
Eric Laurentae970022019-01-29 14:25:04 -0800308 };
309
310 if (doCheckForDeviceAndOutputChanges) {
311 checkForDeviceAndOutputChanges(checkCloseOutputs);
312 } else {
313 checkCloseOutputs();
314 }
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100315 (void)updateCallRouting(false /*fromCache*/);
François Gaffie11d30102018-11-02 16:09:09 +0100316 const DeviceVector msdOutDevices = getMsdAudioOutDevices();
jiabinbce0c1d2020-10-05 11:20:18 -0700317 const DeviceVector activeMediaDevices =
318 mEngine->getActiveMediaDevices(mAvailableOutputDevices);
jiabin3ff8d7d2022-12-13 06:27:44 +0000319 std::map<audio_io_handle_t, DeviceVector> outputsToReopenWithDevices;
Eric Laurente552edb2014-03-10 17:42:56 -0700320 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700321 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Jaideep Sharma89b5b852020-11-23 16:41:33 +0530322 if (desc->isActive() && ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) ||
323 (desc != mPrimaryOutput))) {
François Gaffie11d30102018-11-02 16:09:09 +0100324 DeviceVector newDevices = getNewOutputDevices(desc, true /*fromCache*/);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700325 // do not force device change on duplicated output because if device is 0, it will
326 // also force a device 0 for the two outputs it is duplicated to which may override
327 // a valid device selection on those outputs.
François Gaffie11d30102018-11-02 16:09:09 +0100328 bool force = (msdOutDevices.isEmpty() || msdOutDevices != desc->devices())
Mikhail Naganov15be9d22017-11-08 14:18:13 +1100329 && !desc->isDuplicated()
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700330 && (!device_distinguishes_on_address(device->type())
Eric Laurentc2730ba2014-07-20 15:47:07 -0700331 // always force when disconnecting (a non-duplicated device)
332 || (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE));
jiabin3ff8d7d2022-12-13 06:27:44 +0000333 if (desc->mUsePreferredMixerAttributes && newDevices != desc->devices()) {
334 // If the device is using preferred mixer attributes, the output need to reopen
335 // with default configuration when the new selected devices are different from
336 // current routing devices
337 outputsToReopenWithDevices.emplace(mOutputs.keyAt(i), newDevices);
338 continue;
339 }
François Gaffie11d30102018-11-02 16:09:09 +0100340 setOutputDevices(desc, newDevices, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700341 }
jiabinbce0c1d2020-10-05 11:20:18 -0700342 if (!desc->isDuplicated() && desc->mProfile->hasDynamicAudioProfile() &&
jiabin498d2152021-04-02 00:26:46 +0000343 !activeMediaDevices.empty() && desc->devices() != activeMediaDevices &&
jiabinbce0c1d2020-10-05 11:20:18 -0700344 desc->supportsDevicesForPlayback(activeMediaDevices)) {
345 // Reopen the output to query the dynamic profiles when there is not active
346 // clients or all active clients will be rerouted. Otherwise, set the flag
347 // `mPendingReopenToQueryProfiles` in the SwOutputDescriptor so that the output
348 // can be reopened to query dynamic profiles when all clients are inactive.
349 if (areAllActiveTracksRerouted(desc)) {
jiabin3ff8d7d2022-12-13 06:27:44 +0000350 outputsToReopenWithDevices.emplace(mOutputs.keyAt(i), activeMediaDevices);
jiabinbce0c1d2020-10-05 11:20:18 -0700351 } else {
352 desc->mPendingReopenToQueryProfiles = true;
353 }
354 }
355 if (!desc->supportsDevicesForPlayback(activeMediaDevices)) {
356 // Clear the flag that previously set for re-querying profiles.
357 desc->mPendingReopenToQueryProfiles = false;
358 }
359 }
jiabin3ff8d7d2022-12-13 06:27:44 +0000360 reopenOutputsWithDevices(outputsToReopenWithDevices);
Eric Laurente552edb2014-03-10 17:42:56 -0700361
Eric Laurentd60560a2015-04-10 11:31:20 -0700362 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
François Gaffie11d30102018-11-02 16:09:09 +0100363 cleanUpForDevice(device);
Eric Laurentd60560a2015-04-10 11:31:20 -0700364 }
365
Eric Laurent96d1dda2022-03-14 17:14:19 +0100366 checkLeBroadcastRoutes(wasLeUnicastActive, nullptr, 0);
367
Eric Laurent72aa32f2014-05-30 18:51:48 -0700368 mpClientInterface->onAudioPortListUpdate();
Eric Laurentb71e58b2014-05-29 16:08:11 -0700369 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700370 } // end if is output device
371
Eric Laurente552edb2014-03-10 17:42:56 -0700372 // handle input devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700373 if (audio_is_input_device(device->type())) {
François Gaffie11d30102018-11-02 16:09:09 +0100374 ssize_t index = mAvailableInputDevices.indexOf(device);
Eric Laurente552edb2014-03-10 17:42:56 -0700375 switch (state)
376 {
377 // handle input device connection
Eric Laurent3b73df72014-03-11 09:06:29 -0700378 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700379 if (index >= 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100380 ALOGW("%s() device already connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700381 return INVALID_OPERATION;
382 }
Eric Laurent0dd51852019-04-19 18:18:58 -0700383
384 if (mAvailableInputDevices.add(device) < 0) {
385 return NO_MEMORY;
386 }
387
François Gaffie44481e72016-04-20 07:49:57 +0200388 // Before checking intputs, broadcast connect event to allow HAL to retrieve dynamic
389 // parameters on newly connected devices (instead of opening the inputs...)
jiabinc0048632023-04-27 22:04:31 +0000390 broadcastDeviceConnectionState(device, media::DeviceConnectedState::CONNECTED);
François Gaffie44481e72016-04-20 07:49:57 +0200391
Eric Laurent0dd51852019-04-19 18:18:58 -0700392 if (checkInputsForDevice(device, state) != NO_ERROR) {
393 mAvailableInputDevices.remove(device);
394
jiabinc0048632023-04-27 22:04:31 +0000395 broadcastDeviceConnectionState(device, media::DeviceConnectedState::DISCONNECTED);
Francois Gaffie716e1432019-01-14 16:58:59 +0100396
397 mHwModules.cleanUpForDevice(device);
398
Eric Laurentd4692962014-05-05 18:13:44 -0700399 return INVALID_OPERATION;
400 }
401
Eric Laurentd4692962014-05-05 18:13:44 -0700402 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700403
404 // handle input device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700405 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700406 if (index < 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100407 ALOGW("%s() device not connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700408 return INVALID_OPERATION;
409 }
Paul McLean5c477aa2014-08-20 16:47:57 -0700410
François Gaffie11d30102018-11-02 16:09:09 +0100411 ALOGV("%s() disconnecting input device %s", __func__, device->toString().c_str());
Paul McLean5c477aa2014-08-20 16:47:57 -0700412
jiabinc0048632023-04-27 22:04:31 +0000413 // Notify the HAL to prepare to disconnect device
414 broadcastDeviceConnectionState(
415 device, media::DeviceConnectedState::PREPARE_TO_DISCONNECT);
Paul McLean5c477aa2014-08-20 16:47:57 -0700416
François Gaffie11d30102018-11-02 16:09:09 +0100417 mAvailableInputDevices.remove(device);
Eric Laurent0dd51852019-04-19 18:18:58 -0700418
419 checkInputsForDevice(device, state);
Kriti Dangef6be8f2020-11-05 11:58:19 +0100420
jiabinc0048632023-04-27 22:04:31 +0000421 // Set Disconnect to HALs
422 broadcastDeviceConnectionState(device, media::DeviceConnectedState::DISCONNECTED);
423
Kriti Dangef6be8f2020-11-05 11:58:19 +0100424 // remove device from mReportedFormatsMap cache
425 mReportedFormatsMap.erase(device);
Eric Laurentd4692962014-05-05 18:13:44 -0700426 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700427
428 default:
François Gaffie11d30102018-11-02 16:09:09 +0100429 ALOGE("%s() invalid state: %x", __func__, state);
Eric Laurente552edb2014-03-10 17:42:56 -0700430 return BAD_VALUE;
431 }
432
Eric Laurent736a1022019-03-27 18:28:46 -0700433 // Propagate device availability to Engine
434 setEngineDeviceConnectionState(device, state);
435
Eric Laurent0dd51852019-04-19 18:18:58 -0700436 checkCloseInputs();
Eric Laurent5f5fca52016-08-04 11:48:57 -0700437 // As the input device list can impact the output device selection, update
438 // getDeviceForStrategy() cache
439 updateDevicesAndOutputs();
Eric Laurente552edb2014-03-10 17:42:56 -0700440
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100441 (void)updateCallRouting(false /*fromCache*/);
Francois Gaffiea0e5c992020-09-29 16:05:07 +0200442 // Reconnect Audio Source
443 for (const auto &strategy : mEngine->getOrderedProductStrategies()) {
444 auto attributes = mEngine->getAllAttributesForProductStrategy(strategy).front();
445 checkAudioSourceForAttributes(attributes);
446 }
Eric Laurentd60560a2015-04-10 11:31:20 -0700447 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
François Gaffie11d30102018-11-02 16:09:09 +0100448 cleanUpForDevice(device);
Eric Laurentd60560a2015-04-10 11:31:20 -0700449 }
450
Eric Laurentb52c1522014-05-20 11:27:36 -0700451 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -0700452 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700453 } // end if is input device
Eric Laurente552edb2014-03-10 17:42:56 -0700454
François Gaffie11d30102018-11-02 16:09:09 +0100455 ALOGW("%s() invalid device: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700456 return BAD_VALUE;
457}
458
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100459status_t AudioPolicyManager::deviceToAudioPort(audio_devices_t device, const char* device_address,
460 const char* device_name,
Atneya Nair638a6e42022-12-18 16:45:15 -0800461 media::AudioPortFw* aidlPort) {
Andy Hung5b9a6112023-08-09 19:56:57 -0700462 const auto devDescr = sp<DeviceDescriptorBase>::make(device, device_address);
463 devDescr->setName(device_name);
464 return devDescr->writeToParcelable(aidlPort);
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100465}
466
Eric Laurent736a1022019-03-27 18:28:46 -0700467void AudioPolicyManager::setEngineDeviceConnectionState(const sp<DeviceDescriptor> device,
468 audio_policy_dev_state_t state) {
469
470 // the Engine does not have to know about remote submix devices used by dynamic audio policies
471 if (audio_is_remote_submix_device(device->type()) && device->address() != "0") {
472 return;
473 }
474 mEngine->setDeviceConnectionState(device, state);
475}
476
477
Eric Laurente0720872014-03-11 09:30:41 -0700478audio_policy_dev_state_t AudioPolicyManager::getDeviceConnectionState(audio_devices_t device,
François Gaffie53615e22015-03-19 09:24:12 +0100479 const char *device_address)
Eric Laurente552edb2014-03-10 17:42:56 -0700480{
Eric Laurent634b7142016-04-20 13:48:02 -0700481 sp<DeviceDescriptor> devDesc =
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800482 mHwModules.getDeviceDescriptor(device, device_address, "", AUDIO_FORMAT_DEFAULT,
483 false /* allowToCreate */,
Eric Laurent634b7142016-04-20 13:48:02 -0700484 (strlen(device_address) != 0)/*matchAddress*/);
485
486 if (devDesc == 0) {
François Gaffie251c7f02018-11-07 10:41:08 +0100487 ALOGV("getDeviceConnectionState() undeclared device, type %08x, address: %s",
Eric Laurent634b7142016-04-20 13:48:02 -0700488 device, device_address);
489 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
490 }
François Gaffie53615e22015-03-19 09:24:12 +0100491
Eric Laurent3a4311c2014-03-17 12:00:47 -0700492 DeviceVector *deviceVector;
493
Eric Laurente552edb2014-03-10 17:42:56 -0700494 if (audio_is_output_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700495 deviceVector = &mAvailableOutputDevices;
Eric Laurente552edb2014-03-10 17:42:56 -0700496 } else if (audio_is_input_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700497 deviceVector = &mAvailableInputDevices;
498 } else {
François Gaffie11d30102018-11-02 16:09:09 +0100499 ALOGW("%s() invalid device type %08x", __func__, device);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700500 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurente552edb2014-03-10 17:42:56 -0700501 }
Eric Laurent634b7142016-04-20 13:48:02 -0700502
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800503 return (deviceVector->getDevice(
504 device, String8(device_address), AUDIO_FORMAT_DEFAULT) != 0) ?
Eric Laurent634b7142016-04-20 13:48:02 -0700505 AUDIO_POLICY_DEVICE_STATE_AVAILABLE : AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurenta1d525f2015-01-29 13:36:45 -0800506}
507
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800508status_t AudioPolicyManager::handleDeviceConfigChange(audio_devices_t device,
509 const char *device_address,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800510 const char *device_name,
511 audio_format_t encodedFormat)
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800512{
513 status_t status;
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700514 String8 reply;
515 AudioParameter param;
516 int isReconfigA2dpSupported = 0;
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800517
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800518 ALOGV("handleDeviceConfigChange(() device: 0x%X, address %s name %s encodedFormat: 0x%X",
519 device, device_address, device_name, encodedFormat);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800520
Pavlin Radoslavovc694ff42017-01-09 23:27:29 -0800521 // connect/disconnect only 1 device at a time
522 if (!audio_is_output_device(device) && !audio_is_input_device(device)) return BAD_VALUE;
523
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800524 // Check if the device is currently connected
jiabin9a3361e2019-10-01 09:38:30 -0700525 DeviceVector deviceList = mAvailableOutputDevices.getDevicesFromType(device);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800526 if (deviceList.empty()) {
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800527 // Nothing to do: device is not connected
528 return NO_ERROR;
529 }
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800530 sp<DeviceDescriptor> devDesc = deviceList.itemAt(0);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800531
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700532 // For offloaded A2DP, Hw modules may have the capability to
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800533 // configure codecs.
534 // Handle two specific cases by sending a set parameter to
535 // configure A2DP codecs. No need to toggle device state.
536 // Case 1: A2DP active device switches from primary to primary
537 // module
538 // Case 2: A2DP device config changes on primary module.
Francois Gaffiebce7cd42020-10-14 16:13:20 +0200539 if (audio_is_a2dp_out_device(device) && hasPrimaryOutput()) {
jiabin9a3361e2019-10-01 09:38:30 -0700540 sp<HwModule> module = mHwModules.getModuleForDeviceType(device, encodedFormat);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800541 audio_module_handle_t primaryHandle = mPrimaryOutput->getModuleHandle();
542 if (availablePrimaryOutputDevices().contains(devDesc) &&
543 (module != 0 && module->getHandle() == primaryHandle)) {
544 reply = mpClientInterface->getParameters(
545 AUDIO_IO_HANDLE_NONE,
546 String8(AudioParameter::keyReconfigA2dpSupported));
547 AudioParameter repliedParameters(reply);
548 repliedParameters.getInt(
549 String8(AudioParameter::keyReconfigA2dpSupported), isReconfigA2dpSupported);
550 if (isReconfigA2dpSupported) {
551 const String8 key(AudioParameter::keyReconfigA2dp);
552 param.add(key, String8("true"));
553 mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString());
554 devDesc->setEncodedFormat(encodedFormat);
555 return NO_ERROR;
556 }
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700557 }
558 }
cnx421bd2dcc42020-07-11 14:58:44 +0800559 auto musicStrategy = streamToStrategy(AUDIO_STREAM_MUSIC);
560 for (size_t i = 0; i < mOutputs.size(); i++) {
561 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
562 // mute media strategies and delay device switch by the largest
563 // This avoid sending the music tail into the earpiece or headset.
564 setStrategyMute(musicStrategy, true, desc);
565 setStrategyMute(musicStrategy, false, desc, MUTE_TIME_MS,
566 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
567 nullptr, true /*fromCache*/).types());
568 }
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800569 // Toggle the device state: UNAVAILABLE -> AVAILABLE
570 // This will force reading again the device configuration
571 status = setDeviceConnectionState(device,
572 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800573 device_address, device_name,
574 devDesc->getEncodedFormat());
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800575 if (status != NO_ERROR) {
576 ALOGW("handleDeviceConfigChange() error disabling connection state: %d",
577 status);
578 return status;
579 }
580
581 status = setDeviceConnectionState(device,
582 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800583 device_address, device_name, encodedFormat);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800584 if (status != NO_ERROR) {
585 ALOGW("handleDeviceConfigChange() error enabling connection state: %d",
586 status);
587 return status;
588 }
589
590 return NO_ERROR;
591}
592
Pattydd807582021-11-04 21:01:03 +0800593status_t AudioPolicyManager::getHwOffloadFormatsSupportedForBluetoothMedia(
594 audio_devices_t device, std::vector<audio_format_t> *formats)
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800595{
Pattydd807582021-11-04 21:01:03 +0800596 ALOGV("getHwOffloadFormatsSupportedForBluetoothMedia()");
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800597 status_t status = NO_ERROR;
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800598 std::unordered_set<audio_format_t> formatSet;
599 sp<HwModule> primaryModule =
600 mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_PRIMARY);
Aniket Kumar Latafedb5982019-07-03 11:20:36 -0700601 if (primaryModule == nullptr) {
602 ALOGE("%s() unable to get primary module", __func__);
603 return NO_INIT;
604 }
Pattydd807582021-11-04 21:01:03 +0800605
606 DeviceTypeSet audioDeviceSet;
607
608 switch(device) {
609 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP:
610 audioDeviceSet = getAudioDeviceOutAllA2dpSet();
611 break;
612 case AUDIO_DEVICE_OUT_BLE_HEADSET:
Patty Huang36028df2022-07-06 00:14:12 +0800613 audioDeviceSet = getAudioDeviceOutLeAudioUnicastSet();
614 break;
615 case AUDIO_DEVICE_OUT_BLE_BROADCAST:
616 audioDeviceSet = getAudioDeviceOutLeAudioBroadcastSet();
Pattydd807582021-11-04 21:01:03 +0800617 break;
618 default:
619 ALOGE("%s() device type 0x%08x not supported", __func__, device);
620 return BAD_VALUE;
621 }
622
jiabin9a3361e2019-10-01 09:38:30 -0700623 DeviceVector declaredDevices = primaryModule->getDeclaredDevices().getDevicesFromTypes(
Pattydd807582021-11-04 21:01:03 +0800624 audioDeviceSet);
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800625 for (const auto& device : declaredDevices) {
626 formatSet.insert(device->encodedFormats().begin(), device->encodedFormats().end());
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800627 }
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800628 formats->assign(formatSet.begin(), formatSet.end());
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800629 return status;
630}
631
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100632DeviceVector AudioPolicyManager::selectBestRxSinkDevicesForCall(bool fromCache)
633{
634 DeviceVector rxSinkdevices{};
635 rxSinkdevices = mEngine->getOutputDevicesForAttributes(
636 attributes_initializer(AUDIO_USAGE_VOICE_COMMUNICATION), nullptr, fromCache);
637 if (!rxSinkdevices.isEmpty() && mAvailableOutputDevices.contains(rxSinkdevices.itemAt(0))) {
638 auto rxSinkDevice = rxSinkdevices.itemAt(0);
639 auto telephonyRxModule = mHwModules.getModuleForDeviceType(
640 AUDIO_DEVICE_IN_TELEPHONY_RX, AUDIO_FORMAT_DEFAULT);
641 // retrieve Rx Source device descriptor
642 sp<DeviceDescriptor> rxSourceDevice = mAvailableInputDevices.getDevice(
643 AUDIO_DEVICE_IN_TELEPHONY_RX, String8(), AUDIO_FORMAT_DEFAULT);
644
645 // RX Telephony and Rx sink devices are declared by Primary Audio HAL
646 if (isPrimaryModule(telephonyRxModule) && (telephonyRxModule->getHalVersionMajor() >= 3) &&
647 telephonyRxModule->supportsPatch(rxSourceDevice, rxSinkDevice)) {
648 ALOGW("%s() device %s using HW Bridge", __func__, rxSinkDevice->toString().c_str());
649 return DeviceVector(rxSinkDevice);
650 }
651 }
652 // Note that despite the fact that getNewOutputDevices() is called on the primary output,
653 // the device returned is not necessarily reachable via this output
654 // (filter later by setOutputDevices())
655 return getNewOutputDevices(mPrimaryOutput, fromCache);
656}
657
658status_t AudioPolicyManager::updateCallRouting(bool fromCache, uint32_t delayMs, uint32_t *waitMs)
659{
660 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL && hasPrimaryOutput()) {
661 DeviceVector rxDevices = selectBestRxSinkDevicesForCall(fromCache);
662 return updateCallRoutingInternal(rxDevices, delayMs, waitMs);
663 }
664 return INVALID_OPERATION;
665}
666
667status_t AudioPolicyManager::updateCallRoutingInternal(
668 const DeviceVector &rxDevices, uint32_t delayMs, uint32_t *waitMs)
Eric Laurentc2730ba2014-07-20 15:47:07 -0700669{
670 bool createTxPatch = false;
François Gaffie9eb18552018-11-05 10:33:26 +0100671 bool createRxPatch = false;
Eric Laurentdc462862016-07-19 12:29:53 -0700672 uint32_t muteWaitMs = 0;
jiabin9a3361e2019-10-01 09:38:30 -0700673 if(!hasPrimaryOutput() ||
674 mPrimaryOutput->devices().onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_STUB)) {
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100675 return INVALID_OPERATION;
Eric Laurent87ffa392015-05-22 10:32:38 -0700676 }
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100677 ALOG_ASSERT(!rxDevices.isEmpty(), "%s() no selected output device", __func__);
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);
Eric Laurentcedd5b52023-03-22 00:03:31 +0000681 if (txSourceDevice == nullptr) {
682 ALOGE("%s() selected input device not available", __func__);
683 return INVALID_OPERATION;
684 }
François Gaffiec005e562018-11-06 15:04:49 +0100685
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100686 ALOGV("%s device rxDevice %s txDevice %s", __func__,
François Gaffie9eb18552018-11-05 10:33:26 +0100687 rxDevices.itemAt(0)->toString().c_str(), txSourceDevice->toString().c_str());
Eric Laurentc2730ba2014-07-20 15:47:07 -0700688
Francois Gaffie601801d2021-06-22 13:27:39 +0200689 disconnectTelephonyAudioSource(mCallRxSourceClient);
690 disconnectTelephonyAudioSource(mCallTxSourceClient);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700691
François Gaffie9eb18552018-11-05 10:33:26 +0100692 auto telephonyRxModule =
jiabin9a3361e2019-10-01 09:38:30 -0700693 mHwModules.getModuleForDeviceType(AUDIO_DEVICE_IN_TELEPHONY_RX, AUDIO_FORMAT_DEFAULT);
François Gaffie9eb18552018-11-05 10:33:26 +0100694 auto telephonyTxModule =
jiabin9a3361e2019-10-01 09:38:30 -0700695 mHwModules.getModuleForDeviceType(AUDIO_DEVICE_OUT_TELEPHONY_TX, AUDIO_FORMAT_DEFAULT);
François Gaffie9eb18552018-11-05 10:33:26 +0100696 // retrieve Rx Source and Tx Sink device descriptors
697 sp<DeviceDescriptor> rxSourceDevice =
698 mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_TELEPHONY_RX,
699 String8(),
700 AUDIO_FORMAT_DEFAULT);
701 sp<DeviceDescriptor> txSinkDevice =
702 mAvailableOutputDevices.getDevice(AUDIO_DEVICE_OUT_TELEPHONY_TX,
703 String8(),
704 AUDIO_FORMAT_DEFAULT);
705
706 // RX and TX Telephony device are declared by Primary Audio HAL
707 if (isPrimaryModule(telephonyRxModule) && isPrimaryModule(telephonyTxModule) &&
708 (telephonyRxModule->getHalVersionMajor() >= 3)) {
709 if (rxSourceDevice == 0 || txSinkDevice == 0) {
710 // RX / TX Telephony device(s) is(are) not currently available
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100711 ALOGE("%s() no telephony Tx and/or RX device", __func__);
712 return INVALID_OPERATION;
François Gaffie9eb18552018-11-05 10:33:26 +0100713 }
François Gaffieafd4cea2019-11-18 15:50:22 +0100714 // createAudioPatchInternal now supports both HW / SW bridging
715 createRxPatch = true;
716 createTxPatch = true;
François Gaffie9eb18552018-11-05 10:33:26 +0100717 } else {
718 // If the RX device is on the primary HW module, then use legacy routing method for
719 // voice calls via setOutputDevice() on primary output.
720 // Otherwise, create two audio patches for TX and RX path.
721 createRxPatch = !(availablePrimaryOutputDevices().contains(rxDevices.itemAt(0))) &&
722 (rxSourceDevice != 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700723 // If the TX device is also on the primary HW module, setOutputDevice() will take care
724 // of it due to legacy implementation. If not, create a patch.
François Gaffie9eb18552018-11-05 10:33:26 +0100725 createTxPatch = !(availablePrimaryModuleInputDevices().contains(txSourceDevice)) &&
726 (txSinkDevice != 0);
727 }
728 // Use legacy routing method for voice calls via setOutputDevice() on primary output.
729 // Otherwise, create two audio patches for TX and RX path.
730 if (!createRxPatch) {
731 muteWaitMs = setOutputDevices(mPrimaryOutput, rxDevices, true, delayMs);
Eric Laurent8ae73122016-04-12 10:13:29 -0700732 } else { // create RX path audio patch
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200733 connectTelephonyRxAudioSource();
juyuchen2224c5a2019-01-21 12:00:58 +0800734 // If the TX device is on the primary HW module but RX device is
735 // on other HW module, SinkMetaData of telephony input should handle it
736 // assuming the device uses audio HAL V5.0 and above
Eric Laurentc2730ba2014-07-20 15:47:07 -0700737 }
Eric Laurent8ae73122016-04-12 10:13:29 -0700738 if (createTxPatch) { // create TX path audio patch
François Gaffieafd4cea2019-11-18 15:50:22 +0100739 // terminate active capture if on the same HW module as the call TX source device
740 // FIXME: would be better to refine to only inputs whose profile connects to the
741 // call TX device but this information is not in the audio patch and logic here must be
742 // symmetric to the one in startInput()
743 for (const auto& activeDesc : mInputs.getActiveInputs()) {
744 if (activeDesc->hasSameHwModuleAs(txSourceDevice)) {
745 closeActiveClients(activeDesc);
746 }
747 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200748 connectTelephonyTxAudioSource(txSourceDevice, txSinkDevice, delayMs);
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800749 }
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100750 if (waitMs != nullptr) {
751 *waitMs = muteWaitMs;
752 }
753 return NO_ERROR;
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800754}
Eric Laurentc2730ba2014-07-20 15:47:07 -0700755
Mikhail Naganov100f0122018-11-29 11:22:16 -0800756bool AudioPolicyManager::isDeviceOfModule(
757 const sp<DeviceDescriptor>& devDesc, const char *moduleId) const {
758 sp<HwModule> module = mHwModules.getModuleFromName(moduleId);
759 if (module != 0) {
760 return mAvailableOutputDevices.getDevicesFromHwModule(module->getHandle())
761 .indexOf(devDesc) != NAME_NOT_FOUND
762 || mAvailableInputDevices.getDevicesFromHwModule(module->getHandle())
763 .indexOf(devDesc) != NAME_NOT_FOUND;
764 }
765 return false;
766}
767
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200768void AudioPolicyManager::connectTelephonyRxAudioSource()
769{
Francois Gaffie601801d2021-06-22 13:27:39 +0200770 disconnectTelephonyAudioSource(mCallRxSourceClient);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200771 const struct audio_port_config source = {
772 .role = AUDIO_PORT_ROLE_SOURCE, .type = AUDIO_PORT_TYPE_DEVICE,
773 .ext.device.type = AUDIO_DEVICE_IN_TELEPHONY_RX, .ext.device.address = ""
774 };
775 const auto aa = mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL);
Francois Gaffie601801d2021-06-22 13:27:39 +0200776 mCallRxSourceClient = startAudioSourceInternal(&source, &aa, 0/*uid*/);
777 ALOGE_IF(mCallRxSourceClient == nullptr,
778 "%s failed to start Telephony Rx AudioSource", __func__);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200779}
780
Francois Gaffie601801d2021-06-22 13:27:39 +0200781void AudioPolicyManager::disconnectTelephonyAudioSource(sp<SourceClientDescriptor> &clientDesc)
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200782{
Francois Gaffie601801d2021-06-22 13:27:39 +0200783 if (clientDesc == nullptr) {
784 return;
785 }
786 ALOGW_IF(stopAudioSource(clientDesc->portId()) != NO_ERROR,
787 "%s error stopping audio source", __func__);
788 clientDesc.clear();
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200789}
790
791void AudioPolicyManager::connectTelephonyTxAudioSource(
792 const sp<DeviceDescriptor> &srcDevice, const sp<DeviceDescriptor> &sinkDevice,
793 uint32_t delayMs)
794{
Francois Gaffie601801d2021-06-22 13:27:39 +0200795 disconnectTelephonyAudioSource(mCallTxSourceClient);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200796 if (srcDevice == nullptr || sinkDevice == nullptr) {
797 ALOGW("%s could not create patch, invalid sink and/or source device(s)", __func__);
798 return;
799 }
800 PatchBuilder patchBuilder;
801 patchBuilder.addSource(srcDevice).addSink(sinkDevice);
802 ALOGV("%s between source %s and sink %s", __func__,
803 srcDevice->toString().c_str(), sinkDevice->toString().c_str());
Francois Gaffie601801d2021-06-22 13:27:39 +0200804 auto callTxSourceClientPortId = PolicyAudioPort::getNextUniqueId();
Eric Laurent78b07302022-10-07 16:20:34 +0200805 const auto aa = mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL);
806
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200807 struct audio_port_config source = {};
808 srcDevice->toAudioPortConfig(&source);
Francois Gaffie601801d2021-06-22 13:27:39 +0200809 mCallTxSourceClient = new InternalSourceClientDescriptor(
810 callTxSourceClientPortId, mUidCached, aa, source, srcDevice, sinkDevice,
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200811 mCommunnicationStrategy, toVolumeSource(aa));
812 audio_patch_handle_t patchHandle = AUDIO_PATCH_HANDLE_NONE;
813 status_t status = connectAudioSourceToSink(
Francois Gaffie601801d2021-06-22 13:27:39 +0200814 mCallTxSourceClient, sinkDevice, patchBuilder.patch(), patchHandle, mUidCached,
815 delayMs);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200816 ALOGE_IF(status != NO_ERROR, "%s() error %d creating TX audio patch", __func__, status);
817 if (status == NO_ERROR) {
Francois Gaffie601801d2021-06-22 13:27:39 +0200818 mAudioSources.add(callTxSourceClientPortId, mCallTxSourceClient);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200819 }
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200820}
821
Eric Laurente0720872014-03-11 09:30:41 -0700822void AudioPolicyManager::setPhoneState(audio_mode_t state)
Eric Laurente552edb2014-03-10 17:42:56 -0700823{
824 ALOGV("setPhoneState() state %d", state);
François Gaffie2110e042015-03-24 08:41:51 +0100825 // store previous phone state for management of sonification strategy below
826 int oldState = mEngine->getPhoneState();
Eric Laurent96d1dda2022-03-14 17:14:19 +0100827 bool wasLeUnicastActive = isLeUnicastActive();
François Gaffie2110e042015-03-24 08:41:51 +0100828
829 if (mEngine->setPhoneState(state) != NO_ERROR) {
830 ALOGW("setPhoneState() invalid or same state %d", state);
Eric Laurente552edb2014-03-10 17:42:56 -0700831 return;
832 }
François Gaffie2110e042015-03-24 08:41:51 +0100833 /// Opens: can these line be executed after the switch of volume curves???
Eric Laurent63dea1d2015-07-02 17:10:28 -0700834 if (isStateInCall(oldState)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700835 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent63dea1d2015-07-02 17:10:28 -0700836 // force reevaluating accessibility routing when call stops
jiabinc44b3462022-12-08 12:52:31 -0800837 invalidateStreams({AUDIO_STREAM_ACCESSIBILITY});
Eric Laurente552edb2014-03-10 17:42:56 -0700838 }
839
François Gaffie2110e042015-03-24 08:41:51 +0100840 /**
841 * Switching to or from incall state or switching between telephony and VoIP lead to force
842 * routing command.
843 */
Eric Laurent74b71512019-11-06 17:21:57 -0800844 bool force = ((isStateInCall(oldState) != isStateInCall(state))
845 || (isStateInCall(state) && (state != oldState)));
Eric Laurente552edb2014-03-10 17:42:56 -0700846
847 // check for device and output changes triggered by new phone state
Mikhail Naganov37977152018-07-11 15:54:44 -0700848 checkForDeviceAndOutputChanges();
Eric Laurente552edb2014-03-10 17:42:56 -0700849
Eric Laurente552edb2014-03-10 17:42:56 -0700850 int delayMs = 0;
851 if (isStateInCall(state)) {
852 nsecs_t sysTime = systemTime();
François Gaffiec005e562018-11-06 15:04:49 +0100853 auto musicStrategy = streamToStrategy(AUDIO_STREAM_MUSIC);
854 auto sonificationStrategy = streamToStrategy(AUDIO_STREAM_ALARM);
Eric Laurente552edb2014-03-10 17:42:56 -0700855 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700856 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700857 // mute media and sonification strategies and delay device switch by the largest
858 // latency of any output where either strategy is active.
859 // This avoid sending the ring tone or music tail into the earpiece or headset.
François Gaffiec005e562018-11-06 15:04:49 +0100860 if ((desc->isStrategyActive(musicStrategy, SONIFICATION_HEADSET_MUSIC_DELAY, sysTime) ||
861 desc->isStrategyActive(sonificationStrategy, SONIFICATION_HEADSET_MUSIC_DELAY,
862 sysTime)) &&
Eric Laurentc75307b2015-03-17 15:29:32 -0700863 (delayMs < (int)desc->latency()*2)) {
864 delayMs = desc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -0700865 }
François Gaffiec005e562018-11-06 15:04:49 +0100866 setStrategyMute(musicStrategy, true, desc);
867 setStrategyMute(musicStrategy, false, desc, MUTE_TIME_MS,
868 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
869 nullptr, true /*fromCache*/).types());
870 setStrategyMute(sonificationStrategy, true, desc);
871 setStrategyMute(sonificationStrategy, false, desc, MUTE_TIME_MS,
872 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_ALARM),
873 nullptr, true /*fromCache*/).types());
Eric Laurente552edb2014-03-10 17:42:56 -0700874 }
875 }
876
Eric Laurent87ffa392015-05-22 10:32:38 -0700877 if (hasPrimaryOutput()) {
Eric Laurent87ffa392015-05-22 10:32:38 -0700878 if (state == AUDIO_MODE_IN_CALL) {
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100879 (void)updateCallRouting(false /*fromCache*/, delayMs);
Eric Laurent87ffa392015-05-22 10:32:38 -0700880 } else {
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100881 DeviceVector rxDevices = getNewOutputDevices(mPrimaryOutput, false /*fromCache*/);
882 // force routing command to audio hardware when ending call
883 // even if no device change is needed
884 if (isStateInCall(oldState) && rxDevices.isEmpty()) {
885 rxDevices = mPrimaryOutput->devices();
886 }
887 if (oldState == AUDIO_MODE_IN_CALL) {
Francois Gaffie601801d2021-06-22 13:27:39 +0200888 disconnectTelephonyAudioSource(mCallRxSourceClient);
889 disconnectTelephonyAudioSource(mCallTxSourceClient);
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100890 }
François Gaffie11d30102018-11-02 16:09:09 +0100891 setOutputDevices(mPrimaryOutput, rxDevices, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700892 }
Eric Laurentc2730ba2014-07-20 15:47:07 -0700893 }
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700894
jiabin3ff8d7d2022-12-13 06:27:44 +0000895 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700896 // reevaluate routing on all outputs in case tracks have been started during the call
897 for (size_t i = 0; i < mOutputs.size(); i++) {
898 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
François Gaffie11d30102018-11-02 16:09:09 +0100899 DeviceVector newDevices = getNewOutputDevices(desc, true /*fromCache*/);
Francois Gaffie601801d2021-06-22 13:27:39 +0200900 if (state != AUDIO_MODE_IN_CALL || (desc != mPrimaryOutput && !isTelephonyRxOrTx(desc))) {
901 bool forceRouting = !newDevices.isEmpty();
jiabin3ff8d7d2022-12-13 06:27:44 +0000902 if (desc->mUsePreferredMixerAttributes && newDevices != desc->devices()) {
903 // If the device is using preferred mixer attributes, the output need to reopen
904 // with default configuration when the new selected devices are different from
905 // current routing devices.
906 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices);
907 continue;
908 }
Francois Gaffie601801d2021-06-22 13:27:39 +0200909 setOutputDevices(desc, newDevices, forceRouting, 0 /*delayMs*/, nullptr,
910 true /*requiresMuteCheck*/, !forceRouting /*requiresVolumeCheck*/);
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700911 }
912 }
jiabin3ff8d7d2022-12-13 06:27:44 +0000913 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700914
Eric Laurent96d1dda2022-03-14 17:14:19 +0100915 checkLeBroadcastRoutes(wasLeUnicastActive, nullptr, delayMs);
916
Eric Laurente552edb2014-03-10 17:42:56 -0700917 if (isStateInCall(state)) {
918 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent63dea1d2015-07-02 17:10:28 -0700919 // force reevaluating accessibility routing when call starts
jiabinc44b3462022-12-08 12:52:31 -0800920 invalidateStreams({AUDIO_STREAM_ACCESSIBILITY});
Eric Laurente552edb2014-03-10 17:42:56 -0700921 }
922
923 // Flag that ringtone volume must be limited to music volume until we exit MODE_RINGTONE
François Gaffiec005e562018-11-06 15:04:49 +0100924 mLimitRingtoneVolume = (state == AUDIO_MODE_RINGTONE &&
925 isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY));
Eric Laurente552edb2014-03-10 17:42:56 -0700926}
927
Jean-Michel Trivi887a9ed2015-03-31 18:02:24 -0700928audio_mode_t AudioPolicyManager::getPhoneState() {
929 return mEngine->getPhoneState();
930}
931
Eric Laurente0720872014-03-11 09:30:41 -0700932void AudioPolicyManager::setForceUse(audio_policy_force_use_t usage,
François Gaffie11d30102018-11-02 16:09:09 +0100933 audio_policy_forced_cfg_t config)
Eric Laurente552edb2014-03-10 17:42:56 -0700934{
François Gaffie2110e042015-03-24 08:41:51 +0100935 ALOGV("setForceUse() usage %d, config %d, mPhoneState %d", usage, config, mEngine->getPhoneState());
Eric Laurent8dc87a62017-05-16 19:00:40 -0700936 if (config == mEngine->getForceUse(usage)) {
937 return;
938 }
Eric Laurente552edb2014-03-10 17:42:56 -0700939
François Gaffie2110e042015-03-24 08:41:51 +0100940 if (mEngine->setForceUse(usage, config) != NO_ERROR) {
941 ALOGW("setForceUse() could not set force cfg %d for usage %d", config, usage);
942 return;
Eric Laurente552edb2014-03-10 17:42:56 -0700943 }
François Gaffie2110e042015-03-24 08:41:51 +0100944 bool forceVolumeReeval = (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) ||
945 (usage == AUDIO_POLICY_FORCE_FOR_DOCK) ||
946 (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM);
Eric Laurente552edb2014-03-10 17:42:56 -0700947
948 // check for device and output changes triggered by new force usage
Mikhail Naganov37977152018-07-11 15:54:44 -0700949 checkForDeviceAndOutputChanges();
Phil Burk09bc4612016-02-24 15:58:15 -0800950
Eric Laurent22fcda22019-05-17 16:28:47 -0700951 // force client reconnection to reevaluate flag AUDIO_FLAG_AUDIBILITY_ENFORCED
952 if (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM) {
jiabinc44b3462022-12-08 12:52:31 -0800953 invalidateStreams({AUDIO_STREAM_SYSTEM, AUDIO_STREAM_ENFORCED_AUDIBLE});
Eric Laurent22fcda22019-05-17 16:28:47 -0700954 }
955
Eric Laurentdc462862016-07-19 12:29:53 -0700956 //FIXME: workaround for truncated touch sounds
957 // to be removed when the problem is handled by system UI
958 uint32_t delayMs = 0;
Eric Laurentdc462862016-07-19 12:29:53 -0700959 if (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) {
960 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
961 }
Jean-Michel Trivi30857152019-11-01 11:04:15 -0700962
963 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Eric Laurent2517af32020-11-25 15:31:27 +0100964 updateInputRouting();
Eric Laurente552edb2014-03-10 17:42:56 -0700965}
966
Eric Laurente0720872014-03-11 09:30:41 -0700967void AudioPolicyManager::setSystemProperty(const char* property, const char* value)
Eric Laurente552edb2014-03-10 17:42:56 -0700968{
969 ALOGV("setSystemProperty() property %s, value %s", property, value);
970}
971
Dorin Drimusecc9f422022-03-09 17:57:40 +0100972// Find an MSD output profile compatible with the parameters passed.
973// When "directOnly" is set, restrict search to profiles for direct outputs.
974sp<IOProfile> AudioPolicyManager::getMsdProfileForOutput(
975 const DeviceVector& devices,
976 uint32_t samplingRate,
977 audio_format_t format,
978 audio_channel_mask_t channelMask,
979 audio_output_flags_t flags,
980 bool directOnly)
981{
982 flags = getRelevantFlags(flags, directOnly);
983
984 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
985 if (msdModule != nullptr) {
986 // for the msd module check if there are patches to the output devices
987 if (msdHasPatchesToAllDevices(devices.toTypeAddrVector())) {
988 HwModuleCollection modules;
989 modules.add(msdModule);
990 return searchCompatibleProfileHwModules(
991 modules, getMsdAudioOutDevices(), samplingRate, format, channelMask,
992 flags, directOnly);
993 }
994 }
995 return nullptr;
996}
997
Michael Chana94fbb22018-04-24 14:31:19 +1000998// Find an output profile compatible with the parameters passed. When "directOnly" is set, restrict
999// search to profiles for direct outputs.
1000sp<IOProfile> AudioPolicyManager::getProfileForOutput(
François Gaffie11d30102018-11-02 16:09:09 +01001001 const DeviceVector& devices,
Michael Chana94fbb22018-04-24 14:31:19 +10001002 uint32_t samplingRate,
1003 audio_format_t format,
1004 audio_channel_mask_t channelMask,
1005 audio_output_flags_t flags,
1006 bool directOnly)
Eric Laurente552edb2014-03-10 17:42:56 -07001007{
Dorin Drimusecc9f422022-03-09 17:57:40 +01001008 flags = getRelevantFlags(flags, directOnly);
1009
1010 return searchCompatibleProfileHwModules(
1011 mHwModules, devices, samplingRate, format, channelMask, flags, directOnly);
1012}
1013
1014audio_output_flags_t AudioPolicyManager::getRelevantFlags (
1015 audio_output_flags_t flags, bool directOnly) {
Michael Chana94fbb22018-04-24 14:31:19 +10001016 if (directOnly) {
Dorin Drimusecc9f422022-03-09 17:57:40 +01001017 // only retain flags that will drive the direct output profile selection
1018 // if explicitly requested
1019 static const uint32_t kRelevantFlags =
Michael Chana94fbb22018-04-24 14:31:19 +10001020 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD |
Dorin Drimusecc9f422022-03-09 17:57:40 +01001021 AUDIO_OUTPUT_FLAG_VOIP_RX | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ);
1022 flags = (audio_output_flags_t)((flags & kRelevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
Michael Chana94fbb22018-04-24 14:31:19 +10001023 }
Dorin Drimusecc9f422022-03-09 17:57:40 +01001024 return flags;
1025}
Eric Laurent861a6282015-05-18 15:40:16 -07001026
Dorin Drimusecc9f422022-03-09 17:57:40 +01001027sp<IOProfile> AudioPolicyManager::searchCompatibleProfileHwModules (
1028 const HwModuleCollection& hwModules,
1029 const DeviceVector& devices,
1030 uint32_t samplingRate,
1031 audio_format_t format,
1032 audio_channel_mask_t channelMask,
1033 audio_output_flags_t flags,
1034 bool directOnly) {
Eric Laurent861a6282015-05-18 15:40:16 -07001035 sp<IOProfile> profile;
Dorin Drimusecc9f422022-03-09 17:57:40 +01001036 for (const auto& hwModule : hwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08001037 for (const auto& curProfile : hwModule->getOutputProfiles()) {
Dorin Drimusecc9f422022-03-09 17:57:40 +01001038 if (!curProfile->isCompatibleProfile(devices,
1039 samplingRate, NULL /*updatedSamplingRate*/,
1040 format, NULL /*updatedFormat*/,
1041 channelMask, NULL /*updatedChannelMask*/,
1042 flags)) {
1043 continue;
1044 }
1045 // reject profiles not corresponding to a device currently available
1046 if (!mAvailableOutputDevices.containsAtLeastOne(curProfile->getSupportedDevices())) {
1047 continue;
1048 }
1049 // reject profiles if connected device does not support codec
1050 if (!curProfile->devicesSupportEncodedFormats(devices.types())) {
1051 continue;
1052 }
1053 if (!directOnly) {
1054 return curProfile;
1055 }
1056
1057 // when searching for direct outputs, if several profiles are compatible, give priority
1058 // to one with offload capability
Patty Huang36028df2022-07-06 00:14:12 +08001059 if (profile != 0 &&
Dorin Drimusecc9f422022-03-09 17:57:40 +01001060 ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0)) {
Eric Laurent861a6282015-05-18 15:40:16 -07001061 continue;
Dorin Drimusecc9f422022-03-09 17:57:40 +01001062 }
1063 profile = curProfile;
1064 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1065 break;
1066 }
Eric Laurente552edb2014-03-10 17:42:56 -07001067 }
1068 }
Eric Laurent861a6282015-05-18 15:40:16 -07001069 return profile;
Eric Laurente552edb2014-03-10 17:42:56 -07001070}
1071
Eric Laurentfa0f6742021-08-17 18:39:44 +02001072sp<IOProfile> AudioPolicyManager::getSpatializerOutputProfile(
Eric Laurent39095982021-08-24 18:29:27 +02001073 const audio_config_t *config __unused, const AudioDeviceTypeAddrVector &devices) const
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001074{
1075 for (const auto& hwModule : mHwModules) {
1076 for (const auto& curProfile : hwModule->getOutputProfiles()) {
Eric Laurent1c5e2e32021-08-18 18:50:28 +02001077 if (curProfile->getFlags() != AUDIO_OUTPUT_FLAG_SPATIALIZER) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001078 continue;
1079 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001080 if (!devices.empty()) {
Eric Laurent0c8f7cc2022-06-24 14:32:36 +02001081 // reject profiles not corresponding to a device currently available
1082 DeviceVector supportedDevices = curProfile->getSupportedDevices();
1083 if (!mAvailableOutputDevices.containsAtLeastOne(supportedDevices)) {
1084 continue;
1085 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001086 if (supportedDevices.getDevicesFromDeviceTypeAddrVec(devices).size()
1087 != devices.size()) {
1088 continue;
1089 }
1090 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001091 ALOGV("%s found profile %s", __func__, curProfile->getName().c_str());
1092 return curProfile;
1093 }
1094 }
1095 return nullptr;
1096}
1097
Eric Laurentf4e63452017-11-06 19:31:46 +00001098audio_io_handle_t AudioPolicyManager::getOutput(audio_stream_type_t stream)
Eric Laurente552edb2014-03-10 17:42:56 -07001099{
François Gaffiec005e562018-11-06 15:04:49 +01001100 DeviceVector devices = mEngine->getOutputDevicesForStream(stream, false /*fromCache*/);
Andy Hungc9901522017-11-10 20:07:54 -08001101
1102 // Note that related method getOutputForAttr() uses getOutputForDevice() not selectOutput().
1103 // We use selectOutput() here since we don't have the desired AudioTrack sample rate,
1104 // format, flags, etc. This may result in some discrepancy for functions that utilize
1105 // getOutput() solely on audio_stream_type such as AudioSystem::getOutputFrameCount()
1106 // and AudioSystem::getOutputSamplingRate().
1107
François Gaffie11d30102018-11-02 16:09:09 +01001108 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Mingyu Shih75563d32023-05-24 04:47:40 +08001109 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
1110 if (stream == AUDIO_STREAM_MUSIC &&
1111 property_get_bool("audio.deep_buffer.media", false /* default_value */)) {
1112 flags = AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
1113 }
1114 const audio_io_handle_t output = selectOutput(outputs, flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001115
François Gaffie11d30102018-11-02 16:09:09 +01001116 ALOGV("getOutput() stream %d selected devices %s, output %d", stream,
1117 devices.toString().c_str(), output);
Eric Laurentf4e63452017-11-06 19:31:46 +00001118 return output;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001119}
1120
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001121status_t AudioPolicyManager::getAudioAttributes(audio_attributes_t *dstAttr,
1122 const audio_attributes_t *srcAttr,
1123 audio_stream_type_t srcStream)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001124{
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001125 if (srcAttr != NULL) {
1126 if (!isValidAttributes(srcAttr)) {
1127 ALOGE("%s invalid attributes: usage=%d content=%d flags=0x%x tags=[%s]",
1128 __func__,
1129 srcAttr->usage, srcAttr->content_type, srcAttr->flags,
1130 srcAttr->tags);
1131 return BAD_VALUE;
1132 }
1133 *dstAttr = *srcAttr;
1134 } else {
1135 if (srcStream < AUDIO_STREAM_MIN || srcStream >= AUDIO_STREAM_PUBLIC_CNT) {
1136 ALOGE("%s: invalid stream type", __func__);
1137 return BAD_VALUE;
1138 }
François Gaffiec005e562018-11-06 15:04:49 +01001139 *dstAttr = mEngine->getAttributesForStreamType(srcStream);
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001140 }
Eric Laurent22fcda22019-05-17 16:28:47 -07001141
1142 // Only honor audibility enforced when required. The client will be
1143 // forced to reconnect if the forced usage changes.
1144 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Mikhail Naganov55773032020-10-01 15:08:13 -07001145 dstAttr->flags = static_cast<audio_flags_mask_t>(
1146 dstAttr->flags & ~AUDIO_FLAG_AUDIBILITY_ENFORCED);
Eric Laurent22fcda22019-05-17 16:28:47 -07001147 }
1148
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001149 return NO_ERROR;
1150}
1151
Kevin Rocard153f92d2018-12-18 18:33:28 -08001152status_t AudioPolicyManager::getOutputForAttrInt(
1153 audio_attributes_t *resultAttr,
1154 audio_io_handle_t *output,
1155 audio_session_t session,
1156 const audio_attributes_t *attr,
1157 audio_stream_type_t *stream,
1158 uid_t uid,
jiabinf1c73972022-04-14 16:28:52 -07001159 audio_config_t *config,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001160 audio_output_flags_t *flags,
1161 audio_port_handle_t *selectedDeviceId,
1162 bool *isRequestedDeviceForExclusiveUse,
Eric Laurentc529cf62020-04-17 18:19:10 -07001163 std::vector<sp<AudioPolicyMix>> *secondaryMixes,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001164 output_type_t *outputType,
jiabinc658e452022-10-21 20:52:21 +00001165 bool *isSpatialized,
1166 bool *isBitPerfect)
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001167{
François Gaffiec005e562018-11-06 15:04:49 +01001168 DeviceVector outputDevices;
Francois Gaffie716e1432019-01-14 16:58:59 +01001169 const audio_port_handle_t requestedPortId = *selectedDeviceId;
François Gaffie11d30102018-11-02 16:09:09 +01001170 DeviceVector msdDevices = getMsdAudioOutDevices();
François Gaffiec005e562018-11-06 15:04:49 +01001171 const sp<DeviceDescriptor> requestedDevice =
1172 mAvailableOutputDevices.getDeviceFromId(requestedPortId);
1173
Eric Laurent8a1095a2019-11-08 14:44:16 -08001174 *outputType = API_OUTPUT_INVALID;
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001175 *isSpatialized = false;
1176
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001177 status_t status = getAudioAttributes(resultAttr, attr, *stream);
1178 if (status != NO_ERROR) {
1179 return status;
Eric Laurent8f42ea12018-08-08 09:08:25 -07001180 }
Kevin Rocardb99cc752019-03-21 20:52:24 -07001181 if (auto it = mAllowedCapturePolicies.find(uid); it != end(mAllowedCapturePolicies)) {
Mikhail Naganov55773032020-10-01 15:08:13 -07001182 resultAttr->flags = static_cast<audio_flags_mask_t>(resultAttr->flags | it->second);
Kevin Rocardb99cc752019-03-21 20:52:24 -07001183 }
François Gaffiec005e562018-11-06 15:04:49 +01001184 *stream = mEngine->getStreamTypeForAttributes(*resultAttr);
Eric Laurent8f42ea12018-08-08 09:08:25 -07001185
François Gaffiec005e562018-11-06 15:04:49 +01001186 ALOGV("%s() attributes=%s stream=%s session %d selectedDeviceId %d", __func__,
1187 toString(*resultAttr).c_str(), toString(*stream).c_str(), session, requestedPortId);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001188
Oscar Azucena873d10f2023-01-12 18:34:42 -08001189 bool usePrimaryOutputFromPolicyMixes = false;
1190
Kevin Rocard153f92d2018-12-18 18:33:28 -08001191 // The primary output is the explicit routing (eg. setPreferredDevice) if specified,
1192 // otherwise, fallback to the dynamic policies, if none match, query the engine.
1193 // Secondary outputs are always found by dynamic policies as the engine do not support them
Eric Laurentc529cf62020-04-17 18:19:10 -07001194 sp<AudioPolicyMix> primaryMix;
Dean Wheatleyd082f472022-02-04 11:10:48 +11001195 const audio_config_base_t clientConfig = {.sample_rate = config->sample_rate,
1196 .channel_mask = config->channel_mask,
1197 .format = config->format,
1198 };
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02001199 status = mPolicyMixes.getOutputForAttr(*resultAttr, clientConfig, uid, session, *flags,
Oscar Azucena873d10f2023-01-12 18:34:42 -08001200 mAvailableOutputDevices, requestedDevice, primaryMix,
1201 secondaryMixes, usePrimaryOutputFromPolicyMixes);
Kevin Rocard94114a22019-04-01 19:38:23 -07001202 if (status != OK) {
1203 return status;
Kevin Rocard153f92d2018-12-18 18:33:28 -08001204 }
Kevin Rocard94114a22019-04-01 19:38:23 -07001205
Kevin Rocard153f92d2018-12-18 18:33:28 -08001206 // FIXME: in case of RENDER policy, the output capabilities should be checked
Dean Wheatleyd082f472022-02-04 11:10:48 +11001207 if ((secondaryMixes != nullptr && !secondaryMixes->empty())
1208 && !audio_is_linear_pcm(config->format)) {
1209 ALOGD("%s: rejecting request as secondary mixes only support pcm", __func__);
Kevin Rocard153f92d2018-12-18 18:33:28 -08001210 return BAD_VALUE;
1211 }
1212 if (usePrimaryOutputFromPolicyMixes) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001213 sp<DeviceDescriptor> deviceDesc =
1214 mAvailableOutputDevices.getDevice(primaryMix->mDeviceType,
1215 primaryMix->mDeviceAddress,
1216 AUDIO_FORMAT_DEFAULT);
1217 sp<SwAudioOutputDescriptor> policyDesc = primaryMix->getOutput();
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001218 bool tryDirectForFlags = policyDesc == nullptr ||
1219 (policyDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT);
1220 // if a direct output can be opened to deliver the track's multi-channel content to the
1221 // output rather than being downmixed by the primary output, then use this direct
1222 // output by by-passing the primary mix if possible, otherwise fall-through to primary
1223 // mix.
1224 bool tryDirectForChannelMask = policyDesc != nullptr
1225 && (audio_channel_count_from_out_mask(policyDesc->getConfig().channel_mask) <
1226 audio_channel_count_from_out_mask(config->channel_mask));
1227 if (deviceDesc != nullptr && (tryDirectForFlags || tryDirectForChannelMask)) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001228 audio_io_handle_t newOutput;
1229 status = openDirectOutput(
1230 *stream, session, config,
1231 (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT),
1232 DeviceVector(deviceDesc), &newOutput);
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001233 if (status == NO_ERROR) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001234 policyDesc = mOutputs.valueFor(newOutput);
1235 primaryMix->setOutput(policyDesc);
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001236 } else if (tryDirectForFlags) {
1237 policyDesc = nullptr;
1238 } // otherwise use primary if available.
Eric Laurentc529cf62020-04-17 18:19:10 -07001239 }
1240 if (policyDesc != nullptr) {
1241 policyDesc->mPolicyMix = primaryMix;
1242 *output = policyDesc->mIoHandle;
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08001243 *selectedDeviceId = deviceDesc != 0 ? deviceDesc->getId() : AUDIO_PORT_HANDLE_NONE;
Eric Laurent8a1095a2019-11-08 14:44:16 -08001244
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08001245 ALOGV("getOutputForAttr() returns output %d", *output);
1246 if (resultAttr->usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
1247 *outputType = API_OUT_MIX_PLAYBACK;
1248 } else {
1249 *outputType = API_OUTPUT_LEGACY;
1250 }
1251 return NO_ERROR;
Eric Laurent8a1095a2019-11-08 14:44:16 -08001252 }
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001253 }
François Gaffiec005e562018-11-06 15:04:49 +01001254 // Virtual sources must always be dynamicaly or explicitly routed
1255 if (resultAttr->usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
1256 ALOGW("getOutputForAttr() no policy mix found for usage AUDIO_USAGE_VIRTUAL_SOURCE");
1257 return BAD_VALUE;
1258 }
1259 // explicit routing managed by getDeviceForStrategy in APM is now handled by engine
1260 // in order to let the choice of the order to future vendor engine
1261 outputDevices = mEngine->getOutputDevicesForAttributes(*resultAttr, requestedDevice, false);
Scott Randolph7b1fd232018-06-18 15:33:03 -07001262
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001263 if ((resultAttr->flags & AUDIO_FLAG_HW_AV_SYNC) != 0) {
Nadav Bar766fb022018-01-07 12:18:03 +02001264 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
Eric Laurent93c3d412014-08-01 14:48:35 -07001265 }
1266
Nadav Barb2f18162018-07-18 13:01:53 +03001267 // Set incall music only if device was explicitly set, and fallback to the device which is
1268 // chosen by the engine if not.
1269 // FIXME: provide a more generic approach which is not device specific and move this back
1270 // to getOutputForDevice.
Nadav Bar20919492018-11-20 10:20:51 +02001271 // TODO: Remove check of AUDIO_STREAM_MUSIC once migration is completed on the app side.
jiabin9a3361e2019-10-01 09:38:30 -07001272 if (outputDevices.onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_TELEPHONY_TX) &&
François Gaffiec005e562018-11-06 15:04:49 +01001273 (*stream == AUDIO_STREAM_MUSIC || resultAttr->usage == AUDIO_USAGE_VOICE_COMMUNICATION) &&
Nadav Barb2f18162018-07-18 13:01:53 +03001274 audio_is_linear_pcm(config->format) &&
Eric Laurent74b71512019-11-06 17:21:57 -08001275 isCallAudioAccessible()) {
Francois Gaffie716e1432019-01-14 16:58:59 +01001276 if (requestedPortId != AUDIO_PORT_HANDLE_NONE) {
Nadav Barb2f18162018-07-18 13:01:53 +03001277 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_INCALL_MUSIC;
François Gaffief579db52018-11-13 11:25:16 +01001278 *isRequestedDeviceForExclusiveUse = true;
Nadav Barb2f18162018-07-18 13:01:53 +03001279 }
1280 }
1281
François Gaffiec005e562018-11-06 15:04:49 +01001282 ALOGV("%s() device %s, sampling rate %d, format %#x, channel mask %#x, flags %#x stream %s",
1283 __func__, outputDevices.toString().c_str(), config->sample_rate, config->format,
1284 config->channel_mask, *flags, toString(*stream).c_str());
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001285
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001286 *output = AUDIO_IO_HANDLE_NONE;
François Gaffie11d30102018-11-02 16:09:09 +01001287 if (!msdDevices.isEmpty()) {
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001288 *output = getOutputForDevices(msdDevices, session, resultAttr, config, flags, isSpatialized);
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001289 if (*output != AUDIO_IO_HANDLE_NONE && setMsdOutputPatches(&outputDevices) == NO_ERROR) {
François Gaffiec005e562018-11-06 15:04:49 +01001290 ALOGV("%s() Using MSD devices %s instead of devices %s",
1291 __func__, msdDevices.toString().c_str(), outputDevices.toString().c_str());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001292 } else {
1293 *output = AUDIO_IO_HANDLE_NONE;
1294 }
1295 }
1296 if (*output == AUDIO_IO_HANDLE_NONE) {
jiabina84c3d32022-12-02 18:59:55 +00001297 sp<PreferredMixerAttributesInfo> info = nullptr;
1298 if (outputDevices.size() == 1) {
1299 info = getPreferredMixerAttributesInfo(
1300 outputDevices.itemAt(0)->getId(),
jiabind9a58d32023-06-01 17:57:30 +00001301 mEngine->getProductStrategyForAttributes(*resultAttr),
1302 true /*activeBitPerfectPreferred*/);
jiabin5eaf0962022-12-20 20:11:38 +00001303 // Only use preferred mixer if the uid matches or the preferred mixer is bit-perfect
1304 // and it is currently active.
1305 if (info != nullptr && info->getUid() != uid &&
1306 ((info->getFlags() & AUDIO_OUTPUT_FLAG_BIT_PERFECT) == AUDIO_OUTPUT_FLAG_NONE ||
1307 info->getActiveClientCount() == 0)) {
jiabina84c3d32022-12-02 18:59:55 +00001308 info = nullptr;
1309 }
1310 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001311 *output = getOutputForDevices(outputDevices, session, resultAttr, config,
jiabina84c3d32022-12-02 18:59:55 +00001312 flags, isSpatialized, info, resultAttr->flags & AUDIO_FLAG_MUTE_HAPTIC);
jiabin5eaf0962022-12-20 20:11:38 +00001313 // The client will be active if the client is currently preferred mixer owner and the
1314 // requested configuration matches the preferred mixer configuration.
jiabinc658e452022-10-21 20:52:21 +00001315 *isBitPerfect = (info != nullptr
1316 && (info->getFlags() & AUDIO_OUTPUT_FLAG_BIT_PERFECT) != AUDIO_OUTPUT_FLAG_NONE
jiabin5eaf0962022-12-20 20:11:38 +00001317 && info->getUid() == uid
1318 && *output != AUDIO_IO_HANDLE_NONE
1319 // When bit-perfect output is selected for the preferred mixer attributes owner,
1320 // only need to consider the config matches.
1321 && mOutputs.valueFor(*output)->isConfigurationMatched(
1322 clientConfig, AUDIO_OUTPUT_FLAG_NONE));
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001323 }
Eric Laurente83b55d2014-11-14 10:06:21 -08001324 if (*output == AUDIO_IO_HANDLE_NONE) {
jiabinf1c73972022-04-14 16:28:52 -07001325 AudioProfileVector profiles;
1326 status_t ret = getProfilesForDevices(outputDevices, profiles, *flags, false /*isInput*/);
1327 if (ret == NO_ERROR && !profiles.empty()) {
Robert Wub98ff1b2023-06-15 22:53:58 +00001328 const auto channels = profiles[0]->getChannels();
1329 if (!channels.empty() && (channels.find(config->channel_mask) == channels.end())) {
1330 config->channel_mask = *channels.begin();
1331 }
1332 const auto sampleRates = profiles[0]->getSampleRates();
1333 if (!sampleRates.empty() &&
1334 (sampleRates.find(config->sample_rate) == sampleRates.end())) {
1335 config->sample_rate = *sampleRates.begin();
1336 }
jiabinf1c73972022-04-14 16:28:52 -07001337 config->format = profiles[0]->getFormat();
1338 }
Eric Laurente83b55d2014-11-14 10:06:21 -08001339 return INVALID_OPERATION;
1340 }
Paul McLeanaa981192015-03-21 09:55:15 -07001341
François Gaffiec005e562018-11-06 15:04:49 +01001342 *selectedDeviceId = getFirstDeviceId(outputDevices);
Michael Chan6fb34492020-12-08 15:44:49 +11001343 for (auto &outputDevice : outputDevices) {
Mikhail Naganov68e3f642023-04-28 13:06:32 -07001344 if (outputDevice->getId() == mConfig->getDefaultOutputDevice()->getId()) {
Michael Chan6fb34492020-12-08 15:44:49 +11001345 *selectedDeviceId = outputDevice->getId();
1346 break;
1347 }
1348 }
Eric Laurent2ac76942017-06-22 17:17:09 -07001349
Eric Laurent8a1095a2019-11-08 14:44:16 -08001350 if (outputDevices.onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_TELEPHONY_TX)) {
1351 *outputType = API_OUTPUT_TELEPHONY_TX;
1352 } else {
1353 *outputType = API_OUTPUT_LEGACY;
1354 }
1355
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001356 ALOGV("%s returns output %d selectedDeviceId %d", __func__, *output, *selectedDeviceId);
1357
1358 return NO_ERROR;
1359}
1360
1361status_t AudioPolicyManager::getOutputForAttr(const audio_attributes_t *attr,
1362 audio_io_handle_t *output,
1363 audio_session_t session,
1364 audio_stream_type_t *stream,
Svet Ganov3e5f14f2021-05-13 22:51:08 +00001365 const AttributionSourceState& attributionSource,
jiabinf1c73972022-04-14 16:28:52 -07001366 audio_config_t *config,
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001367 audio_output_flags_t *flags,
1368 audio_port_handle_t *selectedDeviceId,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001369 audio_port_handle_t *portId,
Eric Laurent8a1095a2019-11-08 14:44:16 -08001370 std::vector<audio_io_handle_t> *secondaryOutputs,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001371 output_type_t *outputType,
jiabinc658e452022-10-21 20:52:21 +00001372 bool *isSpatialized,
1373 bool *isBitPerfect)
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001374{
1375 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
1376 if (*portId != AUDIO_PORT_HANDLE_NONE) {
1377 return INVALID_OPERATION;
1378 }
Philip P. Moltmannbda45752020-07-17 16:41:18 -07001379 const uid_t uid = VALUE_OR_RETURN_STATUS(
Svet Ganov3e5f14f2021-05-13 22:51:08 +00001380 aidl2legacy_int32_t_uid_t(attributionSource.uid));
Francois Gaffie716e1432019-01-14 16:58:59 +01001381 const audio_port_handle_t requestedPortId = *selectedDeviceId;
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001382 audio_attributes_t resultAttr;
François Gaffief579db52018-11-13 11:25:16 +01001383 bool isRequestedDeviceForExclusiveUse = false;
Eric Laurentc529cf62020-04-17 18:19:10 -07001384 std::vector<sp<AudioPolicyMix>> secondaryMixes;
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001385 const sp<DeviceDescriptor> requestedDevice =
1386 mAvailableOutputDevices.getDeviceFromId(requestedPortId);
1387
1388 // Prevent from storing invalid requested device id in clients
1389 const audio_port_handle_t sanitizedRequestedPortId =
1390 requestedDevice != nullptr ? requestedPortId : AUDIO_PORT_HANDLE_NONE;
1391 *selectedDeviceId = sanitizedRequestedPortId;
1392
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001393 status_t status = getOutputForAttrInt(&resultAttr, output, session, attr, stream, uid,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001394 config, flags, selectedDeviceId, &isRequestedDeviceForExclusiveUse,
jiabinc658e452022-10-21 20:52:21 +00001395 secondaryOutputs != nullptr ? &secondaryMixes : nullptr, outputType, isSpatialized,
1396 isBitPerfect);
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001397 if (status != NO_ERROR) {
1398 return status;
1399 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001400 std::vector<wp<SwAudioOutputDescriptor>> weakSecondaryOutputDescs;
Eric Laurentc529cf62020-04-17 18:19:10 -07001401 if (secondaryOutputs != nullptr) {
1402 for (auto &secondaryMix : secondaryMixes) {
1403 sp<SwAudioOutputDescriptor> outputDesc = secondaryMix->getOutput();
1404 if (outputDesc != nullptr &&
1405 outputDesc->mIoHandle != AUDIO_IO_HANDLE_NONE) {
1406 secondaryOutputs->push_back(outputDesc->mIoHandle);
1407 weakSecondaryOutputDescs.push_back(outputDesc);
1408 }
1409 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001410 }
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001411
Eric Laurent8fc147b2018-07-22 19:13:55 -07001412 audio_config_base_t clientConfig = {.sample_rate = config->sample_rate,
Nick Desaulniersa30e3202019-10-18 13:38:23 -07001413 .channel_mask = config->channel_mask,
Eric Laurent8fc147b2018-07-22 19:13:55 -07001414 .format = config->format,
Nick Desaulniersa30e3202019-10-18 13:38:23 -07001415 };
jiabin4ef93452019-09-10 14:29:54 -07001416 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurent8f42ea12018-08-08 09:08:25 -07001417
Eric Laurentc209fe42020-06-05 18:11:23 -07001418 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(*output);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001419 sp<TrackClientDescriptor> clientDesc =
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001420 new TrackClientDescriptor(*portId, uid, session, resultAttr, clientConfig,
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001421 sanitizedRequestedPortId, *stream,
François Gaffiec005e562018-11-06 15:04:49 +01001422 mEngine->getProductStrategyForAttributes(resultAttr),
François Gaffieaaac0fd2018-11-22 17:56:39 +01001423 toVolumeSource(resultAttr),
Kevin Rocard153f92d2018-12-18 18:33:28 -08001424 *flags, isRequestedDeviceForExclusiveUse,
Eric Laurentc209fe42020-06-05 18:11:23 -07001425 std::move(weakSecondaryOutputDescs),
1426 outputDesc->mPolicyMix);
Andy Hung39efb7a2018-09-26 15:39:28 -07001427 outputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001428
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001429 ALOGV("%s() returns output %d requestedPortId %d selectedDeviceId %d for port ID %d", __func__,
1430 *output, requestedPortId, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07001431
Eric Laurente83b55d2014-11-14 10:06:21 -08001432 return NO_ERROR;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001433}
1434
Eric Laurentc529cf62020-04-17 18:19:10 -07001435status_t AudioPolicyManager::openDirectOutput(audio_stream_type_t stream,
1436 audio_session_t session,
1437 const audio_config_t *config,
1438 audio_output_flags_t flags,
1439 const DeviceVector &devices,
1440 audio_io_handle_t *output) {
1441
1442 *output = AUDIO_IO_HANDLE_NONE;
1443
1444 // skip direct output selection if the request can obviously be attached to a mixed output
1445 // and not explicitly requested
1446 if (((flags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
1447 audio_is_linear_pcm(config->format) && config->sample_rate <= SAMPLE_RATE_HZ_MAX &&
1448 audio_channel_count_from_out_mask(config->channel_mask) <= 2) {
1449 return NAME_NOT_FOUND;
1450 }
1451
1452 // Do not allow offloading if one non offloadable effect is enabled or MasterMono is enabled.
1453 // This prevents creating an offloaded track and tearing it down immediately after start
1454 // when audioflinger detects there is an active non offloadable effect.
1455 // FIXME: We should check the audio session here but we do not have it in this context.
1456 // This may prevent offloading in rare situations where effects are left active by apps
1457 // in the background.
1458 sp<IOProfile> profile;
1459 if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) ||
1460 !(mEffects.isNonOffloadableEffectEnabled() || mMasterMono)) {
1461 profile = getProfileForOutput(
1462 devices, config->sample_rate, config->format, config->channel_mask,
1463 flags, true /* directOnly */);
1464 }
1465
1466 if (profile == nullptr) {
1467 return NAME_NOT_FOUND;
1468 }
1469
1470 // exclusive outputs for MMAP and Offload are enforced by different session ids.
1471 for (size_t i = 0; i < mOutputs.size(); i++) {
1472 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
1473 if (!desc->isDuplicated() && (profile == desc->mProfile)) {
1474 // reuse direct output if currently open by the same client
1475 // and configured with same parameters
1476 if ((config->sample_rate == desc->getSamplingRate()) &&
1477 (config->format == desc->getFormat()) &&
1478 (config->channel_mask == desc->getChannelMask()) &&
1479 (session == desc->mDirectClientSession)) {
1480 desc->mDirectOpenCount++;
Eric Laurentfecbceb2021-02-09 14:46:43 +01001481 ALOGV("%s reusing direct output %d for session %d", __func__,
Eric Laurentc529cf62020-04-17 18:19:10 -07001482 mOutputs.keyAt(i), session);
1483 *output = mOutputs.keyAt(i);
1484 return NO_ERROR;
1485 }
1486 }
1487 }
1488
1489 if (!profile->canOpenNewIo()) {
1490 return NAME_NOT_FOUND;
1491 }
1492
1493 sp<SwAudioOutputDescriptor> outputDesc =
1494 new SwAudioOutputDescriptor(profile, mpClientInterface);
1495
Michael Chan6fb34492020-12-08 15:44:49 +11001496 // An MSD patch may be using the only output stream that can service this request. Release
1497 // all MSD patches to prioritize this request over any active output on MSD.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001498 releaseMsdOutputPatches(devices);
Eric Laurentc529cf62020-04-17 18:19:10 -07001499
Eric Laurentf1f22e72021-07-13 14:04:14 +02001500 status_t status =
1501 outputDesc->open(config, nullptr /* mixerConfig */, devices, stream, flags, output);
Eric Laurentc529cf62020-04-17 18:19:10 -07001502
1503 // only accept an output with the requested parameters
1504 if (status != NO_ERROR ||
1505 (config->sample_rate != 0 && config->sample_rate != outputDesc->getSamplingRate()) ||
1506 (config->format != AUDIO_FORMAT_DEFAULT && config->format != outputDesc->getFormat()) ||
1507 (config->channel_mask != 0 && config->channel_mask != outputDesc->getChannelMask())) {
1508 ALOGV("%s failed opening direct output: output %d sample rate %d %d,"
1509 "format %d %d, channel mask %04x %04x", __func__, *output, config->sample_rate,
1510 outputDesc->getSamplingRate(), config->format, outputDesc->getFormat(),
1511 config->channel_mask, outputDesc->getChannelMask());
1512 if (*output != AUDIO_IO_HANDLE_NONE) {
1513 outputDesc->close();
1514 }
1515 // fall back to mixer output if possible when the direct output could not be open
1516 if (audio_is_linear_pcm(config->format) &&
1517 config->sample_rate <= SAMPLE_RATE_HZ_MAX) {
1518 return NAME_NOT_FOUND;
1519 }
1520 *output = AUDIO_IO_HANDLE_NONE;
1521 return BAD_VALUE;
1522 }
1523 outputDesc->mDirectOpenCount = 1;
1524 outputDesc->mDirectClientSession = session;
1525
1526 addOutput(*output, outputDesc);
1527 mPreviousOutputs = mOutputs;
1528 ALOGV("%s returns new direct output %d", __func__, *output);
1529 mpClientInterface->onAudioPortListUpdate();
1530 return NO_ERROR;
1531}
1532
François Gaffie11d30102018-11-02 16:09:09 +01001533audio_io_handle_t AudioPolicyManager::getOutputForDevices(
1534 const DeviceVector &devices,
Kevin Rocard169753c2017-03-06 14:18:23 -08001535 audio_session_t session,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001536 const audio_attributes_t *attr,
Eric Laurentfe231122017-11-17 17:48:06 -08001537 const audio_config_t *config,
jiabine375d412019-02-26 12:54:53 -08001538 audio_output_flags_t *flags,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001539 bool *isSpatialized,
jiabina84c3d32022-12-02 18:59:55 +00001540 sp<PreferredMixerAttributesInfo> prefMixerConfigInfo,
jiabine375d412019-02-26 12:54:53 -08001541 bool forceMutingHaptic)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001542{
Andy Hungc88b0642018-04-27 15:42:35 -07001543 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001544
jiabine375d412019-02-26 12:54:53 -08001545 // Discard haptic channel mask when forcing muting haptic channels.
1546 audio_channel_mask_t channelMask = forceMutingHaptic
Mikhail Naganov55773032020-10-01 15:08:13 -07001547 ? static_cast<audio_channel_mask_t>(config->channel_mask & ~AUDIO_CHANNEL_HAPTIC_ALL)
1548 : config->channel_mask;
jiabine375d412019-02-26 12:54:53 -08001549
Eric Laurente552edb2014-03-10 17:42:56 -07001550 // open a direct output if required by specified parameters
1551 //force direct flag if offload flag is set: offloading implies a direct output stream
1552 // and all common behaviors are driven by checking only the direct flag
1553 // this should normally be set appropriately in the policy configuration file
Nadav Bar766fb022018-01-07 12:18:03 +02001554 if ((*flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1555 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurente552edb2014-03-10 17:42:56 -07001556 }
Nadav Bar766fb022018-01-07 12:18:03 +02001557 if ((*flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
1558 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent93c3d412014-08-01 14:48:35 -07001559 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001560
1561 audio_stream_type_t stream = mEngine->getStreamTypeForAttributes(*attr);
1562
Eric Laurente83b55d2014-11-14 10:06:21 -08001563 // only allow deep buffering for music stream type
1564 if (stream != AUDIO_STREAM_MUSIC) {
Nadav Bar766fb022018-01-07 12:18:03 +02001565 *flags = (audio_output_flags_t)(*flags &~AUDIO_OUTPUT_FLAG_DEEP_BUFFER);
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -07001566 } else if (/* stream == AUDIO_STREAM_MUSIC && */
Nadav Bar766fb022018-01-07 12:18:03 +02001567 *flags == AUDIO_OUTPUT_FLAG_NONE &&
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -07001568 property_get_bool("audio.deep_buffer.media", false /* default_value */)) {
1569 // use DEEP_BUFFER as default output for music stream type
Nadav Bar766fb022018-01-07 12:18:03 +02001570 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
Eric Laurente83b55d2014-11-14 10:06:21 -08001571 }
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -07001572 if (stream == AUDIO_STREAM_TTS) {
Nadav Bar766fb022018-01-07 12:18:03 +02001573 *flags = AUDIO_OUTPUT_FLAG_TTS;
Haynes Mathew George84c621e2017-04-25 11:41:50 -07001574 } else if (stream == AUDIO_STREAM_VOICE_CALL &&
Nadav Bar20919492018-11-20 10:20:51 +02001575 audio_is_linear_pcm(config->format) &&
1576 (*flags & AUDIO_OUTPUT_FLAG_INCALL_MUSIC) == 0) {
Nadav Bar766fb022018-01-07 12:18:03 +02001577 *flags = (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_VOIP_RX |
Haynes Mathew George84c621e2017-04-25 11:41:50 -07001578 AUDIO_OUTPUT_FLAG_DIRECT);
1579 ALOGV("Set VoIP and Direct output flags for PCM format");
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -07001580 }
Eric Laurente552edb2014-03-10 17:42:56 -07001581
Carter Hsua3abb402021-10-26 11:11:20 +08001582 // Attach the Ultrasound flag for the AUDIO_CONTENT_TYPE_ULTRASOUND
1583 if (attr->content_type == AUDIO_CONTENT_TYPE_ULTRASOUND) {
1584 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_ULTRASOUND);
1585 }
1586
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001587 *isSpatialized = false;
Eric Laurentfa0f6742021-08-17 18:39:44 +02001588 if (mSpatializerOutput != nullptr
Andy Hung9dd1a5b2022-05-10 15:39:39 -07001589 && canBeSpatializedInt(attr, config, devices.toTypeAddrVector())) {
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001590 *isSpatialized = true;
Eric Laurentfa0f6742021-08-17 18:39:44 +02001591 return mSpatializerOutput->mIoHandle;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001592 }
1593
Eric Laurentc529cf62020-04-17 18:19:10 -07001594 audio_config_t directConfig = *config;
1595 directConfig.channel_mask = channelMask;
1596 status_t status = openDirectOutput(stream, session, &directConfig, *flags, devices, &output);
1597 if (status != NAME_NOT_FOUND) {
Eric Laurente552edb2014-03-10 17:42:56 -07001598 return output;
1599 }
1600
Eric Laurent14cbfca2016-03-17 09:42:16 -07001601 // A request for HW A/V sync cannot fallback to a mixed output because time
1602 // stamps are embedded in audio data
Phil Burk2d059932018-02-15 15:55:11 -08001603 if ((*flags & (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ)) != 0) {
Eric Laurent14cbfca2016-03-17 09:42:16 -07001604 return AUDIO_IO_HANDLE_NONE;
1605 }
Pierre Couillaude73496b2023-03-06 16:19:05 +00001606 // A request for Tuner cannot fallback to a mixed output
1607 if ((directConfig.offload_info.content_id || directConfig.offload_info.sync_id)) {
1608 return AUDIO_IO_HANDLE_NONE;
1609 }
Eric Laurent14cbfca2016-03-17 09:42:16 -07001610
Eric Laurente552edb2014-03-10 17:42:56 -07001611 // ignoring channel mask due to downmix capability in mixer
1612
1613 // open a non direct output
1614
1615 // for non direct outputs, only PCM is supported
Eric Laurentfe231122017-11-17 17:48:06 -08001616 if (audio_is_linear_pcm(config->format)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001617 // get which output is suitable for the specified stream. The actual
1618 // routing change will happen when startOutput() will be called
François Gaffie11d30102018-11-02 16:09:09 +01001619 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
jiabina84c3d32022-12-02 18:59:55 +00001620 if (prefMixerConfigInfo != nullptr) {
1621 for (audio_io_handle_t outputHandle : outputs) {
1622 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(outputHandle);
1623 if (outputDesc->mProfile == prefMixerConfigInfo->getProfile()) {
1624 output = outputHandle;
1625 break;
1626 }
1627 }
1628 if (output == AUDIO_IO_HANDLE_NONE) {
1629 // No output open with the preferred profile. Open a new one.
1630 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
1631 config.channel_mask = prefMixerConfigInfo->getConfigBase().channel_mask;
1632 config.sample_rate = prefMixerConfigInfo->getConfigBase().sample_rate;
1633 config.format = prefMixerConfigInfo->getConfigBase().format;
1634 sp<SwAudioOutputDescriptor> preferredOutput = openOutputWithProfileAndDevice(
1635 prefMixerConfigInfo->getProfile(), devices, nullptr /*mixerConfig*/,
1636 &config, prefMixerConfigInfo->getFlags());
1637 if (preferredOutput == nullptr) {
1638 ALOGE("%s failed to open output with preferred mixer config", __func__);
1639 } else {
1640 output = preferredOutput->mIoHandle;
1641 }
1642 }
1643 } else {
1644 // at this stage we should ignore the DIRECT flag as no direct output could be
1645 // found earlier
1646 *flags = (audio_output_flags_t) (*flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
1647 output = selectOutput(
1648 outputs, *flags, config->format, channelMask, config->sample_rate, session);
1649 }
Eric Laurente552edb2014-03-10 17:42:56 -07001650 }
François Gaffie11d30102018-11-02 16:09:09 +01001651 ALOGW_IF((output == 0), "getOutputForDevices() could not find output for stream %d, "
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001652 "sampling rate %d, format %#x, channels %#x, flags %#x",
jiabine375d412019-02-26 12:54:53 -08001653 stream, config->sample_rate, config->format, channelMask, *flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001654
Eric Laurente552edb2014-03-10 17:42:56 -07001655 return output;
1656}
1657
Mikhail Naganovf02f3672018-11-09 12:44:16 -08001658sp<DeviceDescriptor> AudioPolicyManager::getMsdAudioInDevice() const {
François Gaffie11d30102018-11-02 16:09:09 +01001659 auto msdInDevices = mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1660 mAvailableInputDevices);
1661 return msdInDevices.isEmpty()? nullptr : msdInDevices.itemAt(0);
1662}
1663
1664DeviceVector AudioPolicyManager::getMsdAudioOutDevices() const {
1665 return mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1666 mAvailableOutputDevices);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001667}
1668
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001669const AudioPatchCollection AudioPolicyManager::getMsdOutputPatches() const {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001670 AudioPatchCollection msdPatches;
Mikhail Naganov86112352018-10-04 09:02:49 -07001671 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1672 if (msdModule != 0) {
1673 for (size_t i = 0; i < mAudioPatches.size(); ++i) {
1674 sp<AudioPatch> patch = mAudioPatches.valueAt(i);
1675 for (size_t j = 0; j < patch->mPatch.num_sources; ++j) {
1676 const struct audio_port_config *source = &patch->mPatch.sources[j];
1677 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
1678 source->ext.device.hw_module == msdModule->getHandle()) {
François Gaffieafd4cea2019-11-18 15:50:22 +01001679 msdPatches.addAudioPatch(patch->getHandle(), patch);
Mikhail Naganov86112352018-10-04 09:02:49 -07001680 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001681 }
1682 }
1683 }
1684 return msdPatches;
1685}
1686
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02001687bool AudioPolicyManager::isMsdPatch(const audio_patch_handle_t &handle) const {
1688 ssize_t index = mAudioPatches.indexOfKey(handle);
1689 if (index < 0) {
1690 return false;
1691 }
1692 const sp<AudioPatch> patch = mAudioPatches.valueAt(index);
1693 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1694 if (msdModule == nullptr) {
1695 return false;
1696 }
1697 const struct audio_port_config *sink = &patch->mPatch.sinks[0];
1698 if (getMsdAudioOutDevices().contains(mAvailableOutputDevices.getDeviceFromId(sink->id))) {
1699 return true;
1700 }
1701 index = getMsdOutputPatches().indexOfKey(handle);
1702 if (index < 0) {
1703 return false;
1704 }
1705 return true;
1706}
1707
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001708status_t AudioPolicyManager::getMsdProfiles(bool hwAvSync,
1709 const InputProfileCollection &inputProfiles,
1710 const OutputProfileCollection &outputProfiles,
1711 const sp<DeviceDescriptor> &sourceDevice,
1712 const sp<DeviceDescriptor> &sinkDevice,
1713 AudioProfileVector& sourceProfiles,
1714 AudioProfileVector& sinkProfiles) const {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001715 if (inputProfiles.isEmpty()) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001716 ALOGE("%s() no input profiles for source module", __func__);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001717 return NO_INIT;
1718 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001719 if (outputProfiles.isEmpty()) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001720 ALOGE("%s() no output profiles for sink module", __func__);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001721 return NO_INIT;
1722 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001723 for (const auto &inProfile : inputProfiles) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001724 if (hwAvSync == ((inProfile->getFlags() & AUDIO_INPUT_FLAG_HW_AV_SYNC) != 0) &&
1725 inProfile->supportsDevice(sourceDevice)) {
1726 appendAudioProfiles(sourceProfiles, inProfile->getAudioProfiles());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001727 }
1728 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001729 for (const auto &outProfile : outputProfiles) {
Michael Chan6fb34492020-12-08 15:44:49 +11001730 if (hwAvSync == ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) &&
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001731 outProfile->supportsDevice(sinkDevice)) {
1732 appendAudioProfiles(sinkProfiles, outProfile->getAudioProfiles());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001733 }
1734 }
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001735 return NO_ERROR;
1736}
1737
1738status_t AudioPolicyManager::getBestMsdConfig(bool hwAvSync,
1739 const AudioProfileVector &sourceProfiles, const AudioProfileVector &sinkProfiles,
1740 audio_port_config *sourceConfig, audio_port_config *sinkConfig) const
1741{
Dean Wheatley16809da2022-12-09 14:55:46 +11001742 // Compressed formats for MSD module, ordered from most preferred to least preferred.
1743 static const std::vector<audio_format_t> formatsOrder = {{
1744 AUDIO_FORMAT_IEC60958, AUDIO_FORMAT_MAT_2_1, AUDIO_FORMAT_MAT_2_0, AUDIO_FORMAT_E_AC3,
1745 AUDIO_FORMAT_AC3, AUDIO_FORMAT_PCM_16_BIT }};
1746 static const std::vector<audio_channel_mask_t> channelMasksOrder = [](){
1747 // Channel position masks for MSD module, 3D > 2D > 1D ordering (most preferred to least
1748 // preferred).
1749 std::vector<audio_channel_mask_t> masks = {{
1750 AUDIO_CHANNEL_OUT_3POINT1POINT2, AUDIO_CHANNEL_OUT_3POINT0POINT2,
1751 AUDIO_CHANNEL_OUT_2POINT1POINT2, AUDIO_CHANNEL_OUT_2POINT0POINT2,
1752 AUDIO_CHANNEL_OUT_5POINT1, AUDIO_CHANNEL_OUT_STEREO }};
1753 // insert index masks (higher counts most preferred) as preferred over position masks
1754 for (int i = 1; i <= AUDIO_CHANNEL_COUNT_MAX; i++) {
1755 masks.insert(
1756 masks.begin(), audio_channel_mask_for_index_assignment_from_count(i));
1757 }
1758 return masks;
1759 }();
1760
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001761 struct audio_config_base bestSinkConfig;
Dean Wheatley16809da2022-12-09 14:55:46 +11001762 status_t result = findBestMatchingOutputConfig(sourceProfiles, sinkProfiles, formatsOrder,
1763 channelMasksOrder, true /*preferHigherSamplingRates*/, bestSinkConfig);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001764 if (result != NO_ERROR) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001765 ALOGD("%s() no matching config found for sink, hwAvSync: %d",
1766 __func__, hwAvSync);
Greg Kaiser83289652018-07-30 06:13:57 -07001767 return result;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001768 }
1769 sinkConfig->sample_rate = bestSinkConfig.sample_rate;
1770 sinkConfig->channel_mask = bestSinkConfig.channel_mask;
1771 sinkConfig->format = bestSinkConfig.format;
1772 // For encoded streams force direct flag to prevent downstream mixing.
1773 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1774 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_DIRECT);
Dean Wheatley5c9f0832019-11-21 13:39:31 +11001775 if (audio_is_iec61937_compatible(sinkConfig->format)) {
1776 // For formats compatible with IEC61937 encapsulation, assume that
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001777 // the input is IEC61937 framed (for proportional buffer sizing).
Dean Wheatley5c9f0832019-11-21 13:39:31 +11001778 // Add the AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO flag so downstream HAL can distinguish between
1779 // raw and IEC61937 framed streams.
1780 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1781 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO);
1782 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001783 sourceConfig->sample_rate = bestSinkConfig.sample_rate;
1784 // Specify exact channel mask to prevent guessing by bit count in PatchPanel.
Dean Wheatley16809da2022-12-09 14:55:46 +11001785 sourceConfig->channel_mask =
1786 audio_channel_mask_get_representation(bestSinkConfig.channel_mask)
1787 == AUDIO_CHANNEL_REPRESENTATION_INDEX ?
1788 bestSinkConfig.channel_mask : audio_channel_mask_out_to_in(bestSinkConfig.channel_mask);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001789 sourceConfig->format = bestSinkConfig.format;
1790 // Copy input stream directly without any processing (e.g. resampling).
1791 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1792 sourceConfig->flags.input | AUDIO_INPUT_FLAG_DIRECT);
1793 if (hwAvSync) {
1794 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1795 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
1796 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1797 sourceConfig->flags.input | AUDIO_INPUT_FLAG_HW_AV_SYNC);
1798 }
1799 const unsigned int config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE |
1800 AUDIO_PORT_CONFIG_CHANNEL_MASK | AUDIO_PORT_CONFIG_FORMAT | AUDIO_PORT_CONFIG_FLAGS;
1801 sinkConfig->config_mask |= config_mask;
1802 sourceConfig->config_mask |= config_mask;
1803 return NO_ERROR;
1804}
1805
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001806PatchBuilder AudioPolicyManager::buildMsdPatch(bool msdIsSource,
1807 const sp<DeviceDescriptor> &device) const
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001808{
1809 PatchBuilder patchBuilder;
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001810 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1811 ALOG_ASSERT(msdModule != nullptr, "MSD module not available");
1812 sp<HwModule> deviceModule = mHwModules.getModuleForDevice(device, AUDIO_FORMAT_DEFAULT);
1813 if (deviceModule == nullptr) {
1814 ALOGE("%s() unable to get module for %s", __func__, device->toString().c_str());
1815 return patchBuilder;
1816 }
1817 const InputProfileCollection inputProfiles = msdIsSource ?
1818 msdModule->getInputProfiles() : deviceModule->getInputProfiles();
1819 const OutputProfileCollection outputProfiles = msdIsSource ?
1820 deviceModule->getOutputProfiles() : msdModule->getOutputProfiles();
1821
1822 const sp<DeviceDescriptor> sourceDevice = msdIsSource ? getMsdAudioInDevice() : device;
1823 const sp<DeviceDescriptor> sinkDevice = msdIsSource ?
1824 device : getMsdAudioOutDevices().itemAt(0);
1825 patchBuilder.addSource(sourceDevice).addSink(sinkDevice);
1826
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001827 audio_port_config sourceConfig = patchBuilder.patch()->sources[0];
1828 audio_port_config sinkConfig = patchBuilder.patch()->sinks[0];
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001829 AudioProfileVector sourceProfiles;
1830 AudioProfileVector sinkProfiles;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001831 // TODO: Figure out whether MSD module has HW_AV_SYNC flag set in the AP config file.
1832 // For now, we just forcefully try with HwAvSync first.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001833 for (auto hwAvSync : { true, false }) {
1834 if (getMsdProfiles(hwAvSync, inputProfiles, outputProfiles, sourceDevice, sinkDevice,
1835 sourceProfiles, sinkProfiles) != NO_ERROR) {
1836 continue;
1837 }
1838 if (getBestMsdConfig(hwAvSync, sourceProfiles, sinkProfiles, &sourceConfig,
1839 &sinkConfig) == NO_ERROR) {
1840 // Found a matching config. Re-create PatchBuilder with this config.
1841 return (PatchBuilder()).addSource(sourceConfig).addSink(sinkConfig);
1842 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001843 }
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001844 ALOGV("%s() no matching config found. Fall through to default PCM patch"
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001845 " supporting PCM format conversion.", __func__);
1846 return patchBuilder;
1847}
1848
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001849status_t AudioPolicyManager::setMsdOutputPatches(const DeviceVector *outputDevices) {
Michael Chan6fb34492020-12-08 15:44:49 +11001850 DeviceVector devices;
1851 if (outputDevices != nullptr && outputDevices->size() > 0) {
1852 devices.add(*outputDevices);
1853 } else {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001854 // Use media strategy for unspecified output device. This should only
1855 // occur on checkForDeviceAndOutputChanges(). Device connection events may
1856 // therefore invalidate explicit routing requests.
Michael Chan6fb34492020-12-08 15:44:49 +11001857 devices = mEngine->getOutputDevicesForAttributes(
François Gaffiec005e562018-11-06 15:04:49 +01001858 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
Michael Chan6fb34492020-12-08 15:44:49 +11001859 LOG_ALWAYS_FATAL_IF(devices.isEmpty(), "no output device to set MSD patch");
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001860 }
Michael Chan6fb34492020-12-08 15:44:49 +11001861 std::vector<PatchBuilder> patchesToCreate;
1862 for (auto i = 0u; i < devices.size(); ++i) {
1863 ALOGV("%s() for device %s", __func__, devices[i]->toString().c_str());
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001864 patchesToCreate.push_back(buildMsdPatch(true /*msdIsSource*/, devices[i]));
Michael Chan6fb34492020-12-08 15:44:49 +11001865 }
1866 // Retain only the MSD patches associated with outputDevices request.
1867 // Tear down the others, and create new ones as needed.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001868 AudioPatchCollection patchesToRemove = getMsdOutputPatches();
Michael Chan6fb34492020-12-08 15:44:49 +11001869 for (auto it = patchesToCreate.begin(); it != patchesToCreate.end(); ) {
1870 auto retainedPatch = false;
1871 for (auto i = 0u; i < patchesToRemove.size(); ++i) {
1872 if (audio_patches_are_equal(it->patch(), &patchesToRemove[i]->mPatch)) {
1873 patchesToRemove.removeItemsAt(i);
1874 retainedPatch = true;
1875 break;
1876 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001877 }
Michael Chan6fb34492020-12-08 15:44:49 +11001878 if (retainedPatch) {
1879 it = patchesToCreate.erase(it);
1880 continue;
1881 }
1882 ++it;
1883 }
1884 if (patchesToCreate.size() == 0 && patchesToRemove.size() == 0) {
1885 return NO_ERROR;
1886 }
1887 for (auto i = 0u; i < patchesToRemove.size(); ++i) {
1888 auto &currentPatch = patchesToRemove.valueAt(i);
François Gaffieafd4cea2019-11-18 15:50:22 +01001889 releaseAudioPatch(currentPatch->getHandle(), mUidCached);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001890 }
Michael Chan6fb34492020-12-08 15:44:49 +11001891 status_t status = NO_ERROR;
1892 for (const auto &p : patchesToCreate) {
1893 auto currStatus = installPatch(__func__, -1 /*index*/, nullptr /*patchHandle*/,
1894 p.patch(), 0 /*delayMs*/, mUidCached, nullptr /*patchDescPtr*/);
1895 char message[256];
1896 snprintf(message, sizeof(message), "%s() %s: creating MSD patch from device:IN_BUS to "
1897 "device:%#x (format:%#x channels:%#x samplerate:%d)", __func__,
1898 currStatus == NO_ERROR ? "Success" : "Error",
1899 p.patch()->sinks[0].ext.device.type, p.patch()->sources[0].format,
1900 p.patch()->sources[0].channel_mask, p.patch()->sources[0].sample_rate);
1901 if (currStatus == NO_ERROR) {
1902 ALOGD("%s", message);
1903 } else {
1904 ALOGE("%s", message);
1905 if (status == NO_ERROR) {
1906 status = currStatus;
1907 }
1908 }
1909 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001910 return status;
1911}
1912
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001913void AudioPolicyManager::releaseMsdOutputPatches(const DeviceVector& devices) {
1914 AudioPatchCollection msdPatches = getMsdOutputPatches();
Michael Chan6fb34492020-12-08 15:44:49 +11001915 for (size_t i = 0; i < msdPatches.size(); i++) {
1916 const auto& patch = msdPatches[i];
1917 for (size_t j = 0; j < patch->mPatch.num_sinks; ++j) {
1918 const struct audio_port_config *sink = &patch->mPatch.sinks[j];
1919 if (sink->type == AUDIO_PORT_TYPE_DEVICE && devices.getDevice(sink->ext.device.type,
1920 String8(sink->ext.device.address), AUDIO_FORMAT_DEFAULT) != nullptr) {
1921 releaseAudioPatch(patch->getHandle(), mUidCached);
1922 break;
1923 }
1924 }
1925 }
1926}
1927
Dorin Drimus94d94412022-02-02 09:05:02 +01001928bool AudioPolicyManager::msdHasPatchesToAllDevices(const AudioDeviceTypeAddrVector& devices) {
Mikhail Naganov68e3f642023-04-28 13:06:32 -07001929 DeviceVector devicesToCheck =
1930 mConfig->getOutputDevices().getDevicesFromDeviceTypeAddrVec(devices);
Dorin Drimus94d94412022-02-02 09:05:02 +01001931 AudioPatchCollection msdPatches = getMsdOutputPatches();
1932 for (size_t i = 0; i < msdPatches.size(); i++) {
1933 const auto& patch = msdPatches[i];
1934 for (size_t j = 0; j < patch->mPatch.num_sinks; ++j) {
1935 const struct audio_port_config *sink = &patch->mPatch.sinks[j];
1936 if (sink->type == AUDIO_PORT_TYPE_DEVICE) {
1937 const auto& foundDevice = devicesToCheck.getDevice(
1938 sink->ext.device.type, String8(sink->ext.device.address), AUDIO_FORMAT_DEFAULT);
1939 if (foundDevice != nullptr) {
1940 devicesToCheck.remove(foundDevice);
1941 if (devicesToCheck.isEmpty()) {
1942 return true;
1943 }
1944 }
1945 }
1946 }
1947 }
1948 return false;
1949}
1950
Eric Laurente0720872014-03-11 09:30:41 -07001951audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
jiabinebb6af42020-06-09 17:31:17 -07001952 audio_output_flags_t flags,
1953 audio_format_t format,
1954 audio_channel_mask_t channelMask,
1955 uint32_t samplingRate,
1956 audio_session_t sessionId)
Eric Laurente552edb2014-03-10 17:42:56 -07001957{
Eric Laurent16c66dd2019-05-01 17:54:10 -07001958 LOG_ALWAYS_FATAL_IF(!(format == AUDIO_FORMAT_INVALID || audio_is_linear_pcm(format)),
1959 "%s called with format %#x", __func__, format);
1960
jiabinebb6af42020-06-09 17:31:17 -07001961 // Return the output that haptic-generating attached to when 1) session id is specified,
1962 // 2) haptic-generating effect exists for given session id and 3) the output that
1963 // haptic-generating effect attached to is in given outputs.
1964 if (sessionId != AUDIO_SESSION_NONE) {
1965 audio_io_handle_t hapticGeneratingOutput = mEffects.getIoForSession(
1966 sessionId, FX_IID_HAPTICGENERATOR);
1967 if (outputs.indexOf(hapticGeneratingOutput) >= 0) {
1968 return hapticGeneratingOutput;
1969 }
1970 }
1971
Eric Laurent16c66dd2019-05-01 17:54:10 -07001972 // Flags disqualifying an output: the match must happen before calling selectOutput()
1973 static const audio_output_flags_t kExcludedFlags = (audio_output_flags_t)
1974 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ | AUDIO_OUTPUT_FLAG_DIRECT);
1975
1976 // Flags expressing a functional request: must be honored in priority over
1977 // other criteria
1978 static const audio_output_flags_t kFunctionalFlags = (audio_output_flags_t)
1979 (AUDIO_OUTPUT_FLAG_VOIP_RX | AUDIO_OUTPUT_FLAG_INCALL_MUSIC |
Eric Laurente28c66d2022-01-21 13:40:41 +01001980 AUDIO_OUTPUT_FLAG_TTS | AUDIO_OUTPUT_FLAG_DIRECT_PCM | AUDIO_OUTPUT_FLAG_ULTRASOUND |
1981 AUDIO_OUTPUT_FLAG_SPATIALIZER);
Eric Laurent16c66dd2019-05-01 17:54:10 -07001982 // Flags expressing a performance request: have lower priority than serving
1983 // requested sampling rate or channel mask
1984 static const audio_output_flags_t kPerformanceFlags = (audio_output_flags_t)
1985 (AUDIO_OUTPUT_FLAG_FAST | AUDIO_OUTPUT_FLAG_DEEP_BUFFER |
1986 AUDIO_OUTPUT_FLAG_RAW | AUDIO_OUTPUT_FLAG_SYNC);
1987
1988 const audio_output_flags_t functionalFlags =
1989 (audio_output_flags_t)(flags & kFunctionalFlags);
1990 const audio_output_flags_t performanceFlags =
1991 (audio_output_flags_t)(flags & kPerformanceFlags);
1992
1993 audio_io_handle_t bestOutput = (outputs.size() == 0) ? AUDIO_IO_HANDLE_NONE : outputs[0];
1994
Eric Laurente552edb2014-03-10 17:42:56 -07001995 // select one output among several that provide a path to a particular device or set of
François Gaffie11d30102018-11-02 16:09:09 +01001996 // devices (the list was previously build by getOutputsForDevices()).
Eric Laurente552edb2014-03-10 17:42:56 -07001997 // The priority is as follows:
jiabin40573322018-11-08 12:08:02 -08001998 // 1: the output supporting haptic playback when requesting haptic playback
Eric Laurent16c66dd2019-05-01 17:54:10 -07001999 // 2: the output with the highest number of requested functional flags
Carter Hsu199f1892021-10-15 15:47:29 +08002000 // with tiebreak preferring the minimum number of extra functional flags
2001 // (see b/200293124, the incorrect selection of AUDIO_OUTPUT_FLAG_VOIP_RX).
Eric Laurent16c66dd2019-05-01 17:54:10 -07002002 // 3: the output supporting the exact channel mask
2003 // 4: the output with a higher channel count than requested
jiabinb12a6da2022-06-03 20:48:18 +00002004 // 5: the output with the highest sampling rate if the requested sample rate is
2005 // greater than default sampling rate
Eric Laurent16c66dd2019-05-01 17:54:10 -07002006 // 6: the output with the highest number of requested performance flags
2007 // 7: the output with the bit depth the closest to the requested one
2008 // 8: the primary output
2009 // 9: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07002010
Eric Laurent16c66dd2019-05-01 17:54:10 -07002011 // matching criteria values in priority order for best matching output so far
2012 std::vector<uint32_t> bestMatchCriteria(8, 0);
Eric Laurente552edb2014-03-10 17:42:56 -07002013
Eric Laurent16c66dd2019-05-01 17:54:10 -07002014 const uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
2015 const uint32_t hapticChannelCount = audio_channel_count_from_out_mask(
2016 channelMask & AUDIO_CHANNEL_HAPTIC_ALL);
Eric Laurente78b6762018-12-19 16:29:01 -08002017
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002018 for (audio_io_handle_t output : outputs) {
2019 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent16c66dd2019-05-01 17:54:10 -07002020 // matching criteria values in priority order for current output
2021 std::vector<uint32_t> currentMatchCriteria(8, 0);
jiabin40573322018-11-08 12:08:02 -08002022
Eric Laurent16c66dd2019-05-01 17:54:10 -07002023 if (outputDesc->isDuplicated()) {
2024 continue;
2025 }
2026 if ((kExcludedFlags & outputDesc->mFlags) != 0) {
2027 continue;
2028 }
Eric Laurent8838a382014-09-08 16:44:28 -07002029
Eric Laurent16c66dd2019-05-01 17:54:10 -07002030 // If haptic channel is specified, use the haptic output if present.
2031 // When using haptic output, same audio format and sample rate are required.
2032 const uint32_t outputHapticChannelCount = audio_channel_count_from_out_mask(
jiabin5740f082019-08-19 15:08:30 -07002033 outputDesc->getChannelMask() & AUDIO_CHANNEL_HAPTIC_ALL);
Eric Laurent16c66dd2019-05-01 17:54:10 -07002034 if ((hapticChannelCount == 0) != (outputHapticChannelCount == 0)) {
2035 continue;
2036 }
2037 if (outputHapticChannelCount >= hapticChannelCount
jiabin5740f082019-08-19 15:08:30 -07002038 && format == outputDesc->getFormat()
2039 && samplingRate == outputDesc->getSamplingRate()) {
Eric Laurent16c66dd2019-05-01 17:54:10 -07002040 currentMatchCriteria[0] = outputHapticChannelCount;
2041 }
2042
2043 // functional flags match
Carter Hsu199f1892021-10-15 15:47:29 +08002044 const int matchingFunctionalFlags =
2045 __builtin_popcount(outputDesc->mFlags & functionalFlags);
2046 const int totalFunctionalFlags =
2047 __builtin_popcount(outputDesc->mFlags & kFunctionalFlags);
2048 // Prefer matching functional flags, but subtract unnecessary functional flags.
2049 currentMatchCriteria[1] = 100 * (matchingFunctionalFlags + 1) - totalFunctionalFlags;
Eric Laurent16c66dd2019-05-01 17:54:10 -07002050
2051 // channel mask and channel count match
jiabin5740f082019-08-19 15:08:30 -07002052 uint32_t outputChannelCount = audio_channel_count_from_out_mask(
2053 outputDesc->getChannelMask());
Eric Laurent16c66dd2019-05-01 17:54:10 -07002054 if (channelMask != AUDIO_CHANNEL_NONE && channelCount > 2 &&
2055 channelCount <= outputChannelCount) {
2056 if ((audio_channel_mask_get_representation(channelMask) ==
jiabin5740f082019-08-19 15:08:30 -07002057 audio_channel_mask_get_representation(outputDesc->getChannelMask())) &&
2058 ((channelMask & outputDesc->getChannelMask()) == channelMask)) {
Eric Laurent16c66dd2019-05-01 17:54:10 -07002059 currentMatchCriteria[2] = outputChannelCount;
Eric Laurente552edb2014-03-10 17:42:56 -07002060 }
Eric Laurent16c66dd2019-05-01 17:54:10 -07002061 currentMatchCriteria[3] = outputChannelCount;
2062 }
2063
2064 // sampling rate match
jiabinb12a6da2022-06-03 20:48:18 +00002065 if (samplingRate > SAMPLE_RATE_HZ_DEFAULT) {
jiabin5740f082019-08-19 15:08:30 -07002066 currentMatchCriteria[4] = outputDesc->getSamplingRate();
Eric Laurent16c66dd2019-05-01 17:54:10 -07002067 }
2068
2069 // performance flags match
2070 currentMatchCriteria[5] = popcount(outputDesc->mFlags & performanceFlags);
2071
2072 // format match
2073 if (format != AUDIO_FORMAT_INVALID) {
2074 currentMatchCriteria[6] =
jiabin4ef93452019-09-10 14:29:54 -07002075 PolicyAudioPort::kFormatDistanceMax -
2076 PolicyAudioPort::formatDistance(format, outputDesc->getFormat());
Eric Laurent16c66dd2019-05-01 17:54:10 -07002077 }
2078
2079 // primary output match
2080 currentMatchCriteria[7] = outputDesc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY;
2081
2082 // compare match criteria by priority then value
2083 if (std::lexicographical_compare(bestMatchCriteria.begin(), bestMatchCriteria.end(),
2084 currentMatchCriteria.begin(), currentMatchCriteria.end())) {
2085 bestMatchCriteria = currentMatchCriteria;
2086 bestOutput = output;
2087
2088 std::stringstream result;
2089 std::copy(bestMatchCriteria.begin(), bestMatchCriteria.end(),
2090 std::ostream_iterator<int>(result, " "));
2091 ALOGV("%s new bestOutput %d criteria %s",
2092 __func__, bestOutput, result.str().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07002093 }
2094 }
2095
Eric Laurent16c66dd2019-05-01 17:54:10 -07002096 return bestOutput;
Eric Laurente552edb2014-03-10 17:42:56 -07002097}
2098
Eric Laurent8fc147b2018-07-22 19:13:55 -07002099status_t AudioPolicyManager::startOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002100{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002101 ALOGV("%s portId %d", __FUNCTION__, portId);
2102
2103 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2104 if (outputDesc == 0) {
2105 ALOGW("startOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002106 return BAD_VALUE;
2107 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002108 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002109
Eric Laurent8fc147b2018-07-22 19:13:55 -07002110 ALOGV("startOutput() output %d, stream %d, session %d",
Eric Laurent97ac8712018-07-27 18:59:02 -07002111 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurentc75307b2015-03-17 15:29:32 -07002112
Eric Laurent733ce942017-12-07 12:18:25 -08002113 status_t status = outputDesc->start();
2114 if (status != NO_ERROR) {
2115 return status;
Eric Laurent3974e3b2017-12-07 17:58:43 -08002116 }
2117
Eric Laurent97ac8712018-07-27 18:59:02 -07002118 uint32_t delayMs;
2119 status = startSource(outputDesc, client, &delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07002120
2121 if (status != NO_ERROR) {
Eric Laurent733ce942017-12-07 12:18:25 -08002122 outputDesc->stop();
jiabin3ff8d7d2022-12-13 06:27:44 +00002123 if (status == DEAD_OBJECT) {
2124 sp<SwAudioOutputDescriptor> desc =
2125 reopenOutput(outputDesc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
2126 if (desc == nullptr) {
2127 // This is not common, it may indicate something wrong with the HAL.
2128 ALOGE("%s unable to open output with default config", __func__);
2129 return status;
2130 }
2131 desc->mUsePreferredMixerAttributes = true;
2132 }
Eric Laurent8c7e6da2015-04-21 17:37:00 -07002133 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07002134 }
jiabina84c3d32022-12-02 18:59:55 +00002135
2136 // If the client is the first one active on preferred mixer parameters, reopen the output
2137 // if the current mixer parameters doesn't match the preferred one.
2138 if (outputDesc->devices().size() == 1) {
2139 sp<PreferredMixerAttributesInfo> info = getPreferredMixerAttributesInfo(
2140 outputDesc->devices()[0]->getId(), client->strategy());
2141 if (info != nullptr && info->getUid() == client->uid()) {
2142 if (info->getActiveClientCount() == 0 && !outputDesc->isConfigurationMatched(
2143 info->getConfigBase(), info->getFlags())) {
2144 stopSource(outputDesc, client);
2145 outputDesc->stop();
2146 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
2147 config.channel_mask = info->getConfigBase().channel_mask;
2148 config.sample_rate = info->getConfigBase().sample_rate;
2149 config.format = info->getConfigBase().format;
jiabin3ff8d7d2022-12-13 06:27:44 +00002150 sp<SwAudioOutputDescriptor> desc =
2151 reopenOutput(outputDesc, &config, info->getFlags(), __func__);
2152 if (desc == nullptr) {
2153 return BAD_VALUE;
jiabina84c3d32022-12-02 18:59:55 +00002154 }
jiabin3ff8d7d2022-12-13 06:27:44 +00002155 desc->mUsePreferredMixerAttributes = true;
jiabina84c3d32022-12-02 18:59:55 +00002156 // Intentionally return error to let the client side resending request for
2157 // creating and starting.
2158 return DEAD_OBJECT;
2159 }
2160 info->increaseActiveClient();
jiabine3d1f552023-06-14 17:42:17 +00002161 if (info->getActiveClientCount() == 1 &&
2162 (info->getFlags() & AUDIO_OUTPUT_FLAG_BIT_PERFECT) != AUDIO_OUTPUT_FLAG_NONE) {
2163 // If it is first bit-perfect client, reroute all clients that will be routed to
2164 // the bit-perfect sink so that it is guaranteed only bit-perfect stream is active.
2165 PortHandleVector clientsToInvalidate;
2166 for (size_t i = 0; i < mOutputs.size(); i++) {
2167 if (mOutputs[i] == outputDesc ||
jiabin98c519c2023-07-05 17:34:21 +00002168 mOutputs[i]->devices().filter(outputDesc->devices()).isEmpty()) {
jiabine3d1f552023-06-14 17:42:17 +00002169 continue;
2170 }
2171 for (const auto& c : mOutputs[i]->getClientIterable()) {
2172 clientsToInvalidate.push_back(c->portId());
2173 }
2174 }
2175 if (!clientsToInvalidate.empty()) {
2176 ALOGD("%s Invalidate clients due to first bit-perfect client started",
2177 __func__);
2178 mpClientInterface->invalidateTracks(clientsToInvalidate);
2179 }
2180 }
jiabina84c3d32022-12-02 18:59:55 +00002181 }
2182 }
2183
Jean-Michel Trivib1f6e642023-02-07 20:49:04 +00002184 if (client->hasPreferredDevice()) {
2185 // playback activity with preferred device impacts routing occurred, inform upper layers
2186 mpClientInterface->onRoutingUpdated();
2187 }
Eric Laurentc75307b2015-03-17 15:29:32 -07002188 if (delayMs != 0) {
2189 usleep(delayMs * 1000);
2190 }
2191
2192 return status;
2193}
2194
Eric Laurent96d1dda2022-03-14 17:14:19 +01002195bool AudioPolicyManager::isLeUnicastActive() const {
2196 if (isInCall()) {
2197 return true;
2198 }
2199 return isAnyDeviceTypeActive(getAudioDeviceOutLeAudioUnicastSet());
2200}
2201
2202bool AudioPolicyManager::isAnyDeviceTypeActive(const DeviceTypeSet& deviceTypes) const {
2203 if (mAvailableOutputDevices.getDevicesFromTypes(deviceTypes).isEmpty()) {
2204 return false;
2205 }
2206 bool active = mOutputs.isAnyDeviceTypeActive(deviceTypes);
2207 ALOGV("%s active %d", __func__, active);
2208 return active;
2209}
2210
Eric Laurent97ac8712018-07-27 18:59:02 -07002211status_t AudioPolicyManager::startSource(const sp<SwAudioOutputDescriptor>& outputDesc,
2212 const sp<TrackClientDescriptor>& client,
2213 uint32_t *delayMs)
Eric Laurentc75307b2015-03-17 15:29:32 -07002214{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002215 // cannot start playback of STREAM_TTS if any other output is being used
2216 uint32_t beaconMuteLatency = 0;
Eric Laurentc75307b2015-03-17 15:29:32 -07002217
2218 *delayMs = 0;
Eric Laurent97ac8712018-07-27 18:59:02 -07002219 audio_stream_type_t stream = client->stream();
François Gaffie1c878552018-11-22 16:53:21 +01002220 auto clientVolSrc = client->volumeSource();
François Gaffiec005e562018-11-06 15:04:49 +01002221 auto clientStrategy = client->strategy();
2222 auto clientAttr = client->attributes();
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002223 if (stream == AUDIO_STREAM_TTS) {
2224 ALOGV("\t found BEACON stream");
François Gaffie1c878552018-11-22 16:53:21 +01002225 if (!mTtsOutputAvailable && mOutputs.isAnyOutputActive(
Francois Gaffie4404ddb2021-02-04 17:03:38 +01002226 toVolumeSource(AUDIO_STREAM_TTS, false) /*sourceToIgnore*/)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002227 return INVALID_OPERATION;
2228 } else {
2229 beaconMuteLatency = handleEventForBeacon(STARTING_BEACON);
2230 }
2231 } else {
2232 // some playback other than beacon starts
2233 beaconMuteLatency = handleEventForBeacon(STARTING_OUTPUT);
2234 }
2235
Eric Laurent77305a62016-07-25 16:39:22 -07002236 // force device change if the output is inactive and no audio patch is already present.
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002237 // check active before incrementing usage count
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02002238 bool force = !outputDesc->isActive() && !outputDesc->isRouted();
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002239
François Gaffie11d30102018-11-02 16:09:09 +01002240 DeviceVector devices;
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002241 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
Eric Laurent97ac8712018-07-27 18:59:02 -07002242 const char *address = NULL;
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002243 if (policyMix != nullptr) {
François Gaffie11d30102018-11-02 16:09:09 +01002244 audio_devices_t newDeviceType;
Eric Laurent97ac8712018-07-27 18:59:02 -07002245 address = policyMix->mDeviceAddress.string();
Kevin Rocard153f92d2018-12-18 18:33:28 -08002246 if ((policyMix->mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie11d30102018-11-02 16:09:09 +01002247 newDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Kevin Rocard153f92d2018-12-18 18:33:28 -08002248 } else {
2249 newDeviceType = policyMix->mDeviceType;
Eric Laurent97ac8712018-07-27 18:59:02 -07002250 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08002251 sp device = mAvailableOutputDevices.getDevice(newDeviceType, String8(address),
2252 AUDIO_FORMAT_DEFAULT);
2253 ALOG_ASSERT(device, "%s: no device found t=%u, a=%s", __func__, newDeviceType, address);
2254 devices.add(device);
Eric Laurent97ac8712018-07-27 18:59:02 -07002255 }
2256
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002257 // requiresMuteCheck is false when we can bypass mute strategy.
2258 // It covers a common case when there is no materially active audio
2259 // and muting would result in unnecessary delay and dropped audio.
2260 const uint32_t outputLatencyMs = outputDesc->latency();
2261 bool requiresMuteCheck = outputDesc->isActive(outputLatencyMs * 2); // account for drain
Eric Laurent96d1dda2022-03-14 17:14:19 +01002262 bool wasLeUnicastActive = isLeUnicastActive();
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002263
Eric Laurente552edb2014-03-10 17:42:56 -07002264 // increment usage count for this stream on the requested output:
2265 // NOTE that the usage count is the same for duplicated output and hardware output which is
2266 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
Eric Laurent592dd7b2018-08-05 18:58:48 -07002267 outputDesc->setClientActive(client, true);
Eric Laurent97ac8712018-07-27 18:59:02 -07002268
2269 if (client->hasPreferredDevice(true)) {
Eric Laurent72af8012023-03-15 17:36:22 +01002270 if (outputDesc->sameExclusivePreferredDevicesCount() > 0) {
François Gaffief96e5432019-04-09 17:13:56 +02002271 // Preferred device may be exclusive, use only if no other active clients on this output
2272 devices = DeviceVector(
2273 mAvailableOutputDevices.getDeviceFromId(client->preferredDeviceId()));
2274 } else {
2275 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
2276 }
François Gaffie11d30102018-11-02 16:09:09 +01002277 if (devices != outputDesc->devices()) {
François Gaffiec005e562018-11-06 15:04:49 +01002278 checkStrategyRoute(clientStrategy, outputDesc->mIoHandle);
Eric Laurent97ac8712018-07-27 18:59:02 -07002279 }
2280 }
Eric Laurente552edb2014-03-10 17:42:56 -07002281
François Gaffiec005e562018-11-06 15:04:49 +01002282 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07002283 selectOutputForMusicEffects();
2284 }
2285
François Gaffie1c878552018-11-22 16:53:21 +01002286 if (outputDesc->getActivityCount(clientVolSrc) == 1 || !devices.isEmpty()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08002287 // starting an output being rerouted?
François Gaffie11d30102018-11-02 16:09:09 +01002288 if (devices.isEmpty()) {
2289 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Eric Laurent275e8e92014-11-30 15:14:47 -08002290 }
François Gaffiec005e562018-11-06 15:04:49 +01002291 bool shouldWait =
2292 (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM)) ||
2293 followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_NOTIFICATION)) ||
2294 (beaconMuteLatency > 0));
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002295 uint32_t waitMs = beaconMuteLatency;
Eric Laurente552edb2014-03-10 17:42:56 -07002296 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01002297 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07002298 if (desc != outputDesc) {
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002299 // An output has a shared device if
2300 // - managed by the same hw module
2301 // - supports the currently selected device
2302 const bool sharedDevice = outputDesc->sharesHwModuleWith(desc)
François Gaffie11d30102018-11-02 16:09:09 +01002303 && (!desc->filterSupportedDevices(devices).isEmpty());
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002304
Eric Laurent77305a62016-07-25 16:39:22 -07002305 // force a device change if any other output is:
2306 // - managed by the same hw module
Jean-Michel Trivi4a5b4812018-02-08 17:22:32 +00002307 // - supports currently selected device
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002308 // - has a current device selection that differs from selected device.
Eric Laurent77305a62016-07-25 16:39:22 -07002309 // - has an active audio patch
Eric Laurente552edb2014-03-10 17:42:56 -07002310 // In this case, the audio HAL must receive the new device selection so that it can
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002311 // change the device currently selected by the other output.
2312 if (sharedDevice &&
François Gaffie11d30102018-11-02 16:09:09 +01002313 desc->devices() != devices &&
Eric Laurent77305a62016-07-25 16:39:22 -07002314 desc->getPatchHandle() != AUDIO_PATCH_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07002315 force = true;
2316 }
2317 // wait for audio on other active outputs to be presented when starting
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002318 // a notification so that audio focus effect can propagate, or that a mute/unmute
2319 // event occurred for beacon
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002320 const uint32_t latencyMs = desc->latency();
2321 const bool isActive = desc->isActive(latencyMs * 2); // account for drain
2322
2323 if (shouldWait && isActive && (waitMs < latencyMs)) {
2324 waitMs = latencyMs;
Eric Laurente552edb2014-03-10 17:42:56 -07002325 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002326
2327 // Require mute check if another output is on a shared device
2328 // and currently active to have proper drain and avoid pops.
2329 // Note restoring AudioTracks onto this output needs to invoke
2330 // a volume ramp if there is no mute.
2331 requiresMuteCheck |= sharedDevice && isActive;
Eric Laurente552edb2014-03-10 17:42:56 -07002332 }
2333 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002334
jiabin3ff8d7d2022-12-13 06:27:44 +00002335 if (outputDesc->mUsePreferredMixerAttributes && devices != outputDesc->devices()) {
2336 // If the output is open with preferred mixer attributes, but the routed device is
2337 // changed when calling this function, returning DEAD_OBJECT to indicate routing
2338 // changed.
2339 return DEAD_OBJECT;
2340 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002341 const uint32_t muteWaitMs =
jiabin3ff8d7d2022-12-13 06:27:44 +00002342 setOutputDevices(outputDesc, devices, force, 0, nullptr, requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07002343
Eric Laurente552edb2014-03-10 17:42:56 -07002344 // apply volume rules for current stream and device if necessary
François Gaffieaaac0fd2018-11-22 17:56:39 +01002345 auto &curves = getVolumeCurves(client->attributes());
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00002346 if (NO_ERROR != checkAndSetVolume(curves, client->volumeSource(),
François Gaffieaaac0fd2018-11-22 17:56:39 +01002347 curves.getVolumeIndex(outputDesc->devices().types()),
Eric Laurentc75307b2015-03-17 15:29:32 -07002348 outputDesc,
Francois Gaffied11442b2020-04-27 11:51:09 +02002349 outputDesc->devices().types(), 0 /*delay*/,
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00002350 outputDesc->useHwGain() /*force*/)) {
2351 // request AudioService to reinitialize the volume curves asynchronously
2352 ALOGE("checkAndSetVolume failed, requesting volume range init");
2353 mpClientInterface->onVolumeRangeInitRequest();
2354 };
Eric Laurente552edb2014-03-10 17:42:56 -07002355
2356 // update the outputs if starting an output with a stream that can affect notification
2357 // routing
2358 handleNotificationRoutingForStream(stream);
Eric Laurentc722f302014-12-10 11:21:49 -08002359
Eric Laurent2cbe89a2014-12-19 11:49:08 -08002360 // force reevaluating accessibility routing when ringtone or alarm starts
François Gaffiec005e562018-11-06 15:04:49 +01002361 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM))) {
jiabinc44b3462022-12-08 12:52:31 -08002362 invalidateStreams({AUDIO_STREAM_ACCESSIBILITY});
Eric Laurent2cbe89a2014-12-19 11:49:08 -08002363 }
Eric Laurentdc462862016-07-19 12:29:53 -07002364
2365 if (waitMs > muteWaitMs) {
2366 *delayMs = waitMs - muteWaitMs;
2367 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002368
2369 // FIXME: A device change (muteWaitMs > 0) likely introduces a volume change.
2370 // A volume change enacted by APM with 0 delay is not synchronous, as it goes
2371 // via AudioCommandThread to AudioFlinger. Hence it is possible that the volume
2372 // change occurs after the MixerThread starts and causes a stream volume
2373 // glitch.
2374 //
2375 // We do not introduce additional delay here.
Eric Laurente552edb2014-03-10 17:42:56 -07002376 }
Eric Laurentdc462862016-07-19 12:29:53 -07002377
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002378 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
jiabin9a3361e2019-10-01 09:38:30 -07002379 mEngine->getForceUse(
2380 AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
François Gaffiec005e562018-11-06 15:04:49 +01002381 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), true, outputDesc);
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002382 }
2383
Eric Laurent97ac8712018-07-27 18:59:02 -07002384 // Automatically enable the remote submix input when output is started on a re routing mix
2385 // of type MIX_TYPE_RECORDERS
jiabin9a3361e2019-10-01 09:38:30 -07002386 if (isSingleDeviceType(devices.types(), &audio_is_remote_submix_device) &&
2387 policyMix != NULL && policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002388 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2389 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2390 address,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002391 "remote-submix",
2392 AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07002393 }
2394
Eric Laurent96d1dda2022-03-14 17:14:19 +01002395 checkLeBroadcastRoutes(wasLeUnicastActive, outputDesc, *delayMs);
2396
Eric Laurente552edb2014-03-10 17:42:56 -07002397 return NO_ERROR;
2398}
2399
Eric Laurent96d1dda2022-03-14 17:14:19 +01002400void AudioPolicyManager::checkLeBroadcastRoutes(bool wasUnicastActive,
2401 sp<SwAudioOutputDescriptor> ignoredOutput, uint32_t delayMs) {
2402 bool isUnicastActive = isLeUnicastActive();
2403
2404 if (wasUnicastActive != isUnicastActive) {
jiabin3ff8d7d2022-12-13 06:27:44 +00002405 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent96d1dda2022-03-14 17:14:19 +01002406 //reroute all outputs routed to LE broadcast if LE unicast activy changed on any output
2407 for (size_t i = 0; i < mOutputs.size(); i++) {
2408 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
2409 if (desc != ignoredOutput && desc->isActive()
2410 && ((isUnicastActive &&
2411 !desc->devices().
2412 getDevicesFromType(AUDIO_DEVICE_OUT_BLE_BROADCAST).isEmpty())
2413 || (wasUnicastActive &&
2414 !desc->devices().getDevicesFromTypes(
2415 getAudioDeviceOutLeAudioUnicastSet()).isEmpty()))) {
2416 DeviceVector newDevices = getNewOutputDevices(desc, false /*fromCache*/);
2417 bool force = desc->devices() != newDevices;
jiabin3ff8d7d2022-12-13 06:27:44 +00002418 if (desc->mUsePreferredMixerAttributes && force) {
2419 // If the device is using preferred mixer attributes, the output need to reopen
2420 // with default configuration when the new selected devices are different from
2421 // current routing devices.
2422 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices);
2423 continue;
2424 }
Eric Laurent96d1dda2022-03-14 17:14:19 +01002425 setOutputDevices(desc, newDevices, force, delayMs);
2426 // re-apply device specific volume if not done by setOutputDevice()
2427 if (!force) {
2428 applyStreamVolumes(desc, newDevices.types(), delayMs);
2429 }
2430 }
2431 }
jiabin3ff8d7d2022-12-13 06:27:44 +00002432 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent96d1dda2022-03-14 17:14:19 +01002433 }
2434}
2435
Eric Laurent8fc147b2018-07-22 19:13:55 -07002436status_t AudioPolicyManager::stopOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002437{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002438 ALOGV("%s portId %d", __FUNCTION__, portId);
2439
2440 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2441 if (outputDesc == 0) {
2442 ALOGW("stopOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002443 return BAD_VALUE;
2444 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002445 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002446
Jean-Michel Trivib1f6e642023-02-07 20:49:04 +00002447 if (client->hasPreferredDevice(true)) {
2448 // playback activity with preferred device impacts routing occurred, inform upper layers
2449 mpClientInterface->onRoutingUpdated();
2450 }
2451
Eric Laurent97ac8712018-07-27 18:59:02 -07002452 ALOGV("stopOutput() output %d, stream %d, session %d",
2453 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurente552edb2014-03-10 17:42:56 -07002454
Eric Laurent97ac8712018-07-27 18:59:02 -07002455 status_t status = stopSource(outputDesc, client);
Eric Laurent3974e3b2017-12-07 17:58:43 -08002456
Eric Laurent733ce942017-12-07 12:18:25 -08002457 if (status == NO_ERROR ) {
2458 outputDesc->stop();
jiabina84c3d32022-12-02 18:59:55 +00002459 } else {
2460 return status;
2461 }
2462
2463 if (outputDesc->devices().size() == 1) {
2464 sp<PreferredMixerAttributesInfo> info = getPreferredMixerAttributesInfo(
2465 outputDesc->devices()[0]->getId(), client->strategy());
2466 if (info != nullptr && info->getUid() == client->uid()) {
2467 info->decreaseActiveClient();
2468 if (info->getActiveClientCount() == 0) {
2469 reopenOutput(outputDesc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
2470 }
2471 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002472 }
2473 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07002474}
2475
Eric Laurent97ac8712018-07-27 18:59:02 -07002476status_t AudioPolicyManager::stopSource(const sp<SwAudioOutputDescriptor>& outputDesc,
2477 const sp<TrackClientDescriptor>& client)
Eric Laurentc75307b2015-03-17 15:29:32 -07002478{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002479 // always handle stream stop, check which stream type is stopping
Eric Laurent97ac8712018-07-27 18:59:02 -07002480 audio_stream_type_t stream = client->stream();
François Gaffie1c878552018-11-22 16:53:21 +01002481 auto clientVolSrc = client->volumeSource();
Eric Laurent96d1dda2022-03-14 17:14:19 +01002482 bool wasLeUnicastActive = isLeUnicastActive();
Eric Laurent97ac8712018-07-27 18:59:02 -07002483
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002484 handleEventForBeacon(stream == AUDIO_STREAM_TTS ? STOPPING_BEACON : STOPPING_OUTPUT);
2485
François Gaffie1c878552018-11-22 16:53:21 +01002486 if (outputDesc->getActivityCount(clientVolSrc) > 0) {
2487 if (outputDesc->getActivityCount(clientVolSrc) == 1) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002488 // Automatically disable the remote submix input when output is stopped on a
2489 // re routing mix of type MIX_TYPE_RECORDERS
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002490 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
jiabin9a3361e2019-10-01 09:38:30 -07002491 if (isSingleDeviceType(
2492 outputDesc->devices().types(), &audio_is_remote_submix_device) &&
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002493 policyMix != nullptr &&
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002494 policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002495 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2496 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002497 policyMix->mDeviceAddress,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002498 "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07002499 }
2500 }
2501 bool forceDeviceUpdate = false;
Eric Laurent72af8012023-03-15 17:36:22 +01002502 if (client->hasPreferredDevice(true) &&
2503 outputDesc->sameExclusivePreferredDevicesCount() < 2) {
François Gaffiec005e562018-11-06 15:04:49 +01002504 checkStrategyRoute(client->strategy(), AUDIO_IO_HANDLE_NONE);
Eric Laurent97ac8712018-07-27 18:59:02 -07002505 forceDeviceUpdate = true;
2506 }
2507
Eric Laurente552edb2014-03-10 17:42:56 -07002508 // decrement usage count of this stream on the output
Eric Laurent592dd7b2018-08-05 18:58:48 -07002509 outputDesc->setClientActive(client, false);
Paul McLeanaa981192015-03-21 09:55:15 -07002510
Eric Laurente552edb2014-03-10 17:42:56 -07002511 // store time at which the stream was stopped - see isStreamActive()
François Gaffie1c878552018-11-22 16:53:21 +01002512 if (outputDesc->getActivityCount(clientVolSrc) == 0 || forceDeviceUpdate) {
François Gaffiec005e562018-11-06 15:04:49 +01002513 outputDesc->setStopTime(client, systemTime());
François Gaffie11d30102018-11-02 16:09:09 +01002514 DeviceVector newDevices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Francois Gaffie3523ab32021-06-22 13:24:34 +02002515
2516 // If the routing does not change, if an output is routed on a device using HwGain
2517 // (aka setAudioPortConfig) and there are still active clients following different
2518 // volume group(s), force reapply volume
2519 bool requiresVolumeCheck = outputDesc->getActivityCount(clientVolSrc) == 0 &&
2520 outputDesc->useHwGain() && outputDesc->isAnyActive(VOLUME_SOURCE_NONE);
2521
Eric Laurente552edb2014-03-10 17:42:56 -07002522 // delay the device switch by twice the latency because stopOutput() is executed when
2523 // the track stop() command is received and at that time the audio track buffer can
2524 // still contain data that needs to be drained. The latency only covers the audio HAL
2525 // and kernel buffers. Also the latency does not always include additional delay in the
2526 // audio path (audio DSP, CODEC ...)
Francois Gaffie3523ab32021-06-22 13:24:34 +02002527 setOutputDevices(outputDesc, newDevices, false, outputDesc->latency()*2,
2528 nullptr, true /*requiresMuteCheck*/, requiresVolumeCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07002529
2530 // force restoring the device selection on other active outputs if it differs from the
2531 // one being selected for this output
jiabin3ff8d7d2022-12-13 06:27:44 +00002532 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent57de36c2016-09-28 16:59:11 -07002533 uint32_t delayMs = outputDesc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -07002534 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01002535 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07002536 if (desc != outputDesc &&
Eric Laurente552edb2014-03-10 17:42:56 -07002537 desc->isActive() &&
2538 outputDesc->sharesHwModuleWith(desc) &&
François Gaffie11d30102018-11-02 16:09:09 +01002539 (newDevices != desc->devices())) {
2540 DeviceVector newDevices2 = getNewOutputDevices(desc, false /*fromCache*/);
2541 bool force = desc->devices() != newDevices2;
Eric Laurentf3a5a602018-05-22 18:42:55 -07002542
jiabin3ff8d7d2022-12-13 06:27:44 +00002543 if (desc->mUsePreferredMixerAttributes && force) {
2544 // If the device is using preferred mixer attributes, the output need to
2545 // reopen with default configuration when the new selected devices are
2546 // different from current routing devices.
2547 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices2);
2548 continue;
2549 }
François Gaffie11d30102018-11-02 16:09:09 +01002550 setOutputDevices(desc, newDevices2, force, delayMs);
2551
Eric Laurent57de36c2016-09-28 16:59:11 -07002552 // re-apply device specific volume if not done by setOutputDevice()
2553 if (!force) {
François Gaffie11d30102018-11-02 16:09:09 +01002554 applyStreamVolumes(desc, newDevices2.types(), delayMs);
Eric Laurent57de36c2016-09-28 16:59:11 -07002555 }
Eric Laurente552edb2014-03-10 17:42:56 -07002556 }
2557 }
jiabin3ff8d7d2022-12-13 06:27:44 +00002558 reopenOutputsWithDevices(outputsToReopen);
Eric Laurente552edb2014-03-10 17:42:56 -07002559 // update the outputs if stopping one with a stream that can affect notification routing
2560 handleNotificationRoutingForStream(stream);
2561 }
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002562
2563 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
2564 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Jean-Michel Trivi74e01fa2019-02-25 12:18:09 -08002565 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), false, outputDesc);
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002566 }
2567
François Gaffiec005e562018-11-06 15:04:49 +01002568 if (followsSameRouting(client->attributes(), attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07002569 selectOutputForMusicEffects();
2570 }
Eric Laurent96d1dda2022-03-14 17:14:19 +01002571
2572 checkLeBroadcastRoutes(wasLeUnicastActive, outputDesc, outputDesc->latency()*2);
2573
Eric Laurente552edb2014-03-10 17:42:56 -07002574 return NO_ERROR;
2575 } else {
Eric Laurentc75307b2015-03-17 15:29:32 -07002576 ALOGW("stopOutput() refcount is already 0");
Eric Laurente552edb2014-03-10 17:42:56 -07002577 return INVALID_OPERATION;
2578 }
2579}
2580
jiabinbce0c1d2020-10-05 11:20:18 -07002581bool AudioPolicyManager::releaseOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002582{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002583 ALOGV("%s portId %d", __FUNCTION__, portId);
2584
2585 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2586 if (outputDesc == 0) {
Andy Hung39efb7a2018-09-26 15:39:28 -07002587 // If an output descriptor is closed due to a device routing change,
2588 // then there are race conditions with releaseOutput from tracks
2589 // that may be destroyed (with no PlaybackThread) or a PlaybackThread
2590 // destroyed shortly thereafter.
2591 //
2592 // Here we just log a warning, instead of a fatal error.
Eric Laurent8fc147b2018-07-22 19:13:55 -07002593 ALOGW("releaseOutput() no output for client %d", portId);
jiabinbce0c1d2020-10-05 11:20:18 -07002594 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002595 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002596
2597 ALOGV("releaseOutput() %d", outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -07002598
Jaideep Sharma7bf382e2020-11-26 17:07:29 +05302599 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
2600 if (outputDesc->isClientActive(client)) {
2601 ALOGW("releaseOutput() inactivates portId %d in good faith", portId);
2602 stopOutput(portId);
2603 }
2604
Eric Laurent8fc147b2018-07-22 19:13:55 -07002605 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
2606 if (outputDesc->mDirectOpenCount <= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07002607 ALOGW("releaseOutput() invalid open count %d for output %d",
Eric Laurent8fc147b2018-07-22 19:13:55 -07002608 outputDesc->mDirectOpenCount, outputDesc->mIoHandle);
jiabinbce0c1d2020-10-05 11:20:18 -07002609 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002610 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002611 if (--outputDesc->mDirectOpenCount == 0) {
2612 closeOutput(outputDesc->mIoHandle);
Eric Laurentb52c1522014-05-20 11:27:36 -07002613 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07002614 }
2615 }
Jaideep Sharma7bf382e2020-11-26 17:07:29 +05302616
Andy Hung39efb7a2018-09-26 15:39:28 -07002617 outputDesc->removeClient(portId);
jiabinbce0c1d2020-10-05 11:20:18 -07002618 if (outputDesc->mPendingReopenToQueryProfiles && outputDesc->getClientCount() == 0) {
2619 // The output is pending reopened to query dynamic profiles and
2620 // there is no active clients
2621 closeOutput(outputDesc->mIoHandle);
2622 sp<SwAudioOutputDescriptor> newOutputDesc = openOutputWithProfileAndDevice(
2623 outputDesc->mProfile, mEngine->getActiveMediaDevices(mAvailableOutputDevices));
2624 if (newOutputDesc == nullptr) {
2625 ALOGE("%s failed to open output", __func__);
2626 }
2627 return true;
2628 }
2629 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002630}
2631
Eric Laurentcaf7f482014-11-25 17:50:47 -08002632status_t AudioPolicyManager::getInputForAttr(const audio_attributes_t *attr,
2633 audio_io_handle_t *input,
Mikhail Naganov2996f672019-04-18 12:29:59 -07002634 audio_unique_id_t riid,
Eric Laurentcaf7f482014-11-25 17:50:47 -08002635 audio_session_t session,
Svet Ganov3e5f14f2021-05-13 22:51:08 +00002636 const AttributionSourceState& attributionSource,
jiabinf1c73972022-04-14 16:28:52 -07002637 audio_config_base_t *config,
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002638 audio_input_flags_t flags,
Eric Laurent2ac76942017-06-22 17:17:09 -07002639 audio_port_handle_t *selectedDeviceId,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002640 input_type_t *inputType,
2641 audio_port_handle_t *portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002642{
François Gaffiec005e562018-11-06 15:04:49 +01002643 ALOGV("%s() source %d, sampling rate %d, format %#x, channel mask %#x, session %d, "
Eric Laurent2f2c1982021-06-02 14:03:11 +02002644 "flags %#x attributes=%s requested device ID %d",
2645 __func__, attr->source, config->sample_rate, config->format, config->channel_mask,
2646 session, flags, toString(*attr).c_str(), *selectedDeviceId);
Eric Laurente552edb2014-03-10 17:42:56 -07002647
Eric Laurentad2e7b92017-09-14 20:06:42 -07002648 status_t status = NO_ERROR;
Francois Gaffie716e1432019-01-14 16:58:59 +01002649 audio_attributes_t attributes = *attr;
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002650 sp<AudioPolicyMix> policyMix;
François Gaffie11d30102018-11-02 16:09:09 +01002651 sp<DeviceDescriptor> device;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002652 sp<AudioInputDescriptor> inputDesc;
François Gaffie1b4753e2023-02-06 10:36:33 +01002653 sp<AudioInputDescriptor> previousInputDesc;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002654 sp<RecordClientDescriptor> clientDesc;
2655 audio_port_handle_t requestedDeviceId = *selectedDeviceId;
Svet Ganov3e5f14f2021-05-13 22:51:08 +00002656 uid_t uid = VALUE_OR_RETURN_STATUS(aidl2legacy_int32_t_uid_t(attributionSource.uid));
Eric Laurent8f42ea12018-08-08 09:08:25 -07002657 bool isSoundTrigger;
Eric Laurent8f42ea12018-08-08 09:08:25 -07002658
2659 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
2660 if (*portId != AUDIO_PORT_HANDLE_NONE) {
2661 return INVALID_OPERATION;
2662 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08002663
Francois Gaffie716e1432019-01-14 16:58:59 +01002664 if (attr->source == AUDIO_SOURCE_DEFAULT) {
2665 attributes.source = AUDIO_SOURCE_MIC;
Eric Laurentfe231122017-11-17 17:48:06 -08002666 }
2667
Paul McLean466dc8e2015-04-17 13:15:36 -06002668 // Explicit routing?
Pattydd807582021-11-04 21:01:03 +08002669 sp<DeviceDescriptor> explicitRoutingDevice =
François Gaffie11d30102018-11-02 16:09:09 +01002670 mAvailableInputDevices.getDeviceFromId(*selectedDeviceId);
Paul McLean466dc8e2015-04-17 13:15:36 -06002671
Eric Laurentad2e7b92017-09-14 20:06:42 -07002672 // special case for mmap capture: if an input IO handle is specified, we reuse this input if
2673 // possible
2674 if ((flags & AUDIO_INPUT_FLAG_MMAP_NOIRQ) == AUDIO_INPUT_FLAG_MMAP_NOIRQ &&
2675 *input != AUDIO_IO_HANDLE_NONE) {
2676 ssize_t index = mInputs.indexOfKey(*input);
2677 if (index < 0) {
2678 ALOGW("getInputForAttr() unknown MMAP input %d", *input);
2679 status = BAD_VALUE;
2680 goto error;
2681 }
2682 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002683 RecordClientVector clients = inputDesc->getClientsForSession(session);
2684 if (clients.size() == 0) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07002685 ALOGW("getInputForAttr() unknown session %d on input %d", session, *input);
2686 status = BAD_VALUE;
2687 goto error;
2688 }
2689 // For MMAP mode, the first call to getInputForAttr() is made on behalf of audioflinger.
2690 // The second call is for the first active client and sets the UID. Any further call
Eric Laurent331679c2018-04-16 17:03:16 -07002691 // corresponds to a new client and is only permitted from the same UID.
2692 // If the first UID is silenced, allow a new UID connection and replace with new UID
Eric Laurent8f42ea12018-08-08 09:08:25 -07002693 if (clients.size() > 1) {
2694 for (const auto& client : clients) {
2695 // The client map is ordered by key values (portId) and portIds are allocated
2696 // incrementaly. So the first client in this list is the one opened by audio flinger
2697 // when the mmap stream is created and should be ignored as it does not correspond
2698 // to an actual client
2699 if (client == *clients.cbegin()) {
2700 continue;
2701 }
2702 if (uid != client->uid() && !client->isSilenced()) {
2703 ALOGW("getInputForAttr() bad uid %d for client %d uid %d",
2704 uid, client->portId(), client->uid());
2705 status = INVALID_OPERATION;
2706 goto error;
2707 }
Eric Laurent331679c2018-04-16 17:03:16 -07002708 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002709 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002710 *inputType = API_INPUT_LEGACY;
François Gaffie11d30102018-11-02 16:09:09 +01002711 device = inputDesc->getDevice();
Eric Laurentad2e7b92017-09-14 20:06:42 -07002712
Eric Laurentfecbceb2021-02-09 14:46:43 +01002713 ALOGV("%s reusing MMAP input %d for session %d", __FUNCTION__, *input, session);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002714 goto exit;
Eric Laurentad2e7b92017-09-14 20:06:42 -07002715 }
2716
2717 *input = AUDIO_IO_HANDLE_NONE;
2718 *inputType = API_INPUT_INVALID;
2719
Francois Gaffie716e1432019-01-14 16:58:59 +01002720 if (attributes.source == AUDIO_SOURCE_REMOTE_SUBMIX &&
Jan Sebechlebskybc56bcd2022-09-26 13:15:19 +02002721 extractAddressFromAudioAttributes(attributes).has_value()) {
Francois Gaffie716e1432019-01-14 16:58:59 +01002722 status = mPolicyMixes.getInputMixForAttr(attributes, &policyMix);
Eric Laurentad2e7b92017-09-14 20:06:42 -07002723 if (status != NO_ERROR) {
jiabinc1de2df2019-05-07 14:26:40 -07002724 ALOGW("%s could not find input mix for attr %s",
2725 __func__, toString(attributes).c_str());
Eric Laurentad2e7b92017-09-14 20:06:42 -07002726 goto error;
François Gaffie036e1e92015-03-19 10:16:24 +01002727 }
jiabinc1de2df2019-05-07 14:26:40 -07002728 device = mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2729 String8(attr->tags + strlen("addr=")),
2730 AUDIO_FORMAT_DEFAULT);
2731 if (device == nullptr) {
Kevin Rocard04ed0462019-05-02 17:53:24 -07002732 ALOGW("%s could not find in Remote Submix device for source %d, tags %s",
jiabinc1de2df2019-05-07 14:26:40 -07002733 __func__, attributes.source, attributes.tags);
2734 status = BAD_VALUE;
2735 goto error;
2736 }
2737
Kevin Rocard25f9b052019-02-27 15:08:54 -08002738 if (is_mix_loopback_render(policyMix->mRouteFlags)) {
2739 *inputType = API_INPUT_MIX_PUBLIC_CAPTURE_PLAYBACK;
2740 } else {
2741 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
2742 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002743 } else {
François Gaffie11d30102018-11-02 16:09:09 +01002744 if (explicitRoutingDevice != nullptr) {
2745 device = explicitRoutingDevice;
Eric Laurent97ac8712018-07-27 18:59:02 -07002746 } else {
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01002747 // Prevent from storing invalid requested device id in clients
2748 requestedDeviceId = AUDIO_PORT_HANDLE_NONE;
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02002749 device = mEngine->getInputDeviceForAttributes(attributes, uid, session, &policyMix);
yuanjiahsu4069d5d2021-04-19 07:54:27 +08002750 ALOGV_IF(device != nullptr, "%s found device type is 0x%X",
2751 __FUNCTION__, device->type());
Eric Laurent97ac8712018-07-27 18:59:02 -07002752 }
François Gaffie11d30102018-11-02 16:09:09 +01002753 if (device == nullptr) {
Francois Gaffie716e1432019-01-14 16:58:59 +01002754 ALOGW("getInputForAttr() could not find device for source %d", attributes.source);
Eric Laurentad2e7b92017-09-14 20:06:42 -07002755 status = BAD_VALUE;
2756 goto error;
Eric Laurent275e8e92014-11-30 15:14:47 -08002757 }
Alden DSouzab7d20782021-02-08 08:51:42 -08002758 if (device->type() == AUDIO_DEVICE_IN_ECHO_REFERENCE) {
2759 *inputType = API_INPUT_MIX_CAPTURE;
2760 } else if (policyMix) {
François Gaffie11d30102018-11-02 16:09:09 +01002761 ALOG_ASSERT(policyMix->mMixType == MIX_TYPE_RECORDERS, "Invalid Mix Type");
2762 // there is an external policy, but this input is attached to a mix of recorders,
2763 // meaning it receives audio injected into the framework, so the recorder doesn't
2764 // know about it and is therefore considered "legacy"
2765 *inputType = API_INPUT_LEGACY;
2766 } else if (audio_is_remote_submix_device(device->type())) {
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002767 *inputType = API_INPUT_MIX_CAPTURE;
François Gaffie11d30102018-11-02 16:09:09 +01002768 } else if (device->type() == AUDIO_DEVICE_IN_TELEPHONY_RX) {
Eric Laurent82db2692015-08-07 13:59:42 -07002769 *inputType = API_INPUT_TELEPHONY_RX;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002770 } else {
2771 *inputType = API_INPUT_LEGACY;
Eric Laurentc722f302014-12-10 11:21:49 -08002772 }
Ravi Kumar Alamandab367f5b2015-08-25 08:21:37 -07002773
Eric Laurent599c7582015-12-07 18:05:55 -08002774 }
2775
François Gaffiec005e562018-11-06 15:04:49 +01002776 *input = getInputForDevice(device, session, attributes, config, flags, policyMix);
Eric Laurent599c7582015-12-07 18:05:55 -08002777 if (*input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07002778 status = INVALID_OPERATION;
jiabinf1c73972022-04-14 16:28:52 -07002779 AudioProfileVector profiles;
2780 status_t ret = getProfilesForDevices(
2781 DeviceVector(device), profiles, flags, true /*isInput*/);
2782 if (ret == NO_ERROR && !profiles.empty()) {
Robert Wub98ff1b2023-06-15 22:53:58 +00002783 const auto channels = profiles[0]->getChannels();
2784 if (!channels.empty() && (channels.find(config->channel_mask) == channels.end())) {
2785 config->channel_mask = *channels.begin();
2786 }
2787 const auto sampleRates = profiles[0]->getSampleRates();
2788 if (!sampleRates.empty() &&
2789 (sampleRates.find(config->sample_rate) == sampleRates.end())) {
2790 config->sample_rate = *sampleRates.begin();
2791 }
jiabinf1c73972022-04-14 16:28:52 -07002792 config->format = profiles[0]->getFormat();
2793 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002794 goto error;
Eric Laurent599c7582015-12-07 18:05:55 -08002795 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08002796
Eric Laurent8f42ea12018-08-08 09:08:25 -07002797exit:
2798
François Gaffiec005e562018-11-06 15:04:49 +01002799 *selectedDeviceId = mAvailableInputDevices.contains(device) ?
2800 device->getId() : AUDIO_PORT_HANDLE_NONE;
Eric Laurent2ac76942017-06-22 17:17:09 -07002801
Francois Gaffie716e1432019-01-14 16:58:59 +01002802 isSoundTrigger = attributes.source == AUDIO_SOURCE_HOTWORD &&
Carter Hsud0cce2e2019-05-03 17:36:28 +08002803 mSoundTriggerSessions.indexOfKey(session) >= 0;
jiabin4ef93452019-09-10 14:29:54 -07002804 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002805
Mikhail Naganov2996f672019-04-18 12:29:59 -07002806 clientDesc = new RecordClientDescriptor(*portId, riid, uid, session, attributes, *config,
Francois Gaffie716e1432019-01-14 16:58:59 +01002807 requestedDeviceId, attributes.source, flags,
2808 isSoundTrigger);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002809 inputDesc = mInputs.valueFor(*input);
François Gaffie1b4753e2023-02-06 10:36:33 +01002810 // Move (if found) effect for the client session to its input
2811 mEffects.moveEffectsForIo(session, *input, &mInputs, mpClientInterface);
Andy Hung39efb7a2018-09-26 15:39:28 -07002812 inputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002813
2814 ALOGV("getInputForAttr() returns input %d type %d selectedDeviceId %d for port ID %d",
2815 *input, *inputType, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07002816
Eric Laurent599c7582015-12-07 18:05:55 -08002817 return NO_ERROR;
Eric Laurentad2e7b92017-09-14 20:06:42 -07002818
2819error:
Eric Laurentad2e7b92017-09-14 20:06:42 -07002820 return status;
Eric Laurent599c7582015-12-07 18:05:55 -08002821}
2822
2823
François Gaffie11d30102018-11-02 16:09:09 +01002824audio_io_handle_t AudioPolicyManager::getInputForDevice(const sp<DeviceDescriptor> &device,
Eric Laurent599c7582015-12-07 18:05:55 -08002825 audio_session_t session,
François Gaffiec005e562018-11-06 15:04:49 +01002826 const audio_attributes_t &attributes,
jiabinf1c73972022-04-14 16:28:52 -07002827 audio_config_base_t *config,
Eric Laurent599c7582015-12-07 18:05:55 -08002828 audio_input_flags_t flags,
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002829 const sp<AudioPolicyMix> &policyMix)
Eric Laurent599c7582015-12-07 18:05:55 -08002830{
2831 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
François Gaffiec005e562018-11-06 15:04:49 +01002832 audio_source_t halInputSource = attributes.source;
Eric Laurent599c7582015-12-07 18:05:55 -08002833 bool isSoundTrigger = false;
2834
François Gaffiec005e562018-11-06 15:04:49 +01002835 if (attributes.source == AUDIO_SOURCE_HOTWORD) {
Eric Laurent599c7582015-12-07 18:05:55 -08002836 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
2837 if (index >= 0) {
2838 input = mSoundTriggerSessions.valueFor(session);
2839 isSoundTrigger = true;
2840 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_HW_HOTWORD);
2841 ALOGV("SoundTrigger capture on session %d input %d", session, input);
2842 } else {
2843 halInputSource = AUDIO_SOURCE_VOICE_RECOGNITION;
Eric Laurent5dbe4712014-09-19 19:04:57 -07002844 }
François Gaffiec005e562018-11-06 15:04:49 +01002845 } else if (attributes.source == AUDIO_SOURCE_VOICE_COMMUNICATION &&
Eric Laurentfe231122017-11-17 17:48:06 -08002846 audio_is_linear_pcm(config->format)) {
Haynes Mathew George851d3ff2017-06-19 20:01:57 -07002847 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_VOIP_TX);
Eric Laurent5dbe4712014-09-19 19:04:57 -07002848 }
2849
Carter Hsua3abb402021-10-26 11:11:20 +08002850 if (attributes.source == AUDIO_SOURCE_ULTRASOUND) {
2851 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_ULTRASOUND);
2852 }
2853
Eric Laurentfe231122017-11-17 17:48:06 -08002854 // sampling rate and flags may be updated by getInputProfile
2855 uint32_t profileSamplingRate = (config->sample_rate == 0) ?
2856 SAMPLE_RATE_HZ_DEFAULT : config->sample_rate;
jiabin2fd710d2022-05-02 23:20:22 +00002857 audio_format_t profileFormat = config->format;
Eric Laurentfe231122017-11-17 17:48:06 -08002858 audio_channel_mask_t profileChannelMask = config->channel_mask;
Andy Hungf129b032015-04-07 13:45:50 -07002859 audio_input_flags_t profileFlags = flags;
jiabin2fd710d2022-05-02 23:20:22 +00002860 // find a compatible input profile (not necessarily identical in parameters)
2861 sp<IOProfile> profile = getInputProfile(
2862 device, profileSamplingRate, profileFormat, profileChannelMask, profileFlags);
2863 if (profile == nullptr) {
2864 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07002865 }
jiabin2fd710d2022-05-02 23:20:22 +00002866
Glenn Kasten05ddca52016-02-11 08:17:12 -08002867 // Pick input sampling rate if not specified by client
Eric Laurentfe231122017-11-17 17:48:06 -08002868 uint32_t samplingRate = config->sample_rate;
Glenn Kasten05ddca52016-02-11 08:17:12 -08002869 if (samplingRate == 0) {
2870 samplingRate = profileSamplingRate;
2871 }
Eric Laurente552edb2014-03-10 17:42:56 -07002872
Eric Laurent322b4d22015-04-03 15:57:54 -07002873 if (profile->getModuleHandle() == 0) {
2874 ALOGE("getInputForAttr(): HW module %s not opened", profile->getModuleName());
Eric Laurent599c7582015-12-07 18:05:55 -08002875 return input;
Eric Laurentcf2c0212014-07-25 16:20:43 -07002876 }
2877
Eric Laurentec376dc2021-04-08 20:41:22 +02002878 // Reuse an already opened input if a client with the same session ID already exists
2879 // on that input
2880 for (size_t i = 0; i < mInputs.size(); i++) {
2881 sp <AudioInputDescriptor> desc = mInputs.valueAt(i);
2882 if (desc->mProfile != profile) {
2883 continue;
2884 }
2885 RecordClientVector clients = desc->clientsList();
2886 for (const auto &client : clients) {
2887 if (session == client->session()) {
2888 return desc->mIoHandle;
2889 }
2890 }
2891 }
2892
Eric Laurent3974e3b2017-12-07 17:58:43 -08002893 if (!profile->canOpenNewIo()) {
Eric Laurent4eb58f12018-12-07 16:41:02 -08002894 for (size_t i = 0; i < mInputs.size(); ) {
Eric Laurentc529cf62020-04-17 18:19:10 -07002895 sp<AudioInputDescriptor> desc = mInputs.valueAt(i);
Eric Laurent4eb58f12018-12-07 16:41:02 -08002896 if (desc->mProfile != profile) {
Carter Hsu9a645a92019-05-15 12:15:32 +08002897 i++;
Eric Laurent4eb58f12018-12-07 16:41:02 -08002898 continue;
2899 }
2900 // if sound trigger, reuse input if used by other sound trigger on same session
2901 // else
2902 // reuse input if active client app is not in IDLE state
2903 //
2904 RecordClientVector clients = desc->clientsList();
2905 bool doClose = false;
2906 for (const auto& client : clients) {
2907 if (isSoundTrigger != client->isSoundTrigger()) {
2908 continue;
2909 }
2910 if (client->isSoundTrigger()) {
2911 if (session == client->session()) {
2912 return desc->mIoHandle;
2913 }
2914 continue;
2915 }
2916 if (client->active() && client->appState() != APP_STATE_IDLE) {
2917 return desc->mIoHandle;
2918 }
2919 doClose = true;
2920 }
2921 if (doClose) {
2922 closeInput(desc->mIoHandle);
2923 } else {
2924 i++;
2925 }
2926 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002927 }
2928
Eric Laurentfe231122017-11-17 17:48:06 -08002929 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07002930
Eric Laurentfe231122017-11-17 17:48:06 -08002931 audio_config_t lConfig = AUDIO_CONFIG_INITIALIZER;
2932 lConfig.sample_rate = profileSamplingRate;
2933 lConfig.channel_mask = profileChannelMask;
2934 lConfig.format = profileFormat;
Eric Laurente3014102017-05-03 11:15:43 -07002935
François Gaffie11d30102018-11-02 16:09:09 +01002936 status_t status = inputDesc->open(&lConfig, device, halInputSource, profileFlags, &input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07002937
2938 // only accept input with the exact requested set of parameters
Eric Laurent599c7582015-12-07 18:05:55 -08002939 if (status != NO_ERROR || input == AUDIO_IO_HANDLE_NONE ||
Eric Laurentfe231122017-11-17 17:48:06 -08002940 (profileSamplingRate != lConfig.sample_rate) ||
2941 !audio_formats_match(profileFormat, lConfig.format) ||
2942 (profileChannelMask != lConfig.channel_mask)) {
2943 ALOGW("getInputForAttr() failed opening input: sampling rate %d"
Glenn Kasten49f36ba2017-12-06 13:02:02 -08002944 ", format %#x, channel mask %#x",
Eric Laurentfe231122017-11-17 17:48:06 -08002945 profileSamplingRate, profileFormat, profileChannelMask);
Eric Laurent599c7582015-12-07 18:05:55 -08002946 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfe231122017-11-17 17:48:06 -08002947 inputDesc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07002948 }
Eric Laurent599c7582015-12-07 18:05:55 -08002949 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07002950 }
2951
Eric Laurentc722f302014-12-10 11:21:49 -08002952 inputDesc->mPolicyMix = policyMix;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002953
Eric Laurent599c7582015-12-07 18:05:55 -08002954 addInput(input, inputDesc);
Eric Laurentb52c1522014-05-20 11:27:36 -07002955 mpClientInterface->onAudioPortListUpdate();
Paul McLean466dc8e2015-04-17 13:15:36 -06002956
Eric Laurent599c7582015-12-07 18:05:55 -08002957 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07002958}
2959
Eric Laurent4eb58f12018-12-07 16:41:02 -08002960status_t AudioPolicyManager::startInput(audio_port_handle_t portId)
Eric Laurentbb948092017-01-23 18:33:30 -08002961{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002962 ALOGV("%s portId %d", __FUNCTION__, portId);
2963
2964 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2965 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002966 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurentd52a28c2020-08-21 17:10:39 -07002967 return DEAD_OBJECT;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002968 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002969 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07002970 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002971 if (client->active()) {
2972 ALOGW("%s input %d client %d already started", __FUNCTION__, input, client->portId());
2973 return INVALID_OPERATION;
Eric Laurent4dc68062014-07-28 17:26:49 -07002974 }
2975
Eric Laurent8f42ea12018-08-08 09:08:25 -07002976 audio_session_t session = client->session();
2977
Eric Laurent4eb58f12018-12-07 16:41:02 -08002978 ALOGV("%s input:%d, session:%d)", __FUNCTION__, input, session);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002979
Eric Laurent4eb58f12018-12-07 16:41:02 -08002980 Vector<sp<AudioInputDescriptor>> activeInputs = mInputs.getActiveInputs();
Eric Laurent74708e72017-04-07 17:13:42 -07002981
Eric Laurent4eb58f12018-12-07 16:41:02 -08002982 status_t status = inputDesc->start();
2983 if (status != NO_ERROR) {
2984 return status;
Eric Laurent74708e72017-04-07 17:13:42 -07002985 }
Eric Laurente552edb2014-03-10 17:42:56 -07002986
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002987 // increment activity count before calling getNewInputDevice() below as only active sessions
Eric Laurent313d1e72016-01-29 09:56:57 -08002988 // are considered for device selection
Eric Laurent8f42ea12018-08-08 09:08:25 -07002989 inputDesc->setClientActive(client, true);
Eric Laurent313d1e72016-01-29 09:56:57 -08002990
Eric Laurent8f42ea12018-08-08 09:08:25 -07002991 // indicate active capture to sound trigger service if starting capture from a mic on
2992 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01002993 sp<DeviceDescriptor> device = getNewInputDevice(inputDesc);
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002994 if (device != nullptr) {
2995 status = setInputDevice(input, device, true /* force */);
2996 } else {
2997 ALOGW("%s no new input device can be found for descriptor %d",
2998 __FUNCTION__, inputDesc->getId());
2999 status = BAD_VALUE;
3000 }
Eric Laurente552edb2014-03-10 17:42:56 -07003001
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003002 if (status == NO_ERROR && inputDesc->activeCount() == 1) {
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003003 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003004 // if input maps to a dynamic policy with an activity listener, notify of state change
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003005 if ((policyMix != nullptr)
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003006 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
3007 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
Eric Laurent8f42ea12018-08-08 09:08:25 -07003008 MIX_STATE_MIXING);
Eric Laurent733ce942017-12-07 12:18:25 -08003009 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08003010
François Gaffie11d30102018-11-02 16:09:09 +01003011 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
3012 if (primaryInputDevices.contains(device) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07003013 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 1) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07003014 mpClientInterface->setSoundTriggerCaptureState(true);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003015 }
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07003016
Eric Laurent8f42ea12018-08-08 09:08:25 -07003017 // automatically enable the remote submix output when input is started if not
3018 // used by a policy mix of type MIX_TYPE_RECORDERS
3019 // For remote submix (a virtual device), we open only one input per capture request.
François Gaffie11d30102018-11-02 16:09:09 +01003020 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003021 String8 address = String8("");
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003022 if (policyMix == nullptr) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003023 address = String8("0");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003024 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
3025 address = policyMix->mDeviceAddress;
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07003026 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07003027 if (address != "") {
3028 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
3029 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08003030 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurentc722f302014-12-10 11:21:49 -08003031 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07003032 }
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003033 } else if (status != NO_ERROR) {
3034 // Restore client activity state.
3035 inputDesc->setClientActive(client, false);
3036 inputDesc->stop();
Eric Laurente552edb2014-03-10 17:42:56 -07003037 }
3038
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003039 ALOGV("%s input %d source = %d status = %d exit",
3040 __FUNCTION__, input, client->source(), status);
Eric Laurente552edb2014-03-10 17:42:56 -07003041
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003042 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07003043}
3044
Eric Laurent8fc147b2018-07-22 19:13:55 -07003045status_t AudioPolicyManager::stopInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07003046{
Eric Laurent8fc147b2018-07-22 19:13:55 -07003047 ALOGV("%s portId %d", __FUNCTION__, portId);
3048
3049 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
3050 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003051 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07003052 return BAD_VALUE;
3053 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07003054 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07003055 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003056 if (!client->active()) {
3057 ALOGW("%s input %d client %d already stopped", __FUNCTION__, input, client->portId());
Eric Laurente552edb2014-03-10 17:42:56 -07003058 return INVALID_OPERATION;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003059 }
Carter Hsue6139d52021-07-08 10:30:20 +08003060 auto old_source = inputDesc->source();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003061 inputDesc->setClientActive(client, false);
Paul McLean466dc8e2015-04-17 13:15:36 -06003062
Eric Laurent8f42ea12018-08-08 09:08:25 -07003063 inputDesc->stop();
3064 if (inputDesc->isActive()) {
Carter Hsue6139d52021-07-08 10:30:20 +08003065 auto current_source = inputDesc->source();
3066 setInputDevice(input, getNewInputDevice(inputDesc),
3067 old_source != current_source /* force */);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003068 } else {
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003069 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003070 // if input maps to a dynamic policy with an activity listener, notify of state change
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003071 if ((policyMix != nullptr)
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003072 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
3073 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
Eric Laurent8f42ea12018-08-08 09:08:25 -07003074 MIX_STATE_IDLE);
Eric Laurent84332aa2016-01-28 22:19:18 +00003075 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07003076
3077 // automatically disable the remote submix output when input is stopped if not
3078 // used by a policy mix of type MIX_TYPE_RECORDERS
François Gaffie11d30102018-11-02 16:09:09 +01003079 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003080 String8 address = String8("");
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003081 if (policyMix == nullptr) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003082 address = String8("0");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003083 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
3084 address = policyMix->mDeviceAddress;
Eric Laurent8f42ea12018-08-08 09:08:25 -07003085 }
3086 if (address != "") {
3087 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
3088 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08003089 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003090 }
3091 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07003092 resetInputDevice(input);
3093
3094 // indicate inactive capture to sound trigger service if stopping capture from a mic on
3095 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01003096 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
3097 if (primaryInputDevices.contains(inputDesc->getDevice()) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07003098 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07003099 mpClientInterface->setSoundTriggerCaptureState(false);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003100 }
3101 inputDesc->clearPreemptedSessions();
Eric Laurente552edb2014-03-10 17:42:56 -07003102 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003103 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07003104}
3105
Eric Laurent8fc147b2018-07-22 19:13:55 -07003106void AudioPolicyManager::releaseInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07003107{
Eric Laurent8fc147b2018-07-22 19:13:55 -07003108 ALOGV("%s portId %d", __FUNCTION__, portId);
3109
3110 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
3111 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003112 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07003113 return;
3114 }
Andy Hung39efb7a2018-09-26 15:39:28 -07003115 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8fc147b2018-07-22 19:13:55 -07003116 audio_io_handle_t input = inputDesc->mIoHandle;
3117
Eric Laurent8f42ea12018-08-08 09:08:25 -07003118 ALOGV("%s %d", __FUNCTION__, input);
Paul McLean466dc8e2015-04-17 13:15:36 -06003119
Andy Hung39efb7a2018-09-26 15:39:28 -07003120 inputDesc->removeClient(portId);
François Gaffie1b4753e2023-02-06 10:36:33 +01003121 mEffects.putOrphanEffects(client->session(), input, &mInputs, mpClientInterface);
Andy Hung39efb7a2018-09-26 15:39:28 -07003122 if (inputDesc->getClientCount() > 0) {
3123 ALOGV("%s(%d) %zu clients remaining", __func__, portId, inputDesc->getClientCount());
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003124 return;
3125 }
3126
Eric Laurent05b90f82014-08-27 15:32:29 -07003127 closeInput(input);
Eric Laurentb52c1522014-05-20 11:27:36 -07003128 mpClientInterface->onAudioPortListUpdate();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003129 ALOGV("%s exit", __FUNCTION__);
Eric Laurente552edb2014-03-10 17:42:56 -07003130}
3131
Eric Laurent8f42ea12018-08-08 09:08:25 -07003132void AudioPolicyManager::closeActiveClients(const sp<AudioInputDescriptor>& input)
Eric Laurent8fc147b2018-07-22 19:13:55 -07003133{
Eric Laurent8f42ea12018-08-08 09:08:25 -07003134 RecordClientVector clients = input->clientsList(true);
Eric Laurent8fc147b2018-07-22 19:13:55 -07003135
3136 for (const auto& client : clients) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003137 closeClient(client->portId());
Eric Laurent8fc147b2018-07-22 19:13:55 -07003138 }
3139}
3140
Eric Laurent8f42ea12018-08-08 09:08:25 -07003141void AudioPolicyManager::closeClient(audio_port_handle_t portId)
3142{
3143 stopInput(portId);
3144 releaseInput(portId);
3145}
Eric Laurent8fc147b2018-07-22 19:13:55 -07003146
Eric Laurent0dd51852019-04-19 18:18:58 -07003147void AudioPolicyManager::checkCloseInputs() {
3148 // After connecting or disconnecting an input device, close input if:
3149 // - it has no client (was just opened to check profile) OR
3150 // - none of its supported devices are connected anymore OR
3151 // - one of its clients cannot be routed to one of its supported
3152 // devices anymore. Otherwise update device selection
3153 std::vector<audio_io_handle_t> inputsToClose;
3154 for (size_t i = 0; i < mInputs.size(); i++) {
3155 const sp<AudioInputDescriptor> input = mInputs.valueAt(i);
3156 if (input->clientsList().size() == 0
Eric Laurent85732f42020-03-19 11:31:10 -07003157 || !mAvailableInputDevices.containsAtLeastOne(input->supportedDevices())) {
Eric Laurent0dd51852019-04-19 18:18:58 -07003158 inputsToClose.push_back(mInputs.keyAt(i));
3159 } else {
3160 bool close = false;
3161 for (const auto& client : input->clientsList()) {
3162 sp<DeviceDescriptor> device =
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02003163 mEngine->getInputDeviceForAttributes(client->attributes(), client->uid(),
3164 client->session());
Eric Laurent0dd51852019-04-19 18:18:58 -07003165 if (!input->supportedDevices().contains(device)) {
3166 close = true;
3167 break;
3168 }
3169 }
3170 if (close) {
3171 inputsToClose.push_back(mInputs.keyAt(i));
3172 } else {
3173 setInputDevice(input->mIoHandle, getNewInputDevice(input));
3174 }
3175 }
3176 }
3177
3178 for (const audio_io_handle_t handle : inputsToClose) {
3179 ALOGV("%s closing input %d", __func__, handle);
3180 closeInput(handle);
Eric Laurent05b90f82014-08-27 15:32:29 -07003181 }
Eric Laurentd4692962014-05-05 18:13:44 -07003182}
3183
François Gaffie251c7f02018-11-07 10:41:08 +01003184void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream, int indexMin, int indexMax)
Eric Laurente552edb2014-03-10 17:42:56 -07003185{
3186 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08003187 if (indexMin < 0 || indexMax < 0) {
3188 ALOGE("%s for stream %d: invalid min %d or max %d", __func__, stream , indexMin, indexMax);
3189 return;
3190 }
Eric Laurentf5aa58d2019-02-22 18:20:11 -08003191 getVolumeCurves(stream).initVolume(indexMin, indexMax);
Eric Laurent28d09f02016-03-08 10:43:05 -08003192
3193 // initialize other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08003194 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
3195 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08003196 continue;
3197 }
Eric Laurentf5aa58d2019-02-22 18:20:11 -08003198 getVolumeCurves((audio_stream_type_t)curStream).initVolume(indexMin, indexMax);
Eric Laurent223fd5c2014-11-11 13:43:36 -08003199 }
Eric Laurente552edb2014-03-10 17:42:56 -07003200}
3201
Eric Laurente0720872014-03-11 09:30:41 -07003202status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
François Gaffie53615e22015-03-19 09:24:12 +01003203 int index,
3204 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07003205{
François Gaffieaaac0fd2018-11-22 17:56:39 +01003206 auto attributes = mEngine->getAttributesForStreamType(stream);
Eric Laurent242a9f82020-03-23 15:57:04 -07003207 if (attributes == AUDIO_ATTRIBUTES_INITIALIZER) {
3208 ALOGW("%s: no group for stream %s, bailing out", __func__, toString(stream).c_str());
3209 return NO_ERROR;
3210 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01003211 ALOGV("%s: stream %s attributes=%s", __func__,
3212 toString(stream).c_str(), toString(attributes).c_str());
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003213 return setVolumeIndexForAttributes(attributes, index, device);
Eric Laurente552edb2014-03-10 17:42:56 -07003214}
3215
Eric Laurente0720872014-03-11 09:30:41 -07003216status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
François Gaffieaaac0fd2018-11-22 17:56:39 +01003217 int *index,
3218 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07003219{
François Gaffiec005e562018-11-06 15:04:49 +01003220 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
3221 // stream by the engine.
jiabin9a3361e2019-10-01 09:38:30 -07003222 DeviceTypeSet deviceTypes = {device};
Eric Laurent5a2b6292016-04-14 18:05:57 -07003223 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
jiabin9a3361e2019-10-01 09:38:30 -07003224 deviceTypes = mEngine->getOutputDevicesForStream(
3225 stream, true /*fromCache*/).types();
Eric Laurente552edb2014-03-10 17:42:56 -07003226 }
jiabin9a3361e2019-10-01 09:38:30 -07003227 return getVolumeIndex(getVolumeCurves(stream), *index, deviceTypes);
Eric Laurente552edb2014-03-10 17:42:56 -07003228}
3229
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003230status_t AudioPolicyManager::setVolumeIndexForAttributes(const audio_attributes_t &attributes,
François Gaffiecfe17322018-11-07 13:41:29 +01003231 int index,
3232 audio_devices_t device)
3233{
3234 // Get Volume group matching the Audio Attributes
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003235 auto group = mEngine->getVolumeGroupForAttributes(attributes);
3236 if (group == VOLUME_GROUP_NONE) {
3237 ALOGD("%s: no group matching with %s", __FUNCTION__, toString(attributes).c_str());
François Gaffiecfe17322018-11-07 13:41:29 +01003238 return BAD_VALUE;
3239 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003240 ALOGV("%s: group %d matching with %s", __FUNCTION__, group, toString(attributes).c_str());
François Gaffiecfe17322018-11-07 13:41:29 +01003241 status_t status = NO_ERROR;
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003242 IVolumeCurves &curves = getVolumeCurves(attributes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01003243 VolumeSource vs = toVolumeSource(group);
Eric Laurentf9cccec2022-11-16 19:12:00 +01003244 // AUDIO_STREAM_BLUETOOTH_SCO is only used for volume control so we remap
3245 // to AUDIO_STREAM_VOICE_CALL to match with relevant playback activity
3246 VolumeSource activityVs = (vs == toVolumeSource(AUDIO_STREAM_BLUETOOTH_SCO, false)) ?
3247 toVolumeSource(AUDIO_STREAM_VOICE_CALL, false) : vs;
François Gaffieaaac0fd2018-11-22 17:56:39 +01003248 product_strategy_t strategy = mEngine->getProductStrategyForAttributes(attributes);
3249
3250 status = setVolumeCurveIndex(index, device, curves);
3251 if (status != NO_ERROR) {
3252 ALOGE("%s failed to set curve index for group %d device 0x%X", __func__, group, device);
3253 return status;
3254 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003255
jiabin9a3361e2019-10-01 09:38:30 -07003256 DeviceTypeSet curSrcDevices;
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003257 auto curCurvAttrs = curves.getAttributes();
3258 if (!curCurvAttrs.empty() && curCurvAttrs.front() != defaultAttr) {
3259 auto attr = curCurvAttrs.front();
jiabin9a3361e2019-10-01 09:38:30 -07003260 curSrcDevices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false).types();
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003261 } else if (!curves.getStreamTypes().empty()) {
3262 auto stream = curves.getStreamTypes().front();
jiabin9a3361e2019-10-01 09:38:30 -07003263 curSrcDevices = mEngine->getOutputDevicesForStream(stream, false).types();
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003264 } else {
3265 ALOGE("%s: Invalid src %d: no valid attributes nor stream",__func__, vs);
3266 return BAD_VALUE;
3267 }
jiabin9a3361e2019-10-01 09:38:30 -07003268 audio_devices_t curSrcDevice = Volume::getDeviceForVolume(curSrcDevices);
3269 resetDeviceTypes(curSrcDevices, curSrcDevice);
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003270
François Gaffiecfe17322018-11-07 13:41:29 +01003271 // update volume on all outputs and streams matching the following:
3272 // - The requested stream (or a stream matching for volume control) is active on the output
3273 // - The device (or devices) selected by the engine for this stream includes
3274 // the requested device
3275 // - For non default requested device, currently selected device on the output is either the
3276 // requested device or one of the devices selected by the engine for this stream
3277 // - For default requested device (AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME), apply volume only if
3278 // no specific device volume value exists for currently selected device.
François Gaffieaaac0fd2018-11-22 17:56:39 +01003279 for (size_t i = 0; i < mOutputs.size(); i++) {
3280 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
jiabin9a3361e2019-10-01 09:38:30 -07003281 DeviceTypeSet curDevices = desc->devices().types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01003282
jiabin9a3361e2019-10-01 09:38:30 -07003283 if (curDevices.erase(AUDIO_DEVICE_OUT_SPEAKER_SAFE)) {
3284 curDevices.insert(AUDIO_DEVICE_OUT_SPEAKER);
Robert Lee5e66e792019-04-03 18:37:15 +08003285 }
Eric Laurentf9cccec2022-11-16 19:12:00 +01003286
3287 if (!(desc->isActive(activityVs) || isInCallOrScreening())) {
François Gaffieed91f582020-01-31 10:35:37 +01003288 continue;
3289 }
3290 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME &&
3291 curDevices.find(device) == curDevices.end()) {
3292 continue;
3293 }
3294 bool applyVolume = false;
3295 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
3296 curSrcDevices.insert(device);
3297 applyVolume = (curSrcDevices.find(
3298 Volume::getDeviceForVolume(curDevices)) != curSrcDevices.end());
3299 } else {
3300 applyVolume = !curves.hasVolumeIndexForDevice(curSrcDevice);
3301 }
3302 if (!applyVolume) {
3303 continue; // next output
3304 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01003305 // Inter / intra volume group priority management: Loop on strategies arranged by priority
3306 // If a higher priority strategy is active, and the output is routed to a device with a
3307 // HW Gain management, do not change the volume
François Gaffieaaac0fd2018-11-22 17:56:39 +01003308 if (desc->useHwGain()) {
François Gaffieed91f582020-01-31 10:35:37 +01003309 applyVolume = false;
Francois Gaffie593634d2021-06-22 13:31:31 +02003310 // If the volume source is active with higher priority source, ensure at least Sw Muted
3311 desc->setSwMute((index == 0), vs, curves.getStreamTypes(), curDevices, 0 /*delayMs*/);
François Gaffieaaac0fd2018-11-22 17:56:39 +01003312 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
3313 auto activeClients = desc->clientsList(true /*activeOnly*/, productStrategy,
3314 false /*preferredDevice*/);
3315 if (activeClients.empty()) {
3316 continue;
3317 }
3318 bool isPreempted = false;
3319 bool isHigherPriority = productStrategy < strategy;
3320 for (const auto &client : activeClients) {
Eric Laurentf9cccec2022-11-16 19:12:00 +01003321 if (isHigherPriority && (client->volumeSource() != activityVs)) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01003322 ALOGV("%s: Strategy=%d (\nrequester:\n"
3323 " group %d, volumeGroup=%d attributes=%s)\n"
3324 " higher priority source active:\n"
3325 " volumeGroup=%d attributes=%s) \n"
3326 " on output %zu, bailing out", __func__, productStrategy,
3327 group, group, toString(attributes).c_str(),
3328 client->volumeSource(), toString(client->attributes()).c_str(), i);
3329 applyVolume = false;
3330 isPreempted = true;
3331 break;
3332 }
3333 // However, continue for loop to ensure no higher prio clients running on output
Eric Laurentf9cccec2022-11-16 19:12:00 +01003334 if (client->volumeSource() == activityVs) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01003335 applyVolume = true;
3336 }
3337 }
3338 if (isPreempted || applyVolume) {
3339 break;
3340 }
3341 }
3342 if (!applyVolume) {
3343 continue; // next output
3344 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01003345 }
François Gaffieed91f582020-01-31 10:35:37 +01003346 //FIXME: workaround for truncated touch sounds
3347 // delayed volume change for system stream to be removed when the problem is
3348 // handled by system UI
3349 status_t volStatus = checkAndSetVolume(
3350 curves, vs, index, desc, curDevices,
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003351 ((vs == toVolumeSource(AUDIO_STREAM_SYSTEM, false))?
François Gaffieed91f582020-01-31 10:35:37 +01003352 TOUCH_SOUND_FIXED_DELAY_MS : 0));
3353 if (volStatus != NO_ERROR) {
3354 status = volStatus;
François Gaffieaaac0fd2018-11-22 17:56:39 +01003355 }
3356 }
François Gaffiecfe17322018-11-07 13:41:29 +01003357 mpClientInterface->onAudioVolumeGroupChanged(group, 0 /*flags*/);
3358 return status;
3359}
3360
François Gaffieaaac0fd2018-11-22 17:56:39 +01003361status_t AudioPolicyManager::setVolumeCurveIndex(int index,
François Gaffiecfe17322018-11-07 13:41:29 +01003362 audio_devices_t device,
3363 IVolumeCurves &volumeCurves)
3364{
3365 // VOICE_CALL stream has minVolumeIndex > 0 but can be muted directly by an
3366 // app that has MODIFY_PHONE_STATE permission.
François Gaffieaaac0fd2018-11-22 17:56:39 +01003367 bool hasVoice = hasVoiceStream(volumeCurves.getStreamTypes());
3368 if (((index < volumeCurves.getVolumeIndexMin()) && !(hasVoice && index == 0)) ||
François Gaffiecfe17322018-11-07 13:41:29 +01003369 (index > volumeCurves.getVolumeIndexMax())) {
3370 ALOGD("%s: wrong index %d min=%d max=%d", __FUNCTION__, index,
3371 volumeCurves.getVolumeIndexMin(), volumeCurves.getVolumeIndexMax());
3372 return BAD_VALUE;
3373 }
3374 if (!audio_is_output_device(device)) {
3375 return BAD_VALUE;
3376 }
3377
3378 // Force max volume if stream cannot be muted
3379 if (!volumeCurves.canBeMuted()) index = volumeCurves.getVolumeIndexMax();
3380
François Gaffieaaac0fd2018-11-22 17:56:39 +01003381 ALOGV("%s device %08x, index %d", __FUNCTION__ , device, index);
François Gaffiecfe17322018-11-07 13:41:29 +01003382 volumeCurves.addCurrentVolumeIndex(device, index);
3383 return NO_ERROR;
3384}
3385
3386status_t AudioPolicyManager::getVolumeIndexForAttributes(const audio_attributes_t &attr,
3387 int &index,
3388 audio_devices_t device)
3389{
3390 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
3391 // stream by the engine.
jiabin9a3361e2019-10-01 09:38:30 -07003392 DeviceTypeSet deviceTypes = {device};
François Gaffiecfe17322018-11-07 13:41:29 +01003393 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
Mikhail Naganovbb990f22022-06-15 00:46:43 +00003394 deviceTypes = mEngine->getOutputDevicesForAttributes(
jiabin9a3361e2019-10-01 09:38:30 -07003395 attr, nullptr, true /*fromCache*/).types();
François Gaffiecfe17322018-11-07 13:41:29 +01003396 }
jiabin9a3361e2019-10-01 09:38:30 -07003397 return getVolumeIndex(getVolumeCurves(attr), index, deviceTypes);
François Gaffiecfe17322018-11-07 13:41:29 +01003398}
3399
3400status_t AudioPolicyManager::getVolumeIndex(const IVolumeCurves &curves,
3401 int &index,
jiabin9a3361e2019-10-01 09:38:30 -07003402 const DeviceTypeSet& deviceTypes) const
François Gaffiecfe17322018-11-07 13:41:29 +01003403{
Mikhail Naganovbb990f22022-06-15 00:46:43 +00003404 if (!isSingleDeviceType(deviceTypes, audio_is_output_device)) {
François Gaffiecfe17322018-11-07 13:41:29 +01003405 return BAD_VALUE;
3406 }
jiabin9a3361e2019-10-01 09:38:30 -07003407 index = curves.getVolumeIndex(deviceTypes);
3408 ALOGV("%s: device %s index %d", __FUNCTION__, dumpDeviceTypes(deviceTypes).c_str(), index);
François Gaffiecfe17322018-11-07 13:41:29 +01003409 return NO_ERROR;
3410}
3411
3412status_t AudioPolicyManager::getMinVolumeIndexForAttributes(const audio_attributes_t &attr,
3413 int &index)
3414{
3415 index = getVolumeCurves(attr).getVolumeIndexMin();
3416 return NO_ERROR;
3417}
3418
3419status_t AudioPolicyManager::getMaxVolumeIndexForAttributes(const audio_attributes_t &attr,
3420 int &index)
3421{
3422 index = getVolumeCurves(attr).getVolumeIndexMax();
3423 return NO_ERROR;
3424}
3425
Eric Laurent36829f92017-04-07 19:04:42 -07003426audio_io_handle_t AudioPolicyManager::selectOutputForMusicEffects()
Eric Laurente552edb2014-03-10 17:42:56 -07003427{
3428 // select one output among several suitable for global effects.
3429 // The priority is as follows:
3430 // 1: An offloaded output. If the effect ends up not being offloadable,
3431 // AudioFlinger will invalidate the track and the offloaded output
3432 // will be closed causing the effect to be moved to a PCM output.
3433 // 2: A deep buffer output
Eric Laurent36829f92017-04-07 19:04:42 -07003434 // 3: The primary output
3435 // 4: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07003436
François Gaffiec005e562018-11-06 15:04:49 +01003437 DeviceVector devices = mEngine->getOutputDevicesForAttributes(
3438 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
François Gaffie11d30102018-11-02 16:09:09 +01003439 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07003440
Eric Laurent36829f92017-04-07 19:04:42 -07003441 if (outputs.size() == 0) {
3442 return AUDIO_IO_HANDLE_NONE;
3443 }
Eric Laurente552edb2014-03-10 17:42:56 -07003444
Eric Laurent36829f92017-04-07 19:04:42 -07003445 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
3446 bool activeOnly = true;
3447
3448 while (output == AUDIO_IO_HANDLE_NONE) {
3449 audio_io_handle_t outputOffloaded = AUDIO_IO_HANDLE_NONE;
3450 audio_io_handle_t outputDeepBuffer = AUDIO_IO_HANDLE_NONE;
3451 audio_io_handle_t outputPrimary = AUDIO_IO_HANDLE_NONE;
3452
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003453 for (audio_io_handle_t output : outputs) {
3454 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
Eric Laurent83d17c22019-04-02 17:10:01 -07003455 if (activeOnly && !desc->isActive(toVolumeSource(AUDIO_STREAM_MUSIC))) {
Eric Laurent36829f92017-04-07 19:04:42 -07003456 continue;
3457 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003458 ALOGV("selectOutputForMusicEffects activeOnly %d output %d flags 0x%08x",
3459 activeOnly, output, desc->mFlags);
Eric Laurent36829f92017-04-07 19:04:42 -07003460 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003461 outputOffloaded = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003462 }
3463 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003464 outputDeepBuffer = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003465 }
3466 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003467 outputPrimary = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003468 }
3469 }
3470 if (outputOffloaded != AUDIO_IO_HANDLE_NONE) {
3471 output = outputOffloaded;
3472 } else if (outputDeepBuffer != AUDIO_IO_HANDLE_NONE) {
3473 output = outputDeepBuffer;
3474 } else if (outputPrimary != AUDIO_IO_HANDLE_NONE) {
3475 output = outputPrimary;
3476 } else {
3477 output = outputs[0];
3478 }
3479 activeOnly = false;
3480 }
3481
3482 if (output != mMusicEffectOutput) {
François Gaffie1b4753e2023-02-06 10:36:33 +01003483 mEffects.moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output,
3484 mpClientInterface);
Eric Laurent36829f92017-04-07 19:04:42 -07003485 mMusicEffectOutput = output;
3486 }
3487
3488 ALOGV("selectOutputForMusicEffects selected output %d", output);
Eric Laurente552edb2014-03-10 17:42:56 -07003489 return output;
3490}
3491
Eric Laurent36829f92017-04-07 19:04:42 -07003492audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc __unused)
3493{
3494 return selectOutputForMusicEffects();
3495}
3496
Eric Laurente0720872014-03-11 09:30:41 -07003497status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07003498 audio_io_handle_t io,
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08003499 product_strategy_t strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07003500 int session,
3501 int id)
3502{
Eric Laurentb82e6b72019-11-22 17:25:04 -08003503 if (session != AUDIO_SESSION_DEVICE) {
3504 ssize_t index = mOutputs.indexOfKey(io);
Eric Laurente552edb2014-03-10 17:42:56 -07003505 if (index < 0) {
Eric Laurentb82e6b72019-11-22 17:25:04 -08003506 index = mInputs.indexOfKey(io);
3507 if (index < 0) {
3508 ALOGW("registerEffect() unknown io %d", io);
3509 return INVALID_OPERATION;
3510 }
Eric Laurente552edb2014-03-10 17:42:56 -07003511 }
3512 }
Eric Laurentbf8f69f2022-03-25 17:48:38 +01003513 bool isMusicEffect = (session != AUDIO_SESSION_OUTPUT_STAGE)
3514 && ((strategy == streamToStrategy(AUDIO_STREAM_MUSIC)
3515 || strategy == PRODUCT_STRATEGY_NONE));
3516 return mEffects.registerEffect(desc, io, session, id, isMusicEffect);
Eric Laurente552edb2014-03-10 17:42:56 -07003517}
3518
Eric Laurentc241b0d2018-11-28 09:08:49 -08003519status_t AudioPolicyManager::unregisterEffect(int id)
3520{
3521 if (mEffects.getEffect(id) == nullptr) {
3522 return INVALID_OPERATION;
3523 }
Eric Laurentc241b0d2018-11-28 09:08:49 -08003524 if (mEffects.isEffectEnabled(id)) {
3525 ALOGW("%s effect %d enabled", __FUNCTION__, id);
3526 setEffectEnabled(id, false);
3527 }
3528 return mEffects.unregisterEffect(id);
3529}
3530
3531status_t AudioPolicyManager::setEffectEnabled(int id, bool enabled)
3532{
3533 sp<EffectDescriptor> effect = mEffects.getEffect(id);
3534 if (effect == nullptr) {
3535 return INVALID_OPERATION;
3536 }
3537
3538 status_t status = mEffects.setEffectEnabled(id, enabled);
3539 if (status == NO_ERROR) {
3540 mInputs.trackEffectEnabled(effect, enabled);
3541 }
3542 return status;
3543}
3544
Eric Laurent6c796322019-04-09 14:13:17 -07003545
3546status_t AudioPolicyManager::moveEffectsToIo(const std::vector<int>& ids, audio_io_handle_t io)
3547{
3548 mEffects.moveEffects(ids, io);
3549 return NO_ERROR;
3550}
3551
Eric Laurentc75307b2015-03-17 15:29:32 -07003552bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
3553{
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003554 auto vs = toVolumeSource(stream, false);
3555 return vs != VOLUME_SOURCE_NONE ? mOutputs.isActive(vs, inPastMs) : false;
Eric Laurentc75307b2015-03-17 15:29:32 -07003556}
3557
3558bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream, uint32_t inPastMs) const
3559{
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003560 auto vs = toVolumeSource(stream, false);
3561 return vs != VOLUME_SOURCE_NONE ? mOutputs.isActiveRemotely(vs, inPastMs) : false;
Eric Laurentc75307b2015-03-17 15:29:32 -07003562}
3563
Eric Laurente0720872014-03-11 09:30:41 -07003564bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07003565{
3566 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003567 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08003568 if (inputDescriptor->isSourceActive(source)) {
Eric Laurente552edb2014-03-10 17:42:56 -07003569 return true;
3570 }
3571 }
3572 return false;
3573}
3574
Eric Laurent275e8e92014-11-30 15:14:47 -08003575// Register a list of custom mixes with their attributes and format.
3576// When a mix is registered, corresponding input and output profiles are
3577// added to the remote submix hw module. The profile contains only the
3578// parameters (sampling rate, format...) specified by the mix.
3579// The corresponding input remote submix device is also connected.
3580//
3581// When a remote submix device is connected, the address is checked to select the
3582// appropriate profile and the corresponding input or output stream is opened.
3583//
3584// When capture starts, getInputForAttr() will:
3585// - 1 look for a mix matching the address passed in attribtutes tags if any
3586// - 2 if none found, getDeviceForInputSource() will:
3587// - 2.1 look for a mix matching the attributes source
3588// - 2.2 if none found, default to device selection by policy rules
3589// At this time, the corresponding output remote submix device is also connected
3590// and active playback use cases can be transferred to this mix if needed when reconnecting
3591// after AudioTracks are invalidated
3592//
3593// When playback starts, getOutputForAttr() will:
3594// - 1 look for a mix matching the address passed in attribtutes tags if any
3595// - 2 if none found, look for a mix matching the attributes usage
3596// - 3 if none found, default to device and output selection by policy rules.
3597
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003598status_t AudioPolicyManager::registerPolicyMixes(const Vector<AudioMix>& mixes)
Eric Laurent275e8e92014-11-30 15:14:47 -08003599{
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003600 ALOGV("registerPolicyMixes() %zu mix(es)", mixes.size());
3601 status_t res = NO_ERROR;
Eric Laurentc209fe42020-06-05 18:11:23 -07003602 bool checkOutputs = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003603 sp<HwModule> rSubmixModule;
3604 // examine each mix's route type
3605 for (size_t i = 0; i < mixes.size(); i++) {
Eric Laurent97ac8712018-07-27 18:59:02 -07003606 AudioMix mix = mixes[i];
Kevin Rocard153f92d2018-12-18 18:33:28 -08003607 // Only capture of playback is allowed in LOOP_BACK & RENDER mode
3608 if (is_mix_loopback_render(mix.mRouteFlags) && mix.mMixType != MIX_TYPE_PLAYERS) {
3609 ALOGE("Unsupported Policy Mix %zu of %zu: "
3610 "Only capture of playback is allowed in LOOP_BACK & RENDER mode",
3611 i, mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003612 res = INVALID_OPERATION;
Eric Laurent275e8e92014-11-30 15:14:47 -08003613 break;
3614 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08003615 // LOOP_BACK and LOOP_BACK | RENDER have the same remote submix backend and are handled
3616 // in the same way.
Eric Laurent97ac8712018-07-27 18:59:02 -07003617 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003618 ALOGV("registerPolicyMixes() mix %zu of %zu is LOOP_BACK %d", i, mixes.size(),
3619 mix.mRouteFlags);
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003620 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003621 rSubmixModule = mHwModules.getModuleFromName(
3622 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
3623 if (rSubmixModule == 0) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003624 ALOGE("Unable to find audio module for submix, aborting mix %zu registration",
Mikhail Naganovd4120142017-12-06 15:49:22 -08003625 i);
3626 res = INVALID_OPERATION;
3627 break;
3628 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003629 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003630
Eric Laurent97ac8712018-07-27 18:59:02 -07003631 String8 address = mix.mDeviceAddress;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003632 audio_devices_t deviceTypeToMakeAvailable;
Eric Laurent97ac8712018-07-27 18:59:02 -07003633 if (mix.mMixType == MIX_TYPE_PLAYERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07003634 mix.mDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003635 deviceTypeToMakeAvailable = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
3636 } else {
3637 mix.mDeviceType = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
3638 deviceTypeToMakeAvailable = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Eric Laurent97ac8712018-07-27 18:59:02 -07003639 }
François Gaffie036e1e92015-03-19 10:16:24 +01003640
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003641 if (mPolicyMixes.registerMix(mix, 0 /*output desc*/) != NO_ERROR) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003642 ALOGE("Error registering mix %zu for address %s", i, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003643 res = INVALID_OPERATION;
3644 break;
3645 }
Eric Laurent97ac8712018-07-27 18:59:02 -07003646 audio_config_t outputConfig = mix.mFormat;
3647 audio_config_t inputConfig = mix.mFormat;
Eric Laurentc529cf62020-04-17 18:19:10 -07003648 // NOTE: audio flinger mixer does not support mono output: configure remote submix HAL
3649 // in stereo and let audio flinger do the channel conversion if needed.
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003650 outputConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
3651 inputConfig.channel_mask = AUDIO_CHANNEL_IN_STEREO;
jiabin5740f082019-08-19 15:08:30 -07003652 rSubmixModule->addOutputProfile(address.c_str(), &outputConfig,
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003653 AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address);
jiabin5740f082019-08-19 15:08:30 -07003654 rSubmixModule->addInputProfile(address.c_str(), &inputConfig,
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003655 AUDIO_DEVICE_IN_REMOTE_SUBMIX, address);
François Gaffie036e1e92015-03-19 10:16:24 +01003656
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003657 if ((res = setDeviceConnectionStateInt(deviceTypeToMakeAvailable,
jiabinc1de2df2019-05-07 14:26:40 -07003658 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
3659 address.string(), "remote-submix", AUDIO_FORMAT_DEFAULT)) != NO_ERROR) {
3660 ALOGE("Failed to set remote submix device available, type %u, address %s",
3661 mix.mDeviceType, address.string());
3662 break;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003663 }
Eric Laurent97ac8712018-07-27 18:59:02 -07003664 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
3665 String8 address = mix.mDeviceAddress;
Eric Laurent2c80be02019-01-23 18:06:37 -08003666 audio_devices_t type = mix.mDeviceType;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003667 ALOGV(" registerPolicyMixes() mix %zu of %zu is RENDER, dev=0x%X addr=%s",
Eric Laurent2c80be02019-01-23 18:06:37 -08003668 i, mixes.size(), type, address.string());
3669
3670 sp<DeviceDescriptor> device = mHwModules.getDeviceDescriptor(
3671 mix.mDeviceType, mix.mDeviceAddress,
3672 String8(), AUDIO_FORMAT_DEFAULT);
3673 if (device == nullptr) {
3674 res = INVALID_OPERATION;
3675 break;
3676 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003677
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003678 bool foundOutput = false;
Eric Laurentc529cf62020-04-17 18:19:10 -07003679 // First try to find an already opened output supporting the device
3680 for (size_t j = 0 ; j < mOutputs.size() && !foundOutput && res == NO_ERROR; j++) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003681 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurent2c80be02019-01-23 18:06:37 -08003682
Eric Laurentc529cf62020-04-17 18:19:10 -07003683 if (!desc->isDuplicated() && desc->supportedDevices().contains(device)) {
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003684 if (mPolicyMixes.registerMix(mix, desc) != NO_ERROR) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003685 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
3686 address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003687 res = INVALID_OPERATION;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003688 } else {
3689 foundOutput = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003690 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003691 }
3692 }
Eric Laurentc529cf62020-04-17 18:19:10 -07003693 // If no output found, try to find a direct output profile supporting the device
3694 for (size_t i = 0; i < mHwModules.size() && !foundOutput && res == NO_ERROR; i++) {
3695 sp<HwModule> module = mHwModules[i];
3696 for (size_t j = 0;
3697 j < module->getOutputProfiles().size() && !foundOutput && res == NO_ERROR;
3698 j++) {
3699 sp<IOProfile> profile = module->getOutputProfiles()[j];
3700 if (profile->isDirectOutput() && profile->supportsDevice(device)) {
3701 if (mPolicyMixes.registerMix(mix, nullptr) != NO_ERROR) {
3702 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
3703 address.string());
3704 res = INVALID_OPERATION;
3705 } else {
3706 foundOutput = true;
3707 }
3708 }
3709 }
3710 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003711 if (res != NO_ERROR) {
3712 ALOGE(" Error registering mix %zu for device 0x%X addr %s",
Eric Laurent2c80be02019-01-23 18:06:37 -08003713 i, type, address.string());
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003714 res = INVALID_OPERATION;
3715 break;
3716 } else if (!foundOutput) {
3717 ALOGE(" Output not found for mix %zu for device 0x%X addr %s",
Eric Laurent2c80be02019-01-23 18:06:37 -08003718 i, type, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003719 res = INVALID_OPERATION;
3720 break;
Eric Laurentc209fe42020-06-05 18:11:23 -07003721 } else {
3722 checkOutputs = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003723 }
Eric Laurentc722f302014-12-10 11:21:49 -08003724 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003725 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003726 if (res != NO_ERROR) {
3727 unregisterPolicyMixes(mixes);
Eric Laurentc209fe42020-06-05 18:11:23 -07003728 } else if (checkOutputs) {
3729 checkForDeviceAndOutputChanges();
3730 updateCallAndOutputRouting();
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003731 }
3732 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08003733}
3734
3735status_t AudioPolicyManager::unregisterPolicyMixes(Vector<AudioMix> mixes)
3736{
Eric Laurent7b279bb2015-12-14 10:18:23 -08003737 ALOGV("unregisterPolicyMixes() num mixes %zu", mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003738 status_t res = NO_ERROR;
Eric Laurentc209fe42020-06-05 18:11:23 -07003739 bool checkOutputs = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003740 sp<HwModule> rSubmixModule;
3741 // examine each mix's route type
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003742 for (const auto& mix : mixes) {
3743 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie036e1e92015-03-19 10:16:24 +01003744
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003745 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003746 rSubmixModule = mHwModules.getModuleFromName(
3747 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
3748 if (rSubmixModule == 0) {
3749 res = INVALID_OPERATION;
3750 continue;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003751 }
3752 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003753
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003754 String8 address = mix.mDeviceAddress;
Eric Laurent275e8e92014-11-30 15:14:47 -08003755
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003756 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003757 res = INVALID_OPERATION;
3758 continue;
3759 }
3760
Kevin Rocard04ed0462019-05-02 17:53:24 -07003761 for (auto device : {AUDIO_DEVICE_IN_REMOTE_SUBMIX, AUDIO_DEVICE_OUT_REMOTE_SUBMIX}) {
3762 if (getDeviceConnectionState(device, address.string()) ==
3763 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
3764 res = setDeviceConnectionStateInt(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
3765 address.string(), "remote-submix",
3766 AUDIO_FORMAT_DEFAULT);
3767 if (res != OK) {
3768 ALOGE("Error making RemoteSubmix device unavailable for mix "
3769 "with type %d, address %s", device, address.string());
3770 }
3771 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003772 }
jiabin5740f082019-08-19 15:08:30 -07003773 rSubmixModule->removeOutputProfile(address.c_str());
3774 rSubmixModule->removeInputProfile(address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003775
Kevin Rocard153f92d2018-12-18 18:33:28 -08003776 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003777 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003778 res = INVALID_OPERATION;
3779 continue;
Eric Laurentc209fe42020-06-05 18:11:23 -07003780 } else {
3781 checkOutputs = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003782 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003783 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003784 }
Eric Laurentc209fe42020-06-05 18:11:23 -07003785 if (res == NO_ERROR && checkOutputs) {
3786 checkForDeviceAndOutputChanges();
3787 updateCallAndOutputRouting();
3788 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003789 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08003790}
3791
Mikhail Naganov100f0122018-11-29 11:22:16 -08003792void AudioPolicyManager::dumpManualSurroundFormats(String8 *dst) const
3793{
3794 size_t i = 0;
3795 constexpr size_t audioFormatPrefixLen = sizeof("AUDIO_FORMAT_");
3796 for (const auto& fmt : mManualSurroundFormats) {
3797 if (i++ != 0) dst->append(", ");
3798 std::string sfmt;
3799 FormatConverter::toString(fmt, sfmt);
3800 dst->append(sfmt.size() >= audioFormatPrefixLen ?
3801 sfmt.c_str() + audioFormatPrefixLen - 1 : sfmt.c_str());
3802 }
3803}
3804
Eric Laurentc529cf62020-04-17 18:19:10 -07003805// Returns true if all devices types match the predicate and are supported by one HW module
3806bool AudioPolicyManager::areAllDevicesSupported(
jiabin6a02d532020-08-07 11:56:38 -07003807 const AudioDeviceTypeAddrVector& devices,
Eric Laurentc529cf62020-04-17 18:19:10 -07003808 std::function<bool(audio_devices_t)> predicate,
Eric Laurent78fedbf2023-03-09 14:40:44 +01003809 const char *context,
3810 bool matchAddress) {
Eric Laurentc529cf62020-04-17 18:19:10 -07003811 for (size_t i = 0; i < devices.size(); i++) {
3812 sp<DeviceDescriptor> devDesc = mHwModules.getDeviceDescriptor(
jiabin0a488932020-08-07 17:32:40 -07003813 devices[i].mType, devices[i].getAddress(), String8(),
Eric Laurent78fedbf2023-03-09 14:40:44 +01003814 AUDIO_FORMAT_DEFAULT, false /*allowToCreate*/, matchAddress);
Eric Laurentc529cf62020-04-17 18:19:10 -07003815 if (devDesc == nullptr || (predicate != nullptr && !predicate(devices[i].mType))) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003816 ALOGE("%s: device type %#x address %s not supported or not match predicate",
jiabin0a488932020-08-07 17:32:40 -07003817 context, devices[i].mType, devices[i].getAddress());
Eric Laurentc529cf62020-04-17 18:19:10 -07003818 return false;
3819 }
3820 }
3821 return true;
3822}
3823
Oscar Azucena6acf34b2023-04-27 16:32:09 -07003824void AudioPolicyManager::changeOutputDevicesMuteState(
3825 const AudioDeviceTypeAddrVector& devices) {
3826 ALOGVV("%s() num devices %zu", __func__, devices.size());
3827
3828 std::vector<sp<SwAudioOutputDescriptor>> outputs =
3829 getSoftwareOutputsForDevices(devices);
3830
3831 for (size_t i = 0; i < outputs.size(); i++) {
3832 sp<SwAudioOutputDescriptor> outputDesc = outputs[i];
3833 DeviceVector prevDevices = outputDesc->devices();
3834 checkDeviceMuteStrategies(outputDesc, prevDevices, 0 /* delayMs */);
3835 }
3836}
3837
3838std::vector<sp<SwAudioOutputDescriptor>> AudioPolicyManager::getSoftwareOutputsForDevices(
3839 const AudioDeviceTypeAddrVector& devices) const
3840{
3841 std::vector<sp<SwAudioOutputDescriptor>> outputs;
3842 DeviceVector deviceDescriptors;
3843 for (size_t j = 0; j < devices.size(); j++) {
3844 sp<DeviceDescriptor> desc = mHwModules.getDeviceDescriptor(
3845 devices[j].mType, devices[j].getAddress(), String8(), AUDIO_FORMAT_DEFAULT);
3846 if (desc == nullptr || !audio_is_output_device(devices[j].mType)) {
3847 ALOGE("%s: device type %#x address %s not supported or not an output device",
3848 __func__, devices[j].mType, devices[j].getAddress());
3849 continue;
3850 }
3851 deviceDescriptors.add(desc);
3852 }
3853 for (size_t i = 0; i < mOutputs.size(); i++) {
3854 if (!mOutputs.valueAt(i)->supportsAtLeastOne(deviceDescriptors)) {
3855 continue;
3856 }
3857 outputs.push_back(mOutputs.valueAt(i));
3858 }
3859 return outputs;
3860}
3861
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003862status_t AudioPolicyManager::setUidDeviceAffinities(uid_t uid,
jiabin6a02d532020-08-07 11:56:38 -07003863 const AudioDeviceTypeAddrVector& devices) {
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003864 ALOGV("%s() uid=%d num devices %zu", __FUNCTION__, uid, devices.size());
Eric Laurentc529cf62020-04-17 18:19:10 -07003865 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
3866 return BAD_VALUE;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003867 }
3868 status_t res = mPolicyMixes.setUidDeviceAffinities(uid, devices);
Eric Laurentc529cf62020-04-17 18:19:10 -07003869 if (res != NO_ERROR) {
3870 ALOGE("%s() Could not set all device affinities for uid = %d", __FUNCTION__, uid);
3871 return res;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003872 }
Eric Laurentc529cf62020-04-17 18:19:10 -07003873
3874 checkForDeviceAndOutputChanges();
3875 updateCallAndOutputRouting();
3876
3877 return NO_ERROR;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003878}
3879
3880status_t AudioPolicyManager::removeUidDeviceAffinities(uid_t uid) {
3881 ALOGV("%s() uid=%d", __FUNCTION__, uid);
Oscar Azucena4b2a8212019-04-26 23:48:59 -07003882 status_t res = mPolicyMixes.removeUidDeviceAffinities(uid);
3883 if (res != NO_ERROR) {
Eric Laurentc529cf62020-04-17 18:19:10 -07003884 ALOGE("%s() Could not remove all device affinities for uid = %d",
Oscar Azucena4b2a8212019-04-26 23:48:59 -07003885 __FUNCTION__, uid);
3886 return INVALID_OPERATION;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003887 }
3888
Eric Laurentc529cf62020-04-17 18:19:10 -07003889 checkForDeviceAndOutputChanges();
3890 updateCallAndOutputRouting();
3891
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003892 return res;
3893}
3894
Eric Laurent2517af32020-11-25 15:31:27 +01003895
jiabin0a488932020-08-07 17:32:40 -07003896status_t AudioPolicyManager::setDevicesRoleForStrategy(product_strategy_t strategy,
3897 device_role_t role,
3898 const AudioDeviceTypeAddrVector &devices) {
3899 ALOGV("%s() strategy=%d role=%d %s", __func__, strategy, role,
3900 dumpAudioDeviceTypeAddrVector(devices).c_str());
Eric Laurentc529cf62020-04-17 18:19:10 -07003901
Eric Laurentc529cf62020-04-17 18:19:10 -07003902 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003903 return BAD_VALUE;
3904 }
jiabin0a488932020-08-07 17:32:40 -07003905 status_t status = mEngine->setDevicesRoleForStrategy(strategy, role, devices);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003906 if (status != NO_ERROR) {
jiabin0a488932020-08-07 17:32:40 -07003907 ALOGW("Engine could not set preferred devices %s for strategy %d role %d",
3908 dumpAudioDeviceTypeAddrVector(devices).c_str(), strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003909 return status;
3910 }
3911
3912 checkForDeviceAndOutputChanges();
Eric Laurent2517af32020-11-25 15:31:27 +01003913
3914 bool forceVolumeReeval = false;
3915 // FIXME: workaround for truncated touch sounds
3916 // to be removed when the problem is handled by system UI
3917 uint32_t delayMs = 0;
3918 if (strategy == mCommunnicationStrategy) {
3919 forceVolumeReeval = true;
3920 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
3921 updateInputRouting();
3922 }
3923 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003924
3925 return NO_ERROR;
3926}
3927
Oscar Azucena6acf34b2023-04-27 16:32:09 -07003928void AudioPolicyManager::updateCallAndOutputRouting(bool forceVolumeReeval, uint32_t delayMs,
3929 bool skipDelays)
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003930{
3931 uint32_t waitMs = 0;
Eric Laurent96d1dda2022-03-14 17:14:19 +01003932 bool wasLeUnicastActive = isLeUnicastActive();
Francois Gaffie19fd6c52021-02-04 17:02:59 +01003933 if (updateCallRouting(true /*fromCache*/, delayMs, &waitMs) == NO_ERROR) {
Eric Laurentb36b4ac2020-08-21 12:50:41 -07003934 // Only apply special touch sound delay once
3935 delayMs = 0;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003936 }
jiabin3ff8d7d2022-12-13 06:27:44 +00003937 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003938 for (size_t i = 0; i < mOutputs.size(); i++) {
3939 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
3940 DeviceVector newDevices = getNewOutputDevices(outputDesc, true /*fromCache*/);
Francois Gaffie601801d2021-06-22 13:27:39 +02003941 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) ||
3942 (outputDesc != mPrimaryOutput && !isTelephonyRxOrTx(outputDesc))) {
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003943 // As done in setDeviceConnectionState, we could also fix default device issue by
3944 // preventing the force re-routing in case of default dev that distinguishes on address.
3945 // Let's give back to engine full device choice decision however.
Francois Gaffie601801d2021-06-22 13:27:39 +02003946 bool forceRouting = !newDevices.isEmpty();
jiabin3ff8d7d2022-12-13 06:27:44 +00003947 if (outputDesc->mUsePreferredMixerAttributes && newDevices != outputDesc->devices()) {
3948 // If the device is using preferred mixer attributes, the output need to reopen
3949 // with default configuration when the new selected devices are different from
3950 // current routing devices.
3951 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices);
3952 continue;
3953 }
Francois Gaffie601801d2021-06-22 13:27:39 +02003954 waitMs = setOutputDevices(outputDesc, newDevices, forceRouting, delayMs, nullptr,
Oscar Azucena6acf34b2023-04-27 16:32:09 -07003955 !skipDelays /*requiresMuteCheck*/,
3956 !forceRouting /*requiresVolumeCheck*/, skipDelays);
Eric Laurentb36b4ac2020-08-21 12:50:41 -07003957 // Only apply special touch sound delay once
3958 delayMs = 0;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003959 }
3960 if (forceVolumeReeval && !newDevices.isEmpty()) {
3961 applyStreamVolumes(outputDesc, newDevices.types(), waitMs, true);
3962 }
3963 }
jiabin3ff8d7d2022-12-13 06:27:44 +00003964 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent96d1dda2022-03-14 17:14:19 +01003965 checkLeBroadcastRoutes(wasLeUnicastActive, nullptr, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003966}
3967
Eric Laurent2517af32020-11-25 15:31:27 +01003968void AudioPolicyManager::updateInputRouting() {
3969 for (const auto& activeDesc : mInputs.getActiveInputs()) {
Jaideep Sharma408349a2020-11-27 14:47:17 +05303970 // Skip for hotword recording as the input device switch
3971 // is handled within sound trigger HAL
3972 if (activeDesc->isSoundTrigger() && activeDesc->source() == AUDIO_SOURCE_HOTWORD) {
3973 continue;
3974 }
Eric Laurent2517af32020-11-25 15:31:27 +01003975 auto newDevice = getNewInputDevice(activeDesc);
3976 // Force new input selection if the new device can not be reached via current input
3977 if (activeDesc->mProfile->getSupportedDevices().contains(newDevice)) {
3978 setInputDevice(activeDesc->mIoHandle, newDevice);
3979 } else {
3980 closeInput(activeDesc->mIoHandle);
3981 }
3982 }
3983}
3984
Paul Wang5d7cdb52022-11-22 09:45:06 +00003985status_t
3986AudioPolicyManager::removeDevicesRoleForStrategy(product_strategy_t strategy,
3987 device_role_t role,
3988 const AudioDeviceTypeAddrVector &devices) {
3989 ALOGV("%s() strategy=%d role=%d %s", __func__, strategy, role,
3990 dumpAudioDeviceTypeAddrVector(devices).c_str());
3991
Eric Laurent78fedbf2023-03-09 14:40:44 +01003992 if (!areAllDevicesSupported(
3993 devices, audio_is_output_device, __func__, /*matchAddress*/false)) {
Paul Wang5d7cdb52022-11-22 09:45:06 +00003994 return BAD_VALUE;
3995 }
3996 status_t status = mEngine->removeDevicesRoleForStrategy(strategy, role, devices);
3997 if (status != NO_ERROR) {
3998 ALOGW("Engine could not remove devices %s for strategy %d role %d",
3999 dumpAudioDeviceTypeAddrVector(devices).c_str(), strategy, role);
4000 return status;
4001 }
4002
4003 checkForDeviceAndOutputChanges();
4004
4005 bool forceVolumeReeval = false;
4006 // TODO(b/263479999): workaround for truncated touch sounds
4007 // to be removed when the problem is handled by system UI
4008 uint32_t delayMs = 0;
4009 if (strategy == mCommunnicationStrategy) {
4010 forceVolumeReeval = true;
4011 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
4012 updateInputRouting();
4013 }
4014 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
4015
4016 return NO_ERROR;
4017}
4018
4019status_t AudioPolicyManager::clearDevicesRoleForStrategy(product_strategy_t strategy,
4020 device_role_t role)
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004021{
Eric Laurentfecbceb2021-02-09 14:46:43 +01004022 ALOGV("%s() strategy=%d role=%d", __func__, strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004023
Paul Wang5d7cdb52022-11-22 09:45:06 +00004024 status_t status = mEngine->clearDevicesRoleForStrategy(strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004025 if (status != NO_ERROR) {
Eric Laurent9ae44f32022-12-14 16:17:02 +01004026 ALOGW_IF(status != NAME_NOT_FOUND,
4027 "Engine could not remove device role for strategy %d status %d",
Eric Laurent2517af32020-11-25 15:31:27 +01004028 strategy, status);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004029 return status;
4030 }
4031
4032 checkForDeviceAndOutputChanges();
Eric Laurent2517af32020-11-25 15:31:27 +01004033
4034 bool forceVolumeReeval = false;
4035 // FIXME: workaround for truncated touch sounds
4036 // to be removed when the problem is handled by system UI
4037 uint32_t delayMs = 0;
4038 if (strategy == mCommunnicationStrategy) {
4039 forceVolumeReeval = true;
4040 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
4041 updateInputRouting();
4042 }
4043 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004044
4045 return NO_ERROR;
4046}
4047
jiabin0a488932020-08-07 17:32:40 -07004048status_t AudioPolicyManager::getDevicesForRoleAndStrategy(product_strategy_t strategy,
4049 device_role_t role,
4050 AudioDeviceTypeAddrVector &devices) {
4051 return mEngine->getDevicesForRoleAndStrategy(strategy, role, devices);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004052}
4053
Jiabin Huang3b98d322020-09-03 17:54:16 +00004054status_t AudioPolicyManager::setDevicesRoleForCapturePreset(
4055 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices) {
4056 ALOGV("%s() audioSource=%d role=%d %s", __func__, audioSource, role,
4057 dumpAudioDeviceTypeAddrVector(devices).c_str());
4058
Mikhail Naganov55773032020-10-01 15:08:13 -07004059 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00004060 return BAD_VALUE;
4061 }
4062 status_t status = mEngine->setDevicesRoleForCapturePreset(audioSource, role, devices);
4063 ALOGW_IF(status != NO_ERROR,
4064 "Engine could not set preferred devices %s for audio source %d role %d",
4065 dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
4066
4067 return status;
4068}
4069
4070status_t AudioPolicyManager::addDevicesRoleForCapturePreset(
4071 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices) {
4072 ALOGV("%s() audioSource=%d role=%d %s", __func__, audioSource, role,
4073 dumpAudioDeviceTypeAddrVector(devices).c_str());
4074
Mikhail Naganov55773032020-10-01 15:08:13 -07004075 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00004076 return BAD_VALUE;
4077 }
4078 status_t status = mEngine->addDevicesRoleForCapturePreset(audioSource, role, devices);
4079 ALOGW_IF(status != NO_ERROR,
4080 "Engine could not add preferred devices %s for audio source %d role %d",
4081 dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
4082
Eric Laurent2517af32020-11-25 15:31:27 +01004083 updateInputRouting();
Jiabin Huang3b98d322020-09-03 17:54:16 +00004084 return status;
4085}
4086
4087status_t AudioPolicyManager::removeDevicesRoleForCapturePreset(
4088 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector& devices)
4089{
4090 ALOGV("%s() audioSource=%d role=%d devices=%s", __func__, audioSource, role,
4091 dumpAudioDeviceTypeAddrVector(devices).c_str());
4092
Eric Laurent78fedbf2023-03-09 14:40:44 +01004093 if (!areAllDevicesSupported(
4094 devices, audio_call_is_input_device, __func__, /*matchAddress*/false)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00004095 return BAD_VALUE;
4096 }
4097
4098 status_t status = mEngine->removeDevicesRoleForCapturePreset(
4099 audioSource, role, devices);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004100 ALOGW_IF(status != NO_ERROR && status != NAME_NOT_FOUND,
Jiabin Huang3b98d322020-09-03 17:54:16 +00004101 "Engine could not remove devices role (%d) for capture preset %d", role, audioSource);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004102 if (status == NO_ERROR) {
4103 updateInputRouting();
4104 }
Jiabin Huang3b98d322020-09-03 17:54:16 +00004105 return status;
4106}
4107
4108status_t AudioPolicyManager::clearDevicesRoleForCapturePreset(audio_source_t audioSource,
4109 device_role_t role) {
4110 ALOGV("%s() audioSource=%d role=%d", __func__, audioSource, role);
4111
4112 status_t status = mEngine->clearDevicesRoleForCapturePreset(audioSource, role);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004113 ALOGW_IF(status != NO_ERROR && status != NAME_NOT_FOUND,
Jiabin Huang3b98d322020-09-03 17:54:16 +00004114 "Engine could not clear devices role (%d) for capture preset %d", role, audioSource);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004115 if (status == NO_ERROR) {
4116 updateInputRouting();
4117 }
Jiabin Huang3b98d322020-09-03 17:54:16 +00004118 return status;
4119}
4120
4121status_t AudioPolicyManager::getDevicesForRoleAndCapturePreset(
4122 audio_source_t audioSource, device_role_t role, AudioDeviceTypeAddrVector &devices) {
4123 return mEngine->getDevicesForRoleAndCapturePreset(audioSource, role, devices);
4124}
4125
Oscar Azucena90e77632019-11-27 17:12:28 -08004126status_t AudioPolicyManager::setUserIdDeviceAffinities(int userId,
jiabin6a02d532020-08-07 11:56:38 -07004127 const AudioDeviceTypeAddrVector& devices) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01004128 ALOGV("%s() userId=%d num devices %zu", __func__, userId, devices.size());
Eric Laurentc529cf62020-04-17 18:19:10 -07004129 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
4130 return BAD_VALUE;
Oscar Azucena90e77632019-11-27 17:12:28 -08004131 }
Oscar Azucena90e77632019-11-27 17:12:28 -08004132 status_t status = mPolicyMixes.setUserIdDeviceAffinities(userId, devices);
4133 if (status != NO_ERROR) {
4134 ALOGE("%s() could not set device affinity for userId %d",
4135 __FUNCTION__, userId);
4136 return status;
4137 }
4138
4139 // reevaluate outputs for all devices
4140 checkForDeviceAndOutputChanges();
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004141 changeOutputDevicesMuteState(devices);
4142 updateCallAndOutputRouting(false /* forceVolumeReeval */, 0 /* delayMs */,
4143 true /* skipDelays */);
4144 changeOutputDevicesMuteState(devices);
Oscar Azucena90e77632019-11-27 17:12:28 -08004145
4146 return NO_ERROR;
4147}
4148
4149status_t AudioPolicyManager::removeUserIdDeviceAffinities(int userId) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01004150 ALOGV("%s() userId=%d", __FUNCTION__, userId);
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004151 AudioDeviceTypeAddrVector devices;
4152 mPolicyMixes.getDevicesForUserId(userId, devices);
Oscar Azucena90e77632019-11-27 17:12:28 -08004153 status_t status = mPolicyMixes.removeUserIdDeviceAffinities(userId);
4154 if (status != NO_ERROR) {
4155 ALOGE("%s() Could not remove all device affinities fo userId = %d",
4156 __FUNCTION__, userId);
4157 return status;
4158 }
4159
4160 // reevaluate outputs for all devices
4161 checkForDeviceAndOutputChanges();
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004162 changeOutputDevicesMuteState(devices);
4163 updateCallAndOutputRouting(false /* forceVolumeReeval */, 0 /* delayMs */,
4164 true /* skipDelays */);
4165 changeOutputDevicesMuteState(devices);
Oscar Azucena90e77632019-11-27 17:12:28 -08004166
4167 return NO_ERROR;
4168}
4169
Andy Hungc29d82b2018-10-05 12:23:17 -07004170void AudioPolicyManager::dump(String8 *dst) const
Eric Laurente552edb2014-03-10 17:42:56 -07004171{
Andy Hungc29d82b2018-10-05 12:23:17 -07004172 dst->appendFormat("\nAudioPolicyManager Dump: %p\n", this);
Mikhail Naganov0dbe87b2021-12-01 02:03:31 +00004173 dst->appendFormat(" Primary Output I/O handle: %d\n",
Eric Laurent87ffa392015-05-22 10:32:38 -07004174 hasPrimaryOutput() ? mPrimaryOutput->mIoHandle : AUDIO_IO_HANDLE_NONE);
Mikhail Naganov0d6a0332016-04-19 17:12:38 -07004175 std::string stateLiteral;
4176 AudioModeConverter::toString(mEngine->getPhoneState(), stateLiteral);
Andy Hungc29d82b2018-10-05 12:23:17 -07004177 dst->appendFormat(" Phone state: %s\n", stateLiteral.c_str());
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07004178 const char* forceUses[AUDIO_POLICY_FORCE_USE_CNT] = {
4179 "communications", "media", "record", "dock", "system",
4180 "HDMI system audio", "encoded surround output", "vibrate ringing" };
4181 for (audio_policy_force_use_t i = AUDIO_POLICY_FORCE_FOR_COMMUNICATION;
4182 i < AUDIO_POLICY_FORCE_USE_CNT; i = (audio_policy_force_use_t)((int)i + 1)) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08004183 audio_policy_forced_cfg_t forceUseValue = mEngine->getForceUse(i);
4184 dst->appendFormat(" Force use for %s: %d", forceUses[i], forceUseValue);
4185 if (i == AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND &&
4186 forceUseValue == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
4187 dst->append(" (MANUAL: ");
4188 dumpManualSurroundFormats(dst);
4189 dst->append(")");
4190 }
4191 dst->append("\n");
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07004192 }
Andy Hungc29d82b2018-10-05 12:23:17 -07004193 dst->appendFormat(" TTS output %savailable\n", mTtsOutputAvailable ? "" : "not ");
4194 dst->appendFormat(" Master mono: %s\n", mMasterMono ? "on" : "off");
Mikhail Naganovb3bcb4f2022-02-23 23:46:56 +00004195 dst->appendFormat(" Communication Strategy id: %d\n", mCommunnicationStrategy);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07004196 dst->appendFormat(" Config source: %s\n", mConfig->getSource().c_str());
Eric Laurent2517af32020-11-25 15:31:27 +01004197
Mikhail Naganov0f413b22021-12-02 05:29:27 +00004198 dst->append("\n");
4199 mAvailableOutputDevices.dump(dst, String8("Available output"), 1);
4200 dst->append("\n");
4201 mAvailableInputDevices.dump(dst, String8("Available input"), 1);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07004202 mHwModules.dump(dst);
Andy Hungc29d82b2018-10-05 12:23:17 -07004203 mOutputs.dump(dst);
4204 mInputs.dump(dst);
Mikhail Naganov0f413b22021-12-02 05:29:27 +00004205 mEffects.dump(dst, 1);
Andy Hungc29d82b2018-10-05 12:23:17 -07004206 mAudioPatches.dump(dst);
4207 mPolicyMixes.dump(dst);
4208 mAudioSources.dump(dst);
François Gaffiec005e562018-11-06 15:04:49 +01004209
Kevin Rocardb99cc752019-03-21 20:52:24 -07004210 dst->appendFormat(" AllowedCapturePolicies:\n");
4211 for (auto& policy : mAllowedCapturePolicies) {
4212 dst->appendFormat(" - uid=%d flag_mask=%#x\n", policy.first, policy.second);
4213 }
4214
jiabina84c3d32022-12-02 18:59:55 +00004215 dst->appendFormat(" Preferred mixer audio configuration:\n");
4216 for (const auto it : mPreferredMixerAttrInfos) {
4217 dst->appendFormat(" - device port id: %d\n", it.first);
4218 for (const auto preferredMixerInfoIt : it.second) {
4219 dst->appendFormat(" - strategy: %d; ", preferredMixerInfoIt.first);
4220 preferredMixerInfoIt.second->dump(dst);
4221 }
4222 }
4223
François Gaffiec005e562018-11-06 15:04:49 +01004224 dst->appendFormat("\nPolicy Engine dump:\n");
4225 mEngine->dump(dst);
Andy Hungc29d82b2018-10-05 12:23:17 -07004226}
4227
4228status_t AudioPolicyManager::dump(int fd)
4229{
4230 String8 result;
4231 dump(&result);
Andy Hungbb54e202018-10-05 11:42:02 -07004232 write(fd, result.string(), result.size());
Eric Laurente552edb2014-03-10 17:42:56 -07004233 return NO_ERROR;
4234}
4235
Kevin Rocardb99cc752019-03-21 20:52:24 -07004236status_t AudioPolicyManager::setAllowedCapturePolicy(uid_t uid, audio_flags_mask_t capturePolicy)
4237{
4238 mAllowedCapturePolicies[uid] = capturePolicy;
4239 return NO_ERROR;
4240}
4241
Eric Laurente552edb2014-03-10 17:42:56 -07004242// This function checks for the parameters which can be offloaded.
4243// This can be enhanced depending on the capability of the DSP and policy
4244// of the system.
Eric Laurent90fe31c2020-11-26 20:06:35 +01004245audio_offload_mode_t AudioPolicyManager::getOffloadSupport(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07004246{
Eric Laurent90fe31c2020-11-26 20:06:35 +01004247 ALOGV("%s: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07004248 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurent90fe31c2020-11-26 20:06:35 +01004249 __func__, offloadInfo.sample_rate, offloadInfo.channel_mask,
Eric Laurente552edb2014-03-10 17:42:56 -07004250 offloadInfo.format,
4251 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
4252 offloadInfo.has_video);
4253
jiabin2b9d5a12021-12-10 01:06:29 +00004254 if (!isOffloadPossible(offloadInfo)) {
Eric Laurent90fe31c2020-11-26 20:06:35 +01004255 return AUDIO_OFFLOAD_NOT_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07004256 }
4257
4258 // See if there is a profile to support this.
4259 // AUDIO_DEVICE_NONE
François Gaffie11d30102018-11-02 16:09:09 +01004260 sp<IOProfile> profile = getProfileForOutput(DeviceVector() /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07004261 offloadInfo.sample_rate,
4262 offloadInfo.format,
4263 offloadInfo.channel_mask,
Michael Chana94fbb22018-04-24 14:31:19 +10004264 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD,
4265 true /* directOnly */);
Eric Laurent94365442021-01-08 18:36:05 +01004266 ALOGV("%s: profile %sfound%s", __func__, profile != nullptr ? "" : "NOT ",
4267 (profile != nullptr && (profile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD) != 0)
4268 ? ", supports gapless" : "");
Eric Laurent90fe31c2020-11-26 20:06:35 +01004269 if (profile == nullptr) {
4270 return AUDIO_OFFLOAD_NOT_SUPPORTED;
4271 }
4272 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD) != 0) {
4273 return AUDIO_OFFLOAD_GAPLESS_SUPPORTED;
4274 }
4275 return AUDIO_OFFLOAD_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07004276}
4277
Michael Chana94fbb22018-04-24 14:31:19 +10004278bool AudioPolicyManager::isDirectOutputSupported(const audio_config_base_t& config,
4279 const audio_attributes_t& attributes) {
4280 audio_output_flags_t output_flags = AUDIO_OUTPUT_FLAG_NONE;
François Gaffie58d4be52018-11-06 15:30:12 +01004281 audio_flags_to_audio_output_flags(attributes.flags, &output_flags);
Dorin Drimus9901eb02022-01-14 11:36:51 +00004282 DeviceVector outputDevices = mEngine->getOutputDevicesForAttributes(attributes);
4283 sp<IOProfile> profile = getProfileForOutput(outputDevices,
Michael Chana94fbb22018-04-24 14:31:19 +10004284 config.sample_rate,
4285 config.format,
4286 config.channel_mask,
4287 output_flags,
4288 true /* directOnly */);
4289 ALOGV("%s() profile %sfound with name: %s, "
4290 "sample rate: %u, format: 0x%x, channel_mask: 0x%x, output flags: 0x%x",
4291 __FUNCTION__, profile != 0 ? "" : "NOT ",
jiabin5740f082019-08-19 15:08:30 -07004292 (profile != 0 ? profile->getTagName().c_str() : "null"),
Michael Chana94fbb22018-04-24 14:31:19 +10004293 config.sample_rate, config.format, config.channel_mask, output_flags);
Dorin Drimusecc9f422022-03-09 17:57:40 +01004294
4295 // also try the MSD module if compatible profile not found
4296 if (profile == nullptr) {
4297 profile = getMsdProfileForOutput(outputDevices,
4298 config.sample_rate,
4299 config.format,
4300 config.channel_mask,
4301 output_flags,
4302 true /* directOnly */);
4303 ALOGV("%s() MSD profile %sfound with name: %s, "
4304 "sample rate: %u, format: 0x%x, channel_mask: 0x%x, output flags: 0x%x",
4305 __FUNCTION__, profile != 0 ? "" : "NOT ",
4306 (profile != 0 ? profile->getTagName().c_str() : "null"),
4307 config.sample_rate, config.format, config.channel_mask, output_flags);
4308 }
4309 return (profile != nullptr);
Michael Chana94fbb22018-04-24 14:31:19 +10004310}
4311
jiabin2b9d5a12021-12-10 01:06:29 +00004312bool AudioPolicyManager::isOffloadPossible(const audio_offload_info_t &offloadInfo,
4313 bool durationIgnored) {
4314 if (mMasterMono) {
4315 return false; // no offloading if mono is set.
4316 }
4317
4318 // Check if offload has been disabled
4319 if (property_get_bool("audio.offload.disable", false /* default_value */)) {
4320 ALOGV("%s: offload disabled by audio.offload.disable", __func__);
4321 return false;
4322 }
4323
4324 // Check if stream type is music, then only allow offload as of now.
4325 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
4326 {
4327 ALOGV("%s: stream_type != MUSIC, returning false", __func__);
4328 return false;
4329 }
4330
4331 //TODO: enable audio offloading with video when ready
4332 const bool allowOffloadWithVideo =
4333 property_get_bool("audio.offload.video", false /* default_value */);
4334 if (offloadInfo.has_video && !allowOffloadWithVideo) {
4335 ALOGV("%s: has_video == true, returning false", __func__);
4336 return false;
4337 }
4338
4339 //If duration is less than minimum value defined in property, return false
4340 const int min_duration_secs = property_get_int32(
4341 "audio.offload.min.duration.secs", -1 /* default_value */);
4342 if (!durationIgnored) {
4343 if (min_duration_secs >= 0) {
4344 if (offloadInfo.duration_us < min_duration_secs * 1000000LL) {
4345 ALOGV("%s: Offload denied by duration < audio.offload.min.duration.secs(=%d)",
4346 __func__, min_duration_secs);
4347 return false;
4348 }
4349 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
4350 ALOGV("%s: Offload denied by duration < default min(=%u)",
4351 __func__, OFFLOAD_DEFAULT_MIN_DURATION_SECS);
4352 return false;
4353 }
4354 }
4355
4356 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
4357 // creating an offloaded track and tearing it down immediately after start when audioflinger
4358 // detects there is an active non offloadable effect.
4359 // FIXME: We should check the audio session here but we do not have it in this context.
4360 // This may prevent offloading in rare situations where effects are left active by apps
4361 // in the background.
4362 if (mEffects.isNonOffloadableEffectEnabled()) {
4363 return false;
4364 }
4365
4366 return true;
4367}
4368
4369audio_direct_mode_t AudioPolicyManager::getDirectPlaybackSupport(const audio_attributes_t *attr,
4370 const audio_config_t *config) {
4371 audio_offload_info_t offloadInfo = AUDIO_INFO_INITIALIZER;
4372 offloadInfo.format = config->format;
4373 offloadInfo.sample_rate = config->sample_rate;
4374 offloadInfo.channel_mask = config->channel_mask;
4375 offloadInfo.stream_type = mEngine->getStreamTypeForAttributes(*attr);
4376 offloadInfo.has_video = false;
4377 offloadInfo.is_streaming = false;
4378 const bool offloadPossible = isOffloadPossible(offloadInfo, true /*durationIgnored*/);
4379
4380 audio_direct_mode_t directMode = AUDIO_DIRECT_NOT_SUPPORTED;
4381 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
4382 audio_flags_to_audio_output_flags(attr->flags, &flags);
4383 // only retain flags that will drive compressed offload or passthrough
4384 uint32_t relevantFlags = AUDIO_OUTPUT_FLAG_HW_AV_SYNC;
4385 if (offloadPossible) {
4386 relevantFlags |= AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD;
4387 }
4388 flags = (audio_output_flags_t)((flags & relevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
4389
Dorin Drimusfae3c642022-03-17 18:36:30 +01004390 DeviceVector engineOutputDevices = mEngine->getOutputDevicesForAttributes(*attr);
jiabin2b9d5a12021-12-10 01:06:29 +00004391 for (const auto& hwModule : mHwModules) {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004392 DeviceVector outputDevices = engineOutputDevices;
4393 // the MSD module checks for different conditions and output devices
4394 if (strcmp(hwModule->getName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0) {
4395 if (!msdHasPatchesToAllDevices(engineOutputDevices.toTypeAddrVector())) {
4396 continue;
4397 }
4398 outputDevices = getMsdAudioOutDevices();
4399 }
jiabin2b9d5a12021-12-10 01:06:29 +00004400 for (const auto& curProfile : hwModule->getOutputProfiles()) {
jiabinc8f7dfc2022-01-06 18:42:08 +00004401 if (!curProfile->isCompatibleProfile(outputDevices,
jiabin2b9d5a12021-12-10 01:06:29 +00004402 config->sample_rate, nullptr /*updatedSamplingRate*/,
4403 config->format, nullptr /*updatedFormat*/,
4404 config->channel_mask, nullptr /*updatedChannelMask*/,
4405 flags)) {
4406 continue;
4407 }
4408 // reject profiles not corresponding to a device currently available
4409 if (!mAvailableOutputDevices.containsAtLeastOne(curProfile->getSupportedDevices())) {
4410 continue;
4411 }
4412 if ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)
4413 != AUDIO_OUTPUT_FLAG_NONE) {
jiabinc6132d62022-01-01 07:36:31 +00004414 if ((directMode & AUDIO_DIRECT_OFFLOAD_GAPLESS_SUPPORTED)
jiabin2b9d5a12021-12-10 01:06:29 +00004415 != AUDIO_DIRECT_NOT_SUPPORTED) {
4416 // Already reports offload gapless supported. No need to report offload support.
4417 continue;
4418 }
4419 if ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD)
4420 != AUDIO_OUTPUT_FLAG_NONE) {
4421 // If offload gapless is reported, no need to report offload support.
4422 directMode = (audio_direct_mode_t) ((directMode &
4423 ~AUDIO_DIRECT_OFFLOAD_SUPPORTED) |
4424 AUDIO_DIRECT_OFFLOAD_GAPLESS_SUPPORTED);
4425 } else {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004426 directMode = (audio_direct_mode_t)(directMode | AUDIO_DIRECT_OFFLOAD_SUPPORTED);
jiabin2b9d5a12021-12-10 01:06:29 +00004427 }
4428 } else {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004429 directMode = (audio_direct_mode_t) (directMode | AUDIO_DIRECT_BITSTREAM_SUPPORTED);
jiabin2b9d5a12021-12-10 01:06:29 +00004430 }
4431 }
4432 }
4433 return directMode;
4434}
4435
Dorin Drimusf2196d82022-01-03 12:11:18 +01004436status_t AudioPolicyManager::getDirectProfilesForAttributes(const audio_attributes_t* attr,
4437 AudioProfileVector& audioProfilesVector) {
Dorin Drimus17112632022-09-23 15:28:51 +00004438 if (mEffects.isNonOffloadableEffectEnabled()) {
4439 return OK;
4440 }
jiabinf1c73972022-04-14 16:28:52 -07004441 DeviceVector devices;
4442 status_t status = getDevicesForAttributes(*attr, devices, false /* forVolume */);
Dorin Drimusf2196d82022-01-03 12:11:18 +01004443 if (status != OK) {
4444 return status;
4445 }
4446 ALOGV("%s: found %zu output devices for attributes.", __func__, devices.size());
4447 if (devices.empty()) {
4448 return OK; // no output devices for the attributes
4449 }
jiabinf1c73972022-04-14 16:28:52 -07004450 return getProfilesForDevices(devices, audioProfilesVector,
4451 AUDIO_OUTPUT_FLAG_DIRECT /*flags*/, false /*isInput*/);
Dorin Drimusf2196d82022-01-03 12:11:18 +01004452}
4453
jiabina84c3d32022-12-02 18:59:55 +00004454status_t AudioPolicyManager::getSupportedMixerAttributes(
4455 audio_port_handle_t portId, std::vector<audio_mixer_attributes_t> &mixerAttrs) {
4456 ALOGV("%s, portId=%d", __func__, portId);
4457 sp<DeviceDescriptor> deviceDescriptor = mAvailableOutputDevices.getDeviceFromId(portId);
4458 if (deviceDescriptor == nullptr) {
4459 ALOGE("%s the requested device is currently unavailable", __func__);
4460 return BAD_VALUE;
4461 }
jiabin96daffc2023-05-11 17:51:55 +00004462 if (!audio_is_usb_out_device(deviceDescriptor->type())) {
4463 ALOGE("%s the requested device(type=%#x) is not usb device", __func__,
4464 deviceDescriptor->type());
4465 return BAD_VALUE;
4466 }
jiabina84c3d32022-12-02 18:59:55 +00004467 for (const auto& hwModule : mHwModules) {
4468 for (const auto& curProfile : hwModule->getOutputProfiles()) {
4469 if (curProfile->supportsDevice(deviceDescriptor)) {
4470 curProfile->toSupportedMixerAttributes(&mixerAttrs);
4471 }
4472 }
4473 }
4474 return NO_ERROR;
4475}
4476
4477status_t AudioPolicyManager::setPreferredMixerAttributes(
4478 const audio_attributes_t *attr,
4479 audio_port_handle_t portId,
4480 uid_t uid,
4481 const audio_mixer_attributes_t *mixerAttributes) {
4482 ALOGV("%s, attr=%s, mixerAttributes={format=%#x, channelMask=%#x, samplingRate=%u, "
4483 "mixerBehavior=%d}, uid=%d, portId=%u",
4484 __func__, toString(*attr).c_str(), mixerAttributes->config.format,
4485 mixerAttributes->config.channel_mask, mixerAttributes->config.sample_rate,
4486 mixerAttributes->mixer_behavior, uid, portId);
4487 if (attr->usage != AUDIO_USAGE_MEDIA) {
4488 ALOGE("%s failed, only media is allowed, the given usage is %d", __func__, attr->usage);
4489 return BAD_VALUE;
4490 }
4491 sp<DeviceDescriptor> deviceDescriptor = mAvailableOutputDevices.getDeviceFromId(portId);
4492 if (deviceDescriptor == nullptr) {
4493 ALOGE("%s the requested device is currently unavailable", __func__);
4494 return BAD_VALUE;
4495 }
4496 if (!audio_is_usb_out_device(deviceDescriptor->type())) {
4497 ALOGE("%s(%d), type=%d, is not a usb output device",
4498 __func__, portId, deviceDescriptor->type());
4499 return BAD_VALUE;
4500 }
4501
4502 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
4503 audio_flags_to_audio_output_flags(attr->flags, &flags);
4504 flags = (audio_output_flags_t) (flags |
4505 audio_output_flags_from_mixer_behavior(mixerAttributes->mixer_behavior));
4506 sp<IOProfile> profile = nullptr;
4507 DeviceVector devices(deviceDescriptor);
4508 for (const auto& hwModule : mHwModules) {
4509 for (const auto& curProfile : hwModule->getOutputProfiles()) {
4510 if (curProfile->hasDynamicAudioProfile()
4511 && curProfile->isCompatibleProfile(devices,
4512 mixerAttributes->config.sample_rate,
4513 nullptr /*updatedSamplingRate*/,
4514 mixerAttributes->config.format,
4515 nullptr /*updatedFormat*/,
4516 mixerAttributes->config.channel_mask,
4517 nullptr /*updatedChannelMask*/,
4518 flags,
4519 false /*exactMatchRequiredForInputFlags*/)) {
4520 profile = curProfile;
4521 break;
4522 }
4523 }
4524 }
4525 if (profile == nullptr) {
4526 ALOGE("%s, there is no compatible profile found", __func__);
4527 return BAD_VALUE;
4528 }
4529
4530 sp<PreferredMixerAttributesInfo> mixerAttrInfo =
4531 sp<PreferredMixerAttributesInfo>::make(
4532 uid, portId, profile, flags, *mixerAttributes);
4533 const product_strategy_t strategy = mEngine->getProductStrategyForAttributes(*attr);
4534 mPreferredMixerAttrInfos[portId][strategy] = mixerAttrInfo;
4535
4536 // If 1) there is any client from the preferred mixer configuration owner that is currently
4537 // active and matches the strategy and 2) current output is on the preferred device and the
4538 // mixer configuration doesn't match the preferred one, reopen output with preferred mixer
4539 // configuration.
4540 std::vector<audio_io_handle_t> outputsToReopen;
4541 for (size_t i = 0; i < mOutputs.size(); i++) {
4542 const auto output = mOutputs.valueAt(i);
jiabin3ff8d7d2022-12-13 06:27:44 +00004543 if (output->mProfile == profile && output->devices().onlyContainsDevice(deviceDescriptor)) {
4544 if (output->isConfigurationMatched(mixerAttributes->config, flags)) {
4545 output->mUsePreferredMixerAttributes = true;
4546 } else {
4547 for (const auto &client: output->getActiveClients()) {
4548 if (client->uid() == uid && client->strategy() == strategy) {
4549 client->setIsInvalid();
4550 outputsToReopen.push_back(output->mIoHandle);
4551 }
jiabina84c3d32022-12-02 18:59:55 +00004552 }
4553 }
4554 }
4555 }
4556 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
4557 config.sample_rate = mixerAttributes->config.sample_rate;
4558 config.channel_mask = mixerAttributes->config.channel_mask;
4559 config.format = mixerAttributes->config.format;
4560 for (const auto output : outputsToReopen) {
jiabin3ff8d7d2022-12-13 06:27:44 +00004561 sp<SwAudioOutputDescriptor> desc =
4562 reopenOutput(mOutputs.valueFor(output), &config, flags, __func__);
4563 if (desc == nullptr) {
4564 ALOGE("%s, failed to reopen output with preferred mixer attributes", __func__);
4565 continue;
4566 }
4567 desc->mUsePreferredMixerAttributes = true;
jiabina84c3d32022-12-02 18:59:55 +00004568 }
4569
4570 return NO_ERROR;
4571}
4572
4573sp<PreferredMixerAttributesInfo> AudioPolicyManager::getPreferredMixerAttributesInfo(
jiabind9a58d32023-06-01 17:57:30 +00004574 audio_port_handle_t devicePortId,
4575 product_strategy_t strategy,
4576 bool activeBitPerfectPreferred) {
jiabina84c3d32022-12-02 18:59:55 +00004577 auto it = mPreferredMixerAttrInfos.find(devicePortId);
4578 if (it == mPreferredMixerAttrInfos.end()) {
4579 return nullptr;
4580 }
jiabind9a58d32023-06-01 17:57:30 +00004581 if (activeBitPerfectPreferred) {
4582 for (auto [strategy, info] : it->second) {
4583 if ((info->getFlags() & AUDIO_OUTPUT_FLAG_BIT_PERFECT) != AUDIO_OUTPUT_FLAG_NONE
4584 && info->getActiveClientCount() != 0) {
4585 return info;
4586 }
4587 }
jiabina84c3d32022-12-02 18:59:55 +00004588 }
jiabind9a58d32023-06-01 17:57:30 +00004589 auto strategyMatchedMixerAttrInfoIt = it->second.find(strategy);
4590 return strategyMatchedMixerAttrInfoIt == it->second.end()
4591 ? nullptr : strategyMatchedMixerAttrInfoIt->second;
jiabina84c3d32022-12-02 18:59:55 +00004592}
4593
4594status_t AudioPolicyManager::getPreferredMixerAttributes(
4595 const audio_attributes_t *attr,
4596 audio_port_handle_t portId,
4597 audio_mixer_attributes_t* mixerAttributes) {
4598 sp<PreferredMixerAttributesInfo> info = getPreferredMixerAttributesInfo(
4599 portId, mEngine->getProductStrategyForAttributes(*attr));
4600 if (info == nullptr) {
4601 return NAME_NOT_FOUND;
4602 }
4603 *mixerAttributes = info->getMixerAttributes();
4604 return NO_ERROR;
4605}
4606
4607status_t AudioPolicyManager::clearPreferredMixerAttributes(const audio_attributes_t *attr,
4608 audio_port_handle_t portId,
4609 uid_t uid) {
4610 const product_strategy_t strategy = mEngine->getProductStrategyForAttributes(*attr);
4611 const auto preferredMixerAttrInfo = getPreferredMixerAttributesInfo(portId, strategy);
4612 if (preferredMixerAttrInfo == nullptr) {
4613 return NAME_NOT_FOUND;
4614 }
4615 if (preferredMixerAttrInfo->getUid() != uid) {
4616 ALOGE("%s, requested uid=%d, owned uid=%d",
4617 __func__, uid, preferredMixerAttrInfo->getUid());
4618 return PERMISSION_DENIED;
4619 }
4620 mPreferredMixerAttrInfos[portId].erase(strategy);
4621 if (mPreferredMixerAttrInfos[portId].empty()) {
4622 mPreferredMixerAttrInfos.erase(portId);
4623 }
4624
4625 // Reconfig existing output
4626 std::vector<audio_io_handle_t> potentialOutputsToReopen;
4627 for (size_t i = 0; i < mOutputs.size(); i++) {
4628 if (mOutputs.valueAt(i)->mProfile == preferredMixerAttrInfo->getProfile()) {
4629 potentialOutputsToReopen.push_back(mOutputs.keyAt(i));
4630 }
4631 }
4632 for (const auto output : potentialOutputsToReopen) {
4633 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
4634 if (desc->isConfigurationMatched(preferredMixerAttrInfo->getConfigBase(),
4635 preferredMixerAttrInfo->getFlags())) {
4636 reopenOutput(desc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
4637 }
4638 }
4639 return NO_ERROR;
4640}
4641
Eric Laurent6a94d692014-05-20 11:18:06 -07004642status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
4643 audio_port_type_t type,
4644 unsigned int *num_ports,
jiabin19cdba52020-11-24 11:28:58 -08004645 struct audio_port_v7 *ports,
Eric Laurent6a94d692014-05-20 11:18:06 -07004646 unsigned int *generation)
4647{
jiabin19cdba52020-11-24 11:28:58 -08004648 if (num_ports == nullptr || (*num_ports != 0 && ports == nullptr) ||
4649 generation == nullptr) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004650 return BAD_VALUE;
4651 }
4652 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
jiabin19cdba52020-11-24 11:28:58 -08004653 if (ports == nullptr) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004654 *num_ports = 0;
4655 }
4656
4657 size_t portsWritten = 0;
4658 size_t portsMax = *num_ports;
4659 *num_ports = 0;
4660 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07004661 // do not report devices with type AUDIO_DEVICE_IN_STUB or AUDIO_DEVICE_OUT_STUB
4662 // as they are used by stub HALs by convention
Eric Laurent6a94d692014-05-20 11:18:06 -07004663 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004664 for (const auto& dev : mAvailableOutputDevices) {
4665 if (dev->type() == AUDIO_DEVICE_OUT_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07004666 continue;
4667 }
4668 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004669 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07004670 }
4671 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07004672 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004673 }
4674 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004675 for (const auto& dev : mAvailableInputDevices) {
4676 if (dev->type() == AUDIO_DEVICE_IN_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07004677 continue;
4678 }
4679 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004680 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07004681 }
4682 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07004683 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004684 }
4685 }
4686 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
4687 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
4688 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
4689 mInputs[i]->toAudioPort(&ports[portsWritten++]);
4690 }
4691 *num_ports += mInputs.size();
4692 }
4693 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent84c70242014-06-23 08:46:27 -07004694 size_t numOutputs = 0;
4695 for (size_t i = 0; i < mOutputs.size(); i++) {
4696 if (!mOutputs[i]->isDuplicated()) {
4697 numOutputs++;
4698 if (portsWritten < portsMax) {
4699 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
4700 }
4701 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004702 }
Eric Laurent84c70242014-06-23 08:46:27 -07004703 *num_ports += numOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07004704 }
4705 }
jiabina84c3d32022-12-02 18:59:55 +00004706
Eric Laurent6a94d692014-05-20 11:18:06 -07004707 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07004708 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
Eric Laurent6a94d692014-05-20 11:18:06 -07004709 return NO_ERROR;
4710}
4711
Mikhail Naganov5edc5ed2023-03-23 14:52:15 -07004712status_t AudioPolicyManager::listDeclaredDevicePorts(media::AudioPortRole role,
4713 std::vector<media::AudioPortFw>* _aidl_return) {
4714 auto pushPort = [&](const sp<DeviceDescriptor>& dev) -> status_t {
4715 audio_port_v7 port;
4716 dev->toAudioPort(&port);
4717 auto aidlPort = VALUE_OR_RETURN_STATUS(legacy2aidl_audio_port_v7_AudioPortFw(port));
4718 _aidl_return->push_back(std::move(aidlPort));
4719 return OK;
4720 };
4721
Mikhail Naganov68e3f642023-04-28 13:06:32 -07004722 for (const auto& module : mHwModules) {
Mikhail Naganov5edc5ed2023-03-23 14:52:15 -07004723 for (const auto& dev : module->getDeclaredDevices()) {
4724 if (role == media::AudioPortRole::NONE ||
4725 ((role == media::AudioPortRole::SOURCE)
4726 == audio_is_input_device(dev->type()))) {
4727 RETURN_STATUS_IF_ERROR(pushPort(dev));
4728 }
4729 }
4730 }
4731 return OK;
4732}
4733
jiabin19cdba52020-11-24 11:28:58 -08004734status_t AudioPolicyManager::getAudioPort(struct audio_port_v7 *port)
Eric Laurent6a94d692014-05-20 11:18:06 -07004735{
Eric Laurent99fcae42018-05-17 16:59:18 -07004736 if (port == nullptr || port->id == AUDIO_PORT_HANDLE_NONE) {
4737 return BAD_VALUE;
4738 }
4739 sp<DeviceDescriptor> dev = mAvailableOutputDevices.getDeviceFromId(port->id);
4740 if (dev != 0) {
4741 dev->toAudioPort(port);
4742 return NO_ERROR;
4743 }
4744 dev = mAvailableInputDevices.getDeviceFromId(port->id);
4745 if (dev != 0) {
4746 dev->toAudioPort(port);
4747 return NO_ERROR;
4748 }
4749 sp<SwAudioOutputDescriptor> out = mOutputs.getOutputFromId(port->id);
4750 if (out != 0) {
4751 out->toAudioPort(port);
4752 return NO_ERROR;
4753 }
4754 sp<AudioInputDescriptor> in = mInputs.getInputFromId(port->id);
4755 if (in != 0) {
4756 in->toAudioPort(port);
4757 return NO_ERROR;
4758 }
4759 return BAD_VALUE;
Eric Laurent6a94d692014-05-20 11:18:06 -07004760}
4761
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004762status_t AudioPolicyManager::createAudioPatch(const struct audio_patch *patch,
4763 audio_patch_handle_t *handle,
4764 uid_t uid)
Eric Laurent6a94d692014-05-20 11:18:06 -07004765{
François Gaffieafd4cea2019-11-18 15:50:22 +01004766 ALOGV("%s", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004767 if (handle == NULL || patch == NULL) {
4768 return BAD_VALUE;
4769 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004770 ALOGV("%s num sources %d num sinks %d", __func__, patch->num_sources, patch->num_sinks);
Mikhail Naganovac9858b2018-06-15 13:12:37 -07004771 if (!audio_patch_is_valid(patch)) {
Eric Laurent874c42872014-08-08 15:13:39 -07004772 return BAD_VALUE;
4773 }
4774 // only one source per audio patch supported for now
4775 if (patch->num_sources > 1) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004776 return INVALID_OPERATION;
4777 }
Eric Laurent874c42872014-08-08 15:13:39 -07004778 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004779 return INVALID_OPERATION;
4780 }
Eric Laurent874c42872014-08-08 15:13:39 -07004781 for (size_t i = 0; i < patch->num_sinks; i++) {
4782 if (patch->sinks[i].role != AUDIO_PORT_ROLE_SINK) {
4783 return INVALID_OPERATION;
4784 }
4785 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004786
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004787 sp<DeviceDescriptor> srcDevice = mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
4788 sp<DeviceDescriptor> sinkDevice = mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id);
4789 if (srcDevice == nullptr || sinkDevice == nullptr) {
4790 ALOGW("%s could not create patch, invalid sink and/or source device(s)", __func__);
4791 return BAD_VALUE;
4792 }
4793 ALOGV("%s between source %s and sink %s", __func__,
4794 srcDevice->toString().c_str(), sinkDevice->toString().c_str());
4795 audio_port_handle_t portId = PolicyAudioPort::getNextUniqueId();
4796 // Default attributes, default volume priority, not to infer with non raw audio patches.
4797 audio_attributes_t attributes = attributes_initializer(AUDIO_USAGE_MEDIA);
4798 const struct audio_port_config *source = &patch->sources[0];
4799 sp<SourceClientDescriptor> sourceDesc =
4800 new InternalSourceClientDescriptor(
4801 portId, uid, attributes, *source, srcDevice, sinkDevice,
4802 mEngine->getProductStrategyForAttributes(attributes), toVolumeSource(attributes));
4803
4804 status_t status =
4805 connectAudioSourceToSink(sourceDesc, sinkDevice, patch, *handle, uid, 0 /* delayMs */);
4806
4807 if (status != NO_ERROR) {
4808 return INVALID_OPERATION;
4809 }
4810 mAudioSources.add(portId, sourceDesc);
4811 return NO_ERROR;
4812}
4813
4814status_t AudioPolicyManager::connectAudioSourceToSink(
4815 const sp<SourceClientDescriptor>& sourceDesc, const sp<DeviceDescriptor> &sinkDevice,
4816 const struct audio_patch *patch,
4817 audio_patch_handle_t &handle,
4818 uid_t uid, uint32_t delayMs)
4819{
4820 status_t status = createAudioPatchInternal(patch, &handle, uid, delayMs, sourceDesc);
4821 if (status != NO_ERROR || mAudioPatches.indexOfKey(handle) < 0) {
4822 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
4823 return INVALID_OPERATION;
4824 }
4825 sourceDesc->connect(handle, sinkDevice);
4826 if (isMsdPatch(handle)) {
4827 return NO_ERROR;
4828 }
4829 // SW Bridge? (@todo: HW bridge, keep track of HwOutput for device selection "reconsideration")
4830 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
4831 ALOG_ASSERT(swOutput != nullptr, "%s: a swOutput shall always be associated", __func__);
4832 if (swOutput->getClient(sourceDesc->portId()) != nullptr) {
4833 ALOGW("%s source portId has already been attached to outputDesc", __func__);
4834 goto FailurePatchAdded;
4835 }
4836 status = swOutput->start();
4837 if (status != NO_ERROR) {
4838 goto FailureSourceAdded;
4839 }
4840 swOutput->addClient(sourceDesc);
4841 status = startSource(swOutput, sourceDesc, &delayMs);
4842 if (status != NO_ERROR) {
4843 ALOGW("%s failed to start source, error %d", __FUNCTION__, status);
4844 goto FailureSourceActive;
4845 }
4846 if (delayMs != 0) {
4847 usleep(delayMs * 1000);
4848 }
4849 return NO_ERROR;
4850
4851FailureSourceActive:
4852 swOutput->stop();
4853 releaseOutput(sourceDesc->portId());
4854FailureSourceAdded:
4855 sourceDesc->setSwOutput(nullptr);
4856FailurePatchAdded:
4857 releaseAudioPatchInternal(handle);
4858 return INVALID_OPERATION;
4859}
4860
4861status_t AudioPolicyManager::createAudioPatchInternal(const struct audio_patch *patch,
4862 audio_patch_handle_t *handle,
4863 uid_t uid, uint32_t delayMs,
4864 const sp<SourceClientDescriptor>& sourceDesc)
4865{
4866 ALOGV("%s num sources %d num sinks %d", __func__, patch->num_sources, patch->num_sinks);
Eric Laurent6a94d692014-05-20 11:18:06 -07004867 sp<AudioPatch> patchDesc;
4868 ssize_t index = mAudioPatches.indexOfKey(*handle);
4869
François Gaffieafd4cea2019-11-18 15:50:22 +01004870 ALOGV("%s source id %d role %d type %d", __func__, patch->sources[0].id,
4871 patch->sources[0].role,
4872 patch->sources[0].type);
Eric Laurent874c42872014-08-08 15:13:39 -07004873#if LOG_NDEBUG == 0
4874 for (size_t i = 0; i < patch->num_sinks; i++) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004875 ALOGV("%s sink %zu: id %d role %d type %d", __func__ ,i, patch->sinks[i].id,
4876 patch->sinks[i].role,
4877 patch->sinks[i].type);
Eric Laurent874c42872014-08-08 15:13:39 -07004878 }
4879#endif
Eric Laurent6a94d692014-05-20 11:18:06 -07004880
4881 if (index >= 0) {
4882 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01004883 ALOGV("%s mUidCached %d patchDesc->mUid %d uid %d",
4884 __func__, mUidCached, patchDesc->getUid(), uid);
4885 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004886 return INVALID_OPERATION;
4887 }
4888 } else {
Glenn Kastena13cde92016-03-28 15:26:02 -07004889 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07004890 }
4891
4892 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004893 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004894 if (outputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004895 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004896 return BAD_VALUE;
4897 }
Eric Laurent84c70242014-06-23 08:46:27 -07004898 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
4899 outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004900 if (patchDesc != 0) {
4901 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004902 ALOGV("%s source id differs for patch current id %d new id %d",
4903 __func__, patchDesc->mPatch.sources[0].id, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004904 return BAD_VALUE;
4905 }
4906 }
Eric Laurent874c42872014-08-08 15:13:39 -07004907 DeviceVector devices;
4908 for (size_t i = 0; i < patch->num_sinks; i++) {
4909 // Only support mix to devices connection
4910 // TODO add support for mix to mix connection
4911 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004912 ALOGV("%s source mix but sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07004913 return INVALID_OPERATION;
4914 }
4915 sp<DeviceDescriptor> devDesc =
4916 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
4917 if (devDesc == 0) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004918 ALOGV("%s out device not found for id %d", __func__, patch->sinks[i].id);
Eric Laurent874c42872014-08-08 15:13:39 -07004919 return BAD_VALUE;
4920 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004921
François Gaffie11d30102018-11-02 16:09:09 +01004922 if (!outputDesc->mProfile->isCompatibleProfile(DeviceVector(devDesc),
Eric Laurent874c42872014-08-08 15:13:39 -07004923 patch->sources[0].sample_rate,
François Gaffie53615e22015-03-19 09:24:12 +01004924 NULL, // updatedSamplingRate
4925 patch->sources[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07004926 NULL, // updatedFormat
François Gaffie53615e22015-03-19 09:24:12 +01004927 patch->sources[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07004928 NULL, // updatedChannelMask
François Gaffie53615e22015-03-19 09:24:12 +01004929 AUDIO_OUTPUT_FLAG_NONE /*FIXME*/)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004930 ALOGV("%s profile not supported for device %08x", __func__, devDesc->type());
Eric Laurent874c42872014-08-08 15:13:39 -07004931 return INVALID_OPERATION;
4932 }
4933 devices.add(devDesc);
4934 }
4935 if (devices.size() == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004936 return INVALID_OPERATION;
4937 }
Eric Laurent874c42872014-08-08 15:13:39 -07004938
Eric Laurent6a94d692014-05-20 11:18:06 -07004939 // TODO: reconfigure output format and channels here
François Gaffieafd4cea2019-11-18 15:50:22 +01004940 ALOGV("%s setting device %s on output %d",
4941 __func__, dumpDeviceTypes(devices.types()).c_str(), outputDesc->mIoHandle);
François Gaffie11d30102018-11-02 16:09:09 +01004942 setOutputDevices(outputDesc, devices, true, 0, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004943 index = mAudioPatches.indexOfKey(*handle);
4944 if (index >= 0) {
4945 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004946 ALOGW("%s setOutputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004947 }
4948 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01004949 patchDesc->setUid(uid);
4950 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004951 } else {
François Gaffieafd4cea2019-11-18 15:50:22 +01004952 ALOGW("%s setOutputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004953 return INVALID_OPERATION;
4954 }
4955 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
4956 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
4957 // input device to input mix connection
Eric Laurent874c42872014-08-08 15:13:39 -07004958 // only one sink supported when connecting an input device to a mix
4959 if (patch->num_sinks > 1) {
4960 return INVALID_OPERATION;
4961 }
François Gaffie53615e22015-03-19 09:24:12 +01004962 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004963 if (inputDesc == NULL) {
4964 return BAD_VALUE;
4965 }
4966 if (patchDesc != 0) {
4967 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
4968 return BAD_VALUE;
4969 }
4970 }
François Gaffie11d30102018-11-02 16:09:09 +01004971 sp<DeviceDescriptor> device =
Eric Laurent6a94d692014-05-20 11:18:06 -07004972 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01004973 if (device == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004974 return BAD_VALUE;
4975 }
4976
François Gaffie11d30102018-11-02 16:09:09 +01004977 if (!inputDesc->mProfile->isCompatibleProfile(DeviceVector(device),
Eric Laurent275e8e92014-11-30 15:14:47 -08004978 patch->sinks[0].sample_rate,
4979 NULL, /*updatedSampleRate*/
4980 patch->sinks[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07004981 NULL, /*updatedFormat*/
Eric Laurent275e8e92014-11-30 15:14:47 -08004982 patch->sinks[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07004983 NULL, /*updatedChannelMask*/
Eric Laurent275e8e92014-11-30 15:14:47 -08004984 // FIXME for the parameter type,
4985 // and the NONE
4986 (audio_output_flags_t)
Glenn Kasten6a8ab052014-07-24 14:08:35 -07004987 AUDIO_INPUT_FLAG_NONE)) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004988 return INVALID_OPERATION;
4989 }
4990 // TODO: reconfigure output format and channels here
François Gaffieafd4cea2019-11-18 15:50:22 +01004991 ALOGV("%s setting device %s on output %d", __func__,
François Gaffie11d30102018-11-02 16:09:09 +01004992 device->toString().c_str(), inputDesc->mIoHandle);
4993 setInputDevice(inputDesc->mIoHandle, device, true, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004994 index = mAudioPatches.indexOfKey(*handle);
4995 if (index >= 0) {
4996 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004997 ALOGW("%s setInputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004998 }
4999 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005000 patchDesc->setUid(uid);
5001 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005002 } else {
François Gaffieafd4cea2019-11-18 15:50:22 +01005003 ALOGW("%s setInputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005004 return INVALID_OPERATION;
5005 }
5006 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
5007 // device to device connection
5008 if (patchDesc != 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07005009 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005010 return BAD_VALUE;
5011 }
5012 }
François Gaffie11d30102018-11-02 16:09:09 +01005013 sp<DeviceDescriptor> srcDevice =
Eric Laurent6a94d692014-05-20 11:18:06 -07005014 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01005015 if (srcDevice == 0) {
Eric Laurent58f8eb72014-09-12 16:19:41 -07005016 return BAD_VALUE;
5017 }
Eric Laurent874c42872014-08-08 15:13:39 -07005018
Eric Laurent6a94d692014-05-20 11:18:06 -07005019 //update source and sink with our own data as the data passed in the patch may
5020 // be incomplete.
François Gaffieafd4cea2019-11-18 15:50:22 +01005021 PatchBuilder patchBuilder;
5022 audio_port_config sourcePortConfig = {};
Dean Wheatley8bee85a2021-02-10 16:02:23 +11005023
5024 // if first sink is to MSD, establish single MSD patch
5025 if (getMsdAudioOutDevices().contains(
5026 mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id))) {
5027 ALOGV("%s patching to MSD", __FUNCTION__);
5028 patchBuilder = buildMsdPatch(false /*msdIsSource*/, srcDevice);
5029 goto installPatch;
5030 }
5031
François Gaffieafd4cea2019-11-18 15:50:22 +01005032 srcDevice->toAudioPortConfig(&sourcePortConfig, &patch->sources[0]);
5033 patchBuilder.addSource(sourcePortConfig);
Eric Laurent6a94d692014-05-20 11:18:06 -07005034
Eric Laurent874c42872014-08-08 15:13:39 -07005035 for (size_t i = 0; i < patch->num_sinks; i++) {
5036 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005037 ALOGV("%s source device but one sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07005038 return INVALID_OPERATION;
5039 }
François Gaffie11d30102018-11-02 16:09:09 +01005040 sp<DeviceDescriptor> sinkDevice =
Eric Laurent874c42872014-08-08 15:13:39 -07005041 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
François Gaffie11d30102018-11-02 16:09:09 +01005042 if (sinkDevice == 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07005043 return BAD_VALUE;
5044 }
François Gaffieafd4cea2019-11-18 15:50:22 +01005045 audio_port_config sinkPortConfig = {};
5046 sinkDevice->toAudioPortConfig(&sinkPortConfig, &patch->sinks[i]);
5047 patchBuilder.addSink(sinkPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07005048
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005049 // Whatever Sw or Hw bridge, we do attach an SwOutput to an Audio Source for
5050 // volume management purpose (tracking activity)
5051 // In case of Hw bridge, it is a Work Around. The mixPort used is the one declared
5052 // in config XML to reach the sink so that is can be declared as available.
5053 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurent78b07302022-10-07 16:20:34 +02005054 sp<SwAudioOutputDescriptor> outputDesc;
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005055 if (!sourceDesc->isInternal()) {
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005056 // take care of dynamic routing for SwOutput selection,
5057 audio_attributes_t attributes = sourceDesc->attributes();
5058 audio_stream_type_t stream = sourceDesc->stream();
5059 audio_attributes_t resultAttr;
5060 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
5061 config.sample_rate = sourceDesc->config().sample_rate;
François Gaffie2a24db42022-04-04 16:45:02 +02005062 audio_channel_mask_t sourceMask = sourceDesc->config().channel_mask;
5063 config.channel_mask =
5064 (audio_channel_mask_get_representation(sourceMask)
5065 == AUDIO_CHANNEL_REPRESENTATION_INDEX) ? sourceMask
5066 : audio_channel_mask_in_to_out(sourceMask);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005067 config.format = sourceDesc->config().format;
5068 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
5069 audio_port_handle_t selectedDeviceId = AUDIO_PORT_HANDLE_NONE;
5070 bool isRequestedDeviceForExclusiveUse = false;
5071 output_type_t outputType;
Eric Laurentb0a7bc92022-04-05 15:06:08 +02005072 bool isSpatialized;
jiabinc658e452022-10-21 20:52:21 +00005073 bool isBitPerfect;
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005074 getOutputForAttrInt(&resultAttr, &output, AUDIO_SESSION_NONE, &attributes,
5075 &stream, sourceDesc->uid(), &config, &flags,
5076 &selectedDeviceId, &isRequestedDeviceForExclusiveUse,
jiabinc658e452022-10-21 20:52:21 +00005077 nullptr, &outputType, &isSpatialized, &isBitPerfect);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005078 if (output == AUDIO_IO_HANDLE_NONE) {
5079 ALOGV("%s no output for device %s",
5080 __FUNCTION__, sinkDevice->toString().c_str());
5081 return INVALID_OPERATION;
5082 }
5083 outputDesc = mOutputs.valueFor(output);
5084 if (outputDesc->isDuplicated()) {
5085 ALOGE("%s output is duplicated", __func__);
5086 return INVALID_OPERATION;
5087 }
François Gaffie7e39df22022-04-26 12:48:49 +02005088 bool closeOutput = outputDesc->mDirectOpenCount != 0;
5089 sourceDesc->setSwOutput(outputDesc, closeOutput);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005090 } else {
5091 // Same for "raw patches" aka created from createAudioPatch API
5092 SortedVector<audio_io_handle_t> outputs =
5093 getOutputsForDevices(DeviceVector(sinkDevice), mOutputs);
5094 // if the sink device is reachable via an opened output stream, request to
5095 // go via this output stream by adding a second source to the patch
5096 // description
5097 output = selectOutput(outputs);
5098 if (output == AUDIO_IO_HANDLE_NONE) {
5099 ALOGE("%s no output available for internal patch sink", __func__);
5100 return INVALID_OPERATION;
5101 }
5102 outputDesc = mOutputs.valueFor(output);
5103 if (outputDesc->isDuplicated()) {
5104 ALOGV("%s output for device %s is duplicated",
5105 __func__, sinkDevice->toString().c_str());
5106 return INVALID_OPERATION;
5107 }
François Gaffie7e39df22022-04-26 12:48:49 +02005108 sourceDesc->setSwOutput(outputDesc, /* closeOutput= */ false);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005109 }
Eric Laurent3bcf8592015-04-03 12:13:24 -07005110 // create a software bridge in PatchPanel if:
Scott Randolphf3172402018-01-23 17:06:53 -08005111 // - source and sink devices are on different HW modules OR
Eric Laurent3bcf8592015-04-03 12:13:24 -07005112 // - audio HAL version is < 3.0
Francois Gaffie99896da2018-04-09 11:05:33 +02005113 // - audio HAL version is >= 3.0 but no route has been declared between devices
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005114 // - called from startAudioSource (aka sourceDesc is not internal) and source device
5115 // does not have a gain controller
François Gaffie11d30102018-11-02 16:09:09 +01005116 if (!srcDevice->hasSameHwModuleAs(sinkDevice) ||
5117 (srcDevice->getModuleVersionMajor() < 3) ||
François Gaffieafd4cea2019-11-18 15:50:22 +01005118 !srcDevice->getModule()->supportsPatch(srcDevice, sinkDevice) ||
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005119 (!sourceDesc->isInternal() &&
François Gaffieafd4cea2019-11-18 15:50:22 +01005120 srcDevice->getAudioPort()->getGains().size() == 0)) {
Eric Laurent3bcf8592015-04-03 12:13:24 -07005121 // support only one sink device for now to simplify output selection logic
Eric Laurent874c42872014-08-08 15:13:39 -07005122 if (patch->num_sinks > 1) {
Eric Laurent83b88082014-06-20 18:31:16 -07005123 return INVALID_OPERATION;
5124 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005125 sourceDesc->setUseSwBridge();
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005126 if (outputDesc != nullptr) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005127 audio_port_config srcMixPortConfig = {};
Ytai Ben-Tsvic9d2a912021-11-22 16:43:09 -08005128 outputDesc->toAudioPortConfig(&srcMixPortConfig, nullptr);
François Gaffieafd4cea2019-11-18 15:50:22 +01005129 // for volume control, we may need a valid stream
Eric Laurent78b07302022-10-07 16:20:34 +02005130 srcMixPortConfig.ext.mix.usecase.stream =
5131 (!sourceDesc->isInternal() || isCallTxAudioSource(sourceDesc)) ?
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005132 mEngine->getStreamTypeForAttributes(sourceDesc->attributes()) :
5133 AUDIO_STREAM_PATCH;
François Gaffieafd4cea2019-11-18 15:50:22 +01005134 patchBuilder.addSource(srcMixPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07005135 }
Eric Laurent83b88082014-06-20 18:31:16 -07005136 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005137 }
5138 // TODO: check from routing capabilities in config file and other conflicting patches
5139
Dean Wheatley8bee85a2021-02-10 16:02:23 +11005140installPatch:
François Gaffieafd4cea2019-11-18 15:50:22 +01005141 status_t status = installPatch(
5142 __func__, index, handle, patchBuilder.patch(), delayMs, uid, &patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07005143 if (status != NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005144 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
Eric Laurent6a94d692014-05-20 11:18:06 -07005145 return INVALID_OPERATION;
5146 }
5147 } else {
5148 return BAD_VALUE;
5149 }
5150 } else {
5151 return BAD_VALUE;
5152 }
5153 return NO_ERROR;
5154}
5155
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005156status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle, uid_t uid)
Eric Laurent6a94d692014-05-20 11:18:06 -07005157{
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005158 ALOGV("%s patch %d", __func__, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005159 ssize_t index = mAudioPatches.indexOfKey(handle);
5160
5161 if (index < 0) {
5162 return BAD_VALUE;
5163 }
5164 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005165 ALOGV("%s() mUidCached %d patchDesc->mUid %d uid %d",
5166 __func__, mUidCached, patchDesc->getUid(), uid);
5167 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005168 return INVALID_OPERATION;
5169 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005170 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
5171 for (size_t i = 0; i < mAudioSources.size(); i++) {
5172 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
5173 if (sourceDesc != nullptr && sourceDesc->getPatchHandle() == handle) {
5174 portId = sourceDesc->portId();
5175 break;
5176 }
5177 }
5178 return portId != AUDIO_PORT_HANDLE_NONE ?
5179 stopAudioSource(portId) : releaseAudioPatchInternal(handle);
François Gaffieafd4cea2019-11-18 15:50:22 +01005180}
Eric Laurent6a94d692014-05-20 11:18:06 -07005181
François Gaffieafd4cea2019-11-18 15:50:22 +01005182status_t AudioPolicyManager::releaseAudioPatchInternal(audio_patch_handle_t handle,
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005183 uint32_t delayMs,
5184 const sp<SourceClientDescriptor>& sourceDesc)
François Gaffieafd4cea2019-11-18 15:50:22 +01005185{
5186 ALOGV("%s patch %d", __func__, handle);
5187 if (mAudioPatches.indexOfKey(handle) < 0) {
5188 ALOGE("%s: no patch found with handle=%d", __func__, handle);
5189 return BAD_VALUE;
5190 }
5191 sp<AudioPatch> patchDesc = mAudioPatches.valueFor(handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005192 struct audio_patch *patch = &patchDesc->mPatch;
François Gaffieafd4cea2019-11-18 15:50:22 +01005193 patchDesc->setUid(mUidCached);
Eric Laurent6a94d692014-05-20 11:18:06 -07005194 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005195 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005196 if (outputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005197 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005198 return BAD_VALUE;
5199 }
5200
François Gaffie11d30102018-11-02 16:09:09 +01005201 setOutputDevices(outputDesc,
5202 getNewOutputDevices(outputDesc, true /*fromCache*/),
5203 true,
5204 0,
5205 NULL);
Eric Laurent6a94d692014-05-20 11:18:06 -07005206 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
5207 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
François Gaffie53615e22015-03-19 09:24:12 +01005208 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005209 if (inputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005210 ALOGV("%s input not found for id %d", __func__, patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005211 return BAD_VALUE;
5212 }
5213 setInputDevice(inputDesc->mIoHandle,
Eric Laurentfb66dd92016-01-28 18:32:03 -08005214 getNewInputDevice(inputDesc),
Eric Laurent6a94d692014-05-20 11:18:06 -07005215 true,
5216 NULL);
5217 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005218 status_t status =
5219 mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
5220 ALOGV("%s patch panel returned %d patchHandle %d",
5221 __func__, status, patchDesc->getAfHandle());
5222 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005223 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005224 mpClientInterface->onAudioPatchListUpdate();
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005225 // SW or HW Bridge
5226 sp<SwAudioOutputDescriptor> outputDesc = nullptr;
5227 audio_patch_handle_t patchHandle = AUDIO_PATCH_HANDLE_NONE;
Francois Gaffie7feb8542020-04-06 17:39:47 +02005228 if (patch->num_sources > 1 && patch->sources[1].type == AUDIO_PORT_TYPE_MIX) {
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005229 outputDesc = mOutputs.getOutputFromId(patch->sources[1].id);
5230 } else if (patch->num_sources == 1 && sourceDesc != nullptr) {
5231 outputDesc = sourceDesc->swOutput().promote();
5232 }
5233 if (outputDesc == nullptr) {
5234 ALOGW("%s no output for id %d", __func__, patch->sources[0].id);
5235 // releaseOutput has already called closeOutput in case of direct output
5236 return NO_ERROR;
5237 }
François Gaffie7e39df22022-04-26 12:48:49 +02005238 patchHandle = outputDesc->getPatchHandle();
5239 // When a Sw bridge is released, the mixer used by this bridge will release its
5240 // patch at AudioFlinger side. Hence, the mixer audio patch must be recreated
5241 // Reuse patch handle to force audio flinger removing initial mixer patch removal
5242 // updating hal patch handle (prevent leaks).
5243 // While using a HwBridge, force reconsidering device only if not reusing an existing
5244 // output and no more activity on output (will force to close).
5245 bool force = sourceDesc->useSwBridge() ||
5246 (sourceDesc->canCloseOutput() && !outputDesc->isActive());
5247 // APM pattern is to have always outputs opened / patch realized for reachable devices.
5248 // Update device may result to NONE (empty), coupled with force, it releases the patch.
5249 // Reconsider device only for cases:
5250 // 1 / Active Output
5251 // 2 / Inactive Output previously hosting HwBridge
5252 // 3 / Inactive Output previously hosting SwBridge that can be closed.
5253 bool updateDevice = outputDesc->isActive() || !sourceDesc->useSwBridge() ||
5254 sourceDesc->canCloseOutput();
5255 setOutputDevices(outputDesc,
5256 updateDevice ? getNewOutputDevices(outputDesc, true /*fromCache*/) :
5257 outputDesc->devices(),
5258 force,
5259 0,
5260 patchHandle == AUDIO_PATCH_HANDLE_NONE ? nullptr : &patchHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005261 } else {
5262 return BAD_VALUE;
5263 }
5264 } else {
5265 return BAD_VALUE;
5266 }
5267 return NO_ERROR;
5268}
5269
5270status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
5271 struct audio_patch *patches,
5272 unsigned int *generation)
5273{
François Gaffie53615e22015-03-19 09:24:12 +01005274 if (generation == NULL) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005275 return BAD_VALUE;
5276 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005277 *generation = curAudioPortGeneration();
François Gaffie53615e22015-03-19 09:24:12 +01005278 return mAudioPatches.listAudioPatches(num_patches, patches);
Eric Laurent6a94d692014-05-20 11:18:06 -07005279}
5280
Eric Laurente1715a42014-05-20 11:30:42 -07005281status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07005282{
Eric Laurente1715a42014-05-20 11:30:42 -07005283 ALOGV("setAudioPortConfig()");
5284
5285 if (config == NULL) {
5286 return BAD_VALUE;
5287 }
5288 ALOGV("setAudioPortConfig() on port handle %d", config->id);
5289 // Only support gain configuration for now
Eric Laurenta121f902014-06-03 13:32:54 -07005290 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
5291 return INVALID_OPERATION;
Eric Laurente1715a42014-05-20 11:30:42 -07005292 }
5293
Eric Laurenta121f902014-06-03 13:32:54 -07005294 sp<AudioPortConfig> audioPortConfig;
Eric Laurente1715a42014-05-20 11:30:42 -07005295 if (config->type == AUDIO_PORT_TYPE_MIX) {
5296 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005297 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07005298 if (outputDesc == NULL) {
5299 return BAD_VALUE;
5300 }
Eric Laurent84c70242014-06-23 08:46:27 -07005301 ALOG_ASSERT(!outputDesc->isDuplicated(),
5302 "setAudioPortConfig() called on duplicated output %d",
5303 outputDesc->mIoHandle);
Eric Laurenta121f902014-06-03 13:32:54 -07005304 audioPortConfig = outputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07005305 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
François Gaffie53615e22015-03-19 09:24:12 +01005306 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07005307 if (inputDesc == NULL) {
5308 return BAD_VALUE;
5309 }
Eric Laurenta121f902014-06-03 13:32:54 -07005310 audioPortConfig = inputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07005311 } else {
5312 return BAD_VALUE;
5313 }
5314 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
5315 sp<DeviceDescriptor> deviceDesc;
5316 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
5317 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
5318 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
5319 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
5320 } else {
5321 return BAD_VALUE;
5322 }
5323 if (deviceDesc == NULL) {
5324 return BAD_VALUE;
5325 }
Eric Laurenta121f902014-06-03 13:32:54 -07005326 audioPortConfig = deviceDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07005327 } else {
5328 return BAD_VALUE;
5329 }
5330
Mikhail Naganov7be71d22018-05-23 16:51:46 -07005331 struct audio_port_config backupConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07005332 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
5333 if (status == NO_ERROR) {
Mikhail Naganov7be71d22018-05-23 16:51:46 -07005334 struct audio_port_config newConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07005335 audioPortConfig->toAudioPortConfig(&newConfig, config);
5336 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
Eric Laurente1715a42014-05-20 11:30:42 -07005337 }
Eric Laurenta121f902014-06-03 13:32:54 -07005338 if (status != NO_ERROR) {
5339 audioPortConfig->applyAudioPortConfig(&backupConfig);
Eric Laurente1715a42014-05-20 11:30:42 -07005340 }
Eric Laurente1715a42014-05-20 11:30:42 -07005341
5342 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07005343}
5344
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005345void AudioPolicyManager::releaseResourcesForUid(uid_t uid)
5346{
Eric Laurentd60560a2015-04-10 11:31:20 -07005347 clearAudioSources(uid);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005348 clearAudioPatches(uid);
5349 clearSessionRoutes(uid);
5350}
5351
Eric Laurent6a94d692014-05-20 11:18:06 -07005352void AudioPolicyManager::clearAudioPatches(uid_t uid)
5353{
Eric Laurent0add0fd2014-12-04 18:58:14 -08005354 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005355 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
François Gaffieafd4cea2019-11-18 15:50:22 +01005356 if (patchDesc->getUid() == uid) {
Eric Laurent0add0fd2014-12-04 18:58:14 -08005357 releaseAudioPatch(mAudioPatches.keyAt(i), uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07005358 }
5359 }
5360}
5361
François Gaffiec005e562018-11-06 15:04:49 +01005362void AudioPolicyManager::checkStrategyRoute(product_strategy_t ps, audio_io_handle_t ouptutToSkip)
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005363{
François Gaffiec005e562018-11-06 15:04:49 +01005364 // Take the first attributes following the product strategy as it is used to retrieve the routed
5365 // device. All attributes wihin a strategy follows the same "routing strategy"
5366 auto attributes = mEngine->getAllAttributesForProductStrategy(ps).front();
5367 DeviceVector devices = mEngine->getOutputDevicesForAttributes(attributes, nullptr, false);
François Gaffie11d30102018-11-02 16:09:09 +01005368 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
jiabin3ff8d7d2022-12-13 06:27:44 +00005369 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005370 for (size_t j = 0; j < mOutputs.size(); j++) {
5371 if (mOutputs.keyAt(j) == ouptutToSkip) {
5372 continue;
5373 }
5374 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(j);
François Gaffiec005e562018-11-06 15:04:49 +01005375 if (!outputDesc->isStrategyActive(ps)) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005376 continue;
5377 }
5378 // If the default device for this strategy is on another output mix,
5379 // invalidate all tracks in this strategy to force re connection.
5380 // Otherwise select new device on the output mix.
5381 if (outputs.indexOf(mOutputs.keyAt(j)) < 0) {
jiabinc44b3462022-12-08 12:52:31 -08005382 invalidateStreams(mEngine->getStreamTypesForProductStrategy(ps));
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005383 } else {
jiabin3ff8d7d2022-12-13 06:27:44 +00005384 DeviceVector newDevices = getNewOutputDevices(outputDesc, false /*fromCache*/);
5385 if (outputDesc->mUsePreferredMixerAttributes && outputDesc->devices() != newDevices) {
5386 // If the device is using preferred mixer attributes, the output need to reopen
5387 // with default configuration when the new selected devices are different from
5388 // current routing devices.
5389 outputsToReopen.emplace(mOutputs.keyAt(j), newDevices);
5390 continue;
5391 }
5392 setOutputDevices(outputDesc, newDevices, false);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005393 }
5394 }
jiabin3ff8d7d2022-12-13 06:27:44 +00005395 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005396}
5397
5398void AudioPolicyManager::clearSessionRoutes(uid_t uid)
5399{
5400 // remove output routes associated with this uid
François Gaffiec005e562018-11-06 15:04:49 +01005401 std::vector<product_strategy_t> affectedStrategies;
Eric Laurent97ac8712018-07-27 18:59:02 -07005402 for (size_t i = 0; i < mOutputs.size(); i++) {
5403 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07005404 for (const auto& client : outputDesc->getClientIterable()) {
5405 if (client->hasPreferredDevice() && client->uid() == uid) {
5406 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
François Gaffiec005e562018-11-06 15:04:49 +01005407 auto clientStrategy = client->strategy();
5408 if (std::find(begin(affectedStrategies), end(affectedStrategies), clientStrategy) !=
5409 end(affectedStrategies)) {
5410 continue;
5411 }
5412 affectedStrategies.push_back(client->strategy());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005413 }
5414 }
5415 }
5416 // reroute outputs if necessary
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005417 for (const auto& strategy : affectedStrategies) {
5418 checkStrategyRoute(strategy, AUDIO_IO_HANDLE_NONE);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005419 }
5420
5421 // remove input routes associated with this uid
5422 SortedVector<audio_source_t> affectedSources;
Eric Laurent97ac8712018-07-27 18:59:02 -07005423 for (size_t i = 0; i < mInputs.size(); i++) {
5424 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07005425 for (const auto& client : inputDesc->getClientIterable()) {
5426 if (client->hasPreferredDevice() && client->uid() == uid) {
5427 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
5428 affectedSources.add(client->source());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005429 }
5430 }
5431 }
5432 // reroute inputs if necessary
5433 SortedVector<audio_io_handle_t> inputsToClose;
5434 for (size_t i = 0; i < mInputs.size(); i++) {
5435 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Eric Laurent4eb58f12018-12-07 16:41:02 -08005436 if (affectedSources.indexOf(inputDesc->source()) >= 0) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005437 inputsToClose.add(inputDesc->mIoHandle);
5438 }
5439 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005440 for (const auto& input : inputsToClose) {
5441 closeInput(input);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005442 }
5443}
5444
Eric Laurentd60560a2015-04-10 11:31:20 -07005445void AudioPolicyManager::clearAudioSources(uid_t uid)
5446{
5447 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005448 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
5449 if (sourceDesc->uid() == uid) {
Eric Laurentd60560a2015-04-10 11:31:20 -07005450 stopAudioSource(mAudioSources.keyAt(i));
5451 }
5452 }
5453}
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005454
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005455status_t AudioPolicyManager::acquireSoundTriggerSession(audio_session_t *session,
5456 audio_io_handle_t *ioHandle,
5457 audio_devices_t *device)
5458{
Glenn Kastenf0c6d7d2016-02-26 10:44:04 -08005459 *session = (audio_session_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
5460 *ioHandle = (audio_io_handle_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
Francois Gaffie716e1432019-01-14 16:58:59 +01005461 audio_attributes_t attr = { .source = AUDIO_SOURCE_HOTWORD };
Eric Laurentcedd5b52023-03-22 00:03:31 +00005462 sp<DeviceDescriptor> deviceDesc = mEngine->getInputDeviceForAttributes(attr);
5463 if (deviceDesc == nullptr) {
5464 return INVALID_OPERATION;
5465 }
5466 *device = deviceDesc->type();
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005467
François Gaffiedf372692015-03-19 10:43:27 +01005468 return mSoundTriggerSessions.acquireSession(*session, *ioHandle);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005469}
5470
Eric Laurentd60560a2015-04-10 11:31:20 -07005471status_t AudioPolicyManager::startAudioSource(const struct audio_port_config *source,
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005472 const audio_attributes_t *attributes,
5473 audio_port_handle_t *portId,
5474 uid_t uid)
Eric Laurent554a2772015-04-10 11:29:24 -07005475{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005476 ALOGV("%s", __FUNCTION__);
5477 *portId = AUDIO_PORT_HANDLE_NONE;
5478
5479 if (source == NULL || attributes == NULL || portId == NULL) {
5480 ALOGW("%s invalid argument: source %p attributes %p handle %p",
5481 __FUNCTION__, source, attributes, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005482 return BAD_VALUE;
5483 }
5484
Eric Laurentd60560a2015-04-10 11:31:20 -07005485 if (source->role != AUDIO_PORT_ROLE_SOURCE ||
5486 source->type != AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005487 ALOGW("%s INVALID_OPERATION source->role %d source->type %d",
5488 __FUNCTION__, source->role, source->type);
Eric Laurentd60560a2015-04-10 11:31:20 -07005489 return INVALID_OPERATION;
5490 }
5491
François Gaffie11d30102018-11-02 16:09:09 +01005492 sp<DeviceDescriptor> srcDevice =
Eric Laurentd60560a2015-04-10 11:31:20 -07005493 mAvailableInputDevices.getDevice(source->ext.device.type,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005494 String8(source->ext.device.address),
5495 AUDIO_FORMAT_DEFAULT);
François Gaffie11d30102018-11-02 16:09:09 +01005496 if (srcDevice == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005497 ALOGW("%s source->ext.device.type %08x not found", __FUNCTION__, source->ext.device.type);
Eric Laurentd60560a2015-04-10 11:31:20 -07005498 return BAD_VALUE;
5499 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005500
jiabin4ef93452019-09-10 14:29:54 -07005501 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurentd60560a2015-04-10 11:31:20 -07005502
François Gaffieaaac0fd2018-11-22 17:56:39 +01005503 sp<SourceClientDescriptor> sourceDesc =
François Gaffieafd4cea2019-11-18 15:50:22 +01005504 new SourceClientDescriptor(*portId, uid, *attributes, *source, srcDevice,
François Gaffieaaac0fd2018-11-22 17:56:39 +01005505 mEngine->getStreamTypeForAttributes(*attributes),
5506 mEngine->getProductStrategyForAttributes(*attributes),
5507 toVolumeSource(*attributes));
Eric Laurentd60560a2015-04-10 11:31:20 -07005508
5509 status_t status = connectAudioSource(sourceDesc);
5510 if (status == NO_ERROR) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005511 mAudioSources.add(*portId, sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07005512 }
5513 return status;
5514}
5515
Francois Gaffie601801d2021-06-22 13:27:39 +02005516sp<SourceClientDescriptor> AudioPolicyManager::startAudioSourceInternal(
5517 const struct audio_port_config *source, const audio_attributes_t *attributes, uid_t uid)
5518{
5519 ALOGV("%s", __FUNCTION__);
5520 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
5521
5522 status_t status = startAudioSource(source, attributes, &portId, uid);
5523 ALOGE_IF(status != OK, "%s: failed to start audio source (%d)", __func__, status);
5524 return mAudioSources.valueFor(portId);
5525}
5526
5527
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005528status_t AudioPolicyManager::connectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07005529{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005530 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->portId());
Eric Laurentd60560a2015-04-10 11:31:20 -07005531
5532 // make sure we only have one patch per source.
5533 disconnectAudioSource(sourceDesc);
5534
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005535 audio_attributes_t attributes = sourceDesc->attributes();
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005536 // May the device (dynamic) have been disconnected/reconnected, id has changed.
5537 sp<DeviceDescriptor> srcDevice = mAvailableInputDevices.getDevice(
5538 sourceDesc->srcDevice()->type(),
5539 String8(sourceDesc->srcDevice()->address().c_str()),
5540 AUDIO_FORMAT_DEFAULT);
François Gaffiec005e562018-11-06 15:04:49 +01005541 DeviceVector sinkDevices =
Francois Gaffieff1eb522020-05-06 18:37:04 +02005542 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false /*fromCache*/);
François Gaffiec005e562018-11-06 15:04:49 +01005543 ALOG_ASSERT(!sinkDevices.isEmpty(), "connectAudioSource(): no device found for attributes");
François Gaffie11d30102018-11-02 16:09:09 +01005544 sp<DeviceDescriptor> sinkDevice = sinkDevices.itemAt(0);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005545 if (!mAvailableOutputDevices.contains(sinkDevice)) {
5546 ALOGE("%s Device %s not available", __func__, sinkDevice->toString().c_str());
5547 return INVALID_OPERATION;
5548 }
François Gaffieafd4cea2019-11-18 15:50:22 +01005549 PatchBuilder patchBuilder;
5550 patchBuilder.addSink(sinkDevice).addSource(srcDevice);
5551 audio_patch_handle_t handle = AUDIO_PATCH_HANDLE_NONE;
François Gaffieafd4cea2019-11-18 15:50:22 +01005552
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005553 return connectAudioSourceToSink(
5554 sourceDesc, sinkDevice, patchBuilder.patch(), handle, mUidCached, 0 /*delayMs*/);
Eric Laurent554a2772015-04-10 11:29:24 -07005555}
5556
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005557status_t AudioPolicyManager::stopAudioSource(audio_port_handle_t portId)
Eric Laurent554a2772015-04-10 11:29:24 -07005558{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005559 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueFor(portId);
5560 ALOGV("%s port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005561 if (sourceDesc == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005562 ALOGW("%s unknown source for port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005563 return BAD_VALUE;
5564 }
5565 status_t status = disconnectAudioSource(sourceDesc);
5566
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005567 mAudioSources.removeItem(portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005568 return status;
5569}
5570
Andy Hung2ddee192015-12-18 17:34:44 -08005571status_t AudioPolicyManager::setMasterMono(bool mono)
5572{
5573 if (mMasterMono == mono) {
5574 return NO_ERROR;
5575 }
5576 mMasterMono = mono;
5577 // if enabling mono we close all offloaded devices, which will invalidate the
5578 // corresponding AudioTrack. The AudioTrack client/MediaPlayer is responsible
5579 // for recreating the new AudioTrack as non-offloaded PCM.
5580 //
5581 // If disabling mono, we leave all tracks as is: we don't know which clients
5582 // and tracks are able to be recreated as offloaded. The next "song" should
5583 // play back offloaded.
5584 if (mMasterMono) {
5585 Vector<audio_io_handle_t> offloaded;
5586 for (size_t i = 0; i < mOutputs.size(); ++i) {
5587 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
5588 if (desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
5589 offloaded.push(desc->mIoHandle);
5590 }
5591 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005592 for (const auto& handle : offloaded) {
5593 closeOutput(handle);
Andy Hung2ddee192015-12-18 17:34:44 -08005594 }
5595 }
5596 // update master mono for all remaining outputs
5597 for (size_t i = 0; i < mOutputs.size(); ++i) {
5598 updateMono(mOutputs.keyAt(i));
5599 }
5600 return NO_ERROR;
5601}
5602
5603status_t AudioPolicyManager::getMasterMono(bool *mono)
5604{
5605 *mono = mMasterMono;
5606 return NO_ERROR;
5607}
5608
Eric Laurentac9cef52017-06-09 15:46:26 -07005609float AudioPolicyManager::getStreamVolumeDB(
5610 audio_stream_type_t stream, int index, audio_devices_t device)
5611{
jiabin9a3361e2019-10-01 09:38:30 -07005612 return computeVolume(getVolumeCurves(stream), toVolumeSource(stream), index, {device});
Eric Laurentac9cef52017-06-09 15:46:26 -07005613}
5614
jiabin81772902018-04-02 17:52:27 -07005615status_t AudioPolicyManager::getSurroundFormats(unsigned int *numSurroundFormats,
5616 audio_format_t *surroundFormats,
Kriti Dang6537def2021-03-02 13:46:59 +01005617 bool *surroundFormatsEnabled)
jiabin81772902018-04-02 17:52:27 -07005618{
Kriti Dang6537def2021-03-02 13:46:59 +01005619 if (numSurroundFormats == nullptr || (*numSurroundFormats != 0 &&
5620 (surroundFormats == nullptr || surroundFormatsEnabled == nullptr))) {
jiabin81772902018-04-02 17:52:27 -07005621 return BAD_VALUE;
5622 }
Kriti Dang6537def2021-03-02 13:46:59 +01005623 ALOGV("%s() numSurroundFormats %d surroundFormats %p surroundFormatsEnabled %p",
5624 __func__, *numSurroundFormats, surroundFormats, surroundFormatsEnabled);
jiabin81772902018-04-02 17:52:27 -07005625
5626 size_t formatsWritten = 0;
5627 size_t formatsMax = *numSurroundFormats;
Kriti Dangef6be8f2020-11-05 11:58:19 +01005628
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005629 *numSurroundFormats = mConfig->getSurroundFormats().size();
Mikhail Naganov100f0122018-11-29 11:22:16 -08005630 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
5631 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005632 for (const auto& format: mConfig->getSurroundFormats()) {
jiabin81772902018-04-02 17:52:27 -07005633 if (formatsWritten < formatsMax) {
Kriti Dang6537def2021-03-02 13:46:59 +01005634 surroundFormats[formatsWritten] = format.first;
Mikhail Naganov100f0122018-11-29 11:22:16 -08005635 bool formatEnabled = true;
5636 switch (forceUse) {
5637 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL:
Kriti Dang6537def2021-03-02 13:46:59 +01005638 formatEnabled = mManualSurroundFormats.count(format.first) != 0;
Mikhail Naganov100f0122018-11-29 11:22:16 -08005639 break;
5640 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER:
5641 formatEnabled = false;
5642 break;
5643 default: // AUTO or ALWAYS => true
5644 break;
jiabin81772902018-04-02 17:52:27 -07005645 }
5646 surroundFormatsEnabled[formatsWritten++] = formatEnabled;
5647 }
jiabin81772902018-04-02 17:52:27 -07005648 }
5649 return NO_ERROR;
5650}
5651
Kriti Dang6537def2021-03-02 13:46:59 +01005652status_t AudioPolicyManager::getReportedSurroundFormats(unsigned int *numSurroundFormats,
5653 audio_format_t *surroundFormats) {
5654 if (numSurroundFormats == nullptr || (*numSurroundFormats != 0 && surroundFormats == nullptr)) {
5655 return BAD_VALUE;
5656 }
5657 ALOGV("%s() numSurroundFormats %d surroundFormats %p",
5658 __func__, *numSurroundFormats, surroundFormats);
5659
5660 size_t formatsWritten = 0;
5661 size_t formatsMax = *numSurroundFormats;
5662 std::unordered_set<audio_format_t> formats; // Uses primary surround formats only
5663
5664 // Return formats from all device profiles that have already been resolved by
5665 // checkOutputsForDevice().
5666 for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
5667 sp<DeviceDescriptor> device = mAvailableOutputDevices[i];
5668 audio_devices_t deviceType = device->type();
5669 // Enabling/disabling formats are applied to only HDMI devices. So, this function
5670 // returns formats reported by HDMI devices.
5671 if (deviceType != AUDIO_DEVICE_OUT_HDMI) {
5672 continue;
5673 }
5674 // Formats reported by sink devices
5675 std::unordered_set<audio_format_t> formatset;
5676 if (auto it = mReportedFormatsMap.find(device); it != mReportedFormatsMap.end()) {
5677 formatset.insert(it->second.begin(), it->second.end());
5678 }
5679
5680 // Formats hard-coded in the in policy configuration file (if any).
5681 FormatVector encodedFormats = device->encodedFormats();
5682 formatset.insert(encodedFormats.begin(), encodedFormats.end());
5683 // Filter the formats which are supported by the vendor hardware.
5684 for (auto it = formatset.begin(); it != formatset.end(); ++it) {
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005685 if (mConfig->getSurroundFormats().count(*it) != 0) {
Kriti Dang6537def2021-03-02 13:46:59 +01005686 formats.insert(*it);
5687 } else {
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005688 for (const auto& pair : mConfig->getSurroundFormats()) {
Kriti Dang6537def2021-03-02 13:46:59 +01005689 if (pair.second.count(*it) != 0) {
5690 formats.insert(pair.first);
5691 break;
5692 }
5693 }
5694 }
5695 }
5696 }
5697 *numSurroundFormats = formats.size();
5698 for (const auto& format: formats) {
5699 if (formatsWritten < formatsMax) {
5700 surroundFormats[formatsWritten++] = format;
5701 }
5702 }
5703 return NO_ERROR;
5704}
5705
jiabin81772902018-04-02 17:52:27 -07005706status_t AudioPolicyManager::setSurroundFormatEnabled(audio_format_t audioFormat, bool enabled)
5707{
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005708 ALOGV("%s() format 0x%X enabled %d", __func__, audioFormat, enabled);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005709 const auto& formatIter = mConfig->getSurroundFormats().find(audioFormat);
5710 if (formatIter == mConfig->getSurroundFormats().end()) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005711 ALOGW("%s() format 0x%X is not a known surround format", __func__, audioFormat);
jiabin81772902018-04-02 17:52:27 -07005712 return BAD_VALUE;
5713 }
5714
Mikhail Naganov100f0122018-11-29 11:22:16 -08005715 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND) !=
5716 AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005717 ALOGW("%s() not in manual mode for surround sound format selection", __func__);
jiabin81772902018-04-02 17:52:27 -07005718 return INVALID_OPERATION;
5719 }
5720
Mikhail Naganov100f0122018-11-29 11:22:16 -08005721 if ((mManualSurroundFormats.count(audioFormat) != 0) == enabled) {
jiabin81772902018-04-02 17:52:27 -07005722 return NO_ERROR;
5723 }
5724
Mikhail Naganov100f0122018-11-29 11:22:16 -08005725 std::unordered_set<audio_format_t> surroundFormatsBackup(mManualSurroundFormats);
jiabin81772902018-04-02 17:52:27 -07005726 if (enabled) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005727 mManualSurroundFormats.insert(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07005728 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005729 mManualSurroundFormats.insert(subFormat);
jiabin81772902018-04-02 17:52:27 -07005730 }
5731 } else {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005732 mManualSurroundFormats.erase(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07005733 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005734 mManualSurroundFormats.erase(subFormat);
jiabin81772902018-04-02 17:52:27 -07005735 }
5736 }
5737
5738 sp<SwAudioOutputDescriptor> outputDesc;
5739 bool profileUpdated = false;
jiabin9a3361e2019-10-01 09:38:30 -07005740 DeviceVector hdmiOutputDevices = mAvailableOutputDevices.getDevicesFromType(
5741 AUDIO_DEVICE_OUT_HDMI);
jiabin81772902018-04-02 17:52:27 -07005742 for (size_t i = 0; i < hdmiOutputDevices.size(); i++) {
5743 // Simulate reconnection to update enabled surround sound formats.
jiabince9f20e2019-09-12 16:29:15 -07005744 String8 address = String8(hdmiOutputDevices[i]->address().c_str());
jiabin5740f082019-08-19 15:08:30 -07005745 std::string name = hdmiOutputDevices[i]->getName();
jiabin81772902018-04-02 17:52:27 -07005746 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
5747 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
5748 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005749 name.c_str(),
5750 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005751 if (status != NO_ERROR) {
5752 continue;
5753 }
5754 status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
5755 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
5756 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005757 name.c_str(),
5758 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005759 profileUpdated |= (status == NO_ERROR);
5760 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08005761 // FIXME: Why doing this for input HDMI devices if we don't augment their reported formats?
jiabin9a3361e2019-10-01 09:38:30 -07005762 DeviceVector hdmiInputDevices = mAvailableInputDevices.getDevicesFromType(
jiabin81772902018-04-02 17:52:27 -07005763 AUDIO_DEVICE_IN_HDMI);
5764 for (size_t i = 0; i < hdmiInputDevices.size(); i++) {
5765 // Simulate reconnection to update enabled surround sound formats.
jiabince9f20e2019-09-12 16:29:15 -07005766 String8 address = String8(hdmiInputDevices[i]->address().c_str());
jiabin5740f082019-08-19 15:08:30 -07005767 std::string name = hdmiInputDevices[i]->getName();
jiabin81772902018-04-02 17:52:27 -07005768 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
5769 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
5770 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005771 name.c_str(),
5772 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005773 if (status != NO_ERROR) {
5774 continue;
5775 }
5776 status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
5777 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
5778 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005779 name.c_str(),
5780 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005781 profileUpdated |= (status == NO_ERROR);
5782 }
5783
jiabin81772902018-04-02 17:52:27 -07005784 if (!profileUpdated) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005785 ALOGW("%s() no audio profiles updated, undoing surround formats change", __func__);
Mikhail Naganov100f0122018-11-29 11:22:16 -08005786 mManualSurroundFormats = std::move(surroundFormatsBackup);
jiabin81772902018-04-02 17:52:27 -07005787 }
5788
5789 return profileUpdated ? NO_ERROR : INVALID_OPERATION;
5790}
5791
Eric Laurent5ada82e2019-08-29 17:53:54 -07005792void AudioPolicyManager::setAppState(audio_port_handle_t portId, app_state_t state)
Svet Ganovf4ddfef2018-01-16 07:37:58 -08005793{
Eric Laurent5ada82e2019-08-29 17:53:54 -07005794 ALOGV("%s(portId:%d, state:%d)", __func__, portId, state);
Eric Laurenta9f86652018-11-28 17:23:11 -08005795 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent5ada82e2019-08-29 17:53:54 -07005796 mInputs.valueAt(i)->setAppState(portId, state);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08005797 }
5798}
5799
jiabin6012f912018-11-02 17:06:30 -07005800bool AudioPolicyManager::isHapticPlaybackSupported()
5801{
5802 for (const auto& hwModule : mHwModules) {
5803 const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
5804 for (const auto &outProfile : outputProfiles) {
5805 struct audio_port audioPort;
5806 outProfile->toAudioPort(&audioPort);
5807 for (size_t i = 0; i < audioPort.num_channel_masks; i++) {
5808 if (audioPort.channel_masks[i] & AUDIO_CHANNEL_HAPTIC_ALL) {
5809 return true;
5810 }
5811 }
5812 }
5813 }
5814 return false;
5815}
5816
Carter Hsu325a8eb2022-01-19 19:56:51 +08005817bool AudioPolicyManager::isUltrasoundSupported()
5818{
5819 bool hasUltrasoundOutput = false;
5820 bool hasUltrasoundInput = false;
5821 for (const auto& hwModule : mHwModules) {
5822 const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
5823 if (!hasUltrasoundOutput) {
5824 for (const auto &outProfile : outputProfiles) {
5825 if (outProfile->getFlags() & AUDIO_OUTPUT_FLAG_ULTRASOUND) {
5826 hasUltrasoundOutput = true;
5827 break;
5828 }
5829 }
5830 }
5831
5832 const InputProfileCollection &inputProfiles = hwModule->getInputProfiles();
5833 if (!hasUltrasoundInput) {
5834 for (const auto &inputProfile : inputProfiles) {
5835 if (inputProfile->getFlags() & AUDIO_INPUT_FLAG_ULTRASOUND) {
5836 hasUltrasoundInput = true;
5837 break;
5838 }
5839 }
5840 }
5841
5842 if (hasUltrasoundOutput && hasUltrasoundInput)
5843 return true;
5844 }
5845 return false;
5846}
5847
Atneya Nair698f5ef2022-12-15 16:15:09 -08005848bool AudioPolicyManager::isHotwordStreamSupported(bool lookbackAudio)
5849{
5850 const auto mask = AUDIO_INPUT_FLAG_HOTWORD_TAP |
5851 (lookbackAudio ? AUDIO_INPUT_FLAG_HW_LOOKBACK : 0);
5852 for (const auto& hwModule : mHwModules) {
5853 const InputProfileCollection &inputProfiles = hwModule->getInputProfiles();
5854 for (const auto &inputProfile : inputProfiles) {
5855 if ((inputProfile->getFlags() & mask) == mask) {
5856 return true;
5857 }
5858 }
5859 }
5860 return false;
5861}
5862
Eric Laurent8340e672019-11-06 11:01:08 -08005863bool AudioPolicyManager::isCallScreenModeSupported()
5864{
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005865 return mConfig->isCallScreenModeSupported();
Eric Laurent8340e672019-11-06 11:01:08 -08005866}
5867
5868
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005869status_t AudioPolicyManager::disconnectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07005870{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005871 ALOGV("%s port Id %d", __FUNCTION__, sourceDesc->portId());
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005872 if (!sourceDesc->isConnected()) {
5873 ALOGV("%s port Id %d already disconnected", __FUNCTION__, sourceDesc->portId());
5874 return NO_ERROR;
5875 }
François Gaffieafd4cea2019-11-18 15:50:22 +01005876 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
5877 if (swOutput != 0) {
5878 status_t status = stopSource(swOutput, sourceDesc);
Eric Laurent733ce942017-12-07 12:18:25 -08005879 if (status == NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005880 swOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08005881 }
jiabinbce0c1d2020-10-05 11:20:18 -07005882 if (releaseOutput(sourceDesc->portId())) {
5883 // The output descriptor is reopened to query dynamic profiles. In that case, there is
5884 // no need to release audio patch here but just return NO_ERROR.
5885 return NO_ERROR;
5886 }
Eric Laurentd60560a2015-04-10 11:31:20 -07005887 } else {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005888 sp<HwAudioOutputDescriptor> hwOutputDesc = sourceDesc->hwOutput().promote();
Eric Laurentd60560a2015-04-10 11:31:20 -07005889 if (hwOutputDesc != 0) {
Eric Laurentd60560a2015-04-10 11:31:20 -07005890 // close Hwoutput and remove from mHwOutputs
5891 } else {
5892 ALOGW("%s source has neither SW nor HW output", __FUNCTION__);
5893 }
5894 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005895 status_t status = releaseAudioPatchInternal(sourceDesc->getPatchHandle(), 0, sourceDesc);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005896 sourceDesc->disconnect();
5897 return status;
Eric Laurentd60560a2015-04-10 11:31:20 -07005898}
5899
François Gaffiec005e562018-11-06 15:04:49 +01005900sp<SourceClientDescriptor> AudioPolicyManager::getSourceForAttributesOnOutput(
5901 audio_io_handle_t output, const audio_attributes_t &attr)
Eric Laurentd60560a2015-04-10 11:31:20 -07005902{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005903 sp<SourceClientDescriptor> source;
Eric Laurentd60560a2015-04-10 11:31:20 -07005904 for (size_t i = 0; i < mAudioSources.size(); i++) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005905 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005906 sp<SwAudioOutputDescriptor> outputDesc = sourceDesc->swOutput().promote();
François Gaffiec005e562018-11-06 15:04:49 +01005907 if (followsSameRouting(attr, sourceDesc->attributes()) &&
5908 outputDesc != 0 && outputDesc->mIoHandle == output) {
Eric Laurentd60560a2015-04-10 11:31:20 -07005909 source = sourceDesc;
5910 break;
5911 }
5912 }
5913 return source;
Eric Laurent554a2772015-04-10 11:29:24 -07005914}
5915
Eric Laurentb4f42a92022-01-17 17:37:31 +01005916bool AudioPolicyManager::canBeSpatializedInt(const audio_attributes_t *attr,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005917 const audio_config_t *config,
Andy Hung9dd1a5b2022-05-10 15:39:39 -07005918 const AudioDeviceTypeAddrVector &devices) const
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005919{
5920 // The caller can have the audio attributes criteria ignored by either passing a null ptr or
5921 // the AUDIO_ATTRIBUTES_INITIALIZER value.
Eric Laurentfa0f6742021-08-17 18:39:44 +02005922 // If attributes are specified, current policy is to only allow spatialization for media
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005923 // and game usages.
Eric Laurent39095982021-08-24 18:29:27 +02005924 if (attr != nullptr && *attr != AUDIO_ATTRIBUTES_INITIALIZER) {
5925 if (attr->usage != AUDIO_USAGE_MEDIA && attr->usage != AUDIO_USAGE_GAME) {
5926 return false;
5927 }
5928 if ((attr->flags & (AUDIO_FLAG_CONTENT_SPATIALIZED | AUDIO_FLAG_NEVER_SPATIALIZE)) != 0) {
5929 return false;
5930 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005931 }
5932
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005933 sp<IOProfile> profile =
Eric Laurent39095982021-08-24 18:29:27 +02005934 getSpatializerOutputProfile(config, devices);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005935 if (profile == nullptr) {
5936 return false;
5937 }
5938
5939 // The caller can have the audio config criteria ignored by either passing a null ptr or
5940 // the AUDIO_CONFIG_INITIALIZER value.
Eric Laurentfa0f6742021-08-17 18:39:44 +02005941 // If an audio config is specified, current policy is to only allow spatialization for
Eric Laurent39095982021-08-24 18:29:27 +02005942 // some positional channel masks.
Eric Laurent39095982021-08-24 18:29:27 +02005943
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005944 if (config != nullptr && *config != AUDIO_CONFIG_INITIALIZER) {
Andy Hung9dd1a5b2022-05-10 15:39:39 -07005945 if (!audio_is_channel_mask_spatialized(config->channel_mask)) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005946 return false;
5947 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005948 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005949 return true;
5950}
5951
5952void AudioPolicyManager::checkVirtualizerClientRoutes() {
5953 std::set<audio_stream_type_t> streamsToInvalidate;
5954 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent39095982021-08-24 18:29:27 +02005955 const sp<SwAudioOutputDescriptor>& desc = mOutputs[i];
5956 for (const sp<TrackClientDescriptor>& client : desc->getClientIterable()) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005957 audio_attributes_t attr = client->attributes();
5958 DeviceVector devices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false);
5959 AudioDeviceTypeAddrVector devicesTypeAddress = devices.toTypeAddrVector();
5960 audio_config_base_t clientConfig = client->config();
5961 audio_config_t config = audio_config_initializer(&clientConfig);
Eric Laurent39095982021-08-24 18:29:27 +02005962 if (desc != mSpatializerOutput
Andy Hung9dd1a5b2022-05-10 15:39:39 -07005963 && canBeSpatializedInt(&attr, &config, devicesTypeAddress)) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005964 streamsToInvalidate.insert(client->stream());
5965 }
5966 }
5967 }
5968
jiabinc44b3462022-12-08 12:52:31 -08005969 invalidateStreams(StreamTypeVector(streamsToInvalidate.begin(), streamsToInvalidate.end()));
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005970}
5971
Eric Laurente191d1b2022-04-15 11:59:25 +02005972
5973bool AudioPolicyManager::isOutputOnlyAvailableRouteToSomeDevice(
5974 const sp<SwAudioOutputDescriptor>& outputDesc) {
5975 if (outputDesc->isDuplicated()) {
5976 return false;
5977 }
5978 DeviceVector devices = outputDesc->supportedDevices();
5979 for (size_t i = 0; i < mOutputs.size(); i++) {
5980 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
5981 if (desc == outputDesc || desc->isDuplicated()) {
5982 continue;
5983 }
5984 DeviceVector sharedDevices = desc->filterSupportedDevices(devices);
5985 if (!sharedDevices.isEmpty()
5986 && (desc->devicesSupportEncodedFormats(sharedDevices.types())
5987 == outputDesc->devicesSupportEncodedFormats(sharedDevices.types()))) {
5988 return false;
5989 }
5990 }
5991 return true;
5992}
5993
5994
Eric Laurentfa0f6742021-08-17 18:39:44 +02005995status_t AudioPolicyManager::getSpatializerOutput(const audio_config_base_t *mixerConfig,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005996 const audio_attributes_t *attr,
5997 audio_io_handle_t *output) {
5998 *output = AUDIO_IO_HANDLE_NONE;
5999
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006000 DeviceVector devices = mEngine->getOutputDevicesForAttributes(*attr, nullptr, false);
6001 AudioDeviceTypeAddrVector devicesTypeAddress = devices.toTypeAddrVector();
6002 audio_config_t *configPtr = nullptr;
6003 audio_config_t config;
6004 if (mixerConfig != nullptr) {
6005 config = audio_config_initializer(mixerConfig);
6006 configPtr = &config;
6007 }
Andy Hung9dd1a5b2022-05-10 15:39:39 -07006008 if (!canBeSpatializedInt(attr, configPtr, devicesTypeAddress)) {
Eric Laurente191d1b2022-04-15 11:59:25 +02006009 ALOGV("%s provided attributes or mixer config cannot be spatialized", __func__);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006010 return BAD_VALUE;
6011 }
6012
6013 sp<IOProfile> profile =
Eric Laurent39095982021-08-24 18:29:27 +02006014 getSpatializerOutputProfile(configPtr, devicesTypeAddress);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006015 if (profile == nullptr) {
Eric Laurente191d1b2022-04-15 11:59:25 +02006016 ALOGV("%s no suitable output profile for provided attributes or mixer config", __func__);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006017 return BAD_VALUE;
6018 }
6019
Eric Laurente191d1b2022-04-15 11:59:25 +02006020 std::vector<sp<SwAudioOutputDescriptor>> spatializerOutputs;
Eric Laurent39095982021-08-24 18:29:27 +02006021 for (size_t i = 0; i < mOutputs.size(); i++) {
6022 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente191d1b2022-04-15 11:59:25 +02006023 if (!desc->isDuplicated()
6024 && (desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0) {
6025 spatializerOutputs.push_back(desc);
6026 ALOGV("%s adding opened spatializer Output %d", __func__, desc->mIoHandle);
Eric Laurent39095982021-08-24 18:29:27 +02006027 }
6028 }
Eric Laurente191d1b2022-04-15 11:59:25 +02006029 mSpatializerOutput.clear();
6030 bool outputsChanged = false;
6031 for (const auto& desc : spatializerOutputs) {
6032 if (desc->mProfile == profile
6033 && (configPtr == nullptr
6034 || configPtr->channel_mask == desc->mMixerChannelMask)) {
6035 mSpatializerOutput = desc;
6036 ALOGV("%s reusing current spatializer output %d", __func__, desc->mIoHandle);
6037 } else {
6038 ALOGV("%s closing spatializerOutput output %d to match channel mask %#x"
6039 " and devices %s", __func__, desc->mIoHandle,
6040 configPtr != nullptr ? configPtr->channel_mask : 0,
6041 devices.toString().c_str());
6042 closeOutput(desc->mIoHandle);
6043 outputsChanged = true;
6044 }
Eric Laurent39095982021-08-24 18:29:27 +02006045 }
6046
Eric Laurente191d1b2022-04-15 11:59:25 +02006047 if (mSpatializerOutput == nullptr) {
Eric Laurentb4f42a92022-01-17 17:37:31 +01006048 sp<SwAudioOutputDescriptor> desc =
6049 openOutputWithProfileAndDevice(profile, devices, mixerConfig);
Eric Laurente191d1b2022-04-15 11:59:25 +02006050 if (desc != nullptr) {
6051 mSpatializerOutput = desc;
6052 outputsChanged = true;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006053 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006054 }
6055
6056 checkVirtualizerClientRoutes();
6057
Eric Laurente191d1b2022-04-15 11:59:25 +02006058 if (outputsChanged) {
6059 mPreviousOutputs = mOutputs;
6060 mpClientInterface->onAudioPortListUpdate();
6061 }
6062
6063 if (mSpatializerOutput == nullptr) {
6064 ALOGV("%s could not open spatializer output with requested config", __func__);
6065 return BAD_VALUE;
6066 }
Eric Laurent39095982021-08-24 18:29:27 +02006067 *output = mSpatializerOutput->mIoHandle;
Eric Laurente191d1b2022-04-15 11:59:25 +02006068 ALOGV("%s returning new spatializer output %d", __func__, *output);
6069 return OK;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006070}
6071
Eric Laurentfa0f6742021-08-17 18:39:44 +02006072status_t AudioPolicyManager::releaseSpatializerOutput(audio_io_handle_t output) {
6073 if (mSpatializerOutput == nullptr) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006074 return INVALID_OPERATION;
6075 }
Eric Laurentfa0f6742021-08-17 18:39:44 +02006076 if (mSpatializerOutput->mIoHandle != output) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006077 return BAD_VALUE;
6078 }
Eric Laurent39095982021-08-24 18:29:27 +02006079
Eric Laurente191d1b2022-04-15 11:59:25 +02006080 if (!isOutputOnlyAvailableRouteToSomeDevice(mSpatializerOutput)) {
6081 ALOGV("%s closing spatializer output %d", __func__, mSpatializerOutput->mIoHandle);
6082 closeOutput(mSpatializerOutput->mIoHandle);
6083 //from now on mSpatializerOutput is null
6084 checkVirtualizerClientRoutes();
6085 }
Eric Laurent39095982021-08-24 18:29:27 +02006086
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006087 return NO_ERROR;
6088}
6089
Eric Laurente552edb2014-03-10 17:42:56 -07006090// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07006091// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07006092// ----------------------------------------------------------------------------
Eric Laurent6a94d692014-05-20 11:18:06 -07006093uint32_t AudioPolicyManager::nextAudioPortGeneration()
6094{
Mikhail Naganov2773dd72017-12-08 10:12:11 -08006095 return mAudioPortGeneration++;
Eric Laurent6a94d692014-05-20 11:18:06 -07006096}
6097
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006098AudioPolicyManager::AudioPolicyManager(const sp<const AudioPolicyConfig>& config,
Mikhail Naganovf1b6d972023-05-02 13:56:01 -07006099 EngineInstance&& engine,
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006100 AudioPolicyClientInterface *clientInterface)
Eric Laurente552edb2014-03-10 17:42:56 -07006101 :
Andy Hung4ef19fa2018-05-15 19:35:29 -07006102 mUidCached(AID_AUDIOSERVER), // no need to call getuid(), there's only one of us running.
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006103 mConfig(config),
Mikhail Naganovf1b6d972023-05-02 13:56:01 -07006104 mEngine(std::move(engine)),
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006105 mpClientInterface(clientInterface),
Eric Laurente552edb2014-03-10 17:42:56 -07006106 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
Eric Laurent3a4311c2014-03-17 12:00:47 -07006107 mA2dpSuspended(false),
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006108 mAudioPortGeneration(1),
6109 mBeaconMuteRefCount(0),
6110 mBeaconPlayingRefCount(0),
Eric Laurent9459fb02015-08-12 18:36:32 -07006111 mBeaconMuted(false),
Andy Hung2ddee192015-12-18 17:34:44 -08006112 mTtsOutputAvailable(false),
Eric Laurent36829f92017-04-07 19:04:42 -07006113 mMasterMono(false),
Eric Laurent4eb58f12018-12-07 16:41:02 -08006114 mMusicEffectOutput(AUDIO_IO_HANDLE_NONE)
Eric Laurente552edb2014-03-10 17:42:56 -07006115{
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006116}
François Gaffied1ab2bd2015-12-02 18:20:06 +01006117
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006118status_t AudioPolicyManager::initialize() {
Mikhail Naganovf1b6d972023-05-02 13:56:01 -07006119 if (mEngine == nullptr) {
6120 return NO_INIT;
François Gaffie2110e042015-03-24 08:41:51 +01006121 }
6122 mEngine->setObserver(this);
6123 status_t status = mEngine->initCheck();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006124 if (status != NO_ERROR) {
6125 LOG_FATAL("Policy engine not initialized(err=%d)", status);
6126 return status;
6127 }
François Gaffie2110e042015-03-24 08:41:51 +01006128
jiabin29230182023-04-04 21:02:36 +00006129 // The actual device selection cache will be updated when calling `updateDevicesAndOutputs`
6130 // at the end of this function.
6131 mEngine->initializeDeviceSelectionCache();
Eric Laurent1d69c872021-01-11 18:53:01 +01006132 mCommunnicationStrategy = mEngine->getProductStrategyForAttributes(
6133 mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL));
6134
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006135 // after parsing the config, mConfig contain all known devices;
Eric Laurente552edb2014-03-10 17:42:56 -07006136 // open all output streams needed to access attached devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006137 onNewAudioModulesAvailableInt(nullptr /*newDevices*/);
François Gaffie11d30102018-11-02 16:09:09 +01006138
Eric Laurent3a4311c2014-03-17 12:00:47 -07006139 // make sure default device is reachable
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006140 if (const auto defaultOutputDevice = mConfig->getDefaultOutputDevice();
6141 defaultOutputDevice == nullptr ||
6142 !mAvailableOutputDevices.contains(defaultOutputDevice)) {
6143 ALOGE_IF(defaultOutputDevice != nullptr, "Default device %s is unreachable",
6144 defaultOutputDevice->toString().c_str());
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006145 status = NO_INIT;
Eric Laurent3a4311c2014-03-17 12:00:47 -07006146 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02006147 ALOGW_IF(mPrimaryOutput == nullptr, "The policy configuration does not declare a primary output");
Eric Laurente552edb2014-03-10 17:42:56 -07006148
Tomoharu Kasahara71c90912018-10-31 09:10:12 +09006149 // Silence ALOGV statements
6150 property_set("log.tag." LOG_TAG, "D");
6151
Eric Laurente552edb2014-03-10 17:42:56 -07006152 updateDevicesAndOutputs();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006153 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07006154}
6155
Eric Laurente0720872014-03-11 09:30:41 -07006156AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07006157{
Eric Laurente552edb2014-03-10 17:42:56 -07006158 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08006159 mOutputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07006160 }
6161 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08006162 mInputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07006163 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07006164 mAvailableOutputDevices.clear();
6165 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07006166 mOutputs.clear();
6167 mInputs.clear();
6168 mHwModules.clear();
Mikhail Naganov100f0122018-11-29 11:22:16 -08006169 mManualSurroundFormats.clear();
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006170 mConfig.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07006171}
6172
Eric Laurente0720872014-03-11 09:30:41 -07006173status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07006174{
Eric Laurent87ffa392015-05-22 10:32:38 -07006175 return hasPrimaryOutput() ? NO_ERROR : NO_INIT;
Eric Laurente552edb2014-03-10 17:42:56 -07006176}
6177
Eric Laurente552edb2014-03-10 17:42:56 -07006178// ---
6179
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006180void AudioPolicyManager::onNewAudioModulesAvailable()
6181{
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006182 DeviceVector newDevices;
6183 onNewAudioModulesAvailableInt(&newDevices);
6184 if (!newDevices.empty()) {
6185 nextAudioPortGeneration();
6186 mpClientInterface->onAudioPortListUpdate();
6187 }
6188}
6189
6190void AudioPolicyManager::onNewAudioModulesAvailableInt(DeviceVector *newDevices)
6191{
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006192 for (const auto& hwModule : mConfig->getHwModules()) {
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006193 if (std::find(mHwModules.begin(), mHwModules.end(), hwModule) != mHwModules.end()) {
6194 continue;
6195 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006196 if (hwModule->getHandle() == AUDIO_MODULE_HANDLE_NONE) {
Mikhail Naganovffd97712023-05-03 17:45:36 -07006197 if (audio_module_handle_t handle = mpClientInterface->loadHwModule(hwModule->getName());
6198 handle != AUDIO_MODULE_HANDLE_NONE) {
6199 hwModule->setHandle(handle);
6200 } else {
6201 ALOGW("could not load HW module %s", hwModule->getName());
6202 continue;
6203 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006204 }
6205 mHwModules.push_back(hwModule);
Dean Wheatley12a87132021-04-16 10:08:49 +10006206 // open all output streams needed to access attached devices.
6207 // direct outputs are closed immediately after checking the availability of attached devices
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006208 // This also validates mAvailableOutputDevices list
6209 for (const auto& outProfile : hwModule->getOutputProfiles()) {
6210 if (!outProfile->canOpenNewIo()) {
6211 ALOGE("Invalid Output profile max open count %u for profile %s",
6212 outProfile->maxOpenCount, outProfile->getTagName().c_str());
6213 continue;
6214 }
6215 if (!outProfile->hasSupportedDevices()) {
6216 ALOGW("Output profile contains no device on module %s", hwModule->getName());
6217 continue;
6218 }
Carter Hsu1a3364a2022-01-21 15:32:56 +08006219 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_TTS) != 0 ||
6220 (outProfile->getFlags() & AUDIO_OUTPUT_FLAG_ULTRASOUND) != 0) {
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006221 mTtsOutputAvailable = true;
6222 }
6223
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006224 const DeviceVector &supportedDevices = outProfile->getSupportedDevices();
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006225 DeviceVector availProfileDevices = supportedDevices.filter(mConfig->getOutputDevices());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006226 sp<DeviceDescriptor> supportedDevice = 0;
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006227 if (supportedDevices.contains(mConfig->getDefaultOutputDevice())) {
6228 supportedDevice = mConfig->getDefaultOutputDevice();
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006229 } else {
6230 // choose first device present in profile's SupportedDevices also part of
6231 // mAvailableOutputDevices.
6232 if (availProfileDevices.isEmpty()) {
6233 continue;
6234 }
6235 supportedDevice = availProfileDevices.itemAt(0);
6236 }
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006237 if (!mConfig->getOutputDevices().contains(supportedDevice)) {
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006238 continue;
6239 }
6240 sp<SwAudioOutputDescriptor> outputDesc = new SwAudioOutputDescriptor(outProfile,
6241 mpClientInterface);
6242 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentf1f22e72021-07-13 14:04:14 +02006243 status_t status = outputDesc->open(nullptr /* halConfig */, nullptr /* mixerConfig */,
6244 DeviceVector(supportedDevice),
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006245 AUDIO_STREAM_DEFAULT,
6246 AUDIO_OUTPUT_FLAG_NONE, &output);
6247 if (status != NO_ERROR) {
6248 ALOGW("Cannot open output stream for devices %s on hw module %s",
6249 supportedDevice->toString().c_str(), hwModule->getName());
6250 continue;
6251 }
6252 for (const auto &device : availProfileDevices) {
6253 // give a valid ID to an attached device once confirmed it is reachable
6254 if (!device->isAttached()) {
6255 device->attach(hwModule);
6256 mAvailableOutputDevices.add(device);
jiabin1c4794b2020-05-05 10:08:05 -07006257 device->setEncapsulationInfoFromHal(mpClientInterface);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006258 if (newDevices) newDevices->add(device);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006259 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
6260 }
6261 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02006262 if (mPrimaryOutput == nullptr &&
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006263 outProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
6264 mPrimaryOutput = outputDesc;
6265 }
Eric Laurent39095982021-08-24 18:29:27 +02006266 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
Eric Laurentc529cf62020-04-17 18:19:10 -07006267 outputDesc->close();
6268 } else {
6269 addOutput(output, outputDesc);
6270 setOutputDevices(outputDesc,
6271 DeviceVector(supportedDevice),
6272 true,
6273 0,
6274 NULL);
6275 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006276 }
6277 // open input streams needed to access attached devices to validate
6278 // mAvailableInputDevices list
6279 for (const auto& inProfile : hwModule->getInputProfiles()) {
6280 if (!inProfile->canOpenNewIo()) {
6281 ALOGE("Invalid Input profile max open count %u for profile %s",
6282 inProfile->maxOpenCount, inProfile->getTagName().c_str());
6283 continue;
6284 }
6285 if (!inProfile->hasSupportedDevices()) {
6286 ALOGW("Input profile contains no device on module %s", hwModule->getName());
6287 continue;
6288 }
6289 // chose first device present in profile's SupportedDevices also part of
6290 // available input devices
6291 const DeviceVector &supportedDevices = inProfile->getSupportedDevices();
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006292 DeviceVector availProfileDevices = supportedDevices.filter(mConfig->getInputDevices());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006293 if (availProfileDevices.isEmpty()) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01006294 ALOGV("%s: Input device list is empty! for profile %s",
6295 __func__, inProfile->getTagName().c_str());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006296 continue;
6297 }
6298 sp<AudioInputDescriptor> inputDesc =
6299 new AudioInputDescriptor(inProfile, mpClientInterface);
6300
6301 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
6302 status_t status = inputDesc->open(nullptr,
6303 availProfileDevices.itemAt(0),
6304 AUDIO_SOURCE_MIC,
6305 AUDIO_INPUT_FLAG_NONE,
6306 &input);
6307 if (status != NO_ERROR) {
6308 ALOGW("Cannot open input stream for device %s on hw module %s",
6309 availProfileDevices.toString().c_str(),
6310 hwModule->getName());
6311 continue;
6312 }
6313 for (const auto &device : availProfileDevices) {
6314 // give a valid ID to an attached device once confirmed it is reachable
6315 if (!device->isAttached()) {
6316 device->attach(hwModule);
6317 device->importAudioPortAndPickAudioProfile(inProfile, true);
6318 mAvailableInputDevices.add(device);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006319 if (newDevices) newDevices->add(device);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006320 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
6321 }
6322 }
6323 inputDesc->close();
6324 }
6325 }
Eric Laurente191d1b2022-04-15 11:59:25 +02006326
6327 // Check if spatializer outputs can be closed until used.
6328 // mOutputs vector never contains duplicated outputs at this point.
6329 std::vector<audio_io_handle_t> outputsClosed;
6330 for (size_t i = 0; i < mOutputs.size(); i++) {
6331 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
6332 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0
6333 && !isOutputOnlyAvailableRouteToSomeDevice(desc)) {
6334 outputsClosed.push_back(desc->mIoHandle);
6335 desc->close();
6336 }
6337 }
6338 for (auto output : outputsClosed) {
6339 removeOutput(output);
6340 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006341}
6342
Eric Laurent98e38192018-02-15 18:31:53 -08006343void AudioPolicyManager::addOutput(audio_io_handle_t output,
6344 const sp<SwAudioOutputDescriptor>& outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07006345{
Eric Laurent1c333e22014-05-20 10:48:17 -07006346 mOutputs.add(output, outputDesc);
jiabin9a3361e2019-10-01 09:38:30 -07006347 applyStreamVolumes(outputDesc, DeviceTypeSet(), 0 /* delayMs */, true /* force */);
Andy Hung2ddee192015-12-18 17:34:44 -08006348 updateMono(output); // update mono status when adding to output list
Eric Laurent36829f92017-04-07 19:04:42 -07006349 selectOutputForMusicEffects();
Eric Laurent6a94d692014-05-20 11:18:06 -07006350 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07006351}
6352
François Gaffie53615e22015-03-19 09:24:12 +01006353void AudioPolicyManager::removeOutput(audio_io_handle_t output)
6354{
Francois Gaffiebce7cd42020-10-14 16:13:20 +02006355 if (mPrimaryOutput != 0 && mPrimaryOutput == mOutputs.valueFor(output)) {
6356 ALOGV("%s: removing primary output", __func__);
6357 mPrimaryOutput = nullptr;
6358 }
François Gaffie53615e22015-03-19 09:24:12 +01006359 mOutputs.removeItem(output);
Eric Laurent36829f92017-04-07 19:04:42 -07006360 selectOutputForMusicEffects();
François Gaffie53615e22015-03-19 09:24:12 +01006361}
6362
Eric Laurent98e38192018-02-15 18:31:53 -08006363void AudioPolicyManager::addInput(audio_io_handle_t input,
6364 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07006365{
Eric Laurent1c333e22014-05-20 10:48:17 -07006366 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07006367 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07006368}
Eric Laurente552edb2014-03-10 17:42:56 -07006369
François Gaffie11d30102018-11-02 16:09:09 +01006370status_t AudioPolicyManager::checkOutputsForDevice(const sp<DeviceDescriptor>& device,
François Gaffie53615e22015-03-19 09:24:12 +01006371 audio_policy_dev_state_t state,
François Gaffie11d30102018-11-02 16:09:09 +01006372 SortedVector<audio_io_handle_t>& outputs)
Eric Laurente552edb2014-03-10 17:42:56 -07006373{
François Gaffie11d30102018-11-02 16:09:09 +01006374 audio_devices_t deviceType = device->type();
jiabince9f20e2019-09-12 16:29:15 -07006375 const String8 &address = String8(device->address().c_str());
Eric Laurentc75307b2015-03-17 15:29:32 -07006376 sp<SwAudioOutputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07006377
François Gaffie11d30102018-11-02 16:09:09 +01006378 if (audio_device_is_digital(deviceType)) {
Eric Laurentcc750d32015-06-25 11:48:20 -07006379 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01006380 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07006381 }
Eric Laurente552edb2014-03-10 17:42:56 -07006382
Eric Laurent3b73df72014-03-11 09:06:29 -07006383 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
jiabinb4fed192020-09-22 14:45:40 -07006384 // first call getAudioPort to get the supported attributes from the HAL
6385 struct audio_port_v7 port = {};
6386 device->toAudioPort(&port);
6387 status_t status = mpClientInterface->getAudioPort(&port);
6388 if (status == NO_ERROR) {
6389 device->importAudioPort(port);
6390 }
6391
6392 // then list already open outputs that can be routed to this device
Eric Laurente552edb2014-03-10 17:42:56 -07006393 for (size_t i = 0; i < mOutputs.size(); i++) {
6394 desc = mOutputs.valueAt(i);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006395 if (!desc->isDuplicated() && desc->supportsDevice(device)
jiabin9a3361e2019-10-01 09:38:30 -07006396 && desc->devicesSupportEncodedFormats({deviceType})) {
François Gaffie11d30102018-11-02 16:09:09 +01006397 ALOGV("checkOutputsForDevice(): adding opened output %d on device %s",
6398 mOutputs.keyAt(i), device->toString().c_str());
6399 outputs.add(mOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07006400 }
6401 }
6402 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07006403 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006404 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006405 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
6406 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
François Gaffie11d30102018-11-02 16:09:09 +01006407 if (profile->supportsDevice(device)) {
6408 profiles.add(profile);
6409 ALOGV("checkOutputsForDevice(): adding profile %zu from module %s",
6410 j, hwModule->getName());
Eric Laurente552edb2014-03-10 17:42:56 -07006411 }
6412 }
6413 }
6414
Eric Laurent7b279bb2015-12-14 10:18:23 -08006415 ALOGV(" found %zu profiles, %zu outputs", profiles.size(), outputs.size());
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006416
Eric Laurente552edb2014-03-10 17:42:56 -07006417 if (profiles.isEmpty() && outputs.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006418 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07006419 return BAD_VALUE;
6420 }
6421
6422 // open outputs for matching profiles if needed. Direct outputs are also opened to
6423 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
6424 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07006425 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07006426
6427 // nothing to do if one output is already opened for this profile
6428 size_t j;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006429 for (j = 0; j < outputs.size(); j++) {
6430 desc = mOutputs.valueFor(outputs.itemAt(j));
Eric Laurente552edb2014-03-10 17:42:56 -07006431 if (!desc->isDuplicated() && desc->mProfile == profile) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07006432 // matching profile: save the sample rates, format and channel masks supported
6433 // by the profile in our device descriptor
François Gaffie11d30102018-11-02 16:09:09 +01006434 if (audio_device_is_digital(deviceType)) {
jiabin4ef93452019-09-10 14:29:54 -07006435 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006436 }
Eric Laurente552edb2014-03-10 17:42:56 -07006437 break;
6438 }
6439 }
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006440 if (j != outputs.size()) {
Eric Laurente552edb2014-03-10 17:42:56 -07006441 continue;
6442 }
6443
Eric Laurent3974e3b2017-12-07 17:58:43 -08006444 if (!profile->canOpenNewIo()) {
6445 ALOGW("Max Output number %u already opened for this profile %s",
6446 profile->maxOpenCount, profile->getTagName().c_str());
6447 continue;
6448 }
6449
Eric Laurent83efe1c2017-07-09 16:51:08 -07006450 ALOGV("opening output for device %08x with params %s profile %p name %s",
jiabin5740f082019-08-19 15:08:30 -07006451 deviceType, address.string(), profile.get(), profile->getName().c_str());
jiabinbce0c1d2020-10-05 11:20:18 -07006452 desc = openOutputWithProfileAndDevice(profile, DeviceVector(device));
6453 audio_io_handle_t output = desc == nullptr ? AUDIO_IO_HANDLE_NONE : desc->mIoHandle;
Eric Laurentcf2c0212014-07-25 16:20:43 -07006454 if (output == AUDIO_IO_HANDLE_NONE) {
François Gaffie11d30102018-11-02 16:09:09 +01006455 ALOGW("checkOutputsForDevice() could not open output for device %x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07006456 profiles.removeAt(profile_index);
6457 profile_index--;
6458 } else {
6459 outputs.add(output);
Paul McLean9080a4c2015-06-18 08:24:02 -07006460 // Load digital format info only for digital devices
François Gaffie11d30102018-11-02 16:09:09 +01006461 if (audio_device_is_digital(deviceType)) {
jiabinbce0c1d2020-10-05 11:20:18 -07006462 // TODO: when getAudioPort is ready, it may not be needed to import the audio
6463 // port but just pick audio profile
jiabin4ef93452019-09-10 14:29:54 -07006464 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006465 }
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07006466
François Gaffie11d30102018-11-02 16:09:09 +01006467 if (device_distinguishes_on_address(deviceType)) {
6468 ALOGV("checkOutputsForDevice(): setOutputDevices %s",
6469 device->toString().c_str());
6470 setOutputDevices(desc, DeviceVector(device), true/*force*/, 0/*delay*/,
6471 NULL/*patch handle*/);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006472 }
Eric Laurente552edb2014-03-10 17:42:56 -07006473 ALOGV("checkOutputsForDevice(): adding output %d", output);
6474 }
6475 }
6476
6477 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006478 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07006479 return BAD_VALUE;
6480 }
Eric Laurentd4692962014-05-05 18:13:44 -07006481 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07006482 // check if one opened output is not needed any more after disconnecting one device
6483 for (size_t i = 0; i < mOutputs.size(); i++) {
6484 desc = mOutputs.valueAt(i);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006485 if (!desc->isDuplicated()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08006486 // exact match on device
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006487 if (device_distinguishes_on_address(deviceType) && desc->supportsDevice(device)
Francois Gaffiec7d4c222021-12-02 11:12:52 +01006488 && desc->containsSingleDeviceSupportingEncodedFormats(device)) {
François Gaffie11d30102018-11-02 16:09:09 +01006489 outputs.add(mOutputs.keyAt(i));
Francois Gaffie716e1432019-01-14 16:58:59 +01006490 } else if (!mAvailableOutputDevices.containsAtLeastOne(desc->supportedDevices())) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006491 ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
6492 mOutputs.keyAt(i));
6493 outputs.add(mOutputs.keyAt(i));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006494 }
Eric Laurente552edb2014-03-10 17:42:56 -07006495 }
6496 }
Eric Laurentd4692962014-05-05 18:13:44 -07006497 // Clear any profiles associated with the disconnected device.
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006498 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006499 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
6500 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
jiabinbce0c1d2020-10-05 11:20:18 -07006501 if (!profile->supportsDevice(device)) {
6502 continue;
6503 }
6504 ALOGV("checkOutputsForDevice(): "
6505 "clearing direct output profile %zu on module %s",
6506 j, hwModule->getName());
6507 profile->clearAudioProfiles();
6508 if (!profile->hasDynamicAudioProfile()) {
6509 continue;
6510 }
6511 // When a device is disconnected, if there is an IOProfile that contains dynamic
6512 // profiles and supports the disconnected device, call getAudioPort to repopulate
6513 // the capabilities of the devices that is supported by the IOProfile.
6514 for (const auto& supportedDevice : profile->getSupportedDevices()) {
6515 if (supportedDevice == device ||
6516 !mAvailableOutputDevices.contains(supportedDevice)) {
6517 continue;
6518 }
6519 struct audio_port_v7 port;
6520 supportedDevice->toAudioPort(&port);
6521 status_t status = mpClientInterface->getAudioPort(&port);
6522 if (status == NO_ERROR) {
6523 supportedDevice->importAudioPort(port);
6524 }
Eric Laurente552edb2014-03-10 17:42:56 -07006525 }
6526 }
6527 }
6528 }
6529 return NO_ERROR;
6530}
6531
François Gaffie11d30102018-11-02 16:09:09 +01006532status_t AudioPolicyManager::checkInputsForDevice(const sp<DeviceDescriptor>& device,
Eric Laurent0dd51852019-04-19 18:18:58 -07006533 audio_policy_dev_state_t state)
Eric Laurentd4692962014-05-05 18:13:44 -07006534{
Eric Laurent1f2f2232014-06-02 12:01:23 -07006535 sp<AudioInputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07006536
François Gaffie11d30102018-11-02 16:09:09 +01006537 if (audio_device_is_digital(device->type())) {
Eric Laurentcc750d32015-06-25 11:48:20 -07006538 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01006539 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07006540 }
6541
Eric Laurentd4692962014-05-05 18:13:44 -07006542 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
jiabinbf5f4262023-04-12 21:48:34 +00006543 // first call getAudioPort to get the supported attributes from the HAL
6544 struct audio_port_v7 port = {};
6545 device->toAudioPort(&port);
6546 status_t status = mpClientInterface->getAudioPort(&port);
6547 if (status == NO_ERROR) {
6548 device->importAudioPort(port);
6549 }
6550
Eric Laurent0dd51852019-04-19 18:18:58 -07006551 // look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07006552 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006553 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07006554 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006555 profile_index < hwModule->getInputProfiles().size();
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006556 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006557 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Eric Laurent275e8e92014-11-30 15:14:47 -08006558
François Gaffie11d30102018-11-02 16:09:09 +01006559 if (profile->supportsDevice(device)) {
6560 profiles.add(profile);
6561 ALOGV("checkInputsForDevice(): adding profile %zu from module %s",
6562 profile_index, hwModule->getName());
Eric Laurentd4692962014-05-05 18:13:44 -07006563 }
6564 }
6565 }
6566
Eric Laurent0dd51852019-04-19 18:18:58 -07006567 if (profiles.isEmpty()) {
6568 ALOGW("%s: No input profile available for device %s",
6569 __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07006570 return BAD_VALUE;
6571 }
6572
6573 // open inputs for matching profiles if needed. Direct inputs are also opened to
6574 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
6575 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
6576
Eric Laurent1c333e22014-05-20 10:48:17 -07006577 sp<IOProfile> profile = profiles[profile_index];
Eric Laurent3974e3b2017-12-07 17:58:43 -08006578
Eric Laurentd4692962014-05-05 18:13:44 -07006579 // nothing to do if one input is already opened for this profile
6580 size_t input_index;
6581 for (input_index = 0; input_index < mInputs.size(); input_index++) {
6582 desc = mInputs.valueAt(input_index);
6583 if (desc->mProfile == profile) {
François Gaffie11d30102018-11-02 16:09:09 +01006584 if (audio_device_is_digital(device->type())) {
jiabin4ef93452019-09-10 14:29:54 -07006585 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006586 }
Eric Laurentd4692962014-05-05 18:13:44 -07006587 break;
6588 }
6589 }
6590 if (input_index != mInputs.size()) {
6591 continue;
6592 }
6593
Eric Laurent3974e3b2017-12-07 17:58:43 -08006594 if (!profile->canOpenNewIo()) {
6595 ALOGW("Max Input number %u already opened for this profile %s",
6596 profile->maxOpenCount, profile->getTagName().c_str());
6597 continue;
6598 }
6599
Eric Laurentfe231122017-11-17 17:48:06 -08006600 desc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentcf2c0212014-07-25 16:20:43 -07006601 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
jiabinbf5f4262023-04-12 21:48:34 +00006602 status = desc->open(nullptr, device, AUDIO_SOURCE_MIC, AUDIO_INPUT_FLAG_NONE, &input);
Eric Laurentd4692962014-05-05 18:13:44 -07006603
Eric Laurentcf2c0212014-07-25 16:20:43 -07006604 if (status == NO_ERROR) {
jiabince9f20e2019-09-12 16:29:15 -07006605 const String8& address = String8(device->address().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07006606 if (!address.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006607 char *param = audio_device_address_to_parameter(device->type(), address);
Eric Laurentcf2c0212014-07-25 16:20:43 -07006608 mpClientInterface->setParameters(input, String8(param));
6609 free(param);
Eric Laurentd4692962014-05-05 18:13:44 -07006610 }
François Gaffie11d30102018-11-02 16:09:09 +01006611 updateAudioProfiles(device, input, profile->getAudioProfiles());
François Gaffie112b0af2015-11-19 16:13:25 +01006612 if (!profile->hasValidAudioProfile()) {
Eric Laurentd4692962014-05-05 18:13:44 -07006613 ALOGW("checkInputsForDevice() direct input missing param");
Eric Laurentfe231122017-11-17 17:48:06 -08006614 desc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07006615 input = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07006616 }
6617
Eric Laurent0dd51852019-04-19 18:18:58 -07006618 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07006619 addInput(input, desc);
6620 }
6621 } // endif input != 0
6622
Eric Laurentcf2c0212014-07-25 16:20:43 -07006623 if (input == AUDIO_IO_HANDLE_NONE) {
Pattydd807582021-11-04 21:01:03 +08006624 ALOGW("%s could not open input for device %s", __func__,
François Gaffie11d30102018-11-02 16:09:09 +01006625 device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07006626 profiles.removeAt(profile_index);
6627 profile_index--;
6628 } else {
François Gaffie11d30102018-11-02 16:09:09 +01006629 if (audio_device_is_digital(device->type())) {
jiabin4ef93452019-09-10 14:29:54 -07006630 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006631 }
Eric Laurentd4692962014-05-05 18:13:44 -07006632 ALOGV("checkInputsForDevice(): adding input %d", input);
6633 }
6634 } // end scan profiles
6635
6636 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006637 ALOGW("%s: No input available for device %s", __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07006638 return BAD_VALUE;
6639 }
6640 } else {
6641 // Disconnect
Eric Laurentd4692962014-05-05 18:13:44 -07006642 // Clear any profiles associated with the disconnected device.
Mikhail Naganovd4120142017-12-06 15:49:22 -08006643 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07006644 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006645 profile_index < hwModule->getInputProfiles().size();
Eric Laurentd4692962014-05-05 18:13:44 -07006646 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006647 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Francois Gaffie716e1432019-01-14 16:58:59 +01006648 if (profile->supportsDevice(device)) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08006649 ALOGV("checkInputsForDevice(): clearing direct input profile %zu on module %s",
6650 profile_index, hwModule->getName());
François Gaffie112b0af2015-11-19 16:13:25 +01006651 profile->clearAudioProfiles();
Eric Laurentd4692962014-05-05 18:13:44 -07006652 }
6653 }
6654 }
6655 } // end disconnect
6656
6657 return NO_ERROR;
6658}
6659
6660
Eric Laurente0720872014-03-11 09:30:41 -07006661void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07006662{
6663 ALOGV("closeOutput(%d)", output);
6664
François Gaffie1c878552018-11-22 16:53:21 +01006665 sp<SwAudioOutputDescriptor> closingOutput = mOutputs.valueFor(output);
6666 if (closingOutput == NULL) {
Eric Laurente552edb2014-03-10 17:42:56 -07006667 ALOGW("closeOutput() unknown output %d", output);
6668 return;
6669 }
Mikhail Naganov32ebca32019-03-22 15:42:52 -07006670 const bool closingOutputWasActive = closingOutput->isActive();
François Gaffie1c878552018-11-22 16:53:21 +01006671 mPolicyMixes.closeOutput(closingOutput);
Eric Laurent275e8e92014-11-30 15:14:47 -08006672
Eric Laurente552edb2014-03-10 17:42:56 -07006673 // look for duplicated outputs connected to the output being removed.
6674 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie1c878552018-11-22 16:53:21 +01006675 sp<SwAudioOutputDescriptor> dupOutput = mOutputs.valueAt(i);
6676 if (dupOutput->isDuplicated() &&
6677 (dupOutput->mOutput1 == closingOutput || dupOutput->mOutput2 == closingOutput)) {
6678 sp<SwAudioOutputDescriptor> remainingOutput =
6679 dupOutput->mOutput1 == closingOutput ? dupOutput->mOutput2 : dupOutput->mOutput1;
Eric Laurente552edb2014-03-10 17:42:56 -07006680 // As all active tracks on duplicated output will be deleted,
6681 // and as they were also referenced on the other output, the reference
6682 // count for their stream type must be adjusted accordingly on
6683 // the other output.
François Gaffie1c878552018-11-22 16:53:21 +01006684 const bool wasActive = remainingOutput->isActive();
6685 // Note: no-op on the closing output where all clients has already been set inactive
6686 dupOutput->setAllClientsInactive();
Eric Laurent733ce942017-12-07 12:18:25 -08006687 // stop() will be a no op if the output is still active but is needed in case all
6688 // active streams refcounts where cleared above
6689 if (wasActive) {
François Gaffie1c878552018-11-22 16:53:21 +01006690 remainingOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08006691 }
Eric Laurente552edb2014-03-10 17:42:56 -07006692 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
6693 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
6694
6695 mpClientInterface->closeOutput(duplicatedOutput);
François Gaffie53615e22015-03-19 09:24:12 +01006696 removeOutput(duplicatedOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07006697 }
6698 }
6699
Eric Laurent05b90f82014-08-27 15:32:29 -07006700 nextAudioPortGeneration();
6701
François Gaffie1c878552018-11-22 16:53:21 +01006702 ssize_t index = mAudioPatches.indexOfKey(closingOutput->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07006703 if (index >= 0) {
6704 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006705 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
6706 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07006707 mAudioPatches.removeItemsAt(index);
6708 mpClientInterface->onAudioPatchListUpdate();
6709 }
6710
Mikhail Naganov32ebca32019-03-22 15:42:52 -07006711 if (closingOutputWasActive) {
6712 closingOutput->stop();
6713 }
François Gaffie1c878552018-11-22 16:53:21 +01006714 closingOutput->close();
Eric Laurente552edb2014-03-10 17:42:56 -07006715
François Gaffie53615e22015-03-19 09:24:12 +01006716 removeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07006717 mPreviousOutputs = mOutputs;
Eric Laurentb4f42a92022-01-17 17:37:31 +01006718 if (closingOutput == mSpatializerOutput) {
6719 mSpatializerOutput.clear();
6720 }
Dean Wheatley3023b382018-08-09 07:42:40 +10006721
6722 // MSD patches may have been released to support a non-MSD direct output. Reset MSD patch if
6723 // no direct outputs are open.
François Gaffie11d30102018-11-02 16:09:09 +01006724 if (!getMsdAudioOutDevices().isEmpty()) {
Dean Wheatley3023b382018-08-09 07:42:40 +10006725 bool directOutputOpen = false;
6726 for (size_t i = 0; i < mOutputs.size(); i++) {
6727 if (mOutputs[i]->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
6728 directOutputOpen = true;
6729 break;
6730 }
6731 }
6732 if (!directOutputOpen) {
Michael Chan6fb34492020-12-08 15:44:49 +11006733 ALOGV("no direct outputs open, reset MSD patches");
6734 // TODO: The MSD patches to be established here may differ to current MSD patches due to
6735 // how output devices for patching are resolved. Avoid by caching and reusing the
6736 // arguments to mEngine->getOutputDevicesForAttributes() when resolving which output
6737 // devices to patch to. This may be complicated by the fact that devices may become
6738 // unavailable.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11006739 setMsdOutputPatches();
Dean Wheatley3023b382018-08-09 07:42:40 +10006740 }
6741 }
Eric Laurent05b90f82014-08-27 15:32:29 -07006742}
6743
6744void AudioPolicyManager::closeInput(audio_io_handle_t input)
6745{
6746 ALOGV("closeInput(%d)", input);
6747
6748 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
6749 if (inputDesc == NULL) {
6750 ALOGW("closeInput() unknown input %d", input);
6751 return;
6752 }
6753
Eric Laurent6a94d692014-05-20 11:18:06 -07006754 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07006755
François Gaffie11d30102018-11-02 16:09:09 +01006756 sp<DeviceDescriptor> device = inputDesc->getDevice();
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08006757 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07006758 if (index >= 0) {
6759 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006760 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
6761 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07006762 mAudioPatches.removeItemsAt(index);
6763 mpClientInterface->onAudioPatchListUpdate();
6764 }
6765
Eric Laurentfe231122017-11-17 17:48:06 -08006766 inputDesc->close();
Eric Laurent05b90f82014-08-27 15:32:29 -07006767 mInputs.removeItem(input);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07006768
François Gaffie11d30102018-11-02 16:09:09 +01006769 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
6770 if (primaryInputDevices.contains(device) &&
Haynes Mathew George1d539d92018-03-16 11:40:49 -07006771 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07006772 mpClientInterface->setSoundTriggerCaptureState(false);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07006773 }
Eric Laurente552edb2014-03-10 17:42:56 -07006774}
6775
François Gaffie11d30102018-11-02 16:09:09 +01006776SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevices(
6777 const DeviceVector &devices,
6778 const SwAudioOutputCollection& openOutputs)
Eric Laurente552edb2014-03-10 17:42:56 -07006779{
6780 SortedVector<audio_io_handle_t> outputs;
6781
François Gaffie11d30102018-11-02 16:09:09 +01006782 ALOGVV("%s() devices %s", __func__, devices.toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07006783 for (size_t i = 0; i < openOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01006784 ALOGVV("output %zu isDuplicated=%d device=%s",
Eric Laurent8c7e6da2015-04-21 17:37:00 -07006785 i, openOutputs.valueAt(i)->isDuplicated(),
François Gaffie11d30102018-11-02 16:09:09 +01006786 openOutputs.valueAt(i)->supportedDevices().toString().c_str());
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006787 if (openOutputs.valueAt(i)->supportsAllDevices(devices)
jiabin9a3361e2019-10-01 09:38:30 -07006788 && openOutputs.valueAt(i)->devicesSupportEncodedFormats(devices.types())) {
François Gaffie11d30102018-11-02 16:09:09 +01006789 ALOGVV("%s() found output %d", __func__, openOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07006790 outputs.add(openOutputs.keyAt(i));
6791 }
6792 }
6793 return outputs;
6794}
6795
Mikhail Naganov37977152018-07-11 15:54:44 -07006796void AudioPolicyManager::checkForDeviceAndOutputChanges(std::function<bool()> onOutputsChecked)
6797{
6798 // checkA2dpSuspend must run before checkOutputForAllStrategies so that A2DP
6799 // output is suspended before any tracks are moved to it
6800 checkA2dpSuspend();
6801 checkOutputForAllStrategies();
Kevin Rocard153f92d2018-12-18 18:33:28 -08006802 checkSecondaryOutputs();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11006803 if (onOutputsChecked != nullptr && onOutputsChecked()) checkA2dpSuspend();
Mikhail Naganov37977152018-07-11 15:54:44 -07006804 updateDevicesAndOutputs();
Mikhail Naganov7bd9b8d2018-11-15 02:09:03 +00006805 if (mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD) != 0) {
Michael Chan6fb34492020-12-08 15:44:49 +11006806 // TODO: The MSD patches to be established here may differ to current MSD patches due to how
6807 // output devices for patching are resolved. Nevertheless, AudioTracks affected by device
6808 // configuration changes will ultimately be rerouted correctly. We can still avoid
6809 // unnecessary rerouting by caching and reusing the arguments to
6810 // mEngine->getOutputDevicesForAttributes() when resolving which output devices to patch to.
6811 // This may be complicated by the fact that devices may become unavailable.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11006812 setMsdOutputPatches();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11006813 }
Jean-Michel Trivi9a6b9ad2020-10-22 16:46:43 -07006814 // an event that changed routing likely occurred, inform upper layers
6815 mpClientInterface->onRoutingUpdated();
Mikhail Naganov37977152018-07-11 15:54:44 -07006816}
6817
François Gaffiec005e562018-11-06 15:04:49 +01006818bool AudioPolicyManager::followsSameRouting(const audio_attributes_t &lAttr,
6819 const audio_attributes_t &rAttr) const
Eric Laurente552edb2014-03-10 17:42:56 -07006820{
François Gaffiec005e562018-11-06 15:04:49 +01006821 return mEngine->getProductStrategyForAttributes(lAttr) ==
6822 mEngine->getProductStrategyForAttributes(rAttr);
6823}
6824
Francois Gaffieff1eb522020-05-06 18:37:04 +02006825void AudioPolicyManager::checkAudioSourceForAttributes(const audio_attributes_t &attr)
6826{
6827 for (size_t i = 0; i < mAudioSources.size(); i++) {
6828 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
6829 if (sourceDesc != nullptr && followsSameRouting(attr, sourceDesc->attributes())
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02006830 && sourceDesc->getPatchHandle() == AUDIO_PATCH_HANDLE_NONE
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02006831 && !isCallRxAudioSource(sourceDesc) && !sourceDesc->isInternal()) {
Francois Gaffieff1eb522020-05-06 18:37:04 +02006832 connectAudioSource(sourceDesc);
6833 }
6834 }
6835}
6836
6837void AudioPolicyManager::clearAudioSourcesForOutput(audio_io_handle_t output)
6838{
6839 for (size_t i = 0; i < mAudioSources.size(); i++) {
6840 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
6841 if (sourceDesc != nullptr && sourceDesc->swOutput().promote() != nullptr
6842 && sourceDesc->swOutput().promote()->mIoHandle == output) {
6843 disconnectAudioSource(sourceDesc);
6844 }
6845 }
6846}
6847
François Gaffiec005e562018-11-06 15:04:49 +01006848void AudioPolicyManager::checkOutputForAttributes(const audio_attributes_t &attr)
6849{
6850 auto psId = mEngine->getProductStrategyForAttributes(attr);
6851
6852 DeviceVector oldDevices = mEngine->getOutputDevicesForAttributes(attr, 0, true /*fromCache*/);
6853 DeviceVector newDevices = mEngine->getOutputDevicesForAttributes(attr, 0, false /*fromCache*/);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07006854
François Gaffie11d30102018-11-02 16:09:09 +01006855 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevices(oldDevices, mPreviousOutputs);
6856 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevices(newDevices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07006857
Eric Laurentc209fe42020-06-05 18:11:23 -07006858 uint32_t maxLatency = 0;
Oscar Azucena873d10f2023-01-12 18:34:42 -08006859 bool unneededUsePrimaryOutputFromPolicyMixes = false;
Eric Laurent56ed8842022-11-15 16:04:41 +01006860 std::vector<sp<SwAudioOutputDescriptor>> invalidatedOutputs;
Eric Laurentc209fe42020-06-05 18:11:23 -07006861 // take into account dynamic audio policies related changes: if a client is now associated
6862 // to a different policy mix than at creation time, invalidate corresponding stream
Eric Laurent56ed8842022-11-15 16:04:41 +01006863 for (size_t i = 0; i < mPreviousOutputs.size(); i++) {
Eric Laurentc209fe42020-06-05 18:11:23 -07006864 const sp<SwAudioOutputDescriptor>& desc = mPreviousOutputs.valueAt(i);
6865 if (desc->isDuplicated()) {
6866 continue;
Jean-Michel Trivife472e22014-12-16 14:23:13 -08006867 }
Eric Laurentc209fe42020-06-05 18:11:23 -07006868 for (const sp<TrackClientDescriptor>& client : desc->getClientIterable()) {
6869 if (mEngine->getProductStrategyForAttributes(client->attributes()) != psId) {
6870 continue;
6871 }
6872 sp<AudioPolicyMix> primaryMix;
Dean Wheatleyd082f472022-02-04 11:10:48 +11006873 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->config(),
Oscar Azucena873d10f2023-01-12 18:34:42 -08006874 client->uid(), client->session(), client->flags(), mAvailableOutputDevices,
6875 nullptr /* requestedDevice */, primaryMix, nullptr /* secondaryMixes */,
6876 unneededUsePrimaryOutputFromPolicyMixes);
Eric Laurentc209fe42020-06-05 18:11:23 -07006877 if (status != OK) {
6878 continue;
6879 }
yucliuf4de36d2020-09-14 14:57:56 -07006880 if (client->getPrimaryMix() != primaryMix || client->hasLostPrimaryMix()) {
Eric Laurent56ed8842022-11-15 16:04:41 +01006881 if (desc->isStrategyActive(psId) && maxLatency < desc->latency()) {
Eric Laurentc209fe42020-06-05 18:11:23 -07006882 maxLatency = desc->latency();
6883 }
Eric Laurent56ed8842022-11-15 16:04:41 +01006884 invalidatedOutputs.push_back(desc);
Eric Laurentc209fe42020-06-05 18:11:23 -07006885 }
Jean-Michel Trivife472e22014-12-16 14:23:13 -08006886 }
6887 }
6888
Eric Laurent56ed8842022-11-15 16:04:41 +01006889 if (srcOutputs != dstOutputs || !invalidatedOutputs.empty()) {
Eric Laurentac3a6902018-05-11 16:39:10 -07006890 // get maximum latency of all source outputs to determine the minimum mute time guaranteeing
6891 // audio from invalidated tracks will be rendered when unmuting
Eric Laurentac3a6902018-05-11 16:39:10 -07006892 for (audio_io_handle_t srcOut : srcOutputs) {
6893 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
Eric Laurentaa02db82019-09-05 17:31:49 -07006894 if (desc == nullptr) continue;
6895
6896 if (desc->isStrategyActive(psId) && maxLatency < desc->latency()) {
Eric Laurentac3a6902018-05-11 16:39:10 -07006897 maxLatency = desc->latency();
6898 }
Eric Laurentaa02db82019-09-05 17:31:49 -07006899
Eric Laurent56ed8842022-11-15 16:04:41 +01006900 bool invalidate = false;
Eric Laurentaa02db82019-09-05 17:31:49 -07006901 for (auto client : desc->clientsList(false /*activeOnly*/)) {
Eric Laurent78aade82019-09-13 18:55:08 -07006902 if (desc->isDuplicated() || !desc->mProfile->isDirectOutput()) {
Eric Laurentaa02db82019-09-05 17:31:49 -07006903 // a client on a non direct outputs has necessarily a linear PCM format
6904 // so we can call selectOutput() safely
6905 const audio_io_handle_t newOutput = selectOutput(dstOutputs,
6906 client->flags(),
6907 client->config().format,
6908 client->config().channel_mask,
jiabinebb6af42020-06-09 17:31:17 -07006909 client->config().sample_rate,
6910 client->session());
Eric Laurentaa02db82019-09-05 17:31:49 -07006911 if (newOutput != srcOut) {
6912 invalidate = true;
6913 break;
6914 }
6915 } else {
6916 sp<IOProfile> profile = getProfileForOutput(newDevices,
6917 client->config().sample_rate,
6918 client->config().format,
6919 client->config().channel_mask,
6920 client->flags(),
6921 true /* directOnly */);
6922 if (profile != desc->mProfile) {
6923 invalidate = true;
6924 break;
6925 }
6926 }
6927 }
Eric Laurent56ed8842022-11-15 16:04:41 +01006928 // mute strategy while moving tracks from one output to another
6929 if (invalidate) {
6930 invalidatedOutputs.push_back(desc);
6931 if (desc->isStrategyActive(psId)) {
6932 setStrategyMute(psId, true, desc);
6933 setStrategyMute(psId, false, desc, maxLatency * LATENCY_MUTE_FACTOR,
6934 newDevices.types());
6935 }
Eric Laurente552edb2014-03-10 17:42:56 -07006936 }
François Gaffiec005e562018-11-06 15:04:49 +01006937 sp<SourceClientDescriptor> source = getSourceForAttributesOnOutput(srcOut, attr);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02006938 if (source != nullptr && !isCallRxAudioSource(source) && !source->isInternal()) {
Eric Laurentd60560a2015-04-10 11:31:20 -07006939 connectAudioSource(source);
6940 }
Eric Laurente552edb2014-03-10 17:42:56 -07006941 }
6942
Eric Laurent56ed8842022-11-15 16:04:41 +01006943 ALOGV_IF(!(srcOutputs.isEmpty() || dstOutputs.isEmpty()),
6944 "%s: strategy %d, moving from output %s to output %s", __func__, psId,
6945 std::to_string(srcOutputs[0]).c_str(),
6946 std::to_string(dstOutputs[0]).c_str());
6947
François Gaffiec005e562018-11-06 15:04:49 +01006948 // Move effects associated to this stream from previous output to new output
6949 if (followsSameRouting(attr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07006950 selectOutputForMusicEffects();
Eric Laurente552edb2014-03-10 17:42:56 -07006951 }
François Gaffiec005e562018-11-06 15:04:49 +01006952 // Move tracks associated to this stream (and linked) from previous output to new output
Eric Laurent56ed8842022-11-15 16:04:41 +01006953 if (!invalidatedOutputs.empty()) {
jiabinc44b3462022-12-08 12:52:31 -08006954 invalidateStreams(mEngine->getStreamTypesForProductStrategy(psId));
Eric Laurent56ed8842022-11-15 16:04:41 +01006955 for (sp<SwAudioOutputDescriptor> desc : invalidatedOutputs) {
jiabin49256852022-03-09 11:21:35 -08006956 desc->setTracksInvalidatedStatusByStrategy(psId);
6957 }
Eric Laurente552edb2014-03-10 17:42:56 -07006958 }
6959 }
6960}
6961
Eric Laurente0720872014-03-11 09:30:41 -07006962void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07006963{
François Gaffiec005e562018-11-06 15:04:49 +01006964 for (const auto &strategy : mEngine->getOrderedProductStrategies()) {
6965 auto attributes = mEngine->getAllAttributesForProductStrategy(strategy).front();
6966 checkOutputForAttributes(attributes);
Francois Gaffieff1eb522020-05-06 18:37:04 +02006967 checkAudioSourceForAttributes(attributes);
François Gaffiec005e562018-11-06 15:04:49 +01006968 }
Eric Laurente552edb2014-03-10 17:42:56 -07006969}
6970
Kevin Rocard153f92d2018-12-18 18:33:28 -08006971void AudioPolicyManager::checkSecondaryOutputs() {
jiabinc44b3462022-12-08 12:52:31 -08006972 PortHandleVector clientsToInvalidate;
jiabin10a03f12021-05-07 23:46:28 +00006973 TrackSecondaryOutputsMap trackSecondaryOutputs;
Oscar Azucena873d10f2023-01-12 18:34:42 -08006974 bool unneededUsePrimaryOutputFromPolicyMixes = false;
Kevin Rocard153f92d2018-12-18 18:33:28 -08006975 for (size_t i = 0; i < mOutputs.size(); i++) {
6976 const sp<SwAudioOutputDescriptor>& outputDescriptor = mOutputs[i];
6977 for (const sp<TrackClientDescriptor>& client : outputDescriptor->getClientIterable()) {
Eric Laurentc529cf62020-04-17 18:19:10 -07006978 sp<AudioPolicyMix> primaryMix;
6979 std::vector<sp<AudioPolicyMix>> secondaryMixes;
Dean Wheatleyd082f472022-02-04 11:10:48 +11006980 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->config(),
Oscar Azucena873d10f2023-01-12 18:34:42 -08006981 client->uid(), client->session(), client->flags(), mAvailableOutputDevices,
6982 nullptr /* requestedDevice */, primaryMix, &secondaryMixes,
6983 unneededUsePrimaryOutputFromPolicyMixes);
Eric Laurentc529cf62020-04-17 18:19:10 -07006984 std::vector<sp<SwAudioOutputDescriptor>> secondaryDescs;
6985 for (auto &secondaryMix : secondaryMixes) {
6986 sp<SwAudioOutputDescriptor> outputDesc = secondaryMix->getOutput();
6987 if (outputDesc != nullptr &&
6988 outputDesc->mIoHandle != AUDIO_IO_HANDLE_NONE) {
6989 secondaryDescs.push_back(outputDesc);
6990 }
6991 }
6992
jiabinc44b3462022-12-08 12:52:31 -08006993 if (status != OK &&
6994 (client->flags() & AUDIO_OUTPUT_FLAG_MMAP_NOIRQ) == AUDIO_OUTPUT_FLAG_NONE) {
6995 // When it failed to query secondary output, only invalidate the client that is not
6996 // MMAP. The reason is that MMAP stream will not support secondary output.
6997 clientsToInvalidate.push_back(client->portId());
jiabin10a03f12021-05-07 23:46:28 +00006998 } else if (!std::equal(
6999 client->getSecondaryOutputs().begin(),
7000 client->getSecondaryOutputs().end(),
7001 secondaryDescs.begin(), secondaryDescs.end())) {
jiabina5281062021-11-23 00:10:23 +00007002 if (!audio_is_linear_pcm(client->config().format)) {
7003 // If the format is not PCM, the tracks should be invalidated to get correct
7004 // behavior when the secondary output is changed.
jiabinc44b3462022-12-08 12:52:31 -08007005 clientsToInvalidate.push_back(client->portId());
jiabina5281062021-11-23 00:10:23 +00007006 } else {
7007 std::vector<wp<SwAudioOutputDescriptor>> weakSecondaryDescs;
7008 std::vector<audio_io_handle_t> secondaryOutputIds;
7009 for (const auto &secondaryDesc: secondaryDescs) {
7010 secondaryOutputIds.push_back(secondaryDesc->mIoHandle);
7011 weakSecondaryDescs.push_back(secondaryDesc);
7012 }
7013 trackSecondaryOutputs.emplace(client->portId(), secondaryOutputIds);
7014 client->setSecondaryOutputs(std::move(weakSecondaryDescs));
jiabin10a03f12021-05-07 23:46:28 +00007015 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08007016 }
7017 }
7018 }
jiabin10a03f12021-05-07 23:46:28 +00007019 if (!trackSecondaryOutputs.empty()) {
7020 mpClientInterface->updateSecondaryOutputs(trackSecondaryOutputs);
7021 }
jiabinc44b3462022-12-08 12:52:31 -08007022 if (!clientsToInvalidate.empty()) {
7023 ALOGD("%s Invalidate clients due to fail getting output for attr", __func__);
7024 mpClientInterface->invalidateTracks(clientsToInvalidate);
Kevin Rocard153f92d2018-12-18 18:33:28 -08007025 }
7026}
7027
Eric Laurent2517af32020-11-25 15:31:27 +01007028bool AudioPolicyManager::isScoRequestedForComm() const {
7029 AudioDeviceTypeAddrVector devices;
7030 mEngine->getDevicesForRoleAndStrategy(mCommunnicationStrategy, DEVICE_ROLE_PREFERRED, devices);
7031 for (const auto &device : devices) {
7032 if (audio_is_bluetooth_out_sco_device(device.mType)) {
7033 return true;
7034 }
7035 }
7036 return false;
7037}
7038
Eric Laurent1a8b45f2022-04-13 16:01:47 +02007039bool AudioPolicyManager::isHearingAidUsedForComm() const {
7040 DeviceVector devices = mEngine->getOutputDevicesForStream(AUDIO_STREAM_VOICE_CALL,
7041 true /*fromCache*/);
7042 for (const auto &device : devices) {
7043 if (device->type() == AUDIO_DEVICE_OUT_HEARING_AID) {
7044 return true;
7045 }
7046 }
7047 return false;
7048}
7049
7050
Eric Laurente0720872014-03-11 09:30:41 -07007051void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07007052{
François Gaffie53615e22015-03-19 09:24:12 +01007053 audio_io_handle_t a2dpOutput = mOutputs.getA2dpOutput();
Aniket Kumar Lataa8ee9962018-01-31 20:24:23 -08007054 if (a2dpOutput == 0 || mOutputs.isA2dpOffloadedOnPrimary()) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07007055 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07007056 return;
7057 }
7058
Eric Laurent3a4311c2014-03-17 12:00:47 -07007059 bool isScoConnected =
jiabin9a3361e2019-10-01 09:38:30 -07007060 (mAvailableInputDevices.types().count(AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) != 0 ||
7061 !Intersection(mAvailableOutputDevices.types(), getAudioDeviceOutAllScoSet()).empty());
Eric Laurent2517af32020-11-25 15:31:27 +01007062 bool isScoRequested = isScoRequestedForComm();
Eric Laurentf732e072016-08-03 19:30:28 -07007063
7064 // if suspended, restore A2DP output if:
7065 // ((SCO device is NOT connected) ||
Eric Laurent2517af32020-11-25 15:31:27 +01007066 // ((SCO is not requested) &&
Eric Laurentf732e072016-08-03 19:30:28 -07007067 // (phone state is NOT in call) && (phone state is NOT ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07007068 //
Eric Laurentf732e072016-08-03 19:30:28 -07007069 // if not suspended, suspend A2DP output if:
7070 // (SCO device is connected) &&
Eric Laurent2517af32020-11-25 15:31:27 +01007071 // ((SCO is requested) ||
Eric Laurentf732e072016-08-03 19:30:28 -07007072 // ((phone state is in call) || (phone state is ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07007073 //
7074 if (mA2dpSuspended) {
Eric Laurentf732e072016-08-03 19:30:28 -07007075 if (!isScoConnected ||
Eric Laurent2517af32020-11-25 15:31:27 +01007076 (!isScoRequested &&
Eric Laurentf732e072016-08-03 19:30:28 -07007077 (mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) &&
François Gaffie2110e042015-03-24 08:41:51 +01007078 (mEngine->getPhoneState() != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07007079
7080 mpClientInterface->restoreOutput(a2dpOutput);
7081 mA2dpSuspended = false;
7082 }
7083 } else {
Eric Laurentf732e072016-08-03 19:30:28 -07007084 if (isScoConnected &&
Eric Laurent2517af32020-11-25 15:31:27 +01007085 (isScoRequested ||
Eric Laurentf732e072016-08-03 19:30:28 -07007086 (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) ||
François Gaffie2110e042015-03-24 08:41:51 +01007087 (mEngine->getPhoneState() == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07007088
7089 mpClientInterface->suspendOutput(a2dpOutput);
7090 mA2dpSuspended = true;
7091 }
7092 }
7093}
7094
François Gaffie11d30102018-11-02 16:09:09 +01007095DeviceVector AudioPolicyManager::getNewOutputDevices(const sp<SwAudioOutputDescriptor>& outputDesc,
7096 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07007097{
François Gaffie11d30102018-11-02 16:09:09 +01007098 DeviceVector devices;
7099
Jean-Michel Triviff155c62016-02-26 12:07:16 -08007100 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007101 if (index >= 0) {
7102 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007103 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01007104 ALOGV("%s device %s forced by patch %d", __func__,
7105 outputDesc->devices().toString().c_str(), outputDesc->getPatchHandle());
7106 return outputDesc->devices();
Eric Laurent6a94d692014-05-20 11:18:06 -07007107 }
7108 }
7109
Dean Wheatley514b4312020-06-17 21:45:00 +10007110 // Do not retrieve engine device for outputs through MSD
7111 // TODO: support explicit routing requests by resetting MSD patch to engine device.
7112 if (outputDesc->devices() == getMsdAudioOutDevices()) {
7113 return outputDesc->devices();
7114 }
7115
Eric Laurent97ac8712018-07-27 18:59:02 -07007116 // Honor explicit routing requests only if no client using default routing is active on this
7117 // input: a specific app can not force routing for other apps by setting a preferred device.
7118 bool active; // unused
François Gaffie11d30102018-11-02 16:09:09 +01007119 sp<DeviceDescriptor> device =
François Gaffiec005e562018-11-06 15:04:49 +01007120 findPreferredDevice(outputDesc, PRODUCT_STRATEGY_NONE, active, mAvailableOutputDevices);
François Gaffie11d30102018-11-02 16:09:09 +01007121 if (device != nullptr) {
7122 return DeviceVector(device);
Eric Laurentf3a5a602018-05-22 18:42:55 -07007123 }
7124
François Gaffiea807ef92018-11-05 10:44:33 +01007125 // Legacy Engine cannot take care of bus devices and mix, so we need to handle the conflict
7126 // of setForceUse / Default Bus device here
7127 device = mPolicyMixes.getDeviceAndMixForOutput(outputDesc, mAvailableOutputDevices);
7128 if (device != nullptr) {
7129 return DeviceVector(device);
7130 }
7131
François Gaffiec005e562018-11-06 15:04:49 +01007132 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
7133 StreamTypeVector streams = mEngine->getStreamTypesForProductStrategy(productStrategy);
7134 auto attr = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307135 auto hasStreamActive = [&](auto stream) {
7136 return hasStream(streams, stream) && isStreamActive(stream, 0);
7137 };
Eric Laurent484e9272018-06-07 17:29:23 -07007138
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307139 auto doGetOutputDevicesForVoice = [&]() {
7140 return hasVoiceStream(streams) && (outputDesc == mPrimaryOutput ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007141 outputDesc->isActive(toVolumeSource(AUDIO_STREAM_VOICE_CALL, false))) &&
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307142 (isInCall() ||
Henrik Backlund07c654a2021-10-14 15:57:10 +02007143 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc)) &&
7144 !isStreamActive(AUDIO_STREAM_ENFORCED_AUDIBLE, 0);
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307145 };
7146
7147 // With low-latency playing on speaker, music on WFD, when the first low-latency
7148 // output is stopped, getNewOutputDevices checks for a product strategy
7149 // from the list, as STRATEGY_SONIFICATION comes prior to STRATEGY_MEDIA.
Carter Hsucc58a6b2021-07-20 08:44:50 +00007150 // If an ALARM or ENFORCED_AUDIBLE stream is supported by the product strategy,
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307151 // devices are returned for STRATEGY_SONIFICATION without checking whether the
7152 // stream is associated to the output descriptor.
7153 if (doGetOutputDevicesForVoice() || outputDesc->isStrategyActive(productStrategy) ||
7154 ((hasStreamActive(AUDIO_STREAM_ALARM) ||
7155 hasStreamActive(AUDIO_STREAM_ENFORCED_AUDIBLE)) &&
7156 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc))) {
François Gaffiec005e562018-11-06 15:04:49 +01007157 // Retrieval of devices for voice DL is done on primary output profile, cannot
7158 // check the route (would force modifying configuration file for this profile)
7159 devices = mEngine->getOutputDevicesForAttributes(attr, nullptr, fromCache);
7160 break;
7161 }
Eric Laurente552edb2014-03-10 17:42:56 -07007162 }
François Gaffiec005e562018-11-06 15:04:49 +01007163 ALOGV("%s selected devices %s", __func__, devices.toString().c_str());
François Gaffie11d30102018-11-02 16:09:09 +01007164 return devices;
Eric Laurent1c333e22014-05-20 10:48:17 -07007165}
7166
François Gaffie11d30102018-11-02 16:09:09 +01007167sp<DeviceDescriptor> AudioPolicyManager::getNewInputDevice(
7168 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurent1c333e22014-05-20 10:48:17 -07007169{
François Gaffie11d30102018-11-02 16:09:09 +01007170 sp<DeviceDescriptor> device;
Eric Laurent6a94d692014-05-20 11:18:06 -07007171
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08007172 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007173 if (index >= 0) {
7174 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007175 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01007176 ALOGV("getNewInputDevice() device %s forced by patch %d",
7177 inputDesc->getDevice()->toString().c_str(), inputDesc->getPatchHandle());
7178 return inputDesc->getDevice();
Eric Laurent6a94d692014-05-20 11:18:06 -07007179 }
7180 }
7181
Eric Laurent97ac8712018-07-27 18:59:02 -07007182 // Honor explicit routing requests only if no client using default routing is active on this
7183 // input: a specific app can not force routing for other apps by setting a preferred device.
7184 bool active;
François Gaffie11d30102018-11-02 16:09:09 +01007185 device = findPreferredDevice(inputDesc, AUDIO_SOURCE_DEFAULT, active, mAvailableInputDevices);
7186 if (device != nullptr) {
7187 return device;
Eric Laurent97ac8712018-07-27 18:59:02 -07007188 }
7189
Eric Laurentdc95a252018-04-12 12:46:56 -07007190 // If we are not in call and no client is active on this input, this methods returns
Andy Hungf024a9e2019-01-30 16:01:02 -08007191 // a null sp<>, causing the patch on the input stream to be released.
yuanjiahsu0735bf32021-03-18 08:12:54 +08007192 audio_attributes_t attributes;
7193 uid_t uid;
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007194 audio_session_t session;
yuanjiahsu0735bf32021-03-18 08:12:54 +08007195 sp<RecordClientDescriptor> topClient = inputDesc->getHighestPriorityClient();
7196 if (topClient != nullptr) {
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01007197 attributes = topClient->attributes();
7198 uid = topClient->uid();
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007199 session = topClient->session();
yuanjiahsu0735bf32021-03-18 08:12:54 +08007200 } else {
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01007201 attributes = { .source = AUDIO_SOURCE_DEFAULT };
7202 uid = 0;
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007203 session = AUDIO_SESSION_NONE;
yuanjiahsu0735bf32021-03-18 08:12:54 +08007204 }
7205
Francois Gaffie716e1432019-01-14 16:58:59 +01007206 if (attributes.source == AUDIO_SOURCE_DEFAULT && isInCall()) {
7207 attributes.source = AUDIO_SOURCE_VOICE_COMMUNICATION;
Eric Laurentdc95a252018-04-12 12:46:56 -07007208 }
Francois Gaffie716e1432019-01-14 16:58:59 +01007209 if (attributes.source != AUDIO_SOURCE_DEFAULT) {
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007210 device = mEngine->getInputDeviceForAttributes(attributes, uid, session);
Eric Laurentfb66dd92016-01-28 18:32:03 -08007211 }
Eric Laurent1c333e22014-05-20 10:48:17 -07007212
Eric Laurente552edb2014-03-10 17:42:56 -07007213 return device;
7214}
7215
Eric Laurent794fde22016-03-11 09:50:45 -08007216bool AudioPolicyManager::streamsMatchForvolume(audio_stream_type_t stream1,
7217 audio_stream_type_t stream2) {
Jean-Michel Trivi99bb2f92016-11-23 15:52:07 -08007218 return (stream1 == stream2);
Eric Laurent28d09f02016-03-08 10:43:05 -08007219}
7220
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08007221status_t AudioPolicyManager::getDevicesForAttributes(
Andy Hung6d23c0f2022-02-16 09:37:15 -08007222 const audio_attributes_t &attr, AudioDeviceTypeAddrVector *devices, bool forVolume) {
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08007223 if (devices == nullptr) {
7224 return BAD_VALUE;
7225 }
Andy Hung6d23c0f2022-02-16 09:37:15 -08007226
Andy Hung6d23c0f2022-02-16 09:37:15 -08007227 DeviceVector curDevices;
jiabinf1c73972022-04-14 16:28:52 -07007228 if (status_t status = getDevicesForAttributes(attr, curDevices, forVolume); status != OK) {
7229 return status;
Andy Hung6d23c0f2022-02-16 09:37:15 -08007230 }
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08007231 for (const auto& device : curDevices) {
7232 devices->push_back(device->getDeviceTypeAddr());
7233 }
7234 return NO_ERROR;
7235}
7236
Eric Laurente0720872014-03-11 09:30:41 -07007237void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07007238 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07007239 case AUDIO_STREAM_MUSIC:
François Gaffiec005e562018-11-06 15:04:49 +01007240 checkOutputForAttributes(attributes_initializer(AUDIO_USAGE_NOTIFICATION));
Eric Laurente552edb2014-03-10 17:42:56 -07007241 updateDevicesAndOutputs();
7242 break;
7243 default:
7244 break;
7245 }
7246}
7247
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007248uint32_t AudioPolicyManager::handleEventForBeacon(int event) {
Eric Laurent9459fb02015-08-12 18:36:32 -07007249
7250 // skip beacon mute management if a dedicated TTS output is available
7251 if (mTtsOutputAvailable) {
7252 return 0;
7253 }
7254
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007255 switch(event) {
7256 case STARTING_OUTPUT:
7257 mBeaconMuteRefCount++;
7258 break;
7259 case STOPPING_OUTPUT:
7260 if (mBeaconMuteRefCount > 0) {
7261 mBeaconMuteRefCount--;
7262 }
7263 break;
7264 case STARTING_BEACON:
7265 mBeaconPlayingRefCount++;
7266 break;
7267 case STOPPING_BEACON:
7268 if (mBeaconPlayingRefCount > 0) {
7269 mBeaconPlayingRefCount--;
7270 }
7271 break;
7272 }
7273
7274 if (mBeaconMuteRefCount > 0) {
7275 // any playback causes beacon to be muted
7276 return setBeaconMute(true);
7277 } else {
7278 // no other playback: unmute when beacon starts playing, mute when it stops
7279 return setBeaconMute(mBeaconPlayingRefCount == 0);
7280 }
7281}
7282
7283uint32_t AudioPolicyManager::setBeaconMute(bool mute) {
7284 ALOGV("setBeaconMute(%d) mBeaconMuteRefCount=%d mBeaconPlayingRefCount=%d",
7285 mute, mBeaconMuteRefCount, mBeaconPlayingRefCount);
7286 // keep track of muted state to avoid repeating mute/unmute operations
7287 if (mBeaconMuted != mute) {
7288 // mute/unmute AUDIO_STREAM_TTS on all outputs
7289 ALOGV("\t muting %d", mute);
7290 uint32_t maxLatency = 0;
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007291 auto ttsVolumeSource = toVolumeSource(AUDIO_STREAM_TTS, false);
7292 if (ttsVolumeSource == VOLUME_SOURCE_NONE) {
7293 ALOGV("\t no tts volume source available");
7294 return 0;
7295 }
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007296 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07007297 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
jiabin9a3361e2019-10-01 09:38:30 -07007298 setVolumeSourceMute(ttsVolumeSource, mute/*on*/, desc, 0 /*delay*/, DeviceTypeSet());
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007299 const uint32_t latency = desc->latency() * 2;
Eric Laurentcdb2b352020-07-23 10:57:02 -07007300 if (desc->isActive(latency * 2) && latency > maxLatency) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007301 maxLatency = latency;
7302 }
7303 }
7304 mBeaconMuted = mute;
7305 return maxLatency;
7306 }
7307 return 0;
7308}
7309
Eric Laurente0720872014-03-11 09:30:41 -07007310void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07007311{
François Gaffiec005e562018-11-06 15:04:49 +01007312 mEngine->updateDeviceSelectionCache();
Eric Laurente552edb2014-03-10 17:42:56 -07007313 mPreviousOutputs = mOutputs;
7314}
7315
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07007316uint32_t AudioPolicyManager::checkDeviceMuteStrategies(const sp<AudioOutputDescriptor>& outputDesc,
François Gaffiec005e562018-11-06 15:04:49 +01007317 const DeviceVector &prevDevices,
Eric Laurente552edb2014-03-10 17:42:56 -07007318 uint32_t delayMs)
7319{
7320 // mute/unmute strategies using an incompatible device combination
7321 // if muting, wait for the audio in pcm buffer to be drained before proceeding
7322 // if unmuting, unmute only after the specified delay
7323 if (outputDesc->isDuplicated()) {
7324 return 0;
7325 }
7326
7327 uint32_t muteWaitMs = 0;
François Gaffiec005e562018-11-06 15:04:49 +01007328 DeviceVector devices = outputDesc->devices();
7329 bool shouldMute = outputDesc->isActive() && (devices.size() >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07007330
François Gaffiec005e562018-11-06 15:04:49 +01007331 auto productStrategies = mEngine->getOrderedProductStrategies();
7332 for (const auto &productStrategy : productStrategies) {
7333 auto attributes = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
7334 DeviceVector curDevices =
7335 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false/*fromCache*/);
7336 curDevices = curDevices.filter(outputDesc->supportedDevices());
7337 bool mute = shouldMute && curDevices.containsAtLeastOne(devices) && curDevices != devices;
Eric Laurente552edb2014-03-10 17:42:56 -07007338 bool doMute = false;
7339
François Gaffiec005e562018-11-06 15:04:49 +01007340 if (mute && !outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07007341 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01007342 outputDesc->setStrategyMutedByDevice(productStrategy, true);
7343 } else if (!mute && outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07007344 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01007345 outputDesc->setStrategyMutedByDevice(productStrategy, false);
Eric Laurente552edb2014-03-10 17:42:56 -07007346 }
Eric Laurent99401132014-05-07 19:48:15 -07007347 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07007348 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07007349 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07007350 // skip output if it does not share any device with current output
François Gaffie11d30102018-11-02 16:09:09 +01007351 if (!desc->supportedDevices().containsAtLeastOne(outputDesc->supportedDevices())) {
Eric Laurente552edb2014-03-10 17:42:56 -07007352 continue;
7353 }
François Gaffiec005e562018-11-06 15:04:49 +01007354 ALOGVV("%s() %s (curDevice %s)", __func__,
7355 mute ? "muting" : "unmuting", curDevices.toString().c_str());
7356 setStrategyMute(productStrategy, mute, desc, mute ? 0 : delayMs);
7357 if (desc->isStrategyActive(productStrategy)) {
Eric Laurent99401132014-05-07 19:48:15 -07007358 if (mute) {
7359 // FIXME: should not need to double latency if volume could be applied
7360 // immediately by the audioflinger mixer. We must account for the delay
7361 // between now and the next time the audioflinger thread for this output
7362 // will process a buffer (which corresponds to one buffer size,
7363 // usually 1/2 or 1/4 of the latency).
7364 if (muteWaitMs < desc->latency() * 2) {
7365 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07007366 }
7367 }
7368 }
7369 }
7370 }
7371 }
7372
Eric Laurent99401132014-05-07 19:48:15 -07007373 // temporary mute output if device selection changes to avoid volume bursts due to
7374 // different per device volumes
François Gaffiec005e562018-11-06 15:04:49 +01007375 if (outputDesc->isActive() && (devices != prevDevices)) {
Eric Laurentdc462862016-07-19 12:29:53 -07007376 uint32_t tempMuteWaitMs = outputDesc->latency() * 2;
Jasmine Chaf6074fe2021-08-17 13:44:31 +08007377
Eric Laurentdc462862016-07-19 12:29:53 -07007378 if (muteWaitMs < tempMuteWaitMs) {
7379 muteWaitMs = tempMuteWaitMs;
Eric Laurent99401132014-05-07 19:48:15 -07007380 }
Jasmine Chaf6074fe2021-08-17 13:44:31 +08007381
7382 // If recommended duration is defined, replace temporary mute duration to avoid
7383 // truncated notifications at beginning, which depends on duration of changing path in HAL.
7384 // Otherwise, temporary mute duration is conservatively set to 4 times the reported latency.
7385 uint32_t tempRecommendedMuteDuration = outputDesc->getRecommendedMuteDurationMs();
7386 uint32_t tempMuteDurationMs = tempRecommendedMuteDuration > 0 ?
7387 tempRecommendedMuteDuration : outputDesc->latency() * 4;
7388
François Gaffieaaac0fd2018-11-22 17:56:39 +01007389 for (const auto &activeVs : outputDesc->getActiveVolumeSources()) {
7390 // make sure that we do not start the temporary mute period too early in case of
7391 // delayed device change
7392 setVolumeSourceMute(activeVs, true, outputDesc, delayMs);
7393 setVolumeSourceMute(activeVs, false, outputDesc, delayMs + tempMuteDurationMs,
François Gaffiec005e562018-11-06 15:04:49 +01007394 devices.types());
Eric Laurent99401132014-05-07 19:48:15 -07007395 }
7396 }
7397
Eric Laurente552edb2014-03-10 17:42:56 -07007398 // wait for the PCM output buffers to empty before proceeding with the rest of the command
7399 if (muteWaitMs > delayMs) {
7400 muteWaitMs -= delayMs;
7401 usleep(muteWaitMs * 1000);
7402 return muteWaitMs;
7403 }
7404 return 0;
7405}
7406
François Gaffie11d30102018-11-02 16:09:09 +01007407uint32_t AudioPolicyManager::setOutputDevices(const sp<SwAudioOutputDescriptor>& outputDesc,
7408 const DeviceVector &devices,
7409 bool force,
7410 int delayMs,
7411 audio_patch_handle_t *patchHandle,
Oscar Azucena6acf34b2023-04-27 16:32:09 -07007412 bool requiresMuteCheck, bool requiresVolumeCheck,
7413 bool skipMuteDelay)
Eric Laurente552edb2014-03-10 17:42:56 -07007414{
jiabin3ff8d7d2022-12-13 06:27:44 +00007415 // TODO(b/262404095): Consider if the output need to be reopened.
François Gaffie11d30102018-11-02 16:09:09 +01007416 ALOGV("%s device %s delayMs %d", __func__, devices.toString().c_str(), delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07007417 uint32_t muteWaitMs;
7418
7419 if (outputDesc->isDuplicated()) {
François Gaffie11d30102018-11-02 16:09:09 +01007420 muteWaitMs = setOutputDevices(outputDesc->subOutput1(), devices, force, delayMs,
Oscar Azucena6acf34b2023-04-27 16:32:09 -07007421 nullptr /* patchHandle */, requiresMuteCheck, skipMuteDelay);
François Gaffie11d30102018-11-02 16:09:09 +01007422 muteWaitMs += setOutputDevices(outputDesc->subOutput2(), devices, force, delayMs,
Oscar Azucena6acf34b2023-04-27 16:32:09 -07007423 nullptr /* patchHandle */, requiresMuteCheck, skipMuteDelay);
Eric Laurente552edb2014-03-10 17:42:56 -07007424 return muteWaitMs;
7425 }
Eric Laurente552edb2014-03-10 17:42:56 -07007426
7427 // filter devices according to output selected
Francois Gaffie716e1432019-01-14 16:58:59 +01007428 DeviceVector filteredDevices = outputDesc->filterSupportedDevices(devices);
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01007429 DeviceVector prevDevices = outputDesc->devices();
Francois Gaffie3523ab32021-06-22 13:24:34 +02007430 DeviceVector availPrevDevices = mAvailableOutputDevices.filter(prevDevices);
Eric Laurente552edb2014-03-10 17:42:56 -07007431
François Gaffie11d30102018-11-02 16:09:09 +01007432 ALOGV("setOutputDevices() prevDevice %s", prevDevices.toString().c_str());
7433
7434 if (!filteredDevices.isEmpty()) {
7435 outputDesc->setDevices(filteredDevices);
Eric Laurente552edb2014-03-10 17:42:56 -07007436 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00007437
7438 // if the outputs are not materially active, there is no need to mute.
7439 if (requiresMuteCheck) {
François Gaffiec005e562018-11-06 15:04:49 +01007440 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevices, delayMs);
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00007441 } else {
7442 ALOGV("%s: suppressing checkDeviceMuteStrategies", __func__);
7443 muteWaitMs = 0;
7444 }
Eric Laurente552edb2014-03-10 17:42:56 -07007445
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02007446 bool outputRouted = outputDesc->isRouted();
7447
Eric Laurent79ea9582020-06-11 18:49:24 -07007448 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
7449 // output profile or if new device is not supported AND previous device(s) is(are) still
7450 // available (otherwise reset device must be done on the output)
Francois Gaffie3523ab32021-06-22 13:24:34 +02007451 if (!devices.isEmpty() && filteredDevices.isEmpty() && !availPrevDevices.empty()) {
Eric Laurent79ea9582020-06-11 18:49:24 -07007452 ALOGV("%s: unsupported device %s for output", __func__, devices.toString().c_str());
7453 // restore previous device after evaluating strategy mute state
7454 outputDesc->setDevices(prevDevices);
7455 return muteWaitMs;
7456 }
7457
Eric Laurente552edb2014-03-10 17:42:56 -07007458 // Do not change the routing if:
Eric Laurentb80a2a82014-10-27 16:07:59 -07007459 // the requested device is AUDIO_DEVICE_NONE
7460 // OR the requested device is the same as current device
7461 // AND force is not specified
7462 // AND the output is connected by a valid audio patch.
François Gaffie11d30102018-11-02 16:09:09 +01007463 // Doing this check here allows the caller to call setOutputDevices() without conditions
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02007464 if ((filteredDevices.isEmpty() || filteredDevices == prevDevices) && !force && outputRouted) {
François Gaffie11d30102018-11-02 16:09:09 +01007465 ALOGV("%s setting same device %s or null device, force=%d, patch handle=%d", __func__,
7466 filteredDevices.toString().c_str(), force, outputDesc->getPatchHandle());
Francois Gaffie3523ab32021-06-22 13:24:34 +02007467 if (requiresVolumeCheck && !filteredDevices.isEmpty()) {
7468 ALOGV("%s setting same device on routed output, force apply volumes", __func__);
7469 applyStreamVolumes(outputDesc, filteredDevices.types(), delayMs, true /*force*/);
7470 }
Eric Laurente552edb2014-03-10 17:42:56 -07007471 return muteWaitMs;
7472 }
7473
François Gaffie11d30102018-11-02 16:09:09 +01007474 ALOGV("%s changing device to %s", __func__, filteredDevices.toString().c_str());
Eric Laurent1c333e22014-05-20 10:48:17 -07007475
Eric Laurente552edb2014-03-10 17:42:56 -07007476 // do the routing
Francois Gaffie3523ab32021-06-22 13:24:34 +02007477 if (filteredDevices.isEmpty() || mAvailableOutputDevices.filter(filteredDevices).empty()) {
Eric Laurentc75307b2015-03-17 15:29:32 -07007478 resetOutputDevice(outputDesc, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07007479 } else {
François Gaffie11d30102018-11-02 16:09:09 +01007480 PatchBuilder patchBuilder;
7481 patchBuilder.addSource(outputDesc);
7482 ALOG_ASSERT(filteredDevices.size() <= AUDIO_PATCH_PORTS_MAX, "Too many sink ports");
7483 for (const auto &filteredDevice : filteredDevices) {
7484 patchBuilder.addSink(filteredDevice);
Eric Laurentc40d9692016-04-13 19:14:13 -07007485 }
7486
Jasmine Cha7f82d1a2020-03-16 13:21:47 +08007487 // Add half reported latency to delayMs when muteWaitMs is null in order
7488 // to avoid disordered sequence of muting volume and changing devices.
Oscar Azucena6acf34b2023-04-27 16:32:09 -07007489 int actualDelayMs = !skipMuteDelay && muteWaitMs == 0
7490 ? (delayMs + (outputDesc->latency() / 2)) : delayMs;
7491 installPatch(__func__, patchHandle, outputDesc.get(), patchBuilder.patch(), actualDelayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07007492 }
Eric Laurente552edb2014-03-10 17:42:56 -07007493
Oscar Azucena6acf34b2023-04-27 16:32:09 -07007494 // Since the mute is skip, also skip the apply stream volume as that will be applied externally
7495 if (!skipMuteDelay) {
7496 // update stream volumes according to new device
7497 applyStreamVolumes(outputDesc, filteredDevices.types(), delayMs);
7498 }
Eric Laurente552edb2014-03-10 17:42:56 -07007499
7500 return muteWaitMs;
7501}
7502
Eric Laurentc75307b2015-03-17 15:29:32 -07007503status_t AudioPolicyManager::resetOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurent6a94d692014-05-20 11:18:06 -07007504 int delayMs,
7505 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07007506{
Eric Laurent6a94d692014-05-20 11:18:06 -07007507 ssize_t index;
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02007508 if (patchHandle == nullptr && !outputDesc->isRouted()) {
7509 return INVALID_OPERATION;
7510 }
Eric Laurent6a94d692014-05-20 11:18:06 -07007511 if (patchHandle) {
7512 index = mAudioPatches.indexOfKey(*patchHandle);
7513 } else {
Jean-Michel Triviff155c62016-02-26 12:07:16 -08007514 index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007515 }
7516 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07007517 return INVALID_OPERATION;
7518 }
Eric Laurent6a94d692014-05-20 11:18:06 -07007519 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007520 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07007521 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07007522 outputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
François Gaffieafd4cea2019-11-18 15:50:22 +01007523 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007524 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07007525 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07007526 return status;
7527}
7528
7529status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
François Gaffie11d30102018-11-02 16:09:09 +01007530 const sp<DeviceDescriptor> &device,
Eric Laurent6a94d692014-05-20 11:18:06 -07007531 bool force,
7532 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07007533{
7534 status_t status = NO_ERROR;
7535
Eric Laurent1f2f2232014-06-02 12:01:23 -07007536 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
François Gaffie11d30102018-11-02 16:09:09 +01007537 if ((device != nullptr) && ((device != inputDesc->getDevice()) || force)) {
7538 inputDesc->setDevice(device);
Eric Laurent1c333e22014-05-20 10:48:17 -07007539
François Gaffie11d30102018-11-02 16:09:09 +01007540 if (mAvailableInputDevices.contains(device)) {
Mikhail Naganovdc769682018-05-04 15:34:08 -07007541 PatchBuilder patchBuilder;
7542 patchBuilder.addSink(inputDesc,
Eric Laurentdaf92cc2014-07-22 15:36:10 -07007543 // AUDIO_SOURCE_HOTWORD is for internal use only:
7544 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
Mikhail Naganovdc769682018-05-04 15:34:08 -07007545 [inputDesc](const PatchBuilder::mix_usecase_t& usecase) {
7546 auto result = usecase;
7547 if (result.source == AUDIO_SOURCE_HOTWORD && !inputDesc->isSoundTrigger()) {
7548 result.source = AUDIO_SOURCE_VOICE_RECOGNITION;
7549 }
7550 return result; }).
Eric Laurent1c333e22014-05-20 10:48:17 -07007551 //only one input device for now
François Gaffie11d30102018-11-02 16:09:09 +01007552 addSource(device);
Mikhail Naganovdc769682018-05-04 15:34:08 -07007553 status = installPatch(__func__, patchHandle, inputDesc.get(), patchBuilder.patch(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07007554 }
7555 }
7556 return status;
7557}
7558
Eric Laurent6a94d692014-05-20 11:18:06 -07007559status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
7560 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07007561{
Eric Laurent1f2f2232014-06-02 12:01:23 -07007562 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07007563 ssize_t index;
7564 if (patchHandle) {
7565 index = mAudioPatches.indexOfKey(*patchHandle);
7566 } else {
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08007567 index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007568 }
7569 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07007570 return INVALID_OPERATION;
7571 }
Eric Laurent6a94d692014-05-20 11:18:06 -07007572 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007573 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07007574 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07007575 inputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
François Gaffieafd4cea2019-11-18 15:50:22 +01007576 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007577 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07007578 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07007579 return status;
7580}
7581
François Gaffie11d30102018-11-02 16:09:09 +01007582sp<IOProfile> AudioPolicyManager::getInputProfile(const sp<DeviceDescriptor> &device,
François Gaffie53615e22015-03-19 09:24:12 +01007583 uint32_t& samplingRate,
Andy Hungf129b032015-04-07 13:45:50 -07007584 audio_format_t& format,
7585 audio_channel_mask_t& channelMask,
François Gaffie53615e22015-03-19 09:24:12 +01007586 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07007587{
7588 // Choose an input profile based on the requested capture parameters: select the first available
7589 // profile supporting all requested parameters.
jiabin2fd710d2022-05-02 23:20:22 +00007590 // The flags can be ignored if it doesn't contain a much match flag.
Andy Hungf129b032015-04-07 13:45:50 -07007591 //
7592 // TODO: perhaps isCompatibleProfile should return a "matching" score so we can return
7593 // the best matching profile, not the first one.
Eric Laurente552edb2014-03-10 17:42:56 -07007594
Atneya Nair0f0a8032022-12-12 16:20:12 -08007595 using underlying_input_flag_t = std::underlying_type_t<audio_input_flags_t>;
7596 const underlying_input_flag_t mustMatchFlag = AUDIO_INPUT_FLAG_MMAP_NOIRQ |
7597 AUDIO_INPUT_FLAG_HOTWORD_TAP | AUDIO_INPUT_FLAG_HW_LOOKBACK;
7598
7599 const underlying_input_flag_t oriFlags = flags;
Glenn Kasten730b9262018-03-29 15:01:26 -07007600
jiabin2fd710d2022-05-02 23:20:22 +00007601 for (;;) {
7602 sp<IOProfile> firstInexact = nullptr;
7603 uint32_t updatedSamplingRate = 0;
7604 audio_format_t updatedFormat = AUDIO_FORMAT_INVALID;
7605 audio_channel_mask_t updatedChannelMask = AUDIO_CHANNEL_INVALID;
7606 for (const auto& hwModule : mHwModules) {
7607 for (const auto& profile : hwModule->getInputProfiles()) {
7608 // profile->log();
7609 //updatedFormat = format;
7610 if (profile->isCompatibleProfile(DeviceVector(device), samplingRate,
7611 &samplingRate /*updatedSamplingRate*/,
7612 format,
7613 &format, /*updatedFormat*/
7614 channelMask,
7615 &channelMask /*updatedChannelMask*/,
7616 // FIXME ugly cast
7617 (audio_output_flags_t) flags,
7618 true /*exactMatchRequiredForInputFlags*/)) {
7619 return profile;
7620 }
7621 if (firstInexact == nullptr && profile->isCompatibleProfile(DeviceVector(device),
7622 samplingRate,
7623 &updatedSamplingRate,
7624 format,
7625 &updatedFormat,
7626 channelMask,
7627 &updatedChannelMask,
7628 // FIXME ugly cast
7629 (audio_output_flags_t) flags,
7630 false /*exactMatchRequiredForInputFlags*/)) {
7631 firstInexact = profile;
7632 }
7633 }
7634 }
7635
7636 if (firstInexact != nullptr) {
7637 samplingRate = updatedSamplingRate;
7638 format = updatedFormat;
7639 channelMask = updatedChannelMask;
7640 return firstInexact;
7641 } else if (flags & AUDIO_INPUT_FLAG_RAW) {
7642 flags = (audio_input_flags_t) (flags & ~AUDIO_INPUT_FLAG_RAW); // retry
7643 } else if ((flags & mustMatchFlag) == AUDIO_INPUT_FLAG_NONE &&
7644 flags != AUDIO_INPUT_FLAG_NONE && audio_is_linear_pcm(format)) {
7645 flags = AUDIO_INPUT_FLAG_NONE;
7646 } else { // fail
7647 ALOGW("%s could not find profile for device %s, sampling rate %u, format %#x, "
7648 "channel mask 0x%X, flags %#x", __func__, device->toString().c_str(),
7649 samplingRate, format, channelMask, oriFlags);
7650 break;
Eric Laurente552edb2014-03-10 17:42:56 -07007651 }
7652 }
jiabin2fd710d2022-05-02 23:20:22 +00007653
7654 return nullptr;
Eric Laurente552edb2014-03-10 17:42:56 -07007655}
7656
François Gaffieaaac0fd2018-11-22 17:56:39 +01007657float AudioPolicyManager::computeVolume(IVolumeCurves &curves,
7658 VolumeSource volumeSource,
François Gaffied1ab2bd2015-12-02 18:20:06 +01007659 int index,
jiabin9a3361e2019-10-01 09:38:30 -07007660 const DeviceTypeSet& deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07007661{
jiabin9a3361e2019-10-01 09:38:30 -07007662 float volumeDb = curves.volIndexToDb(Volume::getDeviceCategory(deviceTypes), index);
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07007663
7664 // handle the case of accessibility active while a ringtone is playing: if the ringtone is much
7665 // louder than the accessibility prompt, the prompt cannot be heard, thus masking the touch
7666 // exploration of the dialer UI. In this situation, bring the accessibility volume closer to
7667 // the ringtone volume
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007668 const auto callVolumeSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL, false);
7669 const auto ringVolumeSrc = toVolumeSource(AUDIO_STREAM_RING, false);
7670 const auto musicVolumeSrc = toVolumeSource(AUDIO_STREAM_MUSIC, false);
7671 const auto alarmVolumeSrc = toVolumeSource(AUDIO_STREAM_ALARM, false);
7672 const auto a11yVolumeSrc = toVolumeSource(AUDIO_STREAM_ACCESSIBILITY, false);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007673
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07007674 if (volumeSource == a11yVolumeSrc
François Gaffieaaac0fd2018-11-22 17:56:39 +01007675 && (AUDIO_MODE_RINGTONE == mEngine->getPhoneState()) &&
7676 mOutputs.isActive(ringVolumeSrc, 0)) {
7677 auto &ringCurves = getVolumeCurves(AUDIO_STREAM_RING);
jiabin9a3361e2019-10-01 09:38:30 -07007678 const float ringVolumeDb = computeVolume(ringCurves, ringVolumeSrc, index, deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007679 return ringVolumeDb - 4 > volumeDb ? ringVolumeDb - 4 : volumeDb;
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07007680 }
7681
Eric Laurentdcd4ab12018-06-29 17:45:13 -07007682 // in-call: always cap volume by voice volume + some low headroom
François Gaffieaaac0fd2018-11-22 17:56:39 +01007683 if ((volumeSource != callVolumeSrc && (isInCall() ||
7684 mOutputs.isActiveLocally(callVolumeSrc))) &&
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007685 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM, false) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01007686 volumeSource == ringVolumeSrc || volumeSource == musicVolumeSrc ||
7687 volumeSource == alarmVolumeSrc ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007688 volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION, false) ||
7689 volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false) ||
7690 volumeSource == toVolumeSource(AUDIO_STREAM_DTMF, false) ||
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07007691 volumeSource == a11yVolumeSrc)) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007692 auto &voiceCurves = getVolumeCurves(callVolumeSrc);
jiabin9a3361e2019-10-01 09:38:30 -07007693 int voiceVolumeIndex = voiceCurves.getVolumeIndex(deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007694 const float maxVoiceVolDb =
jiabin9a3361e2019-10-01 09:38:30 -07007695 computeVolume(voiceCurves, callVolumeSrc, voiceVolumeIndex, deviceTypes)
Eric Laurent7731b5a2018-04-06 15:47:22 -07007696 + IN_CALL_EARPIECE_HEADROOM_DB;
Abhijith Shastry329ddab2019-04-23 11:53:26 -07007697 // FIXME: Workaround for call screening applications until a proper audio mode is defined
7698 // to support this scenario : Exempt the RING stream from the audio cap if the audio was
7699 // programmatically muted.
7700 // VOICE_CALL stream has minVolumeIndex > 0 : Users cannot set the volume of voice calls to
7701 // 0. We don't want to cap volume when the system has programmatically muted the voice call
7702 // stream. See setVolumeCurveIndex() for more information.
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07007703 bool exemptFromCapping =
7704 ((volumeSource == ringVolumeSrc) || (volumeSource == a11yVolumeSrc))
7705 && (voiceVolumeIndex == 0);
Abhijith Shastry329ddab2019-04-23 11:53:26 -07007706 ALOGV_IF(exemptFromCapping, "%s volume source %d at vol=%f not capped", __func__,
7707 volumeSource, volumeDb);
7708 if ((volumeDb > maxVoiceVolDb) && !exemptFromCapping) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007709 ALOGV("%s volume source %d at vol=%f overriden by volume group %d at vol=%f", __func__,
7710 volumeSource, volumeDb, callVolumeSrc, maxVoiceVolDb);
7711 volumeDb = maxVoiceVolDb;
Jean-Michel Trivi719a9872017-08-05 13:51:35 -07007712 }
7713 }
Eric Laurente552edb2014-03-10 17:42:56 -07007714 // if a headset is connected, apply the following rules to ring tones and notifications
7715 // to avoid sound level bursts in user's ears:
Eric Laurent6af1c1d2016-04-14 11:20:44 -07007716 // - always attenuate notifications volume by 6dB
7717 // - attenuate ring tones volume by 6dB unless music is not playing and
7718 // speaker is part of the select devices
Eric Laurente552edb2014-03-10 17:42:56 -07007719 // - if music is playing, always limit the volume to current music volume,
7720 // with a minimum threshold at -36dB so that notification is always perceived.
jiabin9a3361e2019-10-01 09:38:30 -07007721 if (!Intersection(deviceTypes,
7722 {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP, AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES,
7723 AUDIO_DEVICE_OUT_WIRED_HEADSET, AUDIO_DEVICE_OUT_WIRED_HEADPHONE,
Eric Laurentc42df452020-08-07 10:51:53 -07007724 AUDIO_DEVICE_OUT_USB_HEADSET, AUDIO_DEVICE_OUT_HEARING_AID,
7725 AUDIO_DEVICE_OUT_BLE_HEADSET}).empty() &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01007726 ((volumeSource == alarmVolumeSrc ||
7727 volumeSource == ringVolumeSrc) ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007728 (volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION, false)) ||
7729 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM, false)) ||
7730 ((volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false)) &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01007731 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) &&
7732 curves.canBeMuted()) {
7733
Eric Laurente552edb2014-03-10 17:42:56 -07007734 // when the phone is ringing we must consider that music could have been paused just before
7735 // by the music application and behave as if music was active if the last music track was
7736 // just stopped
Eric Laurent3b73df72014-03-11 09:06:29 -07007737 if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY) ||
Eric Laurente552edb2014-03-10 17:42:56 -07007738 mLimitRingtoneVolume) {
François Gaffie43c73442018-11-08 08:21:55 +01007739 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
jiabin9a3361e2019-10-01 09:38:30 -07007740 DeviceTypeSet musicDevice =
François Gaffiec005e562018-11-06 15:04:49 +01007741 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
7742 nullptr, true /*fromCache*/).types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01007743 auto &musicCurves = getVolumeCurves(AUDIO_STREAM_MUSIC);
jiabin9a3361e2019-10-01 09:38:30 -07007744 float musicVolDb = computeVolume(musicCurves,
7745 musicVolumeSrc,
7746 musicCurves.getVolumeIndex(musicDevice),
7747 musicDevice);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007748 float minVolDb = (musicVolDb > SONIFICATION_HEADSET_VOLUME_MIN_DB) ?
7749 musicVolDb : SONIFICATION_HEADSET_VOLUME_MIN_DB;
7750 if (volumeDb > minVolDb) {
7751 volumeDb = minVolDb;
7752 ALOGV("computeVolume limiting volume to %f musicVol %f", minVolDb, musicVolDb);
Eric Laurente552edb2014-03-10 17:42:56 -07007753 }
Eric Laurent7b6385c2021-05-12 17:55:36 +02007754 if (Volume::getDeviceForVolume(deviceTypes) != AUDIO_DEVICE_OUT_SPEAKER
7755 && !Intersection(deviceTypes, {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP,
7756 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES}).empty()) {
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07007757 // on A2DP, also ensure notification volume is not too low compared to media when
7758 // intended to be played
François Gaffie43c73442018-11-08 08:21:55 +01007759 if ((volumeDb > -96.0f) &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01007760 (musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB > volumeDb)) {
jiabin9a3361e2019-10-01 09:38:30 -07007761 ALOGV("%s increasing volume for volume source=%d device=%s from %f to %f",
7762 __func__, volumeSource, dumpDeviceTypes(deviceTypes).c_str(), volumeDb,
François Gaffieaaac0fd2018-11-22 17:56:39 +01007763 musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB);
7764 volumeDb = musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB;
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07007765 }
7766 }
jiabin9a3361e2019-10-01 09:38:30 -07007767 } else if ((Volume::getDeviceForVolume(deviceTypes) != AUDIO_DEVICE_OUT_SPEAKER) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01007768 (!(volumeSource == alarmVolumeSrc || volumeSource == ringVolumeSrc))) {
François Gaffie43c73442018-11-08 08:21:55 +01007769 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07007770 }
7771 }
7772
François Gaffie43c73442018-11-08 08:21:55 +01007773 return volumeDb;
Eric Laurente552edb2014-03-10 17:42:56 -07007774}
7775
Eric Laurent3839bc02018-07-10 18:33:34 -07007776int AudioPolicyManager::rescaleVolumeIndex(int srcIndex,
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01007777 VolumeSource fromVolumeSource,
7778 VolumeSource toVolumeSource)
Eric Laurent3839bc02018-07-10 18:33:34 -07007779{
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01007780 if (fromVolumeSource == toVolumeSource) {
Eric Laurent3839bc02018-07-10 18:33:34 -07007781 return srcIndex;
7782 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01007783 auto &srcCurves = getVolumeCurves(fromVolumeSource);
7784 auto &dstCurves = getVolumeCurves(toVolumeSource);
Eric Laurentf5aa58d2019-02-22 18:20:11 -08007785 float minSrc = (float)srcCurves.getVolumeIndexMin();
7786 float maxSrc = (float)srcCurves.getVolumeIndexMax();
7787 float minDst = (float)dstCurves.getVolumeIndexMin();
7788 float maxDst = (float)dstCurves.getVolumeIndexMax();
Eric Laurent3839bc02018-07-10 18:33:34 -07007789
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08007790 // preserve mute request or correct range
7791 if (srcIndex < minSrc) {
7792 if (srcIndex == 0) {
7793 return 0;
7794 }
7795 srcIndex = minSrc;
7796 } else if (srcIndex > maxSrc) {
7797 srcIndex = maxSrc;
7798 }
Eric Laurent3839bc02018-07-10 18:33:34 -07007799 return (int)(minDst + ((srcIndex - minSrc) * (maxDst - minDst)) / (maxSrc - minSrc));
7800}
7801
François Gaffieaaac0fd2018-11-22 17:56:39 +01007802status_t AudioPolicyManager::checkAndSetVolume(IVolumeCurves &curves,
7803 VolumeSource volumeSource,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08007804 int index,
7805 const sp<AudioOutputDescriptor>& outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07007806 DeviceTypeSet deviceTypes,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08007807 int delayMs,
7808 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07007809{
François Gaffieaaac0fd2018-11-22 17:56:39 +01007810 // do not change actual attributes volume if the attributes is muted
7811 if (outputDesc->isMuted(volumeSource)) {
7812 ALOGVV("%s: volume source %d muted count %d active=%d", __func__, volumeSource,
7813 outputDesc->getMuteCount(volumeSource), outputDesc->isActive(volumeSource));
Eric Laurente552edb2014-03-10 17:42:56 -07007814 return NO_ERROR;
7815 }
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007816 VolumeSource callVolSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL, false);
7817 VolumeSource btScoVolSrc = toVolumeSource(AUDIO_STREAM_BLUETOOTH_SCO, false);
7818 bool isVoiceVolSrc = (volumeSource != VOLUME_SOURCE_NONE) && (callVolSrc == volumeSource);
7819 bool isBtScoVolSrc = (volumeSource != VOLUME_SOURCE_NONE) && (btScoVolSrc == volumeSource);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007820
Eric Laurent2517af32020-11-25 15:31:27 +01007821 bool isScoRequested = isScoRequestedForComm();
Eric Laurent1a8b45f2022-04-13 16:01:47 +02007822 bool isHAUsed = isHearingAidUsedForComm();
7823
Eric Laurente552edb2014-03-10 17:42:56 -07007824 // do not change in call volume if bluetooth is connected and vice versa
François Gaffieaaac0fd2018-11-22 17:56:39 +01007825 // if sco and call follow same curves, bypass forceUseForComm
7826 if ((callVolSrc != btScoVolSrc) &&
Eric Laurent2517af32020-11-25 15:31:27 +01007827 ((isVoiceVolSrc && isScoRequested) ||
Beibeif660a512023-02-28 17:00:34 +08007828 (isBtScoVolSrc && !(isScoRequested || isHAUsed))) &&
7829 !isSingleDeviceType(deviceTypes, AUDIO_DEVICE_OUT_TELEPHONY_TX)) {
Eric Laurent2517af32020-11-25 15:31:27 +01007830 ALOGV("%s cannot set volume group %d volume when is%srequested for comm", __func__,
Eric Laurent1a8b45f2022-04-13 16:01:47 +02007831 volumeSource, isScoRequested ? " " : " not ");
Eric Laurent571ef962020-07-24 11:43:48 -07007832 // Do not return an error here as AudioService will always set both voice call
7833 // and bluetooth SCO volumes due to stream aliasing.
7834 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07007835 }
jiabin9a3361e2019-10-01 09:38:30 -07007836 if (deviceTypes.empty()) {
7837 deviceTypes = outputDesc->devices().types();
chenxin2080986da2023-07-17 11:45:21 +08007838 index = curves.getVolumeIndex(deviceTypes);
7839 ALOGD("%s if deviceTypes is change from none to device %s, need get index %d",
7840 __func__, dumpDeviceTypes(deviceTypes).c_str(), index);
Eric Laurentc75307b2015-03-17 15:29:32 -07007841 }
Eric Laurent275e8e92014-11-30 15:14:47 -08007842
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00007843 if (curves.getVolumeIndexMin() < 0 || curves.getVolumeIndexMax() < 0) {
7844 ALOGE("invalid volume index range");
7845 return BAD_VALUE;
7846 }
7847
jiabin9a3361e2019-10-01 09:38:30 -07007848 float volumeDb = computeVolume(curves, volumeSource, index, deviceTypes);
7849 if (outputDesc->isFixedVolume(deviceTypes) ||
Eric Laurent9698a4c2020-10-12 17:10:23 -07007850 // Force VoIP volume to max for bluetooth SCO device except if muted
7851 (index != 0 && (isVoiceVolSrc || isBtScoVolSrc) &&
jiabin9a3361e2019-10-01 09:38:30 -07007852 isSingleDeviceType(deviceTypes, audio_is_bluetooth_out_sco_device))) {
Eric Laurentffbc80f2015-03-18 18:30:19 -07007853 volumeDb = 0.0f;
Eric Laurent275e8e92014-11-30 15:14:47 -08007854 }
Francois Gaffie593634d2021-06-22 13:31:31 +02007855 const bool muted = (index == 0) && (volumeDb != 0.0f);
jiabin9a3361e2019-10-01 09:38:30 -07007856 outputDesc->setVolume(
Francois Gaffie593634d2021-06-22 13:31:31 +02007857 volumeDb, muted, volumeSource, curves.getStreamTypes(), deviceTypes, delayMs, force);
Eric Laurentc75307b2015-03-17 15:29:32 -07007858
Eric Laurente8f2c0f2021-08-17 11:17:19 +02007859 if (outputDesc == mPrimaryOutput && (isVoiceVolSrc || isBtScoVolSrc)) {
Eric Laurente552edb2014-03-10 17:42:56 -07007860 float voiceVolume;
Eric Laurentfad001d2019-06-11 19:17:57 -07007861 // 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 +01007862 if (isVoiceVolSrc) {
7863 voiceVolume = (float)index/(float)curves.getVolumeIndexMax();
Eric Laurente552edb2014-03-10 17:42:56 -07007864 } else {
Eric Laurentfad001d2019-06-11 19:17:57 -07007865 voiceVolume = index == 0 ? 0.0 : 1.0;
Eric Laurente552edb2014-03-10 17:42:56 -07007866 }
Eric Laurent18fba842016-03-31 14:41:26 -07007867 if (voiceVolume != mLastVoiceVolume) {
Eric Laurente552edb2014-03-10 17:42:56 -07007868 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
7869 mLastVoiceVolume = voiceVolume;
7870 }
7871 }
Eric Laurente552edb2014-03-10 17:42:56 -07007872 return NO_ERROR;
7873}
7874
Eric Laurentc75307b2015-03-17 15:29:32 -07007875void AudioPolicyManager::applyStreamVolumes(const sp<AudioOutputDescriptor>& outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07007876 const DeviceTypeSet& deviceTypes,
7877 int delayMs,
7878 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07007879{
jiabincd510522020-01-22 09:40:55 -08007880 ALOGVV("applyStreamVolumes() for device %s", dumpDeviceTypes(deviceTypes).c_str());
François Gaffieaaac0fd2018-11-22 17:56:39 +01007881 for (const auto &volumeGroup : mEngine->getVolumeGroups()) {
7882 auto &curves = getVolumeCurves(toVolumeSource(volumeGroup));
7883 checkAndSetVolume(curves, toVolumeSource(volumeGroup),
jiabin9a3361e2019-10-01 09:38:30 -07007884 curves.getVolumeIndex(deviceTypes),
7885 outputDesc, deviceTypes, delayMs, force);
Eric Laurente552edb2014-03-10 17:42:56 -07007886 }
7887}
7888
François Gaffiec005e562018-11-06 15:04:49 +01007889void AudioPolicyManager::setStrategyMute(product_strategy_t strategy,
7890 bool on,
7891 const sp<AudioOutputDescriptor>& outputDesc,
7892 int delayMs,
jiabin9a3361e2019-10-01 09:38:30 -07007893 DeviceTypeSet deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07007894{
François Gaffieaaac0fd2018-11-22 17:56:39 +01007895 std::vector<VolumeSource> sourcesToMute;
7896 for (auto attributes: mEngine->getAllAttributesForProductStrategy(strategy)) {
7897 ALOGVV("%s() attributes %s, mute %d, output ID %d", __func__,
7898 toString(attributes).c_str(), on, outputDesc->getId());
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007899 VolumeSource source = toVolumeSource(attributes, false);
7900 if ((source != VOLUME_SOURCE_NONE) &&
7901 (std::find(begin(sourcesToMute), end(sourcesToMute), source)
7902 == end(sourcesToMute))) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007903 sourcesToMute.push_back(source);
7904 }
Eric Laurente552edb2014-03-10 17:42:56 -07007905 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01007906 for (auto source : sourcesToMute) {
jiabin9a3361e2019-10-01 09:38:30 -07007907 setVolumeSourceMute(source, on, outputDesc, delayMs, deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007908 }
7909
Eric Laurente552edb2014-03-10 17:42:56 -07007910}
7911
François Gaffieaaac0fd2018-11-22 17:56:39 +01007912void AudioPolicyManager::setVolumeSourceMute(VolumeSource volumeSource,
7913 bool on,
7914 const sp<AudioOutputDescriptor>& outputDesc,
7915 int delayMs,
jiabin9a3361e2019-10-01 09:38:30 -07007916 DeviceTypeSet deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07007917{
jiabin9a3361e2019-10-01 09:38:30 -07007918 if (deviceTypes.empty()) {
7919 deviceTypes = outputDesc->devices().types();
Eric Laurente552edb2014-03-10 17:42:56 -07007920 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01007921 auto &curves = getVolumeCurves(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07007922 if (on) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007923 if (!outputDesc->isMuted(volumeSource)) {
Eric Laurentf5aa58d2019-02-22 18:20:11 -08007924 if (curves.canBeMuted() &&
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007925 (volumeSource != toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01007926 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) ==
7927 AUDIO_POLICY_FORCE_NONE))) {
jiabin9a3361e2019-10-01 09:38:30 -07007928 checkAndSetVolume(curves, volumeSource, 0, outputDesc, deviceTypes, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07007929 }
7930 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01007931 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not
7932 // ignored
7933 outputDesc->incMuteCount(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07007934 } else {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007935 if (!outputDesc->isMuted(volumeSource)) {
7936 ALOGV("%s unmuting non muted attributes!", __func__);
Eric Laurente552edb2014-03-10 17:42:56 -07007937 return;
7938 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01007939 if (outputDesc->decMuteCount(volumeSource) == 0) {
7940 checkAndSetVolume(curves, volumeSource,
jiabin9a3361e2019-10-01 09:38:30 -07007941 curves.getVolumeIndex(deviceTypes),
Eric Laurentc75307b2015-03-17 15:29:32 -07007942 outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07007943 deviceTypes,
Eric Laurente552edb2014-03-10 17:42:56 -07007944 delayMs);
7945 }
7946 }
7947}
7948
François Gaffie53615e22015-03-19 09:24:12 +01007949bool AudioPolicyManager::isValidAttributes(const audio_attributes_t *paa)
7950{
François Gaffiec005e562018-11-06 15:04:49 +01007951 // has flags that map to a stream type?
Eric Laurente83b55d2014-11-14 10:06:21 -08007952 if ((paa->flags & (AUDIO_FLAG_AUDIBILITY_ENFORCED | AUDIO_FLAG_SCO | AUDIO_FLAG_BEACON)) != 0) {
7953 return true;
7954 }
7955
7956 // has known usage?
7957 switch (paa->usage) {
7958 case AUDIO_USAGE_UNKNOWN:
7959 case AUDIO_USAGE_MEDIA:
7960 case AUDIO_USAGE_VOICE_COMMUNICATION:
7961 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
7962 case AUDIO_USAGE_ALARM:
7963 case AUDIO_USAGE_NOTIFICATION:
7964 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
7965 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
7966 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
7967 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
7968 case AUDIO_USAGE_NOTIFICATION_EVENT:
7969 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
7970 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
7971 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
7972 case AUDIO_USAGE_GAME:
Eric Laurent275e8e92014-11-30 15:14:47 -08007973 case AUDIO_USAGE_VIRTUAL_SOURCE:
Jean-Michel Trivi36867762016-12-29 12:03:28 -08007974 case AUDIO_USAGE_ASSISTANT:
Eric Laurent21777f82019-12-06 18:12:06 -08007975 case AUDIO_USAGE_CALL_ASSISTANT:
Hayden Gomes524159d2019-12-23 14:41:47 -08007976 case AUDIO_USAGE_EMERGENCY:
7977 case AUDIO_USAGE_SAFETY:
7978 case AUDIO_USAGE_VEHICLE_STATUS:
7979 case AUDIO_USAGE_ANNOUNCEMENT:
Eric Laurente83b55d2014-11-14 10:06:21 -08007980 break;
7981 default:
7982 return false;
7983 }
7984 return true;
7985}
7986
François Gaffie2110e042015-03-24 08:41:51 +01007987audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
7988{
7989 return mEngine->getForceUse(usage);
7990}
7991
Eric Laurent96d1dda2022-03-14 17:14:19 +01007992bool AudioPolicyManager::isInCall() const {
François Gaffie2110e042015-03-24 08:41:51 +01007993 return isStateInCall(mEngine->getPhoneState());
7994}
7995
Eric Laurent96d1dda2022-03-14 17:14:19 +01007996bool AudioPolicyManager::isStateInCall(int state) const {
François Gaffie2110e042015-03-24 08:41:51 +01007997 return is_state_in_call(state);
7998}
7999
Eric Laurentf9cccec2022-11-16 19:12:00 +01008000bool AudioPolicyManager::isCallAudioAccessible() const {
Eric Laurent74b71512019-11-06 17:21:57 -08008001 audio_mode_t mode = mEngine->getPhoneState();
8002 return (mode == AUDIO_MODE_IN_CALL)
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01008003 || (mode == AUDIO_MODE_CALL_SCREEN)
8004 || (mode == AUDIO_MODE_CALL_REDIRECT);
Eric Laurent74b71512019-11-06 17:21:57 -08008005}
8006
Eric Laurentf9cccec2022-11-16 19:12:00 +01008007bool AudioPolicyManager::isInCallOrScreening() const {
8008 audio_mode_t mode = mEngine->getPhoneState();
8009 return isStateInCall(mode) || mode == AUDIO_MODE_CALL_SCREEN;
8010}
8011
Eric Laurentd60560a2015-04-10 11:31:20 -07008012void AudioPolicyManager::cleanUpForDevice(const sp<DeviceDescriptor>& deviceDesc)
8013{
8014 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07008015 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008016 if (sourceDesc->isConnected() && (sourceDesc->srcDevice()->equals(deviceDesc) ||
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02008017 sourceDesc->sinkDevice()->equals(deviceDesc))
8018 && !isCallRxAudioSource(sourceDesc)) {
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008019 disconnectAudioSource(sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07008020 }
8021 }
8022
8023 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
8024 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
8025 bool release = false;
8026 for (size_t j = 0; j < patchDesc->mPatch.num_sources && !release; j++) {
8027 const struct audio_port_config *source = &patchDesc->mPatch.sources[j];
8028 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
8029 source->ext.device.type == deviceDesc->type()) {
8030 release = true;
8031 }
8032 }
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008033 const char *address = deviceDesc->address().c_str();
Eric Laurentd60560a2015-04-10 11:31:20 -07008034 for (size_t j = 0; j < patchDesc->mPatch.num_sinks && !release; j++) {
8035 const struct audio_port_config *sink = &patchDesc->mPatch.sinks[j];
8036 if (sink->type == AUDIO_PORT_TYPE_DEVICE &&
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008037 sink->ext.device.type == deviceDesc->type() &&
8038 (strnlen(address, AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0
8039 || strncmp(sink->ext.device.address, address,
8040 AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0)) {
Eric Laurentd60560a2015-04-10 11:31:20 -07008041 release = true;
8042 }
8043 }
8044 if (release) {
François Gaffieafd4cea2019-11-18 15:50:22 +01008045 ALOGV("%s releasing patch %u", __FUNCTION__, patchDesc->getHandle());
8046 releaseAudioPatch(patchDesc->getHandle(), patchDesc->getUid());
Eric Laurentd60560a2015-04-10 11:31:20 -07008047 }
8048 }
Francois Gaffie716e1432019-01-14 16:58:59 +01008049
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01008050 mInputs.clearSessionRoutesForDevice(deviceDesc);
8051
Francois Gaffie716e1432019-01-14 16:58:59 +01008052 mHwModules.cleanUpForDevice(deviceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07008053}
8054
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008055void AudioPolicyManager::modifySurroundFormats(
8056 const sp<DeviceDescriptor>& devDesc, FormatVector *formatsPtr) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008057 std::unordered_set<audio_format_t> enforcedSurround(
8058 devDesc->encodedFormats().begin(), devDesc->encodedFormats().end());
Mikhail Naganov100f0122018-11-29 11:22:16 -08008059 std::unordered_set<audio_format_t> allSurround; // A flat set of all known surround formats
Mikhail Naganov68e3f642023-04-28 13:06:32 -07008060 for (const auto& pair : mConfig->getSurroundFormats()) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008061 allSurround.insert(pair.first);
8062 for (const auto& subformat : pair.second) allSurround.insert(subformat);
8063 }
Phil Burk09bc4612016-02-24 15:58:15 -08008064
8065 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
8066 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Phil Burk0709b0a2016-03-31 12:54:57 -07008067 ALOGD("%s: forced use = %d", __FUNCTION__, forceUse);
Mikhail Naganov100f0122018-11-29 11:22:16 -08008068 // This is the resulting set of formats depending on the surround mode:
8069 // 'all surround' = allSurround
8070 // 'enforced surround' = enforcedSurround [may include IEC69137 which isn't raw surround fmt]
8071 // 'non-surround' = not in 'all surround' and not in 'enforced surround'
8072 // 'manual surround' = mManualSurroundFormats
8073 // AUTO: formats v 'enforced surround'
8074 // ALWAYS: formats v 'all surround' v 'enforced surround'
8075 // NEVER: formats ^ 'non-surround'
8076 // MANUAL: formats ^ ('non-surround' v 'manual surround' v (IEC69137 ^ 'enforced surround'))
Phil Burk09bc4612016-02-24 15:58:15 -08008077
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008078 std::unordered_set<audio_format_t> formatSet;
8079 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL
8080 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008081 // formatSet is (formats ^ 'non-surround')
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008082 for (auto formatIter = formatsPtr->begin(); formatIter != formatsPtr->end(); ++formatIter) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008083 if (allSurround.count(*formatIter) == 0 && enforcedSurround.count(*formatIter) == 0) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008084 formatSet.insert(*formatIter);
8085 }
8086 }
8087 } else {
8088 formatSet.insert(formatsPtr->begin(), formatsPtr->end());
8089 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08008090 formatsPtr->clear(); // Re-filled from the formatSet at the end.
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008091
jiabin81772902018-04-02 17:52:27 -07008092 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008093 formatSet.insert(mManualSurroundFormats.begin(), mManualSurroundFormats.end());
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008094 // Enable IEC61937 when in MANUAL mode if it's enforced for this device.
8095 if (enforcedSurround.count(AUDIO_FORMAT_IEC61937) != 0) {
8096 formatSet.insert(AUDIO_FORMAT_IEC61937);
Phil Burk09bc4612016-02-24 15:58:15 -08008097 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08008098 } else if (forceUse != AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) { // AUTO or ALWAYS
8099 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS) {
8100 formatSet.insert(allSurround.begin(), allSurround.end());
Phil Burk07ac1142016-03-25 13:39:29 -07008101 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08008102 formatSet.insert(enforcedSurround.begin(), enforcedSurround.end());
Phil Burk09bc4612016-02-24 15:58:15 -08008103 }
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008104 for (const auto& format : formatSet) {
jiabin06e4bab2019-07-29 10:13:34 -07008105 formatsPtr->push_back(format);
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008106 }
Phil Burk0709b0a2016-03-31 12:54:57 -07008107}
8108
jiabin06e4bab2019-07-29 10:13:34 -07008109void AudioPolicyManager::modifySurroundChannelMasks(ChannelMaskSet *channelMasksPtr) {
8110 ChannelMaskSet &channelMasks = *channelMasksPtr;
Phil Burk0709b0a2016-03-31 12:54:57 -07008111 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
8112 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
8113
8114 // If NEVER, then remove support for channelMasks > stereo.
8115 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
jiabin06e4bab2019-07-29 10:13:34 -07008116 for (auto it = channelMasks.begin(); it != channelMasks.end();) {
8117 audio_channel_mask_t channelMask = *it;
Phil Burk0709b0a2016-03-31 12:54:57 -07008118 if (channelMask & ~AUDIO_CHANNEL_OUT_STEREO) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01008119 ALOGV("%s: force NEVER, so remove channelMask 0x%08x", __FUNCTION__, channelMask);
jiabin06e4bab2019-07-29 10:13:34 -07008120 it = channelMasks.erase(it);
Phil Burk0709b0a2016-03-31 12:54:57 -07008121 } else {
jiabin06e4bab2019-07-29 10:13:34 -07008122 ++it;
Phil Burk0709b0a2016-03-31 12:54:57 -07008123 }
8124 }
jiabin81772902018-04-02 17:52:27 -07008125 // If ALWAYS or MANUAL, then make sure we at least support 5.1
8126 } else if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS
8127 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Phil Burk0709b0a2016-03-31 12:54:57 -07008128 bool supports5dot1 = false;
8129 // Are there any channel masks that can be considered "surround"?
Mikhail Naganovcf84e592017-12-07 11:25:11 -08008130 for (audio_channel_mask_t channelMask : channelMasks) {
Phil Burk0709b0a2016-03-31 12:54:57 -07008131 if ((channelMask & AUDIO_CHANNEL_OUT_5POINT1) == AUDIO_CHANNEL_OUT_5POINT1) {
8132 supports5dot1 = true;
8133 break;
8134 }
8135 }
8136 // If not then add 5.1 support.
8137 if (!supports5dot1) {
jiabin06e4bab2019-07-29 10:13:34 -07008138 channelMasks.insert(AUDIO_CHANNEL_OUT_5POINT1);
Eric Laurentfecbceb2021-02-09 14:46:43 +01008139 ALOGV("%s: force MANUAL or ALWAYS, so adding channelMask for 5.1 surround", __func__);
Phil Burk0709b0a2016-03-31 12:54:57 -07008140 }
Phil Burk09bc4612016-02-24 15:58:15 -08008141 }
8142}
8143
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008144void AudioPolicyManager::updateAudioProfiles(const sp<DeviceDescriptor>& devDesc,
Phil Burk00eeb322016-03-31 12:41:00 -07008145 audio_io_handle_t ioHandle,
François Gaffie112b0af2015-11-19 16:13:25 +01008146 AudioProfileVector &profiles)
8147{
8148 String8 reply;
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008149 audio_devices_t device = devDesc->type();
Phil Burk0709b0a2016-03-31 12:54:57 -07008150
François Gaffie112b0af2015-11-19 16:13:25 +01008151 // Format MUST be checked first to update the list of AudioProfile
8152 if (profiles.hasDynamicFormat()) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07008153 reply = mpClientInterface->getParameters(
8154 ioHandle, String8(AudioParameter::keyStreamSupportedFormats));
jiabin81772902018-04-02 17:52:27 -07008155 ALOGV("%s: supported formats %d, %s", __FUNCTION__, ioHandle, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08008156 AudioParameter repliedParameters(reply);
jiabinf26596b2023-04-12 18:56:39 +00008157 FormatVector formats;
Eric Laurent62e4bc52016-02-02 18:37:28 -08008158 if (repliedParameters.get(
jiabinf26596b2023-04-12 18:56:39 +00008159 String8(AudioParameter::keyStreamSupportedFormats), reply) == NO_ERROR) {
8160 formats = formatsFromString(reply.string());
8161 } else if (devDesc->hasValidAudioProfile()) {
8162 ALOGD("%s: using the device profiles", __func__);
8163 formats = devDesc->getAudioProfiles().getSupportedFormats();
8164 } else {
8165 ALOGE("%s: failed to retrieve format, bailing out", __func__);
François Gaffie112b0af2015-11-19 16:13:25 +01008166 return;
8167 }
Kriti Dangef6be8f2020-11-05 11:58:19 +01008168 mReportedFormatsMap[devDesc] = formats;
Mikhail Naganov100f0122018-11-29 11:22:16 -08008169 if (device == AUDIO_DEVICE_OUT_HDMI
8170 || isDeviceOfModule(devDesc, AUDIO_HARDWARE_MODULE_ID_MSD)) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008171 modifySurroundFormats(devDesc, &formats);
Phil Burk00eeb322016-03-31 12:41:00 -07008172 }
jiabin3e277cc2019-09-10 14:27:34 -07008173 addProfilesForFormats(profiles, formats);
François Gaffie112b0af2015-11-19 16:13:25 +01008174 }
François Gaffie112b0af2015-11-19 16:13:25 +01008175
Mikhail Naganovcf84e592017-12-07 11:25:11 -08008176 for (audio_format_t format : profiles.getSupportedFormats()) {
jiabinf26596b2023-04-12 18:56:39 +00008177 std::optional<ChannelMaskSet> channelMasks;
jiabin06e4bab2019-07-29 10:13:34 -07008178 SampleRateSet samplingRates;
François Gaffie112b0af2015-11-19 16:13:25 +01008179 AudioParameter requestedParameters;
Mikhail Naganov388360c2016-10-17 17:09:41 -07008180 requestedParameters.addInt(String8(AudioParameter::keyFormat), format);
François Gaffie112b0af2015-11-19 16:13:25 +01008181
8182 if (profiles.hasDynamicRateFor(format)) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07008183 reply = mpClientInterface->getParameters(
8184 ioHandle,
8185 requestedParameters.toString() + ";" +
8186 AudioParameter::keyStreamSupportedSamplingRates);
François Gaffie112b0af2015-11-19 16:13:25 +01008187 ALOGV("%s: supported sampling rates %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08008188 AudioParameter repliedParameters(reply);
8189 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07008190 String8(AudioParameter::keyStreamSupportedSamplingRates), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08008191 samplingRates = samplingRatesFromString(reply.string());
jiabinf26596b2023-04-12 18:56:39 +00008192 } else {
8193 samplingRates = devDesc->getAudioProfiles().getSampleRatesFor(format);
François Gaffie112b0af2015-11-19 16:13:25 +01008194 }
8195 }
8196 if (profiles.hasDynamicChannelsFor(format)) {
8197 reply = mpClientInterface->getParameters(ioHandle,
8198 requestedParameters.toString() + ";" +
Mikhail Naganov388360c2016-10-17 17:09:41 -07008199 AudioParameter::keyStreamSupportedChannels);
François Gaffie112b0af2015-11-19 16:13:25 +01008200 ALOGV("%s: supported channel masks %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08008201 AudioParameter repliedParameters(reply);
8202 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07008203 String8(AudioParameter::keyStreamSupportedChannels), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08008204 channelMasks = channelMasksFromString(reply.string());
jiabinf26596b2023-04-12 18:56:39 +00008205 } else {
8206 channelMasks = devDesc->getAudioProfiles().getChannelMasksFor(format);
8207 }
8208 if (channelMasks.has_value() && (device == AUDIO_DEVICE_OUT_HDMI
8209 || isDeviceOfModule(devDesc, AUDIO_HARDWARE_MODULE_ID_MSD))) {
8210 modifySurroundChannelMasks(&channelMasks.value());
François Gaffie112b0af2015-11-19 16:13:25 +01008211 }
8212 }
jiabin3e277cc2019-09-10 14:27:34 -07008213 addDynamicAudioProfileAndSort(
jiabinf26596b2023-04-12 18:56:39 +00008214 profiles, new AudioProfile(
8215 format, channelMasks.value_or(ChannelMaskSet()), samplingRates));
François Gaffie112b0af2015-11-19 16:13:25 +01008216 }
8217}
Eric Laurentd60560a2015-04-10 11:31:20 -07008218
Mikhail Naganovdc769682018-05-04 15:34:08 -07008219status_t AudioPolicyManager::installPatch(const char *caller,
8220 audio_patch_handle_t *patchHandle,
8221 AudioIODescriptorInterface *ioDescriptor,
8222 const struct audio_patch *patch,
8223 int delayMs)
8224{
8225 ssize_t index = mAudioPatches.indexOfKey(
8226 patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE ?
8227 *patchHandle : ioDescriptor->getPatchHandle());
8228 sp<AudioPatch> patchDesc;
8229 status_t status = installPatch(
8230 caller, index, patchHandle, patch, delayMs, mUidCached, &patchDesc);
8231 if (status == NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01008232 ioDescriptor->setPatchHandle(patchDesc->getHandle());
Mikhail Naganovdc769682018-05-04 15:34:08 -07008233 }
8234 return status;
8235}
8236
8237status_t AudioPolicyManager::installPatch(const char *caller,
8238 ssize_t index,
8239 audio_patch_handle_t *patchHandle,
8240 const struct audio_patch *patch,
8241 int delayMs,
8242 uid_t uid,
8243 sp<AudioPatch> *patchDescPtr)
8244{
8245 sp<AudioPatch> patchDesc;
8246 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
8247 if (index >= 0) {
8248 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01008249 afPatchHandle = patchDesc->getAfHandle();
Mikhail Naganovdc769682018-05-04 15:34:08 -07008250 }
8251
8252 status_t status = mpClientInterface->createAudioPatch(patch, &afPatchHandle, delayMs);
8253 ALOGV("%s() AF::createAudioPatch returned %d patchHandle %d num_sources %d num_sinks %d",
8254 caller, status, afPatchHandle, patch->num_sources, patch->num_sinks);
8255 if (status == NO_ERROR) {
8256 if (index < 0) {
8257 patchDesc = new AudioPatch(patch, uid);
François Gaffieafd4cea2019-11-18 15:50:22 +01008258 addAudioPatch(patchDesc->getHandle(), patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07008259 } else {
8260 patchDesc->mPatch = *patch;
8261 }
François Gaffieafd4cea2019-11-18 15:50:22 +01008262 patchDesc->setAfHandle(afPatchHandle);
Mikhail Naganovdc769682018-05-04 15:34:08 -07008263 if (patchHandle) {
François Gaffieafd4cea2019-11-18 15:50:22 +01008264 *patchHandle = patchDesc->getHandle();
Mikhail Naganovdc769682018-05-04 15:34:08 -07008265 }
8266 nextAudioPortGeneration();
8267 mpClientInterface->onAudioPatchListUpdate();
8268 }
8269 if (patchDescPtr) *patchDescPtr = patchDesc;
8270 return status;
8271}
8272
jiabinbce0c1d2020-10-05 11:20:18 -07008273bool AudioPolicyManager::areAllActiveTracksRerouted(const sp<SwAudioOutputDescriptor>& output)
8274{
8275 const TrackClientVector activeClients = output->getActiveClients();
8276 if (activeClients.empty()) {
8277 return true;
8278 }
8279 ssize_t index = mAudioPatches.indexOfKey(output->getPatchHandle());
8280 if (index < 0) {
8281 ALOGE("%s, no audio patch found while there are active clients on output %d",
8282 __func__, output->getId());
8283 return false;
8284 }
8285 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
8286 DeviceVector routedDevices;
8287 for (int i = 0; i < patchDesc->mPatch.num_sinks; ++i) {
8288 sp<DeviceDescriptor> device = mAvailableOutputDevices.getDeviceFromId(
8289 patchDesc->mPatch.sinks[i].id);
8290 if (device == nullptr) {
8291 ALOGE("%s, no audio device found with id(%d)",
8292 __func__, patchDesc->mPatch.sinks[i].id);
8293 return false;
8294 }
8295 routedDevices.add(device);
8296 }
8297 for (const auto& client : activeClients) {
jiabin49256852022-03-09 11:21:35 -08008298 if (client->isInvalid()) {
8299 // No need to take care about invalidated clients.
8300 continue;
8301 }
jiabinbce0c1d2020-10-05 11:20:18 -07008302 sp<DeviceDescriptor> preferredDevice =
8303 mAvailableOutputDevices.getDeviceFromId(client->preferredDeviceId());
8304 if (mEngine->getOutputDevicesForAttributes(
8305 client->attributes(), preferredDevice, false) == routedDevices) {
8306 return false;
8307 }
8308 }
8309 return true;
8310}
8311
8312sp<SwAudioOutputDescriptor> AudioPolicyManager::openOutputWithProfileAndDevice(
Eric Laurentb4f42a92022-01-17 17:37:31 +01008313 const sp<IOProfile>& profile, const DeviceVector& devices,
jiabina84c3d32022-12-02 18:59:55 +00008314 const audio_config_base_t *mixerConfig, const audio_config_t *halConfig,
8315 audio_output_flags_t flags)
jiabinbce0c1d2020-10-05 11:20:18 -07008316{
8317 for (const auto& device : devices) {
8318 // TODO: This should be checking if the profile supports the device combo.
8319 if (!profile->supportsDevice(device)) {
jiabina84c3d32022-12-02 18:59:55 +00008320 ALOGE("%s profile(%s) doesn't support device %#x", __func__, profile->getName().c_str(),
8321 device->type());
jiabinbce0c1d2020-10-05 11:20:18 -07008322 return nullptr;
8323 }
8324 }
8325 sp<SwAudioOutputDescriptor> desc = new SwAudioOutputDescriptor(profile, mpClientInterface);
8326 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
jiabina84c3d32022-12-02 18:59:55 +00008327 status_t status = desc->open(halConfig, mixerConfig, devices,
8328 AUDIO_STREAM_DEFAULT, flags, &output);
jiabinbce0c1d2020-10-05 11:20:18 -07008329 if (status != NO_ERROR) {
jiabina84c3d32022-12-02 18:59:55 +00008330 ALOGE("%s failed to open output %d", __func__, status);
jiabinbce0c1d2020-10-05 11:20:18 -07008331 return nullptr;
8332 }
8333
8334 // Here is where the out_set_parameters() for card & device gets called
8335 sp<DeviceDescriptor> device = devices.getDeviceForOpening();
8336 const audio_devices_t deviceType = device->type();
8337 const String8 &address = String8(device->address().c_str());
8338 if (!address.isEmpty()) {
8339 char *param = audio_device_address_to_parameter(deviceType, address.c_str());
8340 mpClientInterface->setParameters(output, String8(param));
8341 free(param);
8342 }
8343 updateAudioProfiles(device, output, profile->getAudioProfiles());
8344 if (!profile->hasValidAudioProfile()) {
8345 ALOGW("%s() missing param", __func__);
8346 desc->close();
8347 return nullptr;
jiabina84c3d32022-12-02 18:59:55 +00008348 } else if (profile->hasDynamicAudioProfile() && halConfig == nullptr) {
8349 // Reopen the output with the best audio profile picked by APM when the profile supports
8350 // dynamic audio profile and the hal config is not specified.
jiabinbce0c1d2020-10-05 11:20:18 -07008351 desc->close();
8352 output = AUDIO_IO_HANDLE_NONE;
8353 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
8354 profile->pickAudioProfile(
8355 config.sample_rate, config.channel_mask, config.format);
8356 config.offload_info.sample_rate = config.sample_rate;
8357 config.offload_info.channel_mask = config.channel_mask;
8358 config.offload_info.format = config.format;
8359
jiabina84c3d32022-12-02 18:59:55 +00008360 status = desc->open(&config, mixerConfig, devices, AUDIO_STREAM_DEFAULT, flags, &output);
jiabinbce0c1d2020-10-05 11:20:18 -07008361 if (status != NO_ERROR) {
8362 return nullptr;
8363 }
8364 }
8365
8366 addOutput(output, desc);
Eric Laurentb4f42a92022-01-17 17:37:31 +01008367
baek.kim -61c20122022-07-27 10:05:32 +00008368 sp<DeviceDescriptor> speaker = mAvailableOutputDevices.getDevice(
8369 AUDIO_DEVICE_OUT_SPEAKER, String8(""), AUDIO_FORMAT_DEFAULT);
8370
jiabinbce0c1d2020-10-05 11:20:18 -07008371 if (audio_is_remote_submix_device(deviceType) && address != "0") {
8372 sp<AudioPolicyMix> policyMix;
8373 if (mPolicyMixes.getAudioPolicyMix(deviceType, address, policyMix) == NO_ERROR) {
8374 policyMix->setOutput(desc);
8375 desc->mPolicyMix = policyMix;
8376 } else {
8377 ALOGW("checkOutputsForDevice() cannot find policy for address %s",
8378 address.string());
8379 }
8380
baek.kim -61c20122022-07-27 10:05:32 +00008381 } else if (hasPrimaryOutput() && speaker != nullptr
8382 && mPrimaryOutput->supportsDevice(speaker) && !desc->supportsDevice(speaker)
Eric Laurentb4f42a92022-01-17 17:37:31 +01008383 && ((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0)) {
8384 // no duplicated output for:
8385 // - direct outputs
8386 // - outputs used by dynamic policy mixes
baek.kim -61c20122022-07-27 10:05:32 +00008387 // - outputs that supports SPEAKER while the primary output does not.
jiabinbce0c1d2020-10-05 11:20:18 -07008388 audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE;
8389
8390 //TODO: configure audio effect output stage here
8391
8392 // open a duplicating output thread for the new output and the primary output
8393 sp<SwAudioOutputDescriptor> dupOutputDesc =
8394 new SwAudioOutputDescriptor(nullptr, mpClientInterface);
8395 status = dupOutputDesc->openDuplicating(mPrimaryOutput, desc, &duplicatedOutput);
8396 if (status == NO_ERROR) {
8397 // add duplicated output descriptor
8398 addOutput(duplicatedOutput, dupOutputDesc);
8399 } else {
8400 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
8401 mPrimaryOutput->mIoHandle, output);
8402 desc->close();
8403 removeOutput(output);
8404 nextAudioPortGeneration();
8405 return nullptr;
8406 }
8407 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02008408 if (mPrimaryOutput == nullptr && profile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
8409 ALOGV("%s(): re-assigning mPrimaryOutput", __func__);
8410 mPrimaryOutput = desc;
8411 }
jiabinbce0c1d2020-10-05 11:20:18 -07008412 return desc;
8413}
8414
jiabinf1c73972022-04-14 16:28:52 -07008415status_t AudioPolicyManager::getDevicesForAttributes(
8416 const audio_attributes_t &attr, DeviceVector &devices, bool forVolume) {
8417 // Devices are determined in the following precedence:
8418 //
8419 // 1) Devices associated with a dynamic policy matching the attributes. This is often
8420 // a remote submix from MIX_ROUTE_FLAG_LOOP_BACK.
8421 //
8422 // If no such dynamic policy then
8423 // 2) Devices containing an active client using setPreferredDevice
8424 // with same strategy as the attributes.
8425 // (from the default Engine::getOutputDevicesForAttributes() implementation).
8426 //
8427 // If no corresponding active client with setPreferredDevice then
8428 // 3) Devices associated with the strategy determined by the attributes
8429 // (from the default Engine::getOutputDevicesForAttributes() implementation).
8430 //
8431 // See related getOutputForAttrInt().
8432
8433 // check dynamic policies but only for primary descriptors (secondary not used for audible
8434 // audio routing, only used for duplication for playback capture)
8435 sp<AudioPolicyMix> policyMix;
Oscar Azucena873d10f2023-01-12 18:34:42 -08008436 bool unneededUsePrimaryOutputFromPolicyMixes = false;
jiabinf1c73972022-04-14 16:28:52 -07008437 status_t status = mPolicyMixes.getOutputForAttr(attr, AUDIO_CONFIG_BASE_INITIALIZER,
Oscar Azucena873d10f2023-01-12 18:34:42 -08008438 0 /*uid unknown here*/, AUDIO_SESSION_NONE, AUDIO_OUTPUT_FLAG_NONE,
8439 mAvailableOutputDevices, nullptr /* requestedDevice */, policyMix,
8440 nullptr /* secondaryMixes */, unneededUsePrimaryOutputFromPolicyMixes);
jiabinf1c73972022-04-14 16:28:52 -07008441 if (status != OK) {
8442 return status;
8443 }
8444
8445 if (policyMix != nullptr && policyMix->getOutput() != nullptr &&
8446 // For volume control, skip LOOPBACK mixes which use AUDIO_DEVICE_OUT_REMOTE_SUBMIX
8447 // as they are unaffected by device/stream volume
8448 // (per SwAudioOutputDescriptor::isFixedVolume()).
8449 (!forVolume || policyMix->mDeviceType != AUDIO_DEVICE_OUT_REMOTE_SUBMIX)
8450 ) {
8451 sp<DeviceDescriptor> deviceDesc = mAvailableOutputDevices.getDevice(
8452 policyMix->mDeviceType, policyMix->mDeviceAddress, AUDIO_FORMAT_DEFAULT);
8453 devices.add(deviceDesc);
8454 } else {
8455 // The default Engine::getOutputDevicesForAttributes() uses findPreferredDevice()
8456 // which selects setPreferredDevice if active. This means forVolume call
8457 // will take an active setPreferredDevice, if such exists.
8458
8459 devices = mEngine->getOutputDevicesForAttributes(
8460 attr, nullptr /* preferredDevice */, false /* fromCache */);
8461 }
8462
8463 if (forVolume) {
8464 // We alias the device AUDIO_DEVICE_OUT_SPEAKER_SAFE to AUDIO_DEVICE_OUT_SPEAKER
8465 // for single volume control in AudioService (such relationship should exist if
8466 // SPEAKER_SAFE is present).
8467 //
8468 // (This is unrelated to a different device grouping as Volume::getDeviceCategory)
8469 DeviceVector speakerSafeDevices =
8470 devices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER_SAFE);
8471 if (!speakerSafeDevices.isEmpty()) {
8472 devices.merge(mAvailableOutputDevices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER));
8473 devices.remove(speakerSafeDevices);
8474 }
8475 }
8476
8477 return NO_ERROR;
8478}
8479
8480status_t AudioPolicyManager::getProfilesForDevices(const DeviceVector& devices,
8481 AudioProfileVector& audioProfiles,
8482 uint32_t flags,
8483 bool isInput) {
8484 for (const auto& hwModule : mHwModules) {
8485 // the MSD module checks for different conditions
8486 if (strcmp(hwModule->getName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0) {
8487 continue;
8488 }
8489 IOProfileCollection ioProfiles = isInput ? hwModule->getInputProfiles()
8490 : hwModule->getOutputProfiles();
8491 for (const auto& profile : ioProfiles) {
8492 if (!profile->areAllDevicesSupported(devices) ||
8493 !profile->isCompatibleProfileForFlags(
8494 flags, false /*exactMatchRequiredForInputFlags*/)) {
8495 continue;
8496 }
8497 audioProfiles.addAllValidProfiles(profile->asAudioPort()->getAudioProfiles());
8498 }
8499 }
8500
8501 if (!isInput) {
8502 // add the direct profiles from MSD if present and has audio patches to all the output(s)
8503 const auto &msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
8504 if (msdModule != nullptr) {
8505 if (msdHasPatchesToAllDevices(devices.toTypeAddrVector())) {
8506 ALOGV("%s: MSD audio patches set to all output devices.", __func__);
8507 for (const auto &profile: msdModule->getOutputProfiles()) {
8508 if (!profile->asAudioPort()->isDirectOutput()) {
8509 continue;
8510 }
8511 audioProfiles.addAllValidProfiles(profile->asAudioPort()->getAudioProfiles());
8512 }
8513 } else {
8514 ALOGV("%s: MSD audio patches NOT set to all output devices.", __func__);
8515 }
8516 }
8517 }
8518
8519 return NO_ERROR;
8520}
8521
jiabin3ff8d7d2022-12-13 06:27:44 +00008522sp<SwAudioOutputDescriptor> AudioPolicyManager::reopenOutput(sp<SwAudioOutputDescriptor> outputDesc,
8523 const audio_config_t *config,
8524 audio_output_flags_t flags,
8525 const char* caller) {
jiabina84c3d32022-12-02 18:59:55 +00008526 closeOutput(outputDesc->mIoHandle);
8527 sp<SwAudioOutputDescriptor> preferredOutput = openOutputWithProfileAndDevice(
8528 outputDesc->mProfile, outputDesc->devices(), nullptr /*mixerConfig*/, config, flags);
8529 if (preferredOutput == nullptr) {
8530 ALOGE("%s failed to reopen output device=%d, caller=%s",
8531 __func__, outputDesc->devices()[0]->getId(), caller);
jiabina84c3d32022-12-02 18:59:55 +00008532 }
jiabin3ff8d7d2022-12-13 06:27:44 +00008533 return preferredOutput;
8534}
8535
8536void AudioPolicyManager::reopenOutputsWithDevices(
8537 const std::map<audio_io_handle_t, DeviceVector> &outputsToReopen) {
8538 for (const auto& [output, devices] : outputsToReopen) {
8539 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
8540 closeOutput(output);
8541 openOutputWithProfileAndDevice(desc->mProfile, devices);
8542 }
jiabina84c3d32022-12-02 18:59:55 +00008543}
8544
jiabinc44b3462022-12-08 12:52:31 -08008545PortHandleVector AudioPolicyManager::getClientsForStream(
8546 audio_stream_type_t streamType) const {
8547 PortHandleVector clients;
8548 for (size_t i = 0; i < mOutputs.size(); ++i) {
8549 PortHandleVector clientsForStream = mOutputs.valueAt(i)->getClientsForStream(streamType);
8550 clients.insert(clients.end(), clientsForStream.begin(), clientsForStream.end());
8551 }
8552 return clients;
8553}
8554
8555void AudioPolicyManager::invalidateStreams(StreamTypeVector streams) const {
8556 PortHandleVector clients;
8557 for (auto stream : streams) {
8558 PortHandleVector clientsForStream = getClientsForStream(stream);
8559 clients.insert(clients.end(), clientsForStream.begin(), clientsForStream.end());
8560 }
8561 mpClientInterface->invalidateTracks(clients);
8562}
8563
Mikhail Naganov1b2a7942017-12-08 10:18:09 -08008564} // namespace android