blob: b17177dcb6880eac30b8e86b6e159b92c1b28982 [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) {
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100462 DeviceDescriptorBase devDescr(device, device_address);
463 devDescr.setName(device_name);
464 return devDescr.writeToParcelable(aidlPort);
465}
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);
Eric Laurent16c66dd2019-05-01 17:54:10 -07001109 const audio_io_handle_t output = selectOutput(outputs);
Eric Laurente552edb2014-03-10 17:42:56 -07001110
François Gaffie11d30102018-11-02 16:09:09 +01001111 ALOGV("getOutput() stream %d selected devices %s, output %d", stream,
1112 devices.toString().c_str(), output);
Eric Laurentf4e63452017-11-06 19:31:46 +00001113 return output;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001114}
1115
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001116status_t AudioPolicyManager::getAudioAttributes(audio_attributes_t *dstAttr,
1117 const audio_attributes_t *srcAttr,
1118 audio_stream_type_t srcStream)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001119{
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001120 if (srcAttr != NULL) {
1121 if (!isValidAttributes(srcAttr)) {
1122 ALOGE("%s invalid attributes: usage=%d content=%d flags=0x%x tags=[%s]",
1123 __func__,
1124 srcAttr->usage, srcAttr->content_type, srcAttr->flags,
1125 srcAttr->tags);
1126 return BAD_VALUE;
1127 }
1128 *dstAttr = *srcAttr;
1129 } else {
1130 if (srcStream < AUDIO_STREAM_MIN || srcStream >= AUDIO_STREAM_PUBLIC_CNT) {
1131 ALOGE("%s: invalid stream type", __func__);
1132 return BAD_VALUE;
1133 }
François Gaffiec005e562018-11-06 15:04:49 +01001134 *dstAttr = mEngine->getAttributesForStreamType(srcStream);
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001135 }
Eric Laurent22fcda22019-05-17 16:28:47 -07001136
1137 // Only honor audibility enforced when required. The client will be
1138 // forced to reconnect if the forced usage changes.
1139 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Mikhail Naganov55773032020-10-01 15:08:13 -07001140 dstAttr->flags = static_cast<audio_flags_mask_t>(
1141 dstAttr->flags & ~AUDIO_FLAG_AUDIBILITY_ENFORCED);
Eric Laurent22fcda22019-05-17 16:28:47 -07001142 }
1143
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001144 return NO_ERROR;
1145}
1146
Kevin Rocard153f92d2018-12-18 18:33:28 -08001147status_t AudioPolicyManager::getOutputForAttrInt(
1148 audio_attributes_t *resultAttr,
1149 audio_io_handle_t *output,
1150 audio_session_t session,
1151 const audio_attributes_t *attr,
1152 audio_stream_type_t *stream,
1153 uid_t uid,
jiabinf1c73972022-04-14 16:28:52 -07001154 audio_config_t *config,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001155 audio_output_flags_t *flags,
1156 audio_port_handle_t *selectedDeviceId,
1157 bool *isRequestedDeviceForExclusiveUse,
Eric Laurentc529cf62020-04-17 18:19:10 -07001158 std::vector<sp<AudioPolicyMix>> *secondaryMixes,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001159 output_type_t *outputType,
jiabinc658e452022-10-21 20:52:21 +00001160 bool *isSpatialized,
1161 bool *isBitPerfect)
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001162{
François Gaffiec005e562018-11-06 15:04:49 +01001163 DeviceVector outputDevices;
Francois Gaffie716e1432019-01-14 16:58:59 +01001164 const audio_port_handle_t requestedPortId = *selectedDeviceId;
François Gaffie11d30102018-11-02 16:09:09 +01001165 DeviceVector msdDevices = getMsdAudioOutDevices();
François Gaffiec005e562018-11-06 15:04:49 +01001166 const sp<DeviceDescriptor> requestedDevice =
1167 mAvailableOutputDevices.getDeviceFromId(requestedPortId);
1168
Eric Laurent8a1095a2019-11-08 14:44:16 -08001169 *outputType = API_OUTPUT_INVALID;
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001170 *isSpatialized = false;
1171
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001172 status_t status = getAudioAttributes(resultAttr, attr, *stream);
1173 if (status != NO_ERROR) {
1174 return status;
Eric Laurent8f42ea12018-08-08 09:08:25 -07001175 }
Kevin Rocardb99cc752019-03-21 20:52:24 -07001176 if (auto it = mAllowedCapturePolicies.find(uid); it != end(mAllowedCapturePolicies)) {
Mikhail Naganov55773032020-10-01 15:08:13 -07001177 resultAttr->flags = static_cast<audio_flags_mask_t>(resultAttr->flags | it->second);
Kevin Rocardb99cc752019-03-21 20:52:24 -07001178 }
François Gaffiec005e562018-11-06 15:04:49 +01001179 *stream = mEngine->getStreamTypeForAttributes(*resultAttr);
Eric Laurent8f42ea12018-08-08 09:08:25 -07001180
François Gaffiec005e562018-11-06 15:04:49 +01001181 ALOGV("%s() attributes=%s stream=%s session %d selectedDeviceId %d", __func__,
1182 toString(*resultAttr).c_str(), toString(*stream).c_str(), session, requestedPortId);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001183
Oscar Azucena873d10f2023-01-12 18:34:42 -08001184 bool usePrimaryOutputFromPolicyMixes = false;
1185
Kevin Rocard153f92d2018-12-18 18:33:28 -08001186 // The primary output is the explicit routing (eg. setPreferredDevice) if specified,
1187 // otherwise, fallback to the dynamic policies, if none match, query the engine.
1188 // Secondary outputs are always found by dynamic policies as the engine do not support them
Eric Laurentc529cf62020-04-17 18:19:10 -07001189 sp<AudioPolicyMix> primaryMix;
Dean Wheatleyd082f472022-02-04 11:10:48 +11001190 const audio_config_base_t clientConfig = {.sample_rate = config->sample_rate,
1191 .channel_mask = config->channel_mask,
1192 .format = config->format,
1193 };
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02001194 status = mPolicyMixes.getOutputForAttr(*resultAttr, clientConfig, uid, session, *flags,
Oscar Azucena873d10f2023-01-12 18:34:42 -08001195 mAvailableOutputDevices, requestedDevice, primaryMix,
1196 secondaryMixes, usePrimaryOutputFromPolicyMixes);
Kevin Rocard94114a22019-04-01 19:38:23 -07001197 if (status != OK) {
1198 return status;
Kevin Rocard153f92d2018-12-18 18:33:28 -08001199 }
Kevin Rocard94114a22019-04-01 19:38:23 -07001200
Kevin Rocard153f92d2018-12-18 18:33:28 -08001201 // FIXME: in case of RENDER policy, the output capabilities should be checked
Dean Wheatleyd082f472022-02-04 11:10:48 +11001202 if ((secondaryMixes != nullptr && !secondaryMixes->empty())
1203 && !audio_is_linear_pcm(config->format)) {
1204 ALOGD("%s: rejecting request as secondary mixes only support pcm", __func__);
Kevin Rocard153f92d2018-12-18 18:33:28 -08001205 return BAD_VALUE;
1206 }
1207 if (usePrimaryOutputFromPolicyMixes) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001208 sp<DeviceDescriptor> deviceDesc =
1209 mAvailableOutputDevices.getDevice(primaryMix->mDeviceType,
1210 primaryMix->mDeviceAddress,
1211 AUDIO_FORMAT_DEFAULT);
1212 sp<SwAudioOutputDescriptor> policyDesc = primaryMix->getOutput();
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001213 bool tryDirectForFlags = policyDesc == nullptr ||
1214 (policyDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT);
1215 // if a direct output can be opened to deliver the track's multi-channel content to the
1216 // output rather than being downmixed by the primary output, then use this direct
1217 // output by by-passing the primary mix if possible, otherwise fall-through to primary
1218 // mix.
1219 bool tryDirectForChannelMask = policyDesc != nullptr
1220 && (audio_channel_count_from_out_mask(policyDesc->getConfig().channel_mask) <
1221 audio_channel_count_from_out_mask(config->channel_mask));
1222 if (deviceDesc != nullptr && (tryDirectForFlags || tryDirectForChannelMask)) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001223 audio_io_handle_t newOutput;
1224 status = openDirectOutput(
1225 *stream, session, config,
1226 (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT),
1227 DeviceVector(deviceDesc), &newOutput);
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001228 if (status == NO_ERROR) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001229 policyDesc = mOutputs.valueFor(newOutput);
1230 primaryMix->setOutput(policyDesc);
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001231 } else if (tryDirectForFlags) {
1232 policyDesc = nullptr;
1233 } // otherwise use primary if available.
Eric Laurentc529cf62020-04-17 18:19:10 -07001234 }
1235 if (policyDesc != nullptr) {
1236 policyDesc->mPolicyMix = primaryMix;
1237 *output = policyDesc->mIoHandle;
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08001238 *selectedDeviceId = deviceDesc != 0 ? deviceDesc->getId() : AUDIO_PORT_HANDLE_NONE;
Eric Laurent8a1095a2019-11-08 14:44:16 -08001239
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08001240 ALOGV("getOutputForAttr() returns output %d", *output);
1241 if (resultAttr->usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
1242 *outputType = API_OUT_MIX_PLAYBACK;
1243 } else {
1244 *outputType = API_OUTPUT_LEGACY;
1245 }
1246 return NO_ERROR;
Eric Laurent8a1095a2019-11-08 14:44:16 -08001247 }
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001248 }
François Gaffiec005e562018-11-06 15:04:49 +01001249 // Virtual sources must always be dynamicaly or explicitly routed
1250 if (resultAttr->usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
1251 ALOGW("getOutputForAttr() no policy mix found for usage AUDIO_USAGE_VIRTUAL_SOURCE");
1252 return BAD_VALUE;
1253 }
1254 // explicit routing managed by getDeviceForStrategy in APM is now handled by engine
1255 // in order to let the choice of the order to future vendor engine
1256 outputDevices = mEngine->getOutputDevicesForAttributes(*resultAttr, requestedDevice, false);
Scott Randolph7b1fd232018-06-18 15:33:03 -07001257
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001258 if ((resultAttr->flags & AUDIO_FLAG_HW_AV_SYNC) != 0) {
Nadav Bar766fb022018-01-07 12:18:03 +02001259 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
Eric Laurent93c3d412014-08-01 14:48:35 -07001260 }
1261
Nadav Barb2f18162018-07-18 13:01:53 +03001262 // Set incall music only if device was explicitly set, and fallback to the device which is
1263 // chosen by the engine if not.
1264 // FIXME: provide a more generic approach which is not device specific and move this back
1265 // to getOutputForDevice.
Nadav Bar20919492018-11-20 10:20:51 +02001266 // TODO: Remove check of AUDIO_STREAM_MUSIC once migration is completed on the app side.
jiabin9a3361e2019-10-01 09:38:30 -07001267 if (outputDevices.onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_TELEPHONY_TX) &&
François Gaffiec005e562018-11-06 15:04:49 +01001268 (*stream == AUDIO_STREAM_MUSIC || resultAttr->usage == AUDIO_USAGE_VOICE_COMMUNICATION) &&
Nadav Barb2f18162018-07-18 13:01:53 +03001269 audio_is_linear_pcm(config->format) &&
Eric Laurent74b71512019-11-06 17:21:57 -08001270 isCallAudioAccessible()) {
Francois Gaffie716e1432019-01-14 16:58:59 +01001271 if (requestedPortId != AUDIO_PORT_HANDLE_NONE) {
Nadav Barb2f18162018-07-18 13:01:53 +03001272 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_INCALL_MUSIC;
François Gaffief579db52018-11-13 11:25:16 +01001273 *isRequestedDeviceForExclusiveUse = true;
Nadav Barb2f18162018-07-18 13:01:53 +03001274 }
1275 }
1276
François Gaffiec005e562018-11-06 15:04:49 +01001277 ALOGV("%s() device %s, sampling rate %d, format %#x, channel mask %#x, flags %#x stream %s",
1278 __func__, outputDevices.toString().c_str(), config->sample_rate, config->format,
1279 config->channel_mask, *flags, toString(*stream).c_str());
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001280
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001281 *output = AUDIO_IO_HANDLE_NONE;
François Gaffie11d30102018-11-02 16:09:09 +01001282 if (!msdDevices.isEmpty()) {
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001283 *output = getOutputForDevices(msdDevices, session, resultAttr, config, flags, isSpatialized);
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001284 if (*output != AUDIO_IO_HANDLE_NONE && setMsdOutputPatches(&outputDevices) == NO_ERROR) {
François Gaffiec005e562018-11-06 15:04:49 +01001285 ALOGV("%s() Using MSD devices %s instead of devices %s",
1286 __func__, msdDevices.toString().c_str(), outputDevices.toString().c_str());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001287 } else {
1288 *output = AUDIO_IO_HANDLE_NONE;
1289 }
1290 }
1291 if (*output == AUDIO_IO_HANDLE_NONE) {
jiabina84c3d32022-12-02 18:59:55 +00001292 sp<PreferredMixerAttributesInfo> info = nullptr;
1293 if (outputDevices.size() == 1) {
1294 info = getPreferredMixerAttributesInfo(
1295 outputDevices.itemAt(0)->getId(),
jiabind9a58d32023-06-01 17:57:30 +00001296 mEngine->getProductStrategyForAttributes(*resultAttr),
1297 true /*activeBitPerfectPreferred*/);
jiabin5eaf0962022-12-20 20:11:38 +00001298 // Only use preferred mixer if the uid matches or the preferred mixer is bit-perfect
1299 // and it is currently active.
1300 if (info != nullptr && info->getUid() != uid &&
1301 ((info->getFlags() & AUDIO_OUTPUT_FLAG_BIT_PERFECT) == AUDIO_OUTPUT_FLAG_NONE ||
1302 info->getActiveClientCount() == 0)) {
jiabina84c3d32022-12-02 18:59:55 +00001303 info = nullptr;
1304 }
1305 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001306 *output = getOutputForDevices(outputDevices, session, resultAttr, config,
jiabina84c3d32022-12-02 18:59:55 +00001307 flags, isSpatialized, info, resultAttr->flags & AUDIO_FLAG_MUTE_HAPTIC);
jiabin5eaf0962022-12-20 20:11:38 +00001308 // The client will be active if the client is currently preferred mixer owner and the
1309 // requested configuration matches the preferred mixer configuration.
jiabinc658e452022-10-21 20:52:21 +00001310 *isBitPerfect = (info != nullptr
1311 && (info->getFlags() & AUDIO_OUTPUT_FLAG_BIT_PERFECT) != AUDIO_OUTPUT_FLAG_NONE
jiabin5eaf0962022-12-20 20:11:38 +00001312 && info->getUid() == uid
1313 && *output != AUDIO_IO_HANDLE_NONE
1314 // When bit-perfect output is selected for the preferred mixer attributes owner,
1315 // only need to consider the config matches.
1316 && mOutputs.valueFor(*output)->isConfigurationMatched(
1317 clientConfig, AUDIO_OUTPUT_FLAG_NONE));
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001318 }
Eric Laurente83b55d2014-11-14 10:06:21 -08001319 if (*output == AUDIO_IO_HANDLE_NONE) {
jiabinf1c73972022-04-14 16:28:52 -07001320 AudioProfileVector profiles;
1321 status_t ret = getProfilesForDevices(outputDevices, profiles, *flags, false /*isInput*/);
1322 if (ret == NO_ERROR && !profiles.empty()) {
1323 config->channel_mask = profiles[0]->getChannels().empty() ? config->channel_mask
1324 : *profiles[0]->getChannels().begin();
1325 config->sample_rate = profiles[0]->getSampleRates().empty() ? config->sample_rate
1326 : *profiles[0]->getSampleRates().begin();
1327 config->format = profiles[0]->getFormat();
1328 }
Eric Laurente83b55d2014-11-14 10:06:21 -08001329 return INVALID_OPERATION;
1330 }
Paul McLeanaa981192015-03-21 09:55:15 -07001331
François Gaffiec005e562018-11-06 15:04:49 +01001332 *selectedDeviceId = getFirstDeviceId(outputDevices);
Michael Chan6fb34492020-12-08 15:44:49 +11001333 for (auto &outputDevice : outputDevices) {
Mikhail Naganov68e3f642023-04-28 13:06:32 -07001334 if (outputDevice->getId() == mConfig->getDefaultOutputDevice()->getId()) {
Michael Chan6fb34492020-12-08 15:44:49 +11001335 *selectedDeviceId = outputDevice->getId();
1336 break;
1337 }
1338 }
Eric Laurent2ac76942017-06-22 17:17:09 -07001339
Eric Laurent8a1095a2019-11-08 14:44:16 -08001340 if (outputDevices.onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_TELEPHONY_TX)) {
1341 *outputType = API_OUTPUT_TELEPHONY_TX;
1342 } else {
1343 *outputType = API_OUTPUT_LEGACY;
1344 }
1345
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001346 ALOGV("%s returns output %d selectedDeviceId %d", __func__, *output, *selectedDeviceId);
1347
1348 return NO_ERROR;
1349}
1350
1351status_t AudioPolicyManager::getOutputForAttr(const audio_attributes_t *attr,
1352 audio_io_handle_t *output,
1353 audio_session_t session,
1354 audio_stream_type_t *stream,
Svet Ganov3e5f14f2021-05-13 22:51:08 +00001355 const AttributionSourceState& attributionSource,
jiabinf1c73972022-04-14 16:28:52 -07001356 audio_config_t *config,
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001357 audio_output_flags_t *flags,
1358 audio_port_handle_t *selectedDeviceId,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001359 audio_port_handle_t *portId,
Eric Laurent8a1095a2019-11-08 14:44:16 -08001360 std::vector<audio_io_handle_t> *secondaryOutputs,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001361 output_type_t *outputType,
jiabinc658e452022-10-21 20:52:21 +00001362 bool *isSpatialized,
1363 bool *isBitPerfect)
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001364{
1365 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
1366 if (*portId != AUDIO_PORT_HANDLE_NONE) {
1367 return INVALID_OPERATION;
1368 }
Philip P. Moltmannbda45752020-07-17 16:41:18 -07001369 const uid_t uid = VALUE_OR_RETURN_STATUS(
Svet Ganov3e5f14f2021-05-13 22:51:08 +00001370 aidl2legacy_int32_t_uid_t(attributionSource.uid));
Francois Gaffie716e1432019-01-14 16:58:59 +01001371 const audio_port_handle_t requestedPortId = *selectedDeviceId;
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001372 audio_attributes_t resultAttr;
François Gaffief579db52018-11-13 11:25:16 +01001373 bool isRequestedDeviceForExclusiveUse = false;
Eric Laurentc529cf62020-04-17 18:19:10 -07001374 std::vector<sp<AudioPolicyMix>> secondaryMixes;
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001375 const sp<DeviceDescriptor> requestedDevice =
1376 mAvailableOutputDevices.getDeviceFromId(requestedPortId);
1377
1378 // Prevent from storing invalid requested device id in clients
1379 const audio_port_handle_t sanitizedRequestedPortId =
1380 requestedDevice != nullptr ? requestedPortId : AUDIO_PORT_HANDLE_NONE;
1381 *selectedDeviceId = sanitizedRequestedPortId;
1382
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001383 status_t status = getOutputForAttrInt(&resultAttr, output, session, attr, stream, uid,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001384 config, flags, selectedDeviceId, &isRequestedDeviceForExclusiveUse,
jiabinc658e452022-10-21 20:52:21 +00001385 secondaryOutputs != nullptr ? &secondaryMixes : nullptr, outputType, isSpatialized,
1386 isBitPerfect);
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001387 if (status != NO_ERROR) {
1388 return status;
1389 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001390 std::vector<wp<SwAudioOutputDescriptor>> weakSecondaryOutputDescs;
Eric Laurentc529cf62020-04-17 18:19:10 -07001391 if (secondaryOutputs != nullptr) {
1392 for (auto &secondaryMix : secondaryMixes) {
1393 sp<SwAudioOutputDescriptor> outputDesc = secondaryMix->getOutput();
1394 if (outputDesc != nullptr &&
1395 outputDesc->mIoHandle != AUDIO_IO_HANDLE_NONE) {
1396 secondaryOutputs->push_back(outputDesc->mIoHandle);
1397 weakSecondaryOutputDescs.push_back(outputDesc);
1398 }
1399 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001400 }
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001401
Eric Laurent8fc147b2018-07-22 19:13:55 -07001402 audio_config_base_t clientConfig = {.sample_rate = config->sample_rate,
Nick Desaulniersa30e3202019-10-18 13:38:23 -07001403 .channel_mask = config->channel_mask,
Eric Laurent8fc147b2018-07-22 19:13:55 -07001404 .format = config->format,
Nick Desaulniersa30e3202019-10-18 13:38:23 -07001405 };
jiabin4ef93452019-09-10 14:29:54 -07001406 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurent8f42ea12018-08-08 09:08:25 -07001407
Eric Laurentc209fe42020-06-05 18:11:23 -07001408 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(*output);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001409 sp<TrackClientDescriptor> clientDesc =
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001410 new TrackClientDescriptor(*portId, uid, session, resultAttr, clientConfig,
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001411 sanitizedRequestedPortId, *stream,
François Gaffiec005e562018-11-06 15:04:49 +01001412 mEngine->getProductStrategyForAttributes(resultAttr),
François Gaffieaaac0fd2018-11-22 17:56:39 +01001413 toVolumeSource(resultAttr),
Kevin Rocard153f92d2018-12-18 18:33:28 -08001414 *flags, isRequestedDeviceForExclusiveUse,
Eric Laurentc209fe42020-06-05 18:11:23 -07001415 std::move(weakSecondaryOutputDescs),
1416 outputDesc->mPolicyMix);
Andy Hung39efb7a2018-09-26 15:39:28 -07001417 outputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001418
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001419 ALOGV("%s() returns output %d requestedPortId %d selectedDeviceId %d for port ID %d", __func__,
1420 *output, requestedPortId, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07001421
Eric Laurente83b55d2014-11-14 10:06:21 -08001422 return NO_ERROR;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001423}
1424
Eric Laurentc529cf62020-04-17 18:19:10 -07001425status_t AudioPolicyManager::openDirectOutput(audio_stream_type_t stream,
1426 audio_session_t session,
1427 const audio_config_t *config,
1428 audio_output_flags_t flags,
1429 const DeviceVector &devices,
1430 audio_io_handle_t *output) {
1431
1432 *output = AUDIO_IO_HANDLE_NONE;
1433
1434 // skip direct output selection if the request can obviously be attached to a mixed output
1435 // and not explicitly requested
1436 if (((flags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
1437 audio_is_linear_pcm(config->format) && config->sample_rate <= SAMPLE_RATE_HZ_MAX &&
1438 audio_channel_count_from_out_mask(config->channel_mask) <= 2) {
1439 return NAME_NOT_FOUND;
1440 }
1441
1442 // Do not allow offloading if one non offloadable effect is enabled or MasterMono is enabled.
1443 // This prevents creating an offloaded track and tearing it down immediately after start
1444 // when audioflinger detects there is an active non offloadable effect.
1445 // FIXME: We should check the audio session here but we do not have it in this context.
1446 // This may prevent offloading in rare situations where effects are left active by apps
1447 // in the background.
1448 sp<IOProfile> profile;
1449 if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) ||
1450 !(mEffects.isNonOffloadableEffectEnabled() || mMasterMono)) {
1451 profile = getProfileForOutput(
1452 devices, config->sample_rate, config->format, config->channel_mask,
1453 flags, true /* directOnly */);
1454 }
1455
1456 if (profile == nullptr) {
1457 return NAME_NOT_FOUND;
1458 }
1459
1460 // exclusive outputs for MMAP and Offload are enforced by different session ids.
1461 for (size_t i = 0; i < mOutputs.size(); i++) {
1462 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
1463 if (!desc->isDuplicated() && (profile == desc->mProfile)) {
1464 // reuse direct output if currently open by the same client
1465 // and configured with same parameters
1466 if ((config->sample_rate == desc->getSamplingRate()) &&
1467 (config->format == desc->getFormat()) &&
1468 (config->channel_mask == desc->getChannelMask()) &&
1469 (session == desc->mDirectClientSession)) {
1470 desc->mDirectOpenCount++;
Eric Laurentfecbceb2021-02-09 14:46:43 +01001471 ALOGV("%s reusing direct output %d for session %d", __func__,
Eric Laurentc529cf62020-04-17 18:19:10 -07001472 mOutputs.keyAt(i), session);
1473 *output = mOutputs.keyAt(i);
1474 return NO_ERROR;
1475 }
1476 }
1477 }
1478
1479 if (!profile->canOpenNewIo()) {
1480 return NAME_NOT_FOUND;
1481 }
1482
1483 sp<SwAudioOutputDescriptor> outputDesc =
1484 new SwAudioOutputDescriptor(profile, mpClientInterface);
1485
Michael Chan6fb34492020-12-08 15:44:49 +11001486 // An MSD patch may be using the only output stream that can service this request. Release
1487 // all MSD patches to prioritize this request over any active output on MSD.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001488 releaseMsdOutputPatches(devices);
Eric Laurentc529cf62020-04-17 18:19:10 -07001489
Eric Laurentf1f22e72021-07-13 14:04:14 +02001490 status_t status =
1491 outputDesc->open(config, nullptr /* mixerConfig */, devices, stream, flags, output);
Eric Laurentc529cf62020-04-17 18:19:10 -07001492
1493 // only accept an output with the requested parameters
1494 if (status != NO_ERROR ||
1495 (config->sample_rate != 0 && config->sample_rate != outputDesc->getSamplingRate()) ||
1496 (config->format != AUDIO_FORMAT_DEFAULT && config->format != outputDesc->getFormat()) ||
1497 (config->channel_mask != 0 && config->channel_mask != outputDesc->getChannelMask())) {
1498 ALOGV("%s failed opening direct output: output %d sample rate %d %d,"
1499 "format %d %d, channel mask %04x %04x", __func__, *output, config->sample_rate,
1500 outputDesc->getSamplingRate(), config->format, outputDesc->getFormat(),
1501 config->channel_mask, outputDesc->getChannelMask());
1502 if (*output != AUDIO_IO_HANDLE_NONE) {
1503 outputDesc->close();
1504 }
1505 // fall back to mixer output if possible when the direct output could not be open
1506 if (audio_is_linear_pcm(config->format) &&
1507 config->sample_rate <= SAMPLE_RATE_HZ_MAX) {
1508 return NAME_NOT_FOUND;
1509 }
1510 *output = AUDIO_IO_HANDLE_NONE;
1511 return BAD_VALUE;
1512 }
1513 outputDesc->mDirectOpenCount = 1;
1514 outputDesc->mDirectClientSession = session;
1515
1516 addOutput(*output, outputDesc);
1517 mPreviousOutputs = mOutputs;
1518 ALOGV("%s returns new direct output %d", __func__, *output);
1519 mpClientInterface->onAudioPortListUpdate();
1520 return NO_ERROR;
1521}
1522
François Gaffie11d30102018-11-02 16:09:09 +01001523audio_io_handle_t AudioPolicyManager::getOutputForDevices(
1524 const DeviceVector &devices,
Kevin Rocard169753c2017-03-06 14:18:23 -08001525 audio_session_t session,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001526 const audio_attributes_t *attr,
Eric Laurentfe231122017-11-17 17:48:06 -08001527 const audio_config_t *config,
jiabine375d412019-02-26 12:54:53 -08001528 audio_output_flags_t *flags,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001529 bool *isSpatialized,
jiabina84c3d32022-12-02 18:59:55 +00001530 sp<PreferredMixerAttributesInfo> prefMixerConfigInfo,
jiabine375d412019-02-26 12:54:53 -08001531 bool forceMutingHaptic)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001532{
Andy Hungc88b0642018-04-27 15:42:35 -07001533 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001534
jiabine375d412019-02-26 12:54:53 -08001535 // Discard haptic channel mask when forcing muting haptic channels.
1536 audio_channel_mask_t channelMask = forceMutingHaptic
Mikhail Naganov55773032020-10-01 15:08:13 -07001537 ? static_cast<audio_channel_mask_t>(config->channel_mask & ~AUDIO_CHANNEL_HAPTIC_ALL)
1538 : config->channel_mask;
jiabine375d412019-02-26 12:54:53 -08001539
Eric Laurente552edb2014-03-10 17:42:56 -07001540 // open a direct output if required by specified parameters
1541 //force direct flag if offload flag is set: offloading implies a direct output stream
1542 // and all common behaviors are driven by checking only the direct flag
1543 // this should normally be set appropriately in the policy configuration file
Nadav Bar766fb022018-01-07 12:18:03 +02001544 if ((*flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1545 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurente552edb2014-03-10 17:42:56 -07001546 }
Nadav Bar766fb022018-01-07 12:18:03 +02001547 if ((*flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
1548 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent93c3d412014-08-01 14:48:35 -07001549 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001550
1551 audio_stream_type_t stream = mEngine->getStreamTypeForAttributes(*attr);
1552
Eric Laurente83b55d2014-11-14 10:06:21 -08001553 // only allow deep buffering for music stream type
1554 if (stream != AUDIO_STREAM_MUSIC) {
Nadav Bar766fb022018-01-07 12:18:03 +02001555 *flags = (audio_output_flags_t)(*flags &~AUDIO_OUTPUT_FLAG_DEEP_BUFFER);
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -07001556 } else if (/* stream == AUDIO_STREAM_MUSIC && */
Nadav Bar766fb022018-01-07 12:18:03 +02001557 *flags == AUDIO_OUTPUT_FLAG_NONE &&
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -07001558 property_get_bool("audio.deep_buffer.media", false /* default_value */)) {
1559 // use DEEP_BUFFER as default output for music stream type
Nadav Bar766fb022018-01-07 12:18:03 +02001560 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
Eric Laurente83b55d2014-11-14 10:06:21 -08001561 }
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -07001562 if (stream == AUDIO_STREAM_TTS) {
Nadav Bar766fb022018-01-07 12:18:03 +02001563 *flags = AUDIO_OUTPUT_FLAG_TTS;
Haynes Mathew George84c621e2017-04-25 11:41:50 -07001564 } else if (stream == AUDIO_STREAM_VOICE_CALL &&
Nadav Bar20919492018-11-20 10:20:51 +02001565 audio_is_linear_pcm(config->format) &&
1566 (*flags & AUDIO_OUTPUT_FLAG_INCALL_MUSIC) == 0) {
Nadav Bar766fb022018-01-07 12:18:03 +02001567 *flags = (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_VOIP_RX |
Haynes Mathew George84c621e2017-04-25 11:41:50 -07001568 AUDIO_OUTPUT_FLAG_DIRECT);
1569 ALOGV("Set VoIP and Direct output flags for PCM format");
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -07001570 }
Eric Laurente552edb2014-03-10 17:42:56 -07001571
Carter Hsua3abb402021-10-26 11:11:20 +08001572 // Attach the Ultrasound flag for the AUDIO_CONTENT_TYPE_ULTRASOUND
1573 if (attr->content_type == AUDIO_CONTENT_TYPE_ULTRASOUND) {
1574 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_ULTRASOUND);
1575 }
1576
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001577 *isSpatialized = false;
Eric Laurentfa0f6742021-08-17 18:39:44 +02001578 if (mSpatializerOutput != nullptr
Andy Hung9dd1a5b2022-05-10 15:39:39 -07001579 && canBeSpatializedInt(attr, config, devices.toTypeAddrVector())) {
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001580 *isSpatialized = true;
Eric Laurentfa0f6742021-08-17 18:39:44 +02001581 return mSpatializerOutput->mIoHandle;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001582 }
1583
Eric Laurentc529cf62020-04-17 18:19:10 -07001584 audio_config_t directConfig = *config;
1585 directConfig.channel_mask = channelMask;
1586 status_t status = openDirectOutput(stream, session, &directConfig, *flags, devices, &output);
1587 if (status != NAME_NOT_FOUND) {
Eric Laurente552edb2014-03-10 17:42:56 -07001588 return output;
1589 }
1590
Eric Laurent14cbfca2016-03-17 09:42:16 -07001591 // A request for HW A/V sync cannot fallback to a mixed output because time
1592 // stamps are embedded in audio data
Phil Burk2d059932018-02-15 15:55:11 -08001593 if ((*flags & (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ)) != 0) {
Eric Laurent14cbfca2016-03-17 09:42:16 -07001594 return AUDIO_IO_HANDLE_NONE;
1595 }
Pierre Couillaude73496b2023-03-06 16:19:05 +00001596 // A request for Tuner cannot fallback to a mixed output
1597 if ((directConfig.offload_info.content_id || directConfig.offload_info.sync_id)) {
1598 return AUDIO_IO_HANDLE_NONE;
1599 }
Eric Laurent14cbfca2016-03-17 09:42:16 -07001600
Eric Laurente552edb2014-03-10 17:42:56 -07001601 // ignoring channel mask due to downmix capability in mixer
1602
1603 // open a non direct output
1604
1605 // for non direct outputs, only PCM is supported
Eric Laurentfe231122017-11-17 17:48:06 -08001606 if (audio_is_linear_pcm(config->format)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001607 // get which output is suitable for the specified stream. The actual
1608 // routing change will happen when startOutput() will be called
François Gaffie11d30102018-11-02 16:09:09 +01001609 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
jiabina84c3d32022-12-02 18:59:55 +00001610 if (prefMixerConfigInfo != nullptr) {
1611 for (audio_io_handle_t outputHandle : outputs) {
1612 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(outputHandle);
1613 if (outputDesc->mProfile == prefMixerConfigInfo->getProfile()) {
1614 output = outputHandle;
1615 break;
1616 }
1617 }
1618 if (output == AUDIO_IO_HANDLE_NONE) {
1619 // No output open with the preferred profile. Open a new one.
1620 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
1621 config.channel_mask = prefMixerConfigInfo->getConfigBase().channel_mask;
1622 config.sample_rate = prefMixerConfigInfo->getConfigBase().sample_rate;
1623 config.format = prefMixerConfigInfo->getConfigBase().format;
1624 sp<SwAudioOutputDescriptor> preferredOutput = openOutputWithProfileAndDevice(
1625 prefMixerConfigInfo->getProfile(), devices, nullptr /*mixerConfig*/,
1626 &config, prefMixerConfigInfo->getFlags());
1627 if (preferredOutput == nullptr) {
1628 ALOGE("%s failed to open output with preferred mixer config", __func__);
1629 } else {
1630 output = preferredOutput->mIoHandle;
1631 }
1632 }
1633 } else {
1634 // at this stage we should ignore the DIRECT flag as no direct output could be
1635 // found earlier
1636 *flags = (audio_output_flags_t) (*flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
1637 output = selectOutput(
1638 outputs, *flags, config->format, channelMask, config->sample_rate, session);
1639 }
Eric Laurente552edb2014-03-10 17:42:56 -07001640 }
François Gaffie11d30102018-11-02 16:09:09 +01001641 ALOGW_IF((output == 0), "getOutputForDevices() could not find output for stream %d, "
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001642 "sampling rate %d, format %#x, channels %#x, flags %#x",
jiabine375d412019-02-26 12:54:53 -08001643 stream, config->sample_rate, config->format, channelMask, *flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001644
Eric Laurente552edb2014-03-10 17:42:56 -07001645 return output;
1646}
1647
Mikhail Naganovf02f3672018-11-09 12:44:16 -08001648sp<DeviceDescriptor> AudioPolicyManager::getMsdAudioInDevice() const {
François Gaffie11d30102018-11-02 16:09:09 +01001649 auto msdInDevices = mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1650 mAvailableInputDevices);
1651 return msdInDevices.isEmpty()? nullptr : msdInDevices.itemAt(0);
1652}
1653
1654DeviceVector AudioPolicyManager::getMsdAudioOutDevices() const {
1655 return mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1656 mAvailableOutputDevices);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001657}
1658
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001659const AudioPatchCollection AudioPolicyManager::getMsdOutputPatches() const {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001660 AudioPatchCollection msdPatches;
Mikhail Naganov86112352018-10-04 09:02:49 -07001661 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1662 if (msdModule != 0) {
1663 for (size_t i = 0; i < mAudioPatches.size(); ++i) {
1664 sp<AudioPatch> patch = mAudioPatches.valueAt(i);
1665 for (size_t j = 0; j < patch->mPatch.num_sources; ++j) {
1666 const struct audio_port_config *source = &patch->mPatch.sources[j];
1667 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
1668 source->ext.device.hw_module == msdModule->getHandle()) {
François Gaffieafd4cea2019-11-18 15:50:22 +01001669 msdPatches.addAudioPatch(patch->getHandle(), patch);
Mikhail Naganov86112352018-10-04 09:02:49 -07001670 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001671 }
1672 }
1673 }
1674 return msdPatches;
1675}
1676
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02001677bool AudioPolicyManager::isMsdPatch(const audio_patch_handle_t &handle) const {
1678 ssize_t index = mAudioPatches.indexOfKey(handle);
1679 if (index < 0) {
1680 return false;
1681 }
1682 const sp<AudioPatch> patch = mAudioPatches.valueAt(index);
1683 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1684 if (msdModule == nullptr) {
1685 return false;
1686 }
1687 const struct audio_port_config *sink = &patch->mPatch.sinks[0];
1688 if (getMsdAudioOutDevices().contains(mAvailableOutputDevices.getDeviceFromId(sink->id))) {
1689 return true;
1690 }
1691 index = getMsdOutputPatches().indexOfKey(handle);
1692 if (index < 0) {
1693 return false;
1694 }
1695 return true;
1696}
1697
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001698status_t AudioPolicyManager::getMsdProfiles(bool hwAvSync,
1699 const InputProfileCollection &inputProfiles,
1700 const OutputProfileCollection &outputProfiles,
1701 const sp<DeviceDescriptor> &sourceDevice,
1702 const sp<DeviceDescriptor> &sinkDevice,
1703 AudioProfileVector& sourceProfiles,
1704 AudioProfileVector& sinkProfiles) const {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001705 if (inputProfiles.isEmpty()) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001706 ALOGE("%s() no input profiles for source module", __func__);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001707 return NO_INIT;
1708 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001709 if (outputProfiles.isEmpty()) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001710 ALOGE("%s() no output profiles for sink module", __func__);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001711 return NO_INIT;
1712 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001713 for (const auto &inProfile : inputProfiles) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001714 if (hwAvSync == ((inProfile->getFlags() & AUDIO_INPUT_FLAG_HW_AV_SYNC) != 0) &&
1715 inProfile->supportsDevice(sourceDevice)) {
1716 appendAudioProfiles(sourceProfiles, inProfile->getAudioProfiles());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001717 }
1718 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001719 for (const auto &outProfile : outputProfiles) {
Michael Chan6fb34492020-12-08 15:44:49 +11001720 if (hwAvSync == ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) &&
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001721 outProfile->supportsDevice(sinkDevice)) {
1722 appendAudioProfiles(sinkProfiles, outProfile->getAudioProfiles());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001723 }
1724 }
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001725 return NO_ERROR;
1726}
1727
1728status_t AudioPolicyManager::getBestMsdConfig(bool hwAvSync,
1729 const AudioProfileVector &sourceProfiles, const AudioProfileVector &sinkProfiles,
1730 audio_port_config *sourceConfig, audio_port_config *sinkConfig) const
1731{
Dean Wheatley16809da2022-12-09 14:55:46 +11001732 // Compressed formats for MSD module, ordered from most preferred to least preferred.
1733 static const std::vector<audio_format_t> formatsOrder = {{
1734 AUDIO_FORMAT_IEC60958, AUDIO_FORMAT_MAT_2_1, AUDIO_FORMAT_MAT_2_0, AUDIO_FORMAT_E_AC3,
1735 AUDIO_FORMAT_AC3, AUDIO_FORMAT_PCM_16_BIT }};
1736 static const std::vector<audio_channel_mask_t> channelMasksOrder = [](){
1737 // Channel position masks for MSD module, 3D > 2D > 1D ordering (most preferred to least
1738 // preferred).
1739 std::vector<audio_channel_mask_t> masks = {{
1740 AUDIO_CHANNEL_OUT_3POINT1POINT2, AUDIO_CHANNEL_OUT_3POINT0POINT2,
1741 AUDIO_CHANNEL_OUT_2POINT1POINT2, AUDIO_CHANNEL_OUT_2POINT0POINT2,
1742 AUDIO_CHANNEL_OUT_5POINT1, AUDIO_CHANNEL_OUT_STEREO }};
1743 // insert index masks (higher counts most preferred) as preferred over position masks
1744 for (int i = 1; i <= AUDIO_CHANNEL_COUNT_MAX; i++) {
1745 masks.insert(
1746 masks.begin(), audio_channel_mask_for_index_assignment_from_count(i));
1747 }
1748 return masks;
1749 }();
1750
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001751 struct audio_config_base bestSinkConfig;
Dean Wheatley16809da2022-12-09 14:55:46 +11001752 status_t result = findBestMatchingOutputConfig(sourceProfiles, sinkProfiles, formatsOrder,
1753 channelMasksOrder, true /*preferHigherSamplingRates*/, bestSinkConfig);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001754 if (result != NO_ERROR) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001755 ALOGD("%s() no matching config found for sink, hwAvSync: %d",
1756 __func__, hwAvSync);
Greg Kaiser83289652018-07-30 06:13:57 -07001757 return result;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001758 }
1759 sinkConfig->sample_rate = bestSinkConfig.sample_rate;
1760 sinkConfig->channel_mask = bestSinkConfig.channel_mask;
1761 sinkConfig->format = bestSinkConfig.format;
1762 // For encoded streams force direct flag to prevent downstream mixing.
1763 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1764 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_DIRECT);
Dean Wheatley5c9f0832019-11-21 13:39:31 +11001765 if (audio_is_iec61937_compatible(sinkConfig->format)) {
1766 // For formats compatible with IEC61937 encapsulation, assume that
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001767 // the input is IEC61937 framed (for proportional buffer sizing).
Dean Wheatley5c9f0832019-11-21 13:39:31 +11001768 // Add the AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO flag so downstream HAL can distinguish between
1769 // raw and IEC61937 framed streams.
1770 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1771 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO);
1772 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001773 sourceConfig->sample_rate = bestSinkConfig.sample_rate;
1774 // Specify exact channel mask to prevent guessing by bit count in PatchPanel.
Dean Wheatley16809da2022-12-09 14:55:46 +11001775 sourceConfig->channel_mask =
1776 audio_channel_mask_get_representation(bestSinkConfig.channel_mask)
1777 == AUDIO_CHANNEL_REPRESENTATION_INDEX ?
1778 bestSinkConfig.channel_mask : audio_channel_mask_out_to_in(bestSinkConfig.channel_mask);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001779 sourceConfig->format = bestSinkConfig.format;
1780 // Copy input stream directly without any processing (e.g. resampling).
1781 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1782 sourceConfig->flags.input | AUDIO_INPUT_FLAG_DIRECT);
1783 if (hwAvSync) {
1784 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1785 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
1786 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1787 sourceConfig->flags.input | AUDIO_INPUT_FLAG_HW_AV_SYNC);
1788 }
1789 const unsigned int config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE |
1790 AUDIO_PORT_CONFIG_CHANNEL_MASK | AUDIO_PORT_CONFIG_FORMAT | AUDIO_PORT_CONFIG_FLAGS;
1791 sinkConfig->config_mask |= config_mask;
1792 sourceConfig->config_mask |= config_mask;
1793 return NO_ERROR;
1794}
1795
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001796PatchBuilder AudioPolicyManager::buildMsdPatch(bool msdIsSource,
1797 const sp<DeviceDescriptor> &device) const
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001798{
1799 PatchBuilder patchBuilder;
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001800 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1801 ALOG_ASSERT(msdModule != nullptr, "MSD module not available");
1802 sp<HwModule> deviceModule = mHwModules.getModuleForDevice(device, AUDIO_FORMAT_DEFAULT);
1803 if (deviceModule == nullptr) {
1804 ALOGE("%s() unable to get module for %s", __func__, device->toString().c_str());
1805 return patchBuilder;
1806 }
1807 const InputProfileCollection inputProfiles = msdIsSource ?
1808 msdModule->getInputProfiles() : deviceModule->getInputProfiles();
1809 const OutputProfileCollection outputProfiles = msdIsSource ?
1810 deviceModule->getOutputProfiles() : msdModule->getOutputProfiles();
1811
1812 const sp<DeviceDescriptor> sourceDevice = msdIsSource ? getMsdAudioInDevice() : device;
1813 const sp<DeviceDescriptor> sinkDevice = msdIsSource ?
1814 device : getMsdAudioOutDevices().itemAt(0);
1815 patchBuilder.addSource(sourceDevice).addSink(sinkDevice);
1816
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001817 audio_port_config sourceConfig = patchBuilder.patch()->sources[0];
1818 audio_port_config sinkConfig = patchBuilder.patch()->sinks[0];
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001819 AudioProfileVector sourceProfiles;
1820 AudioProfileVector sinkProfiles;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001821 // TODO: Figure out whether MSD module has HW_AV_SYNC flag set in the AP config file.
1822 // For now, we just forcefully try with HwAvSync first.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001823 for (auto hwAvSync : { true, false }) {
1824 if (getMsdProfiles(hwAvSync, inputProfiles, outputProfiles, sourceDevice, sinkDevice,
1825 sourceProfiles, sinkProfiles) != NO_ERROR) {
1826 continue;
1827 }
1828 if (getBestMsdConfig(hwAvSync, sourceProfiles, sinkProfiles, &sourceConfig,
1829 &sinkConfig) == NO_ERROR) {
1830 // Found a matching config. Re-create PatchBuilder with this config.
1831 return (PatchBuilder()).addSource(sourceConfig).addSink(sinkConfig);
1832 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001833 }
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001834 ALOGV("%s() no matching config found. Fall through to default PCM patch"
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001835 " supporting PCM format conversion.", __func__);
1836 return patchBuilder;
1837}
1838
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001839status_t AudioPolicyManager::setMsdOutputPatches(const DeviceVector *outputDevices) {
Michael Chan6fb34492020-12-08 15:44:49 +11001840 DeviceVector devices;
1841 if (outputDevices != nullptr && outputDevices->size() > 0) {
1842 devices.add(*outputDevices);
1843 } else {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001844 // Use media strategy for unspecified output device. This should only
1845 // occur on checkForDeviceAndOutputChanges(). Device connection events may
1846 // therefore invalidate explicit routing requests.
Michael Chan6fb34492020-12-08 15:44:49 +11001847 devices = mEngine->getOutputDevicesForAttributes(
François Gaffiec005e562018-11-06 15:04:49 +01001848 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
Michael Chan6fb34492020-12-08 15:44:49 +11001849 LOG_ALWAYS_FATAL_IF(devices.isEmpty(), "no output device to set MSD patch");
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001850 }
Michael Chan6fb34492020-12-08 15:44:49 +11001851 std::vector<PatchBuilder> patchesToCreate;
1852 for (auto i = 0u; i < devices.size(); ++i) {
1853 ALOGV("%s() for device %s", __func__, devices[i]->toString().c_str());
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001854 patchesToCreate.push_back(buildMsdPatch(true /*msdIsSource*/, devices[i]));
Michael Chan6fb34492020-12-08 15:44:49 +11001855 }
1856 // Retain only the MSD patches associated with outputDevices request.
1857 // Tear down the others, and create new ones as needed.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001858 AudioPatchCollection patchesToRemove = getMsdOutputPatches();
Michael Chan6fb34492020-12-08 15:44:49 +11001859 for (auto it = patchesToCreate.begin(); it != patchesToCreate.end(); ) {
1860 auto retainedPatch = false;
1861 for (auto i = 0u; i < patchesToRemove.size(); ++i) {
1862 if (audio_patches_are_equal(it->patch(), &patchesToRemove[i]->mPatch)) {
1863 patchesToRemove.removeItemsAt(i);
1864 retainedPatch = true;
1865 break;
1866 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001867 }
Michael Chan6fb34492020-12-08 15:44:49 +11001868 if (retainedPatch) {
1869 it = patchesToCreate.erase(it);
1870 continue;
1871 }
1872 ++it;
1873 }
1874 if (patchesToCreate.size() == 0 && patchesToRemove.size() == 0) {
1875 return NO_ERROR;
1876 }
1877 for (auto i = 0u; i < patchesToRemove.size(); ++i) {
1878 auto &currentPatch = patchesToRemove.valueAt(i);
François Gaffieafd4cea2019-11-18 15:50:22 +01001879 releaseAudioPatch(currentPatch->getHandle(), mUidCached);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001880 }
Michael Chan6fb34492020-12-08 15:44:49 +11001881 status_t status = NO_ERROR;
1882 for (const auto &p : patchesToCreate) {
1883 auto currStatus = installPatch(__func__, -1 /*index*/, nullptr /*patchHandle*/,
1884 p.patch(), 0 /*delayMs*/, mUidCached, nullptr /*patchDescPtr*/);
1885 char message[256];
1886 snprintf(message, sizeof(message), "%s() %s: creating MSD patch from device:IN_BUS to "
1887 "device:%#x (format:%#x channels:%#x samplerate:%d)", __func__,
1888 currStatus == NO_ERROR ? "Success" : "Error",
1889 p.patch()->sinks[0].ext.device.type, p.patch()->sources[0].format,
1890 p.patch()->sources[0].channel_mask, p.patch()->sources[0].sample_rate);
1891 if (currStatus == NO_ERROR) {
1892 ALOGD("%s", message);
1893 } else {
1894 ALOGE("%s", message);
1895 if (status == NO_ERROR) {
1896 status = currStatus;
1897 }
1898 }
1899 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001900 return status;
1901}
1902
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001903void AudioPolicyManager::releaseMsdOutputPatches(const DeviceVector& devices) {
1904 AudioPatchCollection msdPatches = getMsdOutputPatches();
Michael Chan6fb34492020-12-08 15:44:49 +11001905 for (size_t i = 0; i < msdPatches.size(); i++) {
1906 const auto& patch = msdPatches[i];
1907 for (size_t j = 0; j < patch->mPatch.num_sinks; ++j) {
1908 const struct audio_port_config *sink = &patch->mPatch.sinks[j];
1909 if (sink->type == AUDIO_PORT_TYPE_DEVICE && devices.getDevice(sink->ext.device.type,
1910 String8(sink->ext.device.address), AUDIO_FORMAT_DEFAULT) != nullptr) {
1911 releaseAudioPatch(patch->getHandle(), mUidCached);
1912 break;
1913 }
1914 }
1915 }
1916}
1917
Dorin Drimus94d94412022-02-02 09:05:02 +01001918bool AudioPolicyManager::msdHasPatchesToAllDevices(const AudioDeviceTypeAddrVector& devices) {
Mikhail Naganov68e3f642023-04-28 13:06:32 -07001919 DeviceVector devicesToCheck =
1920 mConfig->getOutputDevices().getDevicesFromDeviceTypeAddrVec(devices);
Dorin Drimus94d94412022-02-02 09:05:02 +01001921 AudioPatchCollection msdPatches = getMsdOutputPatches();
1922 for (size_t i = 0; i < msdPatches.size(); i++) {
1923 const auto& patch = msdPatches[i];
1924 for (size_t j = 0; j < patch->mPatch.num_sinks; ++j) {
1925 const struct audio_port_config *sink = &patch->mPatch.sinks[j];
1926 if (sink->type == AUDIO_PORT_TYPE_DEVICE) {
1927 const auto& foundDevice = devicesToCheck.getDevice(
1928 sink->ext.device.type, String8(sink->ext.device.address), AUDIO_FORMAT_DEFAULT);
1929 if (foundDevice != nullptr) {
1930 devicesToCheck.remove(foundDevice);
1931 if (devicesToCheck.isEmpty()) {
1932 return true;
1933 }
1934 }
1935 }
1936 }
1937 }
1938 return false;
1939}
1940
Eric Laurente0720872014-03-11 09:30:41 -07001941audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
jiabinebb6af42020-06-09 17:31:17 -07001942 audio_output_flags_t flags,
1943 audio_format_t format,
1944 audio_channel_mask_t channelMask,
1945 uint32_t samplingRate,
1946 audio_session_t sessionId)
Eric Laurente552edb2014-03-10 17:42:56 -07001947{
Eric Laurent16c66dd2019-05-01 17:54:10 -07001948 LOG_ALWAYS_FATAL_IF(!(format == AUDIO_FORMAT_INVALID || audio_is_linear_pcm(format)),
1949 "%s called with format %#x", __func__, format);
1950
jiabinebb6af42020-06-09 17:31:17 -07001951 // Return the output that haptic-generating attached to when 1) session id is specified,
1952 // 2) haptic-generating effect exists for given session id and 3) the output that
1953 // haptic-generating effect attached to is in given outputs.
1954 if (sessionId != AUDIO_SESSION_NONE) {
1955 audio_io_handle_t hapticGeneratingOutput = mEffects.getIoForSession(
1956 sessionId, FX_IID_HAPTICGENERATOR);
1957 if (outputs.indexOf(hapticGeneratingOutput) >= 0) {
1958 return hapticGeneratingOutput;
1959 }
1960 }
1961
Eric Laurent16c66dd2019-05-01 17:54:10 -07001962 // Flags disqualifying an output: the match must happen before calling selectOutput()
1963 static const audio_output_flags_t kExcludedFlags = (audio_output_flags_t)
1964 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ | AUDIO_OUTPUT_FLAG_DIRECT);
1965
1966 // Flags expressing a functional request: must be honored in priority over
1967 // other criteria
1968 static const audio_output_flags_t kFunctionalFlags = (audio_output_flags_t)
1969 (AUDIO_OUTPUT_FLAG_VOIP_RX | AUDIO_OUTPUT_FLAG_INCALL_MUSIC |
Eric Laurente28c66d2022-01-21 13:40:41 +01001970 AUDIO_OUTPUT_FLAG_TTS | AUDIO_OUTPUT_FLAG_DIRECT_PCM | AUDIO_OUTPUT_FLAG_ULTRASOUND |
1971 AUDIO_OUTPUT_FLAG_SPATIALIZER);
Eric Laurent16c66dd2019-05-01 17:54:10 -07001972 // Flags expressing a performance request: have lower priority than serving
1973 // requested sampling rate or channel mask
1974 static const audio_output_flags_t kPerformanceFlags = (audio_output_flags_t)
1975 (AUDIO_OUTPUT_FLAG_FAST | AUDIO_OUTPUT_FLAG_DEEP_BUFFER |
1976 AUDIO_OUTPUT_FLAG_RAW | AUDIO_OUTPUT_FLAG_SYNC);
1977
1978 const audio_output_flags_t functionalFlags =
1979 (audio_output_flags_t)(flags & kFunctionalFlags);
1980 const audio_output_flags_t performanceFlags =
1981 (audio_output_flags_t)(flags & kPerformanceFlags);
1982
1983 audio_io_handle_t bestOutput = (outputs.size() == 0) ? AUDIO_IO_HANDLE_NONE : outputs[0];
1984
Eric Laurente552edb2014-03-10 17:42:56 -07001985 // select one output among several that provide a path to a particular device or set of
François Gaffie11d30102018-11-02 16:09:09 +01001986 // devices (the list was previously build by getOutputsForDevices()).
Eric Laurente552edb2014-03-10 17:42:56 -07001987 // The priority is as follows:
jiabin40573322018-11-08 12:08:02 -08001988 // 1: the output supporting haptic playback when requesting haptic playback
Eric Laurent16c66dd2019-05-01 17:54:10 -07001989 // 2: the output with the highest number of requested functional flags
Carter Hsu199f1892021-10-15 15:47:29 +08001990 // with tiebreak preferring the minimum number of extra functional flags
1991 // (see b/200293124, the incorrect selection of AUDIO_OUTPUT_FLAG_VOIP_RX).
Eric Laurent16c66dd2019-05-01 17:54:10 -07001992 // 3: the output supporting the exact channel mask
1993 // 4: the output with a higher channel count than requested
jiabinb12a6da2022-06-03 20:48:18 +00001994 // 5: the output with the highest sampling rate if the requested sample rate is
1995 // greater than default sampling rate
Eric Laurent16c66dd2019-05-01 17:54:10 -07001996 // 6: the output with the highest number of requested performance flags
1997 // 7: the output with the bit depth the closest to the requested one
1998 // 8: the primary output
1999 // 9: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07002000
Eric Laurent16c66dd2019-05-01 17:54:10 -07002001 // matching criteria values in priority order for best matching output so far
2002 std::vector<uint32_t> bestMatchCriteria(8, 0);
Eric Laurente552edb2014-03-10 17:42:56 -07002003
Eric Laurent16c66dd2019-05-01 17:54:10 -07002004 const uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
2005 const uint32_t hapticChannelCount = audio_channel_count_from_out_mask(
2006 channelMask & AUDIO_CHANNEL_HAPTIC_ALL);
Eric Laurente78b6762018-12-19 16:29:01 -08002007
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002008 for (audio_io_handle_t output : outputs) {
2009 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent16c66dd2019-05-01 17:54:10 -07002010 // matching criteria values in priority order for current output
2011 std::vector<uint32_t> currentMatchCriteria(8, 0);
jiabin40573322018-11-08 12:08:02 -08002012
Eric Laurent16c66dd2019-05-01 17:54:10 -07002013 if (outputDesc->isDuplicated()) {
2014 continue;
2015 }
2016 if ((kExcludedFlags & outputDesc->mFlags) != 0) {
2017 continue;
2018 }
Eric Laurent8838a382014-09-08 16:44:28 -07002019
Eric Laurent16c66dd2019-05-01 17:54:10 -07002020 // If haptic channel is specified, use the haptic output if present.
2021 // When using haptic output, same audio format and sample rate are required.
2022 const uint32_t outputHapticChannelCount = audio_channel_count_from_out_mask(
jiabin5740f082019-08-19 15:08:30 -07002023 outputDesc->getChannelMask() & AUDIO_CHANNEL_HAPTIC_ALL);
Eric Laurent16c66dd2019-05-01 17:54:10 -07002024 if ((hapticChannelCount == 0) != (outputHapticChannelCount == 0)) {
2025 continue;
2026 }
2027 if (outputHapticChannelCount >= hapticChannelCount
jiabin5740f082019-08-19 15:08:30 -07002028 && format == outputDesc->getFormat()
2029 && samplingRate == outputDesc->getSamplingRate()) {
Eric Laurent16c66dd2019-05-01 17:54:10 -07002030 currentMatchCriteria[0] = outputHapticChannelCount;
2031 }
2032
2033 // functional flags match
Carter Hsu199f1892021-10-15 15:47:29 +08002034 const int matchingFunctionalFlags =
2035 __builtin_popcount(outputDesc->mFlags & functionalFlags);
2036 const int totalFunctionalFlags =
2037 __builtin_popcount(outputDesc->mFlags & kFunctionalFlags);
2038 // Prefer matching functional flags, but subtract unnecessary functional flags.
2039 currentMatchCriteria[1] = 100 * (matchingFunctionalFlags + 1) - totalFunctionalFlags;
Eric Laurent16c66dd2019-05-01 17:54:10 -07002040
2041 // channel mask and channel count match
jiabin5740f082019-08-19 15:08:30 -07002042 uint32_t outputChannelCount = audio_channel_count_from_out_mask(
2043 outputDesc->getChannelMask());
Eric Laurent16c66dd2019-05-01 17:54:10 -07002044 if (channelMask != AUDIO_CHANNEL_NONE && channelCount > 2 &&
2045 channelCount <= outputChannelCount) {
2046 if ((audio_channel_mask_get_representation(channelMask) ==
jiabin5740f082019-08-19 15:08:30 -07002047 audio_channel_mask_get_representation(outputDesc->getChannelMask())) &&
2048 ((channelMask & outputDesc->getChannelMask()) == channelMask)) {
Eric Laurent16c66dd2019-05-01 17:54:10 -07002049 currentMatchCriteria[2] = outputChannelCount;
Eric Laurente552edb2014-03-10 17:42:56 -07002050 }
Eric Laurent16c66dd2019-05-01 17:54:10 -07002051 currentMatchCriteria[3] = outputChannelCount;
2052 }
2053
2054 // sampling rate match
jiabinb12a6da2022-06-03 20:48:18 +00002055 if (samplingRate > SAMPLE_RATE_HZ_DEFAULT) {
jiabin5740f082019-08-19 15:08:30 -07002056 currentMatchCriteria[4] = outputDesc->getSamplingRate();
Eric Laurent16c66dd2019-05-01 17:54:10 -07002057 }
2058
2059 // performance flags match
2060 currentMatchCriteria[5] = popcount(outputDesc->mFlags & performanceFlags);
2061
2062 // format match
2063 if (format != AUDIO_FORMAT_INVALID) {
2064 currentMatchCriteria[6] =
jiabin4ef93452019-09-10 14:29:54 -07002065 PolicyAudioPort::kFormatDistanceMax -
2066 PolicyAudioPort::formatDistance(format, outputDesc->getFormat());
Eric Laurent16c66dd2019-05-01 17:54:10 -07002067 }
2068
2069 // primary output match
2070 currentMatchCriteria[7] = outputDesc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY;
2071
2072 // compare match criteria by priority then value
2073 if (std::lexicographical_compare(bestMatchCriteria.begin(), bestMatchCriteria.end(),
2074 currentMatchCriteria.begin(), currentMatchCriteria.end())) {
2075 bestMatchCriteria = currentMatchCriteria;
2076 bestOutput = output;
2077
2078 std::stringstream result;
2079 std::copy(bestMatchCriteria.begin(), bestMatchCriteria.end(),
2080 std::ostream_iterator<int>(result, " "));
2081 ALOGV("%s new bestOutput %d criteria %s",
2082 __func__, bestOutput, result.str().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07002083 }
2084 }
2085
Eric Laurent16c66dd2019-05-01 17:54:10 -07002086 return bestOutput;
Eric Laurente552edb2014-03-10 17:42:56 -07002087}
2088
Eric Laurent8fc147b2018-07-22 19:13:55 -07002089status_t AudioPolicyManager::startOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002090{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002091 ALOGV("%s portId %d", __FUNCTION__, portId);
2092
2093 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2094 if (outputDesc == 0) {
2095 ALOGW("startOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002096 return BAD_VALUE;
2097 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002098 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002099
Eric Laurent8fc147b2018-07-22 19:13:55 -07002100 ALOGV("startOutput() output %d, stream %d, session %d",
Eric Laurent97ac8712018-07-27 18:59:02 -07002101 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurentc75307b2015-03-17 15:29:32 -07002102
Eric Laurent733ce942017-12-07 12:18:25 -08002103 status_t status = outputDesc->start();
2104 if (status != NO_ERROR) {
2105 return status;
Eric Laurent3974e3b2017-12-07 17:58:43 -08002106 }
2107
Eric Laurent97ac8712018-07-27 18:59:02 -07002108 uint32_t delayMs;
2109 status = startSource(outputDesc, client, &delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07002110
2111 if (status != NO_ERROR) {
Eric Laurent733ce942017-12-07 12:18:25 -08002112 outputDesc->stop();
jiabin3ff8d7d2022-12-13 06:27:44 +00002113 if (status == DEAD_OBJECT) {
2114 sp<SwAudioOutputDescriptor> desc =
2115 reopenOutput(outputDesc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
2116 if (desc == nullptr) {
2117 // This is not common, it may indicate something wrong with the HAL.
2118 ALOGE("%s unable to open output with default config", __func__);
2119 return status;
2120 }
2121 desc->mUsePreferredMixerAttributes = true;
2122 }
Eric Laurent8c7e6da2015-04-21 17:37:00 -07002123 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07002124 }
jiabina84c3d32022-12-02 18:59:55 +00002125
2126 // If the client is the first one active on preferred mixer parameters, reopen the output
2127 // if the current mixer parameters doesn't match the preferred one.
2128 if (outputDesc->devices().size() == 1) {
2129 sp<PreferredMixerAttributesInfo> info = getPreferredMixerAttributesInfo(
2130 outputDesc->devices()[0]->getId(), client->strategy());
2131 if (info != nullptr && info->getUid() == client->uid()) {
2132 if (info->getActiveClientCount() == 0 && !outputDesc->isConfigurationMatched(
2133 info->getConfigBase(), info->getFlags())) {
2134 stopSource(outputDesc, client);
2135 outputDesc->stop();
2136 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
2137 config.channel_mask = info->getConfigBase().channel_mask;
2138 config.sample_rate = info->getConfigBase().sample_rate;
2139 config.format = info->getConfigBase().format;
jiabin3ff8d7d2022-12-13 06:27:44 +00002140 sp<SwAudioOutputDescriptor> desc =
2141 reopenOutput(outputDesc, &config, info->getFlags(), __func__);
2142 if (desc == nullptr) {
2143 return BAD_VALUE;
jiabina84c3d32022-12-02 18:59:55 +00002144 }
jiabin3ff8d7d2022-12-13 06:27:44 +00002145 desc->mUsePreferredMixerAttributes = true;
jiabina84c3d32022-12-02 18:59:55 +00002146 // Intentionally return error to let the client side resending request for
2147 // creating and starting.
2148 return DEAD_OBJECT;
2149 }
2150 info->increaseActiveClient();
jiabine3d1f552023-06-14 17:42:17 +00002151 if (info->getActiveClientCount() == 1 &&
2152 (info->getFlags() & AUDIO_OUTPUT_FLAG_BIT_PERFECT) != AUDIO_OUTPUT_FLAG_NONE) {
2153 // If it is first bit-perfect client, reroute all clients that will be routed to
2154 // the bit-perfect sink so that it is guaranteed only bit-perfect stream is active.
2155 PortHandleVector clientsToInvalidate;
2156 for (size_t i = 0; i < mOutputs.size(); i++) {
2157 if (mOutputs[i] == outputDesc ||
jiabin98c519c2023-07-05 17:34:21 +00002158 mOutputs[i]->devices().filter(outputDesc->devices()).isEmpty()) {
jiabine3d1f552023-06-14 17:42:17 +00002159 continue;
2160 }
2161 for (const auto& c : mOutputs[i]->getClientIterable()) {
2162 clientsToInvalidate.push_back(c->portId());
2163 }
2164 }
2165 if (!clientsToInvalidate.empty()) {
2166 ALOGD("%s Invalidate clients due to first bit-perfect client started",
2167 __func__);
2168 mpClientInterface->invalidateTracks(clientsToInvalidate);
2169 }
2170 }
jiabina84c3d32022-12-02 18:59:55 +00002171 }
2172 }
2173
Jean-Michel Trivib1f6e642023-02-07 20:49:04 +00002174 if (client->hasPreferredDevice()) {
2175 // playback activity with preferred device impacts routing occurred, inform upper layers
2176 mpClientInterface->onRoutingUpdated();
2177 }
Eric Laurentc75307b2015-03-17 15:29:32 -07002178 if (delayMs != 0) {
2179 usleep(delayMs * 1000);
2180 }
2181
2182 return status;
2183}
2184
Eric Laurent96d1dda2022-03-14 17:14:19 +01002185bool AudioPolicyManager::isLeUnicastActive() const {
2186 if (isInCall()) {
2187 return true;
2188 }
2189 return isAnyDeviceTypeActive(getAudioDeviceOutLeAudioUnicastSet());
2190}
2191
2192bool AudioPolicyManager::isAnyDeviceTypeActive(const DeviceTypeSet& deviceTypes) const {
2193 if (mAvailableOutputDevices.getDevicesFromTypes(deviceTypes).isEmpty()) {
2194 return false;
2195 }
2196 bool active = mOutputs.isAnyDeviceTypeActive(deviceTypes);
2197 ALOGV("%s active %d", __func__, active);
2198 return active;
2199}
2200
Eric Laurent97ac8712018-07-27 18:59:02 -07002201status_t AudioPolicyManager::startSource(const sp<SwAudioOutputDescriptor>& outputDesc,
2202 const sp<TrackClientDescriptor>& client,
2203 uint32_t *delayMs)
Eric Laurentc75307b2015-03-17 15:29:32 -07002204{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002205 // cannot start playback of STREAM_TTS if any other output is being used
2206 uint32_t beaconMuteLatency = 0;
Eric Laurentc75307b2015-03-17 15:29:32 -07002207
2208 *delayMs = 0;
Eric Laurent97ac8712018-07-27 18:59:02 -07002209 audio_stream_type_t stream = client->stream();
François Gaffie1c878552018-11-22 16:53:21 +01002210 auto clientVolSrc = client->volumeSource();
François Gaffiec005e562018-11-06 15:04:49 +01002211 auto clientStrategy = client->strategy();
2212 auto clientAttr = client->attributes();
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002213 if (stream == AUDIO_STREAM_TTS) {
2214 ALOGV("\t found BEACON stream");
François Gaffie1c878552018-11-22 16:53:21 +01002215 if (!mTtsOutputAvailable && mOutputs.isAnyOutputActive(
Francois Gaffie4404ddb2021-02-04 17:03:38 +01002216 toVolumeSource(AUDIO_STREAM_TTS, false) /*sourceToIgnore*/)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002217 return INVALID_OPERATION;
2218 } else {
2219 beaconMuteLatency = handleEventForBeacon(STARTING_BEACON);
2220 }
2221 } else {
2222 // some playback other than beacon starts
2223 beaconMuteLatency = handleEventForBeacon(STARTING_OUTPUT);
2224 }
2225
Eric Laurent77305a62016-07-25 16:39:22 -07002226 // force device change if the output is inactive and no audio patch is already present.
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002227 // check active before incrementing usage count
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02002228 bool force = !outputDesc->isActive() && !outputDesc->isRouted();
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002229
François Gaffie11d30102018-11-02 16:09:09 +01002230 DeviceVector devices;
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002231 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
Eric Laurent97ac8712018-07-27 18:59:02 -07002232 const char *address = NULL;
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002233 if (policyMix != nullptr) {
François Gaffie11d30102018-11-02 16:09:09 +01002234 audio_devices_t newDeviceType;
Eric Laurent97ac8712018-07-27 18:59:02 -07002235 address = policyMix->mDeviceAddress.string();
Kevin Rocard153f92d2018-12-18 18:33:28 -08002236 if ((policyMix->mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie11d30102018-11-02 16:09:09 +01002237 newDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Kevin Rocard153f92d2018-12-18 18:33:28 -08002238 } else {
2239 newDeviceType = policyMix->mDeviceType;
Eric Laurent97ac8712018-07-27 18:59:02 -07002240 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08002241 sp device = mAvailableOutputDevices.getDevice(newDeviceType, String8(address),
2242 AUDIO_FORMAT_DEFAULT);
2243 ALOG_ASSERT(device, "%s: no device found t=%u, a=%s", __func__, newDeviceType, address);
2244 devices.add(device);
Eric Laurent97ac8712018-07-27 18:59:02 -07002245 }
2246
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002247 // requiresMuteCheck is false when we can bypass mute strategy.
2248 // It covers a common case when there is no materially active audio
2249 // and muting would result in unnecessary delay and dropped audio.
2250 const uint32_t outputLatencyMs = outputDesc->latency();
2251 bool requiresMuteCheck = outputDesc->isActive(outputLatencyMs * 2); // account for drain
Eric Laurent96d1dda2022-03-14 17:14:19 +01002252 bool wasLeUnicastActive = isLeUnicastActive();
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002253
Eric Laurente552edb2014-03-10 17:42:56 -07002254 // increment usage count for this stream on the requested output:
2255 // NOTE that the usage count is the same for duplicated output and hardware output which is
2256 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
Eric Laurent592dd7b2018-08-05 18:58:48 -07002257 outputDesc->setClientActive(client, true);
Eric Laurent97ac8712018-07-27 18:59:02 -07002258
2259 if (client->hasPreferredDevice(true)) {
Eric Laurent72af8012023-03-15 17:36:22 +01002260 if (outputDesc->sameExclusivePreferredDevicesCount() > 0) {
François Gaffief96e5432019-04-09 17:13:56 +02002261 // Preferred device may be exclusive, use only if no other active clients on this output
2262 devices = DeviceVector(
2263 mAvailableOutputDevices.getDeviceFromId(client->preferredDeviceId()));
2264 } else {
2265 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
2266 }
François Gaffie11d30102018-11-02 16:09:09 +01002267 if (devices != outputDesc->devices()) {
François Gaffiec005e562018-11-06 15:04:49 +01002268 checkStrategyRoute(clientStrategy, outputDesc->mIoHandle);
Eric Laurent97ac8712018-07-27 18:59:02 -07002269 }
2270 }
Eric Laurente552edb2014-03-10 17:42:56 -07002271
François Gaffiec005e562018-11-06 15:04:49 +01002272 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07002273 selectOutputForMusicEffects();
2274 }
2275
François Gaffie1c878552018-11-22 16:53:21 +01002276 if (outputDesc->getActivityCount(clientVolSrc) == 1 || !devices.isEmpty()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08002277 // starting an output being rerouted?
François Gaffie11d30102018-11-02 16:09:09 +01002278 if (devices.isEmpty()) {
2279 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Eric Laurent275e8e92014-11-30 15:14:47 -08002280 }
François Gaffiec005e562018-11-06 15:04:49 +01002281 bool shouldWait =
2282 (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM)) ||
2283 followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_NOTIFICATION)) ||
2284 (beaconMuteLatency > 0));
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002285 uint32_t waitMs = beaconMuteLatency;
Eric Laurente552edb2014-03-10 17:42:56 -07002286 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01002287 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07002288 if (desc != outputDesc) {
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002289 // An output has a shared device if
2290 // - managed by the same hw module
2291 // - supports the currently selected device
2292 const bool sharedDevice = outputDesc->sharesHwModuleWith(desc)
François Gaffie11d30102018-11-02 16:09:09 +01002293 && (!desc->filterSupportedDevices(devices).isEmpty());
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002294
Eric Laurent77305a62016-07-25 16:39:22 -07002295 // force a device change if any other output is:
2296 // - managed by the same hw module
Jean-Michel Trivi4a5b4812018-02-08 17:22:32 +00002297 // - supports currently selected device
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002298 // - has a current device selection that differs from selected device.
Eric Laurent77305a62016-07-25 16:39:22 -07002299 // - has an active audio patch
Eric Laurente552edb2014-03-10 17:42:56 -07002300 // In this case, the audio HAL must receive the new device selection so that it can
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002301 // change the device currently selected by the other output.
2302 if (sharedDevice &&
François Gaffie11d30102018-11-02 16:09:09 +01002303 desc->devices() != devices &&
Eric Laurent77305a62016-07-25 16:39:22 -07002304 desc->getPatchHandle() != AUDIO_PATCH_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07002305 force = true;
2306 }
2307 // wait for audio on other active outputs to be presented when starting
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002308 // a notification so that audio focus effect can propagate, or that a mute/unmute
2309 // event occurred for beacon
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002310 const uint32_t latencyMs = desc->latency();
2311 const bool isActive = desc->isActive(latencyMs * 2); // account for drain
2312
2313 if (shouldWait && isActive && (waitMs < latencyMs)) {
2314 waitMs = latencyMs;
Eric Laurente552edb2014-03-10 17:42:56 -07002315 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002316
2317 // Require mute check if another output is on a shared device
2318 // and currently active to have proper drain and avoid pops.
2319 // Note restoring AudioTracks onto this output needs to invoke
2320 // a volume ramp if there is no mute.
2321 requiresMuteCheck |= sharedDevice && isActive;
Eric Laurente552edb2014-03-10 17:42:56 -07002322 }
2323 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002324
jiabin3ff8d7d2022-12-13 06:27:44 +00002325 if (outputDesc->mUsePreferredMixerAttributes && devices != outputDesc->devices()) {
2326 // If the output is open with preferred mixer attributes, but the routed device is
2327 // changed when calling this function, returning DEAD_OBJECT to indicate routing
2328 // changed.
2329 return DEAD_OBJECT;
2330 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002331 const uint32_t muteWaitMs =
jiabin3ff8d7d2022-12-13 06:27:44 +00002332 setOutputDevices(outputDesc, devices, force, 0, nullptr, requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07002333
Eric Laurente552edb2014-03-10 17:42:56 -07002334 // apply volume rules for current stream and device if necessary
François Gaffieaaac0fd2018-11-22 17:56:39 +01002335 auto &curves = getVolumeCurves(client->attributes());
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00002336 if (NO_ERROR != checkAndSetVolume(curves, client->volumeSource(),
François Gaffieaaac0fd2018-11-22 17:56:39 +01002337 curves.getVolumeIndex(outputDesc->devices().types()),
Eric Laurentc75307b2015-03-17 15:29:32 -07002338 outputDesc,
Francois Gaffied11442b2020-04-27 11:51:09 +02002339 outputDesc->devices().types(), 0 /*delay*/,
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00002340 outputDesc->useHwGain() /*force*/)) {
2341 // request AudioService to reinitialize the volume curves asynchronously
2342 ALOGE("checkAndSetVolume failed, requesting volume range init");
2343 mpClientInterface->onVolumeRangeInitRequest();
2344 };
Eric Laurente552edb2014-03-10 17:42:56 -07002345
2346 // update the outputs if starting an output with a stream that can affect notification
2347 // routing
2348 handleNotificationRoutingForStream(stream);
Eric Laurentc722f302014-12-10 11:21:49 -08002349
Eric Laurent2cbe89a2014-12-19 11:49:08 -08002350 // force reevaluating accessibility routing when ringtone or alarm starts
François Gaffiec005e562018-11-06 15:04:49 +01002351 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM))) {
jiabinc44b3462022-12-08 12:52:31 -08002352 invalidateStreams({AUDIO_STREAM_ACCESSIBILITY});
Eric Laurent2cbe89a2014-12-19 11:49:08 -08002353 }
Eric Laurentdc462862016-07-19 12:29:53 -07002354
2355 if (waitMs > muteWaitMs) {
2356 *delayMs = waitMs - muteWaitMs;
2357 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002358
2359 // FIXME: A device change (muteWaitMs > 0) likely introduces a volume change.
2360 // A volume change enacted by APM with 0 delay is not synchronous, as it goes
2361 // via AudioCommandThread to AudioFlinger. Hence it is possible that the volume
2362 // change occurs after the MixerThread starts and causes a stream volume
2363 // glitch.
2364 //
2365 // We do not introduce additional delay here.
Eric Laurente552edb2014-03-10 17:42:56 -07002366 }
Eric Laurentdc462862016-07-19 12:29:53 -07002367
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002368 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
jiabin9a3361e2019-10-01 09:38:30 -07002369 mEngine->getForceUse(
2370 AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
François Gaffiec005e562018-11-06 15:04:49 +01002371 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), true, outputDesc);
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002372 }
2373
Eric Laurent97ac8712018-07-27 18:59:02 -07002374 // Automatically enable the remote submix input when output is started on a re routing mix
2375 // of type MIX_TYPE_RECORDERS
jiabin9a3361e2019-10-01 09:38:30 -07002376 if (isSingleDeviceType(devices.types(), &audio_is_remote_submix_device) &&
2377 policyMix != NULL && policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002378 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2379 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2380 address,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002381 "remote-submix",
2382 AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07002383 }
2384
Eric Laurent96d1dda2022-03-14 17:14:19 +01002385 checkLeBroadcastRoutes(wasLeUnicastActive, outputDesc, *delayMs);
2386
Eric Laurente552edb2014-03-10 17:42:56 -07002387 return NO_ERROR;
2388}
2389
Eric Laurent96d1dda2022-03-14 17:14:19 +01002390void AudioPolicyManager::checkLeBroadcastRoutes(bool wasUnicastActive,
2391 sp<SwAudioOutputDescriptor> ignoredOutput, uint32_t delayMs) {
2392 bool isUnicastActive = isLeUnicastActive();
2393
2394 if (wasUnicastActive != isUnicastActive) {
jiabin3ff8d7d2022-12-13 06:27:44 +00002395 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent96d1dda2022-03-14 17:14:19 +01002396 //reroute all outputs routed to LE broadcast if LE unicast activy changed on any output
2397 for (size_t i = 0; i < mOutputs.size(); i++) {
2398 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
2399 if (desc != ignoredOutput && desc->isActive()
2400 && ((isUnicastActive &&
2401 !desc->devices().
2402 getDevicesFromType(AUDIO_DEVICE_OUT_BLE_BROADCAST).isEmpty())
2403 || (wasUnicastActive &&
2404 !desc->devices().getDevicesFromTypes(
2405 getAudioDeviceOutLeAudioUnicastSet()).isEmpty()))) {
2406 DeviceVector newDevices = getNewOutputDevices(desc, false /*fromCache*/);
2407 bool force = desc->devices() != newDevices;
jiabin3ff8d7d2022-12-13 06:27:44 +00002408 if (desc->mUsePreferredMixerAttributes && force) {
2409 // If the device is using preferred mixer attributes, the output need to reopen
2410 // with default configuration when the new selected devices are different from
2411 // current routing devices.
2412 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices);
2413 continue;
2414 }
Eric Laurent96d1dda2022-03-14 17:14:19 +01002415 setOutputDevices(desc, newDevices, force, delayMs);
2416 // re-apply device specific volume if not done by setOutputDevice()
2417 if (!force) {
2418 applyStreamVolumes(desc, newDevices.types(), delayMs);
2419 }
2420 }
2421 }
jiabin3ff8d7d2022-12-13 06:27:44 +00002422 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent96d1dda2022-03-14 17:14:19 +01002423 }
2424}
2425
Eric Laurent8fc147b2018-07-22 19:13:55 -07002426status_t AudioPolicyManager::stopOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002427{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002428 ALOGV("%s portId %d", __FUNCTION__, portId);
2429
2430 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2431 if (outputDesc == 0) {
2432 ALOGW("stopOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002433 return BAD_VALUE;
2434 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002435 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002436
Jean-Michel Trivib1f6e642023-02-07 20:49:04 +00002437 if (client->hasPreferredDevice(true)) {
2438 // playback activity with preferred device impacts routing occurred, inform upper layers
2439 mpClientInterface->onRoutingUpdated();
2440 }
2441
Eric Laurent97ac8712018-07-27 18:59:02 -07002442 ALOGV("stopOutput() output %d, stream %d, session %d",
2443 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurente552edb2014-03-10 17:42:56 -07002444
Eric Laurent97ac8712018-07-27 18:59:02 -07002445 status_t status = stopSource(outputDesc, client);
Eric Laurent3974e3b2017-12-07 17:58:43 -08002446
Eric Laurent733ce942017-12-07 12:18:25 -08002447 if (status == NO_ERROR ) {
2448 outputDesc->stop();
jiabina84c3d32022-12-02 18:59:55 +00002449 } else {
2450 return status;
2451 }
2452
2453 if (outputDesc->devices().size() == 1) {
2454 sp<PreferredMixerAttributesInfo> info = getPreferredMixerAttributesInfo(
2455 outputDesc->devices()[0]->getId(), client->strategy());
2456 if (info != nullptr && info->getUid() == client->uid()) {
2457 info->decreaseActiveClient();
2458 if (info->getActiveClientCount() == 0) {
2459 reopenOutput(outputDesc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
2460 }
2461 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002462 }
2463 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07002464}
2465
Eric Laurent97ac8712018-07-27 18:59:02 -07002466status_t AudioPolicyManager::stopSource(const sp<SwAudioOutputDescriptor>& outputDesc,
2467 const sp<TrackClientDescriptor>& client)
Eric Laurentc75307b2015-03-17 15:29:32 -07002468{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002469 // always handle stream stop, check which stream type is stopping
Eric Laurent97ac8712018-07-27 18:59:02 -07002470 audio_stream_type_t stream = client->stream();
François Gaffie1c878552018-11-22 16:53:21 +01002471 auto clientVolSrc = client->volumeSource();
Eric Laurent96d1dda2022-03-14 17:14:19 +01002472 bool wasLeUnicastActive = isLeUnicastActive();
Eric Laurent97ac8712018-07-27 18:59:02 -07002473
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002474 handleEventForBeacon(stream == AUDIO_STREAM_TTS ? STOPPING_BEACON : STOPPING_OUTPUT);
2475
François Gaffie1c878552018-11-22 16:53:21 +01002476 if (outputDesc->getActivityCount(clientVolSrc) > 0) {
2477 if (outputDesc->getActivityCount(clientVolSrc) == 1) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002478 // Automatically disable the remote submix input when output is stopped on a
2479 // re routing mix of type MIX_TYPE_RECORDERS
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002480 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
jiabin9a3361e2019-10-01 09:38:30 -07002481 if (isSingleDeviceType(
2482 outputDesc->devices().types(), &audio_is_remote_submix_device) &&
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002483 policyMix != nullptr &&
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002484 policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002485 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2486 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002487 policyMix->mDeviceAddress,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002488 "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07002489 }
2490 }
2491 bool forceDeviceUpdate = false;
Eric Laurent72af8012023-03-15 17:36:22 +01002492 if (client->hasPreferredDevice(true) &&
2493 outputDesc->sameExclusivePreferredDevicesCount() < 2) {
François Gaffiec005e562018-11-06 15:04:49 +01002494 checkStrategyRoute(client->strategy(), AUDIO_IO_HANDLE_NONE);
Eric Laurent97ac8712018-07-27 18:59:02 -07002495 forceDeviceUpdate = true;
2496 }
2497
Eric Laurente552edb2014-03-10 17:42:56 -07002498 // decrement usage count of this stream on the output
Eric Laurent592dd7b2018-08-05 18:58:48 -07002499 outputDesc->setClientActive(client, false);
Paul McLeanaa981192015-03-21 09:55:15 -07002500
Eric Laurente552edb2014-03-10 17:42:56 -07002501 // store time at which the stream was stopped - see isStreamActive()
François Gaffie1c878552018-11-22 16:53:21 +01002502 if (outputDesc->getActivityCount(clientVolSrc) == 0 || forceDeviceUpdate) {
François Gaffiec005e562018-11-06 15:04:49 +01002503 outputDesc->setStopTime(client, systemTime());
François Gaffie11d30102018-11-02 16:09:09 +01002504 DeviceVector newDevices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Francois Gaffie3523ab32021-06-22 13:24:34 +02002505
2506 // If the routing does not change, if an output is routed on a device using HwGain
2507 // (aka setAudioPortConfig) and there are still active clients following different
2508 // volume group(s), force reapply volume
2509 bool requiresVolumeCheck = outputDesc->getActivityCount(clientVolSrc) == 0 &&
2510 outputDesc->useHwGain() && outputDesc->isAnyActive(VOLUME_SOURCE_NONE);
2511
Eric Laurente552edb2014-03-10 17:42:56 -07002512 // delay the device switch by twice the latency because stopOutput() is executed when
2513 // the track stop() command is received and at that time the audio track buffer can
2514 // still contain data that needs to be drained. The latency only covers the audio HAL
2515 // and kernel buffers. Also the latency does not always include additional delay in the
2516 // audio path (audio DSP, CODEC ...)
Francois Gaffie3523ab32021-06-22 13:24:34 +02002517 setOutputDevices(outputDesc, newDevices, false, outputDesc->latency()*2,
2518 nullptr, true /*requiresMuteCheck*/, requiresVolumeCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07002519
2520 // force restoring the device selection on other active outputs if it differs from the
2521 // one being selected for this output
jiabin3ff8d7d2022-12-13 06:27:44 +00002522 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent57de36c2016-09-28 16:59:11 -07002523 uint32_t delayMs = outputDesc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -07002524 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01002525 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07002526 if (desc != outputDesc &&
Eric Laurente552edb2014-03-10 17:42:56 -07002527 desc->isActive() &&
2528 outputDesc->sharesHwModuleWith(desc) &&
François Gaffie11d30102018-11-02 16:09:09 +01002529 (newDevices != desc->devices())) {
2530 DeviceVector newDevices2 = getNewOutputDevices(desc, false /*fromCache*/);
2531 bool force = desc->devices() != newDevices2;
Eric Laurentf3a5a602018-05-22 18:42:55 -07002532
jiabin3ff8d7d2022-12-13 06:27:44 +00002533 if (desc->mUsePreferredMixerAttributes && force) {
2534 // If the device is using preferred mixer attributes, the output need to
2535 // reopen with default configuration when the new selected devices are
2536 // different from current routing devices.
2537 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices2);
2538 continue;
2539 }
François Gaffie11d30102018-11-02 16:09:09 +01002540 setOutputDevices(desc, newDevices2, force, delayMs);
2541
Eric Laurent57de36c2016-09-28 16:59:11 -07002542 // re-apply device specific volume if not done by setOutputDevice()
2543 if (!force) {
François Gaffie11d30102018-11-02 16:09:09 +01002544 applyStreamVolumes(desc, newDevices2.types(), delayMs);
Eric Laurent57de36c2016-09-28 16:59:11 -07002545 }
Eric Laurente552edb2014-03-10 17:42:56 -07002546 }
2547 }
jiabin3ff8d7d2022-12-13 06:27:44 +00002548 reopenOutputsWithDevices(outputsToReopen);
Eric Laurente552edb2014-03-10 17:42:56 -07002549 // update the outputs if stopping one with a stream that can affect notification routing
2550 handleNotificationRoutingForStream(stream);
2551 }
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002552
2553 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
2554 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Jean-Michel Trivi74e01fa2019-02-25 12:18:09 -08002555 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), false, outputDesc);
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002556 }
2557
François Gaffiec005e562018-11-06 15:04:49 +01002558 if (followsSameRouting(client->attributes(), attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07002559 selectOutputForMusicEffects();
2560 }
Eric Laurent96d1dda2022-03-14 17:14:19 +01002561
2562 checkLeBroadcastRoutes(wasLeUnicastActive, outputDesc, outputDesc->latency()*2);
2563
Eric Laurente552edb2014-03-10 17:42:56 -07002564 return NO_ERROR;
2565 } else {
Eric Laurentc75307b2015-03-17 15:29:32 -07002566 ALOGW("stopOutput() refcount is already 0");
Eric Laurente552edb2014-03-10 17:42:56 -07002567 return INVALID_OPERATION;
2568 }
2569}
2570
jiabinbce0c1d2020-10-05 11:20:18 -07002571bool AudioPolicyManager::releaseOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002572{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002573 ALOGV("%s portId %d", __FUNCTION__, portId);
2574
2575 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2576 if (outputDesc == 0) {
Andy Hung39efb7a2018-09-26 15:39:28 -07002577 // If an output descriptor is closed due to a device routing change,
2578 // then there are race conditions with releaseOutput from tracks
2579 // that may be destroyed (with no PlaybackThread) or a PlaybackThread
2580 // destroyed shortly thereafter.
2581 //
2582 // Here we just log a warning, instead of a fatal error.
Eric Laurent8fc147b2018-07-22 19:13:55 -07002583 ALOGW("releaseOutput() no output for client %d", portId);
jiabinbce0c1d2020-10-05 11:20:18 -07002584 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002585 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002586
2587 ALOGV("releaseOutput() %d", outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -07002588
Jaideep Sharma7bf382e2020-11-26 17:07:29 +05302589 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
2590 if (outputDesc->isClientActive(client)) {
2591 ALOGW("releaseOutput() inactivates portId %d in good faith", portId);
2592 stopOutput(portId);
2593 }
2594
Eric Laurent8fc147b2018-07-22 19:13:55 -07002595 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
2596 if (outputDesc->mDirectOpenCount <= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07002597 ALOGW("releaseOutput() invalid open count %d for output %d",
Eric Laurent8fc147b2018-07-22 19:13:55 -07002598 outputDesc->mDirectOpenCount, outputDesc->mIoHandle);
jiabinbce0c1d2020-10-05 11:20:18 -07002599 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002600 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002601 if (--outputDesc->mDirectOpenCount == 0) {
2602 closeOutput(outputDesc->mIoHandle);
Eric Laurentb52c1522014-05-20 11:27:36 -07002603 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07002604 }
2605 }
Jaideep Sharma7bf382e2020-11-26 17:07:29 +05302606
Andy Hung39efb7a2018-09-26 15:39:28 -07002607 outputDesc->removeClient(portId);
jiabinbce0c1d2020-10-05 11:20:18 -07002608 if (outputDesc->mPendingReopenToQueryProfiles && outputDesc->getClientCount() == 0) {
2609 // The output is pending reopened to query dynamic profiles and
2610 // there is no active clients
2611 closeOutput(outputDesc->mIoHandle);
2612 sp<SwAudioOutputDescriptor> newOutputDesc = openOutputWithProfileAndDevice(
2613 outputDesc->mProfile, mEngine->getActiveMediaDevices(mAvailableOutputDevices));
2614 if (newOutputDesc == nullptr) {
2615 ALOGE("%s failed to open output", __func__);
2616 }
2617 return true;
2618 }
2619 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002620}
2621
Eric Laurentcaf7f482014-11-25 17:50:47 -08002622status_t AudioPolicyManager::getInputForAttr(const audio_attributes_t *attr,
2623 audio_io_handle_t *input,
Mikhail Naganov2996f672019-04-18 12:29:59 -07002624 audio_unique_id_t riid,
Eric Laurentcaf7f482014-11-25 17:50:47 -08002625 audio_session_t session,
Svet Ganov3e5f14f2021-05-13 22:51:08 +00002626 const AttributionSourceState& attributionSource,
jiabinf1c73972022-04-14 16:28:52 -07002627 audio_config_base_t *config,
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002628 audio_input_flags_t flags,
Eric Laurent2ac76942017-06-22 17:17:09 -07002629 audio_port_handle_t *selectedDeviceId,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002630 input_type_t *inputType,
2631 audio_port_handle_t *portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002632{
François Gaffiec005e562018-11-06 15:04:49 +01002633 ALOGV("%s() source %d, sampling rate %d, format %#x, channel mask %#x, session %d, "
Eric Laurent2f2c1982021-06-02 14:03:11 +02002634 "flags %#x attributes=%s requested device ID %d",
2635 __func__, attr->source, config->sample_rate, config->format, config->channel_mask,
2636 session, flags, toString(*attr).c_str(), *selectedDeviceId);
Eric Laurente552edb2014-03-10 17:42:56 -07002637
Eric Laurentad2e7b92017-09-14 20:06:42 -07002638 status_t status = NO_ERROR;
Francois Gaffie716e1432019-01-14 16:58:59 +01002639 audio_attributes_t attributes = *attr;
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002640 sp<AudioPolicyMix> policyMix;
François Gaffie11d30102018-11-02 16:09:09 +01002641 sp<DeviceDescriptor> device;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002642 sp<AudioInputDescriptor> inputDesc;
2643 sp<RecordClientDescriptor> clientDesc;
2644 audio_port_handle_t requestedDeviceId = *selectedDeviceId;
Svet Ganov3e5f14f2021-05-13 22:51:08 +00002645 uid_t uid = VALUE_OR_RETURN_STATUS(aidl2legacy_int32_t_uid_t(attributionSource.uid));
Eric Laurent8f42ea12018-08-08 09:08:25 -07002646 bool isSoundTrigger;
Eric Laurent8f42ea12018-08-08 09:08:25 -07002647
2648 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
2649 if (*portId != AUDIO_PORT_HANDLE_NONE) {
2650 return INVALID_OPERATION;
2651 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08002652
Francois Gaffie716e1432019-01-14 16:58:59 +01002653 if (attr->source == AUDIO_SOURCE_DEFAULT) {
2654 attributes.source = AUDIO_SOURCE_MIC;
Eric Laurentfe231122017-11-17 17:48:06 -08002655 }
2656
Paul McLean466dc8e2015-04-17 13:15:36 -06002657 // Explicit routing?
Pattydd807582021-11-04 21:01:03 +08002658 sp<DeviceDescriptor> explicitRoutingDevice =
François Gaffie11d30102018-11-02 16:09:09 +01002659 mAvailableInputDevices.getDeviceFromId(*selectedDeviceId);
Paul McLean466dc8e2015-04-17 13:15:36 -06002660
Eric Laurentad2e7b92017-09-14 20:06:42 -07002661 // special case for mmap capture: if an input IO handle is specified, we reuse this input if
2662 // possible
2663 if ((flags & AUDIO_INPUT_FLAG_MMAP_NOIRQ) == AUDIO_INPUT_FLAG_MMAP_NOIRQ &&
2664 *input != AUDIO_IO_HANDLE_NONE) {
2665 ssize_t index = mInputs.indexOfKey(*input);
2666 if (index < 0) {
2667 ALOGW("getInputForAttr() unknown MMAP input %d", *input);
2668 status = BAD_VALUE;
2669 goto error;
2670 }
2671 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002672 RecordClientVector clients = inputDesc->getClientsForSession(session);
2673 if (clients.size() == 0) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07002674 ALOGW("getInputForAttr() unknown session %d on input %d", session, *input);
2675 status = BAD_VALUE;
2676 goto error;
2677 }
2678 // For MMAP mode, the first call to getInputForAttr() is made on behalf of audioflinger.
2679 // The second call is for the first active client and sets the UID. Any further call
Eric Laurent331679c2018-04-16 17:03:16 -07002680 // corresponds to a new client and is only permitted from the same UID.
2681 // If the first UID is silenced, allow a new UID connection and replace with new UID
Eric Laurent8f42ea12018-08-08 09:08:25 -07002682 if (clients.size() > 1) {
2683 for (const auto& client : clients) {
2684 // The client map is ordered by key values (portId) and portIds are allocated
2685 // incrementaly. So the first client in this list is the one opened by audio flinger
2686 // when the mmap stream is created and should be ignored as it does not correspond
2687 // to an actual client
2688 if (client == *clients.cbegin()) {
2689 continue;
2690 }
2691 if (uid != client->uid() && !client->isSilenced()) {
2692 ALOGW("getInputForAttr() bad uid %d for client %d uid %d",
2693 uid, client->portId(), client->uid());
2694 status = INVALID_OPERATION;
2695 goto error;
2696 }
Eric Laurent331679c2018-04-16 17:03:16 -07002697 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002698 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002699 *inputType = API_INPUT_LEGACY;
François Gaffie11d30102018-11-02 16:09:09 +01002700 device = inputDesc->getDevice();
Eric Laurentad2e7b92017-09-14 20:06:42 -07002701
Eric Laurentfecbceb2021-02-09 14:46:43 +01002702 ALOGV("%s reusing MMAP input %d for session %d", __FUNCTION__, *input, session);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002703 goto exit;
Eric Laurentad2e7b92017-09-14 20:06:42 -07002704 }
2705
2706 *input = AUDIO_IO_HANDLE_NONE;
2707 *inputType = API_INPUT_INVALID;
2708
Francois Gaffie716e1432019-01-14 16:58:59 +01002709 if (attributes.source == AUDIO_SOURCE_REMOTE_SUBMIX &&
Jan Sebechlebskybc56bcd2022-09-26 13:15:19 +02002710 extractAddressFromAudioAttributes(attributes).has_value()) {
Francois Gaffie716e1432019-01-14 16:58:59 +01002711 status = mPolicyMixes.getInputMixForAttr(attributes, &policyMix);
Eric Laurentad2e7b92017-09-14 20:06:42 -07002712 if (status != NO_ERROR) {
jiabinc1de2df2019-05-07 14:26:40 -07002713 ALOGW("%s could not find input mix for attr %s",
2714 __func__, toString(attributes).c_str());
Eric Laurentad2e7b92017-09-14 20:06:42 -07002715 goto error;
François Gaffie036e1e92015-03-19 10:16:24 +01002716 }
jiabinc1de2df2019-05-07 14:26:40 -07002717 device = mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2718 String8(attr->tags + strlen("addr=")),
2719 AUDIO_FORMAT_DEFAULT);
2720 if (device == nullptr) {
Kevin Rocard04ed0462019-05-02 17:53:24 -07002721 ALOGW("%s could not find in Remote Submix device for source %d, tags %s",
jiabinc1de2df2019-05-07 14:26:40 -07002722 __func__, attributes.source, attributes.tags);
2723 status = BAD_VALUE;
2724 goto error;
2725 }
2726
Kevin Rocard25f9b052019-02-27 15:08:54 -08002727 if (is_mix_loopback_render(policyMix->mRouteFlags)) {
2728 *inputType = API_INPUT_MIX_PUBLIC_CAPTURE_PLAYBACK;
2729 } else {
2730 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
2731 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002732 } else {
François Gaffie11d30102018-11-02 16:09:09 +01002733 if (explicitRoutingDevice != nullptr) {
2734 device = explicitRoutingDevice;
Eric Laurent97ac8712018-07-27 18:59:02 -07002735 } else {
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01002736 // Prevent from storing invalid requested device id in clients
2737 requestedDeviceId = AUDIO_PORT_HANDLE_NONE;
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02002738 device = mEngine->getInputDeviceForAttributes(attributes, uid, session, &policyMix);
yuanjiahsu4069d5d2021-04-19 07:54:27 +08002739 ALOGV_IF(device != nullptr, "%s found device type is 0x%X",
2740 __FUNCTION__, device->type());
Eric Laurent97ac8712018-07-27 18:59:02 -07002741 }
François Gaffie11d30102018-11-02 16:09:09 +01002742 if (device == nullptr) {
Francois Gaffie716e1432019-01-14 16:58:59 +01002743 ALOGW("getInputForAttr() could not find device for source %d", attributes.source);
Eric Laurentad2e7b92017-09-14 20:06:42 -07002744 status = BAD_VALUE;
2745 goto error;
Eric Laurent275e8e92014-11-30 15:14:47 -08002746 }
Alden DSouzab7d20782021-02-08 08:51:42 -08002747 if (device->type() == AUDIO_DEVICE_IN_ECHO_REFERENCE) {
2748 *inputType = API_INPUT_MIX_CAPTURE;
2749 } else if (policyMix) {
François Gaffie11d30102018-11-02 16:09:09 +01002750 ALOG_ASSERT(policyMix->mMixType == MIX_TYPE_RECORDERS, "Invalid Mix Type");
2751 // there is an external policy, but this input is attached to a mix of recorders,
2752 // meaning it receives audio injected into the framework, so the recorder doesn't
2753 // know about it and is therefore considered "legacy"
2754 *inputType = API_INPUT_LEGACY;
2755 } else if (audio_is_remote_submix_device(device->type())) {
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002756 *inputType = API_INPUT_MIX_CAPTURE;
François Gaffie11d30102018-11-02 16:09:09 +01002757 } else if (device->type() == AUDIO_DEVICE_IN_TELEPHONY_RX) {
Eric Laurent82db2692015-08-07 13:59:42 -07002758 *inputType = API_INPUT_TELEPHONY_RX;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002759 } else {
2760 *inputType = API_INPUT_LEGACY;
Eric Laurentc722f302014-12-10 11:21:49 -08002761 }
Ravi Kumar Alamandab367f5b2015-08-25 08:21:37 -07002762
Eric Laurent599c7582015-12-07 18:05:55 -08002763 }
2764
François Gaffiec005e562018-11-06 15:04:49 +01002765 *input = getInputForDevice(device, session, attributes, config, flags, policyMix);
Eric Laurent599c7582015-12-07 18:05:55 -08002766 if (*input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07002767 status = INVALID_OPERATION;
jiabinf1c73972022-04-14 16:28:52 -07002768 AudioProfileVector profiles;
2769 status_t ret = getProfilesForDevices(
2770 DeviceVector(device), profiles, flags, true /*isInput*/);
2771 if (ret == NO_ERROR && !profiles.empty()) {
2772 config->channel_mask = profiles[0]->getChannels().empty() ? config->channel_mask
2773 : *profiles[0]->getChannels().begin();
2774 config->sample_rate = profiles[0]->getSampleRates().empty() ? config->sample_rate
2775 : *profiles[0]->getSampleRates().begin();
2776 config->format = profiles[0]->getFormat();
2777 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002778 goto error;
Eric Laurent599c7582015-12-07 18:05:55 -08002779 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08002780
Eric Laurent8f42ea12018-08-08 09:08:25 -07002781exit:
2782
François Gaffiec005e562018-11-06 15:04:49 +01002783 *selectedDeviceId = mAvailableInputDevices.contains(device) ?
2784 device->getId() : AUDIO_PORT_HANDLE_NONE;
Eric Laurent2ac76942017-06-22 17:17:09 -07002785
Francois Gaffie716e1432019-01-14 16:58:59 +01002786 isSoundTrigger = attributes.source == AUDIO_SOURCE_HOTWORD &&
Carter Hsud0cce2e2019-05-03 17:36:28 +08002787 mSoundTriggerSessions.indexOfKey(session) >= 0;
jiabin4ef93452019-09-10 14:29:54 -07002788 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002789
Mikhail Naganov2996f672019-04-18 12:29:59 -07002790 clientDesc = new RecordClientDescriptor(*portId, riid, uid, session, attributes, *config,
Francois Gaffie716e1432019-01-14 16:58:59 +01002791 requestedDeviceId, attributes.source, flags,
2792 isSoundTrigger);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002793 inputDesc = mInputs.valueFor(*input);
Andy Hung39efb7a2018-09-26 15:39:28 -07002794 inputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002795
2796 ALOGV("getInputForAttr() returns input %d type %d selectedDeviceId %d for port ID %d",
2797 *input, *inputType, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07002798
Eric Laurent599c7582015-12-07 18:05:55 -08002799 return NO_ERROR;
Eric Laurentad2e7b92017-09-14 20:06:42 -07002800
2801error:
Eric Laurentad2e7b92017-09-14 20:06:42 -07002802 return status;
Eric Laurent599c7582015-12-07 18:05:55 -08002803}
2804
2805
François Gaffie11d30102018-11-02 16:09:09 +01002806audio_io_handle_t AudioPolicyManager::getInputForDevice(const sp<DeviceDescriptor> &device,
Eric Laurent599c7582015-12-07 18:05:55 -08002807 audio_session_t session,
François Gaffiec005e562018-11-06 15:04:49 +01002808 const audio_attributes_t &attributes,
jiabinf1c73972022-04-14 16:28:52 -07002809 audio_config_base_t *config,
Eric Laurent599c7582015-12-07 18:05:55 -08002810 audio_input_flags_t flags,
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002811 const sp<AudioPolicyMix> &policyMix)
Eric Laurent599c7582015-12-07 18:05:55 -08002812{
2813 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
François Gaffiec005e562018-11-06 15:04:49 +01002814 audio_source_t halInputSource = attributes.source;
Eric Laurent599c7582015-12-07 18:05:55 -08002815 bool isSoundTrigger = false;
2816
François Gaffiec005e562018-11-06 15:04:49 +01002817 if (attributes.source == AUDIO_SOURCE_HOTWORD) {
Eric Laurent599c7582015-12-07 18:05:55 -08002818 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
2819 if (index >= 0) {
2820 input = mSoundTriggerSessions.valueFor(session);
2821 isSoundTrigger = true;
2822 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_HW_HOTWORD);
2823 ALOGV("SoundTrigger capture on session %d input %d", session, input);
2824 } else {
2825 halInputSource = AUDIO_SOURCE_VOICE_RECOGNITION;
Eric Laurent5dbe4712014-09-19 19:04:57 -07002826 }
François Gaffiec005e562018-11-06 15:04:49 +01002827 } else if (attributes.source == AUDIO_SOURCE_VOICE_COMMUNICATION &&
Eric Laurentfe231122017-11-17 17:48:06 -08002828 audio_is_linear_pcm(config->format)) {
Haynes Mathew George851d3ff2017-06-19 20:01:57 -07002829 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_VOIP_TX);
Eric Laurent5dbe4712014-09-19 19:04:57 -07002830 }
2831
Carter Hsua3abb402021-10-26 11:11:20 +08002832 if (attributes.source == AUDIO_SOURCE_ULTRASOUND) {
2833 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_ULTRASOUND);
2834 }
2835
Eric Laurentfe231122017-11-17 17:48:06 -08002836 // sampling rate and flags may be updated by getInputProfile
2837 uint32_t profileSamplingRate = (config->sample_rate == 0) ?
2838 SAMPLE_RATE_HZ_DEFAULT : config->sample_rate;
jiabin2fd710d2022-05-02 23:20:22 +00002839 audio_format_t profileFormat = config->format;
Eric Laurentfe231122017-11-17 17:48:06 -08002840 audio_channel_mask_t profileChannelMask = config->channel_mask;
Andy Hungf129b032015-04-07 13:45:50 -07002841 audio_input_flags_t profileFlags = flags;
jiabin2fd710d2022-05-02 23:20:22 +00002842 // find a compatible input profile (not necessarily identical in parameters)
2843 sp<IOProfile> profile = getInputProfile(
2844 device, profileSamplingRate, profileFormat, profileChannelMask, profileFlags);
2845 if (profile == nullptr) {
2846 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07002847 }
jiabin2fd710d2022-05-02 23:20:22 +00002848
Glenn Kasten05ddca52016-02-11 08:17:12 -08002849 // Pick input sampling rate if not specified by client
Eric Laurentfe231122017-11-17 17:48:06 -08002850 uint32_t samplingRate = config->sample_rate;
Glenn Kasten05ddca52016-02-11 08:17:12 -08002851 if (samplingRate == 0) {
2852 samplingRate = profileSamplingRate;
2853 }
Eric Laurente552edb2014-03-10 17:42:56 -07002854
Eric Laurent322b4d22015-04-03 15:57:54 -07002855 if (profile->getModuleHandle() == 0) {
2856 ALOGE("getInputForAttr(): HW module %s not opened", profile->getModuleName());
Eric Laurent599c7582015-12-07 18:05:55 -08002857 return input;
Eric Laurentcf2c0212014-07-25 16:20:43 -07002858 }
2859
Eric Laurentec376dc2021-04-08 20:41:22 +02002860 // Reuse an already opened input if a client with the same session ID already exists
2861 // on that input
2862 for (size_t i = 0; i < mInputs.size(); i++) {
2863 sp <AudioInputDescriptor> desc = mInputs.valueAt(i);
2864 if (desc->mProfile != profile) {
2865 continue;
2866 }
2867 RecordClientVector clients = desc->clientsList();
2868 for (const auto &client : clients) {
2869 if (session == client->session()) {
2870 return desc->mIoHandle;
2871 }
2872 }
2873 }
2874
Eric Laurent3974e3b2017-12-07 17:58:43 -08002875 if (!profile->canOpenNewIo()) {
Eric Laurent4eb58f12018-12-07 16:41:02 -08002876 for (size_t i = 0; i < mInputs.size(); ) {
Eric Laurentc529cf62020-04-17 18:19:10 -07002877 sp<AudioInputDescriptor> desc = mInputs.valueAt(i);
Eric Laurent4eb58f12018-12-07 16:41:02 -08002878 if (desc->mProfile != profile) {
Carter Hsu9a645a92019-05-15 12:15:32 +08002879 i++;
Eric Laurent4eb58f12018-12-07 16:41:02 -08002880 continue;
2881 }
2882 // if sound trigger, reuse input if used by other sound trigger on same session
2883 // else
2884 // reuse input if active client app is not in IDLE state
2885 //
2886 RecordClientVector clients = desc->clientsList();
2887 bool doClose = false;
2888 for (const auto& client : clients) {
2889 if (isSoundTrigger != client->isSoundTrigger()) {
2890 continue;
2891 }
2892 if (client->isSoundTrigger()) {
2893 if (session == client->session()) {
2894 return desc->mIoHandle;
2895 }
2896 continue;
2897 }
2898 if (client->active() && client->appState() != APP_STATE_IDLE) {
2899 return desc->mIoHandle;
2900 }
2901 doClose = true;
2902 }
2903 if (doClose) {
2904 closeInput(desc->mIoHandle);
2905 } else {
2906 i++;
2907 }
2908 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002909 }
2910
Eric Laurentfe231122017-11-17 17:48:06 -08002911 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07002912
Eric Laurentfe231122017-11-17 17:48:06 -08002913 audio_config_t lConfig = AUDIO_CONFIG_INITIALIZER;
2914 lConfig.sample_rate = profileSamplingRate;
2915 lConfig.channel_mask = profileChannelMask;
2916 lConfig.format = profileFormat;
Eric Laurente3014102017-05-03 11:15:43 -07002917
François Gaffie11d30102018-11-02 16:09:09 +01002918 status_t status = inputDesc->open(&lConfig, device, halInputSource, profileFlags, &input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07002919
2920 // only accept input with the exact requested set of parameters
Eric Laurent599c7582015-12-07 18:05:55 -08002921 if (status != NO_ERROR || input == AUDIO_IO_HANDLE_NONE ||
Eric Laurentfe231122017-11-17 17:48:06 -08002922 (profileSamplingRate != lConfig.sample_rate) ||
2923 !audio_formats_match(profileFormat, lConfig.format) ||
2924 (profileChannelMask != lConfig.channel_mask)) {
2925 ALOGW("getInputForAttr() failed opening input: sampling rate %d"
Glenn Kasten49f36ba2017-12-06 13:02:02 -08002926 ", format %#x, channel mask %#x",
Eric Laurentfe231122017-11-17 17:48:06 -08002927 profileSamplingRate, profileFormat, profileChannelMask);
Eric Laurent599c7582015-12-07 18:05:55 -08002928 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfe231122017-11-17 17:48:06 -08002929 inputDesc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07002930 }
Eric Laurent599c7582015-12-07 18:05:55 -08002931 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07002932 }
2933
Eric Laurentc722f302014-12-10 11:21:49 -08002934 inputDesc->mPolicyMix = policyMix;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002935
Eric Laurent599c7582015-12-07 18:05:55 -08002936 addInput(input, inputDesc);
Eric Laurentb52c1522014-05-20 11:27:36 -07002937 mpClientInterface->onAudioPortListUpdate();
Paul McLean466dc8e2015-04-17 13:15:36 -06002938
Eric Laurent599c7582015-12-07 18:05:55 -08002939 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07002940}
2941
Eric Laurent4eb58f12018-12-07 16:41:02 -08002942status_t AudioPolicyManager::startInput(audio_port_handle_t portId)
Eric Laurentbb948092017-01-23 18:33:30 -08002943{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002944 ALOGV("%s portId %d", __FUNCTION__, portId);
2945
2946 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2947 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002948 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurentd52a28c2020-08-21 17:10:39 -07002949 return DEAD_OBJECT;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002950 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002951 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07002952 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002953 if (client->active()) {
2954 ALOGW("%s input %d client %d already started", __FUNCTION__, input, client->portId());
2955 return INVALID_OPERATION;
Eric Laurent4dc68062014-07-28 17:26:49 -07002956 }
2957
Eric Laurent8f42ea12018-08-08 09:08:25 -07002958 audio_session_t session = client->session();
2959
Eric Laurent4eb58f12018-12-07 16:41:02 -08002960 ALOGV("%s input:%d, session:%d)", __FUNCTION__, input, session);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002961
Eric Laurent4eb58f12018-12-07 16:41:02 -08002962 Vector<sp<AudioInputDescriptor>> activeInputs = mInputs.getActiveInputs();
Eric Laurent74708e72017-04-07 17:13:42 -07002963
Eric Laurent4eb58f12018-12-07 16:41:02 -08002964 status_t status = inputDesc->start();
2965 if (status != NO_ERROR) {
2966 return status;
Eric Laurent74708e72017-04-07 17:13:42 -07002967 }
Eric Laurente552edb2014-03-10 17:42:56 -07002968
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002969 // increment activity count before calling getNewInputDevice() below as only active sessions
Eric Laurent313d1e72016-01-29 09:56:57 -08002970 // are considered for device selection
Eric Laurent8f42ea12018-08-08 09:08:25 -07002971 inputDesc->setClientActive(client, true);
Eric Laurent313d1e72016-01-29 09:56:57 -08002972
Eric Laurent8f42ea12018-08-08 09:08:25 -07002973 // indicate active capture to sound trigger service if starting capture from a mic on
2974 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01002975 sp<DeviceDescriptor> device = getNewInputDevice(inputDesc);
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002976 if (device != nullptr) {
2977 status = setInputDevice(input, device, true /* force */);
2978 } else {
2979 ALOGW("%s no new input device can be found for descriptor %d",
2980 __FUNCTION__, inputDesc->getId());
2981 status = BAD_VALUE;
2982 }
Eric Laurente552edb2014-03-10 17:42:56 -07002983
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002984 if (status == NO_ERROR && inputDesc->activeCount() == 1) {
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002985 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002986 // if input maps to a dynamic policy with an activity listener, notify of state change
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002987 if ((policyMix != nullptr)
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002988 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
2989 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
Eric Laurent8f42ea12018-08-08 09:08:25 -07002990 MIX_STATE_MIXING);
Eric Laurent733ce942017-12-07 12:18:25 -08002991 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002992
François Gaffie11d30102018-11-02 16:09:09 +01002993 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
2994 if (primaryInputDevices.contains(device) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07002995 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 1) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07002996 mpClientInterface->setSoundTriggerCaptureState(true);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002997 }
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002998
Eric Laurent8f42ea12018-08-08 09:08:25 -07002999 // automatically enable the remote submix output when input is started if not
3000 // used by a policy mix of type MIX_TYPE_RECORDERS
3001 // For remote submix (a virtual device), we open only one input per capture request.
François Gaffie11d30102018-11-02 16:09:09 +01003002 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003003 String8 address = String8("");
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003004 if (policyMix == nullptr) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003005 address = String8("0");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003006 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
3007 address = policyMix->mDeviceAddress;
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07003008 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07003009 if (address != "") {
3010 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
3011 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08003012 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurentc722f302014-12-10 11:21:49 -08003013 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07003014 }
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003015 } else if (status != NO_ERROR) {
3016 // Restore client activity state.
3017 inputDesc->setClientActive(client, false);
3018 inputDesc->stop();
Eric Laurente552edb2014-03-10 17:42:56 -07003019 }
3020
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003021 ALOGV("%s input %d source = %d status = %d exit",
3022 __FUNCTION__, input, client->source(), status);
Eric Laurente552edb2014-03-10 17:42:56 -07003023
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003024 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07003025}
3026
Eric Laurent8fc147b2018-07-22 19:13:55 -07003027status_t AudioPolicyManager::stopInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07003028{
Eric Laurent8fc147b2018-07-22 19:13:55 -07003029 ALOGV("%s portId %d", __FUNCTION__, portId);
3030
3031 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
3032 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003033 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07003034 return BAD_VALUE;
3035 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07003036 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07003037 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003038 if (!client->active()) {
3039 ALOGW("%s input %d client %d already stopped", __FUNCTION__, input, client->portId());
Eric Laurente552edb2014-03-10 17:42:56 -07003040 return INVALID_OPERATION;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003041 }
Carter Hsue6139d52021-07-08 10:30:20 +08003042 auto old_source = inputDesc->source();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003043 inputDesc->setClientActive(client, false);
Paul McLean466dc8e2015-04-17 13:15:36 -06003044
Eric Laurent8f42ea12018-08-08 09:08:25 -07003045 inputDesc->stop();
3046 if (inputDesc->isActive()) {
Carter Hsue6139d52021-07-08 10:30:20 +08003047 auto current_source = inputDesc->source();
3048 setInputDevice(input, getNewInputDevice(inputDesc),
3049 old_source != current_source /* force */);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003050 } else {
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003051 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003052 // if input maps to a dynamic policy with an activity listener, notify of state change
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003053 if ((policyMix != nullptr)
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003054 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
3055 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
Eric Laurent8f42ea12018-08-08 09:08:25 -07003056 MIX_STATE_IDLE);
Eric Laurent84332aa2016-01-28 22:19:18 +00003057 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07003058
3059 // automatically disable the remote submix output when input is stopped if not
3060 // used by a policy mix of type MIX_TYPE_RECORDERS
François Gaffie11d30102018-11-02 16:09:09 +01003061 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003062 String8 address = String8("");
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003063 if (policyMix == nullptr) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003064 address = String8("0");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003065 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
3066 address = policyMix->mDeviceAddress;
Eric Laurent8f42ea12018-08-08 09:08:25 -07003067 }
3068 if (address != "") {
3069 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
3070 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08003071 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003072 }
3073 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07003074 resetInputDevice(input);
3075
3076 // indicate inactive capture to sound trigger service if stopping capture from a mic on
3077 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01003078 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
3079 if (primaryInputDevices.contains(inputDesc->getDevice()) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07003080 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07003081 mpClientInterface->setSoundTriggerCaptureState(false);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003082 }
3083 inputDesc->clearPreemptedSessions();
Eric Laurente552edb2014-03-10 17:42:56 -07003084 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003085 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07003086}
3087
Eric Laurent8fc147b2018-07-22 19:13:55 -07003088void AudioPolicyManager::releaseInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07003089{
Eric Laurent8fc147b2018-07-22 19:13:55 -07003090 ALOGV("%s portId %d", __FUNCTION__, portId);
3091
3092 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
3093 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003094 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07003095 return;
3096 }
Andy Hung39efb7a2018-09-26 15:39:28 -07003097 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8fc147b2018-07-22 19:13:55 -07003098 audio_io_handle_t input = inputDesc->mIoHandle;
3099
Eric Laurent8f42ea12018-08-08 09:08:25 -07003100 ALOGV("%s %d", __FUNCTION__, input);
Paul McLean466dc8e2015-04-17 13:15:36 -06003101
Andy Hung39efb7a2018-09-26 15:39:28 -07003102 inputDesc->removeClient(portId);
Eric Laurent599c7582015-12-07 18:05:55 -08003103
Andy Hung39efb7a2018-09-26 15:39:28 -07003104 if (inputDesc->getClientCount() > 0) {
3105 ALOGV("%s(%d) %zu clients remaining", __func__, portId, inputDesc->getClientCount());
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003106 return;
3107 }
3108
Eric Laurent05b90f82014-08-27 15:32:29 -07003109 closeInput(input);
Eric Laurentb52c1522014-05-20 11:27:36 -07003110 mpClientInterface->onAudioPortListUpdate();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003111 ALOGV("%s exit", __FUNCTION__);
Eric Laurente552edb2014-03-10 17:42:56 -07003112}
3113
Eric Laurent8f42ea12018-08-08 09:08:25 -07003114void AudioPolicyManager::closeActiveClients(const sp<AudioInputDescriptor>& input)
Eric Laurent8fc147b2018-07-22 19:13:55 -07003115{
Eric Laurent8f42ea12018-08-08 09:08:25 -07003116 RecordClientVector clients = input->clientsList(true);
Eric Laurent8fc147b2018-07-22 19:13:55 -07003117
3118 for (const auto& client : clients) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003119 closeClient(client->portId());
Eric Laurent8fc147b2018-07-22 19:13:55 -07003120 }
3121}
3122
Eric Laurent8f42ea12018-08-08 09:08:25 -07003123void AudioPolicyManager::closeClient(audio_port_handle_t portId)
3124{
3125 stopInput(portId);
3126 releaseInput(portId);
3127}
Eric Laurent8fc147b2018-07-22 19:13:55 -07003128
Eric Laurent0dd51852019-04-19 18:18:58 -07003129void AudioPolicyManager::checkCloseInputs() {
3130 // After connecting or disconnecting an input device, close input if:
3131 // - it has no client (was just opened to check profile) OR
3132 // - none of its supported devices are connected anymore OR
3133 // - one of its clients cannot be routed to one of its supported
3134 // devices anymore. Otherwise update device selection
3135 std::vector<audio_io_handle_t> inputsToClose;
3136 for (size_t i = 0; i < mInputs.size(); i++) {
3137 const sp<AudioInputDescriptor> input = mInputs.valueAt(i);
3138 if (input->clientsList().size() == 0
Eric Laurent85732f42020-03-19 11:31:10 -07003139 || !mAvailableInputDevices.containsAtLeastOne(input->supportedDevices())) {
Eric Laurent0dd51852019-04-19 18:18:58 -07003140 inputsToClose.push_back(mInputs.keyAt(i));
3141 } else {
3142 bool close = false;
3143 for (const auto& client : input->clientsList()) {
3144 sp<DeviceDescriptor> device =
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02003145 mEngine->getInputDeviceForAttributes(client->attributes(), client->uid(),
3146 client->session());
Eric Laurent0dd51852019-04-19 18:18:58 -07003147 if (!input->supportedDevices().contains(device)) {
3148 close = true;
3149 break;
3150 }
3151 }
3152 if (close) {
3153 inputsToClose.push_back(mInputs.keyAt(i));
3154 } else {
3155 setInputDevice(input->mIoHandle, getNewInputDevice(input));
3156 }
3157 }
3158 }
3159
3160 for (const audio_io_handle_t handle : inputsToClose) {
3161 ALOGV("%s closing input %d", __func__, handle);
3162 closeInput(handle);
Eric Laurent05b90f82014-08-27 15:32:29 -07003163 }
Eric Laurentd4692962014-05-05 18:13:44 -07003164}
3165
François Gaffie251c7f02018-11-07 10:41:08 +01003166void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream, int indexMin, int indexMax)
Eric Laurente552edb2014-03-10 17:42:56 -07003167{
3168 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08003169 if (indexMin < 0 || indexMax < 0) {
3170 ALOGE("%s for stream %d: invalid min %d or max %d", __func__, stream , indexMin, indexMax);
3171 return;
3172 }
Eric Laurentf5aa58d2019-02-22 18:20:11 -08003173 getVolumeCurves(stream).initVolume(indexMin, indexMax);
Eric Laurent28d09f02016-03-08 10:43:05 -08003174
3175 // initialize other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08003176 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
3177 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08003178 continue;
3179 }
Eric Laurentf5aa58d2019-02-22 18:20:11 -08003180 getVolumeCurves((audio_stream_type_t)curStream).initVolume(indexMin, indexMax);
Eric Laurent223fd5c2014-11-11 13:43:36 -08003181 }
Eric Laurente552edb2014-03-10 17:42:56 -07003182}
3183
Eric Laurente0720872014-03-11 09:30:41 -07003184status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
François Gaffie53615e22015-03-19 09:24:12 +01003185 int index,
3186 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07003187{
François Gaffieaaac0fd2018-11-22 17:56:39 +01003188 auto attributes = mEngine->getAttributesForStreamType(stream);
Eric Laurent242a9f82020-03-23 15:57:04 -07003189 if (attributes == AUDIO_ATTRIBUTES_INITIALIZER) {
3190 ALOGW("%s: no group for stream %s, bailing out", __func__, toString(stream).c_str());
3191 return NO_ERROR;
3192 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01003193 ALOGV("%s: stream %s attributes=%s", __func__,
3194 toString(stream).c_str(), toString(attributes).c_str());
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003195 return setVolumeIndexForAttributes(attributes, index, device);
Eric Laurente552edb2014-03-10 17:42:56 -07003196}
3197
Eric Laurente0720872014-03-11 09:30:41 -07003198status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
François Gaffieaaac0fd2018-11-22 17:56:39 +01003199 int *index,
3200 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07003201{
François Gaffiec005e562018-11-06 15:04:49 +01003202 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
3203 // stream by the engine.
jiabin9a3361e2019-10-01 09:38:30 -07003204 DeviceTypeSet deviceTypes = {device};
Eric Laurent5a2b6292016-04-14 18:05:57 -07003205 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
jiabin9a3361e2019-10-01 09:38:30 -07003206 deviceTypes = mEngine->getOutputDevicesForStream(
3207 stream, true /*fromCache*/).types();
Eric Laurente552edb2014-03-10 17:42:56 -07003208 }
jiabin9a3361e2019-10-01 09:38:30 -07003209 return getVolumeIndex(getVolumeCurves(stream), *index, deviceTypes);
Eric Laurente552edb2014-03-10 17:42:56 -07003210}
3211
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003212status_t AudioPolicyManager::setVolumeIndexForAttributes(const audio_attributes_t &attributes,
François Gaffiecfe17322018-11-07 13:41:29 +01003213 int index,
3214 audio_devices_t device)
3215{
3216 // Get Volume group matching the Audio Attributes
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003217 auto group = mEngine->getVolumeGroupForAttributes(attributes);
3218 if (group == VOLUME_GROUP_NONE) {
3219 ALOGD("%s: no group matching with %s", __FUNCTION__, toString(attributes).c_str());
François Gaffiecfe17322018-11-07 13:41:29 +01003220 return BAD_VALUE;
3221 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003222 ALOGV("%s: group %d matching with %s", __FUNCTION__, group, toString(attributes).c_str());
François Gaffiecfe17322018-11-07 13:41:29 +01003223 status_t status = NO_ERROR;
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003224 IVolumeCurves &curves = getVolumeCurves(attributes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01003225 VolumeSource vs = toVolumeSource(group);
Eric Laurentf9cccec2022-11-16 19:12:00 +01003226 // AUDIO_STREAM_BLUETOOTH_SCO is only used for volume control so we remap
3227 // to AUDIO_STREAM_VOICE_CALL to match with relevant playback activity
3228 VolumeSource activityVs = (vs == toVolumeSource(AUDIO_STREAM_BLUETOOTH_SCO, false)) ?
3229 toVolumeSource(AUDIO_STREAM_VOICE_CALL, false) : vs;
François Gaffieaaac0fd2018-11-22 17:56:39 +01003230 product_strategy_t strategy = mEngine->getProductStrategyForAttributes(attributes);
3231
3232 status = setVolumeCurveIndex(index, device, curves);
3233 if (status != NO_ERROR) {
3234 ALOGE("%s failed to set curve index for group %d device 0x%X", __func__, group, device);
3235 return status;
3236 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003237
jiabin9a3361e2019-10-01 09:38:30 -07003238 DeviceTypeSet curSrcDevices;
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003239 auto curCurvAttrs = curves.getAttributes();
3240 if (!curCurvAttrs.empty() && curCurvAttrs.front() != defaultAttr) {
3241 auto attr = curCurvAttrs.front();
jiabin9a3361e2019-10-01 09:38:30 -07003242 curSrcDevices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false).types();
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003243 } else if (!curves.getStreamTypes().empty()) {
3244 auto stream = curves.getStreamTypes().front();
jiabin9a3361e2019-10-01 09:38:30 -07003245 curSrcDevices = mEngine->getOutputDevicesForStream(stream, false).types();
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003246 } else {
3247 ALOGE("%s: Invalid src %d: no valid attributes nor stream",__func__, vs);
3248 return BAD_VALUE;
3249 }
jiabin9a3361e2019-10-01 09:38:30 -07003250 audio_devices_t curSrcDevice = Volume::getDeviceForVolume(curSrcDevices);
3251 resetDeviceTypes(curSrcDevices, curSrcDevice);
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003252
François Gaffiecfe17322018-11-07 13:41:29 +01003253 // update volume on all outputs and streams matching the following:
3254 // - The requested stream (or a stream matching for volume control) is active on the output
3255 // - The device (or devices) selected by the engine for this stream includes
3256 // the requested device
3257 // - For non default requested device, currently selected device on the output is either the
3258 // requested device or one of the devices selected by the engine for this stream
3259 // - For default requested device (AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME), apply volume only if
3260 // no specific device volume value exists for currently selected device.
François Gaffieaaac0fd2018-11-22 17:56:39 +01003261 for (size_t i = 0; i < mOutputs.size(); i++) {
3262 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
jiabin9a3361e2019-10-01 09:38:30 -07003263 DeviceTypeSet curDevices = desc->devices().types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01003264
jiabin9a3361e2019-10-01 09:38:30 -07003265 if (curDevices.erase(AUDIO_DEVICE_OUT_SPEAKER_SAFE)) {
3266 curDevices.insert(AUDIO_DEVICE_OUT_SPEAKER);
Robert Lee5e66e792019-04-03 18:37:15 +08003267 }
Eric Laurentf9cccec2022-11-16 19:12:00 +01003268
3269 if (!(desc->isActive(activityVs) || isInCallOrScreening())) {
François Gaffieed91f582020-01-31 10:35:37 +01003270 continue;
3271 }
3272 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME &&
3273 curDevices.find(device) == curDevices.end()) {
3274 continue;
3275 }
3276 bool applyVolume = false;
3277 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
3278 curSrcDevices.insert(device);
3279 applyVolume = (curSrcDevices.find(
3280 Volume::getDeviceForVolume(curDevices)) != curSrcDevices.end());
3281 } else {
3282 applyVolume = !curves.hasVolumeIndexForDevice(curSrcDevice);
3283 }
3284 if (!applyVolume) {
3285 continue; // next output
3286 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01003287 // Inter / intra volume group priority management: Loop on strategies arranged by priority
3288 // If a higher priority strategy is active, and the output is routed to a device with a
3289 // HW Gain management, do not change the volume
François Gaffieaaac0fd2018-11-22 17:56:39 +01003290 if (desc->useHwGain()) {
François Gaffieed91f582020-01-31 10:35:37 +01003291 applyVolume = false;
Francois Gaffie593634d2021-06-22 13:31:31 +02003292 // If the volume source is active with higher priority source, ensure at least Sw Muted
3293 desc->setSwMute((index == 0), vs, curves.getStreamTypes(), curDevices, 0 /*delayMs*/);
François Gaffieaaac0fd2018-11-22 17:56:39 +01003294 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
3295 auto activeClients = desc->clientsList(true /*activeOnly*/, productStrategy,
3296 false /*preferredDevice*/);
3297 if (activeClients.empty()) {
3298 continue;
3299 }
3300 bool isPreempted = false;
3301 bool isHigherPriority = productStrategy < strategy;
3302 for (const auto &client : activeClients) {
Eric Laurentf9cccec2022-11-16 19:12:00 +01003303 if (isHigherPriority && (client->volumeSource() != activityVs)) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01003304 ALOGV("%s: Strategy=%d (\nrequester:\n"
3305 " group %d, volumeGroup=%d attributes=%s)\n"
3306 " higher priority source active:\n"
3307 " volumeGroup=%d attributes=%s) \n"
3308 " on output %zu, bailing out", __func__, productStrategy,
3309 group, group, toString(attributes).c_str(),
3310 client->volumeSource(), toString(client->attributes()).c_str(), i);
3311 applyVolume = false;
3312 isPreempted = true;
3313 break;
3314 }
3315 // However, continue for loop to ensure no higher prio clients running on output
Eric Laurentf9cccec2022-11-16 19:12:00 +01003316 if (client->volumeSource() == activityVs) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01003317 applyVolume = true;
3318 }
3319 }
3320 if (isPreempted || applyVolume) {
3321 break;
3322 }
3323 }
3324 if (!applyVolume) {
3325 continue; // next output
3326 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01003327 }
François Gaffieed91f582020-01-31 10:35:37 +01003328 //FIXME: workaround for truncated touch sounds
3329 // delayed volume change for system stream to be removed when the problem is
3330 // handled by system UI
3331 status_t volStatus = checkAndSetVolume(
3332 curves, vs, index, desc, curDevices,
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003333 ((vs == toVolumeSource(AUDIO_STREAM_SYSTEM, false))?
François Gaffieed91f582020-01-31 10:35:37 +01003334 TOUCH_SOUND_FIXED_DELAY_MS : 0));
3335 if (volStatus != NO_ERROR) {
3336 status = volStatus;
François Gaffieaaac0fd2018-11-22 17:56:39 +01003337 }
3338 }
François Gaffiecfe17322018-11-07 13:41:29 +01003339 mpClientInterface->onAudioVolumeGroupChanged(group, 0 /*flags*/);
3340 return status;
3341}
3342
François Gaffieaaac0fd2018-11-22 17:56:39 +01003343status_t AudioPolicyManager::setVolumeCurveIndex(int index,
François Gaffiecfe17322018-11-07 13:41:29 +01003344 audio_devices_t device,
3345 IVolumeCurves &volumeCurves)
3346{
3347 // VOICE_CALL stream has minVolumeIndex > 0 but can be muted directly by an
3348 // app that has MODIFY_PHONE_STATE permission.
François Gaffieaaac0fd2018-11-22 17:56:39 +01003349 bool hasVoice = hasVoiceStream(volumeCurves.getStreamTypes());
3350 if (((index < volumeCurves.getVolumeIndexMin()) && !(hasVoice && index == 0)) ||
François Gaffiecfe17322018-11-07 13:41:29 +01003351 (index > volumeCurves.getVolumeIndexMax())) {
3352 ALOGD("%s: wrong index %d min=%d max=%d", __FUNCTION__, index,
3353 volumeCurves.getVolumeIndexMin(), volumeCurves.getVolumeIndexMax());
3354 return BAD_VALUE;
3355 }
3356 if (!audio_is_output_device(device)) {
3357 return BAD_VALUE;
3358 }
3359
3360 // Force max volume if stream cannot be muted
3361 if (!volumeCurves.canBeMuted()) index = volumeCurves.getVolumeIndexMax();
3362
François Gaffieaaac0fd2018-11-22 17:56:39 +01003363 ALOGV("%s device %08x, index %d", __FUNCTION__ , device, index);
François Gaffiecfe17322018-11-07 13:41:29 +01003364 volumeCurves.addCurrentVolumeIndex(device, index);
3365 return NO_ERROR;
3366}
3367
3368status_t AudioPolicyManager::getVolumeIndexForAttributes(const audio_attributes_t &attr,
3369 int &index,
3370 audio_devices_t device)
3371{
3372 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
3373 // stream by the engine.
jiabin9a3361e2019-10-01 09:38:30 -07003374 DeviceTypeSet deviceTypes = {device};
François Gaffiecfe17322018-11-07 13:41:29 +01003375 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
Mikhail Naganovbb990f22022-06-15 00:46:43 +00003376 deviceTypes = mEngine->getOutputDevicesForAttributes(
jiabin9a3361e2019-10-01 09:38:30 -07003377 attr, nullptr, true /*fromCache*/).types();
François Gaffiecfe17322018-11-07 13:41:29 +01003378 }
jiabin9a3361e2019-10-01 09:38:30 -07003379 return getVolumeIndex(getVolumeCurves(attr), index, deviceTypes);
François Gaffiecfe17322018-11-07 13:41:29 +01003380}
3381
3382status_t AudioPolicyManager::getVolumeIndex(const IVolumeCurves &curves,
3383 int &index,
jiabin9a3361e2019-10-01 09:38:30 -07003384 const DeviceTypeSet& deviceTypes) const
François Gaffiecfe17322018-11-07 13:41:29 +01003385{
Mikhail Naganovbb990f22022-06-15 00:46:43 +00003386 if (!isSingleDeviceType(deviceTypes, audio_is_output_device)) {
François Gaffiecfe17322018-11-07 13:41:29 +01003387 return BAD_VALUE;
3388 }
jiabin9a3361e2019-10-01 09:38:30 -07003389 index = curves.getVolumeIndex(deviceTypes);
3390 ALOGV("%s: device %s index %d", __FUNCTION__, dumpDeviceTypes(deviceTypes).c_str(), index);
François Gaffiecfe17322018-11-07 13:41:29 +01003391 return NO_ERROR;
3392}
3393
3394status_t AudioPolicyManager::getMinVolumeIndexForAttributes(const audio_attributes_t &attr,
3395 int &index)
3396{
3397 index = getVolumeCurves(attr).getVolumeIndexMin();
3398 return NO_ERROR;
3399}
3400
3401status_t AudioPolicyManager::getMaxVolumeIndexForAttributes(const audio_attributes_t &attr,
3402 int &index)
3403{
3404 index = getVolumeCurves(attr).getVolumeIndexMax();
3405 return NO_ERROR;
3406}
3407
Eric Laurent36829f92017-04-07 19:04:42 -07003408audio_io_handle_t AudioPolicyManager::selectOutputForMusicEffects()
Eric Laurente552edb2014-03-10 17:42:56 -07003409{
3410 // select one output among several suitable for global effects.
3411 // The priority is as follows:
3412 // 1: An offloaded output. If the effect ends up not being offloadable,
3413 // AudioFlinger will invalidate the track and the offloaded output
3414 // will be closed causing the effect to be moved to a PCM output.
3415 // 2: A deep buffer output
Eric Laurent36829f92017-04-07 19:04:42 -07003416 // 3: The primary output
3417 // 4: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07003418
François Gaffiec005e562018-11-06 15:04:49 +01003419 DeviceVector devices = mEngine->getOutputDevicesForAttributes(
3420 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
François Gaffie11d30102018-11-02 16:09:09 +01003421 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07003422
Eric Laurent36829f92017-04-07 19:04:42 -07003423 if (outputs.size() == 0) {
3424 return AUDIO_IO_HANDLE_NONE;
3425 }
Eric Laurente552edb2014-03-10 17:42:56 -07003426
Eric Laurent36829f92017-04-07 19:04:42 -07003427 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
3428 bool activeOnly = true;
3429
3430 while (output == AUDIO_IO_HANDLE_NONE) {
3431 audio_io_handle_t outputOffloaded = AUDIO_IO_HANDLE_NONE;
3432 audio_io_handle_t outputDeepBuffer = AUDIO_IO_HANDLE_NONE;
3433 audio_io_handle_t outputPrimary = AUDIO_IO_HANDLE_NONE;
3434
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003435 for (audio_io_handle_t output : outputs) {
3436 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
Eric Laurent83d17c22019-04-02 17:10:01 -07003437 if (activeOnly && !desc->isActive(toVolumeSource(AUDIO_STREAM_MUSIC))) {
Eric Laurent36829f92017-04-07 19:04:42 -07003438 continue;
3439 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003440 ALOGV("selectOutputForMusicEffects activeOnly %d output %d flags 0x%08x",
3441 activeOnly, output, desc->mFlags);
Eric Laurent36829f92017-04-07 19:04:42 -07003442 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003443 outputOffloaded = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003444 }
3445 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003446 outputDeepBuffer = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003447 }
3448 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003449 outputPrimary = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003450 }
3451 }
3452 if (outputOffloaded != AUDIO_IO_HANDLE_NONE) {
3453 output = outputOffloaded;
3454 } else if (outputDeepBuffer != AUDIO_IO_HANDLE_NONE) {
3455 output = outputDeepBuffer;
3456 } else if (outputPrimary != AUDIO_IO_HANDLE_NONE) {
3457 output = outputPrimary;
3458 } else {
3459 output = outputs[0];
3460 }
3461 activeOnly = false;
3462 }
3463
3464 if (output != mMusicEffectOutput) {
Eric Laurent6c796322019-04-09 14:13:17 -07003465 mEffects.moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output);
Eric Laurent36829f92017-04-07 19:04:42 -07003466 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output);
3467 mMusicEffectOutput = output;
3468 }
3469
3470 ALOGV("selectOutputForMusicEffects selected output %d", output);
Eric Laurente552edb2014-03-10 17:42:56 -07003471 return output;
3472}
3473
Eric Laurent36829f92017-04-07 19:04:42 -07003474audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc __unused)
3475{
3476 return selectOutputForMusicEffects();
3477}
3478
Eric Laurente0720872014-03-11 09:30:41 -07003479status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07003480 audio_io_handle_t io,
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08003481 product_strategy_t strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07003482 int session,
3483 int id)
3484{
Eric Laurentb82e6b72019-11-22 17:25:04 -08003485 if (session != AUDIO_SESSION_DEVICE) {
3486 ssize_t index = mOutputs.indexOfKey(io);
Eric Laurente552edb2014-03-10 17:42:56 -07003487 if (index < 0) {
Eric Laurentb82e6b72019-11-22 17:25:04 -08003488 index = mInputs.indexOfKey(io);
3489 if (index < 0) {
3490 ALOGW("registerEffect() unknown io %d", io);
3491 return INVALID_OPERATION;
3492 }
Eric Laurente552edb2014-03-10 17:42:56 -07003493 }
3494 }
Eric Laurentbf8f69f2022-03-25 17:48:38 +01003495 bool isMusicEffect = (session != AUDIO_SESSION_OUTPUT_STAGE)
3496 && ((strategy == streamToStrategy(AUDIO_STREAM_MUSIC)
3497 || strategy == PRODUCT_STRATEGY_NONE));
3498 return mEffects.registerEffect(desc, io, session, id, isMusicEffect);
Eric Laurente552edb2014-03-10 17:42:56 -07003499}
3500
Eric Laurentc241b0d2018-11-28 09:08:49 -08003501status_t AudioPolicyManager::unregisterEffect(int id)
3502{
3503 if (mEffects.getEffect(id) == nullptr) {
3504 return INVALID_OPERATION;
3505 }
Eric Laurentc241b0d2018-11-28 09:08:49 -08003506 if (mEffects.isEffectEnabled(id)) {
3507 ALOGW("%s effect %d enabled", __FUNCTION__, id);
3508 setEffectEnabled(id, false);
3509 }
3510 return mEffects.unregisterEffect(id);
3511}
3512
3513status_t AudioPolicyManager::setEffectEnabled(int id, bool enabled)
3514{
3515 sp<EffectDescriptor> effect = mEffects.getEffect(id);
3516 if (effect == nullptr) {
3517 return INVALID_OPERATION;
3518 }
3519
3520 status_t status = mEffects.setEffectEnabled(id, enabled);
3521 if (status == NO_ERROR) {
3522 mInputs.trackEffectEnabled(effect, enabled);
3523 }
3524 return status;
3525}
3526
Eric Laurent6c796322019-04-09 14:13:17 -07003527
3528status_t AudioPolicyManager::moveEffectsToIo(const std::vector<int>& ids, audio_io_handle_t io)
3529{
3530 mEffects.moveEffects(ids, io);
3531 return NO_ERROR;
3532}
3533
Eric Laurentc75307b2015-03-17 15:29:32 -07003534bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
3535{
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003536 auto vs = toVolumeSource(stream, false);
3537 return vs != VOLUME_SOURCE_NONE ? mOutputs.isActive(vs, inPastMs) : false;
Eric Laurentc75307b2015-03-17 15:29:32 -07003538}
3539
3540bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream, uint32_t inPastMs) const
3541{
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003542 auto vs = toVolumeSource(stream, false);
3543 return vs != VOLUME_SOURCE_NONE ? mOutputs.isActiveRemotely(vs, inPastMs) : false;
Eric Laurentc75307b2015-03-17 15:29:32 -07003544}
3545
Eric Laurente0720872014-03-11 09:30:41 -07003546bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07003547{
3548 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003549 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08003550 if (inputDescriptor->isSourceActive(source)) {
Eric Laurente552edb2014-03-10 17:42:56 -07003551 return true;
3552 }
3553 }
3554 return false;
3555}
3556
Eric Laurent275e8e92014-11-30 15:14:47 -08003557// Register a list of custom mixes with their attributes and format.
3558// When a mix is registered, corresponding input and output profiles are
3559// added to the remote submix hw module. The profile contains only the
3560// parameters (sampling rate, format...) specified by the mix.
3561// The corresponding input remote submix device is also connected.
3562//
3563// When a remote submix device is connected, the address is checked to select the
3564// appropriate profile and the corresponding input or output stream is opened.
3565//
3566// When capture starts, getInputForAttr() will:
3567// - 1 look for a mix matching the address passed in attribtutes tags if any
3568// - 2 if none found, getDeviceForInputSource() will:
3569// - 2.1 look for a mix matching the attributes source
3570// - 2.2 if none found, default to device selection by policy rules
3571// At this time, the corresponding output remote submix device is also connected
3572// and active playback use cases can be transferred to this mix if needed when reconnecting
3573// after AudioTracks are invalidated
3574//
3575// When playback starts, getOutputForAttr() will:
3576// - 1 look for a mix matching the address passed in attribtutes tags if any
3577// - 2 if none found, look for a mix matching the attributes usage
3578// - 3 if none found, default to device and output selection by policy rules.
3579
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003580status_t AudioPolicyManager::registerPolicyMixes(const Vector<AudioMix>& mixes)
Eric Laurent275e8e92014-11-30 15:14:47 -08003581{
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003582 ALOGV("registerPolicyMixes() %zu mix(es)", mixes.size());
3583 status_t res = NO_ERROR;
Eric Laurentc209fe42020-06-05 18:11:23 -07003584 bool checkOutputs = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003585 sp<HwModule> rSubmixModule;
3586 // examine each mix's route type
3587 for (size_t i = 0; i < mixes.size(); i++) {
Eric Laurent97ac8712018-07-27 18:59:02 -07003588 AudioMix mix = mixes[i];
Kevin Rocard153f92d2018-12-18 18:33:28 -08003589 // Only capture of playback is allowed in LOOP_BACK & RENDER mode
3590 if (is_mix_loopback_render(mix.mRouteFlags) && mix.mMixType != MIX_TYPE_PLAYERS) {
3591 ALOGE("Unsupported Policy Mix %zu of %zu: "
3592 "Only capture of playback is allowed in LOOP_BACK & RENDER mode",
3593 i, mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003594 res = INVALID_OPERATION;
Eric Laurent275e8e92014-11-30 15:14:47 -08003595 break;
3596 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08003597 // LOOP_BACK and LOOP_BACK | RENDER have the same remote submix backend and are handled
3598 // in the same way.
Eric Laurent97ac8712018-07-27 18:59:02 -07003599 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003600 ALOGV("registerPolicyMixes() mix %zu of %zu is LOOP_BACK %d", i, mixes.size(),
3601 mix.mRouteFlags);
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003602 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003603 rSubmixModule = mHwModules.getModuleFromName(
3604 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
3605 if (rSubmixModule == 0) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003606 ALOGE("Unable to find audio module for submix, aborting mix %zu registration",
Mikhail Naganovd4120142017-12-06 15:49:22 -08003607 i);
3608 res = INVALID_OPERATION;
3609 break;
3610 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003611 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003612
Eric Laurent97ac8712018-07-27 18:59:02 -07003613 String8 address = mix.mDeviceAddress;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003614 audio_devices_t deviceTypeToMakeAvailable;
Eric Laurent97ac8712018-07-27 18:59:02 -07003615 if (mix.mMixType == MIX_TYPE_PLAYERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07003616 mix.mDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003617 deviceTypeToMakeAvailable = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
3618 } else {
3619 mix.mDeviceType = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
3620 deviceTypeToMakeAvailable = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Eric Laurent97ac8712018-07-27 18:59:02 -07003621 }
François Gaffie036e1e92015-03-19 10:16:24 +01003622
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003623 if (mPolicyMixes.registerMix(mix, 0 /*output desc*/) != NO_ERROR) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003624 ALOGE("Error registering mix %zu for address %s", i, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003625 res = INVALID_OPERATION;
3626 break;
3627 }
Eric Laurent97ac8712018-07-27 18:59:02 -07003628 audio_config_t outputConfig = mix.mFormat;
3629 audio_config_t inputConfig = mix.mFormat;
Eric Laurentc529cf62020-04-17 18:19:10 -07003630 // NOTE: audio flinger mixer does not support mono output: configure remote submix HAL
3631 // in stereo and let audio flinger do the channel conversion if needed.
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003632 outputConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
3633 inputConfig.channel_mask = AUDIO_CHANNEL_IN_STEREO;
jiabin5740f082019-08-19 15:08:30 -07003634 rSubmixModule->addOutputProfile(address.c_str(), &outputConfig,
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003635 AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address);
jiabin5740f082019-08-19 15:08:30 -07003636 rSubmixModule->addInputProfile(address.c_str(), &inputConfig,
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003637 AUDIO_DEVICE_IN_REMOTE_SUBMIX, address);
François Gaffie036e1e92015-03-19 10:16:24 +01003638
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003639 if ((res = setDeviceConnectionStateInt(deviceTypeToMakeAvailable,
jiabinc1de2df2019-05-07 14:26:40 -07003640 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
3641 address.string(), "remote-submix", AUDIO_FORMAT_DEFAULT)) != NO_ERROR) {
3642 ALOGE("Failed to set remote submix device available, type %u, address %s",
3643 mix.mDeviceType, address.string());
3644 break;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003645 }
Eric Laurent97ac8712018-07-27 18:59:02 -07003646 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
3647 String8 address = mix.mDeviceAddress;
Eric Laurent2c80be02019-01-23 18:06:37 -08003648 audio_devices_t type = mix.mDeviceType;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003649 ALOGV(" registerPolicyMixes() mix %zu of %zu is RENDER, dev=0x%X addr=%s",
Eric Laurent2c80be02019-01-23 18:06:37 -08003650 i, mixes.size(), type, address.string());
3651
3652 sp<DeviceDescriptor> device = mHwModules.getDeviceDescriptor(
3653 mix.mDeviceType, mix.mDeviceAddress,
3654 String8(), AUDIO_FORMAT_DEFAULT);
3655 if (device == nullptr) {
3656 res = INVALID_OPERATION;
3657 break;
3658 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003659
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003660 bool foundOutput = false;
Eric Laurentc529cf62020-04-17 18:19:10 -07003661 // First try to find an already opened output supporting the device
3662 for (size_t j = 0 ; j < mOutputs.size() && !foundOutput && res == NO_ERROR; j++) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003663 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurent2c80be02019-01-23 18:06:37 -08003664
Eric Laurentc529cf62020-04-17 18:19:10 -07003665 if (!desc->isDuplicated() && desc->supportedDevices().contains(device)) {
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003666 if (mPolicyMixes.registerMix(mix, desc) != NO_ERROR) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003667 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
3668 address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003669 res = INVALID_OPERATION;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003670 } else {
3671 foundOutput = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003672 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003673 }
3674 }
Eric Laurentc529cf62020-04-17 18:19:10 -07003675 // If no output found, try to find a direct output profile supporting the device
3676 for (size_t i = 0; i < mHwModules.size() && !foundOutput && res == NO_ERROR; i++) {
3677 sp<HwModule> module = mHwModules[i];
3678 for (size_t j = 0;
3679 j < module->getOutputProfiles().size() && !foundOutput && res == NO_ERROR;
3680 j++) {
3681 sp<IOProfile> profile = module->getOutputProfiles()[j];
3682 if (profile->isDirectOutput() && profile->supportsDevice(device)) {
3683 if (mPolicyMixes.registerMix(mix, nullptr) != NO_ERROR) {
3684 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
3685 address.string());
3686 res = INVALID_OPERATION;
3687 } else {
3688 foundOutput = true;
3689 }
3690 }
3691 }
3692 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003693 if (res != NO_ERROR) {
3694 ALOGE(" Error registering mix %zu for device 0x%X addr %s",
Eric Laurent2c80be02019-01-23 18:06:37 -08003695 i, type, address.string());
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003696 res = INVALID_OPERATION;
3697 break;
3698 } else if (!foundOutput) {
3699 ALOGE(" Output not found for mix %zu for device 0x%X addr %s",
Eric Laurent2c80be02019-01-23 18:06:37 -08003700 i, type, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003701 res = INVALID_OPERATION;
3702 break;
Eric Laurentc209fe42020-06-05 18:11:23 -07003703 } else {
3704 checkOutputs = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003705 }
Eric Laurentc722f302014-12-10 11:21:49 -08003706 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003707 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003708 if (res != NO_ERROR) {
3709 unregisterPolicyMixes(mixes);
Eric Laurentc209fe42020-06-05 18:11:23 -07003710 } else if (checkOutputs) {
3711 checkForDeviceAndOutputChanges();
3712 updateCallAndOutputRouting();
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003713 }
3714 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08003715}
3716
3717status_t AudioPolicyManager::unregisterPolicyMixes(Vector<AudioMix> mixes)
3718{
Eric Laurent7b279bb2015-12-14 10:18:23 -08003719 ALOGV("unregisterPolicyMixes() num mixes %zu", mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003720 status_t res = NO_ERROR;
Eric Laurentc209fe42020-06-05 18:11:23 -07003721 bool checkOutputs = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003722 sp<HwModule> rSubmixModule;
3723 // examine each mix's route type
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003724 for (const auto& mix : mixes) {
3725 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie036e1e92015-03-19 10:16:24 +01003726
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003727 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003728 rSubmixModule = mHwModules.getModuleFromName(
3729 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
3730 if (rSubmixModule == 0) {
3731 res = INVALID_OPERATION;
3732 continue;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003733 }
3734 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003735
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003736 String8 address = mix.mDeviceAddress;
Eric Laurent275e8e92014-11-30 15:14:47 -08003737
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003738 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003739 res = INVALID_OPERATION;
3740 continue;
3741 }
3742
Kevin Rocard04ed0462019-05-02 17:53:24 -07003743 for (auto device : {AUDIO_DEVICE_IN_REMOTE_SUBMIX, AUDIO_DEVICE_OUT_REMOTE_SUBMIX}) {
3744 if (getDeviceConnectionState(device, address.string()) ==
3745 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
3746 res = setDeviceConnectionStateInt(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
3747 address.string(), "remote-submix",
3748 AUDIO_FORMAT_DEFAULT);
3749 if (res != OK) {
3750 ALOGE("Error making RemoteSubmix device unavailable for mix "
3751 "with type %d, address %s", device, address.string());
3752 }
3753 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003754 }
jiabin5740f082019-08-19 15:08:30 -07003755 rSubmixModule->removeOutputProfile(address.c_str());
3756 rSubmixModule->removeInputProfile(address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003757
Kevin Rocard153f92d2018-12-18 18:33:28 -08003758 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003759 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003760 res = INVALID_OPERATION;
3761 continue;
Eric Laurentc209fe42020-06-05 18:11:23 -07003762 } else {
3763 checkOutputs = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003764 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003765 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003766 }
Eric Laurentc209fe42020-06-05 18:11:23 -07003767 if (res == NO_ERROR && checkOutputs) {
3768 checkForDeviceAndOutputChanges();
3769 updateCallAndOutputRouting();
3770 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003771 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08003772}
3773
Mikhail Naganov100f0122018-11-29 11:22:16 -08003774void AudioPolicyManager::dumpManualSurroundFormats(String8 *dst) const
3775{
3776 size_t i = 0;
3777 constexpr size_t audioFormatPrefixLen = sizeof("AUDIO_FORMAT_");
3778 for (const auto& fmt : mManualSurroundFormats) {
3779 if (i++ != 0) dst->append(", ");
3780 std::string sfmt;
3781 FormatConverter::toString(fmt, sfmt);
3782 dst->append(sfmt.size() >= audioFormatPrefixLen ?
3783 sfmt.c_str() + audioFormatPrefixLen - 1 : sfmt.c_str());
3784 }
3785}
3786
Eric Laurentc529cf62020-04-17 18:19:10 -07003787// Returns true if all devices types match the predicate and are supported by one HW module
3788bool AudioPolicyManager::areAllDevicesSupported(
jiabin6a02d532020-08-07 11:56:38 -07003789 const AudioDeviceTypeAddrVector& devices,
Eric Laurentc529cf62020-04-17 18:19:10 -07003790 std::function<bool(audio_devices_t)> predicate,
Eric Laurent78fedbf2023-03-09 14:40:44 +01003791 const char *context,
3792 bool matchAddress) {
Eric Laurentc529cf62020-04-17 18:19:10 -07003793 for (size_t i = 0; i < devices.size(); i++) {
3794 sp<DeviceDescriptor> devDesc = mHwModules.getDeviceDescriptor(
jiabin0a488932020-08-07 17:32:40 -07003795 devices[i].mType, devices[i].getAddress(), String8(),
Eric Laurent78fedbf2023-03-09 14:40:44 +01003796 AUDIO_FORMAT_DEFAULT, false /*allowToCreate*/, matchAddress);
Eric Laurentc529cf62020-04-17 18:19:10 -07003797 if (devDesc == nullptr || (predicate != nullptr && !predicate(devices[i].mType))) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003798 ALOGE("%s: device type %#x address %s not supported or not match predicate",
jiabin0a488932020-08-07 17:32:40 -07003799 context, devices[i].mType, devices[i].getAddress());
Eric Laurentc529cf62020-04-17 18:19:10 -07003800 return false;
3801 }
3802 }
3803 return true;
3804}
3805
Oscar Azucena6acf34b2023-04-27 16:32:09 -07003806void AudioPolicyManager::changeOutputDevicesMuteState(
3807 const AudioDeviceTypeAddrVector& devices) {
3808 ALOGVV("%s() num devices %zu", __func__, devices.size());
3809
3810 std::vector<sp<SwAudioOutputDescriptor>> outputs =
3811 getSoftwareOutputsForDevices(devices);
3812
3813 for (size_t i = 0; i < outputs.size(); i++) {
3814 sp<SwAudioOutputDescriptor> outputDesc = outputs[i];
3815 DeviceVector prevDevices = outputDesc->devices();
3816 checkDeviceMuteStrategies(outputDesc, prevDevices, 0 /* delayMs */);
3817 }
3818}
3819
3820std::vector<sp<SwAudioOutputDescriptor>> AudioPolicyManager::getSoftwareOutputsForDevices(
3821 const AudioDeviceTypeAddrVector& devices) const
3822{
3823 std::vector<sp<SwAudioOutputDescriptor>> outputs;
3824 DeviceVector deviceDescriptors;
3825 for (size_t j = 0; j < devices.size(); j++) {
3826 sp<DeviceDescriptor> desc = mHwModules.getDeviceDescriptor(
3827 devices[j].mType, devices[j].getAddress(), String8(), AUDIO_FORMAT_DEFAULT);
3828 if (desc == nullptr || !audio_is_output_device(devices[j].mType)) {
3829 ALOGE("%s: device type %#x address %s not supported or not an output device",
3830 __func__, devices[j].mType, devices[j].getAddress());
3831 continue;
3832 }
3833 deviceDescriptors.add(desc);
3834 }
3835 for (size_t i = 0; i < mOutputs.size(); i++) {
3836 if (!mOutputs.valueAt(i)->supportsAtLeastOne(deviceDescriptors)) {
3837 continue;
3838 }
3839 outputs.push_back(mOutputs.valueAt(i));
3840 }
3841 return outputs;
3842}
3843
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003844status_t AudioPolicyManager::setUidDeviceAffinities(uid_t uid,
jiabin6a02d532020-08-07 11:56:38 -07003845 const AudioDeviceTypeAddrVector& devices) {
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003846 ALOGV("%s() uid=%d num devices %zu", __FUNCTION__, uid, devices.size());
Eric Laurentc529cf62020-04-17 18:19:10 -07003847 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
3848 return BAD_VALUE;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003849 }
3850 status_t res = mPolicyMixes.setUidDeviceAffinities(uid, devices);
Eric Laurentc529cf62020-04-17 18:19:10 -07003851 if (res != NO_ERROR) {
3852 ALOGE("%s() Could not set all device affinities for uid = %d", __FUNCTION__, uid);
3853 return res;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003854 }
Eric Laurentc529cf62020-04-17 18:19:10 -07003855
3856 checkForDeviceAndOutputChanges();
3857 updateCallAndOutputRouting();
3858
3859 return NO_ERROR;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003860}
3861
3862status_t AudioPolicyManager::removeUidDeviceAffinities(uid_t uid) {
3863 ALOGV("%s() uid=%d", __FUNCTION__, uid);
Oscar Azucena4b2a8212019-04-26 23:48:59 -07003864 status_t res = mPolicyMixes.removeUidDeviceAffinities(uid);
3865 if (res != NO_ERROR) {
Eric Laurentc529cf62020-04-17 18:19:10 -07003866 ALOGE("%s() Could not remove all device affinities for uid = %d",
Oscar Azucena4b2a8212019-04-26 23:48:59 -07003867 __FUNCTION__, uid);
3868 return INVALID_OPERATION;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003869 }
3870
Eric Laurentc529cf62020-04-17 18:19:10 -07003871 checkForDeviceAndOutputChanges();
3872 updateCallAndOutputRouting();
3873
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003874 return res;
3875}
3876
Eric Laurent2517af32020-11-25 15:31:27 +01003877
jiabin0a488932020-08-07 17:32:40 -07003878status_t AudioPolicyManager::setDevicesRoleForStrategy(product_strategy_t strategy,
3879 device_role_t role,
3880 const AudioDeviceTypeAddrVector &devices) {
3881 ALOGV("%s() strategy=%d role=%d %s", __func__, strategy, role,
3882 dumpAudioDeviceTypeAddrVector(devices).c_str());
Eric Laurentc529cf62020-04-17 18:19:10 -07003883
Eric Laurentc529cf62020-04-17 18:19:10 -07003884 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003885 return BAD_VALUE;
3886 }
jiabin0a488932020-08-07 17:32:40 -07003887 status_t status = mEngine->setDevicesRoleForStrategy(strategy, role, devices);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003888 if (status != NO_ERROR) {
jiabin0a488932020-08-07 17:32:40 -07003889 ALOGW("Engine could not set preferred devices %s for strategy %d role %d",
3890 dumpAudioDeviceTypeAddrVector(devices).c_str(), strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003891 return status;
3892 }
3893
3894 checkForDeviceAndOutputChanges();
Eric Laurent2517af32020-11-25 15:31:27 +01003895
3896 bool forceVolumeReeval = false;
3897 // FIXME: workaround for truncated touch sounds
3898 // to be removed when the problem is handled by system UI
3899 uint32_t delayMs = 0;
3900 if (strategy == mCommunnicationStrategy) {
3901 forceVolumeReeval = true;
3902 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
3903 updateInputRouting();
3904 }
3905 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003906
3907 return NO_ERROR;
3908}
3909
Oscar Azucena6acf34b2023-04-27 16:32:09 -07003910void AudioPolicyManager::updateCallAndOutputRouting(bool forceVolumeReeval, uint32_t delayMs,
3911 bool skipDelays)
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003912{
3913 uint32_t waitMs = 0;
Eric Laurent96d1dda2022-03-14 17:14:19 +01003914 bool wasLeUnicastActive = isLeUnicastActive();
Francois Gaffie19fd6c52021-02-04 17:02:59 +01003915 if (updateCallRouting(true /*fromCache*/, delayMs, &waitMs) == NO_ERROR) {
Eric Laurentb36b4ac2020-08-21 12:50:41 -07003916 // Only apply special touch sound delay once
3917 delayMs = 0;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003918 }
jiabin3ff8d7d2022-12-13 06:27:44 +00003919 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003920 for (size_t i = 0; i < mOutputs.size(); i++) {
3921 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
3922 DeviceVector newDevices = getNewOutputDevices(outputDesc, true /*fromCache*/);
Francois Gaffie601801d2021-06-22 13:27:39 +02003923 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) ||
3924 (outputDesc != mPrimaryOutput && !isTelephonyRxOrTx(outputDesc))) {
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003925 // As done in setDeviceConnectionState, we could also fix default device issue by
3926 // preventing the force re-routing in case of default dev that distinguishes on address.
3927 // Let's give back to engine full device choice decision however.
Francois Gaffie601801d2021-06-22 13:27:39 +02003928 bool forceRouting = !newDevices.isEmpty();
jiabin3ff8d7d2022-12-13 06:27:44 +00003929 if (outputDesc->mUsePreferredMixerAttributes && newDevices != outputDesc->devices()) {
3930 // If the device is using preferred mixer attributes, the output need to reopen
3931 // with default configuration when the new selected devices are different from
3932 // current routing devices.
3933 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices);
3934 continue;
3935 }
Francois Gaffie601801d2021-06-22 13:27:39 +02003936 waitMs = setOutputDevices(outputDesc, newDevices, forceRouting, delayMs, nullptr,
Oscar Azucena6acf34b2023-04-27 16:32:09 -07003937 !skipDelays /*requiresMuteCheck*/,
3938 !forceRouting /*requiresVolumeCheck*/, skipDelays);
Eric Laurentb36b4ac2020-08-21 12:50:41 -07003939 // Only apply special touch sound delay once
3940 delayMs = 0;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003941 }
3942 if (forceVolumeReeval && !newDevices.isEmpty()) {
3943 applyStreamVolumes(outputDesc, newDevices.types(), waitMs, true);
3944 }
3945 }
jiabin3ff8d7d2022-12-13 06:27:44 +00003946 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent96d1dda2022-03-14 17:14:19 +01003947 checkLeBroadcastRoutes(wasLeUnicastActive, nullptr, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003948}
3949
Eric Laurent2517af32020-11-25 15:31:27 +01003950void AudioPolicyManager::updateInputRouting() {
3951 for (const auto& activeDesc : mInputs.getActiveInputs()) {
Jaideep Sharma408349a2020-11-27 14:47:17 +05303952 // Skip for hotword recording as the input device switch
3953 // is handled within sound trigger HAL
3954 if (activeDesc->isSoundTrigger() && activeDesc->source() == AUDIO_SOURCE_HOTWORD) {
3955 continue;
3956 }
Eric Laurent2517af32020-11-25 15:31:27 +01003957 auto newDevice = getNewInputDevice(activeDesc);
3958 // Force new input selection if the new device can not be reached via current input
3959 if (activeDesc->mProfile->getSupportedDevices().contains(newDevice)) {
3960 setInputDevice(activeDesc->mIoHandle, newDevice);
3961 } else {
3962 closeInput(activeDesc->mIoHandle);
3963 }
3964 }
3965}
3966
Paul Wang5d7cdb52022-11-22 09:45:06 +00003967status_t
3968AudioPolicyManager::removeDevicesRoleForStrategy(product_strategy_t strategy,
3969 device_role_t role,
3970 const AudioDeviceTypeAddrVector &devices) {
3971 ALOGV("%s() strategy=%d role=%d %s", __func__, strategy, role,
3972 dumpAudioDeviceTypeAddrVector(devices).c_str());
3973
Eric Laurent78fedbf2023-03-09 14:40:44 +01003974 if (!areAllDevicesSupported(
3975 devices, audio_is_output_device, __func__, /*matchAddress*/false)) {
Paul Wang5d7cdb52022-11-22 09:45:06 +00003976 return BAD_VALUE;
3977 }
3978 status_t status = mEngine->removeDevicesRoleForStrategy(strategy, role, devices);
3979 if (status != NO_ERROR) {
3980 ALOGW("Engine could not remove devices %s for strategy %d role %d",
3981 dumpAudioDeviceTypeAddrVector(devices).c_str(), strategy, role);
3982 return status;
3983 }
3984
3985 checkForDeviceAndOutputChanges();
3986
3987 bool forceVolumeReeval = false;
3988 // TODO(b/263479999): workaround for truncated touch sounds
3989 // to be removed when the problem is handled by system UI
3990 uint32_t delayMs = 0;
3991 if (strategy == mCommunnicationStrategy) {
3992 forceVolumeReeval = true;
3993 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
3994 updateInputRouting();
3995 }
3996 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
3997
3998 return NO_ERROR;
3999}
4000
4001status_t AudioPolicyManager::clearDevicesRoleForStrategy(product_strategy_t strategy,
4002 device_role_t role)
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004003{
Eric Laurentfecbceb2021-02-09 14:46:43 +01004004 ALOGV("%s() strategy=%d role=%d", __func__, strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004005
Paul Wang5d7cdb52022-11-22 09:45:06 +00004006 status_t status = mEngine->clearDevicesRoleForStrategy(strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004007 if (status != NO_ERROR) {
Eric Laurent9ae44f32022-12-14 16:17:02 +01004008 ALOGW_IF(status != NAME_NOT_FOUND,
4009 "Engine could not remove device role for strategy %d status %d",
Eric Laurent2517af32020-11-25 15:31:27 +01004010 strategy, status);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004011 return status;
4012 }
4013
4014 checkForDeviceAndOutputChanges();
Eric Laurent2517af32020-11-25 15:31:27 +01004015
4016 bool forceVolumeReeval = false;
4017 // FIXME: workaround for truncated touch sounds
4018 // to be removed when the problem is handled by system UI
4019 uint32_t delayMs = 0;
4020 if (strategy == mCommunnicationStrategy) {
4021 forceVolumeReeval = true;
4022 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
4023 updateInputRouting();
4024 }
4025 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004026
4027 return NO_ERROR;
4028}
4029
jiabin0a488932020-08-07 17:32:40 -07004030status_t AudioPolicyManager::getDevicesForRoleAndStrategy(product_strategy_t strategy,
4031 device_role_t role,
4032 AudioDeviceTypeAddrVector &devices) {
4033 return mEngine->getDevicesForRoleAndStrategy(strategy, role, devices);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004034}
4035
Jiabin Huang3b98d322020-09-03 17:54:16 +00004036status_t AudioPolicyManager::setDevicesRoleForCapturePreset(
4037 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices) {
4038 ALOGV("%s() audioSource=%d role=%d %s", __func__, audioSource, role,
4039 dumpAudioDeviceTypeAddrVector(devices).c_str());
4040
Mikhail Naganov55773032020-10-01 15:08:13 -07004041 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00004042 return BAD_VALUE;
4043 }
4044 status_t status = mEngine->setDevicesRoleForCapturePreset(audioSource, role, devices);
4045 ALOGW_IF(status != NO_ERROR,
4046 "Engine could not set preferred devices %s for audio source %d role %d",
4047 dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
4048
4049 return status;
4050}
4051
4052status_t AudioPolicyManager::addDevicesRoleForCapturePreset(
4053 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices) {
4054 ALOGV("%s() audioSource=%d role=%d %s", __func__, audioSource, role,
4055 dumpAudioDeviceTypeAddrVector(devices).c_str());
4056
Mikhail Naganov55773032020-10-01 15:08:13 -07004057 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00004058 return BAD_VALUE;
4059 }
4060 status_t status = mEngine->addDevicesRoleForCapturePreset(audioSource, role, devices);
4061 ALOGW_IF(status != NO_ERROR,
4062 "Engine could not add preferred devices %s for audio source %d role %d",
4063 dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
4064
Eric Laurent2517af32020-11-25 15:31:27 +01004065 updateInputRouting();
Jiabin Huang3b98d322020-09-03 17:54:16 +00004066 return status;
4067}
4068
4069status_t AudioPolicyManager::removeDevicesRoleForCapturePreset(
4070 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector& devices)
4071{
4072 ALOGV("%s() audioSource=%d role=%d devices=%s", __func__, audioSource, role,
4073 dumpAudioDeviceTypeAddrVector(devices).c_str());
4074
Eric Laurent78fedbf2023-03-09 14:40:44 +01004075 if (!areAllDevicesSupported(
4076 devices, audio_call_is_input_device, __func__, /*matchAddress*/false)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00004077 return BAD_VALUE;
4078 }
4079
4080 status_t status = mEngine->removeDevicesRoleForCapturePreset(
4081 audioSource, role, devices);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004082 ALOGW_IF(status != NO_ERROR && status != NAME_NOT_FOUND,
Jiabin Huang3b98d322020-09-03 17:54:16 +00004083 "Engine could not remove devices role (%d) for capture preset %d", role, audioSource);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004084 if (status == NO_ERROR) {
4085 updateInputRouting();
4086 }
Jiabin Huang3b98d322020-09-03 17:54:16 +00004087 return status;
4088}
4089
4090status_t AudioPolicyManager::clearDevicesRoleForCapturePreset(audio_source_t audioSource,
4091 device_role_t role) {
4092 ALOGV("%s() audioSource=%d role=%d", __func__, audioSource, role);
4093
4094 status_t status = mEngine->clearDevicesRoleForCapturePreset(audioSource, role);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004095 ALOGW_IF(status != NO_ERROR && status != NAME_NOT_FOUND,
Jiabin Huang3b98d322020-09-03 17:54:16 +00004096 "Engine could not clear devices role (%d) for capture preset %d", role, audioSource);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004097 if (status == NO_ERROR) {
4098 updateInputRouting();
4099 }
Jiabin Huang3b98d322020-09-03 17:54:16 +00004100 return status;
4101}
4102
4103status_t AudioPolicyManager::getDevicesForRoleAndCapturePreset(
4104 audio_source_t audioSource, device_role_t role, AudioDeviceTypeAddrVector &devices) {
4105 return mEngine->getDevicesForRoleAndCapturePreset(audioSource, role, devices);
4106}
4107
Oscar Azucena90e77632019-11-27 17:12:28 -08004108status_t AudioPolicyManager::setUserIdDeviceAffinities(int userId,
jiabin6a02d532020-08-07 11:56:38 -07004109 const AudioDeviceTypeAddrVector& devices) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01004110 ALOGV("%s() userId=%d num devices %zu", __func__, userId, devices.size());
Eric Laurentc529cf62020-04-17 18:19:10 -07004111 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
4112 return BAD_VALUE;
Oscar Azucena90e77632019-11-27 17:12:28 -08004113 }
Oscar Azucena90e77632019-11-27 17:12:28 -08004114 status_t status = mPolicyMixes.setUserIdDeviceAffinities(userId, devices);
4115 if (status != NO_ERROR) {
4116 ALOGE("%s() could not set device affinity for userId %d",
4117 __FUNCTION__, userId);
4118 return status;
4119 }
4120
4121 // reevaluate outputs for all devices
4122 checkForDeviceAndOutputChanges();
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004123 changeOutputDevicesMuteState(devices);
4124 updateCallAndOutputRouting(false /* forceVolumeReeval */, 0 /* delayMs */,
4125 true /* skipDelays */);
4126 changeOutputDevicesMuteState(devices);
Oscar Azucena90e77632019-11-27 17:12:28 -08004127
4128 return NO_ERROR;
4129}
4130
4131status_t AudioPolicyManager::removeUserIdDeviceAffinities(int userId) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01004132 ALOGV("%s() userId=%d", __FUNCTION__, userId);
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004133 AudioDeviceTypeAddrVector devices;
4134 mPolicyMixes.getDevicesForUserId(userId, devices);
Oscar Azucena90e77632019-11-27 17:12:28 -08004135 status_t status = mPolicyMixes.removeUserIdDeviceAffinities(userId);
4136 if (status != NO_ERROR) {
4137 ALOGE("%s() Could not remove all device affinities fo userId = %d",
4138 __FUNCTION__, userId);
4139 return status;
4140 }
4141
4142 // reevaluate outputs for all devices
4143 checkForDeviceAndOutputChanges();
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004144 changeOutputDevicesMuteState(devices);
4145 updateCallAndOutputRouting(false /* forceVolumeReeval */, 0 /* delayMs */,
4146 true /* skipDelays */);
4147 changeOutputDevicesMuteState(devices);
Oscar Azucena90e77632019-11-27 17:12:28 -08004148
4149 return NO_ERROR;
4150}
4151
Andy Hungc29d82b2018-10-05 12:23:17 -07004152void AudioPolicyManager::dump(String8 *dst) const
Eric Laurente552edb2014-03-10 17:42:56 -07004153{
Andy Hungc29d82b2018-10-05 12:23:17 -07004154 dst->appendFormat("\nAudioPolicyManager Dump: %p\n", this);
Mikhail Naganov0dbe87b2021-12-01 02:03:31 +00004155 dst->appendFormat(" Primary Output I/O handle: %d\n",
Eric Laurent87ffa392015-05-22 10:32:38 -07004156 hasPrimaryOutput() ? mPrimaryOutput->mIoHandle : AUDIO_IO_HANDLE_NONE);
Mikhail Naganov0d6a0332016-04-19 17:12:38 -07004157 std::string stateLiteral;
4158 AudioModeConverter::toString(mEngine->getPhoneState(), stateLiteral);
Andy Hungc29d82b2018-10-05 12:23:17 -07004159 dst->appendFormat(" Phone state: %s\n", stateLiteral.c_str());
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07004160 const char* forceUses[AUDIO_POLICY_FORCE_USE_CNT] = {
4161 "communications", "media", "record", "dock", "system",
4162 "HDMI system audio", "encoded surround output", "vibrate ringing" };
4163 for (audio_policy_force_use_t i = AUDIO_POLICY_FORCE_FOR_COMMUNICATION;
4164 i < AUDIO_POLICY_FORCE_USE_CNT; i = (audio_policy_force_use_t)((int)i + 1)) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08004165 audio_policy_forced_cfg_t forceUseValue = mEngine->getForceUse(i);
4166 dst->appendFormat(" Force use for %s: %d", forceUses[i], forceUseValue);
4167 if (i == AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND &&
4168 forceUseValue == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
4169 dst->append(" (MANUAL: ");
4170 dumpManualSurroundFormats(dst);
4171 dst->append(")");
4172 }
4173 dst->append("\n");
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07004174 }
Andy Hungc29d82b2018-10-05 12:23:17 -07004175 dst->appendFormat(" TTS output %savailable\n", mTtsOutputAvailable ? "" : "not ");
4176 dst->appendFormat(" Master mono: %s\n", mMasterMono ? "on" : "off");
Mikhail Naganovb3bcb4f2022-02-23 23:46:56 +00004177 dst->appendFormat(" Communication Strategy id: %d\n", mCommunnicationStrategy);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07004178 dst->appendFormat(" Config source: %s\n", mConfig->getSource().c_str());
Eric Laurent2517af32020-11-25 15:31:27 +01004179
Mikhail Naganov0f413b22021-12-02 05:29:27 +00004180 dst->append("\n");
4181 mAvailableOutputDevices.dump(dst, String8("Available output"), 1);
4182 dst->append("\n");
4183 mAvailableInputDevices.dump(dst, String8("Available input"), 1);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07004184 mHwModules.dump(dst);
Andy Hungc29d82b2018-10-05 12:23:17 -07004185 mOutputs.dump(dst);
4186 mInputs.dump(dst);
Mikhail Naganov0f413b22021-12-02 05:29:27 +00004187 mEffects.dump(dst, 1);
Andy Hungc29d82b2018-10-05 12:23:17 -07004188 mAudioPatches.dump(dst);
4189 mPolicyMixes.dump(dst);
4190 mAudioSources.dump(dst);
François Gaffiec005e562018-11-06 15:04:49 +01004191
Kevin Rocardb99cc752019-03-21 20:52:24 -07004192 dst->appendFormat(" AllowedCapturePolicies:\n");
4193 for (auto& policy : mAllowedCapturePolicies) {
4194 dst->appendFormat(" - uid=%d flag_mask=%#x\n", policy.first, policy.second);
4195 }
4196
jiabina84c3d32022-12-02 18:59:55 +00004197 dst->appendFormat(" Preferred mixer audio configuration:\n");
4198 for (const auto it : mPreferredMixerAttrInfos) {
4199 dst->appendFormat(" - device port id: %d\n", it.first);
4200 for (const auto preferredMixerInfoIt : it.second) {
4201 dst->appendFormat(" - strategy: %d; ", preferredMixerInfoIt.first);
4202 preferredMixerInfoIt.second->dump(dst);
4203 }
4204 }
4205
François Gaffiec005e562018-11-06 15:04:49 +01004206 dst->appendFormat("\nPolicy Engine dump:\n");
4207 mEngine->dump(dst);
Andy Hungc29d82b2018-10-05 12:23:17 -07004208}
4209
4210status_t AudioPolicyManager::dump(int fd)
4211{
4212 String8 result;
4213 dump(&result);
Andy Hungbb54e202018-10-05 11:42:02 -07004214 write(fd, result.string(), result.size());
Eric Laurente552edb2014-03-10 17:42:56 -07004215 return NO_ERROR;
4216}
4217
Kevin Rocardb99cc752019-03-21 20:52:24 -07004218status_t AudioPolicyManager::setAllowedCapturePolicy(uid_t uid, audio_flags_mask_t capturePolicy)
4219{
4220 mAllowedCapturePolicies[uid] = capturePolicy;
4221 return NO_ERROR;
4222}
4223
Eric Laurente552edb2014-03-10 17:42:56 -07004224// This function checks for the parameters which can be offloaded.
4225// This can be enhanced depending on the capability of the DSP and policy
4226// of the system.
Eric Laurent90fe31c2020-11-26 20:06:35 +01004227audio_offload_mode_t AudioPolicyManager::getOffloadSupport(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07004228{
Eric Laurent90fe31c2020-11-26 20:06:35 +01004229 ALOGV("%s: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07004230 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurent90fe31c2020-11-26 20:06:35 +01004231 __func__, offloadInfo.sample_rate, offloadInfo.channel_mask,
Eric Laurente552edb2014-03-10 17:42:56 -07004232 offloadInfo.format,
4233 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
4234 offloadInfo.has_video);
4235
jiabin2b9d5a12021-12-10 01:06:29 +00004236 if (!isOffloadPossible(offloadInfo)) {
Eric Laurent90fe31c2020-11-26 20:06:35 +01004237 return AUDIO_OFFLOAD_NOT_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07004238 }
4239
4240 // See if there is a profile to support this.
4241 // AUDIO_DEVICE_NONE
François Gaffie11d30102018-11-02 16:09:09 +01004242 sp<IOProfile> profile = getProfileForOutput(DeviceVector() /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07004243 offloadInfo.sample_rate,
4244 offloadInfo.format,
4245 offloadInfo.channel_mask,
Michael Chana94fbb22018-04-24 14:31:19 +10004246 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD,
4247 true /* directOnly */);
Eric Laurent94365442021-01-08 18:36:05 +01004248 ALOGV("%s: profile %sfound%s", __func__, profile != nullptr ? "" : "NOT ",
4249 (profile != nullptr && (profile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD) != 0)
4250 ? ", supports gapless" : "");
Eric Laurent90fe31c2020-11-26 20:06:35 +01004251 if (profile == nullptr) {
4252 return AUDIO_OFFLOAD_NOT_SUPPORTED;
4253 }
4254 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD) != 0) {
4255 return AUDIO_OFFLOAD_GAPLESS_SUPPORTED;
4256 }
4257 return AUDIO_OFFLOAD_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07004258}
4259
Michael Chana94fbb22018-04-24 14:31:19 +10004260bool AudioPolicyManager::isDirectOutputSupported(const audio_config_base_t& config,
4261 const audio_attributes_t& attributes) {
4262 audio_output_flags_t output_flags = AUDIO_OUTPUT_FLAG_NONE;
François Gaffie58d4be52018-11-06 15:30:12 +01004263 audio_flags_to_audio_output_flags(attributes.flags, &output_flags);
Dorin Drimus9901eb02022-01-14 11:36:51 +00004264 DeviceVector outputDevices = mEngine->getOutputDevicesForAttributes(attributes);
4265 sp<IOProfile> profile = getProfileForOutput(outputDevices,
Michael Chana94fbb22018-04-24 14:31:19 +10004266 config.sample_rate,
4267 config.format,
4268 config.channel_mask,
4269 output_flags,
4270 true /* directOnly */);
4271 ALOGV("%s() profile %sfound with name: %s, "
4272 "sample rate: %u, format: 0x%x, channel_mask: 0x%x, output flags: 0x%x",
4273 __FUNCTION__, profile != 0 ? "" : "NOT ",
jiabin5740f082019-08-19 15:08:30 -07004274 (profile != 0 ? profile->getTagName().c_str() : "null"),
Michael Chana94fbb22018-04-24 14:31:19 +10004275 config.sample_rate, config.format, config.channel_mask, output_flags);
Dorin Drimusecc9f422022-03-09 17:57:40 +01004276
4277 // also try the MSD module if compatible profile not found
4278 if (profile == nullptr) {
4279 profile = getMsdProfileForOutput(outputDevices,
4280 config.sample_rate,
4281 config.format,
4282 config.channel_mask,
4283 output_flags,
4284 true /* directOnly */);
4285 ALOGV("%s() MSD profile %sfound with name: %s, "
4286 "sample rate: %u, format: 0x%x, channel_mask: 0x%x, output flags: 0x%x",
4287 __FUNCTION__, profile != 0 ? "" : "NOT ",
4288 (profile != 0 ? profile->getTagName().c_str() : "null"),
4289 config.sample_rate, config.format, config.channel_mask, output_flags);
4290 }
4291 return (profile != nullptr);
Michael Chana94fbb22018-04-24 14:31:19 +10004292}
4293
jiabin2b9d5a12021-12-10 01:06:29 +00004294bool AudioPolicyManager::isOffloadPossible(const audio_offload_info_t &offloadInfo,
4295 bool durationIgnored) {
4296 if (mMasterMono) {
4297 return false; // no offloading if mono is set.
4298 }
4299
4300 // Check if offload has been disabled
4301 if (property_get_bool("audio.offload.disable", false /* default_value */)) {
4302 ALOGV("%s: offload disabled by audio.offload.disable", __func__);
4303 return false;
4304 }
4305
4306 // Check if stream type is music, then only allow offload as of now.
4307 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
4308 {
4309 ALOGV("%s: stream_type != MUSIC, returning false", __func__);
4310 return false;
4311 }
4312
4313 //TODO: enable audio offloading with video when ready
4314 const bool allowOffloadWithVideo =
4315 property_get_bool("audio.offload.video", false /* default_value */);
4316 if (offloadInfo.has_video && !allowOffloadWithVideo) {
4317 ALOGV("%s: has_video == true, returning false", __func__);
4318 return false;
4319 }
4320
4321 //If duration is less than minimum value defined in property, return false
4322 const int min_duration_secs = property_get_int32(
4323 "audio.offload.min.duration.secs", -1 /* default_value */);
4324 if (!durationIgnored) {
4325 if (min_duration_secs >= 0) {
4326 if (offloadInfo.duration_us < min_duration_secs * 1000000LL) {
4327 ALOGV("%s: Offload denied by duration < audio.offload.min.duration.secs(=%d)",
4328 __func__, min_duration_secs);
4329 return false;
4330 }
4331 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
4332 ALOGV("%s: Offload denied by duration < default min(=%u)",
4333 __func__, OFFLOAD_DEFAULT_MIN_DURATION_SECS);
4334 return false;
4335 }
4336 }
4337
4338 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
4339 // creating an offloaded track and tearing it down immediately after start when audioflinger
4340 // detects there is an active non offloadable effect.
4341 // FIXME: We should check the audio session here but we do not have it in this context.
4342 // This may prevent offloading in rare situations where effects are left active by apps
4343 // in the background.
4344 if (mEffects.isNonOffloadableEffectEnabled()) {
4345 return false;
4346 }
4347
4348 return true;
4349}
4350
4351audio_direct_mode_t AudioPolicyManager::getDirectPlaybackSupport(const audio_attributes_t *attr,
4352 const audio_config_t *config) {
4353 audio_offload_info_t offloadInfo = AUDIO_INFO_INITIALIZER;
4354 offloadInfo.format = config->format;
4355 offloadInfo.sample_rate = config->sample_rate;
4356 offloadInfo.channel_mask = config->channel_mask;
4357 offloadInfo.stream_type = mEngine->getStreamTypeForAttributes(*attr);
4358 offloadInfo.has_video = false;
4359 offloadInfo.is_streaming = false;
4360 const bool offloadPossible = isOffloadPossible(offloadInfo, true /*durationIgnored*/);
4361
4362 audio_direct_mode_t directMode = AUDIO_DIRECT_NOT_SUPPORTED;
4363 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
4364 audio_flags_to_audio_output_flags(attr->flags, &flags);
4365 // only retain flags that will drive compressed offload or passthrough
4366 uint32_t relevantFlags = AUDIO_OUTPUT_FLAG_HW_AV_SYNC;
4367 if (offloadPossible) {
4368 relevantFlags |= AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD;
4369 }
4370 flags = (audio_output_flags_t)((flags & relevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
4371
Dorin Drimusfae3c642022-03-17 18:36:30 +01004372 DeviceVector engineOutputDevices = mEngine->getOutputDevicesForAttributes(*attr);
jiabin2b9d5a12021-12-10 01:06:29 +00004373 for (const auto& hwModule : mHwModules) {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004374 DeviceVector outputDevices = engineOutputDevices;
4375 // the MSD module checks for different conditions and output devices
4376 if (strcmp(hwModule->getName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0) {
4377 if (!msdHasPatchesToAllDevices(engineOutputDevices.toTypeAddrVector())) {
4378 continue;
4379 }
4380 outputDevices = getMsdAudioOutDevices();
4381 }
jiabin2b9d5a12021-12-10 01:06:29 +00004382 for (const auto& curProfile : hwModule->getOutputProfiles()) {
jiabinc8f7dfc2022-01-06 18:42:08 +00004383 if (!curProfile->isCompatibleProfile(outputDevices,
jiabin2b9d5a12021-12-10 01:06:29 +00004384 config->sample_rate, nullptr /*updatedSamplingRate*/,
4385 config->format, nullptr /*updatedFormat*/,
4386 config->channel_mask, nullptr /*updatedChannelMask*/,
4387 flags)) {
4388 continue;
4389 }
4390 // reject profiles not corresponding to a device currently available
4391 if (!mAvailableOutputDevices.containsAtLeastOne(curProfile->getSupportedDevices())) {
4392 continue;
4393 }
4394 if ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)
4395 != AUDIO_OUTPUT_FLAG_NONE) {
jiabinc6132d62022-01-01 07:36:31 +00004396 if ((directMode & AUDIO_DIRECT_OFFLOAD_GAPLESS_SUPPORTED)
jiabin2b9d5a12021-12-10 01:06:29 +00004397 != AUDIO_DIRECT_NOT_SUPPORTED) {
4398 // Already reports offload gapless supported. No need to report offload support.
4399 continue;
4400 }
4401 if ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD)
4402 != AUDIO_OUTPUT_FLAG_NONE) {
4403 // If offload gapless is reported, no need to report offload support.
4404 directMode = (audio_direct_mode_t) ((directMode &
4405 ~AUDIO_DIRECT_OFFLOAD_SUPPORTED) |
4406 AUDIO_DIRECT_OFFLOAD_GAPLESS_SUPPORTED);
4407 } else {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004408 directMode = (audio_direct_mode_t)(directMode | AUDIO_DIRECT_OFFLOAD_SUPPORTED);
jiabin2b9d5a12021-12-10 01:06:29 +00004409 }
4410 } else {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004411 directMode = (audio_direct_mode_t) (directMode | AUDIO_DIRECT_BITSTREAM_SUPPORTED);
jiabin2b9d5a12021-12-10 01:06:29 +00004412 }
4413 }
4414 }
4415 return directMode;
4416}
4417
Dorin Drimusf2196d82022-01-03 12:11:18 +01004418status_t AudioPolicyManager::getDirectProfilesForAttributes(const audio_attributes_t* attr,
4419 AudioProfileVector& audioProfilesVector) {
Dorin Drimus17112632022-09-23 15:28:51 +00004420 if (mEffects.isNonOffloadableEffectEnabled()) {
4421 return OK;
4422 }
jiabinf1c73972022-04-14 16:28:52 -07004423 DeviceVector devices;
4424 status_t status = getDevicesForAttributes(*attr, devices, false /* forVolume */);
Dorin Drimusf2196d82022-01-03 12:11:18 +01004425 if (status != OK) {
4426 return status;
4427 }
4428 ALOGV("%s: found %zu output devices for attributes.", __func__, devices.size());
4429 if (devices.empty()) {
4430 return OK; // no output devices for the attributes
4431 }
jiabinf1c73972022-04-14 16:28:52 -07004432 return getProfilesForDevices(devices, audioProfilesVector,
4433 AUDIO_OUTPUT_FLAG_DIRECT /*flags*/, false /*isInput*/);
Dorin Drimusf2196d82022-01-03 12:11:18 +01004434}
4435
jiabina84c3d32022-12-02 18:59:55 +00004436status_t AudioPolicyManager::getSupportedMixerAttributes(
4437 audio_port_handle_t portId, std::vector<audio_mixer_attributes_t> &mixerAttrs) {
4438 ALOGV("%s, portId=%d", __func__, portId);
4439 sp<DeviceDescriptor> deviceDescriptor = mAvailableOutputDevices.getDeviceFromId(portId);
4440 if (deviceDescriptor == nullptr) {
4441 ALOGE("%s the requested device is currently unavailable", __func__);
4442 return BAD_VALUE;
4443 }
jiabin96daffc2023-05-11 17:51:55 +00004444 if (!audio_is_usb_out_device(deviceDescriptor->type())) {
4445 ALOGE("%s the requested device(type=%#x) is not usb device", __func__,
4446 deviceDescriptor->type());
4447 return BAD_VALUE;
4448 }
jiabina84c3d32022-12-02 18:59:55 +00004449 for (const auto& hwModule : mHwModules) {
4450 for (const auto& curProfile : hwModule->getOutputProfiles()) {
4451 if (curProfile->supportsDevice(deviceDescriptor)) {
4452 curProfile->toSupportedMixerAttributes(&mixerAttrs);
4453 }
4454 }
4455 }
4456 return NO_ERROR;
4457}
4458
4459status_t AudioPolicyManager::setPreferredMixerAttributes(
4460 const audio_attributes_t *attr,
4461 audio_port_handle_t portId,
4462 uid_t uid,
4463 const audio_mixer_attributes_t *mixerAttributes) {
4464 ALOGV("%s, attr=%s, mixerAttributes={format=%#x, channelMask=%#x, samplingRate=%u, "
4465 "mixerBehavior=%d}, uid=%d, portId=%u",
4466 __func__, toString(*attr).c_str(), mixerAttributes->config.format,
4467 mixerAttributes->config.channel_mask, mixerAttributes->config.sample_rate,
4468 mixerAttributes->mixer_behavior, uid, portId);
4469 if (attr->usage != AUDIO_USAGE_MEDIA) {
4470 ALOGE("%s failed, only media is allowed, the given usage is %d", __func__, attr->usage);
4471 return BAD_VALUE;
4472 }
4473 sp<DeviceDescriptor> deviceDescriptor = mAvailableOutputDevices.getDeviceFromId(portId);
4474 if (deviceDescriptor == nullptr) {
4475 ALOGE("%s the requested device is currently unavailable", __func__);
4476 return BAD_VALUE;
4477 }
4478 if (!audio_is_usb_out_device(deviceDescriptor->type())) {
4479 ALOGE("%s(%d), type=%d, is not a usb output device",
4480 __func__, portId, deviceDescriptor->type());
4481 return BAD_VALUE;
4482 }
4483
4484 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
4485 audio_flags_to_audio_output_flags(attr->flags, &flags);
4486 flags = (audio_output_flags_t) (flags |
4487 audio_output_flags_from_mixer_behavior(mixerAttributes->mixer_behavior));
4488 sp<IOProfile> profile = nullptr;
4489 DeviceVector devices(deviceDescriptor);
4490 for (const auto& hwModule : mHwModules) {
4491 for (const auto& curProfile : hwModule->getOutputProfiles()) {
4492 if (curProfile->hasDynamicAudioProfile()
4493 && curProfile->isCompatibleProfile(devices,
4494 mixerAttributes->config.sample_rate,
4495 nullptr /*updatedSamplingRate*/,
4496 mixerAttributes->config.format,
4497 nullptr /*updatedFormat*/,
4498 mixerAttributes->config.channel_mask,
4499 nullptr /*updatedChannelMask*/,
4500 flags,
4501 false /*exactMatchRequiredForInputFlags*/)) {
4502 profile = curProfile;
4503 break;
4504 }
4505 }
4506 }
4507 if (profile == nullptr) {
4508 ALOGE("%s, there is no compatible profile found", __func__);
4509 return BAD_VALUE;
4510 }
4511
4512 sp<PreferredMixerAttributesInfo> mixerAttrInfo =
4513 sp<PreferredMixerAttributesInfo>::make(
4514 uid, portId, profile, flags, *mixerAttributes);
4515 const product_strategy_t strategy = mEngine->getProductStrategyForAttributes(*attr);
4516 mPreferredMixerAttrInfos[portId][strategy] = mixerAttrInfo;
4517
4518 // If 1) there is any client from the preferred mixer configuration owner that is currently
4519 // active and matches the strategy and 2) current output is on the preferred device and the
4520 // mixer configuration doesn't match the preferred one, reopen output with preferred mixer
4521 // configuration.
4522 std::vector<audio_io_handle_t> outputsToReopen;
4523 for (size_t i = 0; i < mOutputs.size(); i++) {
4524 const auto output = mOutputs.valueAt(i);
jiabin3ff8d7d2022-12-13 06:27:44 +00004525 if (output->mProfile == profile && output->devices().onlyContainsDevice(deviceDescriptor)) {
4526 if (output->isConfigurationMatched(mixerAttributes->config, flags)) {
4527 output->mUsePreferredMixerAttributes = true;
4528 } else {
4529 for (const auto &client: output->getActiveClients()) {
4530 if (client->uid() == uid && client->strategy() == strategy) {
4531 client->setIsInvalid();
4532 outputsToReopen.push_back(output->mIoHandle);
4533 }
jiabina84c3d32022-12-02 18:59:55 +00004534 }
4535 }
4536 }
4537 }
4538 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
4539 config.sample_rate = mixerAttributes->config.sample_rate;
4540 config.channel_mask = mixerAttributes->config.channel_mask;
4541 config.format = mixerAttributes->config.format;
4542 for (const auto output : outputsToReopen) {
jiabin3ff8d7d2022-12-13 06:27:44 +00004543 sp<SwAudioOutputDescriptor> desc =
4544 reopenOutput(mOutputs.valueFor(output), &config, flags, __func__);
4545 if (desc == nullptr) {
4546 ALOGE("%s, failed to reopen output with preferred mixer attributes", __func__);
4547 continue;
4548 }
4549 desc->mUsePreferredMixerAttributes = true;
jiabina84c3d32022-12-02 18:59:55 +00004550 }
4551
4552 return NO_ERROR;
4553}
4554
4555sp<PreferredMixerAttributesInfo> AudioPolicyManager::getPreferredMixerAttributesInfo(
jiabind9a58d32023-06-01 17:57:30 +00004556 audio_port_handle_t devicePortId,
4557 product_strategy_t strategy,
4558 bool activeBitPerfectPreferred) {
jiabina84c3d32022-12-02 18:59:55 +00004559 auto it = mPreferredMixerAttrInfos.find(devicePortId);
4560 if (it == mPreferredMixerAttrInfos.end()) {
4561 return nullptr;
4562 }
jiabind9a58d32023-06-01 17:57:30 +00004563 if (activeBitPerfectPreferred) {
4564 for (auto [strategy, info] : it->second) {
4565 if ((info->getFlags() & AUDIO_OUTPUT_FLAG_BIT_PERFECT) != AUDIO_OUTPUT_FLAG_NONE
4566 && info->getActiveClientCount() != 0) {
4567 return info;
4568 }
4569 }
jiabina84c3d32022-12-02 18:59:55 +00004570 }
jiabind9a58d32023-06-01 17:57:30 +00004571 auto strategyMatchedMixerAttrInfoIt = it->second.find(strategy);
4572 return strategyMatchedMixerAttrInfoIt == it->second.end()
4573 ? nullptr : strategyMatchedMixerAttrInfoIt->second;
jiabina84c3d32022-12-02 18:59:55 +00004574}
4575
4576status_t AudioPolicyManager::getPreferredMixerAttributes(
4577 const audio_attributes_t *attr,
4578 audio_port_handle_t portId,
4579 audio_mixer_attributes_t* mixerAttributes) {
4580 sp<PreferredMixerAttributesInfo> info = getPreferredMixerAttributesInfo(
4581 portId, mEngine->getProductStrategyForAttributes(*attr));
4582 if (info == nullptr) {
4583 return NAME_NOT_FOUND;
4584 }
4585 *mixerAttributes = info->getMixerAttributes();
4586 return NO_ERROR;
4587}
4588
4589status_t AudioPolicyManager::clearPreferredMixerAttributes(const audio_attributes_t *attr,
4590 audio_port_handle_t portId,
4591 uid_t uid) {
4592 const product_strategy_t strategy = mEngine->getProductStrategyForAttributes(*attr);
4593 const auto preferredMixerAttrInfo = getPreferredMixerAttributesInfo(portId, strategy);
4594 if (preferredMixerAttrInfo == nullptr) {
4595 return NAME_NOT_FOUND;
4596 }
4597 if (preferredMixerAttrInfo->getUid() != uid) {
4598 ALOGE("%s, requested uid=%d, owned uid=%d",
4599 __func__, uid, preferredMixerAttrInfo->getUid());
4600 return PERMISSION_DENIED;
4601 }
4602 mPreferredMixerAttrInfos[portId].erase(strategy);
4603 if (mPreferredMixerAttrInfos[portId].empty()) {
4604 mPreferredMixerAttrInfos.erase(portId);
4605 }
4606
4607 // Reconfig existing output
4608 std::vector<audio_io_handle_t> potentialOutputsToReopen;
4609 for (size_t i = 0; i < mOutputs.size(); i++) {
4610 if (mOutputs.valueAt(i)->mProfile == preferredMixerAttrInfo->getProfile()) {
4611 potentialOutputsToReopen.push_back(mOutputs.keyAt(i));
4612 }
4613 }
4614 for (const auto output : potentialOutputsToReopen) {
4615 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
4616 if (desc->isConfigurationMatched(preferredMixerAttrInfo->getConfigBase(),
4617 preferredMixerAttrInfo->getFlags())) {
4618 reopenOutput(desc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
4619 }
4620 }
4621 return NO_ERROR;
4622}
4623
Eric Laurent6a94d692014-05-20 11:18:06 -07004624status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
4625 audio_port_type_t type,
4626 unsigned int *num_ports,
jiabin19cdba52020-11-24 11:28:58 -08004627 struct audio_port_v7 *ports,
Eric Laurent6a94d692014-05-20 11:18:06 -07004628 unsigned int *generation)
4629{
jiabin19cdba52020-11-24 11:28:58 -08004630 if (num_ports == nullptr || (*num_ports != 0 && ports == nullptr) ||
4631 generation == nullptr) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004632 return BAD_VALUE;
4633 }
4634 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
jiabin19cdba52020-11-24 11:28:58 -08004635 if (ports == nullptr) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004636 *num_ports = 0;
4637 }
4638
4639 size_t portsWritten = 0;
4640 size_t portsMax = *num_ports;
4641 *num_ports = 0;
4642 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07004643 // do not report devices with type AUDIO_DEVICE_IN_STUB or AUDIO_DEVICE_OUT_STUB
4644 // as they are used by stub HALs by convention
Eric Laurent6a94d692014-05-20 11:18:06 -07004645 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004646 for (const auto& dev : mAvailableOutputDevices) {
4647 if (dev->type() == AUDIO_DEVICE_OUT_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07004648 continue;
4649 }
4650 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004651 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07004652 }
4653 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07004654 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004655 }
4656 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004657 for (const auto& dev : mAvailableInputDevices) {
4658 if (dev->type() == AUDIO_DEVICE_IN_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07004659 continue;
4660 }
4661 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004662 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07004663 }
4664 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07004665 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004666 }
4667 }
4668 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
4669 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
4670 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
4671 mInputs[i]->toAudioPort(&ports[portsWritten++]);
4672 }
4673 *num_ports += mInputs.size();
4674 }
4675 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent84c70242014-06-23 08:46:27 -07004676 size_t numOutputs = 0;
4677 for (size_t i = 0; i < mOutputs.size(); i++) {
4678 if (!mOutputs[i]->isDuplicated()) {
4679 numOutputs++;
4680 if (portsWritten < portsMax) {
4681 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
4682 }
4683 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004684 }
Eric Laurent84c70242014-06-23 08:46:27 -07004685 *num_ports += numOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07004686 }
4687 }
jiabina84c3d32022-12-02 18:59:55 +00004688
Eric Laurent6a94d692014-05-20 11:18:06 -07004689 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07004690 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
Eric Laurent6a94d692014-05-20 11:18:06 -07004691 return NO_ERROR;
4692}
4693
Mikhail Naganov5edc5ed2023-03-23 14:52:15 -07004694status_t AudioPolicyManager::listDeclaredDevicePorts(media::AudioPortRole role,
4695 std::vector<media::AudioPortFw>* _aidl_return) {
4696 auto pushPort = [&](const sp<DeviceDescriptor>& dev) -> status_t {
4697 audio_port_v7 port;
4698 dev->toAudioPort(&port);
4699 auto aidlPort = VALUE_OR_RETURN_STATUS(legacy2aidl_audio_port_v7_AudioPortFw(port));
4700 _aidl_return->push_back(std::move(aidlPort));
4701 return OK;
4702 };
4703
Mikhail Naganov68e3f642023-04-28 13:06:32 -07004704 for (const auto& module : mHwModules) {
Mikhail Naganov5edc5ed2023-03-23 14:52:15 -07004705 for (const auto& dev : module->getDeclaredDevices()) {
4706 if (role == media::AudioPortRole::NONE ||
4707 ((role == media::AudioPortRole::SOURCE)
4708 == audio_is_input_device(dev->type()))) {
4709 RETURN_STATUS_IF_ERROR(pushPort(dev));
4710 }
4711 }
4712 }
4713 return OK;
4714}
4715
jiabin19cdba52020-11-24 11:28:58 -08004716status_t AudioPolicyManager::getAudioPort(struct audio_port_v7 *port)
Eric Laurent6a94d692014-05-20 11:18:06 -07004717{
Eric Laurent99fcae42018-05-17 16:59:18 -07004718 if (port == nullptr || port->id == AUDIO_PORT_HANDLE_NONE) {
4719 return BAD_VALUE;
4720 }
4721 sp<DeviceDescriptor> dev = mAvailableOutputDevices.getDeviceFromId(port->id);
4722 if (dev != 0) {
4723 dev->toAudioPort(port);
4724 return NO_ERROR;
4725 }
4726 dev = mAvailableInputDevices.getDeviceFromId(port->id);
4727 if (dev != 0) {
4728 dev->toAudioPort(port);
4729 return NO_ERROR;
4730 }
4731 sp<SwAudioOutputDescriptor> out = mOutputs.getOutputFromId(port->id);
4732 if (out != 0) {
4733 out->toAudioPort(port);
4734 return NO_ERROR;
4735 }
4736 sp<AudioInputDescriptor> in = mInputs.getInputFromId(port->id);
4737 if (in != 0) {
4738 in->toAudioPort(port);
4739 return NO_ERROR;
4740 }
4741 return BAD_VALUE;
Eric Laurent6a94d692014-05-20 11:18:06 -07004742}
4743
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004744status_t AudioPolicyManager::createAudioPatch(const struct audio_patch *patch,
4745 audio_patch_handle_t *handle,
4746 uid_t uid)
Eric Laurent6a94d692014-05-20 11:18:06 -07004747{
François Gaffieafd4cea2019-11-18 15:50:22 +01004748 ALOGV("%s", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004749 if (handle == NULL || patch == NULL) {
4750 return BAD_VALUE;
4751 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004752 ALOGV("%s num sources %d num sinks %d", __func__, patch->num_sources, patch->num_sinks);
Mikhail Naganovac9858b2018-06-15 13:12:37 -07004753 if (!audio_patch_is_valid(patch)) {
Eric Laurent874c42872014-08-08 15:13:39 -07004754 return BAD_VALUE;
4755 }
4756 // only one source per audio patch supported for now
4757 if (patch->num_sources > 1) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004758 return INVALID_OPERATION;
4759 }
Eric Laurent874c42872014-08-08 15:13:39 -07004760 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004761 return INVALID_OPERATION;
4762 }
Eric Laurent874c42872014-08-08 15:13:39 -07004763 for (size_t i = 0; i < patch->num_sinks; i++) {
4764 if (patch->sinks[i].role != AUDIO_PORT_ROLE_SINK) {
4765 return INVALID_OPERATION;
4766 }
4767 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004768
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004769 sp<DeviceDescriptor> srcDevice = mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
4770 sp<DeviceDescriptor> sinkDevice = mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id);
4771 if (srcDevice == nullptr || sinkDevice == nullptr) {
4772 ALOGW("%s could not create patch, invalid sink and/or source device(s)", __func__);
4773 return BAD_VALUE;
4774 }
4775 ALOGV("%s between source %s and sink %s", __func__,
4776 srcDevice->toString().c_str(), sinkDevice->toString().c_str());
4777 audio_port_handle_t portId = PolicyAudioPort::getNextUniqueId();
4778 // Default attributes, default volume priority, not to infer with non raw audio patches.
4779 audio_attributes_t attributes = attributes_initializer(AUDIO_USAGE_MEDIA);
4780 const struct audio_port_config *source = &patch->sources[0];
4781 sp<SourceClientDescriptor> sourceDesc =
4782 new InternalSourceClientDescriptor(
4783 portId, uid, attributes, *source, srcDevice, sinkDevice,
4784 mEngine->getProductStrategyForAttributes(attributes), toVolumeSource(attributes));
4785
4786 status_t status =
4787 connectAudioSourceToSink(sourceDesc, sinkDevice, patch, *handle, uid, 0 /* delayMs */);
4788
4789 if (status != NO_ERROR) {
4790 return INVALID_OPERATION;
4791 }
4792 mAudioSources.add(portId, sourceDesc);
4793 return NO_ERROR;
4794}
4795
4796status_t AudioPolicyManager::connectAudioSourceToSink(
4797 const sp<SourceClientDescriptor>& sourceDesc, const sp<DeviceDescriptor> &sinkDevice,
4798 const struct audio_patch *patch,
4799 audio_patch_handle_t &handle,
4800 uid_t uid, uint32_t delayMs)
4801{
4802 status_t status = createAudioPatchInternal(patch, &handle, uid, delayMs, sourceDesc);
4803 if (status != NO_ERROR || mAudioPatches.indexOfKey(handle) < 0) {
4804 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
4805 return INVALID_OPERATION;
4806 }
4807 sourceDesc->connect(handle, sinkDevice);
4808 if (isMsdPatch(handle)) {
4809 return NO_ERROR;
4810 }
4811 // SW Bridge? (@todo: HW bridge, keep track of HwOutput for device selection "reconsideration")
4812 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
4813 ALOG_ASSERT(swOutput != nullptr, "%s: a swOutput shall always be associated", __func__);
4814 if (swOutput->getClient(sourceDesc->portId()) != nullptr) {
4815 ALOGW("%s source portId has already been attached to outputDesc", __func__);
4816 goto FailurePatchAdded;
4817 }
4818 status = swOutput->start();
4819 if (status != NO_ERROR) {
4820 goto FailureSourceAdded;
4821 }
4822 swOutput->addClient(sourceDesc);
4823 status = startSource(swOutput, sourceDesc, &delayMs);
4824 if (status != NO_ERROR) {
4825 ALOGW("%s failed to start source, error %d", __FUNCTION__, status);
4826 goto FailureSourceActive;
4827 }
4828 if (delayMs != 0) {
4829 usleep(delayMs * 1000);
4830 }
4831 return NO_ERROR;
4832
4833FailureSourceActive:
4834 swOutput->stop();
4835 releaseOutput(sourceDesc->portId());
4836FailureSourceAdded:
4837 sourceDesc->setSwOutput(nullptr);
4838FailurePatchAdded:
4839 releaseAudioPatchInternal(handle);
4840 return INVALID_OPERATION;
4841}
4842
4843status_t AudioPolicyManager::createAudioPatchInternal(const struct audio_patch *patch,
4844 audio_patch_handle_t *handle,
4845 uid_t uid, uint32_t delayMs,
4846 const sp<SourceClientDescriptor>& sourceDesc)
4847{
4848 ALOGV("%s num sources %d num sinks %d", __func__, patch->num_sources, patch->num_sinks);
Eric Laurent6a94d692014-05-20 11:18:06 -07004849 sp<AudioPatch> patchDesc;
4850 ssize_t index = mAudioPatches.indexOfKey(*handle);
4851
François Gaffieafd4cea2019-11-18 15:50:22 +01004852 ALOGV("%s source id %d role %d type %d", __func__, patch->sources[0].id,
4853 patch->sources[0].role,
4854 patch->sources[0].type);
Eric Laurent874c42872014-08-08 15:13:39 -07004855#if LOG_NDEBUG == 0
4856 for (size_t i = 0; i < patch->num_sinks; i++) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004857 ALOGV("%s sink %zu: id %d role %d type %d", __func__ ,i, patch->sinks[i].id,
4858 patch->sinks[i].role,
4859 patch->sinks[i].type);
Eric Laurent874c42872014-08-08 15:13:39 -07004860 }
4861#endif
Eric Laurent6a94d692014-05-20 11:18:06 -07004862
4863 if (index >= 0) {
4864 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01004865 ALOGV("%s mUidCached %d patchDesc->mUid %d uid %d",
4866 __func__, mUidCached, patchDesc->getUid(), uid);
4867 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004868 return INVALID_OPERATION;
4869 }
4870 } else {
Glenn Kastena13cde92016-03-28 15:26:02 -07004871 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07004872 }
4873
4874 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004875 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004876 if (outputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004877 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004878 return BAD_VALUE;
4879 }
Eric Laurent84c70242014-06-23 08:46:27 -07004880 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
4881 outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004882 if (patchDesc != 0) {
4883 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004884 ALOGV("%s source id differs for patch current id %d new id %d",
4885 __func__, patchDesc->mPatch.sources[0].id, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004886 return BAD_VALUE;
4887 }
4888 }
Eric Laurent874c42872014-08-08 15:13:39 -07004889 DeviceVector devices;
4890 for (size_t i = 0; i < patch->num_sinks; i++) {
4891 // Only support mix to devices connection
4892 // TODO add support for mix to mix connection
4893 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004894 ALOGV("%s source mix but sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07004895 return INVALID_OPERATION;
4896 }
4897 sp<DeviceDescriptor> devDesc =
4898 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
4899 if (devDesc == 0) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004900 ALOGV("%s out device not found for id %d", __func__, patch->sinks[i].id);
Eric Laurent874c42872014-08-08 15:13:39 -07004901 return BAD_VALUE;
4902 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004903
François Gaffie11d30102018-11-02 16:09:09 +01004904 if (!outputDesc->mProfile->isCompatibleProfile(DeviceVector(devDesc),
Eric Laurent874c42872014-08-08 15:13:39 -07004905 patch->sources[0].sample_rate,
François Gaffie53615e22015-03-19 09:24:12 +01004906 NULL, // updatedSamplingRate
4907 patch->sources[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07004908 NULL, // updatedFormat
François Gaffie53615e22015-03-19 09:24:12 +01004909 patch->sources[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07004910 NULL, // updatedChannelMask
François Gaffie53615e22015-03-19 09:24:12 +01004911 AUDIO_OUTPUT_FLAG_NONE /*FIXME*/)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004912 ALOGV("%s profile not supported for device %08x", __func__, devDesc->type());
Eric Laurent874c42872014-08-08 15:13:39 -07004913 return INVALID_OPERATION;
4914 }
4915 devices.add(devDesc);
4916 }
4917 if (devices.size() == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004918 return INVALID_OPERATION;
4919 }
Eric Laurent874c42872014-08-08 15:13:39 -07004920
Eric Laurent6a94d692014-05-20 11:18:06 -07004921 // TODO: reconfigure output format and channels here
François Gaffieafd4cea2019-11-18 15:50:22 +01004922 ALOGV("%s setting device %s on output %d",
4923 __func__, dumpDeviceTypes(devices.types()).c_str(), outputDesc->mIoHandle);
François Gaffie11d30102018-11-02 16:09:09 +01004924 setOutputDevices(outputDesc, devices, true, 0, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004925 index = mAudioPatches.indexOfKey(*handle);
4926 if (index >= 0) {
4927 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004928 ALOGW("%s setOutputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004929 }
4930 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01004931 patchDesc->setUid(uid);
4932 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004933 } else {
François Gaffieafd4cea2019-11-18 15:50:22 +01004934 ALOGW("%s setOutputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004935 return INVALID_OPERATION;
4936 }
4937 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
4938 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
4939 // input device to input mix connection
Eric Laurent874c42872014-08-08 15:13:39 -07004940 // only one sink supported when connecting an input device to a mix
4941 if (patch->num_sinks > 1) {
4942 return INVALID_OPERATION;
4943 }
François Gaffie53615e22015-03-19 09:24:12 +01004944 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004945 if (inputDesc == NULL) {
4946 return BAD_VALUE;
4947 }
4948 if (patchDesc != 0) {
4949 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
4950 return BAD_VALUE;
4951 }
4952 }
François Gaffie11d30102018-11-02 16:09:09 +01004953 sp<DeviceDescriptor> device =
Eric Laurent6a94d692014-05-20 11:18:06 -07004954 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01004955 if (device == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004956 return BAD_VALUE;
4957 }
4958
François Gaffie11d30102018-11-02 16:09:09 +01004959 if (!inputDesc->mProfile->isCompatibleProfile(DeviceVector(device),
Eric Laurent275e8e92014-11-30 15:14:47 -08004960 patch->sinks[0].sample_rate,
4961 NULL, /*updatedSampleRate*/
4962 patch->sinks[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07004963 NULL, /*updatedFormat*/
Eric Laurent275e8e92014-11-30 15:14:47 -08004964 patch->sinks[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07004965 NULL, /*updatedChannelMask*/
Eric Laurent275e8e92014-11-30 15:14:47 -08004966 // FIXME for the parameter type,
4967 // and the NONE
4968 (audio_output_flags_t)
Glenn Kasten6a8ab052014-07-24 14:08:35 -07004969 AUDIO_INPUT_FLAG_NONE)) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004970 return INVALID_OPERATION;
4971 }
4972 // TODO: reconfigure output format and channels here
François Gaffieafd4cea2019-11-18 15:50:22 +01004973 ALOGV("%s setting device %s on output %d", __func__,
François Gaffie11d30102018-11-02 16:09:09 +01004974 device->toString().c_str(), inputDesc->mIoHandle);
4975 setInputDevice(inputDesc->mIoHandle, device, true, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004976 index = mAudioPatches.indexOfKey(*handle);
4977 if (index >= 0) {
4978 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004979 ALOGW("%s setInputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004980 }
4981 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01004982 patchDesc->setUid(uid);
4983 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004984 } else {
François Gaffieafd4cea2019-11-18 15:50:22 +01004985 ALOGW("%s setInputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004986 return INVALID_OPERATION;
4987 }
4988 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
4989 // device to device connection
4990 if (patchDesc != 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07004991 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004992 return BAD_VALUE;
4993 }
4994 }
François Gaffie11d30102018-11-02 16:09:09 +01004995 sp<DeviceDescriptor> srcDevice =
Eric Laurent6a94d692014-05-20 11:18:06 -07004996 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01004997 if (srcDevice == 0) {
Eric Laurent58f8eb72014-09-12 16:19:41 -07004998 return BAD_VALUE;
4999 }
Eric Laurent874c42872014-08-08 15:13:39 -07005000
Eric Laurent6a94d692014-05-20 11:18:06 -07005001 //update source and sink with our own data as the data passed in the patch may
5002 // be incomplete.
François Gaffieafd4cea2019-11-18 15:50:22 +01005003 PatchBuilder patchBuilder;
5004 audio_port_config sourcePortConfig = {};
Dean Wheatley8bee85a2021-02-10 16:02:23 +11005005
5006 // if first sink is to MSD, establish single MSD patch
5007 if (getMsdAudioOutDevices().contains(
5008 mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id))) {
5009 ALOGV("%s patching to MSD", __FUNCTION__);
5010 patchBuilder = buildMsdPatch(false /*msdIsSource*/, srcDevice);
5011 goto installPatch;
5012 }
5013
François Gaffieafd4cea2019-11-18 15:50:22 +01005014 srcDevice->toAudioPortConfig(&sourcePortConfig, &patch->sources[0]);
5015 patchBuilder.addSource(sourcePortConfig);
Eric Laurent6a94d692014-05-20 11:18:06 -07005016
Eric Laurent874c42872014-08-08 15:13:39 -07005017 for (size_t i = 0; i < patch->num_sinks; i++) {
5018 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005019 ALOGV("%s source device but one sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07005020 return INVALID_OPERATION;
5021 }
François Gaffie11d30102018-11-02 16:09:09 +01005022 sp<DeviceDescriptor> sinkDevice =
Eric Laurent874c42872014-08-08 15:13:39 -07005023 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
François Gaffie11d30102018-11-02 16:09:09 +01005024 if (sinkDevice == 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07005025 return BAD_VALUE;
5026 }
François Gaffieafd4cea2019-11-18 15:50:22 +01005027 audio_port_config sinkPortConfig = {};
5028 sinkDevice->toAudioPortConfig(&sinkPortConfig, &patch->sinks[i]);
5029 patchBuilder.addSink(sinkPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07005030
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005031 // Whatever Sw or Hw bridge, we do attach an SwOutput to an Audio Source for
5032 // volume management purpose (tracking activity)
5033 // In case of Hw bridge, it is a Work Around. The mixPort used is the one declared
5034 // in config XML to reach the sink so that is can be declared as available.
5035 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurent78b07302022-10-07 16:20:34 +02005036 sp<SwAudioOutputDescriptor> outputDesc;
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005037 if (!sourceDesc->isInternal()) {
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005038 // take care of dynamic routing for SwOutput selection,
5039 audio_attributes_t attributes = sourceDesc->attributes();
5040 audio_stream_type_t stream = sourceDesc->stream();
5041 audio_attributes_t resultAttr;
5042 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
5043 config.sample_rate = sourceDesc->config().sample_rate;
François Gaffie2a24db42022-04-04 16:45:02 +02005044 audio_channel_mask_t sourceMask = sourceDesc->config().channel_mask;
5045 config.channel_mask =
5046 (audio_channel_mask_get_representation(sourceMask)
5047 == AUDIO_CHANNEL_REPRESENTATION_INDEX) ? sourceMask
5048 : audio_channel_mask_in_to_out(sourceMask);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005049 config.format = sourceDesc->config().format;
5050 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
5051 audio_port_handle_t selectedDeviceId = AUDIO_PORT_HANDLE_NONE;
5052 bool isRequestedDeviceForExclusiveUse = false;
5053 output_type_t outputType;
Eric Laurentb0a7bc92022-04-05 15:06:08 +02005054 bool isSpatialized;
jiabinc658e452022-10-21 20:52:21 +00005055 bool isBitPerfect;
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005056 getOutputForAttrInt(&resultAttr, &output, AUDIO_SESSION_NONE, &attributes,
5057 &stream, sourceDesc->uid(), &config, &flags,
5058 &selectedDeviceId, &isRequestedDeviceForExclusiveUse,
jiabinc658e452022-10-21 20:52:21 +00005059 nullptr, &outputType, &isSpatialized, &isBitPerfect);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005060 if (output == AUDIO_IO_HANDLE_NONE) {
5061 ALOGV("%s no output for device %s",
5062 __FUNCTION__, sinkDevice->toString().c_str());
5063 return INVALID_OPERATION;
5064 }
5065 outputDesc = mOutputs.valueFor(output);
5066 if (outputDesc->isDuplicated()) {
5067 ALOGE("%s output is duplicated", __func__);
5068 return INVALID_OPERATION;
5069 }
François Gaffie7e39df22022-04-26 12:48:49 +02005070 bool closeOutput = outputDesc->mDirectOpenCount != 0;
5071 sourceDesc->setSwOutput(outputDesc, closeOutput);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005072 } else {
5073 // Same for "raw patches" aka created from createAudioPatch API
5074 SortedVector<audio_io_handle_t> outputs =
5075 getOutputsForDevices(DeviceVector(sinkDevice), mOutputs);
5076 // if the sink device is reachable via an opened output stream, request to
5077 // go via this output stream by adding a second source to the patch
5078 // description
5079 output = selectOutput(outputs);
5080 if (output == AUDIO_IO_HANDLE_NONE) {
5081 ALOGE("%s no output available for internal patch sink", __func__);
5082 return INVALID_OPERATION;
5083 }
5084 outputDesc = mOutputs.valueFor(output);
5085 if (outputDesc->isDuplicated()) {
5086 ALOGV("%s output for device %s is duplicated",
5087 __func__, sinkDevice->toString().c_str());
5088 return INVALID_OPERATION;
5089 }
François Gaffie7e39df22022-04-26 12:48:49 +02005090 sourceDesc->setSwOutput(outputDesc, /* closeOutput= */ false);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005091 }
Eric Laurent3bcf8592015-04-03 12:13:24 -07005092 // create a software bridge in PatchPanel if:
Scott Randolphf3172402018-01-23 17:06:53 -08005093 // - source and sink devices are on different HW modules OR
Eric Laurent3bcf8592015-04-03 12:13:24 -07005094 // - audio HAL version is < 3.0
Francois Gaffie99896da2018-04-09 11:05:33 +02005095 // - audio HAL version is >= 3.0 but no route has been declared between devices
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005096 // - called from startAudioSource (aka sourceDesc is not internal) and source device
5097 // does not have a gain controller
François Gaffie11d30102018-11-02 16:09:09 +01005098 if (!srcDevice->hasSameHwModuleAs(sinkDevice) ||
5099 (srcDevice->getModuleVersionMajor() < 3) ||
François Gaffieafd4cea2019-11-18 15:50:22 +01005100 !srcDevice->getModule()->supportsPatch(srcDevice, sinkDevice) ||
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005101 (!sourceDesc->isInternal() &&
François Gaffieafd4cea2019-11-18 15:50:22 +01005102 srcDevice->getAudioPort()->getGains().size() == 0)) {
Eric Laurent3bcf8592015-04-03 12:13:24 -07005103 // support only one sink device for now to simplify output selection logic
Eric Laurent874c42872014-08-08 15:13:39 -07005104 if (patch->num_sinks > 1) {
Eric Laurent83b88082014-06-20 18:31:16 -07005105 return INVALID_OPERATION;
5106 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005107 sourceDesc->setUseSwBridge();
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005108 if (outputDesc != nullptr) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005109 audio_port_config srcMixPortConfig = {};
Ytai Ben-Tsvic9d2a912021-11-22 16:43:09 -08005110 outputDesc->toAudioPortConfig(&srcMixPortConfig, nullptr);
François Gaffieafd4cea2019-11-18 15:50:22 +01005111 // for volume control, we may need a valid stream
Eric Laurent78b07302022-10-07 16:20:34 +02005112 srcMixPortConfig.ext.mix.usecase.stream =
5113 (!sourceDesc->isInternal() || isCallTxAudioSource(sourceDesc)) ?
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005114 mEngine->getStreamTypeForAttributes(sourceDesc->attributes()) :
5115 AUDIO_STREAM_PATCH;
François Gaffieafd4cea2019-11-18 15:50:22 +01005116 patchBuilder.addSource(srcMixPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07005117 }
Eric Laurent83b88082014-06-20 18:31:16 -07005118 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005119 }
5120 // TODO: check from routing capabilities in config file and other conflicting patches
5121
Dean Wheatley8bee85a2021-02-10 16:02:23 +11005122installPatch:
François Gaffieafd4cea2019-11-18 15:50:22 +01005123 status_t status = installPatch(
5124 __func__, index, handle, patchBuilder.patch(), delayMs, uid, &patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07005125 if (status != NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005126 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
Eric Laurent6a94d692014-05-20 11:18:06 -07005127 return INVALID_OPERATION;
5128 }
5129 } else {
5130 return BAD_VALUE;
5131 }
5132 } else {
5133 return BAD_VALUE;
5134 }
5135 return NO_ERROR;
5136}
5137
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005138status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle, uid_t uid)
Eric Laurent6a94d692014-05-20 11:18:06 -07005139{
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005140 ALOGV("%s patch %d", __func__, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005141 ssize_t index = mAudioPatches.indexOfKey(handle);
5142
5143 if (index < 0) {
5144 return BAD_VALUE;
5145 }
5146 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005147 ALOGV("%s() mUidCached %d patchDesc->mUid %d uid %d",
5148 __func__, mUidCached, patchDesc->getUid(), uid);
5149 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005150 return INVALID_OPERATION;
5151 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005152 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
5153 for (size_t i = 0; i < mAudioSources.size(); i++) {
5154 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
5155 if (sourceDesc != nullptr && sourceDesc->getPatchHandle() == handle) {
5156 portId = sourceDesc->portId();
5157 break;
5158 }
5159 }
5160 return portId != AUDIO_PORT_HANDLE_NONE ?
5161 stopAudioSource(portId) : releaseAudioPatchInternal(handle);
François Gaffieafd4cea2019-11-18 15:50:22 +01005162}
Eric Laurent6a94d692014-05-20 11:18:06 -07005163
François Gaffieafd4cea2019-11-18 15:50:22 +01005164status_t AudioPolicyManager::releaseAudioPatchInternal(audio_patch_handle_t handle,
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005165 uint32_t delayMs,
5166 const sp<SourceClientDescriptor>& sourceDesc)
François Gaffieafd4cea2019-11-18 15:50:22 +01005167{
5168 ALOGV("%s patch %d", __func__, handle);
5169 if (mAudioPatches.indexOfKey(handle) < 0) {
5170 ALOGE("%s: no patch found with handle=%d", __func__, handle);
5171 return BAD_VALUE;
5172 }
5173 sp<AudioPatch> patchDesc = mAudioPatches.valueFor(handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005174 struct audio_patch *patch = &patchDesc->mPatch;
François Gaffieafd4cea2019-11-18 15:50:22 +01005175 patchDesc->setUid(mUidCached);
Eric Laurent6a94d692014-05-20 11:18:06 -07005176 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005177 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005178 if (outputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005179 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005180 return BAD_VALUE;
5181 }
5182
François Gaffie11d30102018-11-02 16:09:09 +01005183 setOutputDevices(outputDesc,
5184 getNewOutputDevices(outputDesc, true /*fromCache*/),
5185 true,
5186 0,
5187 NULL);
Eric Laurent6a94d692014-05-20 11:18:06 -07005188 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
5189 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
François Gaffie53615e22015-03-19 09:24:12 +01005190 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005191 if (inputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005192 ALOGV("%s input not found for id %d", __func__, patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005193 return BAD_VALUE;
5194 }
5195 setInputDevice(inputDesc->mIoHandle,
Eric Laurentfb66dd92016-01-28 18:32:03 -08005196 getNewInputDevice(inputDesc),
Eric Laurent6a94d692014-05-20 11:18:06 -07005197 true,
5198 NULL);
5199 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005200 status_t status =
5201 mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
5202 ALOGV("%s patch panel returned %d patchHandle %d",
5203 __func__, status, patchDesc->getAfHandle());
5204 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005205 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005206 mpClientInterface->onAudioPatchListUpdate();
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005207 // SW or HW Bridge
5208 sp<SwAudioOutputDescriptor> outputDesc = nullptr;
5209 audio_patch_handle_t patchHandle = AUDIO_PATCH_HANDLE_NONE;
Francois Gaffie7feb8542020-04-06 17:39:47 +02005210 if (patch->num_sources > 1 && patch->sources[1].type == AUDIO_PORT_TYPE_MIX) {
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005211 outputDesc = mOutputs.getOutputFromId(patch->sources[1].id);
5212 } else if (patch->num_sources == 1 && sourceDesc != nullptr) {
5213 outputDesc = sourceDesc->swOutput().promote();
5214 }
5215 if (outputDesc == nullptr) {
5216 ALOGW("%s no output for id %d", __func__, patch->sources[0].id);
5217 // releaseOutput has already called closeOutput in case of direct output
5218 return NO_ERROR;
5219 }
François Gaffie7e39df22022-04-26 12:48:49 +02005220 patchHandle = outputDesc->getPatchHandle();
5221 // When a Sw bridge is released, the mixer used by this bridge will release its
5222 // patch at AudioFlinger side. Hence, the mixer audio patch must be recreated
5223 // Reuse patch handle to force audio flinger removing initial mixer patch removal
5224 // updating hal patch handle (prevent leaks).
5225 // While using a HwBridge, force reconsidering device only if not reusing an existing
5226 // output and no more activity on output (will force to close).
5227 bool force = sourceDesc->useSwBridge() ||
5228 (sourceDesc->canCloseOutput() && !outputDesc->isActive());
5229 // APM pattern is to have always outputs opened / patch realized for reachable devices.
5230 // Update device may result to NONE (empty), coupled with force, it releases the patch.
5231 // Reconsider device only for cases:
5232 // 1 / Active Output
5233 // 2 / Inactive Output previously hosting HwBridge
5234 // 3 / Inactive Output previously hosting SwBridge that can be closed.
5235 bool updateDevice = outputDesc->isActive() || !sourceDesc->useSwBridge() ||
5236 sourceDesc->canCloseOutput();
5237 setOutputDevices(outputDesc,
5238 updateDevice ? getNewOutputDevices(outputDesc, true /*fromCache*/) :
5239 outputDesc->devices(),
5240 force,
5241 0,
5242 patchHandle == AUDIO_PATCH_HANDLE_NONE ? nullptr : &patchHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005243 } else {
5244 return BAD_VALUE;
5245 }
5246 } else {
5247 return BAD_VALUE;
5248 }
5249 return NO_ERROR;
5250}
5251
5252status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
5253 struct audio_patch *patches,
5254 unsigned int *generation)
5255{
François Gaffie53615e22015-03-19 09:24:12 +01005256 if (generation == NULL) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005257 return BAD_VALUE;
5258 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005259 *generation = curAudioPortGeneration();
François Gaffie53615e22015-03-19 09:24:12 +01005260 return mAudioPatches.listAudioPatches(num_patches, patches);
Eric Laurent6a94d692014-05-20 11:18:06 -07005261}
5262
Eric Laurente1715a42014-05-20 11:30:42 -07005263status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07005264{
Eric Laurente1715a42014-05-20 11:30:42 -07005265 ALOGV("setAudioPortConfig()");
5266
5267 if (config == NULL) {
5268 return BAD_VALUE;
5269 }
5270 ALOGV("setAudioPortConfig() on port handle %d", config->id);
5271 // Only support gain configuration for now
Eric Laurenta121f902014-06-03 13:32:54 -07005272 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
5273 return INVALID_OPERATION;
Eric Laurente1715a42014-05-20 11:30:42 -07005274 }
5275
Eric Laurenta121f902014-06-03 13:32:54 -07005276 sp<AudioPortConfig> audioPortConfig;
Eric Laurente1715a42014-05-20 11:30:42 -07005277 if (config->type == AUDIO_PORT_TYPE_MIX) {
5278 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005279 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07005280 if (outputDesc == NULL) {
5281 return BAD_VALUE;
5282 }
Eric Laurent84c70242014-06-23 08:46:27 -07005283 ALOG_ASSERT(!outputDesc->isDuplicated(),
5284 "setAudioPortConfig() called on duplicated output %d",
5285 outputDesc->mIoHandle);
Eric Laurenta121f902014-06-03 13:32:54 -07005286 audioPortConfig = outputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07005287 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
François Gaffie53615e22015-03-19 09:24:12 +01005288 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07005289 if (inputDesc == NULL) {
5290 return BAD_VALUE;
5291 }
Eric Laurenta121f902014-06-03 13:32:54 -07005292 audioPortConfig = inputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07005293 } else {
5294 return BAD_VALUE;
5295 }
5296 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
5297 sp<DeviceDescriptor> deviceDesc;
5298 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
5299 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
5300 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
5301 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
5302 } else {
5303 return BAD_VALUE;
5304 }
5305 if (deviceDesc == NULL) {
5306 return BAD_VALUE;
5307 }
Eric Laurenta121f902014-06-03 13:32:54 -07005308 audioPortConfig = deviceDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07005309 } else {
5310 return BAD_VALUE;
5311 }
5312
Mikhail Naganov7be71d22018-05-23 16:51:46 -07005313 struct audio_port_config backupConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07005314 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
5315 if (status == NO_ERROR) {
Mikhail Naganov7be71d22018-05-23 16:51:46 -07005316 struct audio_port_config newConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07005317 audioPortConfig->toAudioPortConfig(&newConfig, config);
5318 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
Eric Laurente1715a42014-05-20 11:30:42 -07005319 }
Eric Laurenta121f902014-06-03 13:32:54 -07005320 if (status != NO_ERROR) {
5321 audioPortConfig->applyAudioPortConfig(&backupConfig);
Eric Laurente1715a42014-05-20 11:30:42 -07005322 }
Eric Laurente1715a42014-05-20 11:30:42 -07005323
5324 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07005325}
5326
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005327void AudioPolicyManager::releaseResourcesForUid(uid_t uid)
5328{
Eric Laurentd60560a2015-04-10 11:31:20 -07005329 clearAudioSources(uid);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005330 clearAudioPatches(uid);
5331 clearSessionRoutes(uid);
5332}
5333
Eric Laurent6a94d692014-05-20 11:18:06 -07005334void AudioPolicyManager::clearAudioPatches(uid_t uid)
5335{
Eric Laurent0add0fd2014-12-04 18:58:14 -08005336 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005337 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
François Gaffieafd4cea2019-11-18 15:50:22 +01005338 if (patchDesc->getUid() == uid) {
Eric Laurent0add0fd2014-12-04 18:58:14 -08005339 releaseAudioPatch(mAudioPatches.keyAt(i), uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07005340 }
5341 }
5342}
5343
François Gaffiec005e562018-11-06 15:04:49 +01005344void AudioPolicyManager::checkStrategyRoute(product_strategy_t ps, audio_io_handle_t ouptutToSkip)
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005345{
François Gaffiec005e562018-11-06 15:04:49 +01005346 // Take the first attributes following the product strategy as it is used to retrieve the routed
5347 // device. All attributes wihin a strategy follows the same "routing strategy"
5348 auto attributes = mEngine->getAllAttributesForProductStrategy(ps).front();
5349 DeviceVector devices = mEngine->getOutputDevicesForAttributes(attributes, nullptr, false);
François Gaffie11d30102018-11-02 16:09:09 +01005350 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
jiabin3ff8d7d2022-12-13 06:27:44 +00005351 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005352 for (size_t j = 0; j < mOutputs.size(); j++) {
5353 if (mOutputs.keyAt(j) == ouptutToSkip) {
5354 continue;
5355 }
5356 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(j);
François Gaffiec005e562018-11-06 15:04:49 +01005357 if (!outputDesc->isStrategyActive(ps)) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005358 continue;
5359 }
5360 // If the default device for this strategy is on another output mix,
5361 // invalidate all tracks in this strategy to force re connection.
5362 // Otherwise select new device on the output mix.
5363 if (outputs.indexOf(mOutputs.keyAt(j)) < 0) {
jiabinc44b3462022-12-08 12:52:31 -08005364 invalidateStreams(mEngine->getStreamTypesForProductStrategy(ps));
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005365 } else {
jiabin3ff8d7d2022-12-13 06:27:44 +00005366 DeviceVector newDevices = getNewOutputDevices(outputDesc, false /*fromCache*/);
5367 if (outputDesc->mUsePreferredMixerAttributes && outputDesc->devices() != newDevices) {
5368 // If the device is using preferred mixer attributes, the output need to reopen
5369 // with default configuration when the new selected devices are different from
5370 // current routing devices.
5371 outputsToReopen.emplace(mOutputs.keyAt(j), newDevices);
5372 continue;
5373 }
5374 setOutputDevices(outputDesc, newDevices, false);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005375 }
5376 }
jiabin3ff8d7d2022-12-13 06:27:44 +00005377 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005378}
5379
5380void AudioPolicyManager::clearSessionRoutes(uid_t uid)
5381{
5382 // remove output routes associated with this uid
François Gaffiec005e562018-11-06 15:04:49 +01005383 std::vector<product_strategy_t> affectedStrategies;
Eric Laurent97ac8712018-07-27 18:59:02 -07005384 for (size_t i = 0; i < mOutputs.size(); i++) {
5385 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07005386 for (const auto& client : outputDesc->getClientIterable()) {
5387 if (client->hasPreferredDevice() && client->uid() == uid) {
5388 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
François Gaffiec005e562018-11-06 15:04:49 +01005389 auto clientStrategy = client->strategy();
5390 if (std::find(begin(affectedStrategies), end(affectedStrategies), clientStrategy) !=
5391 end(affectedStrategies)) {
5392 continue;
5393 }
5394 affectedStrategies.push_back(client->strategy());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005395 }
5396 }
5397 }
5398 // reroute outputs if necessary
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005399 for (const auto& strategy : affectedStrategies) {
5400 checkStrategyRoute(strategy, AUDIO_IO_HANDLE_NONE);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005401 }
5402
5403 // remove input routes associated with this uid
5404 SortedVector<audio_source_t> affectedSources;
Eric Laurent97ac8712018-07-27 18:59:02 -07005405 for (size_t i = 0; i < mInputs.size(); i++) {
5406 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07005407 for (const auto& client : inputDesc->getClientIterable()) {
5408 if (client->hasPreferredDevice() && client->uid() == uid) {
5409 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
5410 affectedSources.add(client->source());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005411 }
5412 }
5413 }
5414 // reroute inputs if necessary
5415 SortedVector<audio_io_handle_t> inputsToClose;
5416 for (size_t i = 0; i < mInputs.size(); i++) {
5417 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Eric Laurent4eb58f12018-12-07 16:41:02 -08005418 if (affectedSources.indexOf(inputDesc->source()) >= 0) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005419 inputsToClose.add(inputDesc->mIoHandle);
5420 }
5421 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005422 for (const auto& input : inputsToClose) {
5423 closeInput(input);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005424 }
5425}
5426
Eric Laurentd60560a2015-04-10 11:31:20 -07005427void AudioPolicyManager::clearAudioSources(uid_t uid)
5428{
5429 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005430 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
5431 if (sourceDesc->uid() == uid) {
Eric Laurentd60560a2015-04-10 11:31:20 -07005432 stopAudioSource(mAudioSources.keyAt(i));
5433 }
5434 }
5435}
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005436
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005437status_t AudioPolicyManager::acquireSoundTriggerSession(audio_session_t *session,
5438 audio_io_handle_t *ioHandle,
5439 audio_devices_t *device)
5440{
Glenn Kastenf0c6d7d2016-02-26 10:44:04 -08005441 *session = (audio_session_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
5442 *ioHandle = (audio_io_handle_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
Francois Gaffie716e1432019-01-14 16:58:59 +01005443 audio_attributes_t attr = { .source = AUDIO_SOURCE_HOTWORD };
Eric Laurentcedd5b52023-03-22 00:03:31 +00005444 sp<DeviceDescriptor> deviceDesc = mEngine->getInputDeviceForAttributes(attr);
5445 if (deviceDesc == nullptr) {
5446 return INVALID_OPERATION;
5447 }
5448 *device = deviceDesc->type();
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005449
François Gaffiedf372692015-03-19 10:43:27 +01005450 return mSoundTriggerSessions.acquireSession(*session, *ioHandle);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005451}
5452
Eric Laurentd60560a2015-04-10 11:31:20 -07005453status_t AudioPolicyManager::startAudioSource(const struct audio_port_config *source,
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005454 const audio_attributes_t *attributes,
5455 audio_port_handle_t *portId,
5456 uid_t uid)
Eric Laurent554a2772015-04-10 11:29:24 -07005457{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005458 ALOGV("%s", __FUNCTION__);
5459 *portId = AUDIO_PORT_HANDLE_NONE;
5460
5461 if (source == NULL || attributes == NULL || portId == NULL) {
5462 ALOGW("%s invalid argument: source %p attributes %p handle %p",
5463 __FUNCTION__, source, attributes, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005464 return BAD_VALUE;
5465 }
5466
Eric Laurentd60560a2015-04-10 11:31:20 -07005467 if (source->role != AUDIO_PORT_ROLE_SOURCE ||
5468 source->type != AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005469 ALOGW("%s INVALID_OPERATION source->role %d source->type %d",
5470 __FUNCTION__, source->role, source->type);
Eric Laurentd60560a2015-04-10 11:31:20 -07005471 return INVALID_OPERATION;
5472 }
5473
François Gaffie11d30102018-11-02 16:09:09 +01005474 sp<DeviceDescriptor> srcDevice =
Eric Laurentd60560a2015-04-10 11:31:20 -07005475 mAvailableInputDevices.getDevice(source->ext.device.type,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005476 String8(source->ext.device.address),
5477 AUDIO_FORMAT_DEFAULT);
François Gaffie11d30102018-11-02 16:09:09 +01005478 if (srcDevice == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005479 ALOGW("%s source->ext.device.type %08x not found", __FUNCTION__, source->ext.device.type);
Eric Laurentd60560a2015-04-10 11:31:20 -07005480 return BAD_VALUE;
5481 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005482
jiabin4ef93452019-09-10 14:29:54 -07005483 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurentd60560a2015-04-10 11:31:20 -07005484
François Gaffieaaac0fd2018-11-22 17:56:39 +01005485 sp<SourceClientDescriptor> sourceDesc =
François Gaffieafd4cea2019-11-18 15:50:22 +01005486 new SourceClientDescriptor(*portId, uid, *attributes, *source, srcDevice,
François Gaffieaaac0fd2018-11-22 17:56:39 +01005487 mEngine->getStreamTypeForAttributes(*attributes),
5488 mEngine->getProductStrategyForAttributes(*attributes),
5489 toVolumeSource(*attributes));
Eric Laurentd60560a2015-04-10 11:31:20 -07005490
5491 status_t status = connectAudioSource(sourceDesc);
5492 if (status == NO_ERROR) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005493 mAudioSources.add(*portId, sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07005494 }
5495 return status;
5496}
5497
Francois Gaffie601801d2021-06-22 13:27:39 +02005498sp<SourceClientDescriptor> AudioPolicyManager::startAudioSourceInternal(
5499 const struct audio_port_config *source, const audio_attributes_t *attributes, uid_t uid)
5500{
5501 ALOGV("%s", __FUNCTION__);
5502 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
5503
5504 status_t status = startAudioSource(source, attributes, &portId, uid);
5505 ALOGE_IF(status != OK, "%s: failed to start audio source (%d)", __func__, status);
5506 return mAudioSources.valueFor(portId);
5507}
5508
5509
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005510status_t AudioPolicyManager::connectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07005511{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005512 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->portId());
Eric Laurentd60560a2015-04-10 11:31:20 -07005513
5514 // make sure we only have one patch per source.
5515 disconnectAudioSource(sourceDesc);
5516
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005517 audio_attributes_t attributes = sourceDesc->attributes();
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005518 // May the device (dynamic) have been disconnected/reconnected, id has changed.
5519 sp<DeviceDescriptor> srcDevice = mAvailableInputDevices.getDevice(
5520 sourceDesc->srcDevice()->type(),
5521 String8(sourceDesc->srcDevice()->address().c_str()),
5522 AUDIO_FORMAT_DEFAULT);
François Gaffiec005e562018-11-06 15:04:49 +01005523 DeviceVector sinkDevices =
Francois Gaffieff1eb522020-05-06 18:37:04 +02005524 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false /*fromCache*/);
François Gaffiec005e562018-11-06 15:04:49 +01005525 ALOG_ASSERT(!sinkDevices.isEmpty(), "connectAudioSource(): no device found for attributes");
François Gaffie11d30102018-11-02 16:09:09 +01005526 sp<DeviceDescriptor> sinkDevice = sinkDevices.itemAt(0);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005527 if (!mAvailableOutputDevices.contains(sinkDevice)) {
5528 ALOGE("%s Device %s not available", __func__, sinkDevice->toString().c_str());
5529 return INVALID_OPERATION;
5530 }
François Gaffieafd4cea2019-11-18 15:50:22 +01005531 PatchBuilder patchBuilder;
5532 patchBuilder.addSink(sinkDevice).addSource(srcDevice);
5533 audio_patch_handle_t handle = AUDIO_PATCH_HANDLE_NONE;
François Gaffieafd4cea2019-11-18 15:50:22 +01005534
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005535 return connectAudioSourceToSink(
5536 sourceDesc, sinkDevice, patchBuilder.patch(), handle, mUidCached, 0 /*delayMs*/);
Eric Laurent554a2772015-04-10 11:29:24 -07005537}
5538
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005539status_t AudioPolicyManager::stopAudioSource(audio_port_handle_t portId)
Eric Laurent554a2772015-04-10 11:29:24 -07005540{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005541 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueFor(portId);
5542 ALOGV("%s port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005543 if (sourceDesc == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005544 ALOGW("%s unknown source for port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005545 return BAD_VALUE;
5546 }
5547 status_t status = disconnectAudioSource(sourceDesc);
5548
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005549 mAudioSources.removeItem(portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005550 return status;
5551}
5552
Andy Hung2ddee192015-12-18 17:34:44 -08005553status_t AudioPolicyManager::setMasterMono(bool mono)
5554{
5555 if (mMasterMono == mono) {
5556 return NO_ERROR;
5557 }
5558 mMasterMono = mono;
5559 // if enabling mono we close all offloaded devices, which will invalidate the
5560 // corresponding AudioTrack. The AudioTrack client/MediaPlayer is responsible
5561 // for recreating the new AudioTrack as non-offloaded PCM.
5562 //
5563 // If disabling mono, we leave all tracks as is: we don't know which clients
5564 // and tracks are able to be recreated as offloaded. The next "song" should
5565 // play back offloaded.
5566 if (mMasterMono) {
5567 Vector<audio_io_handle_t> offloaded;
5568 for (size_t i = 0; i < mOutputs.size(); ++i) {
5569 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
5570 if (desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
5571 offloaded.push(desc->mIoHandle);
5572 }
5573 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005574 for (const auto& handle : offloaded) {
5575 closeOutput(handle);
Andy Hung2ddee192015-12-18 17:34:44 -08005576 }
5577 }
5578 // update master mono for all remaining outputs
5579 for (size_t i = 0; i < mOutputs.size(); ++i) {
5580 updateMono(mOutputs.keyAt(i));
5581 }
5582 return NO_ERROR;
5583}
5584
5585status_t AudioPolicyManager::getMasterMono(bool *mono)
5586{
5587 *mono = mMasterMono;
5588 return NO_ERROR;
5589}
5590
Eric Laurentac9cef52017-06-09 15:46:26 -07005591float AudioPolicyManager::getStreamVolumeDB(
5592 audio_stream_type_t stream, int index, audio_devices_t device)
5593{
jiabin9a3361e2019-10-01 09:38:30 -07005594 return computeVolume(getVolumeCurves(stream), toVolumeSource(stream), index, {device});
Eric Laurentac9cef52017-06-09 15:46:26 -07005595}
5596
jiabin81772902018-04-02 17:52:27 -07005597status_t AudioPolicyManager::getSurroundFormats(unsigned int *numSurroundFormats,
5598 audio_format_t *surroundFormats,
Kriti Dang6537def2021-03-02 13:46:59 +01005599 bool *surroundFormatsEnabled)
jiabin81772902018-04-02 17:52:27 -07005600{
Kriti Dang6537def2021-03-02 13:46:59 +01005601 if (numSurroundFormats == nullptr || (*numSurroundFormats != 0 &&
5602 (surroundFormats == nullptr || surroundFormatsEnabled == nullptr))) {
jiabin81772902018-04-02 17:52:27 -07005603 return BAD_VALUE;
5604 }
Kriti Dang6537def2021-03-02 13:46:59 +01005605 ALOGV("%s() numSurroundFormats %d surroundFormats %p surroundFormatsEnabled %p",
5606 __func__, *numSurroundFormats, surroundFormats, surroundFormatsEnabled);
jiabin81772902018-04-02 17:52:27 -07005607
5608 size_t formatsWritten = 0;
5609 size_t formatsMax = *numSurroundFormats;
Kriti Dangef6be8f2020-11-05 11:58:19 +01005610
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005611 *numSurroundFormats = mConfig->getSurroundFormats().size();
Mikhail Naganov100f0122018-11-29 11:22:16 -08005612 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
5613 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005614 for (const auto& format: mConfig->getSurroundFormats()) {
jiabin81772902018-04-02 17:52:27 -07005615 if (formatsWritten < formatsMax) {
Kriti Dang6537def2021-03-02 13:46:59 +01005616 surroundFormats[formatsWritten] = format.first;
Mikhail Naganov100f0122018-11-29 11:22:16 -08005617 bool formatEnabled = true;
5618 switch (forceUse) {
5619 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL:
Kriti Dang6537def2021-03-02 13:46:59 +01005620 formatEnabled = mManualSurroundFormats.count(format.first) != 0;
Mikhail Naganov100f0122018-11-29 11:22:16 -08005621 break;
5622 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER:
5623 formatEnabled = false;
5624 break;
5625 default: // AUTO or ALWAYS => true
5626 break;
jiabin81772902018-04-02 17:52:27 -07005627 }
5628 surroundFormatsEnabled[formatsWritten++] = formatEnabled;
5629 }
jiabin81772902018-04-02 17:52:27 -07005630 }
5631 return NO_ERROR;
5632}
5633
Kriti Dang6537def2021-03-02 13:46:59 +01005634status_t AudioPolicyManager::getReportedSurroundFormats(unsigned int *numSurroundFormats,
5635 audio_format_t *surroundFormats) {
5636 if (numSurroundFormats == nullptr || (*numSurroundFormats != 0 && surroundFormats == nullptr)) {
5637 return BAD_VALUE;
5638 }
5639 ALOGV("%s() numSurroundFormats %d surroundFormats %p",
5640 __func__, *numSurroundFormats, surroundFormats);
5641
5642 size_t formatsWritten = 0;
5643 size_t formatsMax = *numSurroundFormats;
5644 std::unordered_set<audio_format_t> formats; // Uses primary surround formats only
5645
5646 // Return formats from all device profiles that have already been resolved by
5647 // checkOutputsForDevice().
5648 for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
5649 sp<DeviceDescriptor> device = mAvailableOutputDevices[i];
5650 audio_devices_t deviceType = device->type();
5651 // Enabling/disabling formats are applied to only HDMI devices. So, this function
5652 // returns formats reported by HDMI devices.
5653 if (deviceType != AUDIO_DEVICE_OUT_HDMI) {
5654 continue;
5655 }
5656 // Formats reported by sink devices
5657 std::unordered_set<audio_format_t> formatset;
5658 if (auto it = mReportedFormatsMap.find(device); it != mReportedFormatsMap.end()) {
5659 formatset.insert(it->second.begin(), it->second.end());
5660 }
5661
5662 // Formats hard-coded in the in policy configuration file (if any).
5663 FormatVector encodedFormats = device->encodedFormats();
5664 formatset.insert(encodedFormats.begin(), encodedFormats.end());
5665 // Filter the formats which are supported by the vendor hardware.
5666 for (auto it = formatset.begin(); it != formatset.end(); ++it) {
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005667 if (mConfig->getSurroundFormats().count(*it) != 0) {
Kriti Dang6537def2021-03-02 13:46:59 +01005668 formats.insert(*it);
5669 } else {
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005670 for (const auto& pair : mConfig->getSurroundFormats()) {
Kriti Dang6537def2021-03-02 13:46:59 +01005671 if (pair.second.count(*it) != 0) {
5672 formats.insert(pair.first);
5673 break;
5674 }
5675 }
5676 }
5677 }
5678 }
5679 *numSurroundFormats = formats.size();
5680 for (const auto& format: formats) {
5681 if (formatsWritten < formatsMax) {
5682 surroundFormats[formatsWritten++] = format;
5683 }
5684 }
5685 return NO_ERROR;
5686}
5687
jiabin81772902018-04-02 17:52:27 -07005688status_t AudioPolicyManager::setSurroundFormatEnabled(audio_format_t audioFormat, bool enabled)
5689{
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005690 ALOGV("%s() format 0x%X enabled %d", __func__, audioFormat, enabled);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005691 const auto& formatIter = mConfig->getSurroundFormats().find(audioFormat);
5692 if (formatIter == mConfig->getSurroundFormats().end()) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005693 ALOGW("%s() format 0x%X is not a known surround format", __func__, audioFormat);
jiabin81772902018-04-02 17:52:27 -07005694 return BAD_VALUE;
5695 }
5696
Mikhail Naganov100f0122018-11-29 11:22:16 -08005697 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND) !=
5698 AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005699 ALOGW("%s() not in manual mode for surround sound format selection", __func__);
jiabin81772902018-04-02 17:52:27 -07005700 return INVALID_OPERATION;
5701 }
5702
Mikhail Naganov100f0122018-11-29 11:22:16 -08005703 if ((mManualSurroundFormats.count(audioFormat) != 0) == enabled) {
jiabin81772902018-04-02 17:52:27 -07005704 return NO_ERROR;
5705 }
5706
Mikhail Naganov100f0122018-11-29 11:22:16 -08005707 std::unordered_set<audio_format_t> surroundFormatsBackup(mManualSurroundFormats);
jiabin81772902018-04-02 17:52:27 -07005708 if (enabled) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005709 mManualSurroundFormats.insert(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07005710 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005711 mManualSurroundFormats.insert(subFormat);
jiabin81772902018-04-02 17:52:27 -07005712 }
5713 } else {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005714 mManualSurroundFormats.erase(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07005715 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005716 mManualSurroundFormats.erase(subFormat);
jiabin81772902018-04-02 17:52:27 -07005717 }
5718 }
5719
5720 sp<SwAudioOutputDescriptor> outputDesc;
5721 bool profileUpdated = false;
jiabin9a3361e2019-10-01 09:38:30 -07005722 DeviceVector hdmiOutputDevices = mAvailableOutputDevices.getDevicesFromType(
5723 AUDIO_DEVICE_OUT_HDMI);
jiabin81772902018-04-02 17:52:27 -07005724 for (size_t i = 0; i < hdmiOutputDevices.size(); i++) {
5725 // Simulate reconnection to update enabled surround sound formats.
jiabince9f20e2019-09-12 16:29:15 -07005726 String8 address = String8(hdmiOutputDevices[i]->address().c_str());
jiabin5740f082019-08-19 15:08:30 -07005727 std::string name = hdmiOutputDevices[i]->getName();
jiabin81772902018-04-02 17:52:27 -07005728 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
5729 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
5730 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005731 name.c_str(),
5732 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005733 if (status != NO_ERROR) {
5734 continue;
5735 }
5736 status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
5737 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
5738 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005739 name.c_str(),
5740 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005741 profileUpdated |= (status == NO_ERROR);
5742 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08005743 // FIXME: Why doing this for input HDMI devices if we don't augment their reported formats?
jiabin9a3361e2019-10-01 09:38:30 -07005744 DeviceVector hdmiInputDevices = mAvailableInputDevices.getDevicesFromType(
jiabin81772902018-04-02 17:52:27 -07005745 AUDIO_DEVICE_IN_HDMI);
5746 for (size_t i = 0; i < hdmiInputDevices.size(); i++) {
5747 // Simulate reconnection to update enabled surround sound formats.
jiabince9f20e2019-09-12 16:29:15 -07005748 String8 address = String8(hdmiInputDevices[i]->address().c_str());
jiabin5740f082019-08-19 15:08:30 -07005749 std::string name = hdmiInputDevices[i]->getName();
jiabin81772902018-04-02 17:52:27 -07005750 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
5751 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
5752 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005753 name.c_str(),
5754 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005755 if (status != NO_ERROR) {
5756 continue;
5757 }
5758 status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
5759 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
5760 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005761 name.c_str(),
5762 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005763 profileUpdated |= (status == NO_ERROR);
5764 }
5765
jiabin81772902018-04-02 17:52:27 -07005766 if (!profileUpdated) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005767 ALOGW("%s() no audio profiles updated, undoing surround formats change", __func__);
Mikhail Naganov100f0122018-11-29 11:22:16 -08005768 mManualSurroundFormats = std::move(surroundFormatsBackup);
jiabin81772902018-04-02 17:52:27 -07005769 }
5770
5771 return profileUpdated ? NO_ERROR : INVALID_OPERATION;
5772}
5773
Eric Laurent5ada82e2019-08-29 17:53:54 -07005774void AudioPolicyManager::setAppState(audio_port_handle_t portId, app_state_t state)
Svet Ganovf4ddfef2018-01-16 07:37:58 -08005775{
Eric Laurent5ada82e2019-08-29 17:53:54 -07005776 ALOGV("%s(portId:%d, state:%d)", __func__, portId, state);
Eric Laurenta9f86652018-11-28 17:23:11 -08005777 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent5ada82e2019-08-29 17:53:54 -07005778 mInputs.valueAt(i)->setAppState(portId, state);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08005779 }
5780}
5781
jiabin6012f912018-11-02 17:06:30 -07005782bool AudioPolicyManager::isHapticPlaybackSupported()
5783{
5784 for (const auto& hwModule : mHwModules) {
5785 const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
5786 for (const auto &outProfile : outputProfiles) {
5787 struct audio_port audioPort;
5788 outProfile->toAudioPort(&audioPort);
5789 for (size_t i = 0; i < audioPort.num_channel_masks; i++) {
5790 if (audioPort.channel_masks[i] & AUDIO_CHANNEL_HAPTIC_ALL) {
5791 return true;
5792 }
5793 }
5794 }
5795 }
5796 return false;
5797}
5798
Carter Hsu325a8eb2022-01-19 19:56:51 +08005799bool AudioPolicyManager::isUltrasoundSupported()
5800{
5801 bool hasUltrasoundOutput = false;
5802 bool hasUltrasoundInput = false;
5803 for (const auto& hwModule : mHwModules) {
5804 const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
5805 if (!hasUltrasoundOutput) {
5806 for (const auto &outProfile : outputProfiles) {
5807 if (outProfile->getFlags() & AUDIO_OUTPUT_FLAG_ULTRASOUND) {
5808 hasUltrasoundOutput = true;
5809 break;
5810 }
5811 }
5812 }
5813
5814 const InputProfileCollection &inputProfiles = hwModule->getInputProfiles();
5815 if (!hasUltrasoundInput) {
5816 for (const auto &inputProfile : inputProfiles) {
5817 if (inputProfile->getFlags() & AUDIO_INPUT_FLAG_ULTRASOUND) {
5818 hasUltrasoundInput = true;
5819 break;
5820 }
5821 }
5822 }
5823
5824 if (hasUltrasoundOutput && hasUltrasoundInput)
5825 return true;
5826 }
5827 return false;
5828}
5829
Atneya Nair698f5ef2022-12-15 16:15:09 -08005830bool AudioPolicyManager::isHotwordStreamSupported(bool lookbackAudio)
5831{
5832 const auto mask = AUDIO_INPUT_FLAG_HOTWORD_TAP |
5833 (lookbackAudio ? AUDIO_INPUT_FLAG_HW_LOOKBACK : 0);
5834 for (const auto& hwModule : mHwModules) {
5835 const InputProfileCollection &inputProfiles = hwModule->getInputProfiles();
5836 for (const auto &inputProfile : inputProfiles) {
5837 if ((inputProfile->getFlags() & mask) == mask) {
5838 return true;
5839 }
5840 }
5841 }
5842 return false;
5843}
5844
Eric Laurent8340e672019-11-06 11:01:08 -08005845bool AudioPolicyManager::isCallScreenModeSupported()
5846{
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005847 return mConfig->isCallScreenModeSupported();
Eric Laurent8340e672019-11-06 11:01:08 -08005848}
5849
5850
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005851status_t AudioPolicyManager::disconnectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07005852{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005853 ALOGV("%s port Id %d", __FUNCTION__, sourceDesc->portId());
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005854 if (!sourceDesc->isConnected()) {
5855 ALOGV("%s port Id %d already disconnected", __FUNCTION__, sourceDesc->portId());
5856 return NO_ERROR;
5857 }
François Gaffieafd4cea2019-11-18 15:50:22 +01005858 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
5859 if (swOutput != 0) {
5860 status_t status = stopSource(swOutput, sourceDesc);
Eric Laurent733ce942017-12-07 12:18:25 -08005861 if (status == NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005862 swOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08005863 }
jiabinbce0c1d2020-10-05 11:20:18 -07005864 if (releaseOutput(sourceDesc->portId())) {
5865 // The output descriptor is reopened to query dynamic profiles. In that case, there is
5866 // no need to release audio patch here but just return NO_ERROR.
5867 return NO_ERROR;
5868 }
Eric Laurentd60560a2015-04-10 11:31:20 -07005869 } else {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005870 sp<HwAudioOutputDescriptor> hwOutputDesc = sourceDesc->hwOutput().promote();
Eric Laurentd60560a2015-04-10 11:31:20 -07005871 if (hwOutputDesc != 0) {
Eric Laurentd60560a2015-04-10 11:31:20 -07005872 // close Hwoutput and remove from mHwOutputs
5873 } else {
5874 ALOGW("%s source has neither SW nor HW output", __FUNCTION__);
5875 }
5876 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005877 status_t status = releaseAudioPatchInternal(sourceDesc->getPatchHandle(), 0, sourceDesc);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005878 sourceDesc->disconnect();
5879 return status;
Eric Laurentd60560a2015-04-10 11:31:20 -07005880}
5881
François Gaffiec005e562018-11-06 15:04:49 +01005882sp<SourceClientDescriptor> AudioPolicyManager::getSourceForAttributesOnOutput(
5883 audio_io_handle_t output, const audio_attributes_t &attr)
Eric Laurentd60560a2015-04-10 11:31:20 -07005884{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005885 sp<SourceClientDescriptor> source;
Eric Laurentd60560a2015-04-10 11:31:20 -07005886 for (size_t i = 0; i < mAudioSources.size(); i++) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005887 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005888 sp<SwAudioOutputDescriptor> outputDesc = sourceDesc->swOutput().promote();
François Gaffiec005e562018-11-06 15:04:49 +01005889 if (followsSameRouting(attr, sourceDesc->attributes()) &&
5890 outputDesc != 0 && outputDesc->mIoHandle == output) {
Eric Laurentd60560a2015-04-10 11:31:20 -07005891 source = sourceDesc;
5892 break;
5893 }
5894 }
5895 return source;
Eric Laurent554a2772015-04-10 11:29:24 -07005896}
5897
Eric Laurentb4f42a92022-01-17 17:37:31 +01005898bool AudioPolicyManager::canBeSpatializedInt(const audio_attributes_t *attr,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005899 const audio_config_t *config,
Andy Hung9dd1a5b2022-05-10 15:39:39 -07005900 const AudioDeviceTypeAddrVector &devices) const
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005901{
5902 // The caller can have the audio attributes criteria ignored by either passing a null ptr or
5903 // the AUDIO_ATTRIBUTES_INITIALIZER value.
Eric Laurentfa0f6742021-08-17 18:39:44 +02005904 // If attributes are specified, current policy is to only allow spatialization for media
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005905 // and game usages.
Eric Laurent39095982021-08-24 18:29:27 +02005906 if (attr != nullptr && *attr != AUDIO_ATTRIBUTES_INITIALIZER) {
5907 if (attr->usage != AUDIO_USAGE_MEDIA && attr->usage != AUDIO_USAGE_GAME) {
5908 return false;
5909 }
5910 if ((attr->flags & (AUDIO_FLAG_CONTENT_SPATIALIZED | AUDIO_FLAG_NEVER_SPATIALIZE)) != 0) {
5911 return false;
5912 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005913 }
5914
Eric Laurentd332bc82023-08-04 11:45:23 +02005915 // The caller can have the audio config criteria ignored by either passing a null ptr or
5916 // the AUDIO_CONFIG_INITIALIZER value.
5917 // If an audio config is specified, current policy is to only allow spatialization for
5918 // some positional channel masks and PCM format
5919
5920 if (config != nullptr && *config != AUDIO_CONFIG_INITIALIZER) {
5921 if (!audio_is_channel_mask_spatialized(config->channel_mask)) {
5922 return false;
5923 }
5924 if (!audio_is_linear_pcm(config->format)) {
5925 return false;
5926 }
5927 }
5928
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005929 sp<IOProfile> profile =
Eric Laurent39095982021-08-24 18:29:27 +02005930 getSpatializerOutputProfile(config, devices);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005931 if (profile == nullptr) {
5932 return false;
5933 }
5934
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005935 return true;
5936}
5937
5938void AudioPolicyManager::checkVirtualizerClientRoutes() {
5939 std::set<audio_stream_type_t> streamsToInvalidate;
5940 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent39095982021-08-24 18:29:27 +02005941 const sp<SwAudioOutputDescriptor>& desc = mOutputs[i];
5942 for (const sp<TrackClientDescriptor>& client : desc->getClientIterable()) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005943 audio_attributes_t attr = client->attributes();
5944 DeviceVector devices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false);
5945 AudioDeviceTypeAddrVector devicesTypeAddress = devices.toTypeAddrVector();
5946 audio_config_base_t clientConfig = client->config();
5947 audio_config_t config = audio_config_initializer(&clientConfig);
Eric Laurent39095982021-08-24 18:29:27 +02005948 if (desc != mSpatializerOutput
Andy Hung9dd1a5b2022-05-10 15:39:39 -07005949 && canBeSpatializedInt(&attr, &config, devicesTypeAddress)) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005950 streamsToInvalidate.insert(client->stream());
5951 }
5952 }
5953 }
5954
jiabinc44b3462022-12-08 12:52:31 -08005955 invalidateStreams(StreamTypeVector(streamsToInvalidate.begin(), streamsToInvalidate.end()));
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005956}
5957
Eric Laurente191d1b2022-04-15 11:59:25 +02005958
5959bool AudioPolicyManager::isOutputOnlyAvailableRouteToSomeDevice(
5960 const sp<SwAudioOutputDescriptor>& outputDesc) {
5961 if (outputDesc->isDuplicated()) {
5962 return false;
5963 }
5964 DeviceVector devices = outputDesc->supportedDevices();
5965 for (size_t i = 0; i < mOutputs.size(); i++) {
5966 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
5967 if (desc == outputDesc || desc->isDuplicated()) {
5968 continue;
5969 }
5970 DeviceVector sharedDevices = desc->filterSupportedDevices(devices);
5971 if (!sharedDevices.isEmpty()
5972 && (desc->devicesSupportEncodedFormats(sharedDevices.types())
5973 == outputDesc->devicesSupportEncodedFormats(sharedDevices.types()))) {
5974 return false;
5975 }
5976 }
5977 return true;
5978}
5979
5980
Eric Laurentfa0f6742021-08-17 18:39:44 +02005981status_t AudioPolicyManager::getSpatializerOutput(const audio_config_base_t *mixerConfig,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005982 const audio_attributes_t *attr,
5983 audio_io_handle_t *output) {
5984 *output = AUDIO_IO_HANDLE_NONE;
5985
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005986 DeviceVector devices = mEngine->getOutputDevicesForAttributes(*attr, nullptr, false);
5987 AudioDeviceTypeAddrVector devicesTypeAddress = devices.toTypeAddrVector();
5988 audio_config_t *configPtr = nullptr;
5989 audio_config_t config;
5990 if (mixerConfig != nullptr) {
5991 config = audio_config_initializer(mixerConfig);
5992 configPtr = &config;
5993 }
Andy Hung9dd1a5b2022-05-10 15:39:39 -07005994 if (!canBeSpatializedInt(attr, configPtr, devicesTypeAddress)) {
Eric Laurente191d1b2022-04-15 11:59:25 +02005995 ALOGV("%s provided attributes or mixer config cannot be spatialized", __func__);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005996 return BAD_VALUE;
5997 }
5998
5999 sp<IOProfile> profile =
Eric Laurent39095982021-08-24 18:29:27 +02006000 getSpatializerOutputProfile(configPtr, devicesTypeAddress);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006001 if (profile == nullptr) {
Eric Laurente191d1b2022-04-15 11:59:25 +02006002 ALOGV("%s no suitable output profile for provided attributes or mixer config", __func__);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006003 return BAD_VALUE;
6004 }
6005
Eric Laurente191d1b2022-04-15 11:59:25 +02006006 std::vector<sp<SwAudioOutputDescriptor>> spatializerOutputs;
Eric Laurent39095982021-08-24 18:29:27 +02006007 for (size_t i = 0; i < mOutputs.size(); i++) {
6008 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente191d1b2022-04-15 11:59:25 +02006009 if (!desc->isDuplicated()
6010 && (desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0) {
6011 spatializerOutputs.push_back(desc);
6012 ALOGV("%s adding opened spatializer Output %d", __func__, desc->mIoHandle);
Eric Laurent39095982021-08-24 18:29:27 +02006013 }
6014 }
Eric Laurente191d1b2022-04-15 11:59:25 +02006015 mSpatializerOutput.clear();
6016 bool outputsChanged = false;
6017 for (const auto& desc : spatializerOutputs) {
6018 if (desc->mProfile == profile
6019 && (configPtr == nullptr
6020 || configPtr->channel_mask == desc->mMixerChannelMask)) {
6021 mSpatializerOutput = desc;
6022 ALOGV("%s reusing current spatializer output %d", __func__, desc->mIoHandle);
6023 } else {
6024 ALOGV("%s closing spatializerOutput output %d to match channel mask %#x"
6025 " and devices %s", __func__, desc->mIoHandle,
6026 configPtr != nullptr ? configPtr->channel_mask : 0,
6027 devices.toString().c_str());
6028 closeOutput(desc->mIoHandle);
6029 outputsChanged = true;
6030 }
Eric Laurent39095982021-08-24 18:29:27 +02006031 }
6032
Eric Laurente191d1b2022-04-15 11:59:25 +02006033 if (mSpatializerOutput == nullptr) {
Eric Laurentb4f42a92022-01-17 17:37:31 +01006034 sp<SwAudioOutputDescriptor> desc =
6035 openOutputWithProfileAndDevice(profile, devices, mixerConfig);
Eric Laurente191d1b2022-04-15 11:59:25 +02006036 if (desc != nullptr) {
6037 mSpatializerOutput = desc;
6038 outputsChanged = true;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006039 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006040 }
6041
6042 checkVirtualizerClientRoutes();
6043
Eric Laurente191d1b2022-04-15 11:59:25 +02006044 if (outputsChanged) {
6045 mPreviousOutputs = mOutputs;
6046 mpClientInterface->onAudioPortListUpdate();
6047 }
6048
6049 if (mSpatializerOutput == nullptr) {
6050 ALOGV("%s could not open spatializer output with requested config", __func__);
6051 return BAD_VALUE;
6052 }
Eric Laurent39095982021-08-24 18:29:27 +02006053 *output = mSpatializerOutput->mIoHandle;
Eric Laurente191d1b2022-04-15 11:59:25 +02006054 ALOGV("%s returning new spatializer output %d", __func__, *output);
6055 return OK;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006056}
6057
Eric Laurentfa0f6742021-08-17 18:39:44 +02006058status_t AudioPolicyManager::releaseSpatializerOutput(audio_io_handle_t output) {
6059 if (mSpatializerOutput == nullptr) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006060 return INVALID_OPERATION;
6061 }
Eric Laurentfa0f6742021-08-17 18:39:44 +02006062 if (mSpatializerOutput->mIoHandle != output) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006063 return BAD_VALUE;
6064 }
Eric Laurent39095982021-08-24 18:29:27 +02006065
Eric Laurente191d1b2022-04-15 11:59:25 +02006066 if (!isOutputOnlyAvailableRouteToSomeDevice(mSpatializerOutput)) {
6067 ALOGV("%s closing spatializer output %d", __func__, mSpatializerOutput->mIoHandle);
6068 closeOutput(mSpatializerOutput->mIoHandle);
6069 //from now on mSpatializerOutput is null
6070 checkVirtualizerClientRoutes();
6071 }
Eric Laurent39095982021-08-24 18:29:27 +02006072
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006073 return NO_ERROR;
6074}
6075
Eric Laurente552edb2014-03-10 17:42:56 -07006076// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07006077// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07006078// ----------------------------------------------------------------------------
Eric Laurent6a94d692014-05-20 11:18:06 -07006079uint32_t AudioPolicyManager::nextAudioPortGeneration()
6080{
Mikhail Naganov2773dd72017-12-08 10:12:11 -08006081 return mAudioPortGeneration++;
Eric Laurent6a94d692014-05-20 11:18:06 -07006082}
6083
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006084AudioPolicyManager::AudioPolicyManager(const sp<const AudioPolicyConfig>& config,
Mikhail Naganovf1b6d972023-05-02 13:56:01 -07006085 EngineInstance&& engine,
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006086 AudioPolicyClientInterface *clientInterface)
Eric Laurente552edb2014-03-10 17:42:56 -07006087 :
Andy Hung4ef19fa2018-05-15 19:35:29 -07006088 mUidCached(AID_AUDIOSERVER), // no need to call getuid(), there's only one of us running.
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006089 mConfig(config),
Mikhail Naganovf1b6d972023-05-02 13:56:01 -07006090 mEngine(std::move(engine)),
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006091 mpClientInterface(clientInterface),
Eric Laurente552edb2014-03-10 17:42:56 -07006092 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
Eric Laurent3a4311c2014-03-17 12:00:47 -07006093 mA2dpSuspended(false),
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006094 mAudioPortGeneration(1),
6095 mBeaconMuteRefCount(0),
6096 mBeaconPlayingRefCount(0),
Eric Laurent9459fb02015-08-12 18:36:32 -07006097 mBeaconMuted(false),
Andy Hung2ddee192015-12-18 17:34:44 -08006098 mTtsOutputAvailable(false),
Eric Laurent36829f92017-04-07 19:04:42 -07006099 mMasterMono(false),
Eric Laurent4eb58f12018-12-07 16:41:02 -08006100 mMusicEffectOutput(AUDIO_IO_HANDLE_NONE)
Eric Laurente552edb2014-03-10 17:42:56 -07006101{
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006102}
François Gaffied1ab2bd2015-12-02 18:20:06 +01006103
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006104status_t AudioPolicyManager::initialize() {
Mikhail Naganovf1b6d972023-05-02 13:56:01 -07006105 if (mEngine == nullptr) {
6106 return NO_INIT;
François Gaffie2110e042015-03-24 08:41:51 +01006107 }
6108 mEngine->setObserver(this);
6109 status_t status = mEngine->initCheck();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006110 if (status != NO_ERROR) {
6111 LOG_FATAL("Policy engine not initialized(err=%d)", status);
6112 return status;
6113 }
François Gaffie2110e042015-03-24 08:41:51 +01006114
jiabin29230182023-04-04 21:02:36 +00006115 // The actual device selection cache will be updated when calling `updateDevicesAndOutputs`
6116 // at the end of this function.
6117 mEngine->initializeDeviceSelectionCache();
Eric Laurent1d69c872021-01-11 18:53:01 +01006118 mCommunnicationStrategy = mEngine->getProductStrategyForAttributes(
6119 mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL));
6120
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006121 // after parsing the config, mConfig contain all known devices;
Eric Laurente552edb2014-03-10 17:42:56 -07006122 // open all output streams needed to access attached devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006123 onNewAudioModulesAvailableInt(nullptr /*newDevices*/);
François Gaffie11d30102018-11-02 16:09:09 +01006124
Eric Laurent3a4311c2014-03-17 12:00:47 -07006125 // make sure default device is reachable
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006126 if (const auto defaultOutputDevice = mConfig->getDefaultOutputDevice();
6127 defaultOutputDevice == nullptr ||
6128 !mAvailableOutputDevices.contains(defaultOutputDevice)) {
6129 ALOGE_IF(defaultOutputDevice != nullptr, "Default device %s is unreachable",
6130 defaultOutputDevice->toString().c_str());
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006131 status = NO_INIT;
Eric Laurent3a4311c2014-03-17 12:00:47 -07006132 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02006133 ALOGW_IF(mPrimaryOutput == nullptr, "The policy configuration does not declare a primary output");
Eric Laurente552edb2014-03-10 17:42:56 -07006134
Tomoharu Kasahara71c90912018-10-31 09:10:12 +09006135 // Silence ALOGV statements
6136 property_set("log.tag." LOG_TAG, "D");
6137
Eric Laurente552edb2014-03-10 17:42:56 -07006138 updateDevicesAndOutputs();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006139 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07006140}
6141
Eric Laurente0720872014-03-11 09:30:41 -07006142AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07006143{
Eric Laurente552edb2014-03-10 17:42:56 -07006144 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08006145 mOutputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07006146 }
6147 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08006148 mInputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07006149 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07006150 mAvailableOutputDevices.clear();
6151 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07006152 mOutputs.clear();
6153 mInputs.clear();
6154 mHwModules.clear();
Mikhail Naganov100f0122018-11-29 11:22:16 -08006155 mManualSurroundFormats.clear();
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006156 mConfig.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07006157}
6158
Eric Laurente0720872014-03-11 09:30:41 -07006159status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07006160{
Eric Laurent87ffa392015-05-22 10:32:38 -07006161 return hasPrimaryOutput() ? NO_ERROR : NO_INIT;
Eric Laurente552edb2014-03-10 17:42:56 -07006162}
6163
Eric Laurente552edb2014-03-10 17:42:56 -07006164// ---
6165
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006166void AudioPolicyManager::onNewAudioModulesAvailable()
6167{
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006168 DeviceVector newDevices;
6169 onNewAudioModulesAvailableInt(&newDevices);
6170 if (!newDevices.empty()) {
6171 nextAudioPortGeneration();
6172 mpClientInterface->onAudioPortListUpdate();
6173 }
6174}
6175
6176void AudioPolicyManager::onNewAudioModulesAvailableInt(DeviceVector *newDevices)
6177{
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006178 for (const auto& hwModule : mConfig->getHwModules()) {
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006179 if (std::find(mHwModules.begin(), mHwModules.end(), hwModule) != mHwModules.end()) {
6180 continue;
6181 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006182 if (hwModule->getHandle() == AUDIO_MODULE_HANDLE_NONE) {
Mikhail Naganovffd97712023-05-03 17:45:36 -07006183 if (audio_module_handle_t handle = mpClientInterface->loadHwModule(hwModule->getName());
6184 handle != AUDIO_MODULE_HANDLE_NONE) {
6185 hwModule->setHandle(handle);
6186 } else {
6187 ALOGW("could not load HW module %s", hwModule->getName());
6188 continue;
6189 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006190 }
6191 mHwModules.push_back(hwModule);
Dean Wheatley12a87132021-04-16 10:08:49 +10006192 // open all output streams needed to access attached devices.
6193 // direct outputs are closed immediately after checking the availability of attached devices
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006194 // This also validates mAvailableOutputDevices list
6195 for (const auto& outProfile : hwModule->getOutputProfiles()) {
6196 if (!outProfile->canOpenNewIo()) {
6197 ALOGE("Invalid Output profile max open count %u for profile %s",
6198 outProfile->maxOpenCount, outProfile->getTagName().c_str());
6199 continue;
6200 }
6201 if (!outProfile->hasSupportedDevices()) {
6202 ALOGW("Output profile contains no device on module %s", hwModule->getName());
6203 continue;
6204 }
Carter Hsu1a3364a2022-01-21 15:32:56 +08006205 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_TTS) != 0 ||
6206 (outProfile->getFlags() & AUDIO_OUTPUT_FLAG_ULTRASOUND) != 0) {
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006207 mTtsOutputAvailable = true;
6208 }
6209
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006210 const DeviceVector &supportedDevices = outProfile->getSupportedDevices();
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006211 DeviceVector availProfileDevices = supportedDevices.filter(mConfig->getOutputDevices());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006212 sp<DeviceDescriptor> supportedDevice = 0;
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006213 if (supportedDevices.contains(mConfig->getDefaultOutputDevice())) {
6214 supportedDevice = mConfig->getDefaultOutputDevice();
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006215 } else {
6216 // choose first device present in profile's SupportedDevices also part of
6217 // mAvailableOutputDevices.
6218 if (availProfileDevices.isEmpty()) {
6219 continue;
6220 }
6221 supportedDevice = availProfileDevices.itemAt(0);
6222 }
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006223 if (!mConfig->getOutputDevices().contains(supportedDevice)) {
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006224 continue;
6225 }
6226 sp<SwAudioOutputDescriptor> outputDesc = new SwAudioOutputDescriptor(outProfile,
6227 mpClientInterface);
6228 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentf1f22e72021-07-13 14:04:14 +02006229 status_t status = outputDesc->open(nullptr /* halConfig */, nullptr /* mixerConfig */,
6230 DeviceVector(supportedDevice),
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006231 AUDIO_STREAM_DEFAULT,
6232 AUDIO_OUTPUT_FLAG_NONE, &output);
6233 if (status != NO_ERROR) {
6234 ALOGW("Cannot open output stream for devices %s on hw module %s",
6235 supportedDevice->toString().c_str(), hwModule->getName());
6236 continue;
6237 }
6238 for (const auto &device : availProfileDevices) {
6239 // give a valid ID to an attached device once confirmed it is reachable
6240 if (!device->isAttached()) {
6241 device->attach(hwModule);
6242 mAvailableOutputDevices.add(device);
jiabin1c4794b2020-05-05 10:08:05 -07006243 device->setEncapsulationInfoFromHal(mpClientInterface);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006244 if (newDevices) newDevices->add(device);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006245 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
6246 }
6247 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02006248 if (mPrimaryOutput == nullptr &&
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006249 outProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
6250 mPrimaryOutput = outputDesc;
6251 }
Eric Laurent39095982021-08-24 18:29:27 +02006252 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
Eric Laurentc529cf62020-04-17 18:19:10 -07006253 outputDesc->close();
6254 } else {
6255 addOutput(output, outputDesc);
6256 setOutputDevices(outputDesc,
6257 DeviceVector(supportedDevice),
6258 true,
6259 0,
6260 NULL);
6261 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006262 }
6263 // open input streams needed to access attached devices to validate
6264 // mAvailableInputDevices list
6265 for (const auto& inProfile : hwModule->getInputProfiles()) {
6266 if (!inProfile->canOpenNewIo()) {
6267 ALOGE("Invalid Input profile max open count %u for profile %s",
6268 inProfile->maxOpenCount, inProfile->getTagName().c_str());
6269 continue;
6270 }
6271 if (!inProfile->hasSupportedDevices()) {
6272 ALOGW("Input profile contains no device on module %s", hwModule->getName());
6273 continue;
6274 }
6275 // chose first device present in profile's SupportedDevices also part of
6276 // available input devices
6277 const DeviceVector &supportedDevices = inProfile->getSupportedDevices();
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006278 DeviceVector availProfileDevices = supportedDevices.filter(mConfig->getInputDevices());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006279 if (availProfileDevices.isEmpty()) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01006280 ALOGV("%s: Input device list is empty! for profile %s",
6281 __func__, inProfile->getTagName().c_str());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006282 continue;
6283 }
6284 sp<AudioInputDescriptor> inputDesc =
6285 new AudioInputDescriptor(inProfile, mpClientInterface);
6286
6287 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
6288 status_t status = inputDesc->open(nullptr,
6289 availProfileDevices.itemAt(0),
6290 AUDIO_SOURCE_MIC,
6291 AUDIO_INPUT_FLAG_NONE,
6292 &input);
6293 if (status != NO_ERROR) {
6294 ALOGW("Cannot open input stream for device %s on hw module %s",
6295 availProfileDevices.toString().c_str(),
6296 hwModule->getName());
6297 continue;
6298 }
6299 for (const auto &device : availProfileDevices) {
6300 // give a valid ID to an attached device once confirmed it is reachable
6301 if (!device->isAttached()) {
6302 device->attach(hwModule);
6303 device->importAudioPortAndPickAudioProfile(inProfile, true);
6304 mAvailableInputDevices.add(device);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006305 if (newDevices) newDevices->add(device);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006306 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
6307 }
6308 }
6309 inputDesc->close();
6310 }
6311 }
Eric Laurente191d1b2022-04-15 11:59:25 +02006312
6313 // Check if spatializer outputs can be closed until used.
6314 // mOutputs vector never contains duplicated outputs at this point.
6315 std::vector<audio_io_handle_t> outputsClosed;
6316 for (size_t i = 0; i < mOutputs.size(); i++) {
6317 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
6318 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0
6319 && !isOutputOnlyAvailableRouteToSomeDevice(desc)) {
6320 outputsClosed.push_back(desc->mIoHandle);
6321 desc->close();
6322 }
6323 }
6324 for (auto output : outputsClosed) {
6325 removeOutput(output);
6326 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006327}
6328
Eric Laurent98e38192018-02-15 18:31:53 -08006329void AudioPolicyManager::addOutput(audio_io_handle_t output,
6330 const sp<SwAudioOutputDescriptor>& outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07006331{
Eric Laurent1c333e22014-05-20 10:48:17 -07006332 mOutputs.add(output, outputDesc);
jiabin9a3361e2019-10-01 09:38:30 -07006333 applyStreamVolumes(outputDesc, DeviceTypeSet(), 0 /* delayMs */, true /* force */);
Andy Hung2ddee192015-12-18 17:34:44 -08006334 updateMono(output); // update mono status when adding to output list
Eric Laurent36829f92017-04-07 19:04:42 -07006335 selectOutputForMusicEffects();
Eric Laurent6a94d692014-05-20 11:18:06 -07006336 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07006337}
6338
François Gaffie53615e22015-03-19 09:24:12 +01006339void AudioPolicyManager::removeOutput(audio_io_handle_t output)
6340{
Francois Gaffiebce7cd42020-10-14 16:13:20 +02006341 if (mPrimaryOutput != 0 && mPrimaryOutput == mOutputs.valueFor(output)) {
6342 ALOGV("%s: removing primary output", __func__);
6343 mPrimaryOutput = nullptr;
6344 }
François Gaffie53615e22015-03-19 09:24:12 +01006345 mOutputs.removeItem(output);
Eric Laurent36829f92017-04-07 19:04:42 -07006346 selectOutputForMusicEffects();
François Gaffie53615e22015-03-19 09:24:12 +01006347}
6348
Eric Laurent98e38192018-02-15 18:31:53 -08006349void AudioPolicyManager::addInput(audio_io_handle_t input,
6350 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07006351{
Eric Laurent1c333e22014-05-20 10:48:17 -07006352 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07006353 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07006354}
Eric Laurente552edb2014-03-10 17:42:56 -07006355
François Gaffie11d30102018-11-02 16:09:09 +01006356status_t AudioPolicyManager::checkOutputsForDevice(const sp<DeviceDescriptor>& device,
François Gaffie53615e22015-03-19 09:24:12 +01006357 audio_policy_dev_state_t state,
François Gaffie11d30102018-11-02 16:09:09 +01006358 SortedVector<audio_io_handle_t>& outputs)
Eric Laurente552edb2014-03-10 17:42:56 -07006359{
François Gaffie11d30102018-11-02 16:09:09 +01006360 audio_devices_t deviceType = device->type();
jiabince9f20e2019-09-12 16:29:15 -07006361 const String8 &address = String8(device->address().c_str());
Eric Laurentc75307b2015-03-17 15:29:32 -07006362 sp<SwAudioOutputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07006363
François Gaffie11d30102018-11-02 16:09:09 +01006364 if (audio_device_is_digital(deviceType)) {
Eric Laurentcc750d32015-06-25 11:48:20 -07006365 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01006366 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07006367 }
Eric Laurente552edb2014-03-10 17:42:56 -07006368
Eric Laurent3b73df72014-03-11 09:06:29 -07006369 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
jiabinb4fed192020-09-22 14:45:40 -07006370 // first call getAudioPort to get the supported attributes from the HAL
6371 struct audio_port_v7 port = {};
6372 device->toAudioPort(&port);
6373 status_t status = mpClientInterface->getAudioPort(&port);
6374 if (status == NO_ERROR) {
6375 device->importAudioPort(port);
6376 }
6377
6378 // then list already open outputs that can be routed to this device
Eric Laurente552edb2014-03-10 17:42:56 -07006379 for (size_t i = 0; i < mOutputs.size(); i++) {
6380 desc = mOutputs.valueAt(i);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006381 if (!desc->isDuplicated() && desc->supportsDevice(device)
jiabin9a3361e2019-10-01 09:38:30 -07006382 && desc->devicesSupportEncodedFormats({deviceType})) {
François Gaffie11d30102018-11-02 16:09:09 +01006383 ALOGV("checkOutputsForDevice(): adding opened output %d on device %s",
6384 mOutputs.keyAt(i), device->toString().c_str());
6385 outputs.add(mOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07006386 }
6387 }
6388 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07006389 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006390 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006391 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
6392 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
François Gaffie11d30102018-11-02 16:09:09 +01006393 if (profile->supportsDevice(device)) {
6394 profiles.add(profile);
6395 ALOGV("checkOutputsForDevice(): adding profile %zu from module %s",
6396 j, hwModule->getName());
Eric Laurente552edb2014-03-10 17:42:56 -07006397 }
6398 }
6399 }
6400
Eric Laurent7b279bb2015-12-14 10:18:23 -08006401 ALOGV(" found %zu profiles, %zu outputs", profiles.size(), outputs.size());
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006402
Eric Laurente552edb2014-03-10 17:42:56 -07006403 if (profiles.isEmpty() && outputs.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006404 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07006405 return BAD_VALUE;
6406 }
6407
6408 // open outputs for matching profiles if needed. Direct outputs are also opened to
6409 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
6410 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07006411 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07006412
6413 // nothing to do if one output is already opened for this profile
6414 size_t j;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006415 for (j = 0; j < outputs.size(); j++) {
6416 desc = mOutputs.valueFor(outputs.itemAt(j));
Eric Laurente552edb2014-03-10 17:42:56 -07006417 if (!desc->isDuplicated() && desc->mProfile == profile) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07006418 // matching profile: save the sample rates, format and channel masks supported
6419 // by the profile in our device descriptor
François Gaffie11d30102018-11-02 16:09:09 +01006420 if (audio_device_is_digital(deviceType)) {
jiabin4ef93452019-09-10 14:29:54 -07006421 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006422 }
Eric Laurente552edb2014-03-10 17:42:56 -07006423 break;
6424 }
6425 }
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006426 if (j != outputs.size()) {
Eric Laurente552edb2014-03-10 17:42:56 -07006427 continue;
6428 }
6429
Eric Laurent3974e3b2017-12-07 17:58:43 -08006430 if (!profile->canOpenNewIo()) {
6431 ALOGW("Max Output number %u already opened for this profile %s",
6432 profile->maxOpenCount, profile->getTagName().c_str());
6433 continue;
6434 }
6435
Eric Laurent83efe1c2017-07-09 16:51:08 -07006436 ALOGV("opening output for device %08x with params %s profile %p name %s",
jiabin5740f082019-08-19 15:08:30 -07006437 deviceType, address.string(), profile.get(), profile->getName().c_str());
jiabinbce0c1d2020-10-05 11:20:18 -07006438 desc = openOutputWithProfileAndDevice(profile, DeviceVector(device));
6439 audio_io_handle_t output = desc == nullptr ? AUDIO_IO_HANDLE_NONE : desc->mIoHandle;
Eric Laurentcf2c0212014-07-25 16:20:43 -07006440 if (output == AUDIO_IO_HANDLE_NONE) {
François Gaffie11d30102018-11-02 16:09:09 +01006441 ALOGW("checkOutputsForDevice() could not open output for device %x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07006442 profiles.removeAt(profile_index);
6443 profile_index--;
6444 } else {
6445 outputs.add(output);
Paul McLean9080a4c2015-06-18 08:24:02 -07006446 // Load digital format info only for digital devices
François Gaffie11d30102018-11-02 16:09:09 +01006447 if (audio_device_is_digital(deviceType)) {
jiabinbce0c1d2020-10-05 11:20:18 -07006448 // TODO: when getAudioPort is ready, it may not be needed to import the audio
6449 // port but just pick audio profile
jiabin4ef93452019-09-10 14:29:54 -07006450 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006451 }
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07006452
François Gaffie11d30102018-11-02 16:09:09 +01006453 if (device_distinguishes_on_address(deviceType)) {
6454 ALOGV("checkOutputsForDevice(): setOutputDevices %s",
6455 device->toString().c_str());
6456 setOutputDevices(desc, DeviceVector(device), true/*force*/, 0/*delay*/,
6457 NULL/*patch handle*/);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006458 }
Eric Laurente552edb2014-03-10 17:42:56 -07006459 ALOGV("checkOutputsForDevice(): adding output %d", output);
6460 }
6461 }
6462
6463 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006464 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07006465 return BAD_VALUE;
6466 }
Eric Laurentd4692962014-05-05 18:13:44 -07006467 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07006468 // check if one opened output is not needed any more after disconnecting one device
6469 for (size_t i = 0; i < mOutputs.size(); i++) {
6470 desc = mOutputs.valueAt(i);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006471 if (!desc->isDuplicated()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08006472 // exact match on device
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006473 if (device_distinguishes_on_address(deviceType) && desc->supportsDevice(device)
Francois Gaffiec7d4c222021-12-02 11:12:52 +01006474 && desc->containsSingleDeviceSupportingEncodedFormats(device)) {
François Gaffie11d30102018-11-02 16:09:09 +01006475 outputs.add(mOutputs.keyAt(i));
Francois Gaffie716e1432019-01-14 16:58:59 +01006476 } else if (!mAvailableOutputDevices.containsAtLeastOne(desc->supportedDevices())) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006477 ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
6478 mOutputs.keyAt(i));
6479 outputs.add(mOutputs.keyAt(i));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006480 }
Eric Laurente552edb2014-03-10 17:42:56 -07006481 }
6482 }
Eric Laurentd4692962014-05-05 18:13:44 -07006483 // Clear any profiles associated with the disconnected device.
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006484 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006485 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
6486 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
jiabinbce0c1d2020-10-05 11:20:18 -07006487 if (!profile->supportsDevice(device)) {
6488 continue;
6489 }
6490 ALOGV("checkOutputsForDevice(): "
6491 "clearing direct output profile %zu on module %s",
6492 j, hwModule->getName());
6493 profile->clearAudioProfiles();
6494 if (!profile->hasDynamicAudioProfile()) {
6495 continue;
6496 }
6497 // When a device is disconnected, if there is an IOProfile that contains dynamic
6498 // profiles and supports the disconnected device, call getAudioPort to repopulate
6499 // the capabilities of the devices that is supported by the IOProfile.
6500 for (const auto& supportedDevice : profile->getSupportedDevices()) {
6501 if (supportedDevice == device ||
6502 !mAvailableOutputDevices.contains(supportedDevice)) {
6503 continue;
6504 }
6505 struct audio_port_v7 port;
6506 supportedDevice->toAudioPort(&port);
6507 status_t status = mpClientInterface->getAudioPort(&port);
6508 if (status == NO_ERROR) {
6509 supportedDevice->importAudioPort(port);
6510 }
Eric Laurente552edb2014-03-10 17:42:56 -07006511 }
6512 }
6513 }
6514 }
6515 return NO_ERROR;
6516}
6517
François Gaffie11d30102018-11-02 16:09:09 +01006518status_t AudioPolicyManager::checkInputsForDevice(const sp<DeviceDescriptor>& device,
Eric Laurent0dd51852019-04-19 18:18:58 -07006519 audio_policy_dev_state_t state)
Eric Laurentd4692962014-05-05 18:13:44 -07006520{
Eric Laurent1f2f2232014-06-02 12:01:23 -07006521 sp<AudioInputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07006522
François Gaffie11d30102018-11-02 16:09:09 +01006523 if (audio_device_is_digital(device->type())) {
Eric Laurentcc750d32015-06-25 11:48:20 -07006524 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01006525 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07006526 }
6527
Eric Laurentd4692962014-05-05 18:13:44 -07006528 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
jiabinbf5f4262023-04-12 21:48:34 +00006529 // first call getAudioPort to get the supported attributes from the HAL
6530 struct audio_port_v7 port = {};
6531 device->toAudioPort(&port);
6532 status_t status = mpClientInterface->getAudioPort(&port);
6533 if (status == NO_ERROR) {
6534 device->importAudioPort(port);
6535 }
6536
Eric Laurent0dd51852019-04-19 18:18:58 -07006537 // look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07006538 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006539 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07006540 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006541 profile_index < hwModule->getInputProfiles().size();
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006542 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006543 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Eric Laurent275e8e92014-11-30 15:14:47 -08006544
François Gaffie11d30102018-11-02 16:09:09 +01006545 if (profile->supportsDevice(device)) {
6546 profiles.add(profile);
6547 ALOGV("checkInputsForDevice(): adding profile %zu from module %s",
6548 profile_index, hwModule->getName());
Eric Laurentd4692962014-05-05 18:13:44 -07006549 }
6550 }
6551 }
6552
Eric Laurent0dd51852019-04-19 18:18:58 -07006553 if (profiles.isEmpty()) {
6554 ALOGW("%s: No input profile available for device %s",
6555 __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07006556 return BAD_VALUE;
6557 }
6558
6559 // open inputs for matching profiles if needed. Direct inputs are also opened to
6560 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
6561 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
6562
Eric Laurent1c333e22014-05-20 10:48:17 -07006563 sp<IOProfile> profile = profiles[profile_index];
Eric Laurent3974e3b2017-12-07 17:58:43 -08006564
Eric Laurentd4692962014-05-05 18:13:44 -07006565 // nothing to do if one input is already opened for this profile
6566 size_t input_index;
6567 for (input_index = 0; input_index < mInputs.size(); input_index++) {
6568 desc = mInputs.valueAt(input_index);
6569 if (desc->mProfile == profile) {
François Gaffie11d30102018-11-02 16:09:09 +01006570 if (audio_device_is_digital(device->type())) {
jiabin4ef93452019-09-10 14:29:54 -07006571 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006572 }
Eric Laurentd4692962014-05-05 18:13:44 -07006573 break;
6574 }
6575 }
6576 if (input_index != mInputs.size()) {
6577 continue;
6578 }
6579
Eric Laurent3974e3b2017-12-07 17:58:43 -08006580 if (!profile->canOpenNewIo()) {
6581 ALOGW("Max Input number %u already opened for this profile %s",
6582 profile->maxOpenCount, profile->getTagName().c_str());
6583 continue;
6584 }
6585
Eric Laurentfe231122017-11-17 17:48:06 -08006586 desc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentcf2c0212014-07-25 16:20:43 -07006587 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
jiabinbf5f4262023-04-12 21:48:34 +00006588 status = desc->open(nullptr, device, AUDIO_SOURCE_MIC, AUDIO_INPUT_FLAG_NONE, &input);
Eric Laurentd4692962014-05-05 18:13:44 -07006589
Eric Laurentcf2c0212014-07-25 16:20:43 -07006590 if (status == NO_ERROR) {
jiabince9f20e2019-09-12 16:29:15 -07006591 const String8& address = String8(device->address().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07006592 if (!address.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006593 char *param = audio_device_address_to_parameter(device->type(), address);
Eric Laurentcf2c0212014-07-25 16:20:43 -07006594 mpClientInterface->setParameters(input, String8(param));
6595 free(param);
Eric Laurentd4692962014-05-05 18:13:44 -07006596 }
François Gaffie11d30102018-11-02 16:09:09 +01006597 updateAudioProfiles(device, input, profile->getAudioProfiles());
François Gaffie112b0af2015-11-19 16:13:25 +01006598 if (!profile->hasValidAudioProfile()) {
Eric Laurentd4692962014-05-05 18:13:44 -07006599 ALOGW("checkInputsForDevice() direct input missing param");
Eric Laurentfe231122017-11-17 17:48:06 -08006600 desc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07006601 input = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07006602 }
6603
Eric Laurent0dd51852019-04-19 18:18:58 -07006604 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07006605 addInput(input, desc);
6606 }
6607 } // endif input != 0
6608
Eric Laurentcf2c0212014-07-25 16:20:43 -07006609 if (input == AUDIO_IO_HANDLE_NONE) {
Pattydd807582021-11-04 21:01:03 +08006610 ALOGW("%s could not open input for device %s", __func__,
François Gaffie11d30102018-11-02 16:09:09 +01006611 device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07006612 profiles.removeAt(profile_index);
6613 profile_index--;
6614 } else {
François Gaffie11d30102018-11-02 16:09:09 +01006615 if (audio_device_is_digital(device->type())) {
jiabin4ef93452019-09-10 14:29:54 -07006616 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006617 }
Eric Laurentd4692962014-05-05 18:13:44 -07006618 ALOGV("checkInputsForDevice(): adding input %d", input);
6619 }
6620 } // end scan profiles
6621
6622 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006623 ALOGW("%s: No input available for device %s", __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07006624 return BAD_VALUE;
6625 }
6626 } else {
6627 // Disconnect
Eric Laurentd4692962014-05-05 18:13:44 -07006628 // Clear any profiles associated with the disconnected device.
Mikhail Naganovd4120142017-12-06 15:49:22 -08006629 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07006630 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006631 profile_index < hwModule->getInputProfiles().size();
Eric Laurentd4692962014-05-05 18:13:44 -07006632 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006633 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Francois Gaffie716e1432019-01-14 16:58:59 +01006634 if (profile->supportsDevice(device)) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08006635 ALOGV("checkInputsForDevice(): clearing direct input profile %zu on module %s",
6636 profile_index, hwModule->getName());
François Gaffie112b0af2015-11-19 16:13:25 +01006637 profile->clearAudioProfiles();
Eric Laurentd4692962014-05-05 18:13:44 -07006638 }
6639 }
6640 }
6641 } // end disconnect
6642
6643 return NO_ERROR;
6644}
6645
6646
Eric Laurente0720872014-03-11 09:30:41 -07006647void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07006648{
6649 ALOGV("closeOutput(%d)", output);
6650
François Gaffie1c878552018-11-22 16:53:21 +01006651 sp<SwAudioOutputDescriptor> closingOutput = mOutputs.valueFor(output);
6652 if (closingOutput == NULL) {
Eric Laurente552edb2014-03-10 17:42:56 -07006653 ALOGW("closeOutput() unknown output %d", output);
6654 return;
6655 }
Mikhail Naganov32ebca32019-03-22 15:42:52 -07006656 const bool closingOutputWasActive = closingOutput->isActive();
François Gaffie1c878552018-11-22 16:53:21 +01006657 mPolicyMixes.closeOutput(closingOutput);
Eric Laurent275e8e92014-11-30 15:14:47 -08006658
Eric Laurente552edb2014-03-10 17:42:56 -07006659 // look for duplicated outputs connected to the output being removed.
6660 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie1c878552018-11-22 16:53:21 +01006661 sp<SwAudioOutputDescriptor> dupOutput = mOutputs.valueAt(i);
6662 if (dupOutput->isDuplicated() &&
6663 (dupOutput->mOutput1 == closingOutput || dupOutput->mOutput2 == closingOutput)) {
6664 sp<SwAudioOutputDescriptor> remainingOutput =
6665 dupOutput->mOutput1 == closingOutput ? dupOutput->mOutput2 : dupOutput->mOutput1;
Eric Laurente552edb2014-03-10 17:42:56 -07006666 // As all active tracks on duplicated output will be deleted,
6667 // and as they were also referenced on the other output, the reference
6668 // count for their stream type must be adjusted accordingly on
6669 // the other output.
François Gaffie1c878552018-11-22 16:53:21 +01006670 const bool wasActive = remainingOutput->isActive();
6671 // Note: no-op on the closing output where all clients has already been set inactive
6672 dupOutput->setAllClientsInactive();
Eric Laurent733ce942017-12-07 12:18:25 -08006673 // stop() will be a no op if the output is still active but is needed in case all
6674 // active streams refcounts where cleared above
6675 if (wasActive) {
François Gaffie1c878552018-11-22 16:53:21 +01006676 remainingOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08006677 }
Eric Laurente552edb2014-03-10 17:42:56 -07006678 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
6679 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
6680
6681 mpClientInterface->closeOutput(duplicatedOutput);
François Gaffie53615e22015-03-19 09:24:12 +01006682 removeOutput(duplicatedOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07006683 }
6684 }
6685
Eric Laurent05b90f82014-08-27 15:32:29 -07006686 nextAudioPortGeneration();
6687
François Gaffie1c878552018-11-22 16:53:21 +01006688 ssize_t index = mAudioPatches.indexOfKey(closingOutput->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07006689 if (index >= 0) {
6690 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006691 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
6692 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07006693 mAudioPatches.removeItemsAt(index);
6694 mpClientInterface->onAudioPatchListUpdate();
6695 }
6696
Mikhail Naganov32ebca32019-03-22 15:42:52 -07006697 if (closingOutputWasActive) {
6698 closingOutput->stop();
6699 }
François Gaffie1c878552018-11-22 16:53:21 +01006700 closingOutput->close();
Eric Laurente552edb2014-03-10 17:42:56 -07006701
François Gaffie53615e22015-03-19 09:24:12 +01006702 removeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07006703 mPreviousOutputs = mOutputs;
Eric Laurentb4f42a92022-01-17 17:37:31 +01006704 if (closingOutput == mSpatializerOutput) {
6705 mSpatializerOutput.clear();
6706 }
Dean Wheatley3023b382018-08-09 07:42:40 +10006707
6708 // MSD patches may have been released to support a non-MSD direct output. Reset MSD patch if
6709 // no direct outputs are open.
François Gaffie11d30102018-11-02 16:09:09 +01006710 if (!getMsdAudioOutDevices().isEmpty()) {
Dean Wheatley3023b382018-08-09 07:42:40 +10006711 bool directOutputOpen = false;
6712 for (size_t i = 0; i < mOutputs.size(); i++) {
6713 if (mOutputs[i]->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
6714 directOutputOpen = true;
6715 break;
6716 }
6717 }
6718 if (!directOutputOpen) {
Michael Chan6fb34492020-12-08 15:44:49 +11006719 ALOGV("no direct outputs open, reset MSD patches");
6720 // TODO: The MSD patches to be established here may differ to current MSD patches due to
6721 // how output devices for patching are resolved. Avoid by caching and reusing the
6722 // arguments to mEngine->getOutputDevicesForAttributes() when resolving which output
6723 // devices to patch to. This may be complicated by the fact that devices may become
6724 // unavailable.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11006725 setMsdOutputPatches();
Dean Wheatley3023b382018-08-09 07:42:40 +10006726 }
6727 }
Eric Laurent05b90f82014-08-27 15:32:29 -07006728}
6729
6730void AudioPolicyManager::closeInput(audio_io_handle_t input)
6731{
6732 ALOGV("closeInput(%d)", input);
6733
6734 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
6735 if (inputDesc == NULL) {
6736 ALOGW("closeInput() unknown input %d", input);
6737 return;
6738 }
6739
Eric Laurent6a94d692014-05-20 11:18:06 -07006740 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07006741
François Gaffie11d30102018-11-02 16:09:09 +01006742 sp<DeviceDescriptor> device = inputDesc->getDevice();
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08006743 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07006744 if (index >= 0) {
6745 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006746 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
6747 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07006748 mAudioPatches.removeItemsAt(index);
6749 mpClientInterface->onAudioPatchListUpdate();
6750 }
6751
Eric Laurentfe231122017-11-17 17:48:06 -08006752 inputDesc->close();
Eric Laurent05b90f82014-08-27 15:32:29 -07006753 mInputs.removeItem(input);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07006754
François Gaffie11d30102018-11-02 16:09:09 +01006755 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
6756 if (primaryInputDevices.contains(device) &&
Haynes Mathew George1d539d92018-03-16 11:40:49 -07006757 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07006758 mpClientInterface->setSoundTriggerCaptureState(false);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07006759 }
Eric Laurente552edb2014-03-10 17:42:56 -07006760}
6761
François Gaffie11d30102018-11-02 16:09:09 +01006762SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevices(
6763 const DeviceVector &devices,
6764 const SwAudioOutputCollection& openOutputs)
Eric Laurente552edb2014-03-10 17:42:56 -07006765{
6766 SortedVector<audio_io_handle_t> outputs;
6767
François Gaffie11d30102018-11-02 16:09:09 +01006768 ALOGVV("%s() devices %s", __func__, devices.toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07006769 for (size_t i = 0; i < openOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01006770 ALOGVV("output %zu isDuplicated=%d device=%s",
Eric Laurent8c7e6da2015-04-21 17:37:00 -07006771 i, openOutputs.valueAt(i)->isDuplicated(),
François Gaffie11d30102018-11-02 16:09:09 +01006772 openOutputs.valueAt(i)->supportedDevices().toString().c_str());
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006773 if (openOutputs.valueAt(i)->supportsAllDevices(devices)
jiabin9a3361e2019-10-01 09:38:30 -07006774 && openOutputs.valueAt(i)->devicesSupportEncodedFormats(devices.types())) {
François Gaffie11d30102018-11-02 16:09:09 +01006775 ALOGVV("%s() found output %d", __func__, openOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07006776 outputs.add(openOutputs.keyAt(i));
6777 }
6778 }
6779 return outputs;
6780}
6781
Mikhail Naganov37977152018-07-11 15:54:44 -07006782void AudioPolicyManager::checkForDeviceAndOutputChanges(std::function<bool()> onOutputsChecked)
6783{
6784 // checkA2dpSuspend must run before checkOutputForAllStrategies so that A2DP
6785 // output is suspended before any tracks are moved to it
6786 checkA2dpSuspend();
6787 checkOutputForAllStrategies();
Kevin Rocard153f92d2018-12-18 18:33:28 -08006788 checkSecondaryOutputs();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11006789 if (onOutputsChecked != nullptr && onOutputsChecked()) checkA2dpSuspend();
Mikhail Naganov37977152018-07-11 15:54:44 -07006790 updateDevicesAndOutputs();
Mikhail Naganov7bd9b8d2018-11-15 02:09:03 +00006791 if (mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD) != 0) {
Michael Chan6fb34492020-12-08 15:44:49 +11006792 // TODO: The MSD patches to be established here may differ to current MSD patches due to how
6793 // output devices for patching are resolved. Nevertheless, AudioTracks affected by device
6794 // configuration changes will ultimately be rerouted correctly. We can still avoid
6795 // unnecessary rerouting by caching and reusing the arguments to
6796 // mEngine->getOutputDevicesForAttributes() when resolving which output devices to patch to.
6797 // This may be complicated by the fact that devices may become unavailable.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11006798 setMsdOutputPatches();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11006799 }
Jean-Michel Trivi9a6b9ad2020-10-22 16:46:43 -07006800 // an event that changed routing likely occurred, inform upper layers
6801 mpClientInterface->onRoutingUpdated();
Mikhail Naganov37977152018-07-11 15:54:44 -07006802}
6803
François Gaffiec005e562018-11-06 15:04:49 +01006804bool AudioPolicyManager::followsSameRouting(const audio_attributes_t &lAttr,
6805 const audio_attributes_t &rAttr) const
Eric Laurente552edb2014-03-10 17:42:56 -07006806{
François Gaffiec005e562018-11-06 15:04:49 +01006807 return mEngine->getProductStrategyForAttributes(lAttr) ==
6808 mEngine->getProductStrategyForAttributes(rAttr);
6809}
6810
Francois Gaffieff1eb522020-05-06 18:37:04 +02006811void AudioPolicyManager::checkAudioSourceForAttributes(const audio_attributes_t &attr)
6812{
6813 for (size_t i = 0; i < mAudioSources.size(); i++) {
6814 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
6815 if (sourceDesc != nullptr && followsSameRouting(attr, sourceDesc->attributes())
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02006816 && sourceDesc->getPatchHandle() == AUDIO_PATCH_HANDLE_NONE
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02006817 && !isCallRxAudioSource(sourceDesc) && !sourceDesc->isInternal()) {
Francois Gaffieff1eb522020-05-06 18:37:04 +02006818 connectAudioSource(sourceDesc);
6819 }
6820 }
6821}
6822
6823void AudioPolicyManager::clearAudioSourcesForOutput(audio_io_handle_t output)
6824{
6825 for (size_t i = 0; i < mAudioSources.size(); i++) {
6826 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
6827 if (sourceDesc != nullptr && sourceDesc->swOutput().promote() != nullptr
6828 && sourceDesc->swOutput().promote()->mIoHandle == output) {
6829 disconnectAudioSource(sourceDesc);
6830 }
6831 }
6832}
6833
François Gaffiec005e562018-11-06 15:04:49 +01006834void AudioPolicyManager::checkOutputForAttributes(const audio_attributes_t &attr)
6835{
6836 auto psId = mEngine->getProductStrategyForAttributes(attr);
6837
6838 DeviceVector oldDevices = mEngine->getOutputDevicesForAttributes(attr, 0, true /*fromCache*/);
6839 DeviceVector newDevices = mEngine->getOutputDevicesForAttributes(attr, 0, false /*fromCache*/);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07006840
François Gaffie11d30102018-11-02 16:09:09 +01006841 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevices(oldDevices, mPreviousOutputs);
6842 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevices(newDevices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07006843
Eric Laurentc209fe42020-06-05 18:11:23 -07006844 uint32_t maxLatency = 0;
Oscar Azucena873d10f2023-01-12 18:34:42 -08006845 bool unneededUsePrimaryOutputFromPolicyMixes = false;
Eric Laurent56ed8842022-11-15 16:04:41 +01006846 std::vector<sp<SwAudioOutputDescriptor>> invalidatedOutputs;
Eric Laurentc209fe42020-06-05 18:11:23 -07006847 // take into account dynamic audio policies related changes: if a client is now associated
6848 // to a different policy mix than at creation time, invalidate corresponding stream
Eric Laurent56ed8842022-11-15 16:04:41 +01006849 for (size_t i = 0; i < mPreviousOutputs.size(); i++) {
Eric Laurentc209fe42020-06-05 18:11:23 -07006850 const sp<SwAudioOutputDescriptor>& desc = mPreviousOutputs.valueAt(i);
6851 if (desc->isDuplicated()) {
6852 continue;
Jean-Michel Trivife472e22014-12-16 14:23:13 -08006853 }
Eric Laurentc209fe42020-06-05 18:11:23 -07006854 for (const sp<TrackClientDescriptor>& client : desc->getClientIterable()) {
6855 if (mEngine->getProductStrategyForAttributes(client->attributes()) != psId) {
6856 continue;
6857 }
6858 sp<AudioPolicyMix> primaryMix;
Dean Wheatleyd082f472022-02-04 11:10:48 +11006859 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->config(),
Oscar Azucena873d10f2023-01-12 18:34:42 -08006860 client->uid(), client->session(), client->flags(), mAvailableOutputDevices,
6861 nullptr /* requestedDevice */, primaryMix, nullptr /* secondaryMixes */,
6862 unneededUsePrimaryOutputFromPolicyMixes);
Eric Laurentc209fe42020-06-05 18:11:23 -07006863 if (status != OK) {
6864 continue;
6865 }
yucliuf4de36d2020-09-14 14:57:56 -07006866 if (client->getPrimaryMix() != primaryMix || client->hasLostPrimaryMix()) {
Eric Laurent56ed8842022-11-15 16:04:41 +01006867 if (desc->isStrategyActive(psId) && maxLatency < desc->latency()) {
Eric Laurentc209fe42020-06-05 18:11:23 -07006868 maxLatency = desc->latency();
6869 }
Eric Laurent56ed8842022-11-15 16:04:41 +01006870 invalidatedOutputs.push_back(desc);
Eric Laurentc209fe42020-06-05 18:11:23 -07006871 }
Jean-Michel Trivife472e22014-12-16 14:23:13 -08006872 }
6873 }
6874
Eric Laurent56ed8842022-11-15 16:04:41 +01006875 if (srcOutputs != dstOutputs || !invalidatedOutputs.empty()) {
Eric Laurentac3a6902018-05-11 16:39:10 -07006876 // get maximum latency of all source outputs to determine the minimum mute time guaranteeing
6877 // audio from invalidated tracks will be rendered when unmuting
Eric Laurentac3a6902018-05-11 16:39:10 -07006878 for (audio_io_handle_t srcOut : srcOutputs) {
6879 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
Eric Laurentaa02db82019-09-05 17:31:49 -07006880 if (desc == nullptr) continue;
6881
6882 if (desc->isStrategyActive(psId) && maxLatency < desc->latency()) {
Eric Laurentac3a6902018-05-11 16:39:10 -07006883 maxLatency = desc->latency();
6884 }
Eric Laurentaa02db82019-09-05 17:31:49 -07006885
Eric Laurent56ed8842022-11-15 16:04:41 +01006886 bool invalidate = false;
Eric Laurentaa02db82019-09-05 17:31:49 -07006887 for (auto client : desc->clientsList(false /*activeOnly*/)) {
Eric Laurent78aade82019-09-13 18:55:08 -07006888 if (desc->isDuplicated() || !desc->mProfile->isDirectOutput()) {
Eric Laurentaa02db82019-09-05 17:31:49 -07006889 // a client on a non direct outputs has necessarily a linear PCM format
6890 // so we can call selectOutput() safely
6891 const audio_io_handle_t newOutput = selectOutput(dstOutputs,
6892 client->flags(),
6893 client->config().format,
6894 client->config().channel_mask,
jiabinebb6af42020-06-09 17:31:17 -07006895 client->config().sample_rate,
6896 client->session());
Eric Laurentaa02db82019-09-05 17:31:49 -07006897 if (newOutput != srcOut) {
6898 invalidate = true;
6899 break;
6900 }
6901 } else {
6902 sp<IOProfile> profile = getProfileForOutput(newDevices,
6903 client->config().sample_rate,
6904 client->config().format,
6905 client->config().channel_mask,
6906 client->flags(),
6907 true /* directOnly */);
6908 if (profile != desc->mProfile) {
6909 invalidate = true;
6910 break;
6911 }
6912 }
6913 }
Eric Laurent56ed8842022-11-15 16:04:41 +01006914 // mute strategy while moving tracks from one output to another
6915 if (invalidate) {
6916 invalidatedOutputs.push_back(desc);
6917 if (desc->isStrategyActive(psId)) {
6918 setStrategyMute(psId, true, desc);
6919 setStrategyMute(psId, false, desc, maxLatency * LATENCY_MUTE_FACTOR,
6920 newDevices.types());
6921 }
Eric Laurente552edb2014-03-10 17:42:56 -07006922 }
François Gaffiec005e562018-11-06 15:04:49 +01006923 sp<SourceClientDescriptor> source = getSourceForAttributesOnOutput(srcOut, attr);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02006924 if (source != nullptr && !isCallRxAudioSource(source) && !source->isInternal()) {
Eric Laurentd60560a2015-04-10 11:31:20 -07006925 connectAudioSource(source);
6926 }
Eric Laurente552edb2014-03-10 17:42:56 -07006927 }
6928
Eric Laurent56ed8842022-11-15 16:04:41 +01006929 ALOGV_IF(!(srcOutputs.isEmpty() || dstOutputs.isEmpty()),
6930 "%s: strategy %d, moving from output %s to output %s", __func__, psId,
6931 std::to_string(srcOutputs[0]).c_str(),
6932 std::to_string(dstOutputs[0]).c_str());
6933
François Gaffiec005e562018-11-06 15:04:49 +01006934 // Move effects associated to this stream from previous output to new output
6935 if (followsSameRouting(attr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07006936 selectOutputForMusicEffects();
Eric Laurente552edb2014-03-10 17:42:56 -07006937 }
François Gaffiec005e562018-11-06 15:04:49 +01006938 // Move tracks associated to this stream (and linked) from previous output to new output
Eric Laurent56ed8842022-11-15 16:04:41 +01006939 if (!invalidatedOutputs.empty()) {
jiabinc44b3462022-12-08 12:52:31 -08006940 invalidateStreams(mEngine->getStreamTypesForProductStrategy(psId));
Eric Laurent56ed8842022-11-15 16:04:41 +01006941 for (sp<SwAudioOutputDescriptor> desc : invalidatedOutputs) {
jiabin49256852022-03-09 11:21:35 -08006942 desc->setTracksInvalidatedStatusByStrategy(psId);
6943 }
Eric Laurente552edb2014-03-10 17:42:56 -07006944 }
6945 }
6946}
6947
Eric Laurente0720872014-03-11 09:30:41 -07006948void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07006949{
François Gaffiec005e562018-11-06 15:04:49 +01006950 for (const auto &strategy : mEngine->getOrderedProductStrategies()) {
6951 auto attributes = mEngine->getAllAttributesForProductStrategy(strategy).front();
6952 checkOutputForAttributes(attributes);
Francois Gaffieff1eb522020-05-06 18:37:04 +02006953 checkAudioSourceForAttributes(attributes);
François Gaffiec005e562018-11-06 15:04:49 +01006954 }
Eric Laurente552edb2014-03-10 17:42:56 -07006955}
6956
Kevin Rocard153f92d2018-12-18 18:33:28 -08006957void AudioPolicyManager::checkSecondaryOutputs() {
jiabinc44b3462022-12-08 12:52:31 -08006958 PortHandleVector clientsToInvalidate;
jiabin10a03f12021-05-07 23:46:28 +00006959 TrackSecondaryOutputsMap trackSecondaryOutputs;
Oscar Azucena873d10f2023-01-12 18:34:42 -08006960 bool unneededUsePrimaryOutputFromPolicyMixes = false;
Kevin Rocard153f92d2018-12-18 18:33:28 -08006961 for (size_t i = 0; i < mOutputs.size(); i++) {
6962 const sp<SwAudioOutputDescriptor>& outputDescriptor = mOutputs[i];
6963 for (const sp<TrackClientDescriptor>& client : outputDescriptor->getClientIterable()) {
Eric Laurentc529cf62020-04-17 18:19:10 -07006964 sp<AudioPolicyMix> primaryMix;
6965 std::vector<sp<AudioPolicyMix>> secondaryMixes;
Dean Wheatleyd082f472022-02-04 11:10:48 +11006966 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->config(),
Oscar Azucena873d10f2023-01-12 18:34:42 -08006967 client->uid(), client->session(), client->flags(), mAvailableOutputDevices,
6968 nullptr /* requestedDevice */, primaryMix, &secondaryMixes,
6969 unneededUsePrimaryOutputFromPolicyMixes);
Eric Laurentc529cf62020-04-17 18:19:10 -07006970 std::vector<sp<SwAudioOutputDescriptor>> secondaryDescs;
6971 for (auto &secondaryMix : secondaryMixes) {
6972 sp<SwAudioOutputDescriptor> outputDesc = secondaryMix->getOutput();
6973 if (outputDesc != nullptr &&
6974 outputDesc->mIoHandle != AUDIO_IO_HANDLE_NONE) {
6975 secondaryDescs.push_back(outputDesc);
6976 }
6977 }
6978
jiabinc44b3462022-12-08 12:52:31 -08006979 if (status != OK &&
6980 (client->flags() & AUDIO_OUTPUT_FLAG_MMAP_NOIRQ) == AUDIO_OUTPUT_FLAG_NONE) {
6981 // When it failed to query secondary output, only invalidate the client that is not
6982 // MMAP. The reason is that MMAP stream will not support secondary output.
6983 clientsToInvalidate.push_back(client->portId());
jiabin10a03f12021-05-07 23:46:28 +00006984 } else if (!std::equal(
6985 client->getSecondaryOutputs().begin(),
6986 client->getSecondaryOutputs().end(),
6987 secondaryDescs.begin(), secondaryDescs.end())) {
jiabina5281062021-11-23 00:10:23 +00006988 if (!audio_is_linear_pcm(client->config().format)) {
6989 // If the format is not PCM, the tracks should be invalidated to get correct
6990 // behavior when the secondary output is changed.
jiabinc44b3462022-12-08 12:52:31 -08006991 clientsToInvalidate.push_back(client->portId());
jiabina5281062021-11-23 00:10:23 +00006992 } else {
6993 std::vector<wp<SwAudioOutputDescriptor>> weakSecondaryDescs;
6994 std::vector<audio_io_handle_t> secondaryOutputIds;
6995 for (const auto &secondaryDesc: secondaryDescs) {
6996 secondaryOutputIds.push_back(secondaryDesc->mIoHandle);
6997 weakSecondaryDescs.push_back(secondaryDesc);
6998 }
6999 trackSecondaryOutputs.emplace(client->portId(), secondaryOutputIds);
7000 client->setSecondaryOutputs(std::move(weakSecondaryDescs));
jiabin10a03f12021-05-07 23:46:28 +00007001 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08007002 }
7003 }
7004 }
jiabin10a03f12021-05-07 23:46:28 +00007005 if (!trackSecondaryOutputs.empty()) {
7006 mpClientInterface->updateSecondaryOutputs(trackSecondaryOutputs);
7007 }
jiabinc44b3462022-12-08 12:52:31 -08007008 if (!clientsToInvalidate.empty()) {
7009 ALOGD("%s Invalidate clients due to fail getting output for attr", __func__);
7010 mpClientInterface->invalidateTracks(clientsToInvalidate);
Kevin Rocard153f92d2018-12-18 18:33:28 -08007011 }
7012}
7013
Eric Laurent2517af32020-11-25 15:31:27 +01007014bool AudioPolicyManager::isScoRequestedForComm() const {
7015 AudioDeviceTypeAddrVector devices;
7016 mEngine->getDevicesForRoleAndStrategy(mCommunnicationStrategy, DEVICE_ROLE_PREFERRED, devices);
7017 for (const auto &device : devices) {
7018 if (audio_is_bluetooth_out_sco_device(device.mType)) {
7019 return true;
7020 }
7021 }
7022 return false;
7023}
7024
Eric Laurent1a8b45f2022-04-13 16:01:47 +02007025bool AudioPolicyManager::isHearingAidUsedForComm() const {
7026 DeviceVector devices = mEngine->getOutputDevicesForStream(AUDIO_STREAM_VOICE_CALL,
7027 true /*fromCache*/);
7028 for (const auto &device : devices) {
7029 if (device->type() == AUDIO_DEVICE_OUT_HEARING_AID) {
7030 return true;
7031 }
7032 }
7033 return false;
7034}
7035
7036
Eric Laurente0720872014-03-11 09:30:41 -07007037void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07007038{
François Gaffie53615e22015-03-19 09:24:12 +01007039 audio_io_handle_t a2dpOutput = mOutputs.getA2dpOutput();
Aniket Kumar Lataa8ee9962018-01-31 20:24:23 -08007040 if (a2dpOutput == 0 || mOutputs.isA2dpOffloadedOnPrimary()) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07007041 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07007042 return;
7043 }
7044
Eric Laurent3a4311c2014-03-17 12:00:47 -07007045 bool isScoConnected =
jiabin9a3361e2019-10-01 09:38:30 -07007046 (mAvailableInputDevices.types().count(AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) != 0 ||
7047 !Intersection(mAvailableOutputDevices.types(), getAudioDeviceOutAllScoSet()).empty());
Eric Laurent2517af32020-11-25 15:31:27 +01007048 bool isScoRequested = isScoRequestedForComm();
Eric Laurentf732e072016-08-03 19:30:28 -07007049
7050 // if suspended, restore A2DP output if:
7051 // ((SCO device is NOT connected) ||
Eric Laurent2517af32020-11-25 15:31:27 +01007052 // ((SCO is not requested) &&
Eric Laurentf732e072016-08-03 19:30:28 -07007053 // (phone state is NOT in call) && (phone state is NOT ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07007054 //
Eric Laurentf732e072016-08-03 19:30:28 -07007055 // if not suspended, suspend A2DP output if:
7056 // (SCO device is connected) &&
Eric Laurent2517af32020-11-25 15:31:27 +01007057 // ((SCO is requested) ||
Eric Laurentf732e072016-08-03 19:30:28 -07007058 // ((phone state is in call) || (phone state is ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07007059 //
7060 if (mA2dpSuspended) {
Eric Laurentf732e072016-08-03 19:30:28 -07007061 if (!isScoConnected ||
Eric Laurent2517af32020-11-25 15:31:27 +01007062 (!isScoRequested &&
Eric Laurentf732e072016-08-03 19:30:28 -07007063 (mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) &&
François Gaffie2110e042015-03-24 08:41:51 +01007064 (mEngine->getPhoneState() != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07007065
7066 mpClientInterface->restoreOutput(a2dpOutput);
7067 mA2dpSuspended = false;
7068 }
7069 } else {
Eric Laurentf732e072016-08-03 19:30:28 -07007070 if (isScoConnected &&
Eric Laurent2517af32020-11-25 15:31:27 +01007071 (isScoRequested ||
Eric Laurentf732e072016-08-03 19:30:28 -07007072 (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) ||
François Gaffie2110e042015-03-24 08:41:51 +01007073 (mEngine->getPhoneState() == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07007074
7075 mpClientInterface->suspendOutput(a2dpOutput);
7076 mA2dpSuspended = true;
7077 }
7078 }
7079}
7080
François Gaffie11d30102018-11-02 16:09:09 +01007081DeviceVector AudioPolicyManager::getNewOutputDevices(const sp<SwAudioOutputDescriptor>& outputDesc,
7082 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07007083{
François Gaffie11d30102018-11-02 16:09:09 +01007084 DeviceVector devices;
7085
Jean-Michel Triviff155c62016-02-26 12:07:16 -08007086 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007087 if (index >= 0) {
7088 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007089 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01007090 ALOGV("%s device %s forced by patch %d", __func__,
7091 outputDesc->devices().toString().c_str(), outputDesc->getPatchHandle());
7092 return outputDesc->devices();
Eric Laurent6a94d692014-05-20 11:18:06 -07007093 }
7094 }
7095
Dean Wheatley514b4312020-06-17 21:45:00 +10007096 // Do not retrieve engine device for outputs through MSD
7097 // TODO: support explicit routing requests by resetting MSD patch to engine device.
7098 if (outputDesc->devices() == getMsdAudioOutDevices()) {
7099 return outputDesc->devices();
7100 }
7101
Eric Laurent97ac8712018-07-27 18:59:02 -07007102 // Honor explicit routing requests only if no client using default routing is active on this
7103 // input: a specific app can not force routing for other apps by setting a preferred device.
7104 bool active; // unused
François Gaffie11d30102018-11-02 16:09:09 +01007105 sp<DeviceDescriptor> device =
François Gaffiec005e562018-11-06 15:04:49 +01007106 findPreferredDevice(outputDesc, PRODUCT_STRATEGY_NONE, active, mAvailableOutputDevices);
François Gaffie11d30102018-11-02 16:09:09 +01007107 if (device != nullptr) {
7108 return DeviceVector(device);
Eric Laurentf3a5a602018-05-22 18:42:55 -07007109 }
7110
François Gaffiea807ef92018-11-05 10:44:33 +01007111 // Legacy Engine cannot take care of bus devices and mix, so we need to handle the conflict
7112 // of setForceUse / Default Bus device here
7113 device = mPolicyMixes.getDeviceAndMixForOutput(outputDesc, mAvailableOutputDevices);
7114 if (device != nullptr) {
7115 return DeviceVector(device);
7116 }
7117
François Gaffiec005e562018-11-06 15:04:49 +01007118 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
7119 StreamTypeVector streams = mEngine->getStreamTypesForProductStrategy(productStrategy);
7120 auto attr = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307121 auto hasStreamActive = [&](auto stream) {
7122 return hasStream(streams, stream) && isStreamActive(stream, 0);
7123 };
Eric Laurent484e9272018-06-07 17:29:23 -07007124
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307125 auto doGetOutputDevicesForVoice = [&]() {
7126 return hasVoiceStream(streams) && (outputDesc == mPrimaryOutput ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007127 outputDesc->isActive(toVolumeSource(AUDIO_STREAM_VOICE_CALL, false))) &&
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307128 (isInCall() ||
Henrik Backlund07c654a2021-10-14 15:57:10 +02007129 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc)) &&
7130 !isStreamActive(AUDIO_STREAM_ENFORCED_AUDIBLE, 0);
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307131 };
7132
7133 // With low-latency playing on speaker, music on WFD, when the first low-latency
7134 // output is stopped, getNewOutputDevices checks for a product strategy
7135 // from the list, as STRATEGY_SONIFICATION comes prior to STRATEGY_MEDIA.
Carter Hsucc58a6b2021-07-20 08:44:50 +00007136 // If an ALARM or ENFORCED_AUDIBLE stream is supported by the product strategy,
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307137 // devices are returned for STRATEGY_SONIFICATION without checking whether the
7138 // stream is associated to the output descriptor.
7139 if (doGetOutputDevicesForVoice() || outputDesc->isStrategyActive(productStrategy) ||
7140 ((hasStreamActive(AUDIO_STREAM_ALARM) ||
7141 hasStreamActive(AUDIO_STREAM_ENFORCED_AUDIBLE)) &&
7142 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc))) {
François Gaffiec005e562018-11-06 15:04:49 +01007143 // Retrieval of devices for voice DL is done on primary output profile, cannot
7144 // check the route (would force modifying configuration file for this profile)
7145 devices = mEngine->getOutputDevicesForAttributes(attr, nullptr, fromCache);
7146 break;
7147 }
Eric Laurente552edb2014-03-10 17:42:56 -07007148 }
François Gaffiec005e562018-11-06 15:04:49 +01007149 ALOGV("%s selected devices %s", __func__, devices.toString().c_str());
François Gaffie11d30102018-11-02 16:09:09 +01007150 return devices;
Eric Laurent1c333e22014-05-20 10:48:17 -07007151}
7152
François Gaffie11d30102018-11-02 16:09:09 +01007153sp<DeviceDescriptor> AudioPolicyManager::getNewInputDevice(
7154 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurent1c333e22014-05-20 10:48:17 -07007155{
François Gaffie11d30102018-11-02 16:09:09 +01007156 sp<DeviceDescriptor> device;
Eric Laurent6a94d692014-05-20 11:18:06 -07007157
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08007158 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007159 if (index >= 0) {
7160 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007161 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01007162 ALOGV("getNewInputDevice() device %s forced by patch %d",
7163 inputDesc->getDevice()->toString().c_str(), inputDesc->getPatchHandle());
7164 return inputDesc->getDevice();
Eric Laurent6a94d692014-05-20 11:18:06 -07007165 }
7166 }
7167
Eric Laurent97ac8712018-07-27 18:59:02 -07007168 // Honor explicit routing requests only if no client using default routing is active on this
7169 // input: a specific app can not force routing for other apps by setting a preferred device.
7170 bool active;
François Gaffie11d30102018-11-02 16:09:09 +01007171 device = findPreferredDevice(inputDesc, AUDIO_SOURCE_DEFAULT, active, mAvailableInputDevices);
7172 if (device != nullptr) {
7173 return device;
Eric Laurent97ac8712018-07-27 18:59:02 -07007174 }
7175
Eric Laurentdc95a252018-04-12 12:46:56 -07007176 // If we are not in call and no client is active on this input, this methods returns
Andy Hungf024a9e2019-01-30 16:01:02 -08007177 // a null sp<>, causing the patch on the input stream to be released.
yuanjiahsu0735bf32021-03-18 08:12:54 +08007178 audio_attributes_t attributes;
7179 uid_t uid;
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007180 audio_session_t session;
yuanjiahsu0735bf32021-03-18 08:12:54 +08007181 sp<RecordClientDescriptor> topClient = inputDesc->getHighestPriorityClient();
7182 if (topClient != nullptr) {
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01007183 attributes = topClient->attributes();
7184 uid = topClient->uid();
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007185 session = topClient->session();
yuanjiahsu0735bf32021-03-18 08:12:54 +08007186 } else {
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01007187 attributes = { .source = AUDIO_SOURCE_DEFAULT };
7188 uid = 0;
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007189 session = AUDIO_SESSION_NONE;
yuanjiahsu0735bf32021-03-18 08:12:54 +08007190 }
7191
Francois Gaffie716e1432019-01-14 16:58:59 +01007192 if (attributes.source == AUDIO_SOURCE_DEFAULT && isInCall()) {
7193 attributes.source = AUDIO_SOURCE_VOICE_COMMUNICATION;
Eric Laurentdc95a252018-04-12 12:46:56 -07007194 }
Francois Gaffie716e1432019-01-14 16:58:59 +01007195 if (attributes.source != AUDIO_SOURCE_DEFAULT) {
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007196 device = mEngine->getInputDeviceForAttributes(attributes, uid, session);
Eric Laurentfb66dd92016-01-28 18:32:03 -08007197 }
Eric Laurent1c333e22014-05-20 10:48:17 -07007198
Eric Laurente552edb2014-03-10 17:42:56 -07007199 return device;
7200}
7201
Eric Laurent794fde22016-03-11 09:50:45 -08007202bool AudioPolicyManager::streamsMatchForvolume(audio_stream_type_t stream1,
7203 audio_stream_type_t stream2) {
Jean-Michel Trivi99bb2f92016-11-23 15:52:07 -08007204 return (stream1 == stream2);
Eric Laurent28d09f02016-03-08 10:43:05 -08007205}
7206
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08007207status_t AudioPolicyManager::getDevicesForAttributes(
Andy Hung6d23c0f2022-02-16 09:37:15 -08007208 const audio_attributes_t &attr, AudioDeviceTypeAddrVector *devices, bool forVolume) {
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08007209 if (devices == nullptr) {
7210 return BAD_VALUE;
7211 }
Andy Hung6d23c0f2022-02-16 09:37:15 -08007212
Andy Hung6d23c0f2022-02-16 09:37:15 -08007213 DeviceVector curDevices;
jiabinf1c73972022-04-14 16:28:52 -07007214 if (status_t status = getDevicesForAttributes(attr, curDevices, forVolume); status != OK) {
7215 return status;
Andy Hung6d23c0f2022-02-16 09:37:15 -08007216 }
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08007217 for (const auto& device : curDevices) {
7218 devices->push_back(device->getDeviceTypeAddr());
7219 }
7220 return NO_ERROR;
7221}
7222
Eric Laurente0720872014-03-11 09:30:41 -07007223void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07007224 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07007225 case AUDIO_STREAM_MUSIC:
François Gaffiec005e562018-11-06 15:04:49 +01007226 checkOutputForAttributes(attributes_initializer(AUDIO_USAGE_NOTIFICATION));
Eric Laurente552edb2014-03-10 17:42:56 -07007227 updateDevicesAndOutputs();
7228 break;
7229 default:
7230 break;
7231 }
7232}
7233
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007234uint32_t AudioPolicyManager::handleEventForBeacon(int event) {
Eric Laurent9459fb02015-08-12 18:36:32 -07007235
7236 // skip beacon mute management if a dedicated TTS output is available
7237 if (mTtsOutputAvailable) {
7238 return 0;
7239 }
7240
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007241 switch(event) {
7242 case STARTING_OUTPUT:
7243 mBeaconMuteRefCount++;
7244 break;
7245 case STOPPING_OUTPUT:
7246 if (mBeaconMuteRefCount > 0) {
7247 mBeaconMuteRefCount--;
7248 }
7249 break;
7250 case STARTING_BEACON:
7251 mBeaconPlayingRefCount++;
7252 break;
7253 case STOPPING_BEACON:
7254 if (mBeaconPlayingRefCount > 0) {
7255 mBeaconPlayingRefCount--;
7256 }
7257 break;
7258 }
7259
7260 if (mBeaconMuteRefCount > 0) {
7261 // any playback causes beacon to be muted
7262 return setBeaconMute(true);
7263 } else {
7264 // no other playback: unmute when beacon starts playing, mute when it stops
7265 return setBeaconMute(mBeaconPlayingRefCount == 0);
7266 }
7267}
7268
7269uint32_t AudioPolicyManager::setBeaconMute(bool mute) {
7270 ALOGV("setBeaconMute(%d) mBeaconMuteRefCount=%d mBeaconPlayingRefCount=%d",
7271 mute, mBeaconMuteRefCount, mBeaconPlayingRefCount);
7272 // keep track of muted state to avoid repeating mute/unmute operations
7273 if (mBeaconMuted != mute) {
7274 // mute/unmute AUDIO_STREAM_TTS on all outputs
7275 ALOGV("\t muting %d", mute);
7276 uint32_t maxLatency = 0;
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007277 auto ttsVolumeSource = toVolumeSource(AUDIO_STREAM_TTS, false);
7278 if (ttsVolumeSource == VOLUME_SOURCE_NONE) {
7279 ALOGV("\t no tts volume source available");
7280 return 0;
7281 }
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007282 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07007283 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
jiabin9a3361e2019-10-01 09:38:30 -07007284 setVolumeSourceMute(ttsVolumeSource, mute/*on*/, desc, 0 /*delay*/, DeviceTypeSet());
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007285 const uint32_t latency = desc->latency() * 2;
Eric Laurentcdb2b352020-07-23 10:57:02 -07007286 if (desc->isActive(latency * 2) && latency > maxLatency) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007287 maxLatency = latency;
7288 }
7289 }
7290 mBeaconMuted = mute;
7291 return maxLatency;
7292 }
7293 return 0;
7294}
7295
Eric Laurente0720872014-03-11 09:30:41 -07007296void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07007297{
François Gaffiec005e562018-11-06 15:04:49 +01007298 mEngine->updateDeviceSelectionCache();
Eric Laurente552edb2014-03-10 17:42:56 -07007299 mPreviousOutputs = mOutputs;
7300}
7301
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07007302uint32_t AudioPolicyManager::checkDeviceMuteStrategies(const sp<AudioOutputDescriptor>& outputDesc,
François Gaffiec005e562018-11-06 15:04:49 +01007303 const DeviceVector &prevDevices,
Eric Laurente552edb2014-03-10 17:42:56 -07007304 uint32_t delayMs)
7305{
7306 // mute/unmute strategies using an incompatible device combination
7307 // if muting, wait for the audio in pcm buffer to be drained before proceeding
7308 // if unmuting, unmute only after the specified delay
7309 if (outputDesc->isDuplicated()) {
7310 return 0;
7311 }
7312
7313 uint32_t muteWaitMs = 0;
François Gaffiec005e562018-11-06 15:04:49 +01007314 DeviceVector devices = outputDesc->devices();
7315 bool shouldMute = outputDesc->isActive() && (devices.size() >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07007316
François Gaffiec005e562018-11-06 15:04:49 +01007317 auto productStrategies = mEngine->getOrderedProductStrategies();
7318 for (const auto &productStrategy : productStrategies) {
7319 auto attributes = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
7320 DeviceVector curDevices =
7321 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false/*fromCache*/);
7322 curDevices = curDevices.filter(outputDesc->supportedDevices());
7323 bool mute = shouldMute && curDevices.containsAtLeastOne(devices) && curDevices != devices;
Eric Laurente552edb2014-03-10 17:42:56 -07007324 bool doMute = false;
7325
François Gaffiec005e562018-11-06 15:04:49 +01007326 if (mute && !outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07007327 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01007328 outputDesc->setStrategyMutedByDevice(productStrategy, true);
7329 } else if (!mute && outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07007330 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01007331 outputDesc->setStrategyMutedByDevice(productStrategy, false);
Eric Laurente552edb2014-03-10 17:42:56 -07007332 }
Eric Laurent99401132014-05-07 19:48:15 -07007333 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07007334 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07007335 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07007336 // skip output if it does not share any device with current output
François Gaffie11d30102018-11-02 16:09:09 +01007337 if (!desc->supportedDevices().containsAtLeastOne(outputDesc->supportedDevices())) {
Eric Laurente552edb2014-03-10 17:42:56 -07007338 continue;
7339 }
François Gaffiec005e562018-11-06 15:04:49 +01007340 ALOGVV("%s() %s (curDevice %s)", __func__,
7341 mute ? "muting" : "unmuting", curDevices.toString().c_str());
7342 setStrategyMute(productStrategy, mute, desc, mute ? 0 : delayMs);
7343 if (desc->isStrategyActive(productStrategy)) {
Eric Laurent99401132014-05-07 19:48:15 -07007344 if (mute) {
7345 // FIXME: should not need to double latency if volume could be applied
7346 // immediately by the audioflinger mixer. We must account for the delay
7347 // between now and the next time the audioflinger thread for this output
7348 // will process a buffer (which corresponds to one buffer size,
7349 // usually 1/2 or 1/4 of the latency).
7350 if (muteWaitMs < desc->latency() * 2) {
7351 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07007352 }
7353 }
7354 }
7355 }
7356 }
7357 }
7358
Eric Laurent99401132014-05-07 19:48:15 -07007359 // temporary mute output if device selection changes to avoid volume bursts due to
7360 // different per device volumes
François Gaffiec005e562018-11-06 15:04:49 +01007361 if (outputDesc->isActive() && (devices != prevDevices)) {
Eric Laurentdc462862016-07-19 12:29:53 -07007362 uint32_t tempMuteWaitMs = outputDesc->latency() * 2;
Jasmine Chaf6074fe2021-08-17 13:44:31 +08007363
Eric Laurentdc462862016-07-19 12:29:53 -07007364 if (muteWaitMs < tempMuteWaitMs) {
7365 muteWaitMs = tempMuteWaitMs;
Eric Laurent99401132014-05-07 19:48:15 -07007366 }
Jasmine Chaf6074fe2021-08-17 13:44:31 +08007367
7368 // If recommended duration is defined, replace temporary mute duration to avoid
7369 // truncated notifications at beginning, which depends on duration of changing path in HAL.
7370 // Otherwise, temporary mute duration is conservatively set to 4 times the reported latency.
7371 uint32_t tempRecommendedMuteDuration = outputDesc->getRecommendedMuteDurationMs();
7372 uint32_t tempMuteDurationMs = tempRecommendedMuteDuration > 0 ?
7373 tempRecommendedMuteDuration : outputDesc->latency() * 4;
7374
François Gaffieaaac0fd2018-11-22 17:56:39 +01007375 for (const auto &activeVs : outputDesc->getActiveVolumeSources()) {
7376 // make sure that we do not start the temporary mute period too early in case of
7377 // delayed device change
7378 setVolumeSourceMute(activeVs, true, outputDesc, delayMs);
7379 setVolumeSourceMute(activeVs, false, outputDesc, delayMs + tempMuteDurationMs,
François Gaffiec005e562018-11-06 15:04:49 +01007380 devices.types());
Eric Laurent99401132014-05-07 19:48:15 -07007381 }
7382 }
7383
Eric Laurente552edb2014-03-10 17:42:56 -07007384 // wait for the PCM output buffers to empty before proceeding with the rest of the command
7385 if (muteWaitMs > delayMs) {
7386 muteWaitMs -= delayMs;
7387 usleep(muteWaitMs * 1000);
7388 return muteWaitMs;
7389 }
7390 return 0;
7391}
7392
François Gaffie11d30102018-11-02 16:09:09 +01007393uint32_t AudioPolicyManager::setOutputDevices(const sp<SwAudioOutputDescriptor>& outputDesc,
7394 const DeviceVector &devices,
7395 bool force,
7396 int delayMs,
7397 audio_patch_handle_t *patchHandle,
Oscar Azucena6acf34b2023-04-27 16:32:09 -07007398 bool requiresMuteCheck, bool requiresVolumeCheck,
7399 bool skipMuteDelay)
Eric Laurente552edb2014-03-10 17:42:56 -07007400{
jiabin3ff8d7d2022-12-13 06:27:44 +00007401 // TODO(b/262404095): Consider if the output need to be reopened.
François Gaffie11d30102018-11-02 16:09:09 +01007402 ALOGV("%s device %s delayMs %d", __func__, devices.toString().c_str(), delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07007403 uint32_t muteWaitMs;
7404
7405 if (outputDesc->isDuplicated()) {
François Gaffie11d30102018-11-02 16:09:09 +01007406 muteWaitMs = setOutputDevices(outputDesc->subOutput1(), devices, force, delayMs,
Oscar Azucena6acf34b2023-04-27 16:32:09 -07007407 nullptr /* patchHandle */, requiresMuteCheck, skipMuteDelay);
François Gaffie11d30102018-11-02 16:09:09 +01007408 muteWaitMs += setOutputDevices(outputDesc->subOutput2(), devices, force, delayMs,
Oscar Azucena6acf34b2023-04-27 16:32:09 -07007409 nullptr /* patchHandle */, requiresMuteCheck, skipMuteDelay);
Eric Laurente552edb2014-03-10 17:42:56 -07007410 return muteWaitMs;
7411 }
Eric Laurente552edb2014-03-10 17:42:56 -07007412
7413 // filter devices according to output selected
Francois Gaffie716e1432019-01-14 16:58:59 +01007414 DeviceVector filteredDevices = outputDesc->filterSupportedDevices(devices);
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01007415 DeviceVector prevDevices = outputDesc->devices();
Francois Gaffie3523ab32021-06-22 13:24:34 +02007416 DeviceVector availPrevDevices = mAvailableOutputDevices.filter(prevDevices);
Eric Laurente552edb2014-03-10 17:42:56 -07007417
François Gaffie11d30102018-11-02 16:09:09 +01007418 ALOGV("setOutputDevices() prevDevice %s", prevDevices.toString().c_str());
7419
7420 if (!filteredDevices.isEmpty()) {
7421 outputDesc->setDevices(filteredDevices);
Eric Laurente552edb2014-03-10 17:42:56 -07007422 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00007423
7424 // if the outputs are not materially active, there is no need to mute.
7425 if (requiresMuteCheck) {
François Gaffiec005e562018-11-06 15:04:49 +01007426 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevices, delayMs);
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00007427 } else {
7428 ALOGV("%s: suppressing checkDeviceMuteStrategies", __func__);
7429 muteWaitMs = 0;
7430 }
Eric Laurente552edb2014-03-10 17:42:56 -07007431
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02007432 bool outputRouted = outputDesc->isRouted();
7433
Eric Laurent79ea9582020-06-11 18:49:24 -07007434 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
7435 // output profile or if new device is not supported AND previous device(s) is(are) still
7436 // available (otherwise reset device must be done on the output)
Francois Gaffie3523ab32021-06-22 13:24:34 +02007437 if (!devices.isEmpty() && filteredDevices.isEmpty() && !availPrevDevices.empty()) {
Eric Laurent79ea9582020-06-11 18:49:24 -07007438 ALOGV("%s: unsupported device %s for output", __func__, devices.toString().c_str());
7439 // restore previous device after evaluating strategy mute state
7440 outputDesc->setDevices(prevDevices);
7441 return muteWaitMs;
7442 }
7443
Eric Laurente552edb2014-03-10 17:42:56 -07007444 // Do not change the routing if:
Eric Laurentb80a2a82014-10-27 16:07:59 -07007445 // the requested device is AUDIO_DEVICE_NONE
7446 // OR the requested device is the same as current device
7447 // AND force is not specified
7448 // AND the output is connected by a valid audio patch.
François Gaffie11d30102018-11-02 16:09:09 +01007449 // Doing this check here allows the caller to call setOutputDevices() without conditions
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02007450 if ((filteredDevices.isEmpty() || filteredDevices == prevDevices) && !force && outputRouted) {
François Gaffie11d30102018-11-02 16:09:09 +01007451 ALOGV("%s setting same device %s or null device, force=%d, patch handle=%d", __func__,
7452 filteredDevices.toString().c_str(), force, outputDesc->getPatchHandle());
Francois Gaffie3523ab32021-06-22 13:24:34 +02007453 if (requiresVolumeCheck && !filteredDevices.isEmpty()) {
7454 ALOGV("%s setting same device on routed output, force apply volumes", __func__);
7455 applyStreamVolumes(outputDesc, filteredDevices.types(), delayMs, true /*force*/);
7456 }
Eric Laurente552edb2014-03-10 17:42:56 -07007457 return muteWaitMs;
7458 }
7459
François Gaffie11d30102018-11-02 16:09:09 +01007460 ALOGV("%s changing device to %s", __func__, filteredDevices.toString().c_str());
Eric Laurent1c333e22014-05-20 10:48:17 -07007461
Eric Laurente552edb2014-03-10 17:42:56 -07007462 // do the routing
Francois Gaffie3523ab32021-06-22 13:24:34 +02007463 if (filteredDevices.isEmpty() || mAvailableOutputDevices.filter(filteredDevices).empty()) {
Eric Laurentc75307b2015-03-17 15:29:32 -07007464 resetOutputDevice(outputDesc, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07007465 } else {
François Gaffie11d30102018-11-02 16:09:09 +01007466 PatchBuilder patchBuilder;
7467 patchBuilder.addSource(outputDesc);
7468 ALOG_ASSERT(filteredDevices.size() <= AUDIO_PATCH_PORTS_MAX, "Too many sink ports");
7469 for (const auto &filteredDevice : filteredDevices) {
7470 patchBuilder.addSink(filteredDevice);
Eric Laurentc40d9692016-04-13 19:14:13 -07007471 }
7472
Jasmine Cha7f82d1a2020-03-16 13:21:47 +08007473 // Add half reported latency to delayMs when muteWaitMs is null in order
7474 // to avoid disordered sequence of muting volume and changing devices.
Oscar Azucena6acf34b2023-04-27 16:32:09 -07007475 int actualDelayMs = !skipMuteDelay && muteWaitMs == 0
7476 ? (delayMs + (outputDesc->latency() / 2)) : delayMs;
7477 installPatch(__func__, patchHandle, outputDesc.get(), patchBuilder.patch(), actualDelayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07007478 }
Eric Laurente552edb2014-03-10 17:42:56 -07007479
Oscar Azucena6acf34b2023-04-27 16:32:09 -07007480 // Since the mute is skip, also skip the apply stream volume as that will be applied externally
7481 if (!skipMuteDelay) {
7482 // update stream volumes according to new device
7483 applyStreamVolumes(outputDesc, filteredDevices.types(), delayMs);
7484 }
Eric Laurente552edb2014-03-10 17:42:56 -07007485
7486 return muteWaitMs;
7487}
7488
Eric Laurentc75307b2015-03-17 15:29:32 -07007489status_t AudioPolicyManager::resetOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurent6a94d692014-05-20 11:18:06 -07007490 int delayMs,
7491 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07007492{
Eric Laurent6a94d692014-05-20 11:18:06 -07007493 ssize_t index;
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02007494 if (patchHandle == nullptr && !outputDesc->isRouted()) {
7495 return INVALID_OPERATION;
7496 }
Eric Laurent6a94d692014-05-20 11:18:06 -07007497 if (patchHandle) {
7498 index = mAudioPatches.indexOfKey(*patchHandle);
7499 } else {
Jean-Michel Triviff155c62016-02-26 12:07:16 -08007500 index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007501 }
7502 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07007503 return INVALID_OPERATION;
7504 }
Eric Laurent6a94d692014-05-20 11:18:06 -07007505 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007506 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07007507 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07007508 outputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
François Gaffieafd4cea2019-11-18 15:50:22 +01007509 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007510 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07007511 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07007512 return status;
7513}
7514
7515status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
François Gaffie11d30102018-11-02 16:09:09 +01007516 const sp<DeviceDescriptor> &device,
Eric Laurent6a94d692014-05-20 11:18:06 -07007517 bool force,
7518 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07007519{
7520 status_t status = NO_ERROR;
7521
Eric Laurent1f2f2232014-06-02 12:01:23 -07007522 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
François Gaffie11d30102018-11-02 16:09:09 +01007523 if ((device != nullptr) && ((device != inputDesc->getDevice()) || force)) {
7524 inputDesc->setDevice(device);
Eric Laurent1c333e22014-05-20 10:48:17 -07007525
François Gaffie11d30102018-11-02 16:09:09 +01007526 if (mAvailableInputDevices.contains(device)) {
Mikhail Naganovdc769682018-05-04 15:34:08 -07007527 PatchBuilder patchBuilder;
7528 patchBuilder.addSink(inputDesc,
Eric Laurentdaf92cc2014-07-22 15:36:10 -07007529 // AUDIO_SOURCE_HOTWORD is for internal use only:
7530 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
Mikhail Naganovdc769682018-05-04 15:34:08 -07007531 [inputDesc](const PatchBuilder::mix_usecase_t& usecase) {
7532 auto result = usecase;
7533 if (result.source == AUDIO_SOURCE_HOTWORD && !inputDesc->isSoundTrigger()) {
7534 result.source = AUDIO_SOURCE_VOICE_RECOGNITION;
7535 }
7536 return result; }).
Eric Laurent1c333e22014-05-20 10:48:17 -07007537 //only one input device for now
François Gaffie11d30102018-11-02 16:09:09 +01007538 addSource(device);
Mikhail Naganovdc769682018-05-04 15:34:08 -07007539 status = installPatch(__func__, patchHandle, inputDesc.get(), patchBuilder.patch(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07007540 }
7541 }
7542 return status;
7543}
7544
Eric Laurent6a94d692014-05-20 11:18:06 -07007545status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
7546 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07007547{
Eric Laurent1f2f2232014-06-02 12:01:23 -07007548 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07007549 ssize_t index;
7550 if (patchHandle) {
7551 index = mAudioPatches.indexOfKey(*patchHandle);
7552 } else {
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08007553 index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007554 }
7555 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07007556 return INVALID_OPERATION;
7557 }
Eric Laurent6a94d692014-05-20 11:18:06 -07007558 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007559 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07007560 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07007561 inputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
François Gaffieafd4cea2019-11-18 15:50:22 +01007562 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007563 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07007564 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07007565 return status;
7566}
7567
François Gaffie11d30102018-11-02 16:09:09 +01007568sp<IOProfile> AudioPolicyManager::getInputProfile(const sp<DeviceDescriptor> &device,
François Gaffie53615e22015-03-19 09:24:12 +01007569 uint32_t& samplingRate,
Andy Hungf129b032015-04-07 13:45:50 -07007570 audio_format_t& format,
7571 audio_channel_mask_t& channelMask,
François Gaffie53615e22015-03-19 09:24:12 +01007572 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07007573{
7574 // Choose an input profile based on the requested capture parameters: select the first available
7575 // profile supporting all requested parameters.
jiabin2fd710d2022-05-02 23:20:22 +00007576 // The flags can be ignored if it doesn't contain a much match flag.
Andy Hungf129b032015-04-07 13:45:50 -07007577 //
7578 // TODO: perhaps isCompatibleProfile should return a "matching" score so we can return
7579 // the best matching profile, not the first one.
Eric Laurente552edb2014-03-10 17:42:56 -07007580
Atneya Nair0f0a8032022-12-12 16:20:12 -08007581 using underlying_input_flag_t = std::underlying_type_t<audio_input_flags_t>;
7582 const underlying_input_flag_t mustMatchFlag = AUDIO_INPUT_FLAG_MMAP_NOIRQ |
7583 AUDIO_INPUT_FLAG_HOTWORD_TAP | AUDIO_INPUT_FLAG_HW_LOOKBACK;
7584
7585 const underlying_input_flag_t oriFlags = flags;
Glenn Kasten730b9262018-03-29 15:01:26 -07007586
jiabin2fd710d2022-05-02 23:20:22 +00007587 for (;;) {
7588 sp<IOProfile> firstInexact = nullptr;
7589 uint32_t updatedSamplingRate = 0;
7590 audio_format_t updatedFormat = AUDIO_FORMAT_INVALID;
7591 audio_channel_mask_t updatedChannelMask = AUDIO_CHANNEL_INVALID;
7592 for (const auto& hwModule : mHwModules) {
7593 for (const auto& profile : hwModule->getInputProfiles()) {
7594 // profile->log();
7595 //updatedFormat = format;
7596 if (profile->isCompatibleProfile(DeviceVector(device), samplingRate,
7597 &samplingRate /*updatedSamplingRate*/,
7598 format,
7599 &format, /*updatedFormat*/
7600 channelMask,
7601 &channelMask /*updatedChannelMask*/,
7602 // FIXME ugly cast
7603 (audio_output_flags_t) flags,
7604 true /*exactMatchRequiredForInputFlags*/)) {
7605 return profile;
7606 }
7607 if (firstInexact == nullptr && profile->isCompatibleProfile(DeviceVector(device),
7608 samplingRate,
7609 &updatedSamplingRate,
7610 format,
7611 &updatedFormat,
7612 channelMask,
7613 &updatedChannelMask,
7614 // FIXME ugly cast
7615 (audio_output_flags_t) flags,
7616 false /*exactMatchRequiredForInputFlags*/)) {
7617 firstInexact = profile;
7618 }
7619 }
7620 }
7621
7622 if (firstInexact != nullptr) {
7623 samplingRate = updatedSamplingRate;
7624 format = updatedFormat;
7625 channelMask = updatedChannelMask;
7626 return firstInexact;
7627 } else if (flags & AUDIO_INPUT_FLAG_RAW) {
7628 flags = (audio_input_flags_t) (flags & ~AUDIO_INPUT_FLAG_RAW); // retry
7629 } else if ((flags & mustMatchFlag) == AUDIO_INPUT_FLAG_NONE &&
7630 flags != AUDIO_INPUT_FLAG_NONE && audio_is_linear_pcm(format)) {
7631 flags = AUDIO_INPUT_FLAG_NONE;
7632 } else { // fail
7633 ALOGW("%s could not find profile for device %s, sampling rate %u, format %#x, "
7634 "channel mask 0x%X, flags %#x", __func__, device->toString().c_str(),
7635 samplingRate, format, channelMask, oriFlags);
7636 break;
Eric Laurente552edb2014-03-10 17:42:56 -07007637 }
7638 }
jiabin2fd710d2022-05-02 23:20:22 +00007639
7640 return nullptr;
Eric Laurente552edb2014-03-10 17:42:56 -07007641}
7642
François Gaffieaaac0fd2018-11-22 17:56:39 +01007643float AudioPolicyManager::computeVolume(IVolumeCurves &curves,
7644 VolumeSource volumeSource,
François Gaffied1ab2bd2015-12-02 18:20:06 +01007645 int index,
jiabin9a3361e2019-10-01 09:38:30 -07007646 const DeviceTypeSet& deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07007647{
jiabin9a3361e2019-10-01 09:38:30 -07007648 float volumeDb = curves.volIndexToDb(Volume::getDeviceCategory(deviceTypes), index);
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07007649
7650 // handle the case of accessibility active while a ringtone is playing: if the ringtone is much
7651 // louder than the accessibility prompt, the prompt cannot be heard, thus masking the touch
7652 // exploration of the dialer UI. In this situation, bring the accessibility volume closer to
7653 // the ringtone volume
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007654 const auto callVolumeSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL, false);
7655 const auto ringVolumeSrc = toVolumeSource(AUDIO_STREAM_RING, false);
7656 const auto musicVolumeSrc = toVolumeSource(AUDIO_STREAM_MUSIC, false);
7657 const auto alarmVolumeSrc = toVolumeSource(AUDIO_STREAM_ALARM, false);
7658 const auto a11yVolumeSrc = toVolumeSource(AUDIO_STREAM_ACCESSIBILITY, false);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007659
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07007660 if (volumeSource == a11yVolumeSrc
François Gaffieaaac0fd2018-11-22 17:56:39 +01007661 && (AUDIO_MODE_RINGTONE == mEngine->getPhoneState()) &&
7662 mOutputs.isActive(ringVolumeSrc, 0)) {
7663 auto &ringCurves = getVolumeCurves(AUDIO_STREAM_RING);
jiabin9a3361e2019-10-01 09:38:30 -07007664 const float ringVolumeDb = computeVolume(ringCurves, ringVolumeSrc, index, deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007665 return ringVolumeDb - 4 > volumeDb ? ringVolumeDb - 4 : volumeDb;
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07007666 }
7667
Eric Laurentdcd4ab12018-06-29 17:45:13 -07007668 // in-call: always cap volume by voice volume + some low headroom
François Gaffieaaac0fd2018-11-22 17:56:39 +01007669 if ((volumeSource != callVolumeSrc && (isInCall() ||
7670 mOutputs.isActiveLocally(callVolumeSrc))) &&
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007671 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM, false) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01007672 volumeSource == ringVolumeSrc || volumeSource == musicVolumeSrc ||
7673 volumeSource == alarmVolumeSrc ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007674 volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION, false) ||
7675 volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false) ||
7676 volumeSource == toVolumeSource(AUDIO_STREAM_DTMF, false) ||
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07007677 volumeSource == a11yVolumeSrc)) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007678 auto &voiceCurves = getVolumeCurves(callVolumeSrc);
jiabin9a3361e2019-10-01 09:38:30 -07007679 int voiceVolumeIndex = voiceCurves.getVolumeIndex(deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007680 const float maxVoiceVolDb =
jiabin9a3361e2019-10-01 09:38:30 -07007681 computeVolume(voiceCurves, callVolumeSrc, voiceVolumeIndex, deviceTypes)
Eric Laurent7731b5a2018-04-06 15:47:22 -07007682 + IN_CALL_EARPIECE_HEADROOM_DB;
Abhijith Shastry329ddab2019-04-23 11:53:26 -07007683 // FIXME: Workaround for call screening applications until a proper audio mode is defined
7684 // to support this scenario : Exempt the RING stream from the audio cap if the audio was
7685 // programmatically muted.
7686 // VOICE_CALL stream has minVolumeIndex > 0 : Users cannot set the volume of voice calls to
7687 // 0. We don't want to cap volume when the system has programmatically muted the voice call
7688 // stream. See setVolumeCurveIndex() for more information.
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07007689 bool exemptFromCapping =
7690 ((volumeSource == ringVolumeSrc) || (volumeSource == a11yVolumeSrc))
7691 && (voiceVolumeIndex == 0);
Abhijith Shastry329ddab2019-04-23 11:53:26 -07007692 ALOGV_IF(exemptFromCapping, "%s volume source %d at vol=%f not capped", __func__,
7693 volumeSource, volumeDb);
7694 if ((volumeDb > maxVoiceVolDb) && !exemptFromCapping) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007695 ALOGV("%s volume source %d at vol=%f overriden by volume group %d at vol=%f", __func__,
7696 volumeSource, volumeDb, callVolumeSrc, maxVoiceVolDb);
7697 volumeDb = maxVoiceVolDb;
Jean-Michel Trivi719a9872017-08-05 13:51:35 -07007698 }
7699 }
Eric Laurente552edb2014-03-10 17:42:56 -07007700 // if a headset is connected, apply the following rules to ring tones and notifications
7701 // to avoid sound level bursts in user's ears:
Eric Laurent6af1c1d2016-04-14 11:20:44 -07007702 // - always attenuate notifications volume by 6dB
7703 // - attenuate ring tones volume by 6dB unless music is not playing and
7704 // speaker is part of the select devices
Eric Laurente552edb2014-03-10 17:42:56 -07007705 // - if music is playing, always limit the volume to current music volume,
7706 // with a minimum threshold at -36dB so that notification is always perceived.
jiabin9a3361e2019-10-01 09:38:30 -07007707 if (!Intersection(deviceTypes,
7708 {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP, AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES,
7709 AUDIO_DEVICE_OUT_WIRED_HEADSET, AUDIO_DEVICE_OUT_WIRED_HEADPHONE,
Eric Laurentc42df452020-08-07 10:51:53 -07007710 AUDIO_DEVICE_OUT_USB_HEADSET, AUDIO_DEVICE_OUT_HEARING_AID,
7711 AUDIO_DEVICE_OUT_BLE_HEADSET}).empty() &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01007712 ((volumeSource == alarmVolumeSrc ||
7713 volumeSource == ringVolumeSrc) ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007714 (volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION, false)) ||
7715 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM, false)) ||
7716 ((volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false)) &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01007717 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) &&
7718 curves.canBeMuted()) {
7719
Eric Laurente552edb2014-03-10 17:42:56 -07007720 // when the phone is ringing we must consider that music could have been paused just before
7721 // by the music application and behave as if music was active if the last music track was
7722 // just stopped
Eric Laurent3b73df72014-03-11 09:06:29 -07007723 if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY) ||
Eric Laurente552edb2014-03-10 17:42:56 -07007724 mLimitRingtoneVolume) {
François Gaffie43c73442018-11-08 08:21:55 +01007725 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
jiabin9a3361e2019-10-01 09:38:30 -07007726 DeviceTypeSet musicDevice =
François Gaffiec005e562018-11-06 15:04:49 +01007727 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
7728 nullptr, true /*fromCache*/).types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01007729 auto &musicCurves = getVolumeCurves(AUDIO_STREAM_MUSIC);
jiabin9a3361e2019-10-01 09:38:30 -07007730 float musicVolDb = computeVolume(musicCurves,
7731 musicVolumeSrc,
7732 musicCurves.getVolumeIndex(musicDevice),
7733 musicDevice);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007734 float minVolDb = (musicVolDb > SONIFICATION_HEADSET_VOLUME_MIN_DB) ?
7735 musicVolDb : SONIFICATION_HEADSET_VOLUME_MIN_DB;
7736 if (volumeDb > minVolDb) {
7737 volumeDb = minVolDb;
7738 ALOGV("computeVolume limiting volume to %f musicVol %f", minVolDb, musicVolDb);
Eric Laurente552edb2014-03-10 17:42:56 -07007739 }
Eric Laurent7b6385c2021-05-12 17:55:36 +02007740 if (Volume::getDeviceForVolume(deviceTypes) != AUDIO_DEVICE_OUT_SPEAKER
7741 && !Intersection(deviceTypes, {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP,
7742 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES}).empty()) {
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07007743 // on A2DP, also ensure notification volume is not too low compared to media when
7744 // intended to be played
François Gaffie43c73442018-11-08 08:21:55 +01007745 if ((volumeDb > -96.0f) &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01007746 (musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB > volumeDb)) {
jiabin9a3361e2019-10-01 09:38:30 -07007747 ALOGV("%s increasing volume for volume source=%d device=%s from %f to %f",
7748 __func__, volumeSource, dumpDeviceTypes(deviceTypes).c_str(), volumeDb,
François Gaffieaaac0fd2018-11-22 17:56:39 +01007749 musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB);
7750 volumeDb = musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB;
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07007751 }
7752 }
jiabin9a3361e2019-10-01 09:38:30 -07007753 } else if ((Volume::getDeviceForVolume(deviceTypes) != AUDIO_DEVICE_OUT_SPEAKER) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01007754 (!(volumeSource == alarmVolumeSrc || volumeSource == ringVolumeSrc))) {
François Gaffie43c73442018-11-08 08:21:55 +01007755 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07007756 }
7757 }
7758
François Gaffie43c73442018-11-08 08:21:55 +01007759 return volumeDb;
Eric Laurente552edb2014-03-10 17:42:56 -07007760}
7761
Eric Laurent3839bc02018-07-10 18:33:34 -07007762int AudioPolicyManager::rescaleVolumeIndex(int srcIndex,
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01007763 VolumeSource fromVolumeSource,
7764 VolumeSource toVolumeSource)
Eric Laurent3839bc02018-07-10 18:33:34 -07007765{
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01007766 if (fromVolumeSource == toVolumeSource) {
Eric Laurent3839bc02018-07-10 18:33:34 -07007767 return srcIndex;
7768 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01007769 auto &srcCurves = getVolumeCurves(fromVolumeSource);
7770 auto &dstCurves = getVolumeCurves(toVolumeSource);
Eric Laurentf5aa58d2019-02-22 18:20:11 -08007771 float minSrc = (float)srcCurves.getVolumeIndexMin();
7772 float maxSrc = (float)srcCurves.getVolumeIndexMax();
7773 float minDst = (float)dstCurves.getVolumeIndexMin();
7774 float maxDst = (float)dstCurves.getVolumeIndexMax();
Eric Laurent3839bc02018-07-10 18:33:34 -07007775
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08007776 // preserve mute request or correct range
7777 if (srcIndex < minSrc) {
7778 if (srcIndex == 0) {
7779 return 0;
7780 }
7781 srcIndex = minSrc;
7782 } else if (srcIndex > maxSrc) {
7783 srcIndex = maxSrc;
7784 }
Eric Laurent3839bc02018-07-10 18:33:34 -07007785 return (int)(minDst + ((srcIndex - minSrc) * (maxDst - minDst)) / (maxSrc - minSrc));
7786}
7787
François Gaffieaaac0fd2018-11-22 17:56:39 +01007788status_t AudioPolicyManager::checkAndSetVolume(IVolumeCurves &curves,
7789 VolumeSource volumeSource,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08007790 int index,
7791 const sp<AudioOutputDescriptor>& outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07007792 DeviceTypeSet deviceTypes,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08007793 int delayMs,
7794 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07007795{
François Gaffieaaac0fd2018-11-22 17:56:39 +01007796 // do not change actual attributes volume if the attributes is muted
7797 if (outputDesc->isMuted(volumeSource)) {
7798 ALOGVV("%s: volume source %d muted count %d active=%d", __func__, volumeSource,
7799 outputDesc->getMuteCount(volumeSource), outputDesc->isActive(volumeSource));
Eric Laurente552edb2014-03-10 17:42:56 -07007800 return NO_ERROR;
7801 }
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007802 VolumeSource callVolSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL, false);
7803 VolumeSource btScoVolSrc = toVolumeSource(AUDIO_STREAM_BLUETOOTH_SCO, false);
7804 bool isVoiceVolSrc = (volumeSource != VOLUME_SOURCE_NONE) && (callVolSrc == volumeSource);
7805 bool isBtScoVolSrc = (volumeSource != VOLUME_SOURCE_NONE) && (btScoVolSrc == volumeSource);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007806
Eric Laurent2517af32020-11-25 15:31:27 +01007807 bool isScoRequested = isScoRequestedForComm();
Eric Laurent1a8b45f2022-04-13 16:01:47 +02007808 bool isHAUsed = isHearingAidUsedForComm();
7809
Eric Laurente552edb2014-03-10 17:42:56 -07007810 // do not change in call volume if bluetooth is connected and vice versa
François Gaffieaaac0fd2018-11-22 17:56:39 +01007811 // if sco and call follow same curves, bypass forceUseForComm
7812 if ((callVolSrc != btScoVolSrc) &&
Eric Laurent2517af32020-11-25 15:31:27 +01007813 ((isVoiceVolSrc && isScoRequested) ||
Beibeif660a512023-02-28 17:00:34 +08007814 (isBtScoVolSrc && !(isScoRequested || isHAUsed))) &&
7815 !isSingleDeviceType(deviceTypes, AUDIO_DEVICE_OUT_TELEPHONY_TX)) {
Eric Laurent2517af32020-11-25 15:31:27 +01007816 ALOGV("%s cannot set volume group %d volume when is%srequested for comm", __func__,
Eric Laurent1a8b45f2022-04-13 16:01:47 +02007817 volumeSource, isScoRequested ? " " : " not ");
Eric Laurent571ef962020-07-24 11:43:48 -07007818 // Do not return an error here as AudioService will always set both voice call
7819 // and bluetooth SCO volumes due to stream aliasing.
7820 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07007821 }
jiabin9a3361e2019-10-01 09:38:30 -07007822 if (deviceTypes.empty()) {
7823 deviceTypes = outputDesc->devices().types();
Eric Laurentc75307b2015-03-17 15:29:32 -07007824 }
Eric Laurent275e8e92014-11-30 15:14:47 -08007825
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00007826 if (curves.getVolumeIndexMin() < 0 || curves.getVolumeIndexMax() < 0) {
7827 ALOGE("invalid volume index range");
7828 return BAD_VALUE;
7829 }
7830
jiabin9a3361e2019-10-01 09:38:30 -07007831 float volumeDb = computeVolume(curves, volumeSource, index, deviceTypes);
7832 if (outputDesc->isFixedVolume(deviceTypes) ||
Eric Laurent9698a4c2020-10-12 17:10:23 -07007833 // Force VoIP volume to max for bluetooth SCO device except if muted
7834 (index != 0 && (isVoiceVolSrc || isBtScoVolSrc) &&
jiabin9a3361e2019-10-01 09:38:30 -07007835 isSingleDeviceType(deviceTypes, audio_is_bluetooth_out_sco_device))) {
Eric Laurentffbc80f2015-03-18 18:30:19 -07007836 volumeDb = 0.0f;
Eric Laurent275e8e92014-11-30 15:14:47 -08007837 }
Francois Gaffie593634d2021-06-22 13:31:31 +02007838 const bool muted = (index == 0) && (volumeDb != 0.0f);
jiabin9a3361e2019-10-01 09:38:30 -07007839 outputDesc->setVolume(
Francois Gaffie593634d2021-06-22 13:31:31 +02007840 volumeDb, muted, volumeSource, curves.getStreamTypes(), deviceTypes, delayMs, force);
Eric Laurentc75307b2015-03-17 15:29:32 -07007841
Eric Laurente8f2c0f2021-08-17 11:17:19 +02007842 if (outputDesc == mPrimaryOutput && (isVoiceVolSrc || isBtScoVolSrc)) {
Eric Laurente552edb2014-03-10 17:42:56 -07007843 float voiceVolume;
Eric Laurentfad001d2019-06-11 19:17:57 -07007844 // 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 +01007845 if (isVoiceVolSrc) {
7846 voiceVolume = (float)index/(float)curves.getVolumeIndexMax();
Eric Laurente552edb2014-03-10 17:42:56 -07007847 } else {
Eric Laurentfad001d2019-06-11 19:17:57 -07007848 voiceVolume = index == 0 ? 0.0 : 1.0;
Eric Laurente552edb2014-03-10 17:42:56 -07007849 }
Eric Laurent18fba842016-03-31 14:41:26 -07007850 if (voiceVolume != mLastVoiceVolume) {
Eric Laurente552edb2014-03-10 17:42:56 -07007851 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
7852 mLastVoiceVolume = voiceVolume;
7853 }
7854 }
Eric Laurente552edb2014-03-10 17:42:56 -07007855 return NO_ERROR;
7856}
7857
Eric Laurentc75307b2015-03-17 15:29:32 -07007858void AudioPolicyManager::applyStreamVolumes(const sp<AudioOutputDescriptor>& outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07007859 const DeviceTypeSet& deviceTypes,
7860 int delayMs,
7861 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07007862{
jiabincd510522020-01-22 09:40:55 -08007863 ALOGVV("applyStreamVolumes() for device %s", dumpDeviceTypes(deviceTypes).c_str());
François Gaffieaaac0fd2018-11-22 17:56:39 +01007864 for (const auto &volumeGroup : mEngine->getVolumeGroups()) {
7865 auto &curves = getVolumeCurves(toVolumeSource(volumeGroup));
7866 checkAndSetVolume(curves, toVolumeSource(volumeGroup),
jiabin9a3361e2019-10-01 09:38:30 -07007867 curves.getVolumeIndex(deviceTypes),
7868 outputDesc, deviceTypes, delayMs, force);
Eric Laurente552edb2014-03-10 17:42:56 -07007869 }
7870}
7871
François Gaffiec005e562018-11-06 15:04:49 +01007872void AudioPolicyManager::setStrategyMute(product_strategy_t strategy,
7873 bool on,
7874 const sp<AudioOutputDescriptor>& outputDesc,
7875 int delayMs,
jiabin9a3361e2019-10-01 09:38:30 -07007876 DeviceTypeSet deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07007877{
François Gaffieaaac0fd2018-11-22 17:56:39 +01007878 std::vector<VolumeSource> sourcesToMute;
7879 for (auto attributes: mEngine->getAllAttributesForProductStrategy(strategy)) {
7880 ALOGVV("%s() attributes %s, mute %d, output ID %d", __func__,
7881 toString(attributes).c_str(), on, outputDesc->getId());
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007882 VolumeSource source = toVolumeSource(attributes, false);
7883 if ((source != VOLUME_SOURCE_NONE) &&
7884 (std::find(begin(sourcesToMute), end(sourcesToMute), source)
7885 == end(sourcesToMute))) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007886 sourcesToMute.push_back(source);
7887 }
Eric Laurente552edb2014-03-10 17:42:56 -07007888 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01007889 for (auto source : sourcesToMute) {
jiabin9a3361e2019-10-01 09:38:30 -07007890 setVolumeSourceMute(source, on, outputDesc, delayMs, deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007891 }
7892
Eric Laurente552edb2014-03-10 17:42:56 -07007893}
7894
François Gaffieaaac0fd2018-11-22 17:56:39 +01007895void AudioPolicyManager::setVolumeSourceMute(VolumeSource volumeSource,
7896 bool on,
7897 const sp<AudioOutputDescriptor>& outputDesc,
7898 int delayMs,
jiabin9a3361e2019-10-01 09:38:30 -07007899 DeviceTypeSet deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07007900{
jiabin9a3361e2019-10-01 09:38:30 -07007901 if (deviceTypes.empty()) {
7902 deviceTypes = outputDesc->devices().types();
Eric Laurente552edb2014-03-10 17:42:56 -07007903 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01007904 auto &curves = getVolumeCurves(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07007905 if (on) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007906 if (!outputDesc->isMuted(volumeSource)) {
Eric Laurentf5aa58d2019-02-22 18:20:11 -08007907 if (curves.canBeMuted() &&
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007908 (volumeSource != toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01007909 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) ==
7910 AUDIO_POLICY_FORCE_NONE))) {
jiabin9a3361e2019-10-01 09:38:30 -07007911 checkAndSetVolume(curves, volumeSource, 0, outputDesc, deviceTypes, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07007912 }
7913 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01007914 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not
7915 // ignored
7916 outputDesc->incMuteCount(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07007917 } else {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007918 if (!outputDesc->isMuted(volumeSource)) {
7919 ALOGV("%s unmuting non muted attributes!", __func__);
Eric Laurente552edb2014-03-10 17:42:56 -07007920 return;
7921 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01007922 if (outputDesc->decMuteCount(volumeSource) == 0) {
7923 checkAndSetVolume(curves, volumeSource,
jiabin9a3361e2019-10-01 09:38:30 -07007924 curves.getVolumeIndex(deviceTypes),
Eric Laurentc75307b2015-03-17 15:29:32 -07007925 outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07007926 deviceTypes,
Eric Laurente552edb2014-03-10 17:42:56 -07007927 delayMs);
7928 }
7929 }
7930}
7931
François Gaffie53615e22015-03-19 09:24:12 +01007932bool AudioPolicyManager::isValidAttributes(const audio_attributes_t *paa)
7933{
François Gaffiec005e562018-11-06 15:04:49 +01007934 // has flags that map to a stream type?
Eric Laurente83b55d2014-11-14 10:06:21 -08007935 if ((paa->flags & (AUDIO_FLAG_AUDIBILITY_ENFORCED | AUDIO_FLAG_SCO | AUDIO_FLAG_BEACON)) != 0) {
7936 return true;
7937 }
7938
7939 // has known usage?
7940 switch (paa->usage) {
7941 case AUDIO_USAGE_UNKNOWN:
7942 case AUDIO_USAGE_MEDIA:
7943 case AUDIO_USAGE_VOICE_COMMUNICATION:
7944 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
7945 case AUDIO_USAGE_ALARM:
7946 case AUDIO_USAGE_NOTIFICATION:
7947 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
7948 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
7949 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
7950 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
7951 case AUDIO_USAGE_NOTIFICATION_EVENT:
7952 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
7953 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
7954 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
7955 case AUDIO_USAGE_GAME:
Eric Laurent275e8e92014-11-30 15:14:47 -08007956 case AUDIO_USAGE_VIRTUAL_SOURCE:
Jean-Michel Trivi36867762016-12-29 12:03:28 -08007957 case AUDIO_USAGE_ASSISTANT:
Eric Laurent21777f82019-12-06 18:12:06 -08007958 case AUDIO_USAGE_CALL_ASSISTANT:
Hayden Gomes524159d2019-12-23 14:41:47 -08007959 case AUDIO_USAGE_EMERGENCY:
7960 case AUDIO_USAGE_SAFETY:
7961 case AUDIO_USAGE_VEHICLE_STATUS:
7962 case AUDIO_USAGE_ANNOUNCEMENT:
Eric Laurente83b55d2014-11-14 10:06:21 -08007963 break;
7964 default:
7965 return false;
7966 }
7967 return true;
7968}
7969
François Gaffie2110e042015-03-24 08:41:51 +01007970audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
7971{
7972 return mEngine->getForceUse(usage);
7973}
7974
Eric Laurent96d1dda2022-03-14 17:14:19 +01007975bool AudioPolicyManager::isInCall() const {
François Gaffie2110e042015-03-24 08:41:51 +01007976 return isStateInCall(mEngine->getPhoneState());
7977}
7978
Eric Laurent96d1dda2022-03-14 17:14:19 +01007979bool AudioPolicyManager::isStateInCall(int state) const {
François Gaffie2110e042015-03-24 08:41:51 +01007980 return is_state_in_call(state);
7981}
7982
Eric Laurentf9cccec2022-11-16 19:12:00 +01007983bool AudioPolicyManager::isCallAudioAccessible() const {
Eric Laurent74b71512019-11-06 17:21:57 -08007984 audio_mode_t mode = mEngine->getPhoneState();
7985 return (mode == AUDIO_MODE_IN_CALL)
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01007986 || (mode == AUDIO_MODE_CALL_SCREEN)
7987 || (mode == AUDIO_MODE_CALL_REDIRECT);
Eric Laurent74b71512019-11-06 17:21:57 -08007988}
7989
Eric Laurentf9cccec2022-11-16 19:12:00 +01007990bool AudioPolicyManager::isInCallOrScreening() const {
7991 audio_mode_t mode = mEngine->getPhoneState();
7992 return isStateInCall(mode) || mode == AUDIO_MODE_CALL_SCREEN;
7993}
7994
Eric Laurentd60560a2015-04-10 11:31:20 -07007995void AudioPolicyManager::cleanUpForDevice(const sp<DeviceDescriptor>& deviceDesc)
7996{
7997 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07007998 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02007999 if (sourceDesc->isConnected() && (sourceDesc->srcDevice()->equals(deviceDesc) ||
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02008000 sourceDesc->sinkDevice()->equals(deviceDesc))
8001 && !isCallRxAudioSource(sourceDesc)) {
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008002 disconnectAudioSource(sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07008003 }
8004 }
8005
8006 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
8007 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
8008 bool release = false;
8009 for (size_t j = 0; j < patchDesc->mPatch.num_sources && !release; j++) {
8010 const struct audio_port_config *source = &patchDesc->mPatch.sources[j];
8011 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
8012 source->ext.device.type == deviceDesc->type()) {
8013 release = true;
8014 }
8015 }
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008016 const char *address = deviceDesc->address().c_str();
Eric Laurentd60560a2015-04-10 11:31:20 -07008017 for (size_t j = 0; j < patchDesc->mPatch.num_sinks && !release; j++) {
8018 const struct audio_port_config *sink = &patchDesc->mPatch.sinks[j];
8019 if (sink->type == AUDIO_PORT_TYPE_DEVICE &&
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008020 sink->ext.device.type == deviceDesc->type() &&
8021 (strnlen(address, AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0
8022 || strncmp(sink->ext.device.address, address,
8023 AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0)) {
Eric Laurentd60560a2015-04-10 11:31:20 -07008024 release = true;
8025 }
8026 }
8027 if (release) {
François Gaffieafd4cea2019-11-18 15:50:22 +01008028 ALOGV("%s releasing patch %u", __FUNCTION__, patchDesc->getHandle());
8029 releaseAudioPatch(patchDesc->getHandle(), patchDesc->getUid());
Eric Laurentd60560a2015-04-10 11:31:20 -07008030 }
8031 }
Francois Gaffie716e1432019-01-14 16:58:59 +01008032
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01008033 mInputs.clearSessionRoutesForDevice(deviceDesc);
8034
Francois Gaffie716e1432019-01-14 16:58:59 +01008035 mHwModules.cleanUpForDevice(deviceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07008036}
8037
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008038void AudioPolicyManager::modifySurroundFormats(
8039 const sp<DeviceDescriptor>& devDesc, FormatVector *formatsPtr) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008040 std::unordered_set<audio_format_t> enforcedSurround(
8041 devDesc->encodedFormats().begin(), devDesc->encodedFormats().end());
Mikhail Naganov100f0122018-11-29 11:22:16 -08008042 std::unordered_set<audio_format_t> allSurround; // A flat set of all known surround formats
Mikhail Naganov68e3f642023-04-28 13:06:32 -07008043 for (const auto& pair : mConfig->getSurroundFormats()) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008044 allSurround.insert(pair.first);
8045 for (const auto& subformat : pair.second) allSurround.insert(subformat);
8046 }
Phil Burk09bc4612016-02-24 15:58:15 -08008047
8048 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
8049 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Phil Burk0709b0a2016-03-31 12:54:57 -07008050 ALOGD("%s: forced use = %d", __FUNCTION__, forceUse);
Mikhail Naganov100f0122018-11-29 11:22:16 -08008051 // This is the resulting set of formats depending on the surround mode:
8052 // 'all surround' = allSurround
8053 // 'enforced surround' = enforcedSurround [may include IEC69137 which isn't raw surround fmt]
8054 // 'non-surround' = not in 'all surround' and not in 'enforced surround'
8055 // 'manual surround' = mManualSurroundFormats
8056 // AUTO: formats v 'enforced surround'
8057 // ALWAYS: formats v 'all surround' v 'enforced surround'
8058 // NEVER: formats ^ 'non-surround'
8059 // MANUAL: formats ^ ('non-surround' v 'manual surround' v (IEC69137 ^ 'enforced surround'))
Phil Burk09bc4612016-02-24 15:58:15 -08008060
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008061 std::unordered_set<audio_format_t> formatSet;
8062 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL
8063 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008064 // formatSet is (formats ^ 'non-surround')
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008065 for (auto formatIter = formatsPtr->begin(); formatIter != formatsPtr->end(); ++formatIter) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008066 if (allSurround.count(*formatIter) == 0 && enforcedSurround.count(*formatIter) == 0) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008067 formatSet.insert(*formatIter);
8068 }
8069 }
8070 } else {
8071 formatSet.insert(formatsPtr->begin(), formatsPtr->end());
8072 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08008073 formatsPtr->clear(); // Re-filled from the formatSet at the end.
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008074
jiabin81772902018-04-02 17:52:27 -07008075 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008076 formatSet.insert(mManualSurroundFormats.begin(), mManualSurroundFormats.end());
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008077 // Enable IEC61937 when in MANUAL mode if it's enforced for this device.
8078 if (enforcedSurround.count(AUDIO_FORMAT_IEC61937) != 0) {
8079 formatSet.insert(AUDIO_FORMAT_IEC61937);
Phil Burk09bc4612016-02-24 15:58:15 -08008080 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08008081 } else if (forceUse != AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) { // AUTO or ALWAYS
8082 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS) {
8083 formatSet.insert(allSurround.begin(), allSurround.end());
Phil Burk07ac1142016-03-25 13:39:29 -07008084 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08008085 formatSet.insert(enforcedSurround.begin(), enforcedSurround.end());
Phil Burk09bc4612016-02-24 15:58:15 -08008086 }
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008087 for (const auto& format : formatSet) {
jiabin06e4bab2019-07-29 10:13:34 -07008088 formatsPtr->push_back(format);
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008089 }
Phil Burk0709b0a2016-03-31 12:54:57 -07008090}
8091
jiabin06e4bab2019-07-29 10:13:34 -07008092void AudioPolicyManager::modifySurroundChannelMasks(ChannelMaskSet *channelMasksPtr) {
8093 ChannelMaskSet &channelMasks = *channelMasksPtr;
Phil Burk0709b0a2016-03-31 12:54:57 -07008094 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
8095 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
8096
8097 // If NEVER, then remove support for channelMasks > stereo.
8098 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
jiabin06e4bab2019-07-29 10:13:34 -07008099 for (auto it = channelMasks.begin(); it != channelMasks.end();) {
8100 audio_channel_mask_t channelMask = *it;
Phil Burk0709b0a2016-03-31 12:54:57 -07008101 if (channelMask & ~AUDIO_CHANNEL_OUT_STEREO) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01008102 ALOGV("%s: force NEVER, so remove channelMask 0x%08x", __FUNCTION__, channelMask);
jiabin06e4bab2019-07-29 10:13:34 -07008103 it = channelMasks.erase(it);
Phil Burk0709b0a2016-03-31 12:54:57 -07008104 } else {
jiabin06e4bab2019-07-29 10:13:34 -07008105 ++it;
Phil Burk0709b0a2016-03-31 12:54:57 -07008106 }
8107 }
jiabin81772902018-04-02 17:52:27 -07008108 // If ALWAYS or MANUAL, then make sure we at least support 5.1
8109 } else if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS
8110 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Phil Burk0709b0a2016-03-31 12:54:57 -07008111 bool supports5dot1 = false;
8112 // Are there any channel masks that can be considered "surround"?
Mikhail Naganovcf84e592017-12-07 11:25:11 -08008113 for (audio_channel_mask_t channelMask : channelMasks) {
Phil Burk0709b0a2016-03-31 12:54:57 -07008114 if ((channelMask & AUDIO_CHANNEL_OUT_5POINT1) == AUDIO_CHANNEL_OUT_5POINT1) {
8115 supports5dot1 = true;
8116 break;
8117 }
8118 }
8119 // If not then add 5.1 support.
8120 if (!supports5dot1) {
jiabin06e4bab2019-07-29 10:13:34 -07008121 channelMasks.insert(AUDIO_CHANNEL_OUT_5POINT1);
Eric Laurentfecbceb2021-02-09 14:46:43 +01008122 ALOGV("%s: force MANUAL or ALWAYS, so adding channelMask for 5.1 surround", __func__);
Phil Burk0709b0a2016-03-31 12:54:57 -07008123 }
Phil Burk09bc4612016-02-24 15:58:15 -08008124 }
8125}
8126
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008127void AudioPolicyManager::updateAudioProfiles(const sp<DeviceDescriptor>& devDesc,
Phil Burk00eeb322016-03-31 12:41:00 -07008128 audio_io_handle_t ioHandle,
François Gaffie112b0af2015-11-19 16:13:25 +01008129 AudioProfileVector &profiles)
8130{
8131 String8 reply;
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008132 audio_devices_t device = devDesc->type();
Phil Burk0709b0a2016-03-31 12:54:57 -07008133
François Gaffie112b0af2015-11-19 16:13:25 +01008134 // Format MUST be checked first to update the list of AudioProfile
8135 if (profiles.hasDynamicFormat()) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07008136 reply = mpClientInterface->getParameters(
8137 ioHandle, String8(AudioParameter::keyStreamSupportedFormats));
jiabin81772902018-04-02 17:52:27 -07008138 ALOGV("%s: supported formats %d, %s", __FUNCTION__, ioHandle, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08008139 AudioParameter repliedParameters(reply);
jiabinf26596b2023-04-12 18:56:39 +00008140 FormatVector formats;
Eric Laurent62e4bc52016-02-02 18:37:28 -08008141 if (repliedParameters.get(
jiabinf26596b2023-04-12 18:56:39 +00008142 String8(AudioParameter::keyStreamSupportedFormats), reply) == NO_ERROR) {
8143 formats = formatsFromString(reply.string());
8144 } else if (devDesc->hasValidAudioProfile()) {
8145 ALOGD("%s: using the device profiles", __func__);
8146 formats = devDesc->getAudioProfiles().getSupportedFormats();
8147 } else {
8148 ALOGE("%s: failed to retrieve format, bailing out", __func__);
François Gaffie112b0af2015-11-19 16:13:25 +01008149 return;
8150 }
Kriti Dangef6be8f2020-11-05 11:58:19 +01008151 mReportedFormatsMap[devDesc] = formats;
Mikhail Naganov100f0122018-11-29 11:22:16 -08008152 if (device == AUDIO_DEVICE_OUT_HDMI
8153 || isDeviceOfModule(devDesc, AUDIO_HARDWARE_MODULE_ID_MSD)) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008154 modifySurroundFormats(devDesc, &formats);
Phil Burk00eeb322016-03-31 12:41:00 -07008155 }
jiabin3e277cc2019-09-10 14:27:34 -07008156 addProfilesForFormats(profiles, formats);
François Gaffie112b0af2015-11-19 16:13:25 +01008157 }
François Gaffie112b0af2015-11-19 16:13:25 +01008158
Mikhail Naganovcf84e592017-12-07 11:25:11 -08008159 for (audio_format_t format : profiles.getSupportedFormats()) {
jiabinf26596b2023-04-12 18:56:39 +00008160 std::optional<ChannelMaskSet> channelMasks;
jiabin06e4bab2019-07-29 10:13:34 -07008161 SampleRateSet samplingRates;
François Gaffie112b0af2015-11-19 16:13:25 +01008162 AudioParameter requestedParameters;
Mikhail Naganov388360c2016-10-17 17:09:41 -07008163 requestedParameters.addInt(String8(AudioParameter::keyFormat), format);
François Gaffie112b0af2015-11-19 16:13:25 +01008164
8165 if (profiles.hasDynamicRateFor(format)) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07008166 reply = mpClientInterface->getParameters(
8167 ioHandle,
8168 requestedParameters.toString() + ";" +
8169 AudioParameter::keyStreamSupportedSamplingRates);
François Gaffie112b0af2015-11-19 16:13:25 +01008170 ALOGV("%s: supported sampling rates %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08008171 AudioParameter repliedParameters(reply);
8172 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07008173 String8(AudioParameter::keyStreamSupportedSamplingRates), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08008174 samplingRates = samplingRatesFromString(reply.string());
jiabinf26596b2023-04-12 18:56:39 +00008175 } else {
8176 samplingRates = devDesc->getAudioProfiles().getSampleRatesFor(format);
François Gaffie112b0af2015-11-19 16:13:25 +01008177 }
8178 }
8179 if (profiles.hasDynamicChannelsFor(format)) {
8180 reply = mpClientInterface->getParameters(ioHandle,
8181 requestedParameters.toString() + ";" +
Mikhail Naganov388360c2016-10-17 17:09:41 -07008182 AudioParameter::keyStreamSupportedChannels);
François Gaffie112b0af2015-11-19 16:13:25 +01008183 ALOGV("%s: supported channel masks %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08008184 AudioParameter repliedParameters(reply);
8185 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07008186 String8(AudioParameter::keyStreamSupportedChannels), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08008187 channelMasks = channelMasksFromString(reply.string());
jiabinf26596b2023-04-12 18:56:39 +00008188 } else {
8189 channelMasks = devDesc->getAudioProfiles().getChannelMasksFor(format);
8190 }
8191 if (channelMasks.has_value() && (device == AUDIO_DEVICE_OUT_HDMI
8192 || isDeviceOfModule(devDesc, AUDIO_HARDWARE_MODULE_ID_MSD))) {
8193 modifySurroundChannelMasks(&channelMasks.value());
François Gaffie112b0af2015-11-19 16:13:25 +01008194 }
8195 }
jiabin3e277cc2019-09-10 14:27:34 -07008196 addDynamicAudioProfileAndSort(
jiabinf26596b2023-04-12 18:56:39 +00008197 profiles, new AudioProfile(
8198 format, channelMasks.value_or(ChannelMaskSet()), samplingRates));
François Gaffie112b0af2015-11-19 16:13:25 +01008199 }
8200}
Eric Laurentd60560a2015-04-10 11:31:20 -07008201
Mikhail Naganovdc769682018-05-04 15:34:08 -07008202status_t AudioPolicyManager::installPatch(const char *caller,
8203 audio_patch_handle_t *patchHandle,
8204 AudioIODescriptorInterface *ioDescriptor,
8205 const struct audio_patch *patch,
8206 int delayMs)
8207{
8208 ssize_t index = mAudioPatches.indexOfKey(
8209 patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE ?
8210 *patchHandle : ioDescriptor->getPatchHandle());
8211 sp<AudioPatch> patchDesc;
8212 status_t status = installPatch(
8213 caller, index, patchHandle, patch, delayMs, mUidCached, &patchDesc);
8214 if (status == NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01008215 ioDescriptor->setPatchHandle(patchDesc->getHandle());
Mikhail Naganovdc769682018-05-04 15:34:08 -07008216 }
8217 return status;
8218}
8219
8220status_t AudioPolicyManager::installPatch(const char *caller,
8221 ssize_t index,
8222 audio_patch_handle_t *patchHandle,
8223 const struct audio_patch *patch,
8224 int delayMs,
8225 uid_t uid,
8226 sp<AudioPatch> *patchDescPtr)
8227{
8228 sp<AudioPatch> patchDesc;
8229 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
8230 if (index >= 0) {
8231 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01008232 afPatchHandle = patchDesc->getAfHandle();
Mikhail Naganovdc769682018-05-04 15:34:08 -07008233 }
8234
8235 status_t status = mpClientInterface->createAudioPatch(patch, &afPatchHandle, delayMs);
8236 ALOGV("%s() AF::createAudioPatch returned %d patchHandle %d num_sources %d num_sinks %d",
8237 caller, status, afPatchHandle, patch->num_sources, patch->num_sinks);
8238 if (status == NO_ERROR) {
8239 if (index < 0) {
8240 patchDesc = new AudioPatch(patch, uid);
François Gaffieafd4cea2019-11-18 15:50:22 +01008241 addAudioPatch(patchDesc->getHandle(), patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07008242 } else {
8243 patchDesc->mPatch = *patch;
8244 }
François Gaffieafd4cea2019-11-18 15:50:22 +01008245 patchDesc->setAfHandle(afPatchHandle);
Mikhail Naganovdc769682018-05-04 15:34:08 -07008246 if (patchHandle) {
François Gaffieafd4cea2019-11-18 15:50:22 +01008247 *patchHandle = patchDesc->getHandle();
Mikhail Naganovdc769682018-05-04 15:34:08 -07008248 }
8249 nextAudioPortGeneration();
8250 mpClientInterface->onAudioPatchListUpdate();
8251 }
8252 if (patchDescPtr) *patchDescPtr = patchDesc;
8253 return status;
8254}
8255
jiabinbce0c1d2020-10-05 11:20:18 -07008256bool AudioPolicyManager::areAllActiveTracksRerouted(const sp<SwAudioOutputDescriptor>& output)
8257{
8258 const TrackClientVector activeClients = output->getActiveClients();
8259 if (activeClients.empty()) {
8260 return true;
8261 }
8262 ssize_t index = mAudioPatches.indexOfKey(output->getPatchHandle());
8263 if (index < 0) {
8264 ALOGE("%s, no audio patch found while there are active clients on output %d",
8265 __func__, output->getId());
8266 return false;
8267 }
8268 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
8269 DeviceVector routedDevices;
8270 for (int i = 0; i < patchDesc->mPatch.num_sinks; ++i) {
8271 sp<DeviceDescriptor> device = mAvailableOutputDevices.getDeviceFromId(
8272 patchDesc->mPatch.sinks[i].id);
8273 if (device == nullptr) {
8274 ALOGE("%s, no audio device found with id(%d)",
8275 __func__, patchDesc->mPatch.sinks[i].id);
8276 return false;
8277 }
8278 routedDevices.add(device);
8279 }
8280 for (const auto& client : activeClients) {
jiabin49256852022-03-09 11:21:35 -08008281 if (client->isInvalid()) {
8282 // No need to take care about invalidated clients.
8283 continue;
8284 }
jiabinbce0c1d2020-10-05 11:20:18 -07008285 sp<DeviceDescriptor> preferredDevice =
8286 mAvailableOutputDevices.getDeviceFromId(client->preferredDeviceId());
8287 if (mEngine->getOutputDevicesForAttributes(
8288 client->attributes(), preferredDevice, false) == routedDevices) {
8289 return false;
8290 }
8291 }
8292 return true;
8293}
8294
8295sp<SwAudioOutputDescriptor> AudioPolicyManager::openOutputWithProfileAndDevice(
Eric Laurentb4f42a92022-01-17 17:37:31 +01008296 const sp<IOProfile>& profile, const DeviceVector& devices,
jiabina84c3d32022-12-02 18:59:55 +00008297 const audio_config_base_t *mixerConfig, const audio_config_t *halConfig,
8298 audio_output_flags_t flags)
jiabinbce0c1d2020-10-05 11:20:18 -07008299{
8300 for (const auto& device : devices) {
8301 // TODO: This should be checking if the profile supports the device combo.
8302 if (!profile->supportsDevice(device)) {
jiabina84c3d32022-12-02 18:59:55 +00008303 ALOGE("%s profile(%s) doesn't support device %#x", __func__, profile->getName().c_str(),
8304 device->type());
jiabinbce0c1d2020-10-05 11:20:18 -07008305 return nullptr;
8306 }
8307 }
8308 sp<SwAudioOutputDescriptor> desc = new SwAudioOutputDescriptor(profile, mpClientInterface);
8309 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
jiabina84c3d32022-12-02 18:59:55 +00008310 status_t status = desc->open(halConfig, mixerConfig, devices,
8311 AUDIO_STREAM_DEFAULT, flags, &output);
jiabinbce0c1d2020-10-05 11:20:18 -07008312 if (status != NO_ERROR) {
jiabina84c3d32022-12-02 18:59:55 +00008313 ALOGE("%s failed to open output %d", __func__, status);
jiabinbce0c1d2020-10-05 11:20:18 -07008314 return nullptr;
8315 }
8316
8317 // Here is where the out_set_parameters() for card & device gets called
8318 sp<DeviceDescriptor> device = devices.getDeviceForOpening();
8319 const audio_devices_t deviceType = device->type();
8320 const String8 &address = String8(device->address().c_str());
8321 if (!address.isEmpty()) {
8322 char *param = audio_device_address_to_parameter(deviceType, address.c_str());
8323 mpClientInterface->setParameters(output, String8(param));
8324 free(param);
8325 }
8326 updateAudioProfiles(device, output, profile->getAudioProfiles());
8327 if (!profile->hasValidAudioProfile()) {
8328 ALOGW("%s() missing param", __func__);
8329 desc->close();
8330 return nullptr;
jiabina84c3d32022-12-02 18:59:55 +00008331 } else if (profile->hasDynamicAudioProfile() && halConfig == nullptr) {
8332 // Reopen the output with the best audio profile picked by APM when the profile supports
8333 // dynamic audio profile and the hal config is not specified.
jiabinbce0c1d2020-10-05 11:20:18 -07008334 desc->close();
8335 output = AUDIO_IO_HANDLE_NONE;
8336 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
8337 profile->pickAudioProfile(
8338 config.sample_rate, config.channel_mask, config.format);
8339 config.offload_info.sample_rate = config.sample_rate;
8340 config.offload_info.channel_mask = config.channel_mask;
8341 config.offload_info.format = config.format;
8342
jiabina84c3d32022-12-02 18:59:55 +00008343 status = desc->open(&config, mixerConfig, devices, AUDIO_STREAM_DEFAULT, flags, &output);
jiabinbce0c1d2020-10-05 11:20:18 -07008344 if (status != NO_ERROR) {
8345 return nullptr;
8346 }
8347 }
8348
8349 addOutput(output, desc);
Eric Laurentb4f42a92022-01-17 17:37:31 +01008350
baek.kim -61c20122022-07-27 10:05:32 +00008351 sp<DeviceDescriptor> speaker = mAvailableOutputDevices.getDevice(
8352 AUDIO_DEVICE_OUT_SPEAKER, String8(""), AUDIO_FORMAT_DEFAULT);
8353
jiabinbce0c1d2020-10-05 11:20:18 -07008354 if (audio_is_remote_submix_device(deviceType) && address != "0") {
8355 sp<AudioPolicyMix> policyMix;
8356 if (mPolicyMixes.getAudioPolicyMix(deviceType, address, policyMix) == NO_ERROR) {
8357 policyMix->setOutput(desc);
8358 desc->mPolicyMix = policyMix;
8359 } else {
8360 ALOGW("checkOutputsForDevice() cannot find policy for address %s",
8361 address.string());
8362 }
8363
baek.kim -61c20122022-07-27 10:05:32 +00008364 } else if (hasPrimaryOutput() && speaker != nullptr
8365 && mPrimaryOutput->supportsDevice(speaker) && !desc->supportsDevice(speaker)
Eric Laurentb4f42a92022-01-17 17:37:31 +01008366 && ((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0)) {
8367 // no duplicated output for:
8368 // - direct outputs
8369 // - outputs used by dynamic policy mixes
baek.kim -61c20122022-07-27 10:05:32 +00008370 // - outputs that supports SPEAKER while the primary output does not.
jiabinbce0c1d2020-10-05 11:20:18 -07008371 audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE;
8372
8373 //TODO: configure audio effect output stage here
8374
8375 // open a duplicating output thread for the new output and the primary output
8376 sp<SwAudioOutputDescriptor> dupOutputDesc =
8377 new SwAudioOutputDescriptor(nullptr, mpClientInterface);
8378 status = dupOutputDesc->openDuplicating(mPrimaryOutput, desc, &duplicatedOutput);
8379 if (status == NO_ERROR) {
8380 // add duplicated output descriptor
8381 addOutput(duplicatedOutput, dupOutputDesc);
8382 } else {
8383 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
8384 mPrimaryOutput->mIoHandle, output);
8385 desc->close();
8386 removeOutput(output);
8387 nextAudioPortGeneration();
8388 return nullptr;
8389 }
8390 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02008391 if (mPrimaryOutput == nullptr && profile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
8392 ALOGV("%s(): re-assigning mPrimaryOutput", __func__);
8393 mPrimaryOutput = desc;
8394 }
jiabinbce0c1d2020-10-05 11:20:18 -07008395 return desc;
8396}
8397
jiabinf1c73972022-04-14 16:28:52 -07008398status_t AudioPolicyManager::getDevicesForAttributes(
8399 const audio_attributes_t &attr, DeviceVector &devices, bool forVolume) {
8400 // Devices are determined in the following precedence:
8401 //
8402 // 1) Devices associated with a dynamic policy matching the attributes. This is often
8403 // a remote submix from MIX_ROUTE_FLAG_LOOP_BACK.
8404 //
8405 // If no such dynamic policy then
8406 // 2) Devices containing an active client using setPreferredDevice
8407 // with same strategy as the attributes.
8408 // (from the default Engine::getOutputDevicesForAttributes() implementation).
8409 //
8410 // If no corresponding active client with setPreferredDevice then
8411 // 3) Devices associated with the strategy determined by the attributes
8412 // (from the default Engine::getOutputDevicesForAttributes() implementation).
8413 //
8414 // See related getOutputForAttrInt().
8415
8416 // check dynamic policies but only for primary descriptors (secondary not used for audible
8417 // audio routing, only used for duplication for playback capture)
8418 sp<AudioPolicyMix> policyMix;
Oscar Azucena873d10f2023-01-12 18:34:42 -08008419 bool unneededUsePrimaryOutputFromPolicyMixes = false;
jiabinf1c73972022-04-14 16:28:52 -07008420 status_t status = mPolicyMixes.getOutputForAttr(attr, AUDIO_CONFIG_BASE_INITIALIZER,
Oscar Azucena873d10f2023-01-12 18:34:42 -08008421 0 /*uid unknown here*/, AUDIO_SESSION_NONE, AUDIO_OUTPUT_FLAG_NONE,
8422 mAvailableOutputDevices, nullptr /* requestedDevice */, policyMix,
8423 nullptr /* secondaryMixes */, unneededUsePrimaryOutputFromPolicyMixes);
jiabinf1c73972022-04-14 16:28:52 -07008424 if (status != OK) {
8425 return status;
8426 }
8427
8428 if (policyMix != nullptr && policyMix->getOutput() != nullptr &&
8429 // For volume control, skip LOOPBACK mixes which use AUDIO_DEVICE_OUT_REMOTE_SUBMIX
8430 // as they are unaffected by device/stream volume
8431 // (per SwAudioOutputDescriptor::isFixedVolume()).
8432 (!forVolume || policyMix->mDeviceType != AUDIO_DEVICE_OUT_REMOTE_SUBMIX)
8433 ) {
8434 sp<DeviceDescriptor> deviceDesc = mAvailableOutputDevices.getDevice(
8435 policyMix->mDeviceType, policyMix->mDeviceAddress, AUDIO_FORMAT_DEFAULT);
8436 devices.add(deviceDesc);
8437 } else {
8438 // The default Engine::getOutputDevicesForAttributes() uses findPreferredDevice()
8439 // which selects setPreferredDevice if active. This means forVolume call
8440 // will take an active setPreferredDevice, if such exists.
8441
8442 devices = mEngine->getOutputDevicesForAttributes(
8443 attr, nullptr /* preferredDevice */, false /* fromCache */);
8444 }
8445
8446 if (forVolume) {
8447 // We alias the device AUDIO_DEVICE_OUT_SPEAKER_SAFE to AUDIO_DEVICE_OUT_SPEAKER
8448 // for single volume control in AudioService (such relationship should exist if
8449 // SPEAKER_SAFE is present).
8450 //
8451 // (This is unrelated to a different device grouping as Volume::getDeviceCategory)
8452 DeviceVector speakerSafeDevices =
8453 devices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER_SAFE);
8454 if (!speakerSafeDevices.isEmpty()) {
8455 devices.merge(mAvailableOutputDevices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER));
8456 devices.remove(speakerSafeDevices);
8457 }
8458 }
8459
8460 return NO_ERROR;
8461}
8462
8463status_t AudioPolicyManager::getProfilesForDevices(const DeviceVector& devices,
8464 AudioProfileVector& audioProfiles,
8465 uint32_t flags,
8466 bool isInput) {
8467 for (const auto& hwModule : mHwModules) {
8468 // the MSD module checks for different conditions
8469 if (strcmp(hwModule->getName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0) {
8470 continue;
8471 }
8472 IOProfileCollection ioProfiles = isInput ? hwModule->getInputProfiles()
8473 : hwModule->getOutputProfiles();
8474 for (const auto& profile : ioProfiles) {
8475 if (!profile->areAllDevicesSupported(devices) ||
8476 !profile->isCompatibleProfileForFlags(
8477 flags, false /*exactMatchRequiredForInputFlags*/)) {
8478 continue;
8479 }
8480 audioProfiles.addAllValidProfiles(profile->asAudioPort()->getAudioProfiles());
8481 }
8482 }
8483
8484 if (!isInput) {
8485 // add the direct profiles from MSD if present and has audio patches to all the output(s)
8486 const auto &msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
8487 if (msdModule != nullptr) {
8488 if (msdHasPatchesToAllDevices(devices.toTypeAddrVector())) {
8489 ALOGV("%s: MSD audio patches set to all output devices.", __func__);
8490 for (const auto &profile: msdModule->getOutputProfiles()) {
8491 if (!profile->asAudioPort()->isDirectOutput()) {
8492 continue;
8493 }
8494 audioProfiles.addAllValidProfiles(profile->asAudioPort()->getAudioProfiles());
8495 }
8496 } else {
8497 ALOGV("%s: MSD audio patches NOT set to all output devices.", __func__);
8498 }
8499 }
8500 }
8501
8502 return NO_ERROR;
8503}
8504
jiabin3ff8d7d2022-12-13 06:27:44 +00008505sp<SwAudioOutputDescriptor> AudioPolicyManager::reopenOutput(sp<SwAudioOutputDescriptor> outputDesc,
8506 const audio_config_t *config,
8507 audio_output_flags_t flags,
8508 const char* caller) {
jiabina84c3d32022-12-02 18:59:55 +00008509 closeOutput(outputDesc->mIoHandle);
8510 sp<SwAudioOutputDescriptor> preferredOutput = openOutputWithProfileAndDevice(
8511 outputDesc->mProfile, outputDesc->devices(), nullptr /*mixerConfig*/, config, flags);
8512 if (preferredOutput == nullptr) {
8513 ALOGE("%s failed to reopen output device=%d, caller=%s",
8514 __func__, outputDesc->devices()[0]->getId(), caller);
jiabina84c3d32022-12-02 18:59:55 +00008515 }
jiabin3ff8d7d2022-12-13 06:27:44 +00008516 return preferredOutput;
8517}
8518
8519void AudioPolicyManager::reopenOutputsWithDevices(
8520 const std::map<audio_io_handle_t, DeviceVector> &outputsToReopen) {
8521 for (const auto& [output, devices] : outputsToReopen) {
8522 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
8523 closeOutput(output);
8524 openOutputWithProfileAndDevice(desc->mProfile, devices);
8525 }
jiabina84c3d32022-12-02 18:59:55 +00008526}
8527
jiabinc44b3462022-12-08 12:52:31 -08008528PortHandleVector AudioPolicyManager::getClientsForStream(
8529 audio_stream_type_t streamType) const {
8530 PortHandleVector clients;
8531 for (size_t i = 0; i < mOutputs.size(); ++i) {
8532 PortHandleVector clientsForStream = mOutputs.valueAt(i)->getClientsForStream(streamType);
8533 clients.insert(clients.end(), clientsForStream.begin(), clientsForStream.end());
8534 }
8535 return clients;
8536}
8537
8538void AudioPolicyManager::invalidateStreams(StreamTypeVector streams) const {
8539 PortHandleVector clients;
8540 for (auto stream : streams) {
8541 PortHandleVector clientsForStream = getClientsForStream(stream);
8542 clients.insert(clients.end(), clientsForStream.begin(), clientsForStream.end());
8543 }
8544 mpClientInterface->invalidateTracks(clients);
8545}
8546
Mikhail Naganov1b2a7942017-12-08 10:18:09 -08008547} // namespace android