blob: cd46279ea7eb8eaecf0a1fa17ae0da57ee2b5830 [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);
Mingyu Shih75563d32023-05-24 04:47:40 +08001109 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
1110 if (stream == AUDIO_STREAM_MUSIC &&
1111 property_get_bool("audio.deep_buffer.media", false /* default_value */)) {
1112 flags = AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
1113 }
1114 const audio_io_handle_t output = selectOutput(outputs, flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001115
François Gaffie11d30102018-11-02 16:09:09 +01001116 ALOGV("getOutput() stream %d selected devices %s, output %d", stream,
1117 devices.toString().c_str(), output);
Eric Laurentf4e63452017-11-06 19:31:46 +00001118 return output;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001119}
1120
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001121status_t AudioPolicyManager::getAudioAttributes(audio_attributes_t *dstAttr,
1122 const audio_attributes_t *srcAttr,
1123 audio_stream_type_t srcStream)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001124{
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001125 if (srcAttr != NULL) {
1126 if (!isValidAttributes(srcAttr)) {
1127 ALOGE("%s invalid attributes: usage=%d content=%d flags=0x%x tags=[%s]",
1128 __func__,
1129 srcAttr->usage, srcAttr->content_type, srcAttr->flags,
1130 srcAttr->tags);
1131 return BAD_VALUE;
1132 }
1133 *dstAttr = *srcAttr;
1134 } else {
1135 if (srcStream < AUDIO_STREAM_MIN || srcStream >= AUDIO_STREAM_PUBLIC_CNT) {
1136 ALOGE("%s: invalid stream type", __func__);
1137 return BAD_VALUE;
1138 }
François Gaffiec005e562018-11-06 15:04:49 +01001139 *dstAttr = mEngine->getAttributesForStreamType(srcStream);
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001140 }
Eric Laurent22fcda22019-05-17 16:28:47 -07001141
1142 // Only honor audibility enforced when required. The client will be
1143 // forced to reconnect if the forced usage changes.
1144 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Mikhail Naganov55773032020-10-01 15:08:13 -07001145 dstAttr->flags = static_cast<audio_flags_mask_t>(
1146 dstAttr->flags & ~AUDIO_FLAG_AUDIBILITY_ENFORCED);
Eric Laurent22fcda22019-05-17 16:28:47 -07001147 }
1148
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001149 return NO_ERROR;
1150}
1151
Kevin Rocard153f92d2018-12-18 18:33:28 -08001152status_t AudioPolicyManager::getOutputForAttrInt(
1153 audio_attributes_t *resultAttr,
1154 audio_io_handle_t *output,
1155 audio_session_t session,
1156 const audio_attributes_t *attr,
1157 audio_stream_type_t *stream,
1158 uid_t uid,
jiabinf1c73972022-04-14 16:28:52 -07001159 audio_config_t *config,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001160 audio_output_flags_t *flags,
1161 audio_port_handle_t *selectedDeviceId,
1162 bool *isRequestedDeviceForExclusiveUse,
Eric Laurentc529cf62020-04-17 18:19:10 -07001163 std::vector<sp<AudioPolicyMix>> *secondaryMixes,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001164 output_type_t *outputType,
jiabinc658e452022-10-21 20:52:21 +00001165 bool *isSpatialized,
1166 bool *isBitPerfect)
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001167{
François Gaffiec005e562018-11-06 15:04:49 +01001168 DeviceVector outputDevices;
Francois Gaffie716e1432019-01-14 16:58:59 +01001169 const audio_port_handle_t requestedPortId = *selectedDeviceId;
François Gaffie11d30102018-11-02 16:09:09 +01001170 DeviceVector msdDevices = getMsdAudioOutDevices();
François Gaffiec005e562018-11-06 15:04:49 +01001171 const sp<DeviceDescriptor> requestedDevice =
1172 mAvailableOutputDevices.getDeviceFromId(requestedPortId);
1173
Eric Laurent8a1095a2019-11-08 14:44:16 -08001174 *outputType = API_OUTPUT_INVALID;
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001175 *isSpatialized = false;
1176
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001177 status_t status = getAudioAttributes(resultAttr, attr, *stream);
1178 if (status != NO_ERROR) {
1179 return status;
Eric Laurent8f42ea12018-08-08 09:08:25 -07001180 }
Kevin Rocardb99cc752019-03-21 20:52:24 -07001181 if (auto it = mAllowedCapturePolicies.find(uid); it != end(mAllowedCapturePolicies)) {
Mikhail Naganov55773032020-10-01 15:08:13 -07001182 resultAttr->flags = static_cast<audio_flags_mask_t>(resultAttr->flags | it->second);
Kevin Rocardb99cc752019-03-21 20:52:24 -07001183 }
François Gaffiec005e562018-11-06 15:04:49 +01001184 *stream = mEngine->getStreamTypeForAttributes(*resultAttr);
Eric Laurent8f42ea12018-08-08 09:08:25 -07001185
François Gaffiec005e562018-11-06 15:04:49 +01001186 ALOGV("%s() attributes=%s stream=%s session %d selectedDeviceId %d", __func__,
1187 toString(*resultAttr).c_str(), toString(*stream).c_str(), session, requestedPortId);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001188
Oscar Azucena873d10f2023-01-12 18:34:42 -08001189 bool usePrimaryOutputFromPolicyMixes = false;
1190
Kevin Rocard153f92d2018-12-18 18:33:28 -08001191 // The primary output is the explicit routing (eg. setPreferredDevice) if specified,
1192 // otherwise, fallback to the dynamic policies, if none match, query the engine.
1193 // Secondary outputs are always found by dynamic policies as the engine do not support them
Eric Laurentc529cf62020-04-17 18:19:10 -07001194 sp<AudioPolicyMix> primaryMix;
Dean Wheatleyd082f472022-02-04 11:10:48 +11001195 const audio_config_base_t clientConfig = {.sample_rate = config->sample_rate,
1196 .channel_mask = config->channel_mask,
1197 .format = config->format,
1198 };
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02001199 status = mPolicyMixes.getOutputForAttr(*resultAttr, clientConfig, uid, session, *flags,
Oscar Azucena873d10f2023-01-12 18:34:42 -08001200 mAvailableOutputDevices, requestedDevice, primaryMix,
1201 secondaryMixes, usePrimaryOutputFromPolicyMixes);
Kevin Rocard94114a22019-04-01 19:38:23 -07001202 if (status != OK) {
1203 return status;
Kevin Rocard153f92d2018-12-18 18:33:28 -08001204 }
Kevin Rocard94114a22019-04-01 19:38:23 -07001205
Kevin Rocard153f92d2018-12-18 18:33:28 -08001206 // FIXME: in case of RENDER policy, the output capabilities should be checked
Dean Wheatleyd082f472022-02-04 11:10:48 +11001207 if ((secondaryMixes != nullptr && !secondaryMixes->empty())
1208 && !audio_is_linear_pcm(config->format)) {
1209 ALOGD("%s: rejecting request as secondary mixes only support pcm", __func__);
Kevin Rocard153f92d2018-12-18 18:33:28 -08001210 return BAD_VALUE;
1211 }
1212 if (usePrimaryOutputFromPolicyMixes) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001213 sp<DeviceDescriptor> deviceDesc =
1214 mAvailableOutputDevices.getDevice(primaryMix->mDeviceType,
1215 primaryMix->mDeviceAddress,
1216 AUDIO_FORMAT_DEFAULT);
1217 sp<SwAudioOutputDescriptor> policyDesc = primaryMix->getOutput();
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001218 bool tryDirectForFlags = policyDesc == nullptr ||
1219 (policyDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT);
1220 // if a direct output can be opened to deliver the track's multi-channel content to the
1221 // output rather than being downmixed by the primary output, then use this direct
1222 // output by by-passing the primary mix if possible, otherwise fall-through to primary
1223 // mix.
1224 bool tryDirectForChannelMask = policyDesc != nullptr
1225 && (audio_channel_count_from_out_mask(policyDesc->getConfig().channel_mask) <
1226 audio_channel_count_from_out_mask(config->channel_mask));
1227 if (deviceDesc != nullptr && (tryDirectForFlags || tryDirectForChannelMask)) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001228 audio_io_handle_t newOutput;
1229 status = openDirectOutput(
1230 *stream, session, config,
1231 (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT),
1232 DeviceVector(deviceDesc), &newOutput);
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001233 if (status == NO_ERROR) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001234 policyDesc = mOutputs.valueFor(newOutput);
1235 primaryMix->setOutput(policyDesc);
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001236 } else if (tryDirectForFlags) {
1237 policyDesc = nullptr;
1238 } // otherwise use primary if available.
Eric Laurentc529cf62020-04-17 18:19:10 -07001239 }
1240 if (policyDesc != nullptr) {
1241 policyDesc->mPolicyMix = primaryMix;
1242 *output = policyDesc->mIoHandle;
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08001243 *selectedDeviceId = deviceDesc != 0 ? deviceDesc->getId() : AUDIO_PORT_HANDLE_NONE;
Eric Laurent8a1095a2019-11-08 14:44:16 -08001244
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08001245 ALOGV("getOutputForAttr() returns output %d", *output);
1246 if (resultAttr->usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
1247 *outputType = API_OUT_MIX_PLAYBACK;
1248 } else {
1249 *outputType = API_OUTPUT_LEGACY;
1250 }
1251 return NO_ERROR;
Eric Laurent8a1095a2019-11-08 14:44:16 -08001252 }
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001253 }
François Gaffiec005e562018-11-06 15:04:49 +01001254 // Virtual sources must always be dynamicaly or explicitly routed
1255 if (resultAttr->usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
1256 ALOGW("getOutputForAttr() no policy mix found for usage AUDIO_USAGE_VIRTUAL_SOURCE");
1257 return BAD_VALUE;
1258 }
1259 // explicit routing managed by getDeviceForStrategy in APM is now handled by engine
1260 // in order to let the choice of the order to future vendor engine
1261 outputDevices = mEngine->getOutputDevicesForAttributes(*resultAttr, requestedDevice, false);
Scott Randolph7b1fd232018-06-18 15:33:03 -07001262
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001263 if ((resultAttr->flags & AUDIO_FLAG_HW_AV_SYNC) != 0) {
Nadav Bar766fb022018-01-07 12:18:03 +02001264 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
Eric Laurent93c3d412014-08-01 14:48:35 -07001265 }
1266
Nadav Barb2f18162018-07-18 13:01:53 +03001267 // Set incall music only if device was explicitly set, and fallback to the device which is
1268 // chosen by the engine if not.
1269 // FIXME: provide a more generic approach which is not device specific and move this back
1270 // to getOutputForDevice.
Nadav Bar20919492018-11-20 10:20:51 +02001271 // TODO: Remove check of AUDIO_STREAM_MUSIC once migration is completed on the app side.
jiabin9a3361e2019-10-01 09:38:30 -07001272 if (outputDevices.onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_TELEPHONY_TX) &&
François Gaffiec005e562018-11-06 15:04:49 +01001273 (*stream == AUDIO_STREAM_MUSIC || resultAttr->usage == AUDIO_USAGE_VOICE_COMMUNICATION) &&
Nadav Barb2f18162018-07-18 13:01:53 +03001274 audio_is_linear_pcm(config->format) &&
Eric Laurent74b71512019-11-06 17:21:57 -08001275 isCallAudioAccessible()) {
Francois Gaffie716e1432019-01-14 16:58:59 +01001276 if (requestedPortId != AUDIO_PORT_HANDLE_NONE) {
Nadav Barb2f18162018-07-18 13:01:53 +03001277 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_INCALL_MUSIC;
François Gaffief579db52018-11-13 11:25:16 +01001278 *isRequestedDeviceForExclusiveUse = true;
Nadav Barb2f18162018-07-18 13:01:53 +03001279 }
1280 }
1281
François Gaffiec005e562018-11-06 15:04:49 +01001282 ALOGV("%s() device %s, sampling rate %d, format %#x, channel mask %#x, flags %#x stream %s",
1283 __func__, outputDevices.toString().c_str(), config->sample_rate, config->format,
1284 config->channel_mask, *flags, toString(*stream).c_str());
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001285
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001286 *output = AUDIO_IO_HANDLE_NONE;
François Gaffie11d30102018-11-02 16:09:09 +01001287 if (!msdDevices.isEmpty()) {
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001288 *output = getOutputForDevices(msdDevices, session, resultAttr, config, flags, isSpatialized);
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001289 if (*output != AUDIO_IO_HANDLE_NONE && setMsdOutputPatches(&outputDevices) == NO_ERROR) {
François Gaffiec005e562018-11-06 15:04:49 +01001290 ALOGV("%s() Using MSD devices %s instead of devices %s",
1291 __func__, msdDevices.toString().c_str(), outputDevices.toString().c_str());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001292 } else {
1293 *output = AUDIO_IO_HANDLE_NONE;
1294 }
1295 }
1296 if (*output == AUDIO_IO_HANDLE_NONE) {
jiabina84c3d32022-12-02 18:59:55 +00001297 sp<PreferredMixerAttributesInfo> info = nullptr;
1298 if (outputDevices.size() == 1) {
1299 info = getPreferredMixerAttributesInfo(
1300 outputDevices.itemAt(0)->getId(),
jiabind9a58d32023-06-01 17:57:30 +00001301 mEngine->getProductStrategyForAttributes(*resultAttr),
1302 true /*activeBitPerfectPreferred*/);
jiabin5eaf0962022-12-20 20:11:38 +00001303 // Only use preferred mixer if the uid matches or the preferred mixer is bit-perfect
1304 // and it is currently active.
1305 if (info != nullptr && info->getUid() != uid &&
1306 ((info->getFlags() & AUDIO_OUTPUT_FLAG_BIT_PERFECT) == AUDIO_OUTPUT_FLAG_NONE ||
1307 info->getActiveClientCount() == 0)) {
jiabina84c3d32022-12-02 18:59:55 +00001308 info = nullptr;
1309 }
1310 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001311 *output = getOutputForDevices(outputDevices, session, resultAttr, config,
jiabina84c3d32022-12-02 18:59:55 +00001312 flags, isSpatialized, info, resultAttr->flags & AUDIO_FLAG_MUTE_HAPTIC);
jiabin5eaf0962022-12-20 20:11:38 +00001313 // The client will be active if the client is currently preferred mixer owner and the
1314 // requested configuration matches the preferred mixer configuration.
jiabinc658e452022-10-21 20:52:21 +00001315 *isBitPerfect = (info != nullptr
1316 && (info->getFlags() & AUDIO_OUTPUT_FLAG_BIT_PERFECT) != AUDIO_OUTPUT_FLAG_NONE
jiabin5eaf0962022-12-20 20:11:38 +00001317 && info->getUid() == uid
1318 && *output != AUDIO_IO_HANDLE_NONE
1319 // When bit-perfect output is selected for the preferred mixer attributes owner,
1320 // only need to consider the config matches.
1321 && mOutputs.valueFor(*output)->isConfigurationMatched(
1322 clientConfig, AUDIO_OUTPUT_FLAG_NONE));
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001323 }
Eric Laurente83b55d2014-11-14 10:06:21 -08001324 if (*output == AUDIO_IO_HANDLE_NONE) {
jiabinf1c73972022-04-14 16:28:52 -07001325 AudioProfileVector profiles;
1326 status_t ret = getProfilesForDevices(outputDevices, profiles, *flags, false /*isInput*/);
1327 if (ret == NO_ERROR && !profiles.empty()) {
1328 config->channel_mask = profiles[0]->getChannels().empty() ? config->channel_mask
1329 : *profiles[0]->getChannels().begin();
1330 config->sample_rate = profiles[0]->getSampleRates().empty() ? config->sample_rate
1331 : *profiles[0]->getSampleRates().begin();
1332 config->format = profiles[0]->getFormat();
1333 }
Eric Laurente83b55d2014-11-14 10:06:21 -08001334 return INVALID_OPERATION;
1335 }
Paul McLeanaa981192015-03-21 09:55:15 -07001336
François Gaffiec005e562018-11-06 15:04:49 +01001337 *selectedDeviceId = getFirstDeviceId(outputDevices);
Michael Chan6fb34492020-12-08 15:44:49 +11001338 for (auto &outputDevice : outputDevices) {
Mikhail Naganov68e3f642023-04-28 13:06:32 -07001339 if (outputDevice->getId() == mConfig->getDefaultOutputDevice()->getId()) {
Michael Chan6fb34492020-12-08 15:44:49 +11001340 *selectedDeviceId = outputDevice->getId();
1341 break;
1342 }
1343 }
Eric Laurent2ac76942017-06-22 17:17:09 -07001344
Eric Laurent8a1095a2019-11-08 14:44:16 -08001345 if (outputDevices.onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_TELEPHONY_TX)) {
1346 *outputType = API_OUTPUT_TELEPHONY_TX;
1347 } else {
1348 *outputType = API_OUTPUT_LEGACY;
1349 }
1350
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001351 ALOGV("%s returns output %d selectedDeviceId %d", __func__, *output, *selectedDeviceId);
1352
1353 return NO_ERROR;
1354}
1355
1356status_t AudioPolicyManager::getOutputForAttr(const audio_attributes_t *attr,
1357 audio_io_handle_t *output,
1358 audio_session_t session,
1359 audio_stream_type_t *stream,
Svet Ganov3e5f14f2021-05-13 22:51:08 +00001360 const AttributionSourceState& attributionSource,
jiabinf1c73972022-04-14 16:28:52 -07001361 audio_config_t *config,
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001362 audio_output_flags_t *flags,
1363 audio_port_handle_t *selectedDeviceId,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001364 audio_port_handle_t *portId,
Eric Laurent8a1095a2019-11-08 14:44:16 -08001365 std::vector<audio_io_handle_t> *secondaryOutputs,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001366 output_type_t *outputType,
jiabinc658e452022-10-21 20:52:21 +00001367 bool *isSpatialized,
1368 bool *isBitPerfect)
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001369{
1370 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
1371 if (*portId != AUDIO_PORT_HANDLE_NONE) {
1372 return INVALID_OPERATION;
1373 }
Philip P. Moltmannbda45752020-07-17 16:41:18 -07001374 const uid_t uid = VALUE_OR_RETURN_STATUS(
Svet Ganov3e5f14f2021-05-13 22:51:08 +00001375 aidl2legacy_int32_t_uid_t(attributionSource.uid));
Francois Gaffie716e1432019-01-14 16:58:59 +01001376 const audio_port_handle_t requestedPortId = *selectedDeviceId;
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001377 audio_attributes_t resultAttr;
François Gaffief579db52018-11-13 11:25:16 +01001378 bool isRequestedDeviceForExclusiveUse = false;
Eric Laurentc529cf62020-04-17 18:19:10 -07001379 std::vector<sp<AudioPolicyMix>> secondaryMixes;
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001380 const sp<DeviceDescriptor> requestedDevice =
1381 mAvailableOutputDevices.getDeviceFromId(requestedPortId);
1382
1383 // Prevent from storing invalid requested device id in clients
1384 const audio_port_handle_t sanitizedRequestedPortId =
1385 requestedDevice != nullptr ? requestedPortId : AUDIO_PORT_HANDLE_NONE;
1386 *selectedDeviceId = sanitizedRequestedPortId;
1387
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001388 status_t status = getOutputForAttrInt(&resultAttr, output, session, attr, stream, uid,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001389 config, flags, selectedDeviceId, &isRequestedDeviceForExclusiveUse,
jiabinc658e452022-10-21 20:52:21 +00001390 secondaryOutputs != nullptr ? &secondaryMixes : nullptr, outputType, isSpatialized,
1391 isBitPerfect);
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001392 if (status != NO_ERROR) {
1393 return status;
1394 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001395 std::vector<wp<SwAudioOutputDescriptor>> weakSecondaryOutputDescs;
Eric Laurentc529cf62020-04-17 18:19:10 -07001396 if (secondaryOutputs != nullptr) {
1397 for (auto &secondaryMix : secondaryMixes) {
1398 sp<SwAudioOutputDescriptor> outputDesc = secondaryMix->getOutput();
1399 if (outputDesc != nullptr &&
1400 outputDesc->mIoHandle != AUDIO_IO_HANDLE_NONE) {
1401 secondaryOutputs->push_back(outputDesc->mIoHandle);
1402 weakSecondaryOutputDescs.push_back(outputDesc);
1403 }
1404 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001405 }
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001406
Eric Laurent8fc147b2018-07-22 19:13:55 -07001407 audio_config_base_t clientConfig = {.sample_rate = config->sample_rate,
Nick Desaulniersa30e3202019-10-18 13:38:23 -07001408 .channel_mask = config->channel_mask,
Eric Laurent8fc147b2018-07-22 19:13:55 -07001409 .format = config->format,
Nick Desaulniersa30e3202019-10-18 13:38:23 -07001410 };
jiabin4ef93452019-09-10 14:29:54 -07001411 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurent8f42ea12018-08-08 09:08:25 -07001412
Eric Laurentc209fe42020-06-05 18:11:23 -07001413 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(*output);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001414 sp<TrackClientDescriptor> clientDesc =
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001415 new TrackClientDescriptor(*portId, uid, session, resultAttr, clientConfig,
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001416 sanitizedRequestedPortId, *stream,
François Gaffiec005e562018-11-06 15:04:49 +01001417 mEngine->getProductStrategyForAttributes(resultAttr),
François Gaffieaaac0fd2018-11-22 17:56:39 +01001418 toVolumeSource(resultAttr),
Kevin Rocard153f92d2018-12-18 18:33:28 -08001419 *flags, isRequestedDeviceForExclusiveUse,
Eric Laurentc209fe42020-06-05 18:11:23 -07001420 std::move(weakSecondaryOutputDescs),
1421 outputDesc->mPolicyMix);
Andy Hung39efb7a2018-09-26 15:39:28 -07001422 outputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001423
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001424 ALOGV("%s() returns output %d requestedPortId %d selectedDeviceId %d for port ID %d", __func__,
1425 *output, requestedPortId, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07001426
Eric Laurente83b55d2014-11-14 10:06:21 -08001427 return NO_ERROR;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001428}
1429
Eric Laurentc529cf62020-04-17 18:19:10 -07001430status_t AudioPolicyManager::openDirectOutput(audio_stream_type_t stream,
1431 audio_session_t session,
1432 const audio_config_t *config,
1433 audio_output_flags_t flags,
1434 const DeviceVector &devices,
1435 audio_io_handle_t *output) {
1436
1437 *output = AUDIO_IO_HANDLE_NONE;
1438
1439 // skip direct output selection if the request can obviously be attached to a mixed output
1440 // and not explicitly requested
1441 if (((flags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
1442 audio_is_linear_pcm(config->format) && config->sample_rate <= SAMPLE_RATE_HZ_MAX &&
1443 audio_channel_count_from_out_mask(config->channel_mask) <= 2) {
1444 return NAME_NOT_FOUND;
1445 }
1446
1447 // Do not allow offloading if one non offloadable effect is enabled or MasterMono is enabled.
1448 // This prevents creating an offloaded track and tearing it down immediately after start
1449 // when audioflinger detects there is an active non offloadable effect.
1450 // FIXME: We should check the audio session here but we do not have it in this context.
1451 // This may prevent offloading in rare situations where effects are left active by apps
1452 // in the background.
1453 sp<IOProfile> profile;
1454 if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) ||
1455 !(mEffects.isNonOffloadableEffectEnabled() || mMasterMono)) {
1456 profile = getProfileForOutput(
1457 devices, config->sample_rate, config->format, config->channel_mask,
1458 flags, true /* directOnly */);
1459 }
1460
1461 if (profile == nullptr) {
1462 return NAME_NOT_FOUND;
1463 }
1464
1465 // exclusive outputs for MMAP and Offload are enforced by different session ids.
1466 for (size_t i = 0; i < mOutputs.size(); i++) {
1467 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
1468 if (!desc->isDuplicated() && (profile == desc->mProfile)) {
1469 // reuse direct output if currently open by the same client
1470 // and configured with same parameters
1471 if ((config->sample_rate == desc->getSamplingRate()) &&
1472 (config->format == desc->getFormat()) &&
1473 (config->channel_mask == desc->getChannelMask()) &&
1474 (session == desc->mDirectClientSession)) {
1475 desc->mDirectOpenCount++;
Eric Laurentfecbceb2021-02-09 14:46:43 +01001476 ALOGV("%s reusing direct output %d for session %d", __func__,
Eric Laurentc529cf62020-04-17 18:19:10 -07001477 mOutputs.keyAt(i), session);
1478 *output = mOutputs.keyAt(i);
1479 return NO_ERROR;
1480 }
1481 }
1482 }
1483
1484 if (!profile->canOpenNewIo()) {
1485 return NAME_NOT_FOUND;
1486 }
1487
1488 sp<SwAudioOutputDescriptor> outputDesc =
1489 new SwAudioOutputDescriptor(profile, mpClientInterface);
1490
Michael Chan6fb34492020-12-08 15:44:49 +11001491 // An MSD patch may be using the only output stream that can service this request. Release
1492 // all MSD patches to prioritize this request over any active output on MSD.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001493 releaseMsdOutputPatches(devices);
Eric Laurentc529cf62020-04-17 18:19:10 -07001494
Eric Laurentf1f22e72021-07-13 14:04:14 +02001495 status_t status =
1496 outputDesc->open(config, nullptr /* mixerConfig */, devices, stream, flags, output);
Eric Laurentc529cf62020-04-17 18:19:10 -07001497
1498 // only accept an output with the requested parameters
1499 if (status != NO_ERROR ||
1500 (config->sample_rate != 0 && config->sample_rate != outputDesc->getSamplingRate()) ||
1501 (config->format != AUDIO_FORMAT_DEFAULT && config->format != outputDesc->getFormat()) ||
1502 (config->channel_mask != 0 && config->channel_mask != outputDesc->getChannelMask())) {
1503 ALOGV("%s failed opening direct output: output %d sample rate %d %d,"
1504 "format %d %d, channel mask %04x %04x", __func__, *output, config->sample_rate,
1505 outputDesc->getSamplingRate(), config->format, outputDesc->getFormat(),
1506 config->channel_mask, outputDesc->getChannelMask());
1507 if (*output != AUDIO_IO_HANDLE_NONE) {
1508 outputDesc->close();
1509 }
1510 // fall back to mixer output if possible when the direct output could not be open
1511 if (audio_is_linear_pcm(config->format) &&
1512 config->sample_rate <= SAMPLE_RATE_HZ_MAX) {
1513 return NAME_NOT_FOUND;
1514 }
1515 *output = AUDIO_IO_HANDLE_NONE;
1516 return BAD_VALUE;
1517 }
1518 outputDesc->mDirectOpenCount = 1;
1519 outputDesc->mDirectClientSession = session;
1520
1521 addOutput(*output, outputDesc);
1522 mPreviousOutputs = mOutputs;
1523 ALOGV("%s returns new direct output %d", __func__, *output);
1524 mpClientInterface->onAudioPortListUpdate();
1525 return NO_ERROR;
1526}
1527
François Gaffie11d30102018-11-02 16:09:09 +01001528audio_io_handle_t AudioPolicyManager::getOutputForDevices(
1529 const DeviceVector &devices,
Kevin Rocard169753c2017-03-06 14:18:23 -08001530 audio_session_t session,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001531 const audio_attributes_t *attr,
Eric Laurentfe231122017-11-17 17:48:06 -08001532 const audio_config_t *config,
jiabine375d412019-02-26 12:54:53 -08001533 audio_output_flags_t *flags,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001534 bool *isSpatialized,
jiabina84c3d32022-12-02 18:59:55 +00001535 sp<PreferredMixerAttributesInfo> prefMixerConfigInfo,
jiabine375d412019-02-26 12:54:53 -08001536 bool forceMutingHaptic)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001537{
Andy Hungc88b0642018-04-27 15:42:35 -07001538 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001539
jiabine375d412019-02-26 12:54:53 -08001540 // Discard haptic channel mask when forcing muting haptic channels.
1541 audio_channel_mask_t channelMask = forceMutingHaptic
Mikhail Naganov55773032020-10-01 15:08:13 -07001542 ? static_cast<audio_channel_mask_t>(config->channel_mask & ~AUDIO_CHANNEL_HAPTIC_ALL)
1543 : config->channel_mask;
jiabine375d412019-02-26 12:54:53 -08001544
Eric Laurente552edb2014-03-10 17:42:56 -07001545 // open a direct output if required by specified parameters
1546 //force direct flag if offload flag is set: offloading implies a direct output stream
1547 // and all common behaviors are driven by checking only the direct flag
1548 // this should normally be set appropriately in the policy configuration file
Nadav Bar766fb022018-01-07 12:18:03 +02001549 if ((*flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1550 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurente552edb2014-03-10 17:42:56 -07001551 }
Nadav Bar766fb022018-01-07 12:18:03 +02001552 if ((*flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
1553 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent93c3d412014-08-01 14:48:35 -07001554 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001555
1556 audio_stream_type_t stream = mEngine->getStreamTypeForAttributes(*attr);
1557
Eric Laurente83b55d2014-11-14 10:06:21 -08001558 // only allow deep buffering for music stream type
1559 if (stream != AUDIO_STREAM_MUSIC) {
Nadav Bar766fb022018-01-07 12:18:03 +02001560 *flags = (audio_output_flags_t)(*flags &~AUDIO_OUTPUT_FLAG_DEEP_BUFFER);
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -07001561 } else if (/* stream == AUDIO_STREAM_MUSIC && */
Nadav Bar766fb022018-01-07 12:18:03 +02001562 *flags == AUDIO_OUTPUT_FLAG_NONE &&
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -07001563 property_get_bool("audio.deep_buffer.media", false /* default_value */)) {
1564 // use DEEP_BUFFER as default output for music stream type
Nadav Bar766fb022018-01-07 12:18:03 +02001565 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
Eric Laurente83b55d2014-11-14 10:06:21 -08001566 }
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -07001567 if (stream == AUDIO_STREAM_TTS) {
Nadav Bar766fb022018-01-07 12:18:03 +02001568 *flags = AUDIO_OUTPUT_FLAG_TTS;
Haynes Mathew George84c621e2017-04-25 11:41:50 -07001569 } else if (stream == AUDIO_STREAM_VOICE_CALL &&
Nadav Bar20919492018-11-20 10:20:51 +02001570 audio_is_linear_pcm(config->format) &&
1571 (*flags & AUDIO_OUTPUT_FLAG_INCALL_MUSIC) == 0) {
Nadav Bar766fb022018-01-07 12:18:03 +02001572 *flags = (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_VOIP_RX |
Haynes Mathew George84c621e2017-04-25 11:41:50 -07001573 AUDIO_OUTPUT_FLAG_DIRECT);
1574 ALOGV("Set VoIP and Direct output flags for PCM format");
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -07001575 }
Eric Laurente552edb2014-03-10 17:42:56 -07001576
Carter Hsua3abb402021-10-26 11:11:20 +08001577 // Attach the Ultrasound flag for the AUDIO_CONTENT_TYPE_ULTRASOUND
1578 if (attr->content_type == AUDIO_CONTENT_TYPE_ULTRASOUND) {
1579 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_ULTRASOUND);
1580 }
1581
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001582 *isSpatialized = false;
Eric Laurentfa0f6742021-08-17 18:39:44 +02001583 if (mSpatializerOutput != nullptr
Andy Hung9dd1a5b2022-05-10 15:39:39 -07001584 && canBeSpatializedInt(attr, config, devices.toTypeAddrVector())) {
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001585 *isSpatialized = true;
Eric Laurentfa0f6742021-08-17 18:39:44 +02001586 return mSpatializerOutput->mIoHandle;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001587 }
1588
Eric Laurentc529cf62020-04-17 18:19:10 -07001589 audio_config_t directConfig = *config;
1590 directConfig.channel_mask = channelMask;
1591 status_t status = openDirectOutput(stream, session, &directConfig, *flags, devices, &output);
1592 if (status != NAME_NOT_FOUND) {
Eric Laurente552edb2014-03-10 17:42:56 -07001593 return output;
1594 }
1595
Eric Laurent14cbfca2016-03-17 09:42:16 -07001596 // A request for HW A/V sync cannot fallback to a mixed output because time
1597 // stamps are embedded in audio data
Phil Burk2d059932018-02-15 15:55:11 -08001598 if ((*flags & (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ)) != 0) {
Eric Laurent14cbfca2016-03-17 09:42:16 -07001599 return AUDIO_IO_HANDLE_NONE;
1600 }
Pierre Couillaude73496b2023-03-06 16:19:05 +00001601 // A request for Tuner cannot fallback to a mixed output
1602 if ((directConfig.offload_info.content_id || directConfig.offload_info.sync_id)) {
1603 return AUDIO_IO_HANDLE_NONE;
1604 }
Eric Laurent14cbfca2016-03-17 09:42:16 -07001605
Eric Laurente552edb2014-03-10 17:42:56 -07001606 // ignoring channel mask due to downmix capability in mixer
1607
1608 // open a non direct output
1609
1610 // for non direct outputs, only PCM is supported
Eric Laurentfe231122017-11-17 17:48:06 -08001611 if (audio_is_linear_pcm(config->format)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001612 // get which output is suitable for the specified stream. The actual
1613 // routing change will happen when startOutput() will be called
François Gaffie11d30102018-11-02 16:09:09 +01001614 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
jiabina84c3d32022-12-02 18:59:55 +00001615 if (prefMixerConfigInfo != nullptr) {
1616 for (audio_io_handle_t outputHandle : outputs) {
1617 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(outputHandle);
1618 if (outputDesc->mProfile == prefMixerConfigInfo->getProfile()) {
1619 output = outputHandle;
1620 break;
1621 }
1622 }
1623 if (output == AUDIO_IO_HANDLE_NONE) {
1624 // No output open with the preferred profile. Open a new one.
1625 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
1626 config.channel_mask = prefMixerConfigInfo->getConfigBase().channel_mask;
1627 config.sample_rate = prefMixerConfigInfo->getConfigBase().sample_rate;
1628 config.format = prefMixerConfigInfo->getConfigBase().format;
1629 sp<SwAudioOutputDescriptor> preferredOutput = openOutputWithProfileAndDevice(
1630 prefMixerConfigInfo->getProfile(), devices, nullptr /*mixerConfig*/,
1631 &config, prefMixerConfigInfo->getFlags());
1632 if (preferredOutput == nullptr) {
1633 ALOGE("%s failed to open output with preferred mixer config", __func__);
1634 } else {
1635 output = preferredOutput->mIoHandle;
1636 }
1637 }
1638 } else {
1639 // at this stage we should ignore the DIRECT flag as no direct output could be
1640 // found earlier
1641 *flags = (audio_output_flags_t) (*flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
1642 output = selectOutput(
1643 outputs, *flags, config->format, channelMask, config->sample_rate, session);
1644 }
Eric Laurente552edb2014-03-10 17:42:56 -07001645 }
François Gaffie11d30102018-11-02 16:09:09 +01001646 ALOGW_IF((output == 0), "getOutputForDevices() could not find output for stream %d, "
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001647 "sampling rate %d, format %#x, channels %#x, flags %#x",
jiabine375d412019-02-26 12:54:53 -08001648 stream, config->sample_rate, config->format, channelMask, *flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001649
Eric Laurente552edb2014-03-10 17:42:56 -07001650 return output;
1651}
1652
Mikhail Naganovf02f3672018-11-09 12:44:16 -08001653sp<DeviceDescriptor> AudioPolicyManager::getMsdAudioInDevice() const {
François Gaffie11d30102018-11-02 16:09:09 +01001654 auto msdInDevices = mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1655 mAvailableInputDevices);
1656 return msdInDevices.isEmpty()? nullptr : msdInDevices.itemAt(0);
1657}
1658
1659DeviceVector AudioPolicyManager::getMsdAudioOutDevices() const {
1660 return mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1661 mAvailableOutputDevices);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001662}
1663
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001664const AudioPatchCollection AudioPolicyManager::getMsdOutputPatches() const {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001665 AudioPatchCollection msdPatches;
Mikhail Naganov86112352018-10-04 09:02:49 -07001666 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1667 if (msdModule != 0) {
1668 for (size_t i = 0; i < mAudioPatches.size(); ++i) {
1669 sp<AudioPatch> patch = mAudioPatches.valueAt(i);
1670 for (size_t j = 0; j < patch->mPatch.num_sources; ++j) {
1671 const struct audio_port_config *source = &patch->mPatch.sources[j];
1672 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
1673 source->ext.device.hw_module == msdModule->getHandle()) {
François Gaffieafd4cea2019-11-18 15:50:22 +01001674 msdPatches.addAudioPatch(patch->getHandle(), patch);
Mikhail Naganov86112352018-10-04 09:02:49 -07001675 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001676 }
1677 }
1678 }
1679 return msdPatches;
1680}
1681
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02001682bool AudioPolicyManager::isMsdPatch(const audio_patch_handle_t &handle) const {
1683 ssize_t index = mAudioPatches.indexOfKey(handle);
1684 if (index < 0) {
1685 return false;
1686 }
1687 const sp<AudioPatch> patch = mAudioPatches.valueAt(index);
1688 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1689 if (msdModule == nullptr) {
1690 return false;
1691 }
1692 const struct audio_port_config *sink = &patch->mPatch.sinks[0];
1693 if (getMsdAudioOutDevices().contains(mAvailableOutputDevices.getDeviceFromId(sink->id))) {
1694 return true;
1695 }
1696 index = getMsdOutputPatches().indexOfKey(handle);
1697 if (index < 0) {
1698 return false;
1699 }
1700 return true;
1701}
1702
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001703status_t AudioPolicyManager::getMsdProfiles(bool hwAvSync,
1704 const InputProfileCollection &inputProfiles,
1705 const OutputProfileCollection &outputProfiles,
1706 const sp<DeviceDescriptor> &sourceDevice,
1707 const sp<DeviceDescriptor> &sinkDevice,
1708 AudioProfileVector& sourceProfiles,
1709 AudioProfileVector& sinkProfiles) const {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001710 if (inputProfiles.isEmpty()) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001711 ALOGE("%s() no input profiles for source module", __func__);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001712 return NO_INIT;
1713 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001714 if (outputProfiles.isEmpty()) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001715 ALOGE("%s() no output profiles for sink module", __func__);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001716 return NO_INIT;
1717 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001718 for (const auto &inProfile : inputProfiles) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001719 if (hwAvSync == ((inProfile->getFlags() & AUDIO_INPUT_FLAG_HW_AV_SYNC) != 0) &&
1720 inProfile->supportsDevice(sourceDevice)) {
1721 appendAudioProfiles(sourceProfiles, inProfile->getAudioProfiles());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001722 }
1723 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001724 for (const auto &outProfile : outputProfiles) {
Michael Chan6fb34492020-12-08 15:44:49 +11001725 if (hwAvSync == ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) &&
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001726 outProfile->supportsDevice(sinkDevice)) {
1727 appendAudioProfiles(sinkProfiles, outProfile->getAudioProfiles());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001728 }
1729 }
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001730 return NO_ERROR;
1731}
1732
1733status_t AudioPolicyManager::getBestMsdConfig(bool hwAvSync,
1734 const AudioProfileVector &sourceProfiles, const AudioProfileVector &sinkProfiles,
1735 audio_port_config *sourceConfig, audio_port_config *sinkConfig) const
1736{
Dean Wheatley16809da2022-12-09 14:55:46 +11001737 // Compressed formats for MSD module, ordered from most preferred to least preferred.
1738 static const std::vector<audio_format_t> formatsOrder = {{
1739 AUDIO_FORMAT_IEC60958, AUDIO_FORMAT_MAT_2_1, AUDIO_FORMAT_MAT_2_0, AUDIO_FORMAT_E_AC3,
1740 AUDIO_FORMAT_AC3, AUDIO_FORMAT_PCM_16_BIT }};
1741 static const std::vector<audio_channel_mask_t> channelMasksOrder = [](){
1742 // Channel position masks for MSD module, 3D > 2D > 1D ordering (most preferred to least
1743 // preferred).
1744 std::vector<audio_channel_mask_t> masks = {{
1745 AUDIO_CHANNEL_OUT_3POINT1POINT2, AUDIO_CHANNEL_OUT_3POINT0POINT2,
1746 AUDIO_CHANNEL_OUT_2POINT1POINT2, AUDIO_CHANNEL_OUT_2POINT0POINT2,
1747 AUDIO_CHANNEL_OUT_5POINT1, AUDIO_CHANNEL_OUT_STEREO }};
1748 // insert index masks (higher counts most preferred) as preferred over position masks
1749 for (int i = 1; i <= AUDIO_CHANNEL_COUNT_MAX; i++) {
1750 masks.insert(
1751 masks.begin(), audio_channel_mask_for_index_assignment_from_count(i));
1752 }
1753 return masks;
1754 }();
1755
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001756 struct audio_config_base bestSinkConfig;
Dean Wheatley16809da2022-12-09 14:55:46 +11001757 status_t result = findBestMatchingOutputConfig(sourceProfiles, sinkProfiles, formatsOrder,
1758 channelMasksOrder, true /*preferHigherSamplingRates*/, bestSinkConfig);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001759 if (result != NO_ERROR) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001760 ALOGD("%s() no matching config found for sink, hwAvSync: %d",
1761 __func__, hwAvSync);
Greg Kaiser83289652018-07-30 06:13:57 -07001762 return result;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001763 }
1764 sinkConfig->sample_rate = bestSinkConfig.sample_rate;
1765 sinkConfig->channel_mask = bestSinkConfig.channel_mask;
1766 sinkConfig->format = bestSinkConfig.format;
1767 // For encoded streams force direct flag to prevent downstream mixing.
1768 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1769 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_DIRECT);
Dean Wheatley5c9f0832019-11-21 13:39:31 +11001770 if (audio_is_iec61937_compatible(sinkConfig->format)) {
1771 // For formats compatible with IEC61937 encapsulation, assume that
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001772 // the input is IEC61937 framed (for proportional buffer sizing).
Dean Wheatley5c9f0832019-11-21 13:39:31 +11001773 // Add the AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO flag so downstream HAL can distinguish between
1774 // raw and IEC61937 framed streams.
1775 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1776 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO);
1777 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001778 sourceConfig->sample_rate = bestSinkConfig.sample_rate;
1779 // Specify exact channel mask to prevent guessing by bit count in PatchPanel.
Dean Wheatley16809da2022-12-09 14:55:46 +11001780 sourceConfig->channel_mask =
1781 audio_channel_mask_get_representation(bestSinkConfig.channel_mask)
1782 == AUDIO_CHANNEL_REPRESENTATION_INDEX ?
1783 bestSinkConfig.channel_mask : audio_channel_mask_out_to_in(bestSinkConfig.channel_mask);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001784 sourceConfig->format = bestSinkConfig.format;
1785 // Copy input stream directly without any processing (e.g. resampling).
1786 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1787 sourceConfig->flags.input | AUDIO_INPUT_FLAG_DIRECT);
1788 if (hwAvSync) {
1789 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1790 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
1791 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1792 sourceConfig->flags.input | AUDIO_INPUT_FLAG_HW_AV_SYNC);
1793 }
1794 const unsigned int config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE |
1795 AUDIO_PORT_CONFIG_CHANNEL_MASK | AUDIO_PORT_CONFIG_FORMAT | AUDIO_PORT_CONFIG_FLAGS;
1796 sinkConfig->config_mask |= config_mask;
1797 sourceConfig->config_mask |= config_mask;
1798 return NO_ERROR;
1799}
1800
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001801PatchBuilder AudioPolicyManager::buildMsdPatch(bool msdIsSource,
1802 const sp<DeviceDescriptor> &device) const
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001803{
1804 PatchBuilder patchBuilder;
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001805 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1806 ALOG_ASSERT(msdModule != nullptr, "MSD module not available");
1807 sp<HwModule> deviceModule = mHwModules.getModuleForDevice(device, AUDIO_FORMAT_DEFAULT);
1808 if (deviceModule == nullptr) {
1809 ALOGE("%s() unable to get module for %s", __func__, device->toString().c_str());
1810 return patchBuilder;
1811 }
1812 const InputProfileCollection inputProfiles = msdIsSource ?
1813 msdModule->getInputProfiles() : deviceModule->getInputProfiles();
1814 const OutputProfileCollection outputProfiles = msdIsSource ?
1815 deviceModule->getOutputProfiles() : msdModule->getOutputProfiles();
1816
1817 const sp<DeviceDescriptor> sourceDevice = msdIsSource ? getMsdAudioInDevice() : device;
1818 const sp<DeviceDescriptor> sinkDevice = msdIsSource ?
1819 device : getMsdAudioOutDevices().itemAt(0);
1820 patchBuilder.addSource(sourceDevice).addSink(sinkDevice);
1821
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001822 audio_port_config sourceConfig = patchBuilder.patch()->sources[0];
1823 audio_port_config sinkConfig = patchBuilder.patch()->sinks[0];
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001824 AudioProfileVector sourceProfiles;
1825 AudioProfileVector sinkProfiles;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001826 // TODO: Figure out whether MSD module has HW_AV_SYNC flag set in the AP config file.
1827 // For now, we just forcefully try with HwAvSync first.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001828 for (auto hwAvSync : { true, false }) {
1829 if (getMsdProfiles(hwAvSync, inputProfiles, outputProfiles, sourceDevice, sinkDevice,
1830 sourceProfiles, sinkProfiles) != NO_ERROR) {
1831 continue;
1832 }
1833 if (getBestMsdConfig(hwAvSync, sourceProfiles, sinkProfiles, &sourceConfig,
1834 &sinkConfig) == NO_ERROR) {
1835 // Found a matching config. Re-create PatchBuilder with this config.
1836 return (PatchBuilder()).addSource(sourceConfig).addSink(sinkConfig);
1837 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001838 }
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001839 ALOGV("%s() no matching config found. Fall through to default PCM patch"
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001840 " supporting PCM format conversion.", __func__);
1841 return patchBuilder;
1842}
1843
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001844status_t AudioPolicyManager::setMsdOutputPatches(const DeviceVector *outputDevices) {
Michael Chan6fb34492020-12-08 15:44:49 +11001845 DeviceVector devices;
1846 if (outputDevices != nullptr && outputDevices->size() > 0) {
1847 devices.add(*outputDevices);
1848 } else {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001849 // Use media strategy for unspecified output device. This should only
1850 // occur on checkForDeviceAndOutputChanges(). Device connection events may
1851 // therefore invalidate explicit routing requests.
Michael Chan6fb34492020-12-08 15:44:49 +11001852 devices = mEngine->getOutputDevicesForAttributes(
François Gaffiec005e562018-11-06 15:04:49 +01001853 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
Michael Chan6fb34492020-12-08 15:44:49 +11001854 LOG_ALWAYS_FATAL_IF(devices.isEmpty(), "no output device to set MSD patch");
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001855 }
Michael Chan6fb34492020-12-08 15:44:49 +11001856 std::vector<PatchBuilder> patchesToCreate;
1857 for (auto i = 0u; i < devices.size(); ++i) {
1858 ALOGV("%s() for device %s", __func__, devices[i]->toString().c_str());
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001859 patchesToCreate.push_back(buildMsdPatch(true /*msdIsSource*/, devices[i]));
Michael Chan6fb34492020-12-08 15:44:49 +11001860 }
1861 // Retain only the MSD patches associated with outputDevices request.
1862 // Tear down the others, and create new ones as needed.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001863 AudioPatchCollection patchesToRemove = getMsdOutputPatches();
Michael Chan6fb34492020-12-08 15:44:49 +11001864 for (auto it = patchesToCreate.begin(); it != patchesToCreate.end(); ) {
1865 auto retainedPatch = false;
1866 for (auto i = 0u; i < patchesToRemove.size(); ++i) {
1867 if (audio_patches_are_equal(it->patch(), &patchesToRemove[i]->mPatch)) {
1868 patchesToRemove.removeItemsAt(i);
1869 retainedPatch = true;
1870 break;
1871 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001872 }
Michael Chan6fb34492020-12-08 15:44:49 +11001873 if (retainedPatch) {
1874 it = patchesToCreate.erase(it);
1875 continue;
1876 }
1877 ++it;
1878 }
1879 if (patchesToCreate.size() == 0 && patchesToRemove.size() == 0) {
1880 return NO_ERROR;
1881 }
1882 for (auto i = 0u; i < patchesToRemove.size(); ++i) {
1883 auto &currentPatch = patchesToRemove.valueAt(i);
François Gaffieafd4cea2019-11-18 15:50:22 +01001884 releaseAudioPatch(currentPatch->getHandle(), mUidCached);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001885 }
Michael Chan6fb34492020-12-08 15:44:49 +11001886 status_t status = NO_ERROR;
1887 for (const auto &p : patchesToCreate) {
1888 auto currStatus = installPatch(__func__, -1 /*index*/, nullptr /*patchHandle*/,
1889 p.patch(), 0 /*delayMs*/, mUidCached, nullptr /*patchDescPtr*/);
1890 char message[256];
1891 snprintf(message, sizeof(message), "%s() %s: creating MSD patch from device:IN_BUS to "
1892 "device:%#x (format:%#x channels:%#x samplerate:%d)", __func__,
1893 currStatus == NO_ERROR ? "Success" : "Error",
1894 p.patch()->sinks[0].ext.device.type, p.patch()->sources[0].format,
1895 p.patch()->sources[0].channel_mask, p.patch()->sources[0].sample_rate);
1896 if (currStatus == NO_ERROR) {
1897 ALOGD("%s", message);
1898 } else {
1899 ALOGE("%s", message);
1900 if (status == NO_ERROR) {
1901 status = currStatus;
1902 }
1903 }
1904 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001905 return status;
1906}
1907
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001908void AudioPolicyManager::releaseMsdOutputPatches(const DeviceVector& devices) {
1909 AudioPatchCollection msdPatches = getMsdOutputPatches();
Michael Chan6fb34492020-12-08 15:44:49 +11001910 for (size_t i = 0; i < msdPatches.size(); i++) {
1911 const auto& patch = msdPatches[i];
1912 for (size_t j = 0; j < patch->mPatch.num_sinks; ++j) {
1913 const struct audio_port_config *sink = &patch->mPatch.sinks[j];
1914 if (sink->type == AUDIO_PORT_TYPE_DEVICE && devices.getDevice(sink->ext.device.type,
1915 String8(sink->ext.device.address), AUDIO_FORMAT_DEFAULT) != nullptr) {
1916 releaseAudioPatch(patch->getHandle(), mUidCached);
1917 break;
1918 }
1919 }
1920 }
1921}
1922
Dorin Drimus94d94412022-02-02 09:05:02 +01001923bool AudioPolicyManager::msdHasPatchesToAllDevices(const AudioDeviceTypeAddrVector& devices) {
Mikhail Naganov68e3f642023-04-28 13:06:32 -07001924 DeviceVector devicesToCheck =
1925 mConfig->getOutputDevices().getDevicesFromDeviceTypeAddrVec(devices);
Dorin Drimus94d94412022-02-02 09:05:02 +01001926 AudioPatchCollection msdPatches = getMsdOutputPatches();
1927 for (size_t i = 0; i < msdPatches.size(); i++) {
1928 const auto& patch = msdPatches[i];
1929 for (size_t j = 0; j < patch->mPatch.num_sinks; ++j) {
1930 const struct audio_port_config *sink = &patch->mPatch.sinks[j];
1931 if (sink->type == AUDIO_PORT_TYPE_DEVICE) {
1932 const auto& foundDevice = devicesToCheck.getDevice(
1933 sink->ext.device.type, String8(sink->ext.device.address), AUDIO_FORMAT_DEFAULT);
1934 if (foundDevice != nullptr) {
1935 devicesToCheck.remove(foundDevice);
1936 if (devicesToCheck.isEmpty()) {
1937 return true;
1938 }
1939 }
1940 }
1941 }
1942 }
1943 return false;
1944}
1945
Eric Laurente0720872014-03-11 09:30:41 -07001946audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
jiabinebb6af42020-06-09 17:31:17 -07001947 audio_output_flags_t flags,
1948 audio_format_t format,
1949 audio_channel_mask_t channelMask,
1950 uint32_t samplingRate,
1951 audio_session_t sessionId)
Eric Laurente552edb2014-03-10 17:42:56 -07001952{
Eric Laurent16c66dd2019-05-01 17:54:10 -07001953 LOG_ALWAYS_FATAL_IF(!(format == AUDIO_FORMAT_INVALID || audio_is_linear_pcm(format)),
1954 "%s called with format %#x", __func__, format);
1955
jiabinebb6af42020-06-09 17:31:17 -07001956 // Return the output that haptic-generating attached to when 1) session id is specified,
1957 // 2) haptic-generating effect exists for given session id and 3) the output that
1958 // haptic-generating effect attached to is in given outputs.
1959 if (sessionId != AUDIO_SESSION_NONE) {
1960 audio_io_handle_t hapticGeneratingOutput = mEffects.getIoForSession(
1961 sessionId, FX_IID_HAPTICGENERATOR);
1962 if (outputs.indexOf(hapticGeneratingOutput) >= 0) {
1963 return hapticGeneratingOutput;
1964 }
1965 }
1966
Eric Laurent16c66dd2019-05-01 17:54:10 -07001967 // Flags disqualifying an output: the match must happen before calling selectOutput()
1968 static const audio_output_flags_t kExcludedFlags = (audio_output_flags_t)
1969 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ | AUDIO_OUTPUT_FLAG_DIRECT);
1970
1971 // Flags expressing a functional request: must be honored in priority over
1972 // other criteria
1973 static const audio_output_flags_t kFunctionalFlags = (audio_output_flags_t)
1974 (AUDIO_OUTPUT_FLAG_VOIP_RX | AUDIO_OUTPUT_FLAG_INCALL_MUSIC |
Eric Laurente28c66d2022-01-21 13:40:41 +01001975 AUDIO_OUTPUT_FLAG_TTS | AUDIO_OUTPUT_FLAG_DIRECT_PCM | AUDIO_OUTPUT_FLAG_ULTRASOUND |
1976 AUDIO_OUTPUT_FLAG_SPATIALIZER);
Eric Laurent16c66dd2019-05-01 17:54:10 -07001977 // Flags expressing a performance request: have lower priority than serving
1978 // requested sampling rate or channel mask
1979 static const audio_output_flags_t kPerformanceFlags = (audio_output_flags_t)
1980 (AUDIO_OUTPUT_FLAG_FAST | AUDIO_OUTPUT_FLAG_DEEP_BUFFER |
1981 AUDIO_OUTPUT_FLAG_RAW | AUDIO_OUTPUT_FLAG_SYNC);
1982
1983 const audio_output_flags_t functionalFlags =
1984 (audio_output_flags_t)(flags & kFunctionalFlags);
1985 const audio_output_flags_t performanceFlags =
1986 (audio_output_flags_t)(flags & kPerformanceFlags);
1987
1988 audio_io_handle_t bestOutput = (outputs.size() == 0) ? AUDIO_IO_HANDLE_NONE : outputs[0];
1989
Eric Laurente552edb2014-03-10 17:42:56 -07001990 // select one output among several that provide a path to a particular device or set of
François Gaffie11d30102018-11-02 16:09:09 +01001991 // devices (the list was previously build by getOutputsForDevices()).
Eric Laurente552edb2014-03-10 17:42:56 -07001992 // The priority is as follows:
jiabin40573322018-11-08 12:08:02 -08001993 // 1: the output supporting haptic playback when requesting haptic playback
Eric Laurent16c66dd2019-05-01 17:54:10 -07001994 // 2: the output with the highest number of requested functional flags
Carter Hsu199f1892021-10-15 15:47:29 +08001995 // with tiebreak preferring the minimum number of extra functional flags
1996 // (see b/200293124, the incorrect selection of AUDIO_OUTPUT_FLAG_VOIP_RX).
Eric Laurent16c66dd2019-05-01 17:54:10 -07001997 // 3: the output supporting the exact channel mask
1998 // 4: the output with a higher channel count than requested
jiabinb12a6da2022-06-03 20:48:18 +00001999 // 5: the output with the highest sampling rate if the requested sample rate is
2000 // greater than default sampling rate
Eric Laurent16c66dd2019-05-01 17:54:10 -07002001 // 6: the output with the highest number of requested performance flags
2002 // 7: the output with the bit depth the closest to the requested one
2003 // 8: the primary output
2004 // 9: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07002005
Eric Laurent16c66dd2019-05-01 17:54:10 -07002006 // matching criteria values in priority order for best matching output so far
2007 std::vector<uint32_t> bestMatchCriteria(8, 0);
Eric Laurente552edb2014-03-10 17:42:56 -07002008
Eric Laurent16c66dd2019-05-01 17:54:10 -07002009 const uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
2010 const uint32_t hapticChannelCount = audio_channel_count_from_out_mask(
2011 channelMask & AUDIO_CHANNEL_HAPTIC_ALL);
Eric Laurente78b6762018-12-19 16:29:01 -08002012
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002013 for (audio_io_handle_t output : outputs) {
2014 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent16c66dd2019-05-01 17:54:10 -07002015 // matching criteria values in priority order for current output
2016 std::vector<uint32_t> currentMatchCriteria(8, 0);
jiabin40573322018-11-08 12:08:02 -08002017
Eric Laurent16c66dd2019-05-01 17:54:10 -07002018 if (outputDesc->isDuplicated()) {
2019 continue;
2020 }
2021 if ((kExcludedFlags & outputDesc->mFlags) != 0) {
2022 continue;
2023 }
Eric Laurent8838a382014-09-08 16:44:28 -07002024
Eric Laurent16c66dd2019-05-01 17:54:10 -07002025 // If haptic channel is specified, use the haptic output if present.
2026 // When using haptic output, same audio format and sample rate are required.
2027 const uint32_t outputHapticChannelCount = audio_channel_count_from_out_mask(
jiabin5740f082019-08-19 15:08:30 -07002028 outputDesc->getChannelMask() & AUDIO_CHANNEL_HAPTIC_ALL);
Eric Laurent16c66dd2019-05-01 17:54:10 -07002029 if ((hapticChannelCount == 0) != (outputHapticChannelCount == 0)) {
2030 continue;
2031 }
2032 if (outputHapticChannelCount >= hapticChannelCount
jiabin5740f082019-08-19 15:08:30 -07002033 && format == outputDesc->getFormat()
2034 && samplingRate == outputDesc->getSamplingRate()) {
Eric Laurent16c66dd2019-05-01 17:54:10 -07002035 currentMatchCriteria[0] = outputHapticChannelCount;
2036 }
2037
2038 // functional flags match
Carter Hsu199f1892021-10-15 15:47:29 +08002039 const int matchingFunctionalFlags =
2040 __builtin_popcount(outputDesc->mFlags & functionalFlags);
2041 const int totalFunctionalFlags =
2042 __builtin_popcount(outputDesc->mFlags & kFunctionalFlags);
2043 // Prefer matching functional flags, but subtract unnecessary functional flags.
2044 currentMatchCriteria[1] = 100 * (matchingFunctionalFlags + 1) - totalFunctionalFlags;
Eric Laurent16c66dd2019-05-01 17:54:10 -07002045
2046 // channel mask and channel count match
jiabin5740f082019-08-19 15:08:30 -07002047 uint32_t outputChannelCount = audio_channel_count_from_out_mask(
2048 outputDesc->getChannelMask());
Eric Laurent16c66dd2019-05-01 17:54:10 -07002049 if (channelMask != AUDIO_CHANNEL_NONE && channelCount > 2 &&
2050 channelCount <= outputChannelCount) {
2051 if ((audio_channel_mask_get_representation(channelMask) ==
jiabin5740f082019-08-19 15:08:30 -07002052 audio_channel_mask_get_representation(outputDesc->getChannelMask())) &&
2053 ((channelMask & outputDesc->getChannelMask()) == channelMask)) {
Eric Laurent16c66dd2019-05-01 17:54:10 -07002054 currentMatchCriteria[2] = outputChannelCount;
Eric Laurente552edb2014-03-10 17:42:56 -07002055 }
Eric Laurent16c66dd2019-05-01 17:54:10 -07002056 currentMatchCriteria[3] = outputChannelCount;
2057 }
2058
2059 // sampling rate match
jiabinb12a6da2022-06-03 20:48:18 +00002060 if (samplingRate > SAMPLE_RATE_HZ_DEFAULT) {
jiabin5740f082019-08-19 15:08:30 -07002061 currentMatchCriteria[4] = outputDesc->getSamplingRate();
Eric Laurent16c66dd2019-05-01 17:54:10 -07002062 }
2063
2064 // performance flags match
2065 currentMatchCriteria[5] = popcount(outputDesc->mFlags & performanceFlags);
2066
2067 // format match
2068 if (format != AUDIO_FORMAT_INVALID) {
2069 currentMatchCriteria[6] =
jiabin4ef93452019-09-10 14:29:54 -07002070 PolicyAudioPort::kFormatDistanceMax -
2071 PolicyAudioPort::formatDistance(format, outputDesc->getFormat());
Eric Laurent16c66dd2019-05-01 17:54:10 -07002072 }
2073
2074 // primary output match
2075 currentMatchCriteria[7] = outputDesc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY;
2076
2077 // compare match criteria by priority then value
2078 if (std::lexicographical_compare(bestMatchCriteria.begin(), bestMatchCriteria.end(),
2079 currentMatchCriteria.begin(), currentMatchCriteria.end())) {
2080 bestMatchCriteria = currentMatchCriteria;
2081 bestOutput = output;
2082
2083 std::stringstream result;
2084 std::copy(bestMatchCriteria.begin(), bestMatchCriteria.end(),
2085 std::ostream_iterator<int>(result, " "));
2086 ALOGV("%s new bestOutput %d criteria %s",
2087 __func__, bestOutput, result.str().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07002088 }
2089 }
2090
Eric Laurent16c66dd2019-05-01 17:54:10 -07002091 return bestOutput;
Eric Laurente552edb2014-03-10 17:42:56 -07002092}
2093
Eric Laurent8fc147b2018-07-22 19:13:55 -07002094status_t AudioPolicyManager::startOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002095{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002096 ALOGV("%s portId %d", __FUNCTION__, portId);
2097
2098 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2099 if (outputDesc == 0) {
2100 ALOGW("startOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002101 return BAD_VALUE;
2102 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002103 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002104
Eric Laurent8fc147b2018-07-22 19:13:55 -07002105 ALOGV("startOutput() output %d, stream %d, session %d",
Eric Laurent97ac8712018-07-27 18:59:02 -07002106 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurentc75307b2015-03-17 15:29:32 -07002107
Eric Laurent733ce942017-12-07 12:18:25 -08002108 status_t status = outputDesc->start();
2109 if (status != NO_ERROR) {
2110 return status;
Eric Laurent3974e3b2017-12-07 17:58:43 -08002111 }
2112
Eric Laurent97ac8712018-07-27 18:59:02 -07002113 uint32_t delayMs;
2114 status = startSource(outputDesc, client, &delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07002115
2116 if (status != NO_ERROR) {
Eric Laurent733ce942017-12-07 12:18:25 -08002117 outputDesc->stop();
jiabin3ff8d7d2022-12-13 06:27:44 +00002118 if (status == DEAD_OBJECT) {
2119 sp<SwAudioOutputDescriptor> desc =
2120 reopenOutput(outputDesc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
2121 if (desc == nullptr) {
2122 // This is not common, it may indicate something wrong with the HAL.
2123 ALOGE("%s unable to open output with default config", __func__);
2124 return status;
2125 }
2126 desc->mUsePreferredMixerAttributes = true;
2127 }
Eric Laurent8c7e6da2015-04-21 17:37:00 -07002128 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07002129 }
jiabina84c3d32022-12-02 18:59:55 +00002130
2131 // If the client is the first one active on preferred mixer parameters, reopen the output
2132 // if the current mixer parameters doesn't match the preferred one.
2133 if (outputDesc->devices().size() == 1) {
2134 sp<PreferredMixerAttributesInfo> info = getPreferredMixerAttributesInfo(
2135 outputDesc->devices()[0]->getId(), client->strategy());
2136 if (info != nullptr && info->getUid() == client->uid()) {
2137 if (info->getActiveClientCount() == 0 && !outputDesc->isConfigurationMatched(
2138 info->getConfigBase(), info->getFlags())) {
2139 stopSource(outputDesc, client);
2140 outputDesc->stop();
2141 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
2142 config.channel_mask = info->getConfigBase().channel_mask;
2143 config.sample_rate = info->getConfigBase().sample_rate;
2144 config.format = info->getConfigBase().format;
jiabin3ff8d7d2022-12-13 06:27:44 +00002145 sp<SwAudioOutputDescriptor> desc =
2146 reopenOutput(outputDesc, &config, info->getFlags(), __func__);
2147 if (desc == nullptr) {
2148 return BAD_VALUE;
jiabina84c3d32022-12-02 18:59:55 +00002149 }
jiabin3ff8d7d2022-12-13 06:27:44 +00002150 desc->mUsePreferredMixerAttributes = true;
jiabina84c3d32022-12-02 18:59:55 +00002151 // Intentionally return error to let the client side resending request for
2152 // creating and starting.
2153 return DEAD_OBJECT;
2154 }
2155 info->increaseActiveClient();
jiabine3d1f552023-06-14 17:42:17 +00002156 if (info->getActiveClientCount() == 1 &&
2157 (info->getFlags() & AUDIO_OUTPUT_FLAG_BIT_PERFECT) != AUDIO_OUTPUT_FLAG_NONE) {
2158 // If it is first bit-perfect client, reroute all clients that will be routed to
2159 // the bit-perfect sink so that it is guaranteed only bit-perfect stream is active.
2160 PortHandleVector clientsToInvalidate;
2161 for (size_t i = 0; i < mOutputs.size(); i++) {
2162 if (mOutputs[i] == outputDesc ||
2163 !mOutputs[i]->devices().filter(outputDesc->devices()).isEmpty()) {
2164 continue;
2165 }
2166 for (const auto& c : mOutputs[i]->getClientIterable()) {
2167 clientsToInvalidate.push_back(c->portId());
2168 }
2169 }
2170 if (!clientsToInvalidate.empty()) {
2171 ALOGD("%s Invalidate clients due to first bit-perfect client started",
2172 __func__);
2173 mpClientInterface->invalidateTracks(clientsToInvalidate);
2174 }
2175 }
jiabina84c3d32022-12-02 18:59:55 +00002176 }
2177 }
2178
Jean-Michel Trivib1f6e642023-02-07 20:49:04 +00002179 if (client->hasPreferredDevice()) {
2180 // playback activity with preferred device impacts routing occurred, inform upper layers
2181 mpClientInterface->onRoutingUpdated();
2182 }
Eric Laurentc75307b2015-03-17 15:29:32 -07002183 if (delayMs != 0) {
2184 usleep(delayMs * 1000);
2185 }
2186
2187 return status;
2188}
2189
Eric Laurent96d1dda2022-03-14 17:14:19 +01002190bool AudioPolicyManager::isLeUnicastActive() const {
2191 if (isInCall()) {
2192 return true;
2193 }
2194 return isAnyDeviceTypeActive(getAudioDeviceOutLeAudioUnicastSet());
2195}
2196
2197bool AudioPolicyManager::isAnyDeviceTypeActive(const DeviceTypeSet& deviceTypes) const {
2198 if (mAvailableOutputDevices.getDevicesFromTypes(deviceTypes).isEmpty()) {
2199 return false;
2200 }
2201 bool active = mOutputs.isAnyDeviceTypeActive(deviceTypes);
2202 ALOGV("%s active %d", __func__, active);
2203 return active;
2204}
2205
Eric Laurent97ac8712018-07-27 18:59:02 -07002206status_t AudioPolicyManager::startSource(const sp<SwAudioOutputDescriptor>& outputDesc,
2207 const sp<TrackClientDescriptor>& client,
2208 uint32_t *delayMs)
Eric Laurentc75307b2015-03-17 15:29:32 -07002209{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002210 // cannot start playback of STREAM_TTS if any other output is being used
2211 uint32_t beaconMuteLatency = 0;
Eric Laurentc75307b2015-03-17 15:29:32 -07002212
2213 *delayMs = 0;
Eric Laurent97ac8712018-07-27 18:59:02 -07002214 audio_stream_type_t stream = client->stream();
François Gaffie1c878552018-11-22 16:53:21 +01002215 auto clientVolSrc = client->volumeSource();
François Gaffiec005e562018-11-06 15:04:49 +01002216 auto clientStrategy = client->strategy();
2217 auto clientAttr = client->attributes();
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002218 if (stream == AUDIO_STREAM_TTS) {
2219 ALOGV("\t found BEACON stream");
François Gaffie1c878552018-11-22 16:53:21 +01002220 if (!mTtsOutputAvailable && mOutputs.isAnyOutputActive(
Francois Gaffie4404ddb2021-02-04 17:03:38 +01002221 toVolumeSource(AUDIO_STREAM_TTS, false) /*sourceToIgnore*/)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002222 return INVALID_OPERATION;
2223 } else {
2224 beaconMuteLatency = handleEventForBeacon(STARTING_BEACON);
2225 }
2226 } else {
2227 // some playback other than beacon starts
2228 beaconMuteLatency = handleEventForBeacon(STARTING_OUTPUT);
2229 }
2230
Eric Laurent77305a62016-07-25 16:39:22 -07002231 // force device change if the output is inactive and no audio patch is already present.
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002232 // check active before incrementing usage count
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02002233 bool force = !outputDesc->isActive() && !outputDesc->isRouted();
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002234
François Gaffie11d30102018-11-02 16:09:09 +01002235 DeviceVector devices;
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002236 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
Eric Laurent97ac8712018-07-27 18:59:02 -07002237 const char *address = NULL;
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002238 if (policyMix != nullptr) {
François Gaffie11d30102018-11-02 16:09:09 +01002239 audio_devices_t newDeviceType;
Eric Laurent97ac8712018-07-27 18:59:02 -07002240 address = policyMix->mDeviceAddress.string();
Kevin Rocard153f92d2018-12-18 18:33:28 -08002241 if ((policyMix->mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie11d30102018-11-02 16:09:09 +01002242 newDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Kevin Rocard153f92d2018-12-18 18:33:28 -08002243 } else {
2244 newDeviceType = policyMix->mDeviceType;
Eric Laurent97ac8712018-07-27 18:59:02 -07002245 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08002246 sp device = mAvailableOutputDevices.getDevice(newDeviceType, String8(address),
2247 AUDIO_FORMAT_DEFAULT);
2248 ALOG_ASSERT(device, "%s: no device found t=%u, a=%s", __func__, newDeviceType, address);
2249 devices.add(device);
Eric Laurent97ac8712018-07-27 18:59:02 -07002250 }
2251
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002252 // requiresMuteCheck is false when we can bypass mute strategy.
2253 // It covers a common case when there is no materially active audio
2254 // and muting would result in unnecessary delay and dropped audio.
2255 const uint32_t outputLatencyMs = outputDesc->latency();
2256 bool requiresMuteCheck = outputDesc->isActive(outputLatencyMs * 2); // account for drain
Eric Laurent96d1dda2022-03-14 17:14:19 +01002257 bool wasLeUnicastActive = isLeUnicastActive();
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002258
Eric Laurente552edb2014-03-10 17:42:56 -07002259 // increment usage count for this stream on the requested output:
2260 // NOTE that the usage count is the same for duplicated output and hardware output which is
2261 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
Eric Laurent592dd7b2018-08-05 18:58:48 -07002262 outputDesc->setClientActive(client, true);
Eric Laurent97ac8712018-07-27 18:59:02 -07002263
2264 if (client->hasPreferredDevice(true)) {
Eric Laurent72af8012023-03-15 17:36:22 +01002265 if (outputDesc->sameExclusivePreferredDevicesCount() > 0) {
François Gaffief96e5432019-04-09 17:13:56 +02002266 // Preferred device may be exclusive, use only if no other active clients on this output
2267 devices = DeviceVector(
2268 mAvailableOutputDevices.getDeviceFromId(client->preferredDeviceId()));
2269 } else {
2270 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
2271 }
François Gaffie11d30102018-11-02 16:09:09 +01002272 if (devices != outputDesc->devices()) {
François Gaffiec005e562018-11-06 15:04:49 +01002273 checkStrategyRoute(clientStrategy, outputDesc->mIoHandle);
Eric Laurent97ac8712018-07-27 18:59:02 -07002274 }
2275 }
Eric Laurente552edb2014-03-10 17:42:56 -07002276
François Gaffiec005e562018-11-06 15:04:49 +01002277 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07002278 selectOutputForMusicEffects();
2279 }
2280
François Gaffie1c878552018-11-22 16:53:21 +01002281 if (outputDesc->getActivityCount(clientVolSrc) == 1 || !devices.isEmpty()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08002282 // starting an output being rerouted?
François Gaffie11d30102018-11-02 16:09:09 +01002283 if (devices.isEmpty()) {
2284 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Eric Laurent275e8e92014-11-30 15:14:47 -08002285 }
François Gaffiec005e562018-11-06 15:04:49 +01002286 bool shouldWait =
2287 (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM)) ||
2288 followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_NOTIFICATION)) ||
2289 (beaconMuteLatency > 0));
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002290 uint32_t waitMs = beaconMuteLatency;
Eric Laurente552edb2014-03-10 17:42:56 -07002291 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01002292 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07002293 if (desc != outputDesc) {
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002294 // An output has a shared device if
2295 // - managed by the same hw module
2296 // - supports the currently selected device
2297 const bool sharedDevice = outputDesc->sharesHwModuleWith(desc)
François Gaffie11d30102018-11-02 16:09:09 +01002298 && (!desc->filterSupportedDevices(devices).isEmpty());
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002299
Eric Laurent77305a62016-07-25 16:39:22 -07002300 // force a device change if any other output is:
2301 // - managed by the same hw module
Jean-Michel Trivi4a5b4812018-02-08 17:22:32 +00002302 // - supports currently selected device
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002303 // - has a current device selection that differs from selected device.
Eric Laurent77305a62016-07-25 16:39:22 -07002304 // - has an active audio patch
Eric Laurente552edb2014-03-10 17:42:56 -07002305 // In this case, the audio HAL must receive the new device selection so that it can
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002306 // change the device currently selected by the other output.
2307 if (sharedDevice &&
François Gaffie11d30102018-11-02 16:09:09 +01002308 desc->devices() != devices &&
Eric Laurent77305a62016-07-25 16:39:22 -07002309 desc->getPatchHandle() != AUDIO_PATCH_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07002310 force = true;
2311 }
2312 // wait for audio on other active outputs to be presented when starting
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002313 // a notification so that audio focus effect can propagate, or that a mute/unmute
2314 // event occurred for beacon
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002315 const uint32_t latencyMs = desc->latency();
2316 const bool isActive = desc->isActive(latencyMs * 2); // account for drain
2317
2318 if (shouldWait && isActive && (waitMs < latencyMs)) {
2319 waitMs = latencyMs;
Eric Laurente552edb2014-03-10 17:42:56 -07002320 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002321
2322 // Require mute check if another output is on a shared device
2323 // and currently active to have proper drain and avoid pops.
2324 // Note restoring AudioTracks onto this output needs to invoke
2325 // a volume ramp if there is no mute.
2326 requiresMuteCheck |= sharedDevice && isActive;
Eric Laurente552edb2014-03-10 17:42:56 -07002327 }
2328 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002329
jiabin3ff8d7d2022-12-13 06:27:44 +00002330 if (outputDesc->mUsePreferredMixerAttributes && devices != outputDesc->devices()) {
2331 // If the output is open with preferred mixer attributes, but the routed device is
2332 // changed when calling this function, returning DEAD_OBJECT to indicate routing
2333 // changed.
2334 return DEAD_OBJECT;
2335 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002336 const uint32_t muteWaitMs =
jiabin3ff8d7d2022-12-13 06:27:44 +00002337 setOutputDevices(outputDesc, devices, force, 0, nullptr, requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07002338
Eric Laurente552edb2014-03-10 17:42:56 -07002339 // apply volume rules for current stream and device if necessary
François Gaffieaaac0fd2018-11-22 17:56:39 +01002340 auto &curves = getVolumeCurves(client->attributes());
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00002341 if (NO_ERROR != checkAndSetVolume(curves, client->volumeSource(),
François Gaffieaaac0fd2018-11-22 17:56:39 +01002342 curves.getVolumeIndex(outputDesc->devices().types()),
Eric Laurentc75307b2015-03-17 15:29:32 -07002343 outputDesc,
Francois Gaffied11442b2020-04-27 11:51:09 +02002344 outputDesc->devices().types(), 0 /*delay*/,
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00002345 outputDesc->useHwGain() /*force*/)) {
2346 // request AudioService to reinitialize the volume curves asynchronously
2347 ALOGE("checkAndSetVolume failed, requesting volume range init");
2348 mpClientInterface->onVolumeRangeInitRequest();
2349 };
Eric Laurente552edb2014-03-10 17:42:56 -07002350
2351 // update the outputs if starting an output with a stream that can affect notification
2352 // routing
2353 handleNotificationRoutingForStream(stream);
Eric Laurentc722f302014-12-10 11:21:49 -08002354
Eric Laurent2cbe89a2014-12-19 11:49:08 -08002355 // force reevaluating accessibility routing when ringtone or alarm starts
François Gaffiec005e562018-11-06 15:04:49 +01002356 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM))) {
jiabinc44b3462022-12-08 12:52:31 -08002357 invalidateStreams({AUDIO_STREAM_ACCESSIBILITY});
Eric Laurent2cbe89a2014-12-19 11:49:08 -08002358 }
Eric Laurentdc462862016-07-19 12:29:53 -07002359
2360 if (waitMs > muteWaitMs) {
2361 *delayMs = waitMs - muteWaitMs;
2362 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002363
2364 // FIXME: A device change (muteWaitMs > 0) likely introduces a volume change.
2365 // A volume change enacted by APM with 0 delay is not synchronous, as it goes
2366 // via AudioCommandThread to AudioFlinger. Hence it is possible that the volume
2367 // change occurs after the MixerThread starts and causes a stream volume
2368 // glitch.
2369 //
2370 // We do not introduce additional delay here.
Eric Laurente552edb2014-03-10 17:42:56 -07002371 }
Eric Laurentdc462862016-07-19 12:29:53 -07002372
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002373 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
jiabin9a3361e2019-10-01 09:38:30 -07002374 mEngine->getForceUse(
2375 AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
François Gaffiec005e562018-11-06 15:04:49 +01002376 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), true, outputDesc);
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002377 }
2378
Eric Laurent97ac8712018-07-27 18:59:02 -07002379 // Automatically enable the remote submix input when output is started on a re routing mix
2380 // of type MIX_TYPE_RECORDERS
jiabin9a3361e2019-10-01 09:38:30 -07002381 if (isSingleDeviceType(devices.types(), &audio_is_remote_submix_device) &&
2382 policyMix != NULL && policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002383 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2384 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2385 address,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002386 "remote-submix",
2387 AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07002388 }
2389
Eric Laurent96d1dda2022-03-14 17:14:19 +01002390 checkLeBroadcastRoutes(wasLeUnicastActive, outputDesc, *delayMs);
2391
Eric Laurente552edb2014-03-10 17:42:56 -07002392 return NO_ERROR;
2393}
2394
Eric Laurent96d1dda2022-03-14 17:14:19 +01002395void AudioPolicyManager::checkLeBroadcastRoutes(bool wasUnicastActive,
2396 sp<SwAudioOutputDescriptor> ignoredOutput, uint32_t delayMs) {
2397 bool isUnicastActive = isLeUnicastActive();
2398
2399 if (wasUnicastActive != isUnicastActive) {
jiabin3ff8d7d2022-12-13 06:27:44 +00002400 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent96d1dda2022-03-14 17:14:19 +01002401 //reroute all outputs routed to LE broadcast if LE unicast activy changed on any output
2402 for (size_t i = 0; i < mOutputs.size(); i++) {
2403 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
2404 if (desc != ignoredOutput && desc->isActive()
2405 && ((isUnicastActive &&
2406 !desc->devices().
2407 getDevicesFromType(AUDIO_DEVICE_OUT_BLE_BROADCAST).isEmpty())
2408 || (wasUnicastActive &&
2409 !desc->devices().getDevicesFromTypes(
2410 getAudioDeviceOutLeAudioUnicastSet()).isEmpty()))) {
2411 DeviceVector newDevices = getNewOutputDevices(desc, false /*fromCache*/);
2412 bool force = desc->devices() != newDevices;
jiabin3ff8d7d2022-12-13 06:27:44 +00002413 if (desc->mUsePreferredMixerAttributes && force) {
2414 // If the device is using preferred mixer attributes, the output need to reopen
2415 // with default configuration when the new selected devices are different from
2416 // current routing devices.
2417 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices);
2418 continue;
2419 }
Eric Laurent96d1dda2022-03-14 17:14:19 +01002420 setOutputDevices(desc, newDevices, force, delayMs);
2421 // re-apply device specific volume if not done by setOutputDevice()
2422 if (!force) {
2423 applyStreamVolumes(desc, newDevices.types(), delayMs);
2424 }
2425 }
2426 }
jiabin3ff8d7d2022-12-13 06:27:44 +00002427 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent96d1dda2022-03-14 17:14:19 +01002428 }
2429}
2430
Eric Laurent8fc147b2018-07-22 19:13:55 -07002431status_t AudioPolicyManager::stopOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002432{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002433 ALOGV("%s portId %d", __FUNCTION__, portId);
2434
2435 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2436 if (outputDesc == 0) {
2437 ALOGW("stopOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002438 return BAD_VALUE;
2439 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002440 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002441
Jean-Michel Trivib1f6e642023-02-07 20:49:04 +00002442 if (client->hasPreferredDevice(true)) {
2443 // playback activity with preferred device impacts routing occurred, inform upper layers
2444 mpClientInterface->onRoutingUpdated();
2445 }
2446
Eric Laurent97ac8712018-07-27 18:59:02 -07002447 ALOGV("stopOutput() output %d, stream %d, session %d",
2448 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurente552edb2014-03-10 17:42:56 -07002449
Eric Laurent97ac8712018-07-27 18:59:02 -07002450 status_t status = stopSource(outputDesc, client);
Eric Laurent3974e3b2017-12-07 17:58:43 -08002451
Eric Laurent733ce942017-12-07 12:18:25 -08002452 if (status == NO_ERROR ) {
2453 outputDesc->stop();
jiabina84c3d32022-12-02 18:59:55 +00002454 } else {
2455 return status;
2456 }
2457
2458 if (outputDesc->devices().size() == 1) {
2459 sp<PreferredMixerAttributesInfo> info = getPreferredMixerAttributesInfo(
2460 outputDesc->devices()[0]->getId(), client->strategy());
2461 if (info != nullptr && info->getUid() == client->uid()) {
2462 info->decreaseActiveClient();
2463 if (info->getActiveClientCount() == 0) {
2464 reopenOutput(outputDesc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
2465 }
2466 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002467 }
2468 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07002469}
2470
Eric Laurent97ac8712018-07-27 18:59:02 -07002471status_t AudioPolicyManager::stopSource(const sp<SwAudioOutputDescriptor>& outputDesc,
2472 const sp<TrackClientDescriptor>& client)
Eric Laurentc75307b2015-03-17 15:29:32 -07002473{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002474 // always handle stream stop, check which stream type is stopping
Eric Laurent97ac8712018-07-27 18:59:02 -07002475 audio_stream_type_t stream = client->stream();
François Gaffie1c878552018-11-22 16:53:21 +01002476 auto clientVolSrc = client->volumeSource();
Eric Laurent96d1dda2022-03-14 17:14:19 +01002477 bool wasLeUnicastActive = isLeUnicastActive();
Eric Laurent97ac8712018-07-27 18:59:02 -07002478
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002479 handleEventForBeacon(stream == AUDIO_STREAM_TTS ? STOPPING_BEACON : STOPPING_OUTPUT);
2480
François Gaffie1c878552018-11-22 16:53:21 +01002481 if (outputDesc->getActivityCount(clientVolSrc) > 0) {
2482 if (outputDesc->getActivityCount(clientVolSrc) == 1) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002483 // Automatically disable the remote submix input when output is stopped on a
2484 // re routing mix of type MIX_TYPE_RECORDERS
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002485 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
jiabin9a3361e2019-10-01 09:38:30 -07002486 if (isSingleDeviceType(
2487 outputDesc->devices().types(), &audio_is_remote_submix_device) &&
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002488 policyMix != nullptr &&
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002489 policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002490 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2491 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002492 policyMix->mDeviceAddress,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002493 "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07002494 }
2495 }
2496 bool forceDeviceUpdate = false;
Eric Laurent72af8012023-03-15 17:36:22 +01002497 if (client->hasPreferredDevice(true) &&
2498 outputDesc->sameExclusivePreferredDevicesCount() < 2) {
François Gaffiec005e562018-11-06 15:04:49 +01002499 checkStrategyRoute(client->strategy(), AUDIO_IO_HANDLE_NONE);
Eric Laurent97ac8712018-07-27 18:59:02 -07002500 forceDeviceUpdate = true;
2501 }
2502
Eric Laurente552edb2014-03-10 17:42:56 -07002503 // decrement usage count of this stream on the output
Eric Laurent592dd7b2018-08-05 18:58:48 -07002504 outputDesc->setClientActive(client, false);
Paul McLeanaa981192015-03-21 09:55:15 -07002505
Eric Laurente552edb2014-03-10 17:42:56 -07002506 // store time at which the stream was stopped - see isStreamActive()
François Gaffie1c878552018-11-22 16:53:21 +01002507 if (outputDesc->getActivityCount(clientVolSrc) == 0 || forceDeviceUpdate) {
François Gaffiec005e562018-11-06 15:04:49 +01002508 outputDesc->setStopTime(client, systemTime());
François Gaffie11d30102018-11-02 16:09:09 +01002509 DeviceVector newDevices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Francois Gaffie3523ab32021-06-22 13:24:34 +02002510
2511 // If the routing does not change, if an output is routed on a device using HwGain
2512 // (aka setAudioPortConfig) and there are still active clients following different
2513 // volume group(s), force reapply volume
2514 bool requiresVolumeCheck = outputDesc->getActivityCount(clientVolSrc) == 0 &&
2515 outputDesc->useHwGain() && outputDesc->isAnyActive(VOLUME_SOURCE_NONE);
2516
Eric Laurente552edb2014-03-10 17:42:56 -07002517 // delay the device switch by twice the latency because stopOutput() is executed when
2518 // the track stop() command is received and at that time the audio track buffer can
2519 // still contain data that needs to be drained. The latency only covers the audio HAL
2520 // and kernel buffers. Also the latency does not always include additional delay in the
2521 // audio path (audio DSP, CODEC ...)
Francois Gaffie3523ab32021-06-22 13:24:34 +02002522 setOutputDevices(outputDesc, newDevices, false, outputDesc->latency()*2,
2523 nullptr, true /*requiresMuteCheck*/, requiresVolumeCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07002524
2525 // force restoring the device selection on other active outputs if it differs from the
2526 // one being selected for this output
jiabin3ff8d7d2022-12-13 06:27:44 +00002527 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent57de36c2016-09-28 16:59:11 -07002528 uint32_t delayMs = outputDesc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -07002529 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01002530 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07002531 if (desc != outputDesc &&
Eric Laurente552edb2014-03-10 17:42:56 -07002532 desc->isActive() &&
2533 outputDesc->sharesHwModuleWith(desc) &&
François Gaffie11d30102018-11-02 16:09:09 +01002534 (newDevices != desc->devices())) {
2535 DeviceVector newDevices2 = getNewOutputDevices(desc, false /*fromCache*/);
2536 bool force = desc->devices() != newDevices2;
Eric Laurentf3a5a602018-05-22 18:42:55 -07002537
jiabin3ff8d7d2022-12-13 06:27:44 +00002538 if (desc->mUsePreferredMixerAttributes && force) {
2539 // If the device is using preferred mixer attributes, the output need to
2540 // reopen with default configuration when the new selected devices are
2541 // different from current routing devices.
2542 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices2);
2543 continue;
2544 }
François Gaffie11d30102018-11-02 16:09:09 +01002545 setOutputDevices(desc, newDevices2, force, delayMs);
2546
Eric Laurent57de36c2016-09-28 16:59:11 -07002547 // re-apply device specific volume if not done by setOutputDevice()
2548 if (!force) {
François Gaffie11d30102018-11-02 16:09:09 +01002549 applyStreamVolumes(desc, newDevices2.types(), delayMs);
Eric Laurent57de36c2016-09-28 16:59:11 -07002550 }
Eric Laurente552edb2014-03-10 17:42:56 -07002551 }
2552 }
jiabin3ff8d7d2022-12-13 06:27:44 +00002553 reopenOutputsWithDevices(outputsToReopen);
Eric Laurente552edb2014-03-10 17:42:56 -07002554 // update the outputs if stopping one with a stream that can affect notification routing
2555 handleNotificationRoutingForStream(stream);
2556 }
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002557
2558 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
2559 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Jean-Michel Trivi74e01fa2019-02-25 12:18:09 -08002560 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), false, outputDesc);
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002561 }
2562
François Gaffiec005e562018-11-06 15:04:49 +01002563 if (followsSameRouting(client->attributes(), attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07002564 selectOutputForMusicEffects();
2565 }
Eric Laurent96d1dda2022-03-14 17:14:19 +01002566
2567 checkLeBroadcastRoutes(wasLeUnicastActive, outputDesc, outputDesc->latency()*2);
2568
Eric Laurente552edb2014-03-10 17:42:56 -07002569 return NO_ERROR;
2570 } else {
Eric Laurentc75307b2015-03-17 15:29:32 -07002571 ALOGW("stopOutput() refcount is already 0");
Eric Laurente552edb2014-03-10 17:42:56 -07002572 return INVALID_OPERATION;
2573 }
2574}
2575
jiabinbce0c1d2020-10-05 11:20:18 -07002576bool AudioPolicyManager::releaseOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002577{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002578 ALOGV("%s portId %d", __FUNCTION__, portId);
2579
2580 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2581 if (outputDesc == 0) {
Andy Hung39efb7a2018-09-26 15:39:28 -07002582 // If an output descriptor is closed due to a device routing change,
2583 // then there are race conditions with releaseOutput from tracks
2584 // that may be destroyed (with no PlaybackThread) or a PlaybackThread
2585 // destroyed shortly thereafter.
2586 //
2587 // Here we just log a warning, instead of a fatal error.
Eric Laurent8fc147b2018-07-22 19:13:55 -07002588 ALOGW("releaseOutput() no output for client %d", portId);
jiabinbce0c1d2020-10-05 11:20:18 -07002589 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002590 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002591
2592 ALOGV("releaseOutput() %d", outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -07002593
Jaideep Sharma7bf382e2020-11-26 17:07:29 +05302594 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
2595 if (outputDesc->isClientActive(client)) {
2596 ALOGW("releaseOutput() inactivates portId %d in good faith", portId);
2597 stopOutput(portId);
2598 }
2599
Eric Laurent8fc147b2018-07-22 19:13:55 -07002600 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
2601 if (outputDesc->mDirectOpenCount <= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07002602 ALOGW("releaseOutput() invalid open count %d for output %d",
Eric Laurent8fc147b2018-07-22 19:13:55 -07002603 outputDesc->mDirectOpenCount, outputDesc->mIoHandle);
jiabinbce0c1d2020-10-05 11:20:18 -07002604 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002605 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002606 if (--outputDesc->mDirectOpenCount == 0) {
2607 closeOutput(outputDesc->mIoHandle);
Eric Laurentb52c1522014-05-20 11:27:36 -07002608 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07002609 }
2610 }
Jaideep Sharma7bf382e2020-11-26 17:07:29 +05302611
Andy Hung39efb7a2018-09-26 15:39:28 -07002612 outputDesc->removeClient(portId);
jiabinbce0c1d2020-10-05 11:20:18 -07002613 if (outputDesc->mPendingReopenToQueryProfiles && outputDesc->getClientCount() == 0) {
2614 // The output is pending reopened to query dynamic profiles and
2615 // there is no active clients
2616 closeOutput(outputDesc->mIoHandle);
2617 sp<SwAudioOutputDescriptor> newOutputDesc = openOutputWithProfileAndDevice(
2618 outputDesc->mProfile, mEngine->getActiveMediaDevices(mAvailableOutputDevices));
2619 if (newOutputDesc == nullptr) {
2620 ALOGE("%s failed to open output", __func__);
2621 }
2622 return true;
2623 }
2624 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002625}
2626
Eric Laurentcaf7f482014-11-25 17:50:47 -08002627status_t AudioPolicyManager::getInputForAttr(const audio_attributes_t *attr,
2628 audio_io_handle_t *input,
Mikhail Naganov2996f672019-04-18 12:29:59 -07002629 audio_unique_id_t riid,
Eric Laurentcaf7f482014-11-25 17:50:47 -08002630 audio_session_t session,
Svet Ganov3e5f14f2021-05-13 22:51:08 +00002631 const AttributionSourceState& attributionSource,
jiabinf1c73972022-04-14 16:28:52 -07002632 audio_config_base_t *config,
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002633 audio_input_flags_t flags,
Eric Laurent2ac76942017-06-22 17:17:09 -07002634 audio_port_handle_t *selectedDeviceId,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002635 input_type_t *inputType,
2636 audio_port_handle_t *portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002637{
François Gaffiec005e562018-11-06 15:04:49 +01002638 ALOGV("%s() source %d, sampling rate %d, format %#x, channel mask %#x, session %d, "
Eric Laurent2f2c1982021-06-02 14:03:11 +02002639 "flags %#x attributes=%s requested device ID %d",
2640 __func__, attr->source, config->sample_rate, config->format, config->channel_mask,
2641 session, flags, toString(*attr).c_str(), *selectedDeviceId);
Eric Laurente552edb2014-03-10 17:42:56 -07002642
Eric Laurentad2e7b92017-09-14 20:06:42 -07002643 status_t status = NO_ERROR;
Francois Gaffie716e1432019-01-14 16:58:59 +01002644 audio_attributes_t attributes = *attr;
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002645 sp<AudioPolicyMix> policyMix;
François Gaffie11d30102018-11-02 16:09:09 +01002646 sp<DeviceDescriptor> device;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002647 sp<AudioInputDescriptor> inputDesc;
2648 sp<RecordClientDescriptor> clientDesc;
2649 audio_port_handle_t requestedDeviceId = *selectedDeviceId;
Svet Ganov3e5f14f2021-05-13 22:51:08 +00002650 uid_t uid = VALUE_OR_RETURN_STATUS(aidl2legacy_int32_t_uid_t(attributionSource.uid));
Eric Laurent8f42ea12018-08-08 09:08:25 -07002651 bool isSoundTrigger;
Eric Laurent8f42ea12018-08-08 09:08:25 -07002652
2653 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
2654 if (*portId != AUDIO_PORT_HANDLE_NONE) {
2655 return INVALID_OPERATION;
2656 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08002657
Francois Gaffie716e1432019-01-14 16:58:59 +01002658 if (attr->source == AUDIO_SOURCE_DEFAULT) {
2659 attributes.source = AUDIO_SOURCE_MIC;
Eric Laurentfe231122017-11-17 17:48:06 -08002660 }
2661
Paul McLean466dc8e2015-04-17 13:15:36 -06002662 // Explicit routing?
Pattydd807582021-11-04 21:01:03 +08002663 sp<DeviceDescriptor> explicitRoutingDevice =
François Gaffie11d30102018-11-02 16:09:09 +01002664 mAvailableInputDevices.getDeviceFromId(*selectedDeviceId);
Paul McLean466dc8e2015-04-17 13:15:36 -06002665
Eric Laurentad2e7b92017-09-14 20:06:42 -07002666 // special case for mmap capture: if an input IO handle is specified, we reuse this input if
2667 // possible
2668 if ((flags & AUDIO_INPUT_FLAG_MMAP_NOIRQ) == AUDIO_INPUT_FLAG_MMAP_NOIRQ &&
2669 *input != AUDIO_IO_HANDLE_NONE) {
2670 ssize_t index = mInputs.indexOfKey(*input);
2671 if (index < 0) {
2672 ALOGW("getInputForAttr() unknown MMAP input %d", *input);
2673 status = BAD_VALUE;
2674 goto error;
2675 }
2676 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002677 RecordClientVector clients = inputDesc->getClientsForSession(session);
2678 if (clients.size() == 0) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07002679 ALOGW("getInputForAttr() unknown session %d on input %d", session, *input);
2680 status = BAD_VALUE;
2681 goto error;
2682 }
2683 // For MMAP mode, the first call to getInputForAttr() is made on behalf of audioflinger.
2684 // The second call is for the first active client and sets the UID. Any further call
Eric Laurent331679c2018-04-16 17:03:16 -07002685 // corresponds to a new client and is only permitted from the same UID.
2686 // If the first UID is silenced, allow a new UID connection and replace with new UID
Eric Laurent8f42ea12018-08-08 09:08:25 -07002687 if (clients.size() > 1) {
2688 for (const auto& client : clients) {
2689 // The client map is ordered by key values (portId) and portIds are allocated
2690 // incrementaly. So the first client in this list is the one opened by audio flinger
2691 // when the mmap stream is created and should be ignored as it does not correspond
2692 // to an actual client
2693 if (client == *clients.cbegin()) {
2694 continue;
2695 }
2696 if (uid != client->uid() && !client->isSilenced()) {
2697 ALOGW("getInputForAttr() bad uid %d for client %d uid %d",
2698 uid, client->portId(), client->uid());
2699 status = INVALID_OPERATION;
2700 goto error;
2701 }
Eric Laurent331679c2018-04-16 17:03:16 -07002702 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002703 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002704 *inputType = API_INPUT_LEGACY;
François Gaffie11d30102018-11-02 16:09:09 +01002705 device = inputDesc->getDevice();
Eric Laurentad2e7b92017-09-14 20:06:42 -07002706
Eric Laurentfecbceb2021-02-09 14:46:43 +01002707 ALOGV("%s reusing MMAP input %d for session %d", __FUNCTION__, *input, session);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002708 goto exit;
Eric Laurentad2e7b92017-09-14 20:06:42 -07002709 }
2710
2711 *input = AUDIO_IO_HANDLE_NONE;
2712 *inputType = API_INPUT_INVALID;
2713
Francois Gaffie716e1432019-01-14 16:58:59 +01002714 if (attributes.source == AUDIO_SOURCE_REMOTE_SUBMIX &&
Jan Sebechlebskybc56bcd2022-09-26 13:15:19 +02002715 extractAddressFromAudioAttributes(attributes).has_value()) {
Francois Gaffie716e1432019-01-14 16:58:59 +01002716 status = mPolicyMixes.getInputMixForAttr(attributes, &policyMix);
Eric Laurentad2e7b92017-09-14 20:06:42 -07002717 if (status != NO_ERROR) {
jiabinc1de2df2019-05-07 14:26:40 -07002718 ALOGW("%s could not find input mix for attr %s",
2719 __func__, toString(attributes).c_str());
Eric Laurentad2e7b92017-09-14 20:06:42 -07002720 goto error;
François Gaffie036e1e92015-03-19 10:16:24 +01002721 }
jiabinc1de2df2019-05-07 14:26:40 -07002722 device = mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2723 String8(attr->tags + strlen("addr=")),
2724 AUDIO_FORMAT_DEFAULT);
2725 if (device == nullptr) {
Kevin Rocard04ed0462019-05-02 17:53:24 -07002726 ALOGW("%s could not find in Remote Submix device for source %d, tags %s",
jiabinc1de2df2019-05-07 14:26:40 -07002727 __func__, attributes.source, attributes.tags);
2728 status = BAD_VALUE;
2729 goto error;
2730 }
2731
Kevin Rocard25f9b052019-02-27 15:08:54 -08002732 if (is_mix_loopback_render(policyMix->mRouteFlags)) {
2733 *inputType = API_INPUT_MIX_PUBLIC_CAPTURE_PLAYBACK;
2734 } else {
2735 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
2736 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002737 } else {
François Gaffie11d30102018-11-02 16:09:09 +01002738 if (explicitRoutingDevice != nullptr) {
2739 device = explicitRoutingDevice;
Eric Laurent97ac8712018-07-27 18:59:02 -07002740 } else {
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01002741 // Prevent from storing invalid requested device id in clients
2742 requestedDeviceId = AUDIO_PORT_HANDLE_NONE;
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02002743 device = mEngine->getInputDeviceForAttributes(attributes, uid, session, &policyMix);
yuanjiahsu4069d5d2021-04-19 07:54:27 +08002744 ALOGV_IF(device != nullptr, "%s found device type is 0x%X",
2745 __FUNCTION__, device->type());
Eric Laurent97ac8712018-07-27 18:59:02 -07002746 }
François Gaffie11d30102018-11-02 16:09:09 +01002747 if (device == nullptr) {
Francois Gaffie716e1432019-01-14 16:58:59 +01002748 ALOGW("getInputForAttr() could not find device for source %d", attributes.source);
Eric Laurentad2e7b92017-09-14 20:06:42 -07002749 status = BAD_VALUE;
2750 goto error;
Eric Laurent275e8e92014-11-30 15:14:47 -08002751 }
Alden DSouzab7d20782021-02-08 08:51:42 -08002752 if (device->type() == AUDIO_DEVICE_IN_ECHO_REFERENCE) {
2753 *inputType = API_INPUT_MIX_CAPTURE;
2754 } else if (policyMix) {
François Gaffie11d30102018-11-02 16:09:09 +01002755 ALOG_ASSERT(policyMix->mMixType == MIX_TYPE_RECORDERS, "Invalid Mix Type");
2756 // there is an external policy, but this input is attached to a mix of recorders,
2757 // meaning it receives audio injected into the framework, so the recorder doesn't
2758 // know about it and is therefore considered "legacy"
2759 *inputType = API_INPUT_LEGACY;
2760 } else if (audio_is_remote_submix_device(device->type())) {
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002761 *inputType = API_INPUT_MIX_CAPTURE;
François Gaffie11d30102018-11-02 16:09:09 +01002762 } else if (device->type() == AUDIO_DEVICE_IN_TELEPHONY_RX) {
Eric Laurent82db2692015-08-07 13:59:42 -07002763 *inputType = API_INPUT_TELEPHONY_RX;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002764 } else {
2765 *inputType = API_INPUT_LEGACY;
Eric Laurentc722f302014-12-10 11:21:49 -08002766 }
Ravi Kumar Alamandab367f5b2015-08-25 08:21:37 -07002767
Eric Laurent599c7582015-12-07 18:05:55 -08002768 }
2769
François Gaffiec005e562018-11-06 15:04:49 +01002770 *input = getInputForDevice(device, session, attributes, config, flags, policyMix);
Eric Laurent599c7582015-12-07 18:05:55 -08002771 if (*input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07002772 status = INVALID_OPERATION;
jiabinf1c73972022-04-14 16:28:52 -07002773 AudioProfileVector profiles;
2774 status_t ret = getProfilesForDevices(
2775 DeviceVector(device), profiles, flags, true /*isInput*/);
2776 if (ret == NO_ERROR && !profiles.empty()) {
2777 config->channel_mask = profiles[0]->getChannels().empty() ? config->channel_mask
2778 : *profiles[0]->getChannels().begin();
2779 config->sample_rate = profiles[0]->getSampleRates().empty() ? config->sample_rate
2780 : *profiles[0]->getSampleRates().begin();
2781 config->format = profiles[0]->getFormat();
2782 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002783 goto error;
Eric Laurent599c7582015-12-07 18:05:55 -08002784 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08002785
Eric Laurent8f42ea12018-08-08 09:08:25 -07002786exit:
2787
François Gaffiec005e562018-11-06 15:04:49 +01002788 *selectedDeviceId = mAvailableInputDevices.contains(device) ?
2789 device->getId() : AUDIO_PORT_HANDLE_NONE;
Eric Laurent2ac76942017-06-22 17:17:09 -07002790
Francois Gaffie716e1432019-01-14 16:58:59 +01002791 isSoundTrigger = attributes.source == AUDIO_SOURCE_HOTWORD &&
Carter Hsud0cce2e2019-05-03 17:36:28 +08002792 mSoundTriggerSessions.indexOfKey(session) >= 0;
jiabin4ef93452019-09-10 14:29:54 -07002793 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002794
Mikhail Naganov2996f672019-04-18 12:29:59 -07002795 clientDesc = new RecordClientDescriptor(*portId, riid, uid, session, attributes, *config,
Francois Gaffie716e1432019-01-14 16:58:59 +01002796 requestedDeviceId, attributes.source, flags,
2797 isSoundTrigger);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002798 inputDesc = mInputs.valueFor(*input);
Andy Hung39efb7a2018-09-26 15:39:28 -07002799 inputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002800
2801 ALOGV("getInputForAttr() returns input %d type %d selectedDeviceId %d for port ID %d",
2802 *input, *inputType, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07002803
Eric Laurent599c7582015-12-07 18:05:55 -08002804 return NO_ERROR;
Eric Laurentad2e7b92017-09-14 20:06:42 -07002805
2806error:
Eric Laurentad2e7b92017-09-14 20:06:42 -07002807 return status;
Eric Laurent599c7582015-12-07 18:05:55 -08002808}
2809
2810
François Gaffie11d30102018-11-02 16:09:09 +01002811audio_io_handle_t AudioPolicyManager::getInputForDevice(const sp<DeviceDescriptor> &device,
Eric Laurent599c7582015-12-07 18:05:55 -08002812 audio_session_t session,
François Gaffiec005e562018-11-06 15:04:49 +01002813 const audio_attributes_t &attributes,
jiabinf1c73972022-04-14 16:28:52 -07002814 audio_config_base_t *config,
Eric Laurent599c7582015-12-07 18:05:55 -08002815 audio_input_flags_t flags,
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002816 const sp<AudioPolicyMix> &policyMix)
Eric Laurent599c7582015-12-07 18:05:55 -08002817{
2818 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
François Gaffiec005e562018-11-06 15:04:49 +01002819 audio_source_t halInputSource = attributes.source;
Eric Laurent599c7582015-12-07 18:05:55 -08002820 bool isSoundTrigger = false;
2821
François Gaffiec005e562018-11-06 15:04:49 +01002822 if (attributes.source == AUDIO_SOURCE_HOTWORD) {
Eric Laurent599c7582015-12-07 18:05:55 -08002823 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
2824 if (index >= 0) {
2825 input = mSoundTriggerSessions.valueFor(session);
2826 isSoundTrigger = true;
2827 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_HW_HOTWORD);
2828 ALOGV("SoundTrigger capture on session %d input %d", session, input);
2829 } else {
2830 halInputSource = AUDIO_SOURCE_VOICE_RECOGNITION;
Eric Laurent5dbe4712014-09-19 19:04:57 -07002831 }
François Gaffiec005e562018-11-06 15:04:49 +01002832 } else if (attributes.source == AUDIO_SOURCE_VOICE_COMMUNICATION &&
Eric Laurentfe231122017-11-17 17:48:06 -08002833 audio_is_linear_pcm(config->format)) {
Haynes Mathew George851d3ff2017-06-19 20:01:57 -07002834 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_VOIP_TX);
Eric Laurent5dbe4712014-09-19 19:04:57 -07002835 }
2836
Carter Hsua3abb402021-10-26 11:11:20 +08002837 if (attributes.source == AUDIO_SOURCE_ULTRASOUND) {
2838 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_ULTRASOUND);
2839 }
2840
Eric Laurentfe231122017-11-17 17:48:06 -08002841 // sampling rate and flags may be updated by getInputProfile
2842 uint32_t profileSamplingRate = (config->sample_rate == 0) ?
2843 SAMPLE_RATE_HZ_DEFAULT : config->sample_rate;
jiabin2fd710d2022-05-02 23:20:22 +00002844 audio_format_t profileFormat = config->format;
Eric Laurentfe231122017-11-17 17:48:06 -08002845 audio_channel_mask_t profileChannelMask = config->channel_mask;
Andy Hungf129b032015-04-07 13:45:50 -07002846 audio_input_flags_t profileFlags = flags;
jiabin2fd710d2022-05-02 23:20:22 +00002847 // find a compatible input profile (not necessarily identical in parameters)
2848 sp<IOProfile> profile = getInputProfile(
2849 device, profileSamplingRate, profileFormat, profileChannelMask, profileFlags);
2850 if (profile == nullptr) {
2851 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07002852 }
jiabin2fd710d2022-05-02 23:20:22 +00002853
Glenn Kasten05ddca52016-02-11 08:17:12 -08002854 // Pick input sampling rate if not specified by client
Eric Laurentfe231122017-11-17 17:48:06 -08002855 uint32_t samplingRate = config->sample_rate;
Glenn Kasten05ddca52016-02-11 08:17:12 -08002856 if (samplingRate == 0) {
2857 samplingRate = profileSamplingRate;
2858 }
Eric Laurente552edb2014-03-10 17:42:56 -07002859
Eric Laurent322b4d22015-04-03 15:57:54 -07002860 if (profile->getModuleHandle() == 0) {
2861 ALOGE("getInputForAttr(): HW module %s not opened", profile->getModuleName());
Eric Laurent599c7582015-12-07 18:05:55 -08002862 return input;
Eric Laurentcf2c0212014-07-25 16:20:43 -07002863 }
2864
Eric Laurentec376dc2021-04-08 20:41:22 +02002865 // Reuse an already opened input if a client with the same session ID already exists
2866 // on that input
2867 for (size_t i = 0; i < mInputs.size(); i++) {
2868 sp <AudioInputDescriptor> desc = mInputs.valueAt(i);
2869 if (desc->mProfile != profile) {
2870 continue;
2871 }
2872 RecordClientVector clients = desc->clientsList();
2873 for (const auto &client : clients) {
2874 if (session == client->session()) {
2875 return desc->mIoHandle;
2876 }
2877 }
2878 }
2879
Eric Laurent3974e3b2017-12-07 17:58:43 -08002880 if (!profile->canOpenNewIo()) {
Eric Laurent4eb58f12018-12-07 16:41:02 -08002881 for (size_t i = 0; i < mInputs.size(); ) {
Eric Laurentc529cf62020-04-17 18:19:10 -07002882 sp<AudioInputDescriptor> desc = mInputs.valueAt(i);
Eric Laurent4eb58f12018-12-07 16:41:02 -08002883 if (desc->mProfile != profile) {
Carter Hsu9a645a92019-05-15 12:15:32 +08002884 i++;
Eric Laurent4eb58f12018-12-07 16:41:02 -08002885 continue;
2886 }
2887 // if sound trigger, reuse input if used by other sound trigger on same session
2888 // else
2889 // reuse input if active client app is not in IDLE state
2890 //
2891 RecordClientVector clients = desc->clientsList();
2892 bool doClose = false;
2893 for (const auto& client : clients) {
2894 if (isSoundTrigger != client->isSoundTrigger()) {
2895 continue;
2896 }
2897 if (client->isSoundTrigger()) {
2898 if (session == client->session()) {
2899 return desc->mIoHandle;
2900 }
2901 continue;
2902 }
2903 if (client->active() && client->appState() != APP_STATE_IDLE) {
2904 return desc->mIoHandle;
2905 }
2906 doClose = true;
2907 }
2908 if (doClose) {
2909 closeInput(desc->mIoHandle);
2910 } else {
2911 i++;
2912 }
2913 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002914 }
2915
Eric Laurentfe231122017-11-17 17:48:06 -08002916 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07002917
Eric Laurentfe231122017-11-17 17:48:06 -08002918 audio_config_t lConfig = AUDIO_CONFIG_INITIALIZER;
2919 lConfig.sample_rate = profileSamplingRate;
2920 lConfig.channel_mask = profileChannelMask;
2921 lConfig.format = profileFormat;
Eric Laurente3014102017-05-03 11:15:43 -07002922
François Gaffie11d30102018-11-02 16:09:09 +01002923 status_t status = inputDesc->open(&lConfig, device, halInputSource, profileFlags, &input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07002924
2925 // only accept input with the exact requested set of parameters
Eric Laurent599c7582015-12-07 18:05:55 -08002926 if (status != NO_ERROR || input == AUDIO_IO_HANDLE_NONE ||
Eric Laurentfe231122017-11-17 17:48:06 -08002927 (profileSamplingRate != lConfig.sample_rate) ||
2928 !audio_formats_match(profileFormat, lConfig.format) ||
2929 (profileChannelMask != lConfig.channel_mask)) {
2930 ALOGW("getInputForAttr() failed opening input: sampling rate %d"
Glenn Kasten49f36ba2017-12-06 13:02:02 -08002931 ", format %#x, channel mask %#x",
Eric Laurentfe231122017-11-17 17:48:06 -08002932 profileSamplingRate, profileFormat, profileChannelMask);
Eric Laurent599c7582015-12-07 18:05:55 -08002933 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfe231122017-11-17 17:48:06 -08002934 inputDesc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07002935 }
Eric Laurent599c7582015-12-07 18:05:55 -08002936 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07002937 }
2938
Eric Laurentc722f302014-12-10 11:21:49 -08002939 inputDesc->mPolicyMix = policyMix;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002940
Eric Laurent599c7582015-12-07 18:05:55 -08002941 addInput(input, inputDesc);
Eric Laurentb52c1522014-05-20 11:27:36 -07002942 mpClientInterface->onAudioPortListUpdate();
Paul McLean466dc8e2015-04-17 13:15:36 -06002943
Eric Laurent599c7582015-12-07 18:05:55 -08002944 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07002945}
2946
Eric Laurent4eb58f12018-12-07 16:41:02 -08002947status_t AudioPolicyManager::startInput(audio_port_handle_t portId)
Eric Laurentbb948092017-01-23 18:33:30 -08002948{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002949 ALOGV("%s portId %d", __FUNCTION__, portId);
2950
2951 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2952 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002953 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurentd52a28c2020-08-21 17:10:39 -07002954 return DEAD_OBJECT;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002955 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002956 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07002957 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002958 if (client->active()) {
2959 ALOGW("%s input %d client %d already started", __FUNCTION__, input, client->portId());
2960 return INVALID_OPERATION;
Eric Laurent4dc68062014-07-28 17:26:49 -07002961 }
2962
Eric Laurent8f42ea12018-08-08 09:08:25 -07002963 audio_session_t session = client->session();
2964
Eric Laurent4eb58f12018-12-07 16:41:02 -08002965 ALOGV("%s input:%d, session:%d)", __FUNCTION__, input, session);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002966
Eric Laurent4eb58f12018-12-07 16:41:02 -08002967 Vector<sp<AudioInputDescriptor>> activeInputs = mInputs.getActiveInputs();
Eric Laurent74708e72017-04-07 17:13:42 -07002968
Eric Laurent4eb58f12018-12-07 16:41:02 -08002969 status_t status = inputDesc->start();
2970 if (status != NO_ERROR) {
2971 return status;
Eric Laurent74708e72017-04-07 17:13:42 -07002972 }
Eric Laurente552edb2014-03-10 17:42:56 -07002973
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002974 // increment activity count before calling getNewInputDevice() below as only active sessions
Eric Laurent313d1e72016-01-29 09:56:57 -08002975 // are considered for device selection
Eric Laurent8f42ea12018-08-08 09:08:25 -07002976 inputDesc->setClientActive(client, true);
Eric Laurent313d1e72016-01-29 09:56:57 -08002977
Eric Laurent8f42ea12018-08-08 09:08:25 -07002978 // indicate active capture to sound trigger service if starting capture from a mic on
2979 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01002980 sp<DeviceDescriptor> device = getNewInputDevice(inputDesc);
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002981 if (device != nullptr) {
2982 status = setInputDevice(input, device, true /* force */);
2983 } else {
2984 ALOGW("%s no new input device can be found for descriptor %d",
2985 __FUNCTION__, inputDesc->getId());
2986 status = BAD_VALUE;
2987 }
Eric Laurente552edb2014-03-10 17:42:56 -07002988
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002989 if (status == NO_ERROR && inputDesc->activeCount() == 1) {
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002990 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002991 // if input maps to a dynamic policy with an activity listener, notify of state change
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002992 if ((policyMix != nullptr)
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002993 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
2994 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
Eric Laurent8f42ea12018-08-08 09:08:25 -07002995 MIX_STATE_MIXING);
Eric Laurent733ce942017-12-07 12:18:25 -08002996 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002997
François Gaffie11d30102018-11-02 16:09:09 +01002998 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
2999 if (primaryInputDevices.contains(device) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07003000 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 1) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07003001 mpClientInterface->setSoundTriggerCaptureState(true);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003002 }
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07003003
Eric Laurent8f42ea12018-08-08 09:08:25 -07003004 // automatically enable the remote submix output when input is started if not
3005 // used by a policy mix of type MIX_TYPE_RECORDERS
3006 // For remote submix (a virtual device), we open only one input per capture request.
François Gaffie11d30102018-11-02 16:09:09 +01003007 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003008 String8 address = String8("");
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003009 if (policyMix == nullptr) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003010 address = String8("0");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003011 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
3012 address = policyMix->mDeviceAddress;
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07003013 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07003014 if (address != "") {
3015 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
3016 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08003017 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurentc722f302014-12-10 11:21:49 -08003018 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07003019 }
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003020 } else if (status != NO_ERROR) {
3021 // Restore client activity state.
3022 inputDesc->setClientActive(client, false);
3023 inputDesc->stop();
Eric Laurente552edb2014-03-10 17:42:56 -07003024 }
3025
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003026 ALOGV("%s input %d source = %d status = %d exit",
3027 __FUNCTION__, input, client->source(), status);
Eric Laurente552edb2014-03-10 17:42:56 -07003028
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003029 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07003030}
3031
Eric Laurent8fc147b2018-07-22 19:13:55 -07003032status_t AudioPolicyManager::stopInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07003033{
Eric Laurent8fc147b2018-07-22 19:13:55 -07003034 ALOGV("%s portId %d", __FUNCTION__, portId);
3035
3036 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
3037 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003038 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07003039 return BAD_VALUE;
3040 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07003041 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07003042 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003043 if (!client->active()) {
3044 ALOGW("%s input %d client %d already stopped", __FUNCTION__, input, client->portId());
Eric Laurente552edb2014-03-10 17:42:56 -07003045 return INVALID_OPERATION;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003046 }
Carter Hsue6139d52021-07-08 10:30:20 +08003047 auto old_source = inputDesc->source();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003048 inputDesc->setClientActive(client, false);
Paul McLean466dc8e2015-04-17 13:15:36 -06003049
Eric Laurent8f42ea12018-08-08 09:08:25 -07003050 inputDesc->stop();
3051 if (inputDesc->isActive()) {
Carter Hsue6139d52021-07-08 10:30:20 +08003052 auto current_source = inputDesc->source();
3053 setInputDevice(input, getNewInputDevice(inputDesc),
3054 old_source != current_source /* force */);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003055 } else {
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003056 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003057 // if input maps to a dynamic policy with an activity listener, notify of state change
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003058 if ((policyMix != nullptr)
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003059 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
3060 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
Eric Laurent8f42ea12018-08-08 09:08:25 -07003061 MIX_STATE_IDLE);
Eric Laurent84332aa2016-01-28 22:19:18 +00003062 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07003063
3064 // automatically disable the remote submix output when input is stopped if not
3065 // used by a policy mix of type MIX_TYPE_RECORDERS
François Gaffie11d30102018-11-02 16:09:09 +01003066 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003067 String8 address = String8("");
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003068 if (policyMix == nullptr) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003069 address = String8("0");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003070 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
3071 address = policyMix->mDeviceAddress;
Eric Laurent8f42ea12018-08-08 09:08:25 -07003072 }
3073 if (address != "") {
3074 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
3075 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08003076 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003077 }
3078 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07003079 resetInputDevice(input);
3080
3081 // indicate inactive capture to sound trigger service if stopping capture from a mic on
3082 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01003083 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
3084 if (primaryInputDevices.contains(inputDesc->getDevice()) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07003085 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07003086 mpClientInterface->setSoundTriggerCaptureState(false);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003087 }
3088 inputDesc->clearPreemptedSessions();
Eric Laurente552edb2014-03-10 17:42:56 -07003089 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003090 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07003091}
3092
Eric Laurent8fc147b2018-07-22 19:13:55 -07003093void AudioPolicyManager::releaseInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07003094{
Eric Laurent8fc147b2018-07-22 19:13:55 -07003095 ALOGV("%s portId %d", __FUNCTION__, portId);
3096
3097 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
3098 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003099 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07003100 return;
3101 }
Andy Hung39efb7a2018-09-26 15:39:28 -07003102 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8fc147b2018-07-22 19:13:55 -07003103 audio_io_handle_t input = inputDesc->mIoHandle;
3104
Eric Laurent8f42ea12018-08-08 09:08:25 -07003105 ALOGV("%s %d", __FUNCTION__, input);
Paul McLean466dc8e2015-04-17 13:15:36 -06003106
Andy Hung39efb7a2018-09-26 15:39:28 -07003107 inputDesc->removeClient(portId);
Eric Laurent599c7582015-12-07 18:05:55 -08003108
Andy Hung39efb7a2018-09-26 15:39:28 -07003109 if (inputDesc->getClientCount() > 0) {
3110 ALOGV("%s(%d) %zu clients remaining", __func__, portId, inputDesc->getClientCount());
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003111 return;
3112 }
3113
Eric Laurent05b90f82014-08-27 15:32:29 -07003114 closeInput(input);
Eric Laurentb52c1522014-05-20 11:27:36 -07003115 mpClientInterface->onAudioPortListUpdate();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003116 ALOGV("%s exit", __FUNCTION__);
Eric Laurente552edb2014-03-10 17:42:56 -07003117}
3118
Eric Laurent8f42ea12018-08-08 09:08:25 -07003119void AudioPolicyManager::closeActiveClients(const sp<AudioInputDescriptor>& input)
Eric Laurent8fc147b2018-07-22 19:13:55 -07003120{
Eric Laurent8f42ea12018-08-08 09:08:25 -07003121 RecordClientVector clients = input->clientsList(true);
Eric Laurent8fc147b2018-07-22 19:13:55 -07003122
3123 for (const auto& client : clients) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003124 closeClient(client->portId());
Eric Laurent8fc147b2018-07-22 19:13:55 -07003125 }
3126}
3127
Eric Laurent8f42ea12018-08-08 09:08:25 -07003128void AudioPolicyManager::closeClient(audio_port_handle_t portId)
3129{
3130 stopInput(portId);
3131 releaseInput(portId);
3132}
Eric Laurent8fc147b2018-07-22 19:13:55 -07003133
Eric Laurent0dd51852019-04-19 18:18:58 -07003134void AudioPolicyManager::checkCloseInputs() {
3135 // After connecting or disconnecting an input device, close input if:
3136 // - it has no client (was just opened to check profile) OR
3137 // - none of its supported devices are connected anymore OR
3138 // - one of its clients cannot be routed to one of its supported
3139 // devices anymore. Otherwise update device selection
3140 std::vector<audio_io_handle_t> inputsToClose;
3141 for (size_t i = 0; i < mInputs.size(); i++) {
3142 const sp<AudioInputDescriptor> input = mInputs.valueAt(i);
3143 if (input->clientsList().size() == 0
Eric Laurent85732f42020-03-19 11:31:10 -07003144 || !mAvailableInputDevices.containsAtLeastOne(input->supportedDevices())) {
Eric Laurent0dd51852019-04-19 18:18:58 -07003145 inputsToClose.push_back(mInputs.keyAt(i));
3146 } else {
3147 bool close = false;
3148 for (const auto& client : input->clientsList()) {
3149 sp<DeviceDescriptor> device =
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02003150 mEngine->getInputDeviceForAttributes(client->attributes(), client->uid(),
3151 client->session());
Eric Laurent0dd51852019-04-19 18:18:58 -07003152 if (!input->supportedDevices().contains(device)) {
3153 close = true;
3154 break;
3155 }
3156 }
3157 if (close) {
3158 inputsToClose.push_back(mInputs.keyAt(i));
3159 } else {
3160 setInputDevice(input->mIoHandle, getNewInputDevice(input));
3161 }
3162 }
3163 }
3164
3165 for (const audio_io_handle_t handle : inputsToClose) {
3166 ALOGV("%s closing input %d", __func__, handle);
3167 closeInput(handle);
Eric Laurent05b90f82014-08-27 15:32:29 -07003168 }
Eric Laurentd4692962014-05-05 18:13:44 -07003169}
3170
François Gaffie251c7f02018-11-07 10:41:08 +01003171void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream, int indexMin, int indexMax)
Eric Laurente552edb2014-03-10 17:42:56 -07003172{
3173 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08003174 if (indexMin < 0 || indexMax < 0) {
3175 ALOGE("%s for stream %d: invalid min %d or max %d", __func__, stream , indexMin, indexMax);
3176 return;
3177 }
Eric Laurentf5aa58d2019-02-22 18:20:11 -08003178 getVolumeCurves(stream).initVolume(indexMin, indexMax);
Eric Laurent28d09f02016-03-08 10:43:05 -08003179
3180 // initialize other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08003181 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
3182 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08003183 continue;
3184 }
Eric Laurentf5aa58d2019-02-22 18:20:11 -08003185 getVolumeCurves((audio_stream_type_t)curStream).initVolume(indexMin, indexMax);
Eric Laurent223fd5c2014-11-11 13:43:36 -08003186 }
Eric Laurente552edb2014-03-10 17:42:56 -07003187}
3188
Eric Laurente0720872014-03-11 09:30:41 -07003189status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
François Gaffie53615e22015-03-19 09:24:12 +01003190 int index,
3191 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07003192{
François Gaffieaaac0fd2018-11-22 17:56:39 +01003193 auto attributes = mEngine->getAttributesForStreamType(stream);
Eric Laurent242a9f82020-03-23 15:57:04 -07003194 if (attributes == AUDIO_ATTRIBUTES_INITIALIZER) {
3195 ALOGW("%s: no group for stream %s, bailing out", __func__, toString(stream).c_str());
3196 return NO_ERROR;
3197 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01003198 ALOGV("%s: stream %s attributes=%s", __func__,
3199 toString(stream).c_str(), toString(attributes).c_str());
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003200 return setVolumeIndexForAttributes(attributes, index, device);
Eric Laurente552edb2014-03-10 17:42:56 -07003201}
3202
Eric Laurente0720872014-03-11 09:30:41 -07003203status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
François Gaffieaaac0fd2018-11-22 17:56:39 +01003204 int *index,
3205 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07003206{
François Gaffiec005e562018-11-06 15:04:49 +01003207 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
3208 // stream by the engine.
jiabin9a3361e2019-10-01 09:38:30 -07003209 DeviceTypeSet deviceTypes = {device};
Eric Laurent5a2b6292016-04-14 18:05:57 -07003210 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
jiabin9a3361e2019-10-01 09:38:30 -07003211 deviceTypes = mEngine->getOutputDevicesForStream(
3212 stream, true /*fromCache*/).types();
Eric Laurente552edb2014-03-10 17:42:56 -07003213 }
jiabin9a3361e2019-10-01 09:38:30 -07003214 return getVolumeIndex(getVolumeCurves(stream), *index, deviceTypes);
Eric Laurente552edb2014-03-10 17:42:56 -07003215}
3216
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003217status_t AudioPolicyManager::setVolumeIndexForAttributes(const audio_attributes_t &attributes,
François Gaffiecfe17322018-11-07 13:41:29 +01003218 int index,
3219 audio_devices_t device)
3220{
3221 // Get Volume group matching the Audio Attributes
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003222 auto group = mEngine->getVolumeGroupForAttributes(attributes);
3223 if (group == VOLUME_GROUP_NONE) {
3224 ALOGD("%s: no group matching with %s", __FUNCTION__, toString(attributes).c_str());
François Gaffiecfe17322018-11-07 13:41:29 +01003225 return BAD_VALUE;
3226 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003227 ALOGV("%s: group %d matching with %s", __FUNCTION__, group, toString(attributes).c_str());
François Gaffiecfe17322018-11-07 13:41:29 +01003228 status_t status = NO_ERROR;
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003229 IVolumeCurves &curves = getVolumeCurves(attributes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01003230 VolumeSource vs = toVolumeSource(group);
Eric Laurentf9cccec2022-11-16 19:12:00 +01003231 // AUDIO_STREAM_BLUETOOTH_SCO is only used for volume control so we remap
3232 // to AUDIO_STREAM_VOICE_CALL to match with relevant playback activity
3233 VolumeSource activityVs = (vs == toVolumeSource(AUDIO_STREAM_BLUETOOTH_SCO, false)) ?
3234 toVolumeSource(AUDIO_STREAM_VOICE_CALL, false) : vs;
François Gaffieaaac0fd2018-11-22 17:56:39 +01003235 product_strategy_t strategy = mEngine->getProductStrategyForAttributes(attributes);
3236
3237 status = setVolumeCurveIndex(index, device, curves);
3238 if (status != NO_ERROR) {
3239 ALOGE("%s failed to set curve index for group %d device 0x%X", __func__, group, device);
3240 return status;
3241 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003242
jiabin9a3361e2019-10-01 09:38:30 -07003243 DeviceTypeSet curSrcDevices;
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003244 auto curCurvAttrs = curves.getAttributes();
3245 if (!curCurvAttrs.empty() && curCurvAttrs.front() != defaultAttr) {
3246 auto attr = curCurvAttrs.front();
jiabin9a3361e2019-10-01 09:38:30 -07003247 curSrcDevices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false).types();
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003248 } else if (!curves.getStreamTypes().empty()) {
3249 auto stream = curves.getStreamTypes().front();
jiabin9a3361e2019-10-01 09:38:30 -07003250 curSrcDevices = mEngine->getOutputDevicesForStream(stream, false).types();
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003251 } else {
3252 ALOGE("%s: Invalid src %d: no valid attributes nor stream",__func__, vs);
3253 return BAD_VALUE;
3254 }
jiabin9a3361e2019-10-01 09:38:30 -07003255 audio_devices_t curSrcDevice = Volume::getDeviceForVolume(curSrcDevices);
3256 resetDeviceTypes(curSrcDevices, curSrcDevice);
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003257
François Gaffiecfe17322018-11-07 13:41:29 +01003258 // update volume on all outputs and streams matching the following:
3259 // - The requested stream (or a stream matching for volume control) is active on the output
3260 // - The device (or devices) selected by the engine for this stream includes
3261 // the requested device
3262 // - For non default requested device, currently selected device on the output is either the
3263 // requested device or one of the devices selected by the engine for this stream
3264 // - For default requested device (AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME), apply volume only if
3265 // no specific device volume value exists for currently selected device.
François Gaffieaaac0fd2018-11-22 17:56:39 +01003266 for (size_t i = 0; i < mOutputs.size(); i++) {
3267 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
jiabin9a3361e2019-10-01 09:38:30 -07003268 DeviceTypeSet curDevices = desc->devices().types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01003269
jiabin9a3361e2019-10-01 09:38:30 -07003270 if (curDevices.erase(AUDIO_DEVICE_OUT_SPEAKER_SAFE)) {
3271 curDevices.insert(AUDIO_DEVICE_OUT_SPEAKER);
Robert Lee5e66e792019-04-03 18:37:15 +08003272 }
Eric Laurentf9cccec2022-11-16 19:12:00 +01003273
3274 if (!(desc->isActive(activityVs) || isInCallOrScreening())) {
François Gaffieed91f582020-01-31 10:35:37 +01003275 continue;
3276 }
3277 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME &&
3278 curDevices.find(device) == curDevices.end()) {
3279 continue;
3280 }
3281 bool applyVolume = false;
3282 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
3283 curSrcDevices.insert(device);
3284 applyVolume = (curSrcDevices.find(
3285 Volume::getDeviceForVolume(curDevices)) != curSrcDevices.end());
3286 } else {
3287 applyVolume = !curves.hasVolumeIndexForDevice(curSrcDevice);
3288 }
3289 if (!applyVolume) {
3290 continue; // next output
3291 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01003292 // Inter / intra volume group priority management: Loop on strategies arranged by priority
3293 // If a higher priority strategy is active, and the output is routed to a device with a
3294 // HW Gain management, do not change the volume
François Gaffieaaac0fd2018-11-22 17:56:39 +01003295 if (desc->useHwGain()) {
François Gaffieed91f582020-01-31 10:35:37 +01003296 applyVolume = false;
Francois Gaffie593634d2021-06-22 13:31:31 +02003297 // If the volume source is active with higher priority source, ensure at least Sw Muted
3298 desc->setSwMute((index == 0), vs, curves.getStreamTypes(), curDevices, 0 /*delayMs*/);
François Gaffieaaac0fd2018-11-22 17:56:39 +01003299 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
3300 auto activeClients = desc->clientsList(true /*activeOnly*/, productStrategy,
3301 false /*preferredDevice*/);
3302 if (activeClients.empty()) {
3303 continue;
3304 }
3305 bool isPreempted = false;
3306 bool isHigherPriority = productStrategy < strategy;
3307 for (const auto &client : activeClients) {
Eric Laurentf9cccec2022-11-16 19:12:00 +01003308 if (isHigherPriority && (client->volumeSource() != activityVs)) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01003309 ALOGV("%s: Strategy=%d (\nrequester:\n"
3310 " group %d, volumeGroup=%d attributes=%s)\n"
3311 " higher priority source active:\n"
3312 " volumeGroup=%d attributes=%s) \n"
3313 " on output %zu, bailing out", __func__, productStrategy,
3314 group, group, toString(attributes).c_str(),
3315 client->volumeSource(), toString(client->attributes()).c_str(), i);
3316 applyVolume = false;
3317 isPreempted = true;
3318 break;
3319 }
3320 // However, continue for loop to ensure no higher prio clients running on output
Eric Laurentf9cccec2022-11-16 19:12:00 +01003321 if (client->volumeSource() == activityVs) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01003322 applyVolume = true;
3323 }
3324 }
3325 if (isPreempted || applyVolume) {
3326 break;
3327 }
3328 }
3329 if (!applyVolume) {
3330 continue; // next output
3331 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01003332 }
François Gaffieed91f582020-01-31 10:35:37 +01003333 //FIXME: workaround for truncated touch sounds
3334 // delayed volume change for system stream to be removed when the problem is
3335 // handled by system UI
3336 status_t volStatus = checkAndSetVolume(
3337 curves, vs, index, desc, curDevices,
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003338 ((vs == toVolumeSource(AUDIO_STREAM_SYSTEM, false))?
François Gaffieed91f582020-01-31 10:35:37 +01003339 TOUCH_SOUND_FIXED_DELAY_MS : 0));
3340 if (volStatus != NO_ERROR) {
3341 status = volStatus;
François Gaffieaaac0fd2018-11-22 17:56:39 +01003342 }
3343 }
François Gaffiecfe17322018-11-07 13:41:29 +01003344 mpClientInterface->onAudioVolumeGroupChanged(group, 0 /*flags*/);
3345 return status;
3346}
3347
François Gaffieaaac0fd2018-11-22 17:56:39 +01003348status_t AudioPolicyManager::setVolumeCurveIndex(int index,
François Gaffiecfe17322018-11-07 13:41:29 +01003349 audio_devices_t device,
3350 IVolumeCurves &volumeCurves)
3351{
3352 // VOICE_CALL stream has minVolumeIndex > 0 but can be muted directly by an
3353 // app that has MODIFY_PHONE_STATE permission.
François Gaffieaaac0fd2018-11-22 17:56:39 +01003354 bool hasVoice = hasVoiceStream(volumeCurves.getStreamTypes());
3355 if (((index < volumeCurves.getVolumeIndexMin()) && !(hasVoice && index == 0)) ||
François Gaffiecfe17322018-11-07 13:41:29 +01003356 (index > volumeCurves.getVolumeIndexMax())) {
3357 ALOGD("%s: wrong index %d min=%d max=%d", __FUNCTION__, index,
3358 volumeCurves.getVolumeIndexMin(), volumeCurves.getVolumeIndexMax());
3359 return BAD_VALUE;
3360 }
3361 if (!audio_is_output_device(device)) {
3362 return BAD_VALUE;
3363 }
3364
3365 // Force max volume if stream cannot be muted
3366 if (!volumeCurves.canBeMuted()) index = volumeCurves.getVolumeIndexMax();
3367
François Gaffieaaac0fd2018-11-22 17:56:39 +01003368 ALOGV("%s device %08x, index %d", __FUNCTION__ , device, index);
François Gaffiecfe17322018-11-07 13:41:29 +01003369 volumeCurves.addCurrentVolumeIndex(device, index);
3370 return NO_ERROR;
3371}
3372
3373status_t AudioPolicyManager::getVolumeIndexForAttributes(const audio_attributes_t &attr,
3374 int &index,
3375 audio_devices_t device)
3376{
3377 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
3378 // stream by the engine.
jiabin9a3361e2019-10-01 09:38:30 -07003379 DeviceTypeSet deviceTypes = {device};
François Gaffiecfe17322018-11-07 13:41:29 +01003380 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
Mikhail Naganovbb990f22022-06-15 00:46:43 +00003381 deviceTypes = mEngine->getOutputDevicesForAttributes(
jiabin9a3361e2019-10-01 09:38:30 -07003382 attr, nullptr, true /*fromCache*/).types();
François Gaffiecfe17322018-11-07 13:41:29 +01003383 }
jiabin9a3361e2019-10-01 09:38:30 -07003384 return getVolumeIndex(getVolumeCurves(attr), index, deviceTypes);
François Gaffiecfe17322018-11-07 13:41:29 +01003385}
3386
3387status_t AudioPolicyManager::getVolumeIndex(const IVolumeCurves &curves,
3388 int &index,
jiabin9a3361e2019-10-01 09:38:30 -07003389 const DeviceTypeSet& deviceTypes) const
François Gaffiecfe17322018-11-07 13:41:29 +01003390{
Mikhail Naganovbb990f22022-06-15 00:46:43 +00003391 if (!isSingleDeviceType(deviceTypes, audio_is_output_device)) {
François Gaffiecfe17322018-11-07 13:41:29 +01003392 return BAD_VALUE;
3393 }
jiabin9a3361e2019-10-01 09:38:30 -07003394 index = curves.getVolumeIndex(deviceTypes);
3395 ALOGV("%s: device %s index %d", __FUNCTION__, dumpDeviceTypes(deviceTypes).c_str(), index);
François Gaffiecfe17322018-11-07 13:41:29 +01003396 return NO_ERROR;
3397}
3398
3399status_t AudioPolicyManager::getMinVolumeIndexForAttributes(const audio_attributes_t &attr,
3400 int &index)
3401{
3402 index = getVolumeCurves(attr).getVolumeIndexMin();
3403 return NO_ERROR;
3404}
3405
3406status_t AudioPolicyManager::getMaxVolumeIndexForAttributes(const audio_attributes_t &attr,
3407 int &index)
3408{
3409 index = getVolumeCurves(attr).getVolumeIndexMax();
3410 return NO_ERROR;
3411}
3412
Eric Laurent36829f92017-04-07 19:04:42 -07003413audio_io_handle_t AudioPolicyManager::selectOutputForMusicEffects()
Eric Laurente552edb2014-03-10 17:42:56 -07003414{
3415 // select one output among several suitable for global effects.
3416 // The priority is as follows:
3417 // 1: An offloaded output. If the effect ends up not being offloadable,
3418 // AudioFlinger will invalidate the track and the offloaded output
3419 // will be closed causing the effect to be moved to a PCM output.
3420 // 2: A deep buffer output
Eric Laurent36829f92017-04-07 19:04:42 -07003421 // 3: The primary output
3422 // 4: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07003423
François Gaffiec005e562018-11-06 15:04:49 +01003424 DeviceVector devices = mEngine->getOutputDevicesForAttributes(
3425 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
François Gaffie11d30102018-11-02 16:09:09 +01003426 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07003427
Eric Laurent36829f92017-04-07 19:04:42 -07003428 if (outputs.size() == 0) {
3429 return AUDIO_IO_HANDLE_NONE;
3430 }
Eric Laurente552edb2014-03-10 17:42:56 -07003431
Eric Laurent36829f92017-04-07 19:04:42 -07003432 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
3433 bool activeOnly = true;
3434
3435 while (output == AUDIO_IO_HANDLE_NONE) {
3436 audio_io_handle_t outputOffloaded = AUDIO_IO_HANDLE_NONE;
3437 audio_io_handle_t outputDeepBuffer = AUDIO_IO_HANDLE_NONE;
3438 audio_io_handle_t outputPrimary = AUDIO_IO_HANDLE_NONE;
3439
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003440 for (audio_io_handle_t output : outputs) {
3441 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
Eric Laurent83d17c22019-04-02 17:10:01 -07003442 if (activeOnly && !desc->isActive(toVolumeSource(AUDIO_STREAM_MUSIC))) {
Eric Laurent36829f92017-04-07 19:04:42 -07003443 continue;
3444 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003445 ALOGV("selectOutputForMusicEffects activeOnly %d output %d flags 0x%08x",
3446 activeOnly, output, desc->mFlags);
Eric Laurent36829f92017-04-07 19:04:42 -07003447 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003448 outputOffloaded = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003449 }
3450 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003451 outputDeepBuffer = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003452 }
3453 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003454 outputPrimary = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003455 }
3456 }
3457 if (outputOffloaded != AUDIO_IO_HANDLE_NONE) {
3458 output = outputOffloaded;
3459 } else if (outputDeepBuffer != AUDIO_IO_HANDLE_NONE) {
3460 output = outputDeepBuffer;
3461 } else if (outputPrimary != AUDIO_IO_HANDLE_NONE) {
3462 output = outputPrimary;
3463 } else {
3464 output = outputs[0];
3465 }
3466 activeOnly = false;
3467 }
3468
3469 if (output != mMusicEffectOutput) {
Eric Laurent6c796322019-04-09 14:13:17 -07003470 mEffects.moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output);
Eric Laurent36829f92017-04-07 19:04:42 -07003471 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output);
3472 mMusicEffectOutput = output;
3473 }
3474
3475 ALOGV("selectOutputForMusicEffects selected output %d", output);
Eric Laurente552edb2014-03-10 17:42:56 -07003476 return output;
3477}
3478
Eric Laurent36829f92017-04-07 19:04:42 -07003479audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc __unused)
3480{
3481 return selectOutputForMusicEffects();
3482}
3483
Eric Laurente0720872014-03-11 09:30:41 -07003484status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07003485 audio_io_handle_t io,
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08003486 product_strategy_t strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07003487 int session,
3488 int id)
3489{
Eric Laurentb82e6b72019-11-22 17:25:04 -08003490 if (session != AUDIO_SESSION_DEVICE) {
3491 ssize_t index = mOutputs.indexOfKey(io);
Eric Laurente552edb2014-03-10 17:42:56 -07003492 if (index < 0) {
Eric Laurentb82e6b72019-11-22 17:25:04 -08003493 index = mInputs.indexOfKey(io);
3494 if (index < 0) {
3495 ALOGW("registerEffect() unknown io %d", io);
3496 return INVALID_OPERATION;
3497 }
Eric Laurente552edb2014-03-10 17:42:56 -07003498 }
3499 }
Eric Laurentbf8f69f2022-03-25 17:48:38 +01003500 bool isMusicEffect = (session != AUDIO_SESSION_OUTPUT_STAGE)
3501 && ((strategy == streamToStrategy(AUDIO_STREAM_MUSIC)
3502 || strategy == PRODUCT_STRATEGY_NONE));
3503 return mEffects.registerEffect(desc, io, session, id, isMusicEffect);
Eric Laurente552edb2014-03-10 17:42:56 -07003504}
3505
Eric Laurentc241b0d2018-11-28 09:08:49 -08003506status_t AudioPolicyManager::unregisterEffect(int id)
3507{
3508 if (mEffects.getEffect(id) == nullptr) {
3509 return INVALID_OPERATION;
3510 }
Eric Laurentc241b0d2018-11-28 09:08:49 -08003511 if (mEffects.isEffectEnabled(id)) {
3512 ALOGW("%s effect %d enabled", __FUNCTION__, id);
3513 setEffectEnabled(id, false);
3514 }
3515 return mEffects.unregisterEffect(id);
3516}
3517
3518status_t AudioPolicyManager::setEffectEnabled(int id, bool enabled)
3519{
3520 sp<EffectDescriptor> effect = mEffects.getEffect(id);
3521 if (effect == nullptr) {
3522 return INVALID_OPERATION;
3523 }
3524
3525 status_t status = mEffects.setEffectEnabled(id, enabled);
3526 if (status == NO_ERROR) {
3527 mInputs.trackEffectEnabled(effect, enabled);
3528 }
3529 return status;
3530}
3531
Eric Laurent6c796322019-04-09 14:13:17 -07003532
3533status_t AudioPolicyManager::moveEffectsToIo(const std::vector<int>& ids, audio_io_handle_t io)
3534{
3535 mEffects.moveEffects(ids, io);
3536 return NO_ERROR;
3537}
3538
Eric Laurentc75307b2015-03-17 15:29:32 -07003539bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
3540{
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003541 auto vs = toVolumeSource(stream, false);
3542 return vs != VOLUME_SOURCE_NONE ? mOutputs.isActive(vs, inPastMs) : false;
Eric Laurentc75307b2015-03-17 15:29:32 -07003543}
3544
3545bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream, uint32_t inPastMs) const
3546{
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003547 auto vs = toVolumeSource(stream, false);
3548 return vs != VOLUME_SOURCE_NONE ? mOutputs.isActiveRemotely(vs, inPastMs) : false;
Eric Laurentc75307b2015-03-17 15:29:32 -07003549}
3550
Eric Laurente0720872014-03-11 09:30:41 -07003551bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07003552{
3553 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003554 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08003555 if (inputDescriptor->isSourceActive(source)) {
Eric Laurente552edb2014-03-10 17:42:56 -07003556 return true;
3557 }
3558 }
3559 return false;
3560}
3561
Eric Laurent275e8e92014-11-30 15:14:47 -08003562// Register a list of custom mixes with their attributes and format.
3563// When a mix is registered, corresponding input and output profiles are
3564// added to the remote submix hw module. The profile contains only the
3565// parameters (sampling rate, format...) specified by the mix.
3566// The corresponding input remote submix device is also connected.
3567//
3568// When a remote submix device is connected, the address is checked to select the
3569// appropriate profile and the corresponding input or output stream is opened.
3570//
3571// When capture starts, getInputForAttr() will:
3572// - 1 look for a mix matching the address passed in attribtutes tags if any
3573// - 2 if none found, getDeviceForInputSource() will:
3574// - 2.1 look for a mix matching the attributes source
3575// - 2.2 if none found, default to device selection by policy rules
3576// At this time, the corresponding output remote submix device is also connected
3577// and active playback use cases can be transferred to this mix if needed when reconnecting
3578// after AudioTracks are invalidated
3579//
3580// When playback starts, getOutputForAttr() will:
3581// - 1 look for a mix matching the address passed in attribtutes tags if any
3582// - 2 if none found, look for a mix matching the attributes usage
3583// - 3 if none found, default to device and output selection by policy rules.
3584
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003585status_t AudioPolicyManager::registerPolicyMixes(const Vector<AudioMix>& mixes)
Eric Laurent275e8e92014-11-30 15:14:47 -08003586{
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003587 ALOGV("registerPolicyMixes() %zu mix(es)", mixes.size());
3588 status_t res = NO_ERROR;
Eric Laurentc209fe42020-06-05 18:11:23 -07003589 bool checkOutputs = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003590 sp<HwModule> rSubmixModule;
3591 // examine each mix's route type
3592 for (size_t i = 0; i < mixes.size(); i++) {
Eric Laurent97ac8712018-07-27 18:59:02 -07003593 AudioMix mix = mixes[i];
Kevin Rocard153f92d2018-12-18 18:33:28 -08003594 // Only capture of playback is allowed in LOOP_BACK & RENDER mode
3595 if (is_mix_loopback_render(mix.mRouteFlags) && mix.mMixType != MIX_TYPE_PLAYERS) {
3596 ALOGE("Unsupported Policy Mix %zu of %zu: "
3597 "Only capture of playback is allowed in LOOP_BACK & RENDER mode",
3598 i, mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003599 res = INVALID_OPERATION;
Eric Laurent275e8e92014-11-30 15:14:47 -08003600 break;
3601 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08003602 // LOOP_BACK and LOOP_BACK | RENDER have the same remote submix backend and are handled
3603 // in the same way.
Eric Laurent97ac8712018-07-27 18:59:02 -07003604 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003605 ALOGV("registerPolicyMixes() mix %zu of %zu is LOOP_BACK %d", i, mixes.size(),
3606 mix.mRouteFlags);
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003607 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003608 rSubmixModule = mHwModules.getModuleFromName(
3609 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
3610 if (rSubmixModule == 0) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003611 ALOGE("Unable to find audio module for submix, aborting mix %zu registration",
Mikhail Naganovd4120142017-12-06 15:49:22 -08003612 i);
3613 res = INVALID_OPERATION;
3614 break;
3615 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003616 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003617
Eric Laurent97ac8712018-07-27 18:59:02 -07003618 String8 address = mix.mDeviceAddress;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003619 audio_devices_t deviceTypeToMakeAvailable;
Eric Laurent97ac8712018-07-27 18:59:02 -07003620 if (mix.mMixType == MIX_TYPE_PLAYERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07003621 mix.mDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003622 deviceTypeToMakeAvailable = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
3623 } else {
3624 mix.mDeviceType = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
3625 deviceTypeToMakeAvailable = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Eric Laurent97ac8712018-07-27 18:59:02 -07003626 }
François Gaffie036e1e92015-03-19 10:16:24 +01003627
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003628 if (mPolicyMixes.registerMix(mix, 0 /*output desc*/) != NO_ERROR) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003629 ALOGE("Error registering mix %zu for address %s", i, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003630 res = INVALID_OPERATION;
3631 break;
3632 }
Eric Laurent97ac8712018-07-27 18:59:02 -07003633 audio_config_t outputConfig = mix.mFormat;
3634 audio_config_t inputConfig = mix.mFormat;
Eric Laurentc529cf62020-04-17 18:19:10 -07003635 // NOTE: audio flinger mixer does not support mono output: configure remote submix HAL
3636 // in stereo and let audio flinger do the channel conversion if needed.
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003637 outputConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
3638 inputConfig.channel_mask = AUDIO_CHANNEL_IN_STEREO;
jiabin5740f082019-08-19 15:08:30 -07003639 rSubmixModule->addOutputProfile(address.c_str(), &outputConfig,
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003640 AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address);
jiabin5740f082019-08-19 15:08:30 -07003641 rSubmixModule->addInputProfile(address.c_str(), &inputConfig,
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003642 AUDIO_DEVICE_IN_REMOTE_SUBMIX, address);
François Gaffie036e1e92015-03-19 10:16:24 +01003643
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003644 if ((res = setDeviceConnectionStateInt(deviceTypeToMakeAvailable,
jiabinc1de2df2019-05-07 14:26:40 -07003645 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
3646 address.string(), "remote-submix", AUDIO_FORMAT_DEFAULT)) != NO_ERROR) {
3647 ALOGE("Failed to set remote submix device available, type %u, address %s",
3648 mix.mDeviceType, address.string());
3649 break;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003650 }
Eric Laurent97ac8712018-07-27 18:59:02 -07003651 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
3652 String8 address = mix.mDeviceAddress;
Eric Laurent2c80be02019-01-23 18:06:37 -08003653 audio_devices_t type = mix.mDeviceType;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003654 ALOGV(" registerPolicyMixes() mix %zu of %zu is RENDER, dev=0x%X addr=%s",
Eric Laurent2c80be02019-01-23 18:06:37 -08003655 i, mixes.size(), type, address.string());
3656
3657 sp<DeviceDescriptor> device = mHwModules.getDeviceDescriptor(
3658 mix.mDeviceType, mix.mDeviceAddress,
3659 String8(), AUDIO_FORMAT_DEFAULT);
3660 if (device == nullptr) {
3661 res = INVALID_OPERATION;
3662 break;
3663 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003664
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003665 bool foundOutput = false;
Eric Laurentc529cf62020-04-17 18:19:10 -07003666 // First try to find an already opened output supporting the device
3667 for (size_t j = 0 ; j < mOutputs.size() && !foundOutput && res == NO_ERROR; j++) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003668 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurent2c80be02019-01-23 18:06:37 -08003669
Eric Laurentc529cf62020-04-17 18:19:10 -07003670 if (!desc->isDuplicated() && desc->supportedDevices().contains(device)) {
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003671 if (mPolicyMixes.registerMix(mix, desc) != NO_ERROR) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003672 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
3673 address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003674 res = INVALID_OPERATION;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003675 } else {
3676 foundOutput = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003677 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003678 }
3679 }
Eric Laurentc529cf62020-04-17 18:19:10 -07003680 // If no output found, try to find a direct output profile supporting the device
3681 for (size_t i = 0; i < mHwModules.size() && !foundOutput && res == NO_ERROR; i++) {
3682 sp<HwModule> module = mHwModules[i];
3683 for (size_t j = 0;
3684 j < module->getOutputProfiles().size() && !foundOutput && res == NO_ERROR;
3685 j++) {
3686 sp<IOProfile> profile = module->getOutputProfiles()[j];
3687 if (profile->isDirectOutput() && profile->supportsDevice(device)) {
3688 if (mPolicyMixes.registerMix(mix, nullptr) != NO_ERROR) {
3689 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
3690 address.string());
3691 res = INVALID_OPERATION;
3692 } else {
3693 foundOutput = true;
3694 }
3695 }
3696 }
3697 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003698 if (res != NO_ERROR) {
3699 ALOGE(" Error registering mix %zu for device 0x%X addr %s",
Eric Laurent2c80be02019-01-23 18:06:37 -08003700 i, type, address.string());
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003701 res = INVALID_OPERATION;
3702 break;
3703 } else if (!foundOutput) {
3704 ALOGE(" Output not found for mix %zu for device 0x%X addr %s",
Eric Laurent2c80be02019-01-23 18:06:37 -08003705 i, type, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003706 res = INVALID_OPERATION;
3707 break;
Eric Laurentc209fe42020-06-05 18:11:23 -07003708 } else {
3709 checkOutputs = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003710 }
Eric Laurentc722f302014-12-10 11:21:49 -08003711 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003712 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003713 if (res != NO_ERROR) {
3714 unregisterPolicyMixes(mixes);
Eric Laurentc209fe42020-06-05 18:11:23 -07003715 } else if (checkOutputs) {
3716 checkForDeviceAndOutputChanges();
3717 updateCallAndOutputRouting();
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003718 }
3719 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08003720}
3721
3722status_t AudioPolicyManager::unregisterPolicyMixes(Vector<AudioMix> mixes)
3723{
Eric Laurent7b279bb2015-12-14 10:18:23 -08003724 ALOGV("unregisterPolicyMixes() num mixes %zu", mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003725 status_t res = NO_ERROR;
Eric Laurentc209fe42020-06-05 18:11:23 -07003726 bool checkOutputs = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003727 sp<HwModule> rSubmixModule;
3728 // examine each mix's route type
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003729 for (const auto& mix : mixes) {
3730 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie036e1e92015-03-19 10:16:24 +01003731
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003732 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003733 rSubmixModule = mHwModules.getModuleFromName(
3734 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
3735 if (rSubmixModule == 0) {
3736 res = INVALID_OPERATION;
3737 continue;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003738 }
3739 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003740
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003741 String8 address = mix.mDeviceAddress;
Eric Laurent275e8e92014-11-30 15:14:47 -08003742
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003743 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003744 res = INVALID_OPERATION;
3745 continue;
3746 }
3747
Kevin Rocard04ed0462019-05-02 17:53:24 -07003748 for (auto device : {AUDIO_DEVICE_IN_REMOTE_SUBMIX, AUDIO_DEVICE_OUT_REMOTE_SUBMIX}) {
3749 if (getDeviceConnectionState(device, address.string()) ==
3750 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
3751 res = setDeviceConnectionStateInt(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
3752 address.string(), "remote-submix",
3753 AUDIO_FORMAT_DEFAULT);
3754 if (res != OK) {
3755 ALOGE("Error making RemoteSubmix device unavailable for mix "
3756 "with type %d, address %s", device, address.string());
3757 }
3758 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003759 }
jiabin5740f082019-08-19 15:08:30 -07003760 rSubmixModule->removeOutputProfile(address.c_str());
3761 rSubmixModule->removeInputProfile(address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003762
Kevin Rocard153f92d2018-12-18 18:33:28 -08003763 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003764 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003765 res = INVALID_OPERATION;
3766 continue;
Eric Laurentc209fe42020-06-05 18:11:23 -07003767 } else {
3768 checkOutputs = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003769 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003770 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003771 }
Eric Laurentc209fe42020-06-05 18:11:23 -07003772 if (res == NO_ERROR && checkOutputs) {
3773 checkForDeviceAndOutputChanges();
3774 updateCallAndOutputRouting();
3775 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003776 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08003777}
3778
Mikhail Naganov100f0122018-11-29 11:22:16 -08003779void AudioPolicyManager::dumpManualSurroundFormats(String8 *dst) const
3780{
3781 size_t i = 0;
3782 constexpr size_t audioFormatPrefixLen = sizeof("AUDIO_FORMAT_");
3783 for (const auto& fmt : mManualSurroundFormats) {
3784 if (i++ != 0) dst->append(", ");
3785 std::string sfmt;
3786 FormatConverter::toString(fmt, sfmt);
3787 dst->append(sfmt.size() >= audioFormatPrefixLen ?
3788 sfmt.c_str() + audioFormatPrefixLen - 1 : sfmt.c_str());
3789 }
3790}
3791
Eric Laurentc529cf62020-04-17 18:19:10 -07003792// Returns true if all devices types match the predicate and are supported by one HW module
3793bool AudioPolicyManager::areAllDevicesSupported(
jiabin6a02d532020-08-07 11:56:38 -07003794 const AudioDeviceTypeAddrVector& devices,
Eric Laurentc529cf62020-04-17 18:19:10 -07003795 std::function<bool(audio_devices_t)> predicate,
Eric Laurent78fedbf2023-03-09 14:40:44 +01003796 const char *context,
3797 bool matchAddress) {
Eric Laurentc529cf62020-04-17 18:19:10 -07003798 for (size_t i = 0; i < devices.size(); i++) {
3799 sp<DeviceDescriptor> devDesc = mHwModules.getDeviceDescriptor(
jiabin0a488932020-08-07 17:32:40 -07003800 devices[i].mType, devices[i].getAddress(), String8(),
Eric Laurent78fedbf2023-03-09 14:40:44 +01003801 AUDIO_FORMAT_DEFAULT, false /*allowToCreate*/, matchAddress);
Eric Laurentc529cf62020-04-17 18:19:10 -07003802 if (devDesc == nullptr || (predicate != nullptr && !predicate(devices[i].mType))) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003803 ALOGE("%s: device type %#x address %s not supported or not match predicate",
jiabin0a488932020-08-07 17:32:40 -07003804 context, devices[i].mType, devices[i].getAddress());
Eric Laurentc529cf62020-04-17 18:19:10 -07003805 return false;
3806 }
3807 }
3808 return true;
3809}
3810
Oscar Azucena6acf34b2023-04-27 16:32:09 -07003811void AudioPolicyManager::changeOutputDevicesMuteState(
3812 const AudioDeviceTypeAddrVector& devices) {
3813 ALOGVV("%s() num devices %zu", __func__, devices.size());
3814
3815 std::vector<sp<SwAudioOutputDescriptor>> outputs =
3816 getSoftwareOutputsForDevices(devices);
3817
3818 for (size_t i = 0; i < outputs.size(); i++) {
3819 sp<SwAudioOutputDescriptor> outputDesc = outputs[i];
3820 DeviceVector prevDevices = outputDesc->devices();
3821 checkDeviceMuteStrategies(outputDesc, prevDevices, 0 /* delayMs */);
3822 }
3823}
3824
3825std::vector<sp<SwAudioOutputDescriptor>> AudioPolicyManager::getSoftwareOutputsForDevices(
3826 const AudioDeviceTypeAddrVector& devices) const
3827{
3828 std::vector<sp<SwAudioOutputDescriptor>> outputs;
3829 DeviceVector deviceDescriptors;
3830 for (size_t j = 0; j < devices.size(); j++) {
3831 sp<DeviceDescriptor> desc = mHwModules.getDeviceDescriptor(
3832 devices[j].mType, devices[j].getAddress(), String8(), AUDIO_FORMAT_DEFAULT);
3833 if (desc == nullptr || !audio_is_output_device(devices[j].mType)) {
3834 ALOGE("%s: device type %#x address %s not supported or not an output device",
3835 __func__, devices[j].mType, devices[j].getAddress());
3836 continue;
3837 }
3838 deviceDescriptors.add(desc);
3839 }
3840 for (size_t i = 0; i < mOutputs.size(); i++) {
3841 if (!mOutputs.valueAt(i)->supportsAtLeastOne(deviceDescriptors)) {
3842 continue;
3843 }
3844 outputs.push_back(mOutputs.valueAt(i));
3845 }
3846 return outputs;
3847}
3848
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003849status_t AudioPolicyManager::setUidDeviceAffinities(uid_t uid,
jiabin6a02d532020-08-07 11:56:38 -07003850 const AudioDeviceTypeAddrVector& devices) {
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003851 ALOGV("%s() uid=%d num devices %zu", __FUNCTION__, uid, devices.size());
Eric Laurentc529cf62020-04-17 18:19:10 -07003852 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
3853 return BAD_VALUE;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003854 }
3855 status_t res = mPolicyMixes.setUidDeviceAffinities(uid, devices);
Eric Laurentc529cf62020-04-17 18:19:10 -07003856 if (res != NO_ERROR) {
3857 ALOGE("%s() Could not set all device affinities for uid = %d", __FUNCTION__, uid);
3858 return res;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003859 }
Eric Laurentc529cf62020-04-17 18:19:10 -07003860
3861 checkForDeviceAndOutputChanges();
3862 updateCallAndOutputRouting();
3863
3864 return NO_ERROR;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003865}
3866
3867status_t AudioPolicyManager::removeUidDeviceAffinities(uid_t uid) {
3868 ALOGV("%s() uid=%d", __FUNCTION__, uid);
Oscar Azucena4b2a8212019-04-26 23:48:59 -07003869 status_t res = mPolicyMixes.removeUidDeviceAffinities(uid);
3870 if (res != NO_ERROR) {
Eric Laurentc529cf62020-04-17 18:19:10 -07003871 ALOGE("%s() Could not remove all device affinities for uid = %d",
Oscar Azucena4b2a8212019-04-26 23:48:59 -07003872 __FUNCTION__, uid);
3873 return INVALID_OPERATION;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003874 }
3875
Eric Laurentc529cf62020-04-17 18:19:10 -07003876 checkForDeviceAndOutputChanges();
3877 updateCallAndOutputRouting();
3878
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003879 return res;
3880}
3881
Eric Laurent2517af32020-11-25 15:31:27 +01003882
jiabin0a488932020-08-07 17:32:40 -07003883status_t AudioPolicyManager::setDevicesRoleForStrategy(product_strategy_t strategy,
3884 device_role_t role,
3885 const AudioDeviceTypeAddrVector &devices) {
3886 ALOGV("%s() strategy=%d role=%d %s", __func__, strategy, role,
3887 dumpAudioDeviceTypeAddrVector(devices).c_str());
Eric Laurentc529cf62020-04-17 18:19:10 -07003888
Eric Laurentc529cf62020-04-17 18:19:10 -07003889 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003890 return BAD_VALUE;
3891 }
jiabin0a488932020-08-07 17:32:40 -07003892 status_t status = mEngine->setDevicesRoleForStrategy(strategy, role, devices);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003893 if (status != NO_ERROR) {
jiabin0a488932020-08-07 17:32:40 -07003894 ALOGW("Engine could not set preferred devices %s for strategy %d role %d",
3895 dumpAudioDeviceTypeAddrVector(devices).c_str(), strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003896 return status;
3897 }
3898
3899 checkForDeviceAndOutputChanges();
Eric Laurent2517af32020-11-25 15:31:27 +01003900
3901 bool forceVolumeReeval = false;
3902 // FIXME: workaround for truncated touch sounds
3903 // to be removed when the problem is handled by system UI
3904 uint32_t delayMs = 0;
3905 if (strategy == mCommunnicationStrategy) {
3906 forceVolumeReeval = true;
3907 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
3908 updateInputRouting();
3909 }
3910 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003911
3912 return NO_ERROR;
3913}
3914
Oscar Azucena6acf34b2023-04-27 16:32:09 -07003915void AudioPolicyManager::updateCallAndOutputRouting(bool forceVolumeReeval, uint32_t delayMs,
3916 bool skipDelays)
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003917{
3918 uint32_t waitMs = 0;
Eric Laurent96d1dda2022-03-14 17:14:19 +01003919 bool wasLeUnicastActive = isLeUnicastActive();
Francois Gaffie19fd6c52021-02-04 17:02:59 +01003920 if (updateCallRouting(true /*fromCache*/, delayMs, &waitMs) == NO_ERROR) {
Eric Laurentb36b4ac2020-08-21 12:50:41 -07003921 // Only apply special touch sound delay once
3922 delayMs = 0;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003923 }
jiabin3ff8d7d2022-12-13 06:27:44 +00003924 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003925 for (size_t i = 0; i < mOutputs.size(); i++) {
3926 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
3927 DeviceVector newDevices = getNewOutputDevices(outputDesc, true /*fromCache*/);
Francois Gaffie601801d2021-06-22 13:27:39 +02003928 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) ||
3929 (outputDesc != mPrimaryOutput && !isTelephonyRxOrTx(outputDesc))) {
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003930 // As done in setDeviceConnectionState, we could also fix default device issue by
3931 // preventing the force re-routing in case of default dev that distinguishes on address.
3932 // Let's give back to engine full device choice decision however.
Francois Gaffie601801d2021-06-22 13:27:39 +02003933 bool forceRouting = !newDevices.isEmpty();
jiabin3ff8d7d2022-12-13 06:27:44 +00003934 if (outputDesc->mUsePreferredMixerAttributes && newDevices != outputDesc->devices()) {
3935 // If the device is using preferred mixer attributes, the output need to reopen
3936 // with default configuration when the new selected devices are different from
3937 // current routing devices.
3938 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices);
3939 continue;
3940 }
Francois Gaffie601801d2021-06-22 13:27:39 +02003941 waitMs = setOutputDevices(outputDesc, newDevices, forceRouting, delayMs, nullptr,
Oscar Azucena6acf34b2023-04-27 16:32:09 -07003942 !skipDelays /*requiresMuteCheck*/,
3943 !forceRouting /*requiresVolumeCheck*/, skipDelays);
Eric Laurentb36b4ac2020-08-21 12:50:41 -07003944 // Only apply special touch sound delay once
3945 delayMs = 0;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003946 }
3947 if (forceVolumeReeval && !newDevices.isEmpty()) {
3948 applyStreamVolumes(outputDesc, newDevices.types(), waitMs, true);
3949 }
3950 }
jiabin3ff8d7d2022-12-13 06:27:44 +00003951 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent96d1dda2022-03-14 17:14:19 +01003952 checkLeBroadcastRoutes(wasLeUnicastActive, nullptr, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003953}
3954
Eric Laurent2517af32020-11-25 15:31:27 +01003955void AudioPolicyManager::updateInputRouting() {
3956 for (const auto& activeDesc : mInputs.getActiveInputs()) {
Jaideep Sharma408349a2020-11-27 14:47:17 +05303957 // Skip for hotword recording as the input device switch
3958 // is handled within sound trigger HAL
3959 if (activeDesc->isSoundTrigger() && activeDesc->source() == AUDIO_SOURCE_HOTWORD) {
3960 continue;
3961 }
Eric Laurent2517af32020-11-25 15:31:27 +01003962 auto newDevice = getNewInputDevice(activeDesc);
3963 // Force new input selection if the new device can not be reached via current input
3964 if (activeDesc->mProfile->getSupportedDevices().contains(newDevice)) {
3965 setInputDevice(activeDesc->mIoHandle, newDevice);
3966 } else {
3967 closeInput(activeDesc->mIoHandle);
3968 }
3969 }
3970}
3971
Paul Wang5d7cdb52022-11-22 09:45:06 +00003972status_t
3973AudioPolicyManager::removeDevicesRoleForStrategy(product_strategy_t strategy,
3974 device_role_t role,
3975 const AudioDeviceTypeAddrVector &devices) {
3976 ALOGV("%s() strategy=%d role=%d %s", __func__, strategy, role,
3977 dumpAudioDeviceTypeAddrVector(devices).c_str());
3978
Eric Laurent78fedbf2023-03-09 14:40:44 +01003979 if (!areAllDevicesSupported(
3980 devices, audio_is_output_device, __func__, /*matchAddress*/false)) {
Paul Wang5d7cdb52022-11-22 09:45:06 +00003981 return BAD_VALUE;
3982 }
3983 status_t status = mEngine->removeDevicesRoleForStrategy(strategy, role, devices);
3984 if (status != NO_ERROR) {
3985 ALOGW("Engine could not remove devices %s for strategy %d role %d",
3986 dumpAudioDeviceTypeAddrVector(devices).c_str(), strategy, role);
3987 return status;
3988 }
3989
3990 checkForDeviceAndOutputChanges();
3991
3992 bool forceVolumeReeval = false;
3993 // TODO(b/263479999): workaround for truncated touch sounds
3994 // to be removed when the problem is handled by system UI
3995 uint32_t delayMs = 0;
3996 if (strategy == mCommunnicationStrategy) {
3997 forceVolumeReeval = true;
3998 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
3999 updateInputRouting();
4000 }
4001 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
4002
4003 return NO_ERROR;
4004}
4005
4006status_t AudioPolicyManager::clearDevicesRoleForStrategy(product_strategy_t strategy,
4007 device_role_t role)
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004008{
Eric Laurentfecbceb2021-02-09 14:46:43 +01004009 ALOGV("%s() strategy=%d role=%d", __func__, strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004010
Paul Wang5d7cdb52022-11-22 09:45:06 +00004011 status_t status = mEngine->clearDevicesRoleForStrategy(strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004012 if (status != NO_ERROR) {
Eric Laurent9ae44f32022-12-14 16:17:02 +01004013 ALOGW_IF(status != NAME_NOT_FOUND,
4014 "Engine could not remove device role for strategy %d status %d",
Eric Laurent2517af32020-11-25 15:31:27 +01004015 strategy, status);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004016 return status;
4017 }
4018
4019 checkForDeviceAndOutputChanges();
Eric Laurent2517af32020-11-25 15:31:27 +01004020
4021 bool forceVolumeReeval = false;
4022 // FIXME: workaround for truncated touch sounds
4023 // to be removed when the problem is handled by system UI
4024 uint32_t delayMs = 0;
4025 if (strategy == mCommunnicationStrategy) {
4026 forceVolumeReeval = true;
4027 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
4028 updateInputRouting();
4029 }
4030 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004031
4032 return NO_ERROR;
4033}
4034
jiabin0a488932020-08-07 17:32:40 -07004035status_t AudioPolicyManager::getDevicesForRoleAndStrategy(product_strategy_t strategy,
4036 device_role_t role,
4037 AudioDeviceTypeAddrVector &devices) {
4038 return mEngine->getDevicesForRoleAndStrategy(strategy, role, devices);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004039}
4040
Jiabin Huang3b98d322020-09-03 17:54:16 +00004041status_t AudioPolicyManager::setDevicesRoleForCapturePreset(
4042 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices) {
4043 ALOGV("%s() audioSource=%d role=%d %s", __func__, audioSource, role,
4044 dumpAudioDeviceTypeAddrVector(devices).c_str());
4045
Mikhail Naganov55773032020-10-01 15:08:13 -07004046 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00004047 return BAD_VALUE;
4048 }
4049 status_t status = mEngine->setDevicesRoleForCapturePreset(audioSource, role, devices);
4050 ALOGW_IF(status != NO_ERROR,
4051 "Engine could not set preferred devices %s for audio source %d role %d",
4052 dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
4053
4054 return status;
4055}
4056
4057status_t AudioPolicyManager::addDevicesRoleForCapturePreset(
4058 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices) {
4059 ALOGV("%s() audioSource=%d role=%d %s", __func__, audioSource, role,
4060 dumpAudioDeviceTypeAddrVector(devices).c_str());
4061
Mikhail Naganov55773032020-10-01 15:08:13 -07004062 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00004063 return BAD_VALUE;
4064 }
4065 status_t status = mEngine->addDevicesRoleForCapturePreset(audioSource, role, devices);
4066 ALOGW_IF(status != NO_ERROR,
4067 "Engine could not add preferred devices %s for audio source %d role %d",
4068 dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
4069
Eric Laurent2517af32020-11-25 15:31:27 +01004070 updateInputRouting();
Jiabin Huang3b98d322020-09-03 17:54:16 +00004071 return status;
4072}
4073
4074status_t AudioPolicyManager::removeDevicesRoleForCapturePreset(
4075 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector& devices)
4076{
4077 ALOGV("%s() audioSource=%d role=%d devices=%s", __func__, audioSource, role,
4078 dumpAudioDeviceTypeAddrVector(devices).c_str());
4079
Eric Laurent78fedbf2023-03-09 14:40:44 +01004080 if (!areAllDevicesSupported(
4081 devices, audio_call_is_input_device, __func__, /*matchAddress*/false)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00004082 return BAD_VALUE;
4083 }
4084
4085 status_t status = mEngine->removeDevicesRoleForCapturePreset(
4086 audioSource, role, devices);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004087 ALOGW_IF(status != NO_ERROR && status != NAME_NOT_FOUND,
Jiabin Huang3b98d322020-09-03 17:54:16 +00004088 "Engine could not remove devices role (%d) for capture preset %d", role, audioSource);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004089 if (status == NO_ERROR) {
4090 updateInputRouting();
4091 }
Jiabin Huang3b98d322020-09-03 17:54:16 +00004092 return status;
4093}
4094
4095status_t AudioPolicyManager::clearDevicesRoleForCapturePreset(audio_source_t audioSource,
4096 device_role_t role) {
4097 ALOGV("%s() audioSource=%d role=%d", __func__, audioSource, role);
4098
4099 status_t status = mEngine->clearDevicesRoleForCapturePreset(audioSource, role);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004100 ALOGW_IF(status != NO_ERROR && status != NAME_NOT_FOUND,
Jiabin Huang3b98d322020-09-03 17:54:16 +00004101 "Engine could not clear devices role (%d) for capture preset %d", role, audioSource);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004102 if (status == NO_ERROR) {
4103 updateInputRouting();
4104 }
Jiabin Huang3b98d322020-09-03 17:54:16 +00004105 return status;
4106}
4107
4108status_t AudioPolicyManager::getDevicesForRoleAndCapturePreset(
4109 audio_source_t audioSource, device_role_t role, AudioDeviceTypeAddrVector &devices) {
4110 return mEngine->getDevicesForRoleAndCapturePreset(audioSource, role, devices);
4111}
4112
Oscar Azucena90e77632019-11-27 17:12:28 -08004113status_t AudioPolicyManager::setUserIdDeviceAffinities(int userId,
jiabin6a02d532020-08-07 11:56:38 -07004114 const AudioDeviceTypeAddrVector& devices) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01004115 ALOGV("%s() userId=%d num devices %zu", __func__, userId, devices.size());
Eric Laurentc529cf62020-04-17 18:19:10 -07004116 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
4117 return BAD_VALUE;
Oscar Azucena90e77632019-11-27 17:12:28 -08004118 }
Oscar Azucena90e77632019-11-27 17:12:28 -08004119 status_t status = mPolicyMixes.setUserIdDeviceAffinities(userId, devices);
4120 if (status != NO_ERROR) {
4121 ALOGE("%s() could not set device affinity for userId %d",
4122 __FUNCTION__, userId);
4123 return status;
4124 }
4125
4126 // reevaluate outputs for all devices
4127 checkForDeviceAndOutputChanges();
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004128 changeOutputDevicesMuteState(devices);
4129 updateCallAndOutputRouting(false /* forceVolumeReeval */, 0 /* delayMs */,
4130 true /* skipDelays */);
4131 changeOutputDevicesMuteState(devices);
Oscar Azucena90e77632019-11-27 17:12:28 -08004132
4133 return NO_ERROR;
4134}
4135
4136status_t AudioPolicyManager::removeUserIdDeviceAffinities(int userId) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01004137 ALOGV("%s() userId=%d", __FUNCTION__, userId);
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004138 AudioDeviceTypeAddrVector devices;
4139 mPolicyMixes.getDevicesForUserId(userId, devices);
Oscar Azucena90e77632019-11-27 17:12:28 -08004140 status_t status = mPolicyMixes.removeUserIdDeviceAffinities(userId);
4141 if (status != NO_ERROR) {
4142 ALOGE("%s() Could not remove all device affinities fo userId = %d",
4143 __FUNCTION__, userId);
4144 return status;
4145 }
4146
4147 // reevaluate outputs for all devices
4148 checkForDeviceAndOutputChanges();
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004149 changeOutputDevicesMuteState(devices);
4150 updateCallAndOutputRouting(false /* forceVolumeReeval */, 0 /* delayMs */,
4151 true /* skipDelays */);
4152 changeOutputDevicesMuteState(devices);
Oscar Azucena90e77632019-11-27 17:12:28 -08004153
4154 return NO_ERROR;
4155}
4156
Andy Hungc29d82b2018-10-05 12:23:17 -07004157void AudioPolicyManager::dump(String8 *dst) const
Eric Laurente552edb2014-03-10 17:42:56 -07004158{
Andy Hungc29d82b2018-10-05 12:23:17 -07004159 dst->appendFormat("\nAudioPolicyManager Dump: %p\n", this);
Mikhail Naganov0dbe87b2021-12-01 02:03:31 +00004160 dst->appendFormat(" Primary Output I/O handle: %d\n",
Eric Laurent87ffa392015-05-22 10:32:38 -07004161 hasPrimaryOutput() ? mPrimaryOutput->mIoHandle : AUDIO_IO_HANDLE_NONE);
Mikhail Naganov0d6a0332016-04-19 17:12:38 -07004162 std::string stateLiteral;
4163 AudioModeConverter::toString(mEngine->getPhoneState(), stateLiteral);
Andy Hungc29d82b2018-10-05 12:23:17 -07004164 dst->appendFormat(" Phone state: %s\n", stateLiteral.c_str());
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07004165 const char* forceUses[AUDIO_POLICY_FORCE_USE_CNT] = {
4166 "communications", "media", "record", "dock", "system",
4167 "HDMI system audio", "encoded surround output", "vibrate ringing" };
4168 for (audio_policy_force_use_t i = AUDIO_POLICY_FORCE_FOR_COMMUNICATION;
4169 i < AUDIO_POLICY_FORCE_USE_CNT; i = (audio_policy_force_use_t)((int)i + 1)) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08004170 audio_policy_forced_cfg_t forceUseValue = mEngine->getForceUse(i);
4171 dst->appendFormat(" Force use for %s: %d", forceUses[i], forceUseValue);
4172 if (i == AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND &&
4173 forceUseValue == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
4174 dst->append(" (MANUAL: ");
4175 dumpManualSurroundFormats(dst);
4176 dst->append(")");
4177 }
4178 dst->append("\n");
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07004179 }
Andy Hungc29d82b2018-10-05 12:23:17 -07004180 dst->appendFormat(" TTS output %savailable\n", mTtsOutputAvailable ? "" : "not ");
4181 dst->appendFormat(" Master mono: %s\n", mMasterMono ? "on" : "off");
Mikhail Naganovb3bcb4f2022-02-23 23:46:56 +00004182 dst->appendFormat(" Communication Strategy id: %d\n", mCommunnicationStrategy);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07004183 dst->appendFormat(" Config source: %s\n", mConfig->getSource().c_str());
Eric Laurent2517af32020-11-25 15:31:27 +01004184
Mikhail Naganov0f413b22021-12-02 05:29:27 +00004185 dst->append("\n");
4186 mAvailableOutputDevices.dump(dst, String8("Available output"), 1);
4187 dst->append("\n");
4188 mAvailableInputDevices.dump(dst, String8("Available input"), 1);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07004189 mHwModules.dump(dst);
Andy Hungc29d82b2018-10-05 12:23:17 -07004190 mOutputs.dump(dst);
4191 mInputs.dump(dst);
Mikhail Naganov0f413b22021-12-02 05:29:27 +00004192 mEffects.dump(dst, 1);
Andy Hungc29d82b2018-10-05 12:23:17 -07004193 mAudioPatches.dump(dst);
4194 mPolicyMixes.dump(dst);
4195 mAudioSources.dump(dst);
François Gaffiec005e562018-11-06 15:04:49 +01004196
Kevin Rocardb99cc752019-03-21 20:52:24 -07004197 dst->appendFormat(" AllowedCapturePolicies:\n");
4198 for (auto& policy : mAllowedCapturePolicies) {
4199 dst->appendFormat(" - uid=%d flag_mask=%#x\n", policy.first, policy.second);
4200 }
4201
jiabina84c3d32022-12-02 18:59:55 +00004202 dst->appendFormat(" Preferred mixer audio configuration:\n");
4203 for (const auto it : mPreferredMixerAttrInfos) {
4204 dst->appendFormat(" - device port id: %d\n", it.first);
4205 for (const auto preferredMixerInfoIt : it.second) {
4206 dst->appendFormat(" - strategy: %d; ", preferredMixerInfoIt.first);
4207 preferredMixerInfoIt.second->dump(dst);
4208 }
4209 }
4210
François Gaffiec005e562018-11-06 15:04:49 +01004211 dst->appendFormat("\nPolicy Engine dump:\n");
4212 mEngine->dump(dst);
Andy Hungc29d82b2018-10-05 12:23:17 -07004213}
4214
4215status_t AudioPolicyManager::dump(int fd)
4216{
4217 String8 result;
4218 dump(&result);
Andy Hungbb54e202018-10-05 11:42:02 -07004219 write(fd, result.string(), result.size());
Eric Laurente552edb2014-03-10 17:42:56 -07004220 return NO_ERROR;
4221}
4222
Kevin Rocardb99cc752019-03-21 20:52:24 -07004223status_t AudioPolicyManager::setAllowedCapturePolicy(uid_t uid, audio_flags_mask_t capturePolicy)
4224{
4225 mAllowedCapturePolicies[uid] = capturePolicy;
4226 return NO_ERROR;
4227}
4228
Eric Laurente552edb2014-03-10 17:42:56 -07004229// This function checks for the parameters which can be offloaded.
4230// This can be enhanced depending on the capability of the DSP and policy
4231// of the system.
Eric Laurent90fe31c2020-11-26 20:06:35 +01004232audio_offload_mode_t AudioPolicyManager::getOffloadSupport(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07004233{
Eric Laurent90fe31c2020-11-26 20:06:35 +01004234 ALOGV("%s: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07004235 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurent90fe31c2020-11-26 20:06:35 +01004236 __func__, offloadInfo.sample_rate, offloadInfo.channel_mask,
Eric Laurente552edb2014-03-10 17:42:56 -07004237 offloadInfo.format,
4238 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
4239 offloadInfo.has_video);
4240
jiabin2b9d5a12021-12-10 01:06:29 +00004241 if (!isOffloadPossible(offloadInfo)) {
Eric Laurent90fe31c2020-11-26 20:06:35 +01004242 return AUDIO_OFFLOAD_NOT_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07004243 }
4244
4245 // See if there is a profile to support this.
4246 // AUDIO_DEVICE_NONE
François Gaffie11d30102018-11-02 16:09:09 +01004247 sp<IOProfile> profile = getProfileForOutput(DeviceVector() /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07004248 offloadInfo.sample_rate,
4249 offloadInfo.format,
4250 offloadInfo.channel_mask,
Michael Chana94fbb22018-04-24 14:31:19 +10004251 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD,
4252 true /* directOnly */);
Eric Laurent94365442021-01-08 18:36:05 +01004253 ALOGV("%s: profile %sfound%s", __func__, profile != nullptr ? "" : "NOT ",
4254 (profile != nullptr && (profile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD) != 0)
4255 ? ", supports gapless" : "");
Eric Laurent90fe31c2020-11-26 20:06:35 +01004256 if (profile == nullptr) {
4257 return AUDIO_OFFLOAD_NOT_SUPPORTED;
4258 }
4259 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD) != 0) {
4260 return AUDIO_OFFLOAD_GAPLESS_SUPPORTED;
4261 }
4262 return AUDIO_OFFLOAD_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07004263}
4264
Michael Chana94fbb22018-04-24 14:31:19 +10004265bool AudioPolicyManager::isDirectOutputSupported(const audio_config_base_t& config,
4266 const audio_attributes_t& attributes) {
4267 audio_output_flags_t output_flags = AUDIO_OUTPUT_FLAG_NONE;
François Gaffie58d4be52018-11-06 15:30:12 +01004268 audio_flags_to_audio_output_flags(attributes.flags, &output_flags);
Dorin Drimus9901eb02022-01-14 11:36:51 +00004269 DeviceVector outputDevices = mEngine->getOutputDevicesForAttributes(attributes);
4270 sp<IOProfile> profile = getProfileForOutput(outputDevices,
Michael Chana94fbb22018-04-24 14:31:19 +10004271 config.sample_rate,
4272 config.format,
4273 config.channel_mask,
4274 output_flags,
4275 true /* directOnly */);
4276 ALOGV("%s() profile %sfound with name: %s, "
4277 "sample rate: %u, format: 0x%x, channel_mask: 0x%x, output flags: 0x%x",
4278 __FUNCTION__, profile != 0 ? "" : "NOT ",
jiabin5740f082019-08-19 15:08:30 -07004279 (profile != 0 ? profile->getTagName().c_str() : "null"),
Michael Chana94fbb22018-04-24 14:31:19 +10004280 config.sample_rate, config.format, config.channel_mask, output_flags);
Dorin Drimusecc9f422022-03-09 17:57:40 +01004281
4282 // also try the MSD module if compatible profile not found
4283 if (profile == nullptr) {
4284 profile = getMsdProfileForOutput(outputDevices,
4285 config.sample_rate,
4286 config.format,
4287 config.channel_mask,
4288 output_flags,
4289 true /* directOnly */);
4290 ALOGV("%s() MSD profile %sfound with name: %s, "
4291 "sample rate: %u, format: 0x%x, channel_mask: 0x%x, output flags: 0x%x",
4292 __FUNCTION__, profile != 0 ? "" : "NOT ",
4293 (profile != 0 ? profile->getTagName().c_str() : "null"),
4294 config.sample_rate, config.format, config.channel_mask, output_flags);
4295 }
4296 return (profile != nullptr);
Michael Chana94fbb22018-04-24 14:31:19 +10004297}
4298
jiabin2b9d5a12021-12-10 01:06:29 +00004299bool AudioPolicyManager::isOffloadPossible(const audio_offload_info_t &offloadInfo,
4300 bool durationIgnored) {
4301 if (mMasterMono) {
4302 return false; // no offloading if mono is set.
4303 }
4304
4305 // Check if offload has been disabled
4306 if (property_get_bool("audio.offload.disable", false /* default_value */)) {
4307 ALOGV("%s: offload disabled by audio.offload.disable", __func__);
4308 return false;
4309 }
4310
4311 // Check if stream type is music, then only allow offload as of now.
4312 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
4313 {
4314 ALOGV("%s: stream_type != MUSIC, returning false", __func__);
4315 return false;
4316 }
4317
4318 //TODO: enable audio offloading with video when ready
4319 const bool allowOffloadWithVideo =
4320 property_get_bool("audio.offload.video", false /* default_value */);
4321 if (offloadInfo.has_video && !allowOffloadWithVideo) {
4322 ALOGV("%s: has_video == true, returning false", __func__);
4323 return false;
4324 }
4325
4326 //If duration is less than minimum value defined in property, return false
4327 const int min_duration_secs = property_get_int32(
4328 "audio.offload.min.duration.secs", -1 /* default_value */);
4329 if (!durationIgnored) {
4330 if (min_duration_secs >= 0) {
4331 if (offloadInfo.duration_us < min_duration_secs * 1000000LL) {
4332 ALOGV("%s: Offload denied by duration < audio.offload.min.duration.secs(=%d)",
4333 __func__, min_duration_secs);
4334 return false;
4335 }
4336 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
4337 ALOGV("%s: Offload denied by duration < default min(=%u)",
4338 __func__, OFFLOAD_DEFAULT_MIN_DURATION_SECS);
4339 return false;
4340 }
4341 }
4342
4343 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
4344 // creating an offloaded track and tearing it down immediately after start when audioflinger
4345 // detects there is an active non offloadable effect.
4346 // FIXME: We should check the audio session here but we do not have it in this context.
4347 // This may prevent offloading in rare situations where effects are left active by apps
4348 // in the background.
4349 if (mEffects.isNonOffloadableEffectEnabled()) {
4350 return false;
4351 }
4352
4353 return true;
4354}
4355
4356audio_direct_mode_t AudioPolicyManager::getDirectPlaybackSupport(const audio_attributes_t *attr,
4357 const audio_config_t *config) {
4358 audio_offload_info_t offloadInfo = AUDIO_INFO_INITIALIZER;
4359 offloadInfo.format = config->format;
4360 offloadInfo.sample_rate = config->sample_rate;
4361 offloadInfo.channel_mask = config->channel_mask;
4362 offloadInfo.stream_type = mEngine->getStreamTypeForAttributes(*attr);
4363 offloadInfo.has_video = false;
4364 offloadInfo.is_streaming = false;
4365 const bool offloadPossible = isOffloadPossible(offloadInfo, true /*durationIgnored*/);
4366
4367 audio_direct_mode_t directMode = AUDIO_DIRECT_NOT_SUPPORTED;
4368 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
4369 audio_flags_to_audio_output_flags(attr->flags, &flags);
4370 // only retain flags that will drive compressed offload or passthrough
4371 uint32_t relevantFlags = AUDIO_OUTPUT_FLAG_HW_AV_SYNC;
4372 if (offloadPossible) {
4373 relevantFlags |= AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD;
4374 }
4375 flags = (audio_output_flags_t)((flags & relevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
4376
Dorin Drimusfae3c642022-03-17 18:36:30 +01004377 DeviceVector engineOutputDevices = mEngine->getOutputDevicesForAttributes(*attr);
jiabin2b9d5a12021-12-10 01:06:29 +00004378 for (const auto& hwModule : mHwModules) {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004379 DeviceVector outputDevices = engineOutputDevices;
4380 // the MSD module checks for different conditions and output devices
4381 if (strcmp(hwModule->getName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0) {
4382 if (!msdHasPatchesToAllDevices(engineOutputDevices.toTypeAddrVector())) {
4383 continue;
4384 }
4385 outputDevices = getMsdAudioOutDevices();
4386 }
jiabin2b9d5a12021-12-10 01:06:29 +00004387 for (const auto& curProfile : hwModule->getOutputProfiles()) {
jiabinc8f7dfc2022-01-06 18:42:08 +00004388 if (!curProfile->isCompatibleProfile(outputDevices,
jiabin2b9d5a12021-12-10 01:06:29 +00004389 config->sample_rate, nullptr /*updatedSamplingRate*/,
4390 config->format, nullptr /*updatedFormat*/,
4391 config->channel_mask, nullptr /*updatedChannelMask*/,
4392 flags)) {
4393 continue;
4394 }
4395 // reject profiles not corresponding to a device currently available
4396 if (!mAvailableOutputDevices.containsAtLeastOne(curProfile->getSupportedDevices())) {
4397 continue;
4398 }
4399 if ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)
4400 != AUDIO_OUTPUT_FLAG_NONE) {
jiabinc6132d62022-01-01 07:36:31 +00004401 if ((directMode & AUDIO_DIRECT_OFFLOAD_GAPLESS_SUPPORTED)
jiabin2b9d5a12021-12-10 01:06:29 +00004402 != AUDIO_DIRECT_NOT_SUPPORTED) {
4403 // Already reports offload gapless supported. No need to report offload support.
4404 continue;
4405 }
4406 if ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD)
4407 != AUDIO_OUTPUT_FLAG_NONE) {
4408 // If offload gapless is reported, no need to report offload support.
4409 directMode = (audio_direct_mode_t) ((directMode &
4410 ~AUDIO_DIRECT_OFFLOAD_SUPPORTED) |
4411 AUDIO_DIRECT_OFFLOAD_GAPLESS_SUPPORTED);
4412 } else {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004413 directMode = (audio_direct_mode_t)(directMode | AUDIO_DIRECT_OFFLOAD_SUPPORTED);
jiabin2b9d5a12021-12-10 01:06:29 +00004414 }
4415 } else {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004416 directMode = (audio_direct_mode_t) (directMode | AUDIO_DIRECT_BITSTREAM_SUPPORTED);
jiabin2b9d5a12021-12-10 01:06:29 +00004417 }
4418 }
4419 }
4420 return directMode;
4421}
4422
Dorin Drimusf2196d82022-01-03 12:11:18 +01004423status_t AudioPolicyManager::getDirectProfilesForAttributes(const audio_attributes_t* attr,
4424 AudioProfileVector& audioProfilesVector) {
Dorin Drimus17112632022-09-23 15:28:51 +00004425 if (mEffects.isNonOffloadableEffectEnabled()) {
4426 return OK;
4427 }
jiabinf1c73972022-04-14 16:28:52 -07004428 DeviceVector devices;
4429 status_t status = getDevicesForAttributes(*attr, devices, false /* forVolume */);
Dorin Drimusf2196d82022-01-03 12:11:18 +01004430 if (status != OK) {
4431 return status;
4432 }
4433 ALOGV("%s: found %zu output devices for attributes.", __func__, devices.size());
4434 if (devices.empty()) {
4435 return OK; // no output devices for the attributes
4436 }
jiabinf1c73972022-04-14 16:28:52 -07004437 return getProfilesForDevices(devices, audioProfilesVector,
4438 AUDIO_OUTPUT_FLAG_DIRECT /*flags*/, false /*isInput*/);
Dorin Drimusf2196d82022-01-03 12:11:18 +01004439}
4440
jiabina84c3d32022-12-02 18:59:55 +00004441status_t AudioPolicyManager::getSupportedMixerAttributes(
4442 audio_port_handle_t portId, std::vector<audio_mixer_attributes_t> &mixerAttrs) {
4443 ALOGV("%s, portId=%d", __func__, portId);
4444 sp<DeviceDescriptor> deviceDescriptor = mAvailableOutputDevices.getDeviceFromId(portId);
4445 if (deviceDescriptor == nullptr) {
4446 ALOGE("%s the requested device is currently unavailable", __func__);
4447 return BAD_VALUE;
4448 }
jiabin96daffc2023-05-11 17:51:55 +00004449 if (!audio_is_usb_out_device(deviceDescriptor->type())) {
4450 ALOGE("%s the requested device(type=%#x) is not usb device", __func__,
4451 deviceDescriptor->type());
4452 return BAD_VALUE;
4453 }
jiabina84c3d32022-12-02 18:59:55 +00004454 for (const auto& hwModule : mHwModules) {
4455 for (const auto& curProfile : hwModule->getOutputProfiles()) {
4456 if (curProfile->supportsDevice(deviceDescriptor)) {
4457 curProfile->toSupportedMixerAttributes(&mixerAttrs);
4458 }
4459 }
4460 }
4461 return NO_ERROR;
4462}
4463
4464status_t AudioPolicyManager::setPreferredMixerAttributes(
4465 const audio_attributes_t *attr,
4466 audio_port_handle_t portId,
4467 uid_t uid,
4468 const audio_mixer_attributes_t *mixerAttributes) {
4469 ALOGV("%s, attr=%s, mixerAttributes={format=%#x, channelMask=%#x, samplingRate=%u, "
4470 "mixerBehavior=%d}, uid=%d, portId=%u",
4471 __func__, toString(*attr).c_str(), mixerAttributes->config.format,
4472 mixerAttributes->config.channel_mask, mixerAttributes->config.sample_rate,
4473 mixerAttributes->mixer_behavior, uid, portId);
4474 if (attr->usage != AUDIO_USAGE_MEDIA) {
4475 ALOGE("%s failed, only media is allowed, the given usage is %d", __func__, attr->usage);
4476 return BAD_VALUE;
4477 }
4478 sp<DeviceDescriptor> deviceDescriptor = mAvailableOutputDevices.getDeviceFromId(portId);
4479 if (deviceDescriptor == nullptr) {
4480 ALOGE("%s the requested device is currently unavailable", __func__);
4481 return BAD_VALUE;
4482 }
4483 if (!audio_is_usb_out_device(deviceDescriptor->type())) {
4484 ALOGE("%s(%d), type=%d, is not a usb output device",
4485 __func__, portId, deviceDescriptor->type());
4486 return BAD_VALUE;
4487 }
4488
4489 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
4490 audio_flags_to_audio_output_flags(attr->flags, &flags);
4491 flags = (audio_output_flags_t) (flags |
4492 audio_output_flags_from_mixer_behavior(mixerAttributes->mixer_behavior));
4493 sp<IOProfile> profile = nullptr;
4494 DeviceVector devices(deviceDescriptor);
4495 for (const auto& hwModule : mHwModules) {
4496 for (const auto& curProfile : hwModule->getOutputProfiles()) {
4497 if (curProfile->hasDynamicAudioProfile()
4498 && curProfile->isCompatibleProfile(devices,
4499 mixerAttributes->config.sample_rate,
4500 nullptr /*updatedSamplingRate*/,
4501 mixerAttributes->config.format,
4502 nullptr /*updatedFormat*/,
4503 mixerAttributes->config.channel_mask,
4504 nullptr /*updatedChannelMask*/,
4505 flags,
4506 false /*exactMatchRequiredForInputFlags*/)) {
4507 profile = curProfile;
4508 break;
4509 }
4510 }
4511 }
4512 if (profile == nullptr) {
4513 ALOGE("%s, there is no compatible profile found", __func__);
4514 return BAD_VALUE;
4515 }
4516
4517 sp<PreferredMixerAttributesInfo> mixerAttrInfo =
4518 sp<PreferredMixerAttributesInfo>::make(
4519 uid, portId, profile, flags, *mixerAttributes);
4520 const product_strategy_t strategy = mEngine->getProductStrategyForAttributes(*attr);
4521 mPreferredMixerAttrInfos[portId][strategy] = mixerAttrInfo;
4522
4523 // If 1) there is any client from the preferred mixer configuration owner that is currently
4524 // active and matches the strategy and 2) current output is on the preferred device and the
4525 // mixer configuration doesn't match the preferred one, reopen output with preferred mixer
4526 // configuration.
4527 std::vector<audio_io_handle_t> outputsToReopen;
4528 for (size_t i = 0; i < mOutputs.size(); i++) {
4529 const auto output = mOutputs.valueAt(i);
jiabin3ff8d7d2022-12-13 06:27:44 +00004530 if (output->mProfile == profile && output->devices().onlyContainsDevice(deviceDescriptor)) {
4531 if (output->isConfigurationMatched(mixerAttributes->config, flags)) {
4532 output->mUsePreferredMixerAttributes = true;
4533 } else {
4534 for (const auto &client: output->getActiveClients()) {
4535 if (client->uid() == uid && client->strategy() == strategy) {
4536 client->setIsInvalid();
4537 outputsToReopen.push_back(output->mIoHandle);
4538 }
jiabina84c3d32022-12-02 18:59:55 +00004539 }
4540 }
4541 }
4542 }
4543 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
4544 config.sample_rate = mixerAttributes->config.sample_rate;
4545 config.channel_mask = mixerAttributes->config.channel_mask;
4546 config.format = mixerAttributes->config.format;
4547 for (const auto output : outputsToReopen) {
jiabin3ff8d7d2022-12-13 06:27:44 +00004548 sp<SwAudioOutputDescriptor> desc =
4549 reopenOutput(mOutputs.valueFor(output), &config, flags, __func__);
4550 if (desc == nullptr) {
4551 ALOGE("%s, failed to reopen output with preferred mixer attributes", __func__);
4552 continue;
4553 }
4554 desc->mUsePreferredMixerAttributes = true;
jiabina84c3d32022-12-02 18:59:55 +00004555 }
4556
4557 return NO_ERROR;
4558}
4559
4560sp<PreferredMixerAttributesInfo> AudioPolicyManager::getPreferredMixerAttributesInfo(
jiabind9a58d32023-06-01 17:57:30 +00004561 audio_port_handle_t devicePortId,
4562 product_strategy_t strategy,
4563 bool activeBitPerfectPreferred) {
jiabina84c3d32022-12-02 18:59:55 +00004564 auto it = mPreferredMixerAttrInfos.find(devicePortId);
4565 if (it == mPreferredMixerAttrInfos.end()) {
4566 return nullptr;
4567 }
jiabind9a58d32023-06-01 17:57:30 +00004568 if (activeBitPerfectPreferred) {
4569 for (auto [strategy, info] : it->second) {
4570 if ((info->getFlags() & AUDIO_OUTPUT_FLAG_BIT_PERFECT) != AUDIO_OUTPUT_FLAG_NONE
4571 && info->getActiveClientCount() != 0) {
4572 return info;
4573 }
4574 }
jiabina84c3d32022-12-02 18:59:55 +00004575 }
jiabind9a58d32023-06-01 17:57:30 +00004576 auto strategyMatchedMixerAttrInfoIt = it->second.find(strategy);
4577 return strategyMatchedMixerAttrInfoIt == it->second.end()
4578 ? nullptr : strategyMatchedMixerAttrInfoIt->second;
jiabina84c3d32022-12-02 18:59:55 +00004579}
4580
4581status_t AudioPolicyManager::getPreferredMixerAttributes(
4582 const audio_attributes_t *attr,
4583 audio_port_handle_t portId,
4584 audio_mixer_attributes_t* mixerAttributes) {
4585 sp<PreferredMixerAttributesInfo> info = getPreferredMixerAttributesInfo(
4586 portId, mEngine->getProductStrategyForAttributes(*attr));
4587 if (info == nullptr) {
4588 return NAME_NOT_FOUND;
4589 }
4590 *mixerAttributes = info->getMixerAttributes();
4591 return NO_ERROR;
4592}
4593
4594status_t AudioPolicyManager::clearPreferredMixerAttributes(const audio_attributes_t *attr,
4595 audio_port_handle_t portId,
4596 uid_t uid) {
4597 const product_strategy_t strategy = mEngine->getProductStrategyForAttributes(*attr);
4598 const auto preferredMixerAttrInfo = getPreferredMixerAttributesInfo(portId, strategy);
4599 if (preferredMixerAttrInfo == nullptr) {
4600 return NAME_NOT_FOUND;
4601 }
4602 if (preferredMixerAttrInfo->getUid() != uid) {
4603 ALOGE("%s, requested uid=%d, owned uid=%d",
4604 __func__, uid, preferredMixerAttrInfo->getUid());
4605 return PERMISSION_DENIED;
4606 }
4607 mPreferredMixerAttrInfos[portId].erase(strategy);
4608 if (mPreferredMixerAttrInfos[portId].empty()) {
4609 mPreferredMixerAttrInfos.erase(portId);
4610 }
4611
4612 // Reconfig existing output
4613 std::vector<audio_io_handle_t> potentialOutputsToReopen;
4614 for (size_t i = 0; i < mOutputs.size(); i++) {
4615 if (mOutputs.valueAt(i)->mProfile == preferredMixerAttrInfo->getProfile()) {
4616 potentialOutputsToReopen.push_back(mOutputs.keyAt(i));
4617 }
4618 }
4619 for (const auto output : potentialOutputsToReopen) {
4620 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
4621 if (desc->isConfigurationMatched(preferredMixerAttrInfo->getConfigBase(),
4622 preferredMixerAttrInfo->getFlags())) {
4623 reopenOutput(desc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
4624 }
4625 }
4626 return NO_ERROR;
4627}
4628
Eric Laurent6a94d692014-05-20 11:18:06 -07004629status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
4630 audio_port_type_t type,
4631 unsigned int *num_ports,
jiabin19cdba52020-11-24 11:28:58 -08004632 struct audio_port_v7 *ports,
Eric Laurent6a94d692014-05-20 11:18:06 -07004633 unsigned int *generation)
4634{
jiabin19cdba52020-11-24 11:28:58 -08004635 if (num_ports == nullptr || (*num_ports != 0 && ports == nullptr) ||
4636 generation == nullptr) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004637 return BAD_VALUE;
4638 }
4639 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
jiabin19cdba52020-11-24 11:28:58 -08004640 if (ports == nullptr) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004641 *num_ports = 0;
4642 }
4643
4644 size_t portsWritten = 0;
4645 size_t portsMax = *num_ports;
4646 *num_ports = 0;
4647 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07004648 // do not report devices with type AUDIO_DEVICE_IN_STUB or AUDIO_DEVICE_OUT_STUB
4649 // as they are used by stub HALs by convention
Eric Laurent6a94d692014-05-20 11:18:06 -07004650 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004651 for (const auto& dev : mAvailableOutputDevices) {
4652 if (dev->type() == AUDIO_DEVICE_OUT_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07004653 continue;
4654 }
4655 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004656 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07004657 }
4658 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07004659 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004660 }
4661 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004662 for (const auto& dev : mAvailableInputDevices) {
4663 if (dev->type() == AUDIO_DEVICE_IN_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07004664 continue;
4665 }
4666 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004667 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07004668 }
4669 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07004670 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004671 }
4672 }
4673 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
4674 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
4675 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
4676 mInputs[i]->toAudioPort(&ports[portsWritten++]);
4677 }
4678 *num_ports += mInputs.size();
4679 }
4680 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent84c70242014-06-23 08:46:27 -07004681 size_t numOutputs = 0;
4682 for (size_t i = 0; i < mOutputs.size(); i++) {
4683 if (!mOutputs[i]->isDuplicated()) {
4684 numOutputs++;
4685 if (portsWritten < portsMax) {
4686 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
4687 }
4688 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004689 }
Eric Laurent84c70242014-06-23 08:46:27 -07004690 *num_ports += numOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07004691 }
4692 }
jiabina84c3d32022-12-02 18:59:55 +00004693
Eric Laurent6a94d692014-05-20 11:18:06 -07004694 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07004695 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
Eric Laurent6a94d692014-05-20 11:18:06 -07004696 return NO_ERROR;
4697}
4698
Mikhail Naganov5edc5ed2023-03-23 14:52:15 -07004699status_t AudioPolicyManager::listDeclaredDevicePorts(media::AudioPortRole role,
4700 std::vector<media::AudioPortFw>* _aidl_return) {
4701 auto pushPort = [&](const sp<DeviceDescriptor>& dev) -> status_t {
4702 audio_port_v7 port;
4703 dev->toAudioPort(&port);
4704 auto aidlPort = VALUE_OR_RETURN_STATUS(legacy2aidl_audio_port_v7_AudioPortFw(port));
4705 _aidl_return->push_back(std::move(aidlPort));
4706 return OK;
4707 };
4708
Mikhail Naganov68e3f642023-04-28 13:06:32 -07004709 for (const auto& module : mHwModules) {
Mikhail Naganov5edc5ed2023-03-23 14:52:15 -07004710 for (const auto& dev : module->getDeclaredDevices()) {
4711 if (role == media::AudioPortRole::NONE ||
4712 ((role == media::AudioPortRole::SOURCE)
4713 == audio_is_input_device(dev->type()))) {
4714 RETURN_STATUS_IF_ERROR(pushPort(dev));
4715 }
4716 }
4717 }
4718 return OK;
4719}
4720
jiabin19cdba52020-11-24 11:28:58 -08004721status_t AudioPolicyManager::getAudioPort(struct audio_port_v7 *port)
Eric Laurent6a94d692014-05-20 11:18:06 -07004722{
Eric Laurent99fcae42018-05-17 16:59:18 -07004723 if (port == nullptr || port->id == AUDIO_PORT_HANDLE_NONE) {
4724 return BAD_VALUE;
4725 }
4726 sp<DeviceDescriptor> dev = mAvailableOutputDevices.getDeviceFromId(port->id);
4727 if (dev != 0) {
4728 dev->toAudioPort(port);
4729 return NO_ERROR;
4730 }
4731 dev = mAvailableInputDevices.getDeviceFromId(port->id);
4732 if (dev != 0) {
4733 dev->toAudioPort(port);
4734 return NO_ERROR;
4735 }
4736 sp<SwAudioOutputDescriptor> out = mOutputs.getOutputFromId(port->id);
4737 if (out != 0) {
4738 out->toAudioPort(port);
4739 return NO_ERROR;
4740 }
4741 sp<AudioInputDescriptor> in = mInputs.getInputFromId(port->id);
4742 if (in != 0) {
4743 in->toAudioPort(port);
4744 return NO_ERROR;
4745 }
4746 return BAD_VALUE;
Eric Laurent6a94d692014-05-20 11:18:06 -07004747}
4748
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004749status_t AudioPolicyManager::createAudioPatch(const struct audio_patch *patch,
4750 audio_patch_handle_t *handle,
4751 uid_t uid)
Eric Laurent6a94d692014-05-20 11:18:06 -07004752{
François Gaffieafd4cea2019-11-18 15:50:22 +01004753 ALOGV("%s", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004754 if (handle == NULL || patch == NULL) {
4755 return BAD_VALUE;
4756 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004757 ALOGV("%s num sources %d num sinks %d", __func__, patch->num_sources, patch->num_sinks);
Mikhail Naganovac9858b2018-06-15 13:12:37 -07004758 if (!audio_patch_is_valid(patch)) {
Eric Laurent874c42872014-08-08 15:13:39 -07004759 return BAD_VALUE;
4760 }
4761 // only one source per audio patch supported for now
4762 if (patch->num_sources > 1) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004763 return INVALID_OPERATION;
4764 }
Eric Laurent874c42872014-08-08 15:13:39 -07004765 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004766 return INVALID_OPERATION;
4767 }
Eric Laurent874c42872014-08-08 15:13:39 -07004768 for (size_t i = 0; i < patch->num_sinks; i++) {
4769 if (patch->sinks[i].role != AUDIO_PORT_ROLE_SINK) {
4770 return INVALID_OPERATION;
4771 }
4772 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004773
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004774 sp<DeviceDescriptor> srcDevice = mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
4775 sp<DeviceDescriptor> sinkDevice = mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id);
4776 if (srcDevice == nullptr || sinkDevice == nullptr) {
4777 ALOGW("%s could not create patch, invalid sink and/or source device(s)", __func__);
4778 return BAD_VALUE;
4779 }
4780 ALOGV("%s between source %s and sink %s", __func__,
4781 srcDevice->toString().c_str(), sinkDevice->toString().c_str());
4782 audio_port_handle_t portId = PolicyAudioPort::getNextUniqueId();
4783 // Default attributes, default volume priority, not to infer with non raw audio patches.
4784 audio_attributes_t attributes = attributes_initializer(AUDIO_USAGE_MEDIA);
4785 const struct audio_port_config *source = &patch->sources[0];
4786 sp<SourceClientDescriptor> sourceDesc =
4787 new InternalSourceClientDescriptor(
4788 portId, uid, attributes, *source, srcDevice, sinkDevice,
4789 mEngine->getProductStrategyForAttributes(attributes), toVolumeSource(attributes));
4790
4791 status_t status =
4792 connectAudioSourceToSink(sourceDesc, sinkDevice, patch, *handle, uid, 0 /* delayMs */);
4793
4794 if (status != NO_ERROR) {
4795 return INVALID_OPERATION;
4796 }
4797 mAudioSources.add(portId, sourceDesc);
4798 return NO_ERROR;
4799}
4800
4801status_t AudioPolicyManager::connectAudioSourceToSink(
4802 const sp<SourceClientDescriptor>& sourceDesc, const sp<DeviceDescriptor> &sinkDevice,
4803 const struct audio_patch *patch,
4804 audio_patch_handle_t &handle,
4805 uid_t uid, uint32_t delayMs)
4806{
4807 status_t status = createAudioPatchInternal(patch, &handle, uid, delayMs, sourceDesc);
4808 if (status != NO_ERROR || mAudioPatches.indexOfKey(handle) < 0) {
4809 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
4810 return INVALID_OPERATION;
4811 }
4812 sourceDesc->connect(handle, sinkDevice);
4813 if (isMsdPatch(handle)) {
4814 return NO_ERROR;
4815 }
4816 // SW Bridge? (@todo: HW bridge, keep track of HwOutput for device selection "reconsideration")
4817 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
4818 ALOG_ASSERT(swOutput != nullptr, "%s: a swOutput shall always be associated", __func__);
4819 if (swOutput->getClient(sourceDesc->portId()) != nullptr) {
4820 ALOGW("%s source portId has already been attached to outputDesc", __func__);
4821 goto FailurePatchAdded;
4822 }
4823 status = swOutput->start();
4824 if (status != NO_ERROR) {
4825 goto FailureSourceAdded;
4826 }
4827 swOutput->addClient(sourceDesc);
4828 status = startSource(swOutput, sourceDesc, &delayMs);
4829 if (status != NO_ERROR) {
4830 ALOGW("%s failed to start source, error %d", __FUNCTION__, status);
4831 goto FailureSourceActive;
4832 }
4833 if (delayMs != 0) {
4834 usleep(delayMs * 1000);
4835 }
4836 return NO_ERROR;
4837
4838FailureSourceActive:
4839 swOutput->stop();
4840 releaseOutput(sourceDesc->portId());
4841FailureSourceAdded:
4842 sourceDesc->setSwOutput(nullptr);
4843FailurePatchAdded:
4844 releaseAudioPatchInternal(handle);
4845 return INVALID_OPERATION;
4846}
4847
4848status_t AudioPolicyManager::createAudioPatchInternal(const struct audio_patch *patch,
4849 audio_patch_handle_t *handle,
4850 uid_t uid, uint32_t delayMs,
4851 const sp<SourceClientDescriptor>& sourceDesc)
4852{
4853 ALOGV("%s num sources %d num sinks %d", __func__, patch->num_sources, patch->num_sinks);
Eric Laurent6a94d692014-05-20 11:18:06 -07004854 sp<AudioPatch> patchDesc;
4855 ssize_t index = mAudioPatches.indexOfKey(*handle);
4856
François Gaffieafd4cea2019-11-18 15:50:22 +01004857 ALOGV("%s source id %d role %d type %d", __func__, patch->sources[0].id,
4858 patch->sources[0].role,
4859 patch->sources[0].type);
Eric Laurent874c42872014-08-08 15:13:39 -07004860#if LOG_NDEBUG == 0
4861 for (size_t i = 0; i < patch->num_sinks; i++) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004862 ALOGV("%s sink %zu: id %d role %d type %d", __func__ ,i, patch->sinks[i].id,
4863 patch->sinks[i].role,
4864 patch->sinks[i].type);
Eric Laurent874c42872014-08-08 15:13:39 -07004865 }
4866#endif
Eric Laurent6a94d692014-05-20 11:18:06 -07004867
4868 if (index >= 0) {
4869 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01004870 ALOGV("%s mUidCached %d patchDesc->mUid %d uid %d",
4871 __func__, mUidCached, patchDesc->getUid(), uid);
4872 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004873 return INVALID_OPERATION;
4874 }
4875 } else {
Glenn Kastena13cde92016-03-28 15:26:02 -07004876 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07004877 }
4878
4879 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004880 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004881 if (outputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004882 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004883 return BAD_VALUE;
4884 }
Eric Laurent84c70242014-06-23 08:46:27 -07004885 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
4886 outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004887 if (patchDesc != 0) {
4888 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004889 ALOGV("%s source id differs for patch current id %d new id %d",
4890 __func__, patchDesc->mPatch.sources[0].id, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004891 return BAD_VALUE;
4892 }
4893 }
Eric Laurent874c42872014-08-08 15:13:39 -07004894 DeviceVector devices;
4895 for (size_t i = 0; i < patch->num_sinks; i++) {
4896 // Only support mix to devices connection
4897 // TODO add support for mix to mix connection
4898 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004899 ALOGV("%s source mix but sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07004900 return INVALID_OPERATION;
4901 }
4902 sp<DeviceDescriptor> devDesc =
4903 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
4904 if (devDesc == 0) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004905 ALOGV("%s out device not found for id %d", __func__, patch->sinks[i].id);
Eric Laurent874c42872014-08-08 15:13:39 -07004906 return BAD_VALUE;
4907 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004908
François Gaffie11d30102018-11-02 16:09:09 +01004909 if (!outputDesc->mProfile->isCompatibleProfile(DeviceVector(devDesc),
Eric Laurent874c42872014-08-08 15:13:39 -07004910 patch->sources[0].sample_rate,
François Gaffie53615e22015-03-19 09:24:12 +01004911 NULL, // updatedSamplingRate
4912 patch->sources[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07004913 NULL, // updatedFormat
François Gaffie53615e22015-03-19 09:24:12 +01004914 patch->sources[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07004915 NULL, // updatedChannelMask
François Gaffie53615e22015-03-19 09:24:12 +01004916 AUDIO_OUTPUT_FLAG_NONE /*FIXME*/)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004917 ALOGV("%s profile not supported for device %08x", __func__, devDesc->type());
Eric Laurent874c42872014-08-08 15:13:39 -07004918 return INVALID_OPERATION;
4919 }
4920 devices.add(devDesc);
4921 }
4922 if (devices.size() == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004923 return INVALID_OPERATION;
4924 }
Eric Laurent874c42872014-08-08 15:13:39 -07004925
Eric Laurent6a94d692014-05-20 11:18:06 -07004926 // TODO: reconfigure output format and channels here
François Gaffieafd4cea2019-11-18 15:50:22 +01004927 ALOGV("%s setting device %s on output %d",
4928 __func__, dumpDeviceTypes(devices.types()).c_str(), outputDesc->mIoHandle);
François Gaffie11d30102018-11-02 16:09:09 +01004929 setOutputDevices(outputDesc, devices, true, 0, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004930 index = mAudioPatches.indexOfKey(*handle);
4931 if (index >= 0) {
4932 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004933 ALOGW("%s setOutputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004934 }
4935 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01004936 patchDesc->setUid(uid);
4937 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004938 } else {
François Gaffieafd4cea2019-11-18 15:50:22 +01004939 ALOGW("%s setOutputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004940 return INVALID_OPERATION;
4941 }
4942 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
4943 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
4944 // input device to input mix connection
Eric Laurent874c42872014-08-08 15:13:39 -07004945 // only one sink supported when connecting an input device to a mix
4946 if (patch->num_sinks > 1) {
4947 return INVALID_OPERATION;
4948 }
François Gaffie53615e22015-03-19 09:24:12 +01004949 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004950 if (inputDesc == NULL) {
4951 return BAD_VALUE;
4952 }
4953 if (patchDesc != 0) {
4954 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
4955 return BAD_VALUE;
4956 }
4957 }
François Gaffie11d30102018-11-02 16:09:09 +01004958 sp<DeviceDescriptor> device =
Eric Laurent6a94d692014-05-20 11:18:06 -07004959 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01004960 if (device == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004961 return BAD_VALUE;
4962 }
4963
François Gaffie11d30102018-11-02 16:09:09 +01004964 if (!inputDesc->mProfile->isCompatibleProfile(DeviceVector(device),
Eric Laurent275e8e92014-11-30 15:14:47 -08004965 patch->sinks[0].sample_rate,
4966 NULL, /*updatedSampleRate*/
4967 patch->sinks[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07004968 NULL, /*updatedFormat*/
Eric Laurent275e8e92014-11-30 15:14:47 -08004969 patch->sinks[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07004970 NULL, /*updatedChannelMask*/
Eric Laurent275e8e92014-11-30 15:14:47 -08004971 // FIXME for the parameter type,
4972 // and the NONE
4973 (audio_output_flags_t)
Glenn Kasten6a8ab052014-07-24 14:08:35 -07004974 AUDIO_INPUT_FLAG_NONE)) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004975 return INVALID_OPERATION;
4976 }
4977 // TODO: reconfigure output format and channels here
François Gaffieafd4cea2019-11-18 15:50:22 +01004978 ALOGV("%s setting device %s on output %d", __func__,
François Gaffie11d30102018-11-02 16:09:09 +01004979 device->toString().c_str(), inputDesc->mIoHandle);
4980 setInputDevice(inputDesc->mIoHandle, device, true, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004981 index = mAudioPatches.indexOfKey(*handle);
4982 if (index >= 0) {
4983 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004984 ALOGW("%s setInputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004985 }
4986 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01004987 patchDesc->setUid(uid);
4988 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004989 } else {
François Gaffieafd4cea2019-11-18 15:50:22 +01004990 ALOGW("%s setInputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004991 return INVALID_OPERATION;
4992 }
4993 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
4994 // device to device connection
4995 if (patchDesc != 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07004996 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004997 return BAD_VALUE;
4998 }
4999 }
François Gaffie11d30102018-11-02 16:09:09 +01005000 sp<DeviceDescriptor> srcDevice =
Eric Laurent6a94d692014-05-20 11:18:06 -07005001 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01005002 if (srcDevice == 0) {
Eric Laurent58f8eb72014-09-12 16:19:41 -07005003 return BAD_VALUE;
5004 }
Eric Laurent874c42872014-08-08 15:13:39 -07005005
Eric Laurent6a94d692014-05-20 11:18:06 -07005006 //update source and sink with our own data as the data passed in the patch may
5007 // be incomplete.
François Gaffieafd4cea2019-11-18 15:50:22 +01005008 PatchBuilder patchBuilder;
5009 audio_port_config sourcePortConfig = {};
Dean Wheatley8bee85a2021-02-10 16:02:23 +11005010
5011 // if first sink is to MSD, establish single MSD patch
5012 if (getMsdAudioOutDevices().contains(
5013 mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id))) {
5014 ALOGV("%s patching to MSD", __FUNCTION__);
5015 patchBuilder = buildMsdPatch(false /*msdIsSource*/, srcDevice);
5016 goto installPatch;
5017 }
5018
François Gaffieafd4cea2019-11-18 15:50:22 +01005019 srcDevice->toAudioPortConfig(&sourcePortConfig, &patch->sources[0]);
5020 patchBuilder.addSource(sourcePortConfig);
Eric Laurent6a94d692014-05-20 11:18:06 -07005021
Eric Laurent874c42872014-08-08 15:13:39 -07005022 for (size_t i = 0; i < patch->num_sinks; i++) {
5023 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005024 ALOGV("%s source device but one sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07005025 return INVALID_OPERATION;
5026 }
François Gaffie11d30102018-11-02 16:09:09 +01005027 sp<DeviceDescriptor> sinkDevice =
Eric Laurent874c42872014-08-08 15:13:39 -07005028 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
François Gaffie11d30102018-11-02 16:09:09 +01005029 if (sinkDevice == 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07005030 return BAD_VALUE;
5031 }
François Gaffieafd4cea2019-11-18 15:50:22 +01005032 audio_port_config sinkPortConfig = {};
5033 sinkDevice->toAudioPortConfig(&sinkPortConfig, &patch->sinks[i]);
5034 patchBuilder.addSink(sinkPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07005035
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005036 // Whatever Sw or Hw bridge, we do attach an SwOutput to an Audio Source for
5037 // volume management purpose (tracking activity)
5038 // In case of Hw bridge, it is a Work Around. The mixPort used is the one declared
5039 // in config XML to reach the sink so that is can be declared as available.
5040 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurent78b07302022-10-07 16:20:34 +02005041 sp<SwAudioOutputDescriptor> outputDesc;
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005042 if (!sourceDesc->isInternal()) {
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005043 // take care of dynamic routing for SwOutput selection,
5044 audio_attributes_t attributes = sourceDesc->attributes();
5045 audio_stream_type_t stream = sourceDesc->stream();
5046 audio_attributes_t resultAttr;
5047 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
5048 config.sample_rate = sourceDesc->config().sample_rate;
François Gaffie2a24db42022-04-04 16:45:02 +02005049 audio_channel_mask_t sourceMask = sourceDesc->config().channel_mask;
5050 config.channel_mask =
5051 (audio_channel_mask_get_representation(sourceMask)
5052 == AUDIO_CHANNEL_REPRESENTATION_INDEX) ? sourceMask
5053 : audio_channel_mask_in_to_out(sourceMask);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005054 config.format = sourceDesc->config().format;
5055 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
5056 audio_port_handle_t selectedDeviceId = AUDIO_PORT_HANDLE_NONE;
5057 bool isRequestedDeviceForExclusiveUse = false;
5058 output_type_t outputType;
Eric Laurentb0a7bc92022-04-05 15:06:08 +02005059 bool isSpatialized;
jiabinc658e452022-10-21 20:52:21 +00005060 bool isBitPerfect;
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005061 getOutputForAttrInt(&resultAttr, &output, AUDIO_SESSION_NONE, &attributes,
5062 &stream, sourceDesc->uid(), &config, &flags,
5063 &selectedDeviceId, &isRequestedDeviceForExclusiveUse,
jiabinc658e452022-10-21 20:52:21 +00005064 nullptr, &outputType, &isSpatialized, &isBitPerfect);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005065 if (output == AUDIO_IO_HANDLE_NONE) {
5066 ALOGV("%s no output for device %s",
5067 __FUNCTION__, sinkDevice->toString().c_str());
5068 return INVALID_OPERATION;
5069 }
5070 outputDesc = mOutputs.valueFor(output);
5071 if (outputDesc->isDuplicated()) {
5072 ALOGE("%s output is duplicated", __func__);
5073 return INVALID_OPERATION;
5074 }
François Gaffie7e39df22022-04-26 12:48:49 +02005075 bool closeOutput = outputDesc->mDirectOpenCount != 0;
5076 sourceDesc->setSwOutput(outputDesc, closeOutput);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005077 } else {
5078 // Same for "raw patches" aka created from createAudioPatch API
5079 SortedVector<audio_io_handle_t> outputs =
5080 getOutputsForDevices(DeviceVector(sinkDevice), mOutputs);
5081 // if the sink device is reachable via an opened output stream, request to
5082 // go via this output stream by adding a second source to the patch
5083 // description
5084 output = selectOutput(outputs);
5085 if (output == AUDIO_IO_HANDLE_NONE) {
5086 ALOGE("%s no output available for internal patch sink", __func__);
5087 return INVALID_OPERATION;
5088 }
5089 outputDesc = mOutputs.valueFor(output);
5090 if (outputDesc->isDuplicated()) {
5091 ALOGV("%s output for device %s is duplicated",
5092 __func__, sinkDevice->toString().c_str());
5093 return INVALID_OPERATION;
5094 }
François Gaffie7e39df22022-04-26 12:48:49 +02005095 sourceDesc->setSwOutput(outputDesc, /* closeOutput= */ false);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005096 }
Eric Laurent3bcf8592015-04-03 12:13:24 -07005097 // create a software bridge in PatchPanel if:
Scott Randolphf3172402018-01-23 17:06:53 -08005098 // - source and sink devices are on different HW modules OR
Eric Laurent3bcf8592015-04-03 12:13:24 -07005099 // - audio HAL version is < 3.0
Francois Gaffie99896da2018-04-09 11:05:33 +02005100 // - audio HAL version is >= 3.0 but no route has been declared between devices
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005101 // - called from startAudioSource (aka sourceDesc is not internal) and source device
5102 // does not have a gain controller
François Gaffie11d30102018-11-02 16:09:09 +01005103 if (!srcDevice->hasSameHwModuleAs(sinkDevice) ||
5104 (srcDevice->getModuleVersionMajor() < 3) ||
François Gaffieafd4cea2019-11-18 15:50:22 +01005105 !srcDevice->getModule()->supportsPatch(srcDevice, sinkDevice) ||
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005106 (!sourceDesc->isInternal() &&
François Gaffieafd4cea2019-11-18 15:50:22 +01005107 srcDevice->getAudioPort()->getGains().size() == 0)) {
Eric Laurent3bcf8592015-04-03 12:13:24 -07005108 // support only one sink device for now to simplify output selection logic
Eric Laurent874c42872014-08-08 15:13:39 -07005109 if (patch->num_sinks > 1) {
Eric Laurent83b88082014-06-20 18:31:16 -07005110 return INVALID_OPERATION;
5111 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005112 sourceDesc->setUseSwBridge();
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005113 if (outputDesc != nullptr) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005114 audio_port_config srcMixPortConfig = {};
Ytai Ben-Tsvic9d2a912021-11-22 16:43:09 -08005115 outputDesc->toAudioPortConfig(&srcMixPortConfig, nullptr);
François Gaffieafd4cea2019-11-18 15:50:22 +01005116 // for volume control, we may need a valid stream
Eric Laurent78b07302022-10-07 16:20:34 +02005117 srcMixPortConfig.ext.mix.usecase.stream =
5118 (!sourceDesc->isInternal() || isCallTxAudioSource(sourceDesc)) ?
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005119 mEngine->getStreamTypeForAttributes(sourceDesc->attributes()) :
5120 AUDIO_STREAM_PATCH;
François Gaffieafd4cea2019-11-18 15:50:22 +01005121 patchBuilder.addSource(srcMixPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07005122 }
Eric Laurent83b88082014-06-20 18:31:16 -07005123 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005124 }
5125 // TODO: check from routing capabilities in config file and other conflicting patches
5126
Dean Wheatley8bee85a2021-02-10 16:02:23 +11005127installPatch:
François Gaffieafd4cea2019-11-18 15:50:22 +01005128 status_t status = installPatch(
5129 __func__, index, handle, patchBuilder.patch(), delayMs, uid, &patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07005130 if (status != NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005131 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
Eric Laurent6a94d692014-05-20 11:18:06 -07005132 return INVALID_OPERATION;
5133 }
5134 } else {
5135 return BAD_VALUE;
5136 }
5137 } else {
5138 return BAD_VALUE;
5139 }
5140 return NO_ERROR;
5141}
5142
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005143status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle, uid_t uid)
Eric Laurent6a94d692014-05-20 11:18:06 -07005144{
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005145 ALOGV("%s patch %d", __func__, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005146 ssize_t index = mAudioPatches.indexOfKey(handle);
5147
5148 if (index < 0) {
5149 return BAD_VALUE;
5150 }
5151 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005152 ALOGV("%s() mUidCached %d patchDesc->mUid %d uid %d",
5153 __func__, mUidCached, patchDesc->getUid(), uid);
5154 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005155 return INVALID_OPERATION;
5156 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005157 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
5158 for (size_t i = 0; i < mAudioSources.size(); i++) {
5159 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
5160 if (sourceDesc != nullptr && sourceDesc->getPatchHandle() == handle) {
5161 portId = sourceDesc->portId();
5162 break;
5163 }
5164 }
5165 return portId != AUDIO_PORT_HANDLE_NONE ?
5166 stopAudioSource(portId) : releaseAudioPatchInternal(handle);
François Gaffieafd4cea2019-11-18 15:50:22 +01005167}
Eric Laurent6a94d692014-05-20 11:18:06 -07005168
François Gaffieafd4cea2019-11-18 15:50:22 +01005169status_t AudioPolicyManager::releaseAudioPatchInternal(audio_patch_handle_t handle,
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005170 uint32_t delayMs,
5171 const sp<SourceClientDescriptor>& sourceDesc)
François Gaffieafd4cea2019-11-18 15:50:22 +01005172{
5173 ALOGV("%s patch %d", __func__, handle);
5174 if (mAudioPatches.indexOfKey(handle) < 0) {
5175 ALOGE("%s: no patch found with handle=%d", __func__, handle);
5176 return BAD_VALUE;
5177 }
5178 sp<AudioPatch> patchDesc = mAudioPatches.valueFor(handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005179 struct audio_patch *patch = &patchDesc->mPatch;
François Gaffieafd4cea2019-11-18 15:50:22 +01005180 patchDesc->setUid(mUidCached);
Eric Laurent6a94d692014-05-20 11:18:06 -07005181 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005182 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005183 if (outputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005184 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005185 return BAD_VALUE;
5186 }
5187
François Gaffie11d30102018-11-02 16:09:09 +01005188 setOutputDevices(outputDesc,
5189 getNewOutputDevices(outputDesc, true /*fromCache*/),
5190 true,
5191 0,
5192 NULL);
Eric Laurent6a94d692014-05-20 11:18:06 -07005193 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
5194 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
François Gaffie53615e22015-03-19 09:24:12 +01005195 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005196 if (inputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005197 ALOGV("%s input not found for id %d", __func__, patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005198 return BAD_VALUE;
5199 }
5200 setInputDevice(inputDesc->mIoHandle,
Eric Laurentfb66dd92016-01-28 18:32:03 -08005201 getNewInputDevice(inputDesc),
Eric Laurent6a94d692014-05-20 11:18:06 -07005202 true,
5203 NULL);
5204 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005205 status_t status =
5206 mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
5207 ALOGV("%s patch panel returned %d patchHandle %d",
5208 __func__, status, patchDesc->getAfHandle());
5209 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005210 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005211 mpClientInterface->onAudioPatchListUpdate();
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005212 // SW or HW Bridge
5213 sp<SwAudioOutputDescriptor> outputDesc = nullptr;
5214 audio_patch_handle_t patchHandle = AUDIO_PATCH_HANDLE_NONE;
Francois Gaffie7feb8542020-04-06 17:39:47 +02005215 if (patch->num_sources > 1 && patch->sources[1].type == AUDIO_PORT_TYPE_MIX) {
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005216 outputDesc = mOutputs.getOutputFromId(patch->sources[1].id);
5217 } else if (patch->num_sources == 1 && sourceDesc != nullptr) {
5218 outputDesc = sourceDesc->swOutput().promote();
5219 }
5220 if (outputDesc == nullptr) {
5221 ALOGW("%s no output for id %d", __func__, patch->sources[0].id);
5222 // releaseOutput has already called closeOutput in case of direct output
5223 return NO_ERROR;
5224 }
François Gaffie7e39df22022-04-26 12:48:49 +02005225 patchHandle = outputDesc->getPatchHandle();
5226 // When a Sw bridge is released, the mixer used by this bridge will release its
5227 // patch at AudioFlinger side. Hence, the mixer audio patch must be recreated
5228 // Reuse patch handle to force audio flinger removing initial mixer patch removal
5229 // updating hal patch handle (prevent leaks).
5230 // While using a HwBridge, force reconsidering device only if not reusing an existing
5231 // output and no more activity on output (will force to close).
5232 bool force = sourceDesc->useSwBridge() ||
5233 (sourceDesc->canCloseOutput() && !outputDesc->isActive());
5234 // APM pattern is to have always outputs opened / patch realized for reachable devices.
5235 // Update device may result to NONE (empty), coupled with force, it releases the patch.
5236 // Reconsider device only for cases:
5237 // 1 / Active Output
5238 // 2 / Inactive Output previously hosting HwBridge
5239 // 3 / Inactive Output previously hosting SwBridge that can be closed.
5240 bool updateDevice = outputDesc->isActive() || !sourceDesc->useSwBridge() ||
5241 sourceDesc->canCloseOutput();
5242 setOutputDevices(outputDesc,
5243 updateDevice ? getNewOutputDevices(outputDesc, true /*fromCache*/) :
5244 outputDesc->devices(),
5245 force,
5246 0,
5247 patchHandle == AUDIO_PATCH_HANDLE_NONE ? nullptr : &patchHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005248 } else {
5249 return BAD_VALUE;
5250 }
5251 } else {
5252 return BAD_VALUE;
5253 }
5254 return NO_ERROR;
5255}
5256
5257status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
5258 struct audio_patch *patches,
5259 unsigned int *generation)
5260{
François Gaffie53615e22015-03-19 09:24:12 +01005261 if (generation == NULL) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005262 return BAD_VALUE;
5263 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005264 *generation = curAudioPortGeneration();
François Gaffie53615e22015-03-19 09:24:12 +01005265 return mAudioPatches.listAudioPatches(num_patches, patches);
Eric Laurent6a94d692014-05-20 11:18:06 -07005266}
5267
Eric Laurente1715a42014-05-20 11:30:42 -07005268status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07005269{
Eric Laurente1715a42014-05-20 11:30:42 -07005270 ALOGV("setAudioPortConfig()");
5271
5272 if (config == NULL) {
5273 return BAD_VALUE;
5274 }
5275 ALOGV("setAudioPortConfig() on port handle %d", config->id);
5276 // Only support gain configuration for now
Eric Laurenta121f902014-06-03 13:32:54 -07005277 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
5278 return INVALID_OPERATION;
Eric Laurente1715a42014-05-20 11:30:42 -07005279 }
5280
Eric Laurenta121f902014-06-03 13:32:54 -07005281 sp<AudioPortConfig> audioPortConfig;
Eric Laurente1715a42014-05-20 11:30:42 -07005282 if (config->type == AUDIO_PORT_TYPE_MIX) {
5283 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005284 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07005285 if (outputDesc == NULL) {
5286 return BAD_VALUE;
5287 }
Eric Laurent84c70242014-06-23 08:46:27 -07005288 ALOG_ASSERT(!outputDesc->isDuplicated(),
5289 "setAudioPortConfig() called on duplicated output %d",
5290 outputDesc->mIoHandle);
Eric Laurenta121f902014-06-03 13:32:54 -07005291 audioPortConfig = outputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07005292 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
François Gaffie53615e22015-03-19 09:24:12 +01005293 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07005294 if (inputDesc == NULL) {
5295 return BAD_VALUE;
5296 }
Eric Laurenta121f902014-06-03 13:32:54 -07005297 audioPortConfig = inputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07005298 } else {
5299 return BAD_VALUE;
5300 }
5301 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
5302 sp<DeviceDescriptor> deviceDesc;
5303 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
5304 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
5305 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
5306 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
5307 } else {
5308 return BAD_VALUE;
5309 }
5310 if (deviceDesc == NULL) {
5311 return BAD_VALUE;
5312 }
Eric Laurenta121f902014-06-03 13:32:54 -07005313 audioPortConfig = deviceDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07005314 } else {
5315 return BAD_VALUE;
5316 }
5317
Mikhail Naganov7be71d22018-05-23 16:51:46 -07005318 struct audio_port_config backupConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07005319 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
5320 if (status == NO_ERROR) {
Mikhail Naganov7be71d22018-05-23 16:51:46 -07005321 struct audio_port_config newConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07005322 audioPortConfig->toAudioPortConfig(&newConfig, config);
5323 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
Eric Laurente1715a42014-05-20 11:30:42 -07005324 }
Eric Laurenta121f902014-06-03 13:32:54 -07005325 if (status != NO_ERROR) {
5326 audioPortConfig->applyAudioPortConfig(&backupConfig);
Eric Laurente1715a42014-05-20 11:30:42 -07005327 }
Eric Laurente1715a42014-05-20 11:30:42 -07005328
5329 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07005330}
5331
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005332void AudioPolicyManager::releaseResourcesForUid(uid_t uid)
5333{
Eric Laurentd60560a2015-04-10 11:31:20 -07005334 clearAudioSources(uid);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005335 clearAudioPatches(uid);
5336 clearSessionRoutes(uid);
5337}
5338
Eric Laurent6a94d692014-05-20 11:18:06 -07005339void AudioPolicyManager::clearAudioPatches(uid_t uid)
5340{
Eric Laurent0add0fd2014-12-04 18:58:14 -08005341 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005342 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
François Gaffieafd4cea2019-11-18 15:50:22 +01005343 if (patchDesc->getUid() == uid) {
Eric Laurent0add0fd2014-12-04 18:58:14 -08005344 releaseAudioPatch(mAudioPatches.keyAt(i), uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07005345 }
5346 }
5347}
5348
François Gaffiec005e562018-11-06 15:04:49 +01005349void AudioPolicyManager::checkStrategyRoute(product_strategy_t ps, audio_io_handle_t ouptutToSkip)
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005350{
François Gaffiec005e562018-11-06 15:04:49 +01005351 // Take the first attributes following the product strategy as it is used to retrieve the routed
5352 // device. All attributes wihin a strategy follows the same "routing strategy"
5353 auto attributes = mEngine->getAllAttributesForProductStrategy(ps).front();
5354 DeviceVector devices = mEngine->getOutputDevicesForAttributes(attributes, nullptr, false);
François Gaffie11d30102018-11-02 16:09:09 +01005355 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
jiabin3ff8d7d2022-12-13 06:27:44 +00005356 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005357 for (size_t j = 0; j < mOutputs.size(); j++) {
5358 if (mOutputs.keyAt(j) == ouptutToSkip) {
5359 continue;
5360 }
5361 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(j);
François Gaffiec005e562018-11-06 15:04:49 +01005362 if (!outputDesc->isStrategyActive(ps)) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005363 continue;
5364 }
5365 // If the default device for this strategy is on another output mix,
5366 // invalidate all tracks in this strategy to force re connection.
5367 // Otherwise select new device on the output mix.
5368 if (outputs.indexOf(mOutputs.keyAt(j)) < 0) {
jiabinc44b3462022-12-08 12:52:31 -08005369 invalidateStreams(mEngine->getStreamTypesForProductStrategy(ps));
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005370 } else {
jiabin3ff8d7d2022-12-13 06:27:44 +00005371 DeviceVector newDevices = getNewOutputDevices(outputDesc, false /*fromCache*/);
5372 if (outputDesc->mUsePreferredMixerAttributes && outputDesc->devices() != newDevices) {
5373 // If the device is using preferred mixer attributes, the output need to reopen
5374 // with default configuration when the new selected devices are different from
5375 // current routing devices.
5376 outputsToReopen.emplace(mOutputs.keyAt(j), newDevices);
5377 continue;
5378 }
5379 setOutputDevices(outputDesc, newDevices, false);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005380 }
5381 }
jiabin3ff8d7d2022-12-13 06:27:44 +00005382 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005383}
5384
5385void AudioPolicyManager::clearSessionRoutes(uid_t uid)
5386{
5387 // remove output routes associated with this uid
François Gaffiec005e562018-11-06 15:04:49 +01005388 std::vector<product_strategy_t> affectedStrategies;
Eric Laurent97ac8712018-07-27 18:59:02 -07005389 for (size_t i = 0; i < mOutputs.size(); i++) {
5390 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07005391 for (const auto& client : outputDesc->getClientIterable()) {
5392 if (client->hasPreferredDevice() && client->uid() == uid) {
5393 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
François Gaffiec005e562018-11-06 15:04:49 +01005394 auto clientStrategy = client->strategy();
5395 if (std::find(begin(affectedStrategies), end(affectedStrategies), clientStrategy) !=
5396 end(affectedStrategies)) {
5397 continue;
5398 }
5399 affectedStrategies.push_back(client->strategy());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005400 }
5401 }
5402 }
5403 // reroute outputs if necessary
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005404 for (const auto& strategy : affectedStrategies) {
5405 checkStrategyRoute(strategy, AUDIO_IO_HANDLE_NONE);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005406 }
5407
5408 // remove input routes associated with this uid
5409 SortedVector<audio_source_t> affectedSources;
Eric Laurent97ac8712018-07-27 18:59:02 -07005410 for (size_t i = 0; i < mInputs.size(); i++) {
5411 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07005412 for (const auto& client : inputDesc->getClientIterable()) {
5413 if (client->hasPreferredDevice() && client->uid() == uid) {
5414 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
5415 affectedSources.add(client->source());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005416 }
5417 }
5418 }
5419 // reroute inputs if necessary
5420 SortedVector<audio_io_handle_t> inputsToClose;
5421 for (size_t i = 0; i < mInputs.size(); i++) {
5422 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Eric Laurent4eb58f12018-12-07 16:41:02 -08005423 if (affectedSources.indexOf(inputDesc->source()) >= 0) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005424 inputsToClose.add(inputDesc->mIoHandle);
5425 }
5426 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005427 for (const auto& input : inputsToClose) {
5428 closeInput(input);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005429 }
5430}
5431
Eric Laurentd60560a2015-04-10 11:31:20 -07005432void AudioPolicyManager::clearAudioSources(uid_t uid)
5433{
5434 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005435 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
5436 if (sourceDesc->uid() == uid) {
Eric Laurentd60560a2015-04-10 11:31:20 -07005437 stopAudioSource(mAudioSources.keyAt(i));
5438 }
5439 }
5440}
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005441
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005442status_t AudioPolicyManager::acquireSoundTriggerSession(audio_session_t *session,
5443 audio_io_handle_t *ioHandle,
5444 audio_devices_t *device)
5445{
Glenn Kastenf0c6d7d2016-02-26 10:44:04 -08005446 *session = (audio_session_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
5447 *ioHandle = (audio_io_handle_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
Francois Gaffie716e1432019-01-14 16:58:59 +01005448 audio_attributes_t attr = { .source = AUDIO_SOURCE_HOTWORD };
Eric Laurentcedd5b52023-03-22 00:03:31 +00005449 sp<DeviceDescriptor> deviceDesc = mEngine->getInputDeviceForAttributes(attr);
5450 if (deviceDesc == nullptr) {
5451 return INVALID_OPERATION;
5452 }
5453 *device = deviceDesc->type();
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005454
François Gaffiedf372692015-03-19 10:43:27 +01005455 return mSoundTriggerSessions.acquireSession(*session, *ioHandle);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005456}
5457
Eric Laurentd60560a2015-04-10 11:31:20 -07005458status_t AudioPolicyManager::startAudioSource(const struct audio_port_config *source,
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005459 const audio_attributes_t *attributes,
5460 audio_port_handle_t *portId,
5461 uid_t uid)
Eric Laurent554a2772015-04-10 11:29:24 -07005462{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005463 ALOGV("%s", __FUNCTION__);
5464 *portId = AUDIO_PORT_HANDLE_NONE;
5465
5466 if (source == NULL || attributes == NULL || portId == NULL) {
5467 ALOGW("%s invalid argument: source %p attributes %p handle %p",
5468 __FUNCTION__, source, attributes, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005469 return BAD_VALUE;
5470 }
5471
Eric Laurentd60560a2015-04-10 11:31:20 -07005472 if (source->role != AUDIO_PORT_ROLE_SOURCE ||
5473 source->type != AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005474 ALOGW("%s INVALID_OPERATION source->role %d source->type %d",
5475 __FUNCTION__, source->role, source->type);
Eric Laurentd60560a2015-04-10 11:31:20 -07005476 return INVALID_OPERATION;
5477 }
5478
François Gaffie11d30102018-11-02 16:09:09 +01005479 sp<DeviceDescriptor> srcDevice =
Eric Laurentd60560a2015-04-10 11:31:20 -07005480 mAvailableInputDevices.getDevice(source->ext.device.type,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005481 String8(source->ext.device.address),
5482 AUDIO_FORMAT_DEFAULT);
François Gaffie11d30102018-11-02 16:09:09 +01005483 if (srcDevice == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005484 ALOGW("%s source->ext.device.type %08x not found", __FUNCTION__, source->ext.device.type);
Eric Laurentd60560a2015-04-10 11:31:20 -07005485 return BAD_VALUE;
5486 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005487
jiabin4ef93452019-09-10 14:29:54 -07005488 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurentd60560a2015-04-10 11:31:20 -07005489
François Gaffieaaac0fd2018-11-22 17:56:39 +01005490 sp<SourceClientDescriptor> sourceDesc =
François Gaffieafd4cea2019-11-18 15:50:22 +01005491 new SourceClientDescriptor(*portId, uid, *attributes, *source, srcDevice,
François Gaffieaaac0fd2018-11-22 17:56:39 +01005492 mEngine->getStreamTypeForAttributes(*attributes),
5493 mEngine->getProductStrategyForAttributes(*attributes),
5494 toVolumeSource(*attributes));
Eric Laurentd60560a2015-04-10 11:31:20 -07005495
5496 status_t status = connectAudioSource(sourceDesc);
5497 if (status == NO_ERROR) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005498 mAudioSources.add(*portId, sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07005499 }
5500 return status;
5501}
5502
Francois Gaffie601801d2021-06-22 13:27:39 +02005503sp<SourceClientDescriptor> AudioPolicyManager::startAudioSourceInternal(
5504 const struct audio_port_config *source, const audio_attributes_t *attributes, uid_t uid)
5505{
5506 ALOGV("%s", __FUNCTION__);
5507 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
5508
5509 status_t status = startAudioSource(source, attributes, &portId, uid);
5510 ALOGE_IF(status != OK, "%s: failed to start audio source (%d)", __func__, status);
5511 return mAudioSources.valueFor(portId);
5512}
5513
5514
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005515status_t AudioPolicyManager::connectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07005516{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005517 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->portId());
Eric Laurentd60560a2015-04-10 11:31:20 -07005518
5519 // make sure we only have one patch per source.
5520 disconnectAudioSource(sourceDesc);
5521
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005522 audio_attributes_t attributes = sourceDesc->attributes();
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005523 // May the device (dynamic) have been disconnected/reconnected, id has changed.
5524 sp<DeviceDescriptor> srcDevice = mAvailableInputDevices.getDevice(
5525 sourceDesc->srcDevice()->type(),
5526 String8(sourceDesc->srcDevice()->address().c_str()),
5527 AUDIO_FORMAT_DEFAULT);
François Gaffiec005e562018-11-06 15:04:49 +01005528 DeviceVector sinkDevices =
Francois Gaffieff1eb522020-05-06 18:37:04 +02005529 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false /*fromCache*/);
François Gaffiec005e562018-11-06 15:04:49 +01005530 ALOG_ASSERT(!sinkDevices.isEmpty(), "connectAudioSource(): no device found for attributes");
François Gaffie11d30102018-11-02 16:09:09 +01005531 sp<DeviceDescriptor> sinkDevice = sinkDevices.itemAt(0);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005532 if (!mAvailableOutputDevices.contains(sinkDevice)) {
5533 ALOGE("%s Device %s not available", __func__, sinkDevice->toString().c_str());
5534 return INVALID_OPERATION;
5535 }
François Gaffieafd4cea2019-11-18 15:50:22 +01005536 PatchBuilder patchBuilder;
5537 patchBuilder.addSink(sinkDevice).addSource(srcDevice);
5538 audio_patch_handle_t handle = AUDIO_PATCH_HANDLE_NONE;
François Gaffieafd4cea2019-11-18 15:50:22 +01005539
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005540 return connectAudioSourceToSink(
5541 sourceDesc, sinkDevice, patchBuilder.patch(), handle, mUidCached, 0 /*delayMs*/);
Eric Laurent554a2772015-04-10 11:29:24 -07005542}
5543
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005544status_t AudioPolicyManager::stopAudioSource(audio_port_handle_t portId)
Eric Laurent554a2772015-04-10 11:29:24 -07005545{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005546 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueFor(portId);
5547 ALOGV("%s port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005548 if (sourceDesc == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005549 ALOGW("%s unknown source for port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005550 return BAD_VALUE;
5551 }
5552 status_t status = disconnectAudioSource(sourceDesc);
5553
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005554 mAudioSources.removeItem(portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005555 return status;
5556}
5557
Andy Hung2ddee192015-12-18 17:34:44 -08005558status_t AudioPolicyManager::setMasterMono(bool mono)
5559{
5560 if (mMasterMono == mono) {
5561 return NO_ERROR;
5562 }
5563 mMasterMono = mono;
5564 // if enabling mono we close all offloaded devices, which will invalidate the
5565 // corresponding AudioTrack. The AudioTrack client/MediaPlayer is responsible
5566 // for recreating the new AudioTrack as non-offloaded PCM.
5567 //
5568 // If disabling mono, we leave all tracks as is: we don't know which clients
5569 // and tracks are able to be recreated as offloaded. The next "song" should
5570 // play back offloaded.
5571 if (mMasterMono) {
5572 Vector<audio_io_handle_t> offloaded;
5573 for (size_t i = 0; i < mOutputs.size(); ++i) {
5574 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
5575 if (desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
5576 offloaded.push(desc->mIoHandle);
5577 }
5578 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005579 for (const auto& handle : offloaded) {
5580 closeOutput(handle);
Andy Hung2ddee192015-12-18 17:34:44 -08005581 }
5582 }
5583 // update master mono for all remaining outputs
5584 for (size_t i = 0; i < mOutputs.size(); ++i) {
5585 updateMono(mOutputs.keyAt(i));
5586 }
5587 return NO_ERROR;
5588}
5589
5590status_t AudioPolicyManager::getMasterMono(bool *mono)
5591{
5592 *mono = mMasterMono;
5593 return NO_ERROR;
5594}
5595
Eric Laurentac9cef52017-06-09 15:46:26 -07005596float AudioPolicyManager::getStreamVolumeDB(
5597 audio_stream_type_t stream, int index, audio_devices_t device)
5598{
jiabin9a3361e2019-10-01 09:38:30 -07005599 return computeVolume(getVolumeCurves(stream), toVolumeSource(stream), index, {device});
Eric Laurentac9cef52017-06-09 15:46:26 -07005600}
5601
jiabin81772902018-04-02 17:52:27 -07005602status_t AudioPolicyManager::getSurroundFormats(unsigned int *numSurroundFormats,
5603 audio_format_t *surroundFormats,
Kriti Dang6537def2021-03-02 13:46:59 +01005604 bool *surroundFormatsEnabled)
jiabin81772902018-04-02 17:52:27 -07005605{
Kriti Dang6537def2021-03-02 13:46:59 +01005606 if (numSurroundFormats == nullptr || (*numSurroundFormats != 0 &&
5607 (surroundFormats == nullptr || surroundFormatsEnabled == nullptr))) {
jiabin81772902018-04-02 17:52:27 -07005608 return BAD_VALUE;
5609 }
Kriti Dang6537def2021-03-02 13:46:59 +01005610 ALOGV("%s() numSurroundFormats %d surroundFormats %p surroundFormatsEnabled %p",
5611 __func__, *numSurroundFormats, surroundFormats, surroundFormatsEnabled);
jiabin81772902018-04-02 17:52:27 -07005612
5613 size_t formatsWritten = 0;
5614 size_t formatsMax = *numSurroundFormats;
Kriti Dangef6be8f2020-11-05 11:58:19 +01005615
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005616 *numSurroundFormats = mConfig->getSurroundFormats().size();
Mikhail Naganov100f0122018-11-29 11:22:16 -08005617 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
5618 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005619 for (const auto& format: mConfig->getSurroundFormats()) {
jiabin81772902018-04-02 17:52:27 -07005620 if (formatsWritten < formatsMax) {
Kriti Dang6537def2021-03-02 13:46:59 +01005621 surroundFormats[formatsWritten] = format.first;
Mikhail Naganov100f0122018-11-29 11:22:16 -08005622 bool formatEnabled = true;
5623 switch (forceUse) {
5624 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL:
Kriti Dang6537def2021-03-02 13:46:59 +01005625 formatEnabled = mManualSurroundFormats.count(format.first) != 0;
Mikhail Naganov100f0122018-11-29 11:22:16 -08005626 break;
5627 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER:
5628 formatEnabled = false;
5629 break;
5630 default: // AUTO or ALWAYS => true
5631 break;
jiabin81772902018-04-02 17:52:27 -07005632 }
5633 surroundFormatsEnabled[formatsWritten++] = formatEnabled;
5634 }
jiabin81772902018-04-02 17:52:27 -07005635 }
5636 return NO_ERROR;
5637}
5638
Kriti Dang6537def2021-03-02 13:46:59 +01005639status_t AudioPolicyManager::getReportedSurroundFormats(unsigned int *numSurroundFormats,
5640 audio_format_t *surroundFormats) {
5641 if (numSurroundFormats == nullptr || (*numSurroundFormats != 0 && surroundFormats == nullptr)) {
5642 return BAD_VALUE;
5643 }
5644 ALOGV("%s() numSurroundFormats %d surroundFormats %p",
5645 __func__, *numSurroundFormats, surroundFormats);
5646
5647 size_t formatsWritten = 0;
5648 size_t formatsMax = *numSurroundFormats;
5649 std::unordered_set<audio_format_t> formats; // Uses primary surround formats only
5650
5651 // Return formats from all device profiles that have already been resolved by
5652 // checkOutputsForDevice().
5653 for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
5654 sp<DeviceDescriptor> device = mAvailableOutputDevices[i];
5655 audio_devices_t deviceType = device->type();
5656 // Enabling/disabling formats are applied to only HDMI devices. So, this function
5657 // returns formats reported by HDMI devices.
5658 if (deviceType != AUDIO_DEVICE_OUT_HDMI) {
5659 continue;
5660 }
5661 // Formats reported by sink devices
5662 std::unordered_set<audio_format_t> formatset;
5663 if (auto it = mReportedFormatsMap.find(device); it != mReportedFormatsMap.end()) {
5664 formatset.insert(it->second.begin(), it->second.end());
5665 }
5666
5667 // Formats hard-coded in the in policy configuration file (if any).
5668 FormatVector encodedFormats = device->encodedFormats();
5669 formatset.insert(encodedFormats.begin(), encodedFormats.end());
5670 // Filter the formats which are supported by the vendor hardware.
5671 for (auto it = formatset.begin(); it != formatset.end(); ++it) {
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005672 if (mConfig->getSurroundFormats().count(*it) != 0) {
Kriti Dang6537def2021-03-02 13:46:59 +01005673 formats.insert(*it);
5674 } else {
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005675 for (const auto& pair : mConfig->getSurroundFormats()) {
Kriti Dang6537def2021-03-02 13:46:59 +01005676 if (pair.second.count(*it) != 0) {
5677 formats.insert(pair.first);
5678 break;
5679 }
5680 }
5681 }
5682 }
5683 }
5684 *numSurroundFormats = formats.size();
5685 for (const auto& format: formats) {
5686 if (formatsWritten < formatsMax) {
5687 surroundFormats[formatsWritten++] = format;
5688 }
5689 }
5690 return NO_ERROR;
5691}
5692
jiabin81772902018-04-02 17:52:27 -07005693status_t AudioPolicyManager::setSurroundFormatEnabled(audio_format_t audioFormat, bool enabled)
5694{
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005695 ALOGV("%s() format 0x%X enabled %d", __func__, audioFormat, enabled);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005696 const auto& formatIter = mConfig->getSurroundFormats().find(audioFormat);
5697 if (formatIter == mConfig->getSurroundFormats().end()) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005698 ALOGW("%s() format 0x%X is not a known surround format", __func__, audioFormat);
jiabin81772902018-04-02 17:52:27 -07005699 return BAD_VALUE;
5700 }
5701
Mikhail Naganov100f0122018-11-29 11:22:16 -08005702 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND) !=
5703 AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005704 ALOGW("%s() not in manual mode for surround sound format selection", __func__);
jiabin81772902018-04-02 17:52:27 -07005705 return INVALID_OPERATION;
5706 }
5707
Mikhail Naganov100f0122018-11-29 11:22:16 -08005708 if ((mManualSurroundFormats.count(audioFormat) != 0) == enabled) {
jiabin81772902018-04-02 17:52:27 -07005709 return NO_ERROR;
5710 }
5711
Mikhail Naganov100f0122018-11-29 11:22:16 -08005712 std::unordered_set<audio_format_t> surroundFormatsBackup(mManualSurroundFormats);
jiabin81772902018-04-02 17:52:27 -07005713 if (enabled) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005714 mManualSurroundFormats.insert(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07005715 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005716 mManualSurroundFormats.insert(subFormat);
jiabin81772902018-04-02 17:52:27 -07005717 }
5718 } else {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005719 mManualSurroundFormats.erase(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07005720 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005721 mManualSurroundFormats.erase(subFormat);
jiabin81772902018-04-02 17:52:27 -07005722 }
5723 }
5724
5725 sp<SwAudioOutputDescriptor> outputDesc;
5726 bool profileUpdated = false;
jiabin9a3361e2019-10-01 09:38:30 -07005727 DeviceVector hdmiOutputDevices = mAvailableOutputDevices.getDevicesFromType(
5728 AUDIO_DEVICE_OUT_HDMI);
jiabin81772902018-04-02 17:52:27 -07005729 for (size_t i = 0; i < hdmiOutputDevices.size(); i++) {
5730 // Simulate reconnection to update enabled surround sound formats.
jiabince9f20e2019-09-12 16:29:15 -07005731 String8 address = String8(hdmiOutputDevices[i]->address().c_str());
jiabin5740f082019-08-19 15:08:30 -07005732 std::string name = hdmiOutputDevices[i]->getName();
jiabin81772902018-04-02 17:52:27 -07005733 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
5734 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
5735 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005736 name.c_str(),
5737 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005738 if (status != NO_ERROR) {
5739 continue;
5740 }
5741 status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
5742 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
5743 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005744 name.c_str(),
5745 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005746 profileUpdated |= (status == NO_ERROR);
5747 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08005748 // FIXME: Why doing this for input HDMI devices if we don't augment their reported formats?
jiabin9a3361e2019-10-01 09:38:30 -07005749 DeviceVector hdmiInputDevices = mAvailableInputDevices.getDevicesFromType(
jiabin81772902018-04-02 17:52:27 -07005750 AUDIO_DEVICE_IN_HDMI);
5751 for (size_t i = 0; i < hdmiInputDevices.size(); i++) {
5752 // Simulate reconnection to update enabled surround sound formats.
jiabince9f20e2019-09-12 16:29:15 -07005753 String8 address = String8(hdmiInputDevices[i]->address().c_str());
jiabin5740f082019-08-19 15:08:30 -07005754 std::string name = hdmiInputDevices[i]->getName();
jiabin81772902018-04-02 17:52:27 -07005755 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
5756 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
5757 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005758 name.c_str(),
5759 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005760 if (status != NO_ERROR) {
5761 continue;
5762 }
5763 status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
5764 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
5765 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005766 name.c_str(),
5767 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005768 profileUpdated |= (status == NO_ERROR);
5769 }
5770
jiabin81772902018-04-02 17:52:27 -07005771 if (!profileUpdated) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005772 ALOGW("%s() no audio profiles updated, undoing surround formats change", __func__);
Mikhail Naganov100f0122018-11-29 11:22:16 -08005773 mManualSurroundFormats = std::move(surroundFormatsBackup);
jiabin81772902018-04-02 17:52:27 -07005774 }
5775
5776 return profileUpdated ? NO_ERROR : INVALID_OPERATION;
5777}
5778
Eric Laurent5ada82e2019-08-29 17:53:54 -07005779void AudioPolicyManager::setAppState(audio_port_handle_t portId, app_state_t state)
Svet Ganovf4ddfef2018-01-16 07:37:58 -08005780{
Eric Laurent5ada82e2019-08-29 17:53:54 -07005781 ALOGV("%s(portId:%d, state:%d)", __func__, portId, state);
Eric Laurenta9f86652018-11-28 17:23:11 -08005782 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent5ada82e2019-08-29 17:53:54 -07005783 mInputs.valueAt(i)->setAppState(portId, state);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08005784 }
5785}
5786
jiabin6012f912018-11-02 17:06:30 -07005787bool AudioPolicyManager::isHapticPlaybackSupported()
5788{
5789 for (const auto& hwModule : mHwModules) {
5790 const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
5791 for (const auto &outProfile : outputProfiles) {
5792 struct audio_port audioPort;
5793 outProfile->toAudioPort(&audioPort);
5794 for (size_t i = 0; i < audioPort.num_channel_masks; i++) {
5795 if (audioPort.channel_masks[i] & AUDIO_CHANNEL_HAPTIC_ALL) {
5796 return true;
5797 }
5798 }
5799 }
5800 }
5801 return false;
5802}
5803
Carter Hsu325a8eb2022-01-19 19:56:51 +08005804bool AudioPolicyManager::isUltrasoundSupported()
5805{
5806 bool hasUltrasoundOutput = false;
5807 bool hasUltrasoundInput = false;
5808 for (const auto& hwModule : mHwModules) {
5809 const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
5810 if (!hasUltrasoundOutput) {
5811 for (const auto &outProfile : outputProfiles) {
5812 if (outProfile->getFlags() & AUDIO_OUTPUT_FLAG_ULTRASOUND) {
5813 hasUltrasoundOutput = true;
5814 break;
5815 }
5816 }
5817 }
5818
5819 const InputProfileCollection &inputProfiles = hwModule->getInputProfiles();
5820 if (!hasUltrasoundInput) {
5821 for (const auto &inputProfile : inputProfiles) {
5822 if (inputProfile->getFlags() & AUDIO_INPUT_FLAG_ULTRASOUND) {
5823 hasUltrasoundInput = true;
5824 break;
5825 }
5826 }
5827 }
5828
5829 if (hasUltrasoundOutput && hasUltrasoundInput)
5830 return true;
5831 }
5832 return false;
5833}
5834
Atneya Nair698f5ef2022-12-15 16:15:09 -08005835bool AudioPolicyManager::isHotwordStreamSupported(bool lookbackAudio)
5836{
5837 const auto mask = AUDIO_INPUT_FLAG_HOTWORD_TAP |
5838 (lookbackAudio ? AUDIO_INPUT_FLAG_HW_LOOKBACK : 0);
5839 for (const auto& hwModule : mHwModules) {
5840 const InputProfileCollection &inputProfiles = hwModule->getInputProfiles();
5841 for (const auto &inputProfile : inputProfiles) {
5842 if ((inputProfile->getFlags() & mask) == mask) {
5843 return true;
5844 }
5845 }
5846 }
5847 return false;
5848}
5849
Eric Laurent8340e672019-11-06 11:01:08 -08005850bool AudioPolicyManager::isCallScreenModeSupported()
5851{
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005852 return mConfig->isCallScreenModeSupported();
Eric Laurent8340e672019-11-06 11:01:08 -08005853}
5854
5855
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005856status_t AudioPolicyManager::disconnectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07005857{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005858 ALOGV("%s port Id %d", __FUNCTION__, sourceDesc->portId());
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005859 if (!sourceDesc->isConnected()) {
5860 ALOGV("%s port Id %d already disconnected", __FUNCTION__, sourceDesc->portId());
5861 return NO_ERROR;
5862 }
François Gaffieafd4cea2019-11-18 15:50:22 +01005863 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
5864 if (swOutput != 0) {
5865 status_t status = stopSource(swOutput, sourceDesc);
Eric Laurent733ce942017-12-07 12:18:25 -08005866 if (status == NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005867 swOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08005868 }
jiabinbce0c1d2020-10-05 11:20:18 -07005869 if (releaseOutput(sourceDesc->portId())) {
5870 // The output descriptor is reopened to query dynamic profiles. In that case, there is
5871 // no need to release audio patch here but just return NO_ERROR.
5872 return NO_ERROR;
5873 }
Eric Laurentd60560a2015-04-10 11:31:20 -07005874 } else {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005875 sp<HwAudioOutputDescriptor> hwOutputDesc = sourceDesc->hwOutput().promote();
Eric Laurentd60560a2015-04-10 11:31:20 -07005876 if (hwOutputDesc != 0) {
Eric Laurentd60560a2015-04-10 11:31:20 -07005877 // close Hwoutput and remove from mHwOutputs
5878 } else {
5879 ALOGW("%s source has neither SW nor HW output", __FUNCTION__);
5880 }
5881 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005882 status_t status = releaseAudioPatchInternal(sourceDesc->getPatchHandle(), 0, sourceDesc);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005883 sourceDesc->disconnect();
5884 return status;
Eric Laurentd60560a2015-04-10 11:31:20 -07005885}
5886
François Gaffiec005e562018-11-06 15:04:49 +01005887sp<SourceClientDescriptor> AudioPolicyManager::getSourceForAttributesOnOutput(
5888 audio_io_handle_t output, const audio_attributes_t &attr)
Eric Laurentd60560a2015-04-10 11:31:20 -07005889{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005890 sp<SourceClientDescriptor> source;
Eric Laurentd60560a2015-04-10 11:31:20 -07005891 for (size_t i = 0; i < mAudioSources.size(); i++) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005892 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005893 sp<SwAudioOutputDescriptor> outputDesc = sourceDesc->swOutput().promote();
François Gaffiec005e562018-11-06 15:04:49 +01005894 if (followsSameRouting(attr, sourceDesc->attributes()) &&
5895 outputDesc != 0 && outputDesc->mIoHandle == output) {
Eric Laurentd60560a2015-04-10 11:31:20 -07005896 source = sourceDesc;
5897 break;
5898 }
5899 }
5900 return source;
Eric Laurent554a2772015-04-10 11:29:24 -07005901}
5902
Eric Laurentb4f42a92022-01-17 17:37:31 +01005903bool AudioPolicyManager::canBeSpatializedInt(const audio_attributes_t *attr,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005904 const audio_config_t *config,
Andy Hung9dd1a5b2022-05-10 15:39:39 -07005905 const AudioDeviceTypeAddrVector &devices) const
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005906{
5907 // The caller can have the audio attributes criteria ignored by either passing a null ptr or
5908 // the AUDIO_ATTRIBUTES_INITIALIZER value.
Eric Laurentfa0f6742021-08-17 18:39:44 +02005909 // If attributes are specified, current policy is to only allow spatialization for media
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005910 // and game usages.
Eric Laurent39095982021-08-24 18:29:27 +02005911 if (attr != nullptr && *attr != AUDIO_ATTRIBUTES_INITIALIZER) {
5912 if (attr->usage != AUDIO_USAGE_MEDIA && attr->usage != AUDIO_USAGE_GAME) {
5913 return false;
5914 }
5915 if ((attr->flags & (AUDIO_FLAG_CONTENT_SPATIALIZED | AUDIO_FLAG_NEVER_SPATIALIZE)) != 0) {
5916 return false;
5917 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005918 }
5919
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005920 sp<IOProfile> profile =
Eric Laurent39095982021-08-24 18:29:27 +02005921 getSpatializerOutputProfile(config, devices);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005922 if (profile == nullptr) {
5923 return false;
5924 }
5925
5926 // The caller can have the audio config criteria ignored by either passing a null ptr or
5927 // the AUDIO_CONFIG_INITIALIZER value.
Eric Laurentfa0f6742021-08-17 18:39:44 +02005928 // If an audio config is specified, current policy is to only allow spatialization for
Eric Laurent39095982021-08-24 18:29:27 +02005929 // some positional channel masks.
Eric Laurent39095982021-08-24 18:29:27 +02005930
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005931 if (config != nullptr && *config != AUDIO_CONFIG_INITIALIZER) {
Andy Hung9dd1a5b2022-05-10 15:39:39 -07005932 if (!audio_is_channel_mask_spatialized(config->channel_mask)) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005933 return false;
5934 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005935 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005936 return true;
5937}
5938
5939void AudioPolicyManager::checkVirtualizerClientRoutes() {
5940 std::set<audio_stream_type_t> streamsToInvalidate;
5941 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent39095982021-08-24 18:29:27 +02005942 const sp<SwAudioOutputDescriptor>& desc = mOutputs[i];
5943 for (const sp<TrackClientDescriptor>& client : desc->getClientIterable()) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005944 audio_attributes_t attr = client->attributes();
5945 DeviceVector devices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false);
5946 AudioDeviceTypeAddrVector devicesTypeAddress = devices.toTypeAddrVector();
5947 audio_config_base_t clientConfig = client->config();
5948 audio_config_t config = audio_config_initializer(&clientConfig);
Eric Laurent39095982021-08-24 18:29:27 +02005949 if (desc != mSpatializerOutput
Andy Hung9dd1a5b2022-05-10 15:39:39 -07005950 && canBeSpatializedInt(&attr, &config, devicesTypeAddress)) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005951 streamsToInvalidate.insert(client->stream());
5952 }
5953 }
5954 }
5955
jiabinc44b3462022-12-08 12:52:31 -08005956 invalidateStreams(StreamTypeVector(streamsToInvalidate.begin(), streamsToInvalidate.end()));
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005957}
5958
Eric Laurente191d1b2022-04-15 11:59:25 +02005959
5960bool AudioPolicyManager::isOutputOnlyAvailableRouteToSomeDevice(
5961 const sp<SwAudioOutputDescriptor>& outputDesc) {
5962 if (outputDesc->isDuplicated()) {
5963 return false;
5964 }
5965 DeviceVector devices = outputDesc->supportedDevices();
5966 for (size_t i = 0; i < mOutputs.size(); i++) {
5967 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
5968 if (desc == outputDesc || desc->isDuplicated()) {
5969 continue;
5970 }
5971 DeviceVector sharedDevices = desc->filterSupportedDevices(devices);
5972 if (!sharedDevices.isEmpty()
5973 && (desc->devicesSupportEncodedFormats(sharedDevices.types())
5974 == outputDesc->devicesSupportEncodedFormats(sharedDevices.types()))) {
5975 return false;
5976 }
5977 }
5978 return true;
5979}
5980
5981
Eric Laurentfa0f6742021-08-17 18:39:44 +02005982status_t AudioPolicyManager::getSpatializerOutput(const audio_config_base_t *mixerConfig,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005983 const audio_attributes_t *attr,
5984 audio_io_handle_t *output) {
5985 *output = AUDIO_IO_HANDLE_NONE;
5986
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005987 DeviceVector devices = mEngine->getOutputDevicesForAttributes(*attr, nullptr, false);
5988 AudioDeviceTypeAddrVector devicesTypeAddress = devices.toTypeAddrVector();
5989 audio_config_t *configPtr = nullptr;
5990 audio_config_t config;
5991 if (mixerConfig != nullptr) {
5992 config = audio_config_initializer(mixerConfig);
5993 configPtr = &config;
5994 }
Andy Hung9dd1a5b2022-05-10 15:39:39 -07005995 if (!canBeSpatializedInt(attr, configPtr, devicesTypeAddress)) {
Eric Laurente191d1b2022-04-15 11:59:25 +02005996 ALOGV("%s provided attributes or mixer config cannot be spatialized", __func__);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005997 return BAD_VALUE;
5998 }
5999
6000 sp<IOProfile> profile =
Eric Laurent39095982021-08-24 18:29:27 +02006001 getSpatializerOutputProfile(configPtr, devicesTypeAddress);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006002 if (profile == nullptr) {
Eric Laurente191d1b2022-04-15 11:59:25 +02006003 ALOGV("%s no suitable output profile for provided attributes or mixer config", __func__);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006004 return BAD_VALUE;
6005 }
6006
Eric Laurente191d1b2022-04-15 11:59:25 +02006007 std::vector<sp<SwAudioOutputDescriptor>> spatializerOutputs;
Eric Laurent39095982021-08-24 18:29:27 +02006008 for (size_t i = 0; i < mOutputs.size(); i++) {
6009 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente191d1b2022-04-15 11:59:25 +02006010 if (!desc->isDuplicated()
6011 && (desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0) {
6012 spatializerOutputs.push_back(desc);
6013 ALOGV("%s adding opened spatializer Output %d", __func__, desc->mIoHandle);
Eric Laurent39095982021-08-24 18:29:27 +02006014 }
6015 }
Eric Laurente191d1b2022-04-15 11:59:25 +02006016 mSpatializerOutput.clear();
6017 bool outputsChanged = false;
6018 for (const auto& desc : spatializerOutputs) {
6019 if (desc->mProfile == profile
6020 && (configPtr == nullptr
6021 || configPtr->channel_mask == desc->mMixerChannelMask)) {
6022 mSpatializerOutput = desc;
6023 ALOGV("%s reusing current spatializer output %d", __func__, desc->mIoHandle);
6024 } else {
6025 ALOGV("%s closing spatializerOutput output %d to match channel mask %#x"
6026 " and devices %s", __func__, desc->mIoHandle,
6027 configPtr != nullptr ? configPtr->channel_mask : 0,
6028 devices.toString().c_str());
6029 closeOutput(desc->mIoHandle);
6030 outputsChanged = true;
6031 }
Eric Laurent39095982021-08-24 18:29:27 +02006032 }
6033
Eric Laurente191d1b2022-04-15 11:59:25 +02006034 if (mSpatializerOutput == nullptr) {
Eric Laurentb4f42a92022-01-17 17:37:31 +01006035 sp<SwAudioOutputDescriptor> desc =
6036 openOutputWithProfileAndDevice(profile, devices, mixerConfig);
Eric Laurente191d1b2022-04-15 11:59:25 +02006037 if (desc != nullptr) {
6038 mSpatializerOutput = desc;
6039 outputsChanged = true;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006040 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006041 }
6042
6043 checkVirtualizerClientRoutes();
6044
Eric Laurente191d1b2022-04-15 11:59:25 +02006045 if (outputsChanged) {
6046 mPreviousOutputs = mOutputs;
6047 mpClientInterface->onAudioPortListUpdate();
6048 }
6049
6050 if (mSpatializerOutput == nullptr) {
6051 ALOGV("%s could not open spatializer output with requested config", __func__);
6052 return BAD_VALUE;
6053 }
Eric Laurent39095982021-08-24 18:29:27 +02006054 *output = mSpatializerOutput->mIoHandle;
Eric Laurente191d1b2022-04-15 11:59:25 +02006055 ALOGV("%s returning new spatializer output %d", __func__, *output);
6056 return OK;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006057}
6058
Eric Laurentfa0f6742021-08-17 18:39:44 +02006059status_t AudioPolicyManager::releaseSpatializerOutput(audio_io_handle_t output) {
6060 if (mSpatializerOutput == nullptr) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006061 return INVALID_OPERATION;
6062 }
Eric Laurentfa0f6742021-08-17 18:39:44 +02006063 if (mSpatializerOutput->mIoHandle != output) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006064 return BAD_VALUE;
6065 }
Eric Laurent39095982021-08-24 18:29:27 +02006066
Eric Laurente191d1b2022-04-15 11:59:25 +02006067 if (!isOutputOnlyAvailableRouteToSomeDevice(mSpatializerOutput)) {
6068 ALOGV("%s closing spatializer output %d", __func__, mSpatializerOutput->mIoHandle);
6069 closeOutput(mSpatializerOutput->mIoHandle);
6070 //from now on mSpatializerOutput is null
6071 checkVirtualizerClientRoutes();
6072 }
Eric Laurent39095982021-08-24 18:29:27 +02006073
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006074 return NO_ERROR;
6075}
6076
Eric Laurente552edb2014-03-10 17:42:56 -07006077// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07006078// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07006079// ----------------------------------------------------------------------------
Eric Laurent6a94d692014-05-20 11:18:06 -07006080uint32_t AudioPolicyManager::nextAudioPortGeneration()
6081{
Mikhail Naganov2773dd72017-12-08 10:12:11 -08006082 return mAudioPortGeneration++;
Eric Laurent6a94d692014-05-20 11:18:06 -07006083}
6084
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006085AudioPolicyManager::AudioPolicyManager(const sp<const AudioPolicyConfig>& config,
Mikhail Naganovf1b6d972023-05-02 13:56:01 -07006086 EngineInstance&& engine,
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006087 AudioPolicyClientInterface *clientInterface)
Eric Laurente552edb2014-03-10 17:42:56 -07006088 :
Andy Hung4ef19fa2018-05-15 19:35:29 -07006089 mUidCached(AID_AUDIOSERVER), // no need to call getuid(), there's only one of us running.
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006090 mConfig(config),
Mikhail Naganovf1b6d972023-05-02 13:56:01 -07006091 mEngine(std::move(engine)),
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006092 mpClientInterface(clientInterface),
Eric Laurente552edb2014-03-10 17:42:56 -07006093 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
Eric Laurent3a4311c2014-03-17 12:00:47 -07006094 mA2dpSuspended(false),
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006095 mAudioPortGeneration(1),
6096 mBeaconMuteRefCount(0),
6097 mBeaconPlayingRefCount(0),
Eric Laurent9459fb02015-08-12 18:36:32 -07006098 mBeaconMuted(false),
Andy Hung2ddee192015-12-18 17:34:44 -08006099 mTtsOutputAvailable(false),
Eric Laurent36829f92017-04-07 19:04:42 -07006100 mMasterMono(false),
Eric Laurent4eb58f12018-12-07 16:41:02 -08006101 mMusicEffectOutput(AUDIO_IO_HANDLE_NONE)
Eric Laurente552edb2014-03-10 17:42:56 -07006102{
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006103}
François Gaffied1ab2bd2015-12-02 18:20:06 +01006104
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006105status_t AudioPolicyManager::initialize() {
Mikhail Naganovf1b6d972023-05-02 13:56:01 -07006106 if (mEngine == nullptr) {
6107 return NO_INIT;
François Gaffie2110e042015-03-24 08:41:51 +01006108 }
6109 mEngine->setObserver(this);
6110 status_t status = mEngine->initCheck();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006111 if (status != NO_ERROR) {
6112 LOG_FATAL("Policy engine not initialized(err=%d)", status);
6113 return status;
6114 }
François Gaffie2110e042015-03-24 08:41:51 +01006115
jiabin29230182023-04-04 21:02:36 +00006116 // The actual device selection cache will be updated when calling `updateDevicesAndOutputs`
6117 // at the end of this function.
6118 mEngine->initializeDeviceSelectionCache();
Eric Laurent1d69c872021-01-11 18:53:01 +01006119 mCommunnicationStrategy = mEngine->getProductStrategyForAttributes(
6120 mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL));
6121
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006122 // after parsing the config, mConfig contain all known devices;
Eric Laurente552edb2014-03-10 17:42:56 -07006123 // open all output streams needed to access attached devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006124 onNewAudioModulesAvailableInt(nullptr /*newDevices*/);
François Gaffie11d30102018-11-02 16:09:09 +01006125
Eric Laurent3a4311c2014-03-17 12:00:47 -07006126 // make sure default device is reachable
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006127 if (const auto defaultOutputDevice = mConfig->getDefaultOutputDevice();
6128 defaultOutputDevice == nullptr ||
6129 !mAvailableOutputDevices.contains(defaultOutputDevice)) {
6130 ALOGE_IF(defaultOutputDevice != nullptr, "Default device %s is unreachable",
6131 defaultOutputDevice->toString().c_str());
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006132 status = NO_INIT;
Eric Laurent3a4311c2014-03-17 12:00:47 -07006133 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02006134 ALOGW_IF(mPrimaryOutput == nullptr, "The policy configuration does not declare a primary output");
Eric Laurente552edb2014-03-10 17:42:56 -07006135
Tomoharu Kasahara71c90912018-10-31 09:10:12 +09006136 // Silence ALOGV statements
6137 property_set("log.tag." LOG_TAG, "D");
6138
Eric Laurente552edb2014-03-10 17:42:56 -07006139 updateDevicesAndOutputs();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006140 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07006141}
6142
Eric Laurente0720872014-03-11 09:30:41 -07006143AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07006144{
Eric Laurente552edb2014-03-10 17:42:56 -07006145 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08006146 mOutputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07006147 }
6148 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08006149 mInputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07006150 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07006151 mAvailableOutputDevices.clear();
6152 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07006153 mOutputs.clear();
6154 mInputs.clear();
6155 mHwModules.clear();
Mikhail Naganov100f0122018-11-29 11:22:16 -08006156 mManualSurroundFormats.clear();
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006157 mConfig.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07006158}
6159
Eric Laurente0720872014-03-11 09:30:41 -07006160status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07006161{
Eric Laurent87ffa392015-05-22 10:32:38 -07006162 return hasPrimaryOutput() ? NO_ERROR : NO_INIT;
Eric Laurente552edb2014-03-10 17:42:56 -07006163}
6164
Eric Laurente552edb2014-03-10 17:42:56 -07006165// ---
6166
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006167void AudioPolicyManager::onNewAudioModulesAvailable()
6168{
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006169 DeviceVector newDevices;
6170 onNewAudioModulesAvailableInt(&newDevices);
6171 if (!newDevices.empty()) {
6172 nextAudioPortGeneration();
6173 mpClientInterface->onAudioPortListUpdate();
6174 }
6175}
6176
6177void AudioPolicyManager::onNewAudioModulesAvailableInt(DeviceVector *newDevices)
6178{
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006179 for (const auto& hwModule : mConfig->getHwModules()) {
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006180 if (std::find(mHwModules.begin(), mHwModules.end(), hwModule) != mHwModules.end()) {
6181 continue;
6182 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006183 if (hwModule->getHandle() == AUDIO_MODULE_HANDLE_NONE) {
Mikhail Naganovffd97712023-05-03 17:45:36 -07006184 if (audio_module_handle_t handle = mpClientInterface->loadHwModule(hwModule->getName());
6185 handle != AUDIO_MODULE_HANDLE_NONE) {
6186 hwModule->setHandle(handle);
6187 } else {
6188 ALOGW("could not load HW module %s", hwModule->getName());
6189 continue;
6190 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006191 }
6192 mHwModules.push_back(hwModule);
Dean Wheatley12a87132021-04-16 10:08:49 +10006193 // open all output streams needed to access attached devices.
6194 // direct outputs are closed immediately after checking the availability of attached devices
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006195 // This also validates mAvailableOutputDevices list
6196 for (const auto& outProfile : hwModule->getOutputProfiles()) {
6197 if (!outProfile->canOpenNewIo()) {
6198 ALOGE("Invalid Output profile max open count %u for profile %s",
6199 outProfile->maxOpenCount, outProfile->getTagName().c_str());
6200 continue;
6201 }
6202 if (!outProfile->hasSupportedDevices()) {
6203 ALOGW("Output profile contains no device on module %s", hwModule->getName());
6204 continue;
6205 }
Carter Hsu1a3364a2022-01-21 15:32:56 +08006206 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_TTS) != 0 ||
6207 (outProfile->getFlags() & AUDIO_OUTPUT_FLAG_ULTRASOUND) != 0) {
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006208 mTtsOutputAvailable = true;
6209 }
6210
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006211 const DeviceVector &supportedDevices = outProfile->getSupportedDevices();
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006212 DeviceVector availProfileDevices = supportedDevices.filter(mConfig->getOutputDevices());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006213 sp<DeviceDescriptor> supportedDevice = 0;
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006214 if (supportedDevices.contains(mConfig->getDefaultOutputDevice())) {
6215 supportedDevice = mConfig->getDefaultOutputDevice();
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006216 } else {
6217 // choose first device present in profile's SupportedDevices also part of
6218 // mAvailableOutputDevices.
6219 if (availProfileDevices.isEmpty()) {
6220 continue;
6221 }
6222 supportedDevice = availProfileDevices.itemAt(0);
6223 }
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006224 if (!mConfig->getOutputDevices().contains(supportedDevice)) {
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006225 continue;
6226 }
6227 sp<SwAudioOutputDescriptor> outputDesc = new SwAudioOutputDescriptor(outProfile,
6228 mpClientInterface);
6229 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentf1f22e72021-07-13 14:04:14 +02006230 status_t status = outputDesc->open(nullptr /* halConfig */, nullptr /* mixerConfig */,
6231 DeviceVector(supportedDevice),
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006232 AUDIO_STREAM_DEFAULT,
6233 AUDIO_OUTPUT_FLAG_NONE, &output);
6234 if (status != NO_ERROR) {
6235 ALOGW("Cannot open output stream for devices %s on hw module %s",
6236 supportedDevice->toString().c_str(), hwModule->getName());
6237 continue;
6238 }
6239 for (const auto &device : availProfileDevices) {
6240 // give a valid ID to an attached device once confirmed it is reachable
6241 if (!device->isAttached()) {
6242 device->attach(hwModule);
6243 mAvailableOutputDevices.add(device);
jiabin1c4794b2020-05-05 10:08:05 -07006244 device->setEncapsulationInfoFromHal(mpClientInterface);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006245 if (newDevices) newDevices->add(device);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006246 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
6247 }
6248 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02006249 if (mPrimaryOutput == nullptr &&
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006250 outProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
6251 mPrimaryOutput = outputDesc;
6252 }
Eric Laurent39095982021-08-24 18:29:27 +02006253 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
Eric Laurentc529cf62020-04-17 18:19:10 -07006254 outputDesc->close();
6255 } else {
6256 addOutput(output, outputDesc);
6257 setOutputDevices(outputDesc,
6258 DeviceVector(supportedDevice),
6259 true,
6260 0,
6261 NULL);
6262 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006263 }
6264 // open input streams needed to access attached devices to validate
6265 // mAvailableInputDevices list
6266 for (const auto& inProfile : hwModule->getInputProfiles()) {
6267 if (!inProfile->canOpenNewIo()) {
6268 ALOGE("Invalid Input profile max open count %u for profile %s",
6269 inProfile->maxOpenCount, inProfile->getTagName().c_str());
6270 continue;
6271 }
6272 if (!inProfile->hasSupportedDevices()) {
6273 ALOGW("Input profile contains no device on module %s", hwModule->getName());
6274 continue;
6275 }
6276 // chose first device present in profile's SupportedDevices also part of
6277 // available input devices
6278 const DeviceVector &supportedDevices = inProfile->getSupportedDevices();
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006279 DeviceVector availProfileDevices = supportedDevices.filter(mConfig->getInputDevices());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006280 if (availProfileDevices.isEmpty()) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01006281 ALOGV("%s: Input device list is empty! for profile %s",
6282 __func__, inProfile->getTagName().c_str());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006283 continue;
6284 }
6285 sp<AudioInputDescriptor> inputDesc =
6286 new AudioInputDescriptor(inProfile, mpClientInterface);
6287
6288 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
6289 status_t status = inputDesc->open(nullptr,
6290 availProfileDevices.itemAt(0),
6291 AUDIO_SOURCE_MIC,
6292 AUDIO_INPUT_FLAG_NONE,
6293 &input);
6294 if (status != NO_ERROR) {
6295 ALOGW("Cannot open input stream for device %s on hw module %s",
6296 availProfileDevices.toString().c_str(),
6297 hwModule->getName());
6298 continue;
6299 }
6300 for (const auto &device : availProfileDevices) {
6301 // give a valid ID to an attached device once confirmed it is reachable
6302 if (!device->isAttached()) {
6303 device->attach(hwModule);
6304 device->importAudioPortAndPickAudioProfile(inProfile, true);
6305 mAvailableInputDevices.add(device);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006306 if (newDevices) newDevices->add(device);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006307 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
6308 }
6309 }
6310 inputDesc->close();
6311 }
6312 }
Eric Laurente191d1b2022-04-15 11:59:25 +02006313
6314 // Check if spatializer outputs can be closed until used.
6315 // mOutputs vector never contains duplicated outputs at this point.
6316 std::vector<audio_io_handle_t> outputsClosed;
6317 for (size_t i = 0; i < mOutputs.size(); i++) {
6318 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
6319 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0
6320 && !isOutputOnlyAvailableRouteToSomeDevice(desc)) {
6321 outputsClosed.push_back(desc->mIoHandle);
6322 desc->close();
6323 }
6324 }
6325 for (auto output : outputsClosed) {
6326 removeOutput(output);
6327 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006328}
6329
Eric Laurent98e38192018-02-15 18:31:53 -08006330void AudioPolicyManager::addOutput(audio_io_handle_t output,
6331 const sp<SwAudioOutputDescriptor>& outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07006332{
Eric Laurent1c333e22014-05-20 10:48:17 -07006333 mOutputs.add(output, outputDesc);
jiabin9a3361e2019-10-01 09:38:30 -07006334 applyStreamVolumes(outputDesc, DeviceTypeSet(), 0 /* delayMs */, true /* force */);
Andy Hung2ddee192015-12-18 17:34:44 -08006335 updateMono(output); // update mono status when adding to output list
Eric Laurent36829f92017-04-07 19:04:42 -07006336 selectOutputForMusicEffects();
Eric Laurent6a94d692014-05-20 11:18:06 -07006337 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07006338}
6339
François Gaffie53615e22015-03-19 09:24:12 +01006340void AudioPolicyManager::removeOutput(audio_io_handle_t output)
6341{
Francois Gaffiebce7cd42020-10-14 16:13:20 +02006342 if (mPrimaryOutput != 0 && mPrimaryOutput == mOutputs.valueFor(output)) {
6343 ALOGV("%s: removing primary output", __func__);
6344 mPrimaryOutput = nullptr;
6345 }
François Gaffie53615e22015-03-19 09:24:12 +01006346 mOutputs.removeItem(output);
Eric Laurent36829f92017-04-07 19:04:42 -07006347 selectOutputForMusicEffects();
François Gaffie53615e22015-03-19 09:24:12 +01006348}
6349
Eric Laurent98e38192018-02-15 18:31:53 -08006350void AudioPolicyManager::addInput(audio_io_handle_t input,
6351 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07006352{
Eric Laurent1c333e22014-05-20 10:48:17 -07006353 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07006354 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07006355}
Eric Laurente552edb2014-03-10 17:42:56 -07006356
François Gaffie11d30102018-11-02 16:09:09 +01006357status_t AudioPolicyManager::checkOutputsForDevice(const sp<DeviceDescriptor>& device,
François Gaffie53615e22015-03-19 09:24:12 +01006358 audio_policy_dev_state_t state,
François Gaffie11d30102018-11-02 16:09:09 +01006359 SortedVector<audio_io_handle_t>& outputs)
Eric Laurente552edb2014-03-10 17:42:56 -07006360{
François Gaffie11d30102018-11-02 16:09:09 +01006361 audio_devices_t deviceType = device->type();
jiabince9f20e2019-09-12 16:29:15 -07006362 const String8 &address = String8(device->address().c_str());
Eric Laurentc75307b2015-03-17 15:29:32 -07006363 sp<SwAudioOutputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07006364
François Gaffie11d30102018-11-02 16:09:09 +01006365 if (audio_device_is_digital(deviceType)) {
Eric Laurentcc750d32015-06-25 11:48:20 -07006366 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01006367 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07006368 }
Eric Laurente552edb2014-03-10 17:42:56 -07006369
Eric Laurent3b73df72014-03-11 09:06:29 -07006370 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
jiabinb4fed192020-09-22 14:45:40 -07006371 // first call getAudioPort to get the supported attributes from the HAL
6372 struct audio_port_v7 port = {};
6373 device->toAudioPort(&port);
6374 status_t status = mpClientInterface->getAudioPort(&port);
6375 if (status == NO_ERROR) {
6376 device->importAudioPort(port);
6377 }
6378
6379 // then list already open outputs that can be routed to this device
Eric Laurente552edb2014-03-10 17:42:56 -07006380 for (size_t i = 0; i < mOutputs.size(); i++) {
6381 desc = mOutputs.valueAt(i);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006382 if (!desc->isDuplicated() && desc->supportsDevice(device)
jiabin9a3361e2019-10-01 09:38:30 -07006383 && desc->devicesSupportEncodedFormats({deviceType})) {
François Gaffie11d30102018-11-02 16:09:09 +01006384 ALOGV("checkOutputsForDevice(): adding opened output %d on device %s",
6385 mOutputs.keyAt(i), device->toString().c_str());
6386 outputs.add(mOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07006387 }
6388 }
6389 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07006390 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006391 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006392 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
6393 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
François Gaffie11d30102018-11-02 16:09:09 +01006394 if (profile->supportsDevice(device)) {
6395 profiles.add(profile);
6396 ALOGV("checkOutputsForDevice(): adding profile %zu from module %s",
6397 j, hwModule->getName());
Eric Laurente552edb2014-03-10 17:42:56 -07006398 }
6399 }
6400 }
6401
Eric Laurent7b279bb2015-12-14 10:18:23 -08006402 ALOGV(" found %zu profiles, %zu outputs", profiles.size(), outputs.size());
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006403
Eric Laurente552edb2014-03-10 17:42:56 -07006404 if (profiles.isEmpty() && outputs.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006405 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07006406 return BAD_VALUE;
6407 }
6408
6409 // open outputs for matching profiles if needed. Direct outputs are also opened to
6410 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
6411 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07006412 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07006413
6414 // nothing to do if one output is already opened for this profile
6415 size_t j;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006416 for (j = 0; j < outputs.size(); j++) {
6417 desc = mOutputs.valueFor(outputs.itemAt(j));
Eric Laurente552edb2014-03-10 17:42:56 -07006418 if (!desc->isDuplicated() && desc->mProfile == profile) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07006419 // matching profile: save the sample rates, format and channel masks supported
6420 // by the profile in our device descriptor
François Gaffie11d30102018-11-02 16:09:09 +01006421 if (audio_device_is_digital(deviceType)) {
jiabin4ef93452019-09-10 14:29:54 -07006422 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006423 }
Eric Laurente552edb2014-03-10 17:42:56 -07006424 break;
6425 }
6426 }
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006427 if (j != outputs.size()) {
Eric Laurente552edb2014-03-10 17:42:56 -07006428 continue;
6429 }
6430
Eric Laurent3974e3b2017-12-07 17:58:43 -08006431 if (!profile->canOpenNewIo()) {
6432 ALOGW("Max Output number %u already opened for this profile %s",
6433 profile->maxOpenCount, profile->getTagName().c_str());
6434 continue;
6435 }
6436
Eric Laurent83efe1c2017-07-09 16:51:08 -07006437 ALOGV("opening output for device %08x with params %s profile %p name %s",
jiabin5740f082019-08-19 15:08:30 -07006438 deviceType, address.string(), profile.get(), profile->getName().c_str());
jiabinbce0c1d2020-10-05 11:20:18 -07006439 desc = openOutputWithProfileAndDevice(profile, DeviceVector(device));
6440 audio_io_handle_t output = desc == nullptr ? AUDIO_IO_HANDLE_NONE : desc->mIoHandle;
Eric Laurentcf2c0212014-07-25 16:20:43 -07006441 if (output == AUDIO_IO_HANDLE_NONE) {
François Gaffie11d30102018-11-02 16:09:09 +01006442 ALOGW("checkOutputsForDevice() could not open output for device %x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07006443 profiles.removeAt(profile_index);
6444 profile_index--;
6445 } else {
6446 outputs.add(output);
Paul McLean9080a4c2015-06-18 08:24:02 -07006447 // Load digital format info only for digital devices
François Gaffie11d30102018-11-02 16:09:09 +01006448 if (audio_device_is_digital(deviceType)) {
jiabinbce0c1d2020-10-05 11:20:18 -07006449 // TODO: when getAudioPort is ready, it may not be needed to import the audio
6450 // port but just pick audio profile
jiabin4ef93452019-09-10 14:29:54 -07006451 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006452 }
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07006453
François Gaffie11d30102018-11-02 16:09:09 +01006454 if (device_distinguishes_on_address(deviceType)) {
6455 ALOGV("checkOutputsForDevice(): setOutputDevices %s",
6456 device->toString().c_str());
6457 setOutputDevices(desc, DeviceVector(device), true/*force*/, 0/*delay*/,
6458 NULL/*patch handle*/);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006459 }
Eric Laurente552edb2014-03-10 17:42:56 -07006460 ALOGV("checkOutputsForDevice(): adding output %d", output);
6461 }
6462 }
6463
6464 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006465 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07006466 return BAD_VALUE;
6467 }
Eric Laurentd4692962014-05-05 18:13:44 -07006468 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07006469 // check if one opened output is not needed any more after disconnecting one device
6470 for (size_t i = 0; i < mOutputs.size(); i++) {
6471 desc = mOutputs.valueAt(i);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006472 if (!desc->isDuplicated()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08006473 // exact match on device
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006474 if (device_distinguishes_on_address(deviceType) && desc->supportsDevice(device)
Francois Gaffiec7d4c222021-12-02 11:12:52 +01006475 && desc->containsSingleDeviceSupportingEncodedFormats(device)) {
François Gaffie11d30102018-11-02 16:09:09 +01006476 outputs.add(mOutputs.keyAt(i));
Francois Gaffie716e1432019-01-14 16:58:59 +01006477 } else if (!mAvailableOutputDevices.containsAtLeastOne(desc->supportedDevices())) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006478 ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
6479 mOutputs.keyAt(i));
6480 outputs.add(mOutputs.keyAt(i));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006481 }
Eric Laurente552edb2014-03-10 17:42:56 -07006482 }
6483 }
Eric Laurentd4692962014-05-05 18:13:44 -07006484 // Clear any profiles associated with the disconnected device.
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006485 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006486 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
6487 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
jiabinbce0c1d2020-10-05 11:20:18 -07006488 if (!profile->supportsDevice(device)) {
6489 continue;
6490 }
6491 ALOGV("checkOutputsForDevice(): "
6492 "clearing direct output profile %zu on module %s",
6493 j, hwModule->getName());
6494 profile->clearAudioProfiles();
6495 if (!profile->hasDynamicAudioProfile()) {
6496 continue;
6497 }
6498 // When a device is disconnected, if there is an IOProfile that contains dynamic
6499 // profiles and supports the disconnected device, call getAudioPort to repopulate
6500 // the capabilities of the devices that is supported by the IOProfile.
6501 for (const auto& supportedDevice : profile->getSupportedDevices()) {
6502 if (supportedDevice == device ||
6503 !mAvailableOutputDevices.contains(supportedDevice)) {
6504 continue;
6505 }
6506 struct audio_port_v7 port;
6507 supportedDevice->toAudioPort(&port);
6508 status_t status = mpClientInterface->getAudioPort(&port);
6509 if (status == NO_ERROR) {
6510 supportedDevice->importAudioPort(port);
6511 }
Eric Laurente552edb2014-03-10 17:42:56 -07006512 }
6513 }
6514 }
6515 }
6516 return NO_ERROR;
6517}
6518
François Gaffie11d30102018-11-02 16:09:09 +01006519status_t AudioPolicyManager::checkInputsForDevice(const sp<DeviceDescriptor>& device,
Eric Laurent0dd51852019-04-19 18:18:58 -07006520 audio_policy_dev_state_t state)
Eric Laurentd4692962014-05-05 18:13:44 -07006521{
Eric Laurent1f2f2232014-06-02 12:01:23 -07006522 sp<AudioInputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07006523
François Gaffie11d30102018-11-02 16:09:09 +01006524 if (audio_device_is_digital(device->type())) {
Eric Laurentcc750d32015-06-25 11:48:20 -07006525 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01006526 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07006527 }
6528
Eric Laurentd4692962014-05-05 18:13:44 -07006529 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
jiabinbf5f4262023-04-12 21:48:34 +00006530 // first call getAudioPort to get the supported attributes from the HAL
6531 struct audio_port_v7 port = {};
6532 device->toAudioPort(&port);
6533 status_t status = mpClientInterface->getAudioPort(&port);
6534 if (status == NO_ERROR) {
6535 device->importAudioPort(port);
6536 }
6537
Eric Laurent0dd51852019-04-19 18:18:58 -07006538 // look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07006539 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006540 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07006541 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006542 profile_index < hwModule->getInputProfiles().size();
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006543 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006544 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Eric Laurent275e8e92014-11-30 15:14:47 -08006545
François Gaffie11d30102018-11-02 16:09:09 +01006546 if (profile->supportsDevice(device)) {
6547 profiles.add(profile);
6548 ALOGV("checkInputsForDevice(): adding profile %zu from module %s",
6549 profile_index, hwModule->getName());
Eric Laurentd4692962014-05-05 18:13:44 -07006550 }
6551 }
6552 }
6553
Eric Laurent0dd51852019-04-19 18:18:58 -07006554 if (profiles.isEmpty()) {
6555 ALOGW("%s: No input profile available for device %s",
6556 __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07006557 return BAD_VALUE;
6558 }
6559
6560 // open inputs for matching profiles if needed. Direct inputs are also opened to
6561 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
6562 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
6563
Eric Laurent1c333e22014-05-20 10:48:17 -07006564 sp<IOProfile> profile = profiles[profile_index];
Eric Laurent3974e3b2017-12-07 17:58:43 -08006565
Eric Laurentd4692962014-05-05 18:13:44 -07006566 // nothing to do if one input is already opened for this profile
6567 size_t input_index;
6568 for (input_index = 0; input_index < mInputs.size(); input_index++) {
6569 desc = mInputs.valueAt(input_index);
6570 if (desc->mProfile == profile) {
François Gaffie11d30102018-11-02 16:09:09 +01006571 if (audio_device_is_digital(device->type())) {
jiabin4ef93452019-09-10 14:29:54 -07006572 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006573 }
Eric Laurentd4692962014-05-05 18:13:44 -07006574 break;
6575 }
6576 }
6577 if (input_index != mInputs.size()) {
6578 continue;
6579 }
6580
Eric Laurent3974e3b2017-12-07 17:58:43 -08006581 if (!profile->canOpenNewIo()) {
6582 ALOGW("Max Input number %u already opened for this profile %s",
6583 profile->maxOpenCount, profile->getTagName().c_str());
6584 continue;
6585 }
6586
Eric Laurentfe231122017-11-17 17:48:06 -08006587 desc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentcf2c0212014-07-25 16:20:43 -07006588 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
jiabinbf5f4262023-04-12 21:48:34 +00006589 status = desc->open(nullptr, device, AUDIO_SOURCE_MIC, AUDIO_INPUT_FLAG_NONE, &input);
Eric Laurentd4692962014-05-05 18:13:44 -07006590
Eric Laurentcf2c0212014-07-25 16:20:43 -07006591 if (status == NO_ERROR) {
jiabince9f20e2019-09-12 16:29:15 -07006592 const String8& address = String8(device->address().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07006593 if (!address.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006594 char *param = audio_device_address_to_parameter(device->type(), address);
Eric Laurentcf2c0212014-07-25 16:20:43 -07006595 mpClientInterface->setParameters(input, String8(param));
6596 free(param);
Eric Laurentd4692962014-05-05 18:13:44 -07006597 }
François Gaffie11d30102018-11-02 16:09:09 +01006598 updateAudioProfiles(device, input, profile->getAudioProfiles());
François Gaffie112b0af2015-11-19 16:13:25 +01006599 if (!profile->hasValidAudioProfile()) {
Eric Laurentd4692962014-05-05 18:13:44 -07006600 ALOGW("checkInputsForDevice() direct input missing param");
Eric Laurentfe231122017-11-17 17:48:06 -08006601 desc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07006602 input = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07006603 }
6604
Eric Laurent0dd51852019-04-19 18:18:58 -07006605 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07006606 addInput(input, desc);
6607 }
6608 } // endif input != 0
6609
Eric Laurentcf2c0212014-07-25 16:20:43 -07006610 if (input == AUDIO_IO_HANDLE_NONE) {
Pattydd807582021-11-04 21:01:03 +08006611 ALOGW("%s could not open input for device %s", __func__,
François Gaffie11d30102018-11-02 16:09:09 +01006612 device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07006613 profiles.removeAt(profile_index);
6614 profile_index--;
6615 } else {
François Gaffie11d30102018-11-02 16:09:09 +01006616 if (audio_device_is_digital(device->type())) {
jiabin4ef93452019-09-10 14:29:54 -07006617 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006618 }
Eric Laurentd4692962014-05-05 18:13:44 -07006619 ALOGV("checkInputsForDevice(): adding input %d", input);
6620 }
6621 } // end scan profiles
6622
6623 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006624 ALOGW("%s: No input available for device %s", __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07006625 return BAD_VALUE;
6626 }
6627 } else {
6628 // Disconnect
Eric Laurentd4692962014-05-05 18:13:44 -07006629 // Clear any profiles associated with the disconnected device.
Mikhail Naganovd4120142017-12-06 15:49:22 -08006630 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07006631 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006632 profile_index < hwModule->getInputProfiles().size();
Eric Laurentd4692962014-05-05 18:13:44 -07006633 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006634 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Francois Gaffie716e1432019-01-14 16:58:59 +01006635 if (profile->supportsDevice(device)) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08006636 ALOGV("checkInputsForDevice(): clearing direct input profile %zu on module %s",
6637 profile_index, hwModule->getName());
François Gaffie112b0af2015-11-19 16:13:25 +01006638 profile->clearAudioProfiles();
Eric Laurentd4692962014-05-05 18:13:44 -07006639 }
6640 }
6641 }
6642 } // end disconnect
6643
6644 return NO_ERROR;
6645}
6646
6647
Eric Laurente0720872014-03-11 09:30:41 -07006648void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07006649{
6650 ALOGV("closeOutput(%d)", output);
6651
François Gaffie1c878552018-11-22 16:53:21 +01006652 sp<SwAudioOutputDescriptor> closingOutput = mOutputs.valueFor(output);
6653 if (closingOutput == NULL) {
Eric Laurente552edb2014-03-10 17:42:56 -07006654 ALOGW("closeOutput() unknown output %d", output);
6655 return;
6656 }
Mikhail Naganov32ebca32019-03-22 15:42:52 -07006657 const bool closingOutputWasActive = closingOutput->isActive();
François Gaffie1c878552018-11-22 16:53:21 +01006658 mPolicyMixes.closeOutput(closingOutput);
Eric Laurent275e8e92014-11-30 15:14:47 -08006659
Eric Laurente552edb2014-03-10 17:42:56 -07006660 // look for duplicated outputs connected to the output being removed.
6661 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie1c878552018-11-22 16:53:21 +01006662 sp<SwAudioOutputDescriptor> dupOutput = mOutputs.valueAt(i);
6663 if (dupOutput->isDuplicated() &&
6664 (dupOutput->mOutput1 == closingOutput || dupOutput->mOutput2 == closingOutput)) {
6665 sp<SwAudioOutputDescriptor> remainingOutput =
6666 dupOutput->mOutput1 == closingOutput ? dupOutput->mOutput2 : dupOutput->mOutput1;
Eric Laurente552edb2014-03-10 17:42:56 -07006667 // As all active tracks on duplicated output will be deleted,
6668 // and as they were also referenced on the other output, the reference
6669 // count for their stream type must be adjusted accordingly on
6670 // the other output.
François Gaffie1c878552018-11-22 16:53:21 +01006671 const bool wasActive = remainingOutput->isActive();
6672 // Note: no-op on the closing output where all clients has already been set inactive
6673 dupOutput->setAllClientsInactive();
Eric Laurent733ce942017-12-07 12:18:25 -08006674 // stop() will be a no op if the output is still active but is needed in case all
6675 // active streams refcounts where cleared above
6676 if (wasActive) {
François Gaffie1c878552018-11-22 16:53:21 +01006677 remainingOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08006678 }
Eric Laurente552edb2014-03-10 17:42:56 -07006679 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
6680 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
6681
6682 mpClientInterface->closeOutput(duplicatedOutput);
François Gaffie53615e22015-03-19 09:24:12 +01006683 removeOutput(duplicatedOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07006684 }
6685 }
6686
Eric Laurent05b90f82014-08-27 15:32:29 -07006687 nextAudioPortGeneration();
6688
François Gaffie1c878552018-11-22 16:53:21 +01006689 ssize_t index = mAudioPatches.indexOfKey(closingOutput->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07006690 if (index >= 0) {
6691 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006692 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
6693 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07006694 mAudioPatches.removeItemsAt(index);
6695 mpClientInterface->onAudioPatchListUpdate();
6696 }
6697
Mikhail Naganov32ebca32019-03-22 15:42:52 -07006698 if (closingOutputWasActive) {
6699 closingOutput->stop();
6700 }
François Gaffie1c878552018-11-22 16:53:21 +01006701 closingOutput->close();
Eric Laurente552edb2014-03-10 17:42:56 -07006702
François Gaffie53615e22015-03-19 09:24:12 +01006703 removeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07006704 mPreviousOutputs = mOutputs;
Eric Laurentb4f42a92022-01-17 17:37:31 +01006705 if (closingOutput == mSpatializerOutput) {
6706 mSpatializerOutput.clear();
6707 }
Dean Wheatley3023b382018-08-09 07:42:40 +10006708
6709 // MSD patches may have been released to support a non-MSD direct output. Reset MSD patch if
6710 // no direct outputs are open.
François Gaffie11d30102018-11-02 16:09:09 +01006711 if (!getMsdAudioOutDevices().isEmpty()) {
Dean Wheatley3023b382018-08-09 07:42:40 +10006712 bool directOutputOpen = false;
6713 for (size_t i = 0; i < mOutputs.size(); i++) {
6714 if (mOutputs[i]->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
6715 directOutputOpen = true;
6716 break;
6717 }
6718 }
6719 if (!directOutputOpen) {
Michael Chan6fb34492020-12-08 15:44:49 +11006720 ALOGV("no direct outputs open, reset MSD patches");
6721 // TODO: The MSD patches to be established here may differ to current MSD patches due to
6722 // how output devices for patching are resolved. Avoid by caching and reusing the
6723 // arguments to mEngine->getOutputDevicesForAttributes() when resolving which output
6724 // devices to patch to. This may be complicated by the fact that devices may become
6725 // unavailable.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11006726 setMsdOutputPatches();
Dean Wheatley3023b382018-08-09 07:42:40 +10006727 }
6728 }
Eric Laurent05b90f82014-08-27 15:32:29 -07006729}
6730
6731void AudioPolicyManager::closeInput(audio_io_handle_t input)
6732{
6733 ALOGV("closeInput(%d)", input);
6734
6735 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
6736 if (inputDesc == NULL) {
6737 ALOGW("closeInput() unknown input %d", input);
6738 return;
6739 }
6740
Eric Laurent6a94d692014-05-20 11:18:06 -07006741 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07006742
François Gaffie11d30102018-11-02 16:09:09 +01006743 sp<DeviceDescriptor> device = inputDesc->getDevice();
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08006744 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07006745 if (index >= 0) {
6746 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006747 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
6748 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07006749 mAudioPatches.removeItemsAt(index);
6750 mpClientInterface->onAudioPatchListUpdate();
6751 }
6752
Eric Laurentfe231122017-11-17 17:48:06 -08006753 inputDesc->close();
Eric Laurent05b90f82014-08-27 15:32:29 -07006754 mInputs.removeItem(input);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07006755
François Gaffie11d30102018-11-02 16:09:09 +01006756 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
6757 if (primaryInputDevices.contains(device) &&
Haynes Mathew George1d539d92018-03-16 11:40:49 -07006758 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07006759 mpClientInterface->setSoundTriggerCaptureState(false);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07006760 }
Eric Laurente552edb2014-03-10 17:42:56 -07006761}
6762
François Gaffie11d30102018-11-02 16:09:09 +01006763SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevices(
6764 const DeviceVector &devices,
6765 const SwAudioOutputCollection& openOutputs)
Eric Laurente552edb2014-03-10 17:42:56 -07006766{
6767 SortedVector<audio_io_handle_t> outputs;
6768
François Gaffie11d30102018-11-02 16:09:09 +01006769 ALOGVV("%s() devices %s", __func__, devices.toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07006770 for (size_t i = 0; i < openOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01006771 ALOGVV("output %zu isDuplicated=%d device=%s",
Eric Laurent8c7e6da2015-04-21 17:37:00 -07006772 i, openOutputs.valueAt(i)->isDuplicated(),
François Gaffie11d30102018-11-02 16:09:09 +01006773 openOutputs.valueAt(i)->supportedDevices().toString().c_str());
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006774 if (openOutputs.valueAt(i)->supportsAllDevices(devices)
jiabin9a3361e2019-10-01 09:38:30 -07006775 && openOutputs.valueAt(i)->devicesSupportEncodedFormats(devices.types())) {
François Gaffie11d30102018-11-02 16:09:09 +01006776 ALOGVV("%s() found output %d", __func__, openOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07006777 outputs.add(openOutputs.keyAt(i));
6778 }
6779 }
6780 return outputs;
6781}
6782
Mikhail Naganov37977152018-07-11 15:54:44 -07006783void AudioPolicyManager::checkForDeviceAndOutputChanges(std::function<bool()> onOutputsChecked)
6784{
6785 // checkA2dpSuspend must run before checkOutputForAllStrategies so that A2DP
6786 // output is suspended before any tracks are moved to it
6787 checkA2dpSuspend();
6788 checkOutputForAllStrategies();
Kevin Rocard153f92d2018-12-18 18:33:28 -08006789 checkSecondaryOutputs();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11006790 if (onOutputsChecked != nullptr && onOutputsChecked()) checkA2dpSuspend();
Mikhail Naganov37977152018-07-11 15:54:44 -07006791 updateDevicesAndOutputs();
Mikhail Naganov7bd9b8d2018-11-15 02:09:03 +00006792 if (mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD) != 0) {
Michael Chan6fb34492020-12-08 15:44:49 +11006793 // TODO: The MSD patches to be established here may differ to current MSD patches due to how
6794 // output devices for patching are resolved. Nevertheless, AudioTracks affected by device
6795 // configuration changes will ultimately be rerouted correctly. We can still avoid
6796 // unnecessary rerouting by caching and reusing the arguments to
6797 // mEngine->getOutputDevicesForAttributes() when resolving which output devices to patch to.
6798 // This may be complicated by the fact that devices may become unavailable.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11006799 setMsdOutputPatches();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11006800 }
Jean-Michel Trivi9a6b9ad2020-10-22 16:46:43 -07006801 // an event that changed routing likely occurred, inform upper layers
6802 mpClientInterface->onRoutingUpdated();
Mikhail Naganov37977152018-07-11 15:54:44 -07006803}
6804
François Gaffiec005e562018-11-06 15:04:49 +01006805bool AudioPolicyManager::followsSameRouting(const audio_attributes_t &lAttr,
6806 const audio_attributes_t &rAttr) const
Eric Laurente552edb2014-03-10 17:42:56 -07006807{
François Gaffiec005e562018-11-06 15:04:49 +01006808 return mEngine->getProductStrategyForAttributes(lAttr) ==
6809 mEngine->getProductStrategyForAttributes(rAttr);
6810}
6811
Francois Gaffieff1eb522020-05-06 18:37:04 +02006812void AudioPolicyManager::checkAudioSourceForAttributes(const audio_attributes_t &attr)
6813{
6814 for (size_t i = 0; i < mAudioSources.size(); i++) {
6815 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
6816 if (sourceDesc != nullptr && followsSameRouting(attr, sourceDesc->attributes())
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02006817 && sourceDesc->getPatchHandle() == AUDIO_PATCH_HANDLE_NONE
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02006818 && !isCallRxAudioSource(sourceDesc) && !sourceDesc->isInternal()) {
Francois Gaffieff1eb522020-05-06 18:37:04 +02006819 connectAudioSource(sourceDesc);
6820 }
6821 }
6822}
6823
6824void AudioPolicyManager::clearAudioSourcesForOutput(audio_io_handle_t output)
6825{
6826 for (size_t i = 0; i < mAudioSources.size(); i++) {
6827 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
6828 if (sourceDesc != nullptr && sourceDesc->swOutput().promote() != nullptr
6829 && sourceDesc->swOutput().promote()->mIoHandle == output) {
6830 disconnectAudioSource(sourceDesc);
6831 }
6832 }
6833}
6834
François Gaffiec005e562018-11-06 15:04:49 +01006835void AudioPolicyManager::checkOutputForAttributes(const audio_attributes_t &attr)
6836{
6837 auto psId = mEngine->getProductStrategyForAttributes(attr);
6838
6839 DeviceVector oldDevices = mEngine->getOutputDevicesForAttributes(attr, 0, true /*fromCache*/);
6840 DeviceVector newDevices = mEngine->getOutputDevicesForAttributes(attr, 0, false /*fromCache*/);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07006841
François Gaffie11d30102018-11-02 16:09:09 +01006842 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevices(oldDevices, mPreviousOutputs);
6843 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevices(newDevices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07006844
Eric Laurentc209fe42020-06-05 18:11:23 -07006845 uint32_t maxLatency = 0;
Oscar Azucena873d10f2023-01-12 18:34:42 -08006846 bool unneededUsePrimaryOutputFromPolicyMixes = false;
Eric Laurent56ed8842022-11-15 16:04:41 +01006847 std::vector<sp<SwAudioOutputDescriptor>> invalidatedOutputs;
Eric Laurentc209fe42020-06-05 18:11:23 -07006848 // take into account dynamic audio policies related changes: if a client is now associated
6849 // to a different policy mix than at creation time, invalidate corresponding stream
Eric Laurent56ed8842022-11-15 16:04:41 +01006850 for (size_t i = 0; i < mPreviousOutputs.size(); i++) {
Eric Laurentc209fe42020-06-05 18:11:23 -07006851 const sp<SwAudioOutputDescriptor>& desc = mPreviousOutputs.valueAt(i);
6852 if (desc->isDuplicated()) {
6853 continue;
Jean-Michel Trivife472e22014-12-16 14:23:13 -08006854 }
Eric Laurentc209fe42020-06-05 18:11:23 -07006855 for (const sp<TrackClientDescriptor>& client : desc->getClientIterable()) {
6856 if (mEngine->getProductStrategyForAttributes(client->attributes()) != psId) {
6857 continue;
6858 }
6859 sp<AudioPolicyMix> primaryMix;
Dean Wheatleyd082f472022-02-04 11:10:48 +11006860 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->config(),
Oscar Azucena873d10f2023-01-12 18:34:42 -08006861 client->uid(), client->session(), client->flags(), mAvailableOutputDevices,
6862 nullptr /* requestedDevice */, primaryMix, nullptr /* secondaryMixes */,
6863 unneededUsePrimaryOutputFromPolicyMixes);
Eric Laurentc209fe42020-06-05 18:11:23 -07006864 if (status != OK) {
6865 continue;
6866 }
yucliuf4de36d2020-09-14 14:57:56 -07006867 if (client->getPrimaryMix() != primaryMix || client->hasLostPrimaryMix()) {
Eric Laurent56ed8842022-11-15 16:04:41 +01006868 if (desc->isStrategyActive(psId) && maxLatency < desc->latency()) {
Eric Laurentc209fe42020-06-05 18:11:23 -07006869 maxLatency = desc->latency();
6870 }
Eric Laurent56ed8842022-11-15 16:04:41 +01006871 invalidatedOutputs.push_back(desc);
Eric Laurentc209fe42020-06-05 18:11:23 -07006872 }
Jean-Michel Trivife472e22014-12-16 14:23:13 -08006873 }
6874 }
6875
Eric Laurent56ed8842022-11-15 16:04:41 +01006876 if (srcOutputs != dstOutputs || !invalidatedOutputs.empty()) {
Eric Laurentac3a6902018-05-11 16:39:10 -07006877 // get maximum latency of all source outputs to determine the minimum mute time guaranteeing
6878 // audio from invalidated tracks will be rendered when unmuting
Eric Laurentac3a6902018-05-11 16:39:10 -07006879 for (audio_io_handle_t srcOut : srcOutputs) {
6880 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
Eric Laurentaa02db82019-09-05 17:31:49 -07006881 if (desc == nullptr) continue;
6882
6883 if (desc->isStrategyActive(psId) && maxLatency < desc->latency()) {
Eric Laurentac3a6902018-05-11 16:39:10 -07006884 maxLatency = desc->latency();
6885 }
Eric Laurentaa02db82019-09-05 17:31:49 -07006886
Eric Laurent56ed8842022-11-15 16:04:41 +01006887 bool invalidate = false;
Eric Laurentaa02db82019-09-05 17:31:49 -07006888 for (auto client : desc->clientsList(false /*activeOnly*/)) {
Eric Laurent78aade82019-09-13 18:55:08 -07006889 if (desc->isDuplicated() || !desc->mProfile->isDirectOutput()) {
Eric Laurentaa02db82019-09-05 17:31:49 -07006890 // a client on a non direct outputs has necessarily a linear PCM format
6891 // so we can call selectOutput() safely
6892 const audio_io_handle_t newOutput = selectOutput(dstOutputs,
6893 client->flags(),
6894 client->config().format,
6895 client->config().channel_mask,
jiabinebb6af42020-06-09 17:31:17 -07006896 client->config().sample_rate,
6897 client->session());
Eric Laurentaa02db82019-09-05 17:31:49 -07006898 if (newOutput != srcOut) {
6899 invalidate = true;
6900 break;
6901 }
6902 } else {
6903 sp<IOProfile> profile = getProfileForOutput(newDevices,
6904 client->config().sample_rate,
6905 client->config().format,
6906 client->config().channel_mask,
6907 client->flags(),
6908 true /* directOnly */);
6909 if (profile != desc->mProfile) {
6910 invalidate = true;
6911 break;
6912 }
6913 }
6914 }
Eric Laurent56ed8842022-11-15 16:04:41 +01006915 // mute strategy while moving tracks from one output to another
6916 if (invalidate) {
6917 invalidatedOutputs.push_back(desc);
6918 if (desc->isStrategyActive(psId)) {
6919 setStrategyMute(psId, true, desc);
6920 setStrategyMute(psId, false, desc, maxLatency * LATENCY_MUTE_FACTOR,
6921 newDevices.types());
6922 }
Eric Laurente552edb2014-03-10 17:42:56 -07006923 }
François Gaffiec005e562018-11-06 15:04:49 +01006924 sp<SourceClientDescriptor> source = getSourceForAttributesOnOutput(srcOut, attr);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02006925 if (source != nullptr && !isCallRxAudioSource(source) && !source->isInternal()) {
Eric Laurentd60560a2015-04-10 11:31:20 -07006926 connectAudioSource(source);
6927 }
Eric Laurente552edb2014-03-10 17:42:56 -07006928 }
6929
Eric Laurent56ed8842022-11-15 16:04:41 +01006930 ALOGV_IF(!(srcOutputs.isEmpty() || dstOutputs.isEmpty()),
6931 "%s: strategy %d, moving from output %s to output %s", __func__, psId,
6932 std::to_string(srcOutputs[0]).c_str(),
6933 std::to_string(dstOutputs[0]).c_str());
6934
François Gaffiec005e562018-11-06 15:04:49 +01006935 // Move effects associated to this stream from previous output to new output
6936 if (followsSameRouting(attr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07006937 selectOutputForMusicEffects();
Eric Laurente552edb2014-03-10 17:42:56 -07006938 }
François Gaffiec005e562018-11-06 15:04:49 +01006939 // Move tracks associated to this stream (and linked) from previous output to new output
Eric Laurent56ed8842022-11-15 16:04:41 +01006940 if (!invalidatedOutputs.empty()) {
jiabinc44b3462022-12-08 12:52:31 -08006941 invalidateStreams(mEngine->getStreamTypesForProductStrategy(psId));
Eric Laurent56ed8842022-11-15 16:04:41 +01006942 for (sp<SwAudioOutputDescriptor> desc : invalidatedOutputs) {
jiabin49256852022-03-09 11:21:35 -08006943 desc->setTracksInvalidatedStatusByStrategy(psId);
6944 }
Eric Laurente552edb2014-03-10 17:42:56 -07006945 }
6946 }
6947}
6948
Eric Laurente0720872014-03-11 09:30:41 -07006949void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07006950{
François Gaffiec005e562018-11-06 15:04:49 +01006951 for (const auto &strategy : mEngine->getOrderedProductStrategies()) {
6952 auto attributes = mEngine->getAllAttributesForProductStrategy(strategy).front();
6953 checkOutputForAttributes(attributes);
Francois Gaffieff1eb522020-05-06 18:37:04 +02006954 checkAudioSourceForAttributes(attributes);
François Gaffiec005e562018-11-06 15:04:49 +01006955 }
Eric Laurente552edb2014-03-10 17:42:56 -07006956}
6957
Kevin Rocard153f92d2018-12-18 18:33:28 -08006958void AudioPolicyManager::checkSecondaryOutputs() {
jiabinc44b3462022-12-08 12:52:31 -08006959 PortHandleVector clientsToInvalidate;
jiabin10a03f12021-05-07 23:46:28 +00006960 TrackSecondaryOutputsMap trackSecondaryOutputs;
Oscar Azucena873d10f2023-01-12 18:34:42 -08006961 bool unneededUsePrimaryOutputFromPolicyMixes = false;
Kevin Rocard153f92d2018-12-18 18:33:28 -08006962 for (size_t i = 0; i < mOutputs.size(); i++) {
6963 const sp<SwAudioOutputDescriptor>& outputDescriptor = mOutputs[i];
6964 for (const sp<TrackClientDescriptor>& client : outputDescriptor->getClientIterable()) {
Eric Laurentc529cf62020-04-17 18:19:10 -07006965 sp<AudioPolicyMix> primaryMix;
6966 std::vector<sp<AudioPolicyMix>> secondaryMixes;
Dean Wheatleyd082f472022-02-04 11:10:48 +11006967 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->config(),
Oscar Azucena873d10f2023-01-12 18:34:42 -08006968 client->uid(), client->session(), client->flags(), mAvailableOutputDevices,
6969 nullptr /* requestedDevice */, primaryMix, &secondaryMixes,
6970 unneededUsePrimaryOutputFromPolicyMixes);
Eric Laurentc529cf62020-04-17 18:19:10 -07006971 std::vector<sp<SwAudioOutputDescriptor>> secondaryDescs;
6972 for (auto &secondaryMix : secondaryMixes) {
6973 sp<SwAudioOutputDescriptor> outputDesc = secondaryMix->getOutput();
6974 if (outputDesc != nullptr &&
6975 outputDesc->mIoHandle != AUDIO_IO_HANDLE_NONE) {
6976 secondaryDescs.push_back(outputDesc);
6977 }
6978 }
6979
jiabinc44b3462022-12-08 12:52:31 -08006980 if (status != OK &&
6981 (client->flags() & AUDIO_OUTPUT_FLAG_MMAP_NOIRQ) == AUDIO_OUTPUT_FLAG_NONE) {
6982 // When it failed to query secondary output, only invalidate the client that is not
6983 // MMAP. The reason is that MMAP stream will not support secondary output.
6984 clientsToInvalidate.push_back(client->portId());
jiabin10a03f12021-05-07 23:46:28 +00006985 } else if (!std::equal(
6986 client->getSecondaryOutputs().begin(),
6987 client->getSecondaryOutputs().end(),
6988 secondaryDescs.begin(), secondaryDescs.end())) {
jiabina5281062021-11-23 00:10:23 +00006989 if (!audio_is_linear_pcm(client->config().format)) {
6990 // If the format is not PCM, the tracks should be invalidated to get correct
6991 // behavior when the secondary output is changed.
jiabinc44b3462022-12-08 12:52:31 -08006992 clientsToInvalidate.push_back(client->portId());
jiabina5281062021-11-23 00:10:23 +00006993 } else {
6994 std::vector<wp<SwAudioOutputDescriptor>> weakSecondaryDescs;
6995 std::vector<audio_io_handle_t> secondaryOutputIds;
6996 for (const auto &secondaryDesc: secondaryDescs) {
6997 secondaryOutputIds.push_back(secondaryDesc->mIoHandle);
6998 weakSecondaryDescs.push_back(secondaryDesc);
6999 }
7000 trackSecondaryOutputs.emplace(client->portId(), secondaryOutputIds);
7001 client->setSecondaryOutputs(std::move(weakSecondaryDescs));
jiabin10a03f12021-05-07 23:46:28 +00007002 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08007003 }
7004 }
7005 }
jiabin10a03f12021-05-07 23:46:28 +00007006 if (!trackSecondaryOutputs.empty()) {
7007 mpClientInterface->updateSecondaryOutputs(trackSecondaryOutputs);
7008 }
jiabinc44b3462022-12-08 12:52:31 -08007009 if (!clientsToInvalidate.empty()) {
7010 ALOGD("%s Invalidate clients due to fail getting output for attr", __func__);
7011 mpClientInterface->invalidateTracks(clientsToInvalidate);
Kevin Rocard153f92d2018-12-18 18:33:28 -08007012 }
7013}
7014
Eric Laurent2517af32020-11-25 15:31:27 +01007015bool AudioPolicyManager::isScoRequestedForComm() const {
7016 AudioDeviceTypeAddrVector devices;
7017 mEngine->getDevicesForRoleAndStrategy(mCommunnicationStrategy, DEVICE_ROLE_PREFERRED, devices);
7018 for (const auto &device : devices) {
7019 if (audio_is_bluetooth_out_sco_device(device.mType)) {
7020 return true;
7021 }
7022 }
7023 return false;
7024}
7025
Eric Laurent1a8b45f2022-04-13 16:01:47 +02007026bool AudioPolicyManager::isHearingAidUsedForComm() const {
7027 DeviceVector devices = mEngine->getOutputDevicesForStream(AUDIO_STREAM_VOICE_CALL,
7028 true /*fromCache*/);
7029 for (const auto &device : devices) {
7030 if (device->type() == AUDIO_DEVICE_OUT_HEARING_AID) {
7031 return true;
7032 }
7033 }
7034 return false;
7035}
7036
7037
Eric Laurente0720872014-03-11 09:30:41 -07007038void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07007039{
François Gaffie53615e22015-03-19 09:24:12 +01007040 audio_io_handle_t a2dpOutput = mOutputs.getA2dpOutput();
Aniket Kumar Lataa8ee9962018-01-31 20:24:23 -08007041 if (a2dpOutput == 0 || mOutputs.isA2dpOffloadedOnPrimary()) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07007042 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07007043 return;
7044 }
7045
Eric Laurent3a4311c2014-03-17 12:00:47 -07007046 bool isScoConnected =
jiabin9a3361e2019-10-01 09:38:30 -07007047 (mAvailableInputDevices.types().count(AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) != 0 ||
7048 !Intersection(mAvailableOutputDevices.types(), getAudioDeviceOutAllScoSet()).empty());
Eric Laurent2517af32020-11-25 15:31:27 +01007049 bool isScoRequested = isScoRequestedForComm();
Eric Laurentf732e072016-08-03 19:30:28 -07007050
7051 // if suspended, restore A2DP output if:
7052 // ((SCO device is NOT connected) ||
Eric Laurent2517af32020-11-25 15:31:27 +01007053 // ((SCO is not requested) &&
Eric Laurentf732e072016-08-03 19:30:28 -07007054 // (phone state is NOT in call) && (phone state is NOT ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07007055 //
Eric Laurentf732e072016-08-03 19:30:28 -07007056 // if not suspended, suspend A2DP output if:
7057 // (SCO device is connected) &&
Eric Laurent2517af32020-11-25 15:31:27 +01007058 // ((SCO is requested) ||
Eric Laurentf732e072016-08-03 19:30:28 -07007059 // ((phone state is in call) || (phone state is ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07007060 //
7061 if (mA2dpSuspended) {
Eric Laurentf732e072016-08-03 19:30:28 -07007062 if (!isScoConnected ||
Eric Laurent2517af32020-11-25 15:31:27 +01007063 (!isScoRequested &&
Eric Laurentf732e072016-08-03 19:30:28 -07007064 (mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) &&
François Gaffie2110e042015-03-24 08:41:51 +01007065 (mEngine->getPhoneState() != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07007066
7067 mpClientInterface->restoreOutput(a2dpOutput);
7068 mA2dpSuspended = false;
7069 }
7070 } else {
Eric Laurentf732e072016-08-03 19:30:28 -07007071 if (isScoConnected &&
Eric Laurent2517af32020-11-25 15:31:27 +01007072 (isScoRequested ||
Eric Laurentf732e072016-08-03 19:30:28 -07007073 (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) ||
François Gaffie2110e042015-03-24 08:41:51 +01007074 (mEngine->getPhoneState() == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07007075
7076 mpClientInterface->suspendOutput(a2dpOutput);
7077 mA2dpSuspended = true;
7078 }
7079 }
7080}
7081
François Gaffie11d30102018-11-02 16:09:09 +01007082DeviceVector AudioPolicyManager::getNewOutputDevices(const sp<SwAudioOutputDescriptor>& outputDesc,
7083 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07007084{
François Gaffie11d30102018-11-02 16:09:09 +01007085 DeviceVector devices;
7086
Jean-Michel Triviff155c62016-02-26 12:07:16 -08007087 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007088 if (index >= 0) {
7089 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007090 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01007091 ALOGV("%s device %s forced by patch %d", __func__,
7092 outputDesc->devices().toString().c_str(), outputDesc->getPatchHandle());
7093 return outputDesc->devices();
Eric Laurent6a94d692014-05-20 11:18:06 -07007094 }
7095 }
7096
Dean Wheatley514b4312020-06-17 21:45:00 +10007097 // Do not retrieve engine device for outputs through MSD
7098 // TODO: support explicit routing requests by resetting MSD patch to engine device.
7099 if (outputDesc->devices() == getMsdAudioOutDevices()) {
7100 return outputDesc->devices();
7101 }
7102
Eric Laurent97ac8712018-07-27 18:59:02 -07007103 // Honor explicit routing requests only if no client using default routing is active on this
7104 // input: a specific app can not force routing for other apps by setting a preferred device.
7105 bool active; // unused
François Gaffie11d30102018-11-02 16:09:09 +01007106 sp<DeviceDescriptor> device =
François Gaffiec005e562018-11-06 15:04:49 +01007107 findPreferredDevice(outputDesc, PRODUCT_STRATEGY_NONE, active, mAvailableOutputDevices);
François Gaffie11d30102018-11-02 16:09:09 +01007108 if (device != nullptr) {
7109 return DeviceVector(device);
Eric Laurentf3a5a602018-05-22 18:42:55 -07007110 }
7111
François Gaffiea807ef92018-11-05 10:44:33 +01007112 // Legacy Engine cannot take care of bus devices and mix, so we need to handle the conflict
7113 // of setForceUse / Default Bus device here
7114 device = mPolicyMixes.getDeviceAndMixForOutput(outputDesc, mAvailableOutputDevices);
7115 if (device != nullptr) {
7116 return DeviceVector(device);
7117 }
7118
François Gaffiec005e562018-11-06 15:04:49 +01007119 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
7120 StreamTypeVector streams = mEngine->getStreamTypesForProductStrategy(productStrategy);
7121 auto attr = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307122 auto hasStreamActive = [&](auto stream) {
7123 return hasStream(streams, stream) && isStreamActive(stream, 0);
7124 };
Eric Laurent484e9272018-06-07 17:29:23 -07007125
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307126 auto doGetOutputDevicesForVoice = [&]() {
7127 return hasVoiceStream(streams) && (outputDesc == mPrimaryOutput ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007128 outputDesc->isActive(toVolumeSource(AUDIO_STREAM_VOICE_CALL, false))) &&
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307129 (isInCall() ||
Henrik Backlund07c654a2021-10-14 15:57:10 +02007130 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc)) &&
7131 !isStreamActive(AUDIO_STREAM_ENFORCED_AUDIBLE, 0);
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307132 };
7133
7134 // With low-latency playing on speaker, music on WFD, when the first low-latency
7135 // output is stopped, getNewOutputDevices checks for a product strategy
7136 // from the list, as STRATEGY_SONIFICATION comes prior to STRATEGY_MEDIA.
Carter Hsucc58a6b2021-07-20 08:44:50 +00007137 // If an ALARM or ENFORCED_AUDIBLE stream is supported by the product strategy,
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307138 // devices are returned for STRATEGY_SONIFICATION without checking whether the
7139 // stream is associated to the output descriptor.
7140 if (doGetOutputDevicesForVoice() || outputDesc->isStrategyActive(productStrategy) ||
7141 ((hasStreamActive(AUDIO_STREAM_ALARM) ||
7142 hasStreamActive(AUDIO_STREAM_ENFORCED_AUDIBLE)) &&
7143 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc))) {
François Gaffiec005e562018-11-06 15:04:49 +01007144 // Retrieval of devices for voice DL is done on primary output profile, cannot
7145 // check the route (would force modifying configuration file for this profile)
7146 devices = mEngine->getOutputDevicesForAttributes(attr, nullptr, fromCache);
7147 break;
7148 }
Eric Laurente552edb2014-03-10 17:42:56 -07007149 }
François Gaffiec005e562018-11-06 15:04:49 +01007150 ALOGV("%s selected devices %s", __func__, devices.toString().c_str());
François Gaffie11d30102018-11-02 16:09:09 +01007151 return devices;
Eric Laurent1c333e22014-05-20 10:48:17 -07007152}
7153
François Gaffie11d30102018-11-02 16:09:09 +01007154sp<DeviceDescriptor> AudioPolicyManager::getNewInputDevice(
7155 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurent1c333e22014-05-20 10:48:17 -07007156{
François Gaffie11d30102018-11-02 16:09:09 +01007157 sp<DeviceDescriptor> device;
Eric Laurent6a94d692014-05-20 11:18:06 -07007158
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08007159 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007160 if (index >= 0) {
7161 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007162 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01007163 ALOGV("getNewInputDevice() device %s forced by patch %d",
7164 inputDesc->getDevice()->toString().c_str(), inputDesc->getPatchHandle());
7165 return inputDesc->getDevice();
Eric Laurent6a94d692014-05-20 11:18:06 -07007166 }
7167 }
7168
Eric Laurent97ac8712018-07-27 18:59:02 -07007169 // Honor explicit routing requests only if no client using default routing is active on this
7170 // input: a specific app can not force routing for other apps by setting a preferred device.
7171 bool active;
François Gaffie11d30102018-11-02 16:09:09 +01007172 device = findPreferredDevice(inputDesc, AUDIO_SOURCE_DEFAULT, active, mAvailableInputDevices);
7173 if (device != nullptr) {
7174 return device;
Eric Laurent97ac8712018-07-27 18:59:02 -07007175 }
7176
Eric Laurentdc95a252018-04-12 12:46:56 -07007177 // If we are not in call and no client is active on this input, this methods returns
Andy Hungf024a9e2019-01-30 16:01:02 -08007178 // a null sp<>, causing the patch on the input stream to be released.
yuanjiahsu0735bf32021-03-18 08:12:54 +08007179 audio_attributes_t attributes;
7180 uid_t uid;
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007181 audio_session_t session;
yuanjiahsu0735bf32021-03-18 08:12:54 +08007182 sp<RecordClientDescriptor> topClient = inputDesc->getHighestPriorityClient();
7183 if (topClient != nullptr) {
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01007184 attributes = topClient->attributes();
7185 uid = topClient->uid();
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007186 session = topClient->session();
yuanjiahsu0735bf32021-03-18 08:12:54 +08007187 } else {
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01007188 attributes = { .source = AUDIO_SOURCE_DEFAULT };
7189 uid = 0;
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007190 session = AUDIO_SESSION_NONE;
yuanjiahsu0735bf32021-03-18 08:12:54 +08007191 }
7192
Francois Gaffie716e1432019-01-14 16:58:59 +01007193 if (attributes.source == AUDIO_SOURCE_DEFAULT && isInCall()) {
7194 attributes.source = AUDIO_SOURCE_VOICE_COMMUNICATION;
Eric Laurentdc95a252018-04-12 12:46:56 -07007195 }
Francois Gaffie716e1432019-01-14 16:58:59 +01007196 if (attributes.source != AUDIO_SOURCE_DEFAULT) {
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007197 device = mEngine->getInputDeviceForAttributes(attributes, uid, session);
Eric Laurentfb66dd92016-01-28 18:32:03 -08007198 }
Eric Laurent1c333e22014-05-20 10:48:17 -07007199
Eric Laurente552edb2014-03-10 17:42:56 -07007200 return device;
7201}
7202
Eric Laurent794fde22016-03-11 09:50:45 -08007203bool AudioPolicyManager::streamsMatchForvolume(audio_stream_type_t stream1,
7204 audio_stream_type_t stream2) {
Jean-Michel Trivi99bb2f92016-11-23 15:52:07 -08007205 return (stream1 == stream2);
Eric Laurent28d09f02016-03-08 10:43:05 -08007206}
7207
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08007208status_t AudioPolicyManager::getDevicesForAttributes(
Andy Hung6d23c0f2022-02-16 09:37:15 -08007209 const audio_attributes_t &attr, AudioDeviceTypeAddrVector *devices, bool forVolume) {
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08007210 if (devices == nullptr) {
7211 return BAD_VALUE;
7212 }
Andy Hung6d23c0f2022-02-16 09:37:15 -08007213
Andy Hung6d23c0f2022-02-16 09:37:15 -08007214 DeviceVector curDevices;
jiabinf1c73972022-04-14 16:28:52 -07007215 if (status_t status = getDevicesForAttributes(attr, curDevices, forVolume); status != OK) {
7216 return status;
Andy Hung6d23c0f2022-02-16 09:37:15 -08007217 }
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08007218 for (const auto& device : curDevices) {
7219 devices->push_back(device->getDeviceTypeAddr());
7220 }
7221 return NO_ERROR;
7222}
7223
Eric Laurente0720872014-03-11 09:30:41 -07007224void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07007225 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07007226 case AUDIO_STREAM_MUSIC:
François Gaffiec005e562018-11-06 15:04:49 +01007227 checkOutputForAttributes(attributes_initializer(AUDIO_USAGE_NOTIFICATION));
Eric Laurente552edb2014-03-10 17:42:56 -07007228 updateDevicesAndOutputs();
7229 break;
7230 default:
7231 break;
7232 }
7233}
7234
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007235uint32_t AudioPolicyManager::handleEventForBeacon(int event) {
Eric Laurent9459fb02015-08-12 18:36:32 -07007236
7237 // skip beacon mute management if a dedicated TTS output is available
7238 if (mTtsOutputAvailable) {
7239 return 0;
7240 }
7241
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007242 switch(event) {
7243 case STARTING_OUTPUT:
7244 mBeaconMuteRefCount++;
7245 break;
7246 case STOPPING_OUTPUT:
7247 if (mBeaconMuteRefCount > 0) {
7248 mBeaconMuteRefCount--;
7249 }
7250 break;
7251 case STARTING_BEACON:
7252 mBeaconPlayingRefCount++;
7253 break;
7254 case STOPPING_BEACON:
7255 if (mBeaconPlayingRefCount > 0) {
7256 mBeaconPlayingRefCount--;
7257 }
7258 break;
7259 }
7260
7261 if (mBeaconMuteRefCount > 0) {
7262 // any playback causes beacon to be muted
7263 return setBeaconMute(true);
7264 } else {
7265 // no other playback: unmute when beacon starts playing, mute when it stops
7266 return setBeaconMute(mBeaconPlayingRefCount == 0);
7267 }
7268}
7269
7270uint32_t AudioPolicyManager::setBeaconMute(bool mute) {
7271 ALOGV("setBeaconMute(%d) mBeaconMuteRefCount=%d mBeaconPlayingRefCount=%d",
7272 mute, mBeaconMuteRefCount, mBeaconPlayingRefCount);
7273 // keep track of muted state to avoid repeating mute/unmute operations
7274 if (mBeaconMuted != mute) {
7275 // mute/unmute AUDIO_STREAM_TTS on all outputs
7276 ALOGV("\t muting %d", mute);
7277 uint32_t maxLatency = 0;
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007278 auto ttsVolumeSource = toVolumeSource(AUDIO_STREAM_TTS, false);
7279 if (ttsVolumeSource == VOLUME_SOURCE_NONE) {
7280 ALOGV("\t no tts volume source available");
7281 return 0;
7282 }
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007283 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07007284 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
jiabin9a3361e2019-10-01 09:38:30 -07007285 setVolumeSourceMute(ttsVolumeSource, mute/*on*/, desc, 0 /*delay*/, DeviceTypeSet());
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007286 const uint32_t latency = desc->latency() * 2;
Eric Laurentcdb2b352020-07-23 10:57:02 -07007287 if (desc->isActive(latency * 2) && latency > maxLatency) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007288 maxLatency = latency;
7289 }
7290 }
7291 mBeaconMuted = mute;
7292 return maxLatency;
7293 }
7294 return 0;
7295}
7296
Eric Laurente0720872014-03-11 09:30:41 -07007297void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07007298{
François Gaffiec005e562018-11-06 15:04:49 +01007299 mEngine->updateDeviceSelectionCache();
Eric Laurente552edb2014-03-10 17:42:56 -07007300 mPreviousOutputs = mOutputs;
7301}
7302
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07007303uint32_t AudioPolicyManager::checkDeviceMuteStrategies(const sp<AudioOutputDescriptor>& outputDesc,
François Gaffiec005e562018-11-06 15:04:49 +01007304 const DeviceVector &prevDevices,
Eric Laurente552edb2014-03-10 17:42:56 -07007305 uint32_t delayMs)
7306{
7307 // mute/unmute strategies using an incompatible device combination
7308 // if muting, wait for the audio in pcm buffer to be drained before proceeding
7309 // if unmuting, unmute only after the specified delay
7310 if (outputDesc->isDuplicated()) {
7311 return 0;
7312 }
7313
7314 uint32_t muteWaitMs = 0;
François Gaffiec005e562018-11-06 15:04:49 +01007315 DeviceVector devices = outputDesc->devices();
7316 bool shouldMute = outputDesc->isActive() && (devices.size() >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07007317
François Gaffiec005e562018-11-06 15:04:49 +01007318 auto productStrategies = mEngine->getOrderedProductStrategies();
7319 for (const auto &productStrategy : productStrategies) {
7320 auto attributes = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
7321 DeviceVector curDevices =
7322 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false/*fromCache*/);
7323 curDevices = curDevices.filter(outputDesc->supportedDevices());
7324 bool mute = shouldMute && curDevices.containsAtLeastOne(devices) && curDevices != devices;
Eric Laurente552edb2014-03-10 17:42:56 -07007325 bool doMute = false;
7326
François Gaffiec005e562018-11-06 15:04:49 +01007327 if (mute && !outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07007328 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01007329 outputDesc->setStrategyMutedByDevice(productStrategy, true);
7330 } else if (!mute && outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07007331 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01007332 outputDesc->setStrategyMutedByDevice(productStrategy, false);
Eric Laurente552edb2014-03-10 17:42:56 -07007333 }
Eric Laurent99401132014-05-07 19:48:15 -07007334 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07007335 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07007336 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07007337 // skip output if it does not share any device with current output
François Gaffie11d30102018-11-02 16:09:09 +01007338 if (!desc->supportedDevices().containsAtLeastOne(outputDesc->supportedDevices())) {
Eric Laurente552edb2014-03-10 17:42:56 -07007339 continue;
7340 }
François Gaffiec005e562018-11-06 15:04:49 +01007341 ALOGVV("%s() %s (curDevice %s)", __func__,
7342 mute ? "muting" : "unmuting", curDevices.toString().c_str());
7343 setStrategyMute(productStrategy, mute, desc, mute ? 0 : delayMs);
7344 if (desc->isStrategyActive(productStrategy)) {
Eric Laurent99401132014-05-07 19:48:15 -07007345 if (mute) {
7346 // FIXME: should not need to double latency if volume could be applied
7347 // immediately by the audioflinger mixer. We must account for the delay
7348 // between now and the next time the audioflinger thread for this output
7349 // will process a buffer (which corresponds to one buffer size,
7350 // usually 1/2 or 1/4 of the latency).
7351 if (muteWaitMs < desc->latency() * 2) {
7352 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07007353 }
7354 }
7355 }
7356 }
7357 }
7358 }
7359
Eric Laurent99401132014-05-07 19:48:15 -07007360 // temporary mute output if device selection changes to avoid volume bursts due to
7361 // different per device volumes
François Gaffiec005e562018-11-06 15:04:49 +01007362 if (outputDesc->isActive() && (devices != prevDevices)) {
Eric Laurentdc462862016-07-19 12:29:53 -07007363 uint32_t tempMuteWaitMs = outputDesc->latency() * 2;
Jasmine Chaf6074fe2021-08-17 13:44:31 +08007364
Eric Laurentdc462862016-07-19 12:29:53 -07007365 if (muteWaitMs < tempMuteWaitMs) {
7366 muteWaitMs = tempMuteWaitMs;
Eric Laurent99401132014-05-07 19:48:15 -07007367 }
Jasmine Chaf6074fe2021-08-17 13:44:31 +08007368
7369 // If recommended duration is defined, replace temporary mute duration to avoid
7370 // truncated notifications at beginning, which depends on duration of changing path in HAL.
7371 // Otherwise, temporary mute duration is conservatively set to 4 times the reported latency.
7372 uint32_t tempRecommendedMuteDuration = outputDesc->getRecommendedMuteDurationMs();
7373 uint32_t tempMuteDurationMs = tempRecommendedMuteDuration > 0 ?
7374 tempRecommendedMuteDuration : outputDesc->latency() * 4;
7375
François Gaffieaaac0fd2018-11-22 17:56:39 +01007376 for (const auto &activeVs : outputDesc->getActiveVolumeSources()) {
7377 // make sure that we do not start the temporary mute period too early in case of
7378 // delayed device change
7379 setVolumeSourceMute(activeVs, true, outputDesc, delayMs);
7380 setVolumeSourceMute(activeVs, false, outputDesc, delayMs + tempMuteDurationMs,
François Gaffiec005e562018-11-06 15:04:49 +01007381 devices.types());
Eric Laurent99401132014-05-07 19:48:15 -07007382 }
7383 }
7384
Eric Laurente552edb2014-03-10 17:42:56 -07007385 // wait for the PCM output buffers to empty before proceeding with the rest of the command
7386 if (muteWaitMs > delayMs) {
7387 muteWaitMs -= delayMs;
7388 usleep(muteWaitMs * 1000);
7389 return muteWaitMs;
7390 }
7391 return 0;
7392}
7393
François Gaffie11d30102018-11-02 16:09:09 +01007394uint32_t AudioPolicyManager::setOutputDevices(const sp<SwAudioOutputDescriptor>& outputDesc,
7395 const DeviceVector &devices,
7396 bool force,
7397 int delayMs,
7398 audio_patch_handle_t *patchHandle,
Oscar Azucena6acf34b2023-04-27 16:32:09 -07007399 bool requiresMuteCheck, bool requiresVolumeCheck,
7400 bool skipMuteDelay)
Eric Laurente552edb2014-03-10 17:42:56 -07007401{
jiabin3ff8d7d2022-12-13 06:27:44 +00007402 // TODO(b/262404095): Consider if the output need to be reopened.
François Gaffie11d30102018-11-02 16:09:09 +01007403 ALOGV("%s device %s delayMs %d", __func__, devices.toString().c_str(), delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07007404 uint32_t muteWaitMs;
7405
7406 if (outputDesc->isDuplicated()) {
François Gaffie11d30102018-11-02 16:09:09 +01007407 muteWaitMs = setOutputDevices(outputDesc->subOutput1(), devices, force, delayMs,
Oscar Azucena6acf34b2023-04-27 16:32:09 -07007408 nullptr /* patchHandle */, requiresMuteCheck, skipMuteDelay);
François Gaffie11d30102018-11-02 16:09:09 +01007409 muteWaitMs += setOutputDevices(outputDesc->subOutput2(), devices, force, delayMs,
Oscar Azucena6acf34b2023-04-27 16:32:09 -07007410 nullptr /* patchHandle */, requiresMuteCheck, skipMuteDelay);
Eric Laurente552edb2014-03-10 17:42:56 -07007411 return muteWaitMs;
7412 }
Eric Laurente552edb2014-03-10 17:42:56 -07007413
7414 // filter devices according to output selected
Francois Gaffie716e1432019-01-14 16:58:59 +01007415 DeviceVector filteredDevices = outputDesc->filterSupportedDevices(devices);
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01007416 DeviceVector prevDevices = outputDesc->devices();
Francois Gaffie3523ab32021-06-22 13:24:34 +02007417 DeviceVector availPrevDevices = mAvailableOutputDevices.filter(prevDevices);
Eric Laurente552edb2014-03-10 17:42:56 -07007418
François Gaffie11d30102018-11-02 16:09:09 +01007419 ALOGV("setOutputDevices() prevDevice %s", prevDevices.toString().c_str());
7420
7421 if (!filteredDevices.isEmpty()) {
7422 outputDesc->setDevices(filteredDevices);
Eric Laurente552edb2014-03-10 17:42:56 -07007423 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00007424
7425 // if the outputs are not materially active, there is no need to mute.
7426 if (requiresMuteCheck) {
François Gaffiec005e562018-11-06 15:04:49 +01007427 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevices, delayMs);
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00007428 } else {
7429 ALOGV("%s: suppressing checkDeviceMuteStrategies", __func__);
7430 muteWaitMs = 0;
7431 }
Eric Laurente552edb2014-03-10 17:42:56 -07007432
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02007433 bool outputRouted = outputDesc->isRouted();
7434
Eric Laurent79ea9582020-06-11 18:49:24 -07007435 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
7436 // output profile or if new device is not supported AND previous device(s) is(are) still
7437 // available (otherwise reset device must be done on the output)
Francois Gaffie3523ab32021-06-22 13:24:34 +02007438 if (!devices.isEmpty() && filteredDevices.isEmpty() && !availPrevDevices.empty()) {
Eric Laurent79ea9582020-06-11 18:49:24 -07007439 ALOGV("%s: unsupported device %s for output", __func__, devices.toString().c_str());
7440 // restore previous device after evaluating strategy mute state
7441 outputDesc->setDevices(prevDevices);
7442 return muteWaitMs;
7443 }
7444
Eric Laurente552edb2014-03-10 17:42:56 -07007445 // Do not change the routing if:
Eric Laurentb80a2a82014-10-27 16:07:59 -07007446 // the requested device is AUDIO_DEVICE_NONE
7447 // OR the requested device is the same as current device
7448 // AND force is not specified
7449 // AND the output is connected by a valid audio patch.
François Gaffie11d30102018-11-02 16:09:09 +01007450 // Doing this check here allows the caller to call setOutputDevices() without conditions
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02007451 if ((filteredDevices.isEmpty() || filteredDevices == prevDevices) && !force && outputRouted) {
François Gaffie11d30102018-11-02 16:09:09 +01007452 ALOGV("%s setting same device %s or null device, force=%d, patch handle=%d", __func__,
7453 filteredDevices.toString().c_str(), force, outputDesc->getPatchHandle());
Francois Gaffie3523ab32021-06-22 13:24:34 +02007454 if (requiresVolumeCheck && !filteredDevices.isEmpty()) {
7455 ALOGV("%s setting same device on routed output, force apply volumes", __func__);
7456 applyStreamVolumes(outputDesc, filteredDevices.types(), delayMs, true /*force*/);
7457 }
Eric Laurente552edb2014-03-10 17:42:56 -07007458 return muteWaitMs;
7459 }
7460
François Gaffie11d30102018-11-02 16:09:09 +01007461 ALOGV("%s changing device to %s", __func__, filteredDevices.toString().c_str());
Eric Laurent1c333e22014-05-20 10:48:17 -07007462
Eric Laurente552edb2014-03-10 17:42:56 -07007463 // do the routing
Francois Gaffie3523ab32021-06-22 13:24:34 +02007464 if (filteredDevices.isEmpty() || mAvailableOutputDevices.filter(filteredDevices).empty()) {
Eric Laurentc75307b2015-03-17 15:29:32 -07007465 resetOutputDevice(outputDesc, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07007466 } else {
François Gaffie11d30102018-11-02 16:09:09 +01007467 PatchBuilder patchBuilder;
7468 patchBuilder.addSource(outputDesc);
7469 ALOG_ASSERT(filteredDevices.size() <= AUDIO_PATCH_PORTS_MAX, "Too many sink ports");
7470 for (const auto &filteredDevice : filteredDevices) {
7471 patchBuilder.addSink(filteredDevice);
Eric Laurentc40d9692016-04-13 19:14:13 -07007472 }
7473
Jasmine Cha7f82d1a2020-03-16 13:21:47 +08007474 // Add half reported latency to delayMs when muteWaitMs is null in order
7475 // to avoid disordered sequence of muting volume and changing devices.
Oscar Azucena6acf34b2023-04-27 16:32:09 -07007476 int actualDelayMs = !skipMuteDelay && muteWaitMs == 0
7477 ? (delayMs + (outputDesc->latency() / 2)) : delayMs;
7478 installPatch(__func__, patchHandle, outputDesc.get(), patchBuilder.patch(), actualDelayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07007479 }
Eric Laurente552edb2014-03-10 17:42:56 -07007480
Oscar Azucena6acf34b2023-04-27 16:32:09 -07007481 // Since the mute is skip, also skip the apply stream volume as that will be applied externally
7482 if (!skipMuteDelay) {
7483 // update stream volumes according to new device
7484 applyStreamVolumes(outputDesc, filteredDevices.types(), delayMs);
7485 }
Eric Laurente552edb2014-03-10 17:42:56 -07007486
7487 return muteWaitMs;
7488}
7489
Eric Laurentc75307b2015-03-17 15:29:32 -07007490status_t AudioPolicyManager::resetOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurent6a94d692014-05-20 11:18:06 -07007491 int delayMs,
7492 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07007493{
Eric Laurent6a94d692014-05-20 11:18:06 -07007494 ssize_t index;
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02007495 if (patchHandle == nullptr && !outputDesc->isRouted()) {
7496 return INVALID_OPERATION;
7497 }
Eric Laurent6a94d692014-05-20 11:18:06 -07007498 if (patchHandle) {
7499 index = mAudioPatches.indexOfKey(*patchHandle);
7500 } else {
Jean-Michel Triviff155c62016-02-26 12:07:16 -08007501 index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007502 }
7503 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07007504 return INVALID_OPERATION;
7505 }
Eric Laurent6a94d692014-05-20 11:18:06 -07007506 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007507 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07007508 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07007509 outputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
François Gaffieafd4cea2019-11-18 15:50:22 +01007510 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007511 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07007512 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07007513 return status;
7514}
7515
7516status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
François Gaffie11d30102018-11-02 16:09:09 +01007517 const sp<DeviceDescriptor> &device,
Eric Laurent6a94d692014-05-20 11:18:06 -07007518 bool force,
7519 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07007520{
7521 status_t status = NO_ERROR;
7522
Eric Laurent1f2f2232014-06-02 12:01:23 -07007523 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
François Gaffie11d30102018-11-02 16:09:09 +01007524 if ((device != nullptr) && ((device != inputDesc->getDevice()) || force)) {
7525 inputDesc->setDevice(device);
Eric Laurent1c333e22014-05-20 10:48:17 -07007526
François Gaffie11d30102018-11-02 16:09:09 +01007527 if (mAvailableInputDevices.contains(device)) {
Mikhail Naganovdc769682018-05-04 15:34:08 -07007528 PatchBuilder patchBuilder;
7529 patchBuilder.addSink(inputDesc,
Eric Laurentdaf92cc2014-07-22 15:36:10 -07007530 // AUDIO_SOURCE_HOTWORD is for internal use only:
7531 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
Mikhail Naganovdc769682018-05-04 15:34:08 -07007532 [inputDesc](const PatchBuilder::mix_usecase_t& usecase) {
7533 auto result = usecase;
7534 if (result.source == AUDIO_SOURCE_HOTWORD && !inputDesc->isSoundTrigger()) {
7535 result.source = AUDIO_SOURCE_VOICE_RECOGNITION;
7536 }
7537 return result; }).
Eric Laurent1c333e22014-05-20 10:48:17 -07007538 //only one input device for now
François Gaffie11d30102018-11-02 16:09:09 +01007539 addSource(device);
Mikhail Naganovdc769682018-05-04 15:34:08 -07007540 status = installPatch(__func__, patchHandle, inputDesc.get(), patchBuilder.patch(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07007541 }
7542 }
7543 return status;
7544}
7545
Eric Laurent6a94d692014-05-20 11:18:06 -07007546status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
7547 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07007548{
Eric Laurent1f2f2232014-06-02 12:01:23 -07007549 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07007550 ssize_t index;
7551 if (patchHandle) {
7552 index = mAudioPatches.indexOfKey(*patchHandle);
7553 } else {
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08007554 index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007555 }
7556 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07007557 return INVALID_OPERATION;
7558 }
Eric Laurent6a94d692014-05-20 11:18:06 -07007559 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007560 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07007561 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07007562 inputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
François Gaffieafd4cea2019-11-18 15:50:22 +01007563 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007564 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07007565 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07007566 return status;
7567}
7568
François Gaffie11d30102018-11-02 16:09:09 +01007569sp<IOProfile> AudioPolicyManager::getInputProfile(const sp<DeviceDescriptor> &device,
François Gaffie53615e22015-03-19 09:24:12 +01007570 uint32_t& samplingRate,
Andy Hungf129b032015-04-07 13:45:50 -07007571 audio_format_t& format,
7572 audio_channel_mask_t& channelMask,
François Gaffie53615e22015-03-19 09:24:12 +01007573 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07007574{
7575 // Choose an input profile based on the requested capture parameters: select the first available
7576 // profile supporting all requested parameters.
jiabin2fd710d2022-05-02 23:20:22 +00007577 // The flags can be ignored if it doesn't contain a much match flag.
Andy Hungf129b032015-04-07 13:45:50 -07007578 //
7579 // TODO: perhaps isCompatibleProfile should return a "matching" score so we can return
7580 // the best matching profile, not the first one.
Eric Laurente552edb2014-03-10 17:42:56 -07007581
Atneya Nair0f0a8032022-12-12 16:20:12 -08007582 using underlying_input_flag_t = std::underlying_type_t<audio_input_flags_t>;
7583 const underlying_input_flag_t mustMatchFlag = AUDIO_INPUT_FLAG_MMAP_NOIRQ |
7584 AUDIO_INPUT_FLAG_HOTWORD_TAP | AUDIO_INPUT_FLAG_HW_LOOKBACK;
7585
7586 const underlying_input_flag_t oriFlags = flags;
Glenn Kasten730b9262018-03-29 15:01:26 -07007587
jiabin2fd710d2022-05-02 23:20:22 +00007588 for (;;) {
7589 sp<IOProfile> firstInexact = nullptr;
7590 uint32_t updatedSamplingRate = 0;
7591 audio_format_t updatedFormat = AUDIO_FORMAT_INVALID;
7592 audio_channel_mask_t updatedChannelMask = AUDIO_CHANNEL_INVALID;
7593 for (const auto& hwModule : mHwModules) {
7594 for (const auto& profile : hwModule->getInputProfiles()) {
7595 // profile->log();
7596 //updatedFormat = format;
7597 if (profile->isCompatibleProfile(DeviceVector(device), samplingRate,
7598 &samplingRate /*updatedSamplingRate*/,
7599 format,
7600 &format, /*updatedFormat*/
7601 channelMask,
7602 &channelMask /*updatedChannelMask*/,
7603 // FIXME ugly cast
7604 (audio_output_flags_t) flags,
7605 true /*exactMatchRequiredForInputFlags*/)) {
7606 return profile;
7607 }
7608 if (firstInexact == nullptr && profile->isCompatibleProfile(DeviceVector(device),
7609 samplingRate,
7610 &updatedSamplingRate,
7611 format,
7612 &updatedFormat,
7613 channelMask,
7614 &updatedChannelMask,
7615 // FIXME ugly cast
7616 (audio_output_flags_t) flags,
7617 false /*exactMatchRequiredForInputFlags*/)) {
7618 firstInexact = profile;
7619 }
7620 }
7621 }
7622
7623 if (firstInexact != nullptr) {
7624 samplingRate = updatedSamplingRate;
7625 format = updatedFormat;
7626 channelMask = updatedChannelMask;
7627 return firstInexact;
7628 } else if (flags & AUDIO_INPUT_FLAG_RAW) {
7629 flags = (audio_input_flags_t) (flags & ~AUDIO_INPUT_FLAG_RAW); // retry
7630 } else if ((flags & mustMatchFlag) == AUDIO_INPUT_FLAG_NONE &&
7631 flags != AUDIO_INPUT_FLAG_NONE && audio_is_linear_pcm(format)) {
7632 flags = AUDIO_INPUT_FLAG_NONE;
7633 } else { // fail
7634 ALOGW("%s could not find profile for device %s, sampling rate %u, format %#x, "
7635 "channel mask 0x%X, flags %#x", __func__, device->toString().c_str(),
7636 samplingRate, format, channelMask, oriFlags);
7637 break;
Eric Laurente552edb2014-03-10 17:42:56 -07007638 }
7639 }
jiabin2fd710d2022-05-02 23:20:22 +00007640
7641 return nullptr;
Eric Laurente552edb2014-03-10 17:42:56 -07007642}
7643
François Gaffieaaac0fd2018-11-22 17:56:39 +01007644float AudioPolicyManager::computeVolume(IVolumeCurves &curves,
7645 VolumeSource volumeSource,
François Gaffied1ab2bd2015-12-02 18:20:06 +01007646 int index,
jiabin9a3361e2019-10-01 09:38:30 -07007647 const DeviceTypeSet& deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07007648{
jiabin9a3361e2019-10-01 09:38:30 -07007649 float volumeDb = curves.volIndexToDb(Volume::getDeviceCategory(deviceTypes), index);
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07007650
7651 // handle the case of accessibility active while a ringtone is playing: if the ringtone is much
7652 // louder than the accessibility prompt, the prompt cannot be heard, thus masking the touch
7653 // exploration of the dialer UI. In this situation, bring the accessibility volume closer to
7654 // the ringtone volume
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007655 const auto callVolumeSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL, false);
7656 const auto ringVolumeSrc = toVolumeSource(AUDIO_STREAM_RING, false);
7657 const auto musicVolumeSrc = toVolumeSource(AUDIO_STREAM_MUSIC, false);
7658 const auto alarmVolumeSrc = toVolumeSource(AUDIO_STREAM_ALARM, false);
7659 const auto a11yVolumeSrc = toVolumeSource(AUDIO_STREAM_ACCESSIBILITY, false);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007660
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07007661 if (volumeSource == a11yVolumeSrc
François Gaffieaaac0fd2018-11-22 17:56:39 +01007662 && (AUDIO_MODE_RINGTONE == mEngine->getPhoneState()) &&
7663 mOutputs.isActive(ringVolumeSrc, 0)) {
7664 auto &ringCurves = getVolumeCurves(AUDIO_STREAM_RING);
jiabin9a3361e2019-10-01 09:38:30 -07007665 const float ringVolumeDb = computeVolume(ringCurves, ringVolumeSrc, index, deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007666 return ringVolumeDb - 4 > volumeDb ? ringVolumeDb - 4 : volumeDb;
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07007667 }
7668
Eric Laurentdcd4ab12018-06-29 17:45:13 -07007669 // in-call: always cap volume by voice volume + some low headroom
François Gaffieaaac0fd2018-11-22 17:56:39 +01007670 if ((volumeSource != callVolumeSrc && (isInCall() ||
7671 mOutputs.isActiveLocally(callVolumeSrc))) &&
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007672 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM, false) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01007673 volumeSource == ringVolumeSrc || volumeSource == musicVolumeSrc ||
7674 volumeSource == alarmVolumeSrc ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007675 volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION, false) ||
7676 volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false) ||
7677 volumeSource == toVolumeSource(AUDIO_STREAM_DTMF, false) ||
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07007678 volumeSource == a11yVolumeSrc)) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007679 auto &voiceCurves = getVolumeCurves(callVolumeSrc);
jiabin9a3361e2019-10-01 09:38:30 -07007680 int voiceVolumeIndex = voiceCurves.getVolumeIndex(deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007681 const float maxVoiceVolDb =
jiabin9a3361e2019-10-01 09:38:30 -07007682 computeVolume(voiceCurves, callVolumeSrc, voiceVolumeIndex, deviceTypes)
Eric Laurent7731b5a2018-04-06 15:47:22 -07007683 + IN_CALL_EARPIECE_HEADROOM_DB;
Abhijith Shastry329ddab2019-04-23 11:53:26 -07007684 // FIXME: Workaround for call screening applications until a proper audio mode is defined
7685 // to support this scenario : Exempt the RING stream from the audio cap if the audio was
7686 // programmatically muted.
7687 // VOICE_CALL stream has minVolumeIndex > 0 : Users cannot set the volume of voice calls to
7688 // 0. We don't want to cap volume when the system has programmatically muted the voice call
7689 // stream. See setVolumeCurveIndex() for more information.
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07007690 bool exemptFromCapping =
7691 ((volumeSource == ringVolumeSrc) || (volumeSource == a11yVolumeSrc))
7692 && (voiceVolumeIndex == 0);
Abhijith Shastry329ddab2019-04-23 11:53:26 -07007693 ALOGV_IF(exemptFromCapping, "%s volume source %d at vol=%f not capped", __func__,
7694 volumeSource, volumeDb);
7695 if ((volumeDb > maxVoiceVolDb) && !exemptFromCapping) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007696 ALOGV("%s volume source %d at vol=%f overriden by volume group %d at vol=%f", __func__,
7697 volumeSource, volumeDb, callVolumeSrc, maxVoiceVolDb);
7698 volumeDb = maxVoiceVolDb;
Jean-Michel Trivi719a9872017-08-05 13:51:35 -07007699 }
7700 }
Eric Laurente552edb2014-03-10 17:42:56 -07007701 // if a headset is connected, apply the following rules to ring tones and notifications
7702 // to avoid sound level bursts in user's ears:
Eric Laurent6af1c1d2016-04-14 11:20:44 -07007703 // - always attenuate notifications volume by 6dB
7704 // - attenuate ring tones volume by 6dB unless music is not playing and
7705 // speaker is part of the select devices
Eric Laurente552edb2014-03-10 17:42:56 -07007706 // - if music is playing, always limit the volume to current music volume,
7707 // with a minimum threshold at -36dB so that notification is always perceived.
jiabin9a3361e2019-10-01 09:38:30 -07007708 if (!Intersection(deviceTypes,
7709 {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP, AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES,
7710 AUDIO_DEVICE_OUT_WIRED_HEADSET, AUDIO_DEVICE_OUT_WIRED_HEADPHONE,
Eric Laurentc42df452020-08-07 10:51:53 -07007711 AUDIO_DEVICE_OUT_USB_HEADSET, AUDIO_DEVICE_OUT_HEARING_AID,
7712 AUDIO_DEVICE_OUT_BLE_HEADSET}).empty() &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01007713 ((volumeSource == alarmVolumeSrc ||
7714 volumeSource == ringVolumeSrc) ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007715 (volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION, false)) ||
7716 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM, false)) ||
7717 ((volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false)) &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01007718 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) &&
7719 curves.canBeMuted()) {
7720
Eric Laurente552edb2014-03-10 17:42:56 -07007721 // when the phone is ringing we must consider that music could have been paused just before
7722 // by the music application and behave as if music was active if the last music track was
7723 // just stopped
Eric Laurent3b73df72014-03-11 09:06:29 -07007724 if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY) ||
Eric Laurente552edb2014-03-10 17:42:56 -07007725 mLimitRingtoneVolume) {
François Gaffie43c73442018-11-08 08:21:55 +01007726 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
jiabin9a3361e2019-10-01 09:38:30 -07007727 DeviceTypeSet musicDevice =
François Gaffiec005e562018-11-06 15:04:49 +01007728 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
7729 nullptr, true /*fromCache*/).types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01007730 auto &musicCurves = getVolumeCurves(AUDIO_STREAM_MUSIC);
jiabin9a3361e2019-10-01 09:38:30 -07007731 float musicVolDb = computeVolume(musicCurves,
7732 musicVolumeSrc,
7733 musicCurves.getVolumeIndex(musicDevice),
7734 musicDevice);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007735 float minVolDb = (musicVolDb > SONIFICATION_HEADSET_VOLUME_MIN_DB) ?
7736 musicVolDb : SONIFICATION_HEADSET_VOLUME_MIN_DB;
7737 if (volumeDb > minVolDb) {
7738 volumeDb = minVolDb;
7739 ALOGV("computeVolume limiting volume to %f musicVol %f", minVolDb, musicVolDb);
Eric Laurente552edb2014-03-10 17:42:56 -07007740 }
Eric Laurent7b6385c2021-05-12 17:55:36 +02007741 if (Volume::getDeviceForVolume(deviceTypes) != AUDIO_DEVICE_OUT_SPEAKER
7742 && !Intersection(deviceTypes, {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP,
7743 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES}).empty()) {
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07007744 // on A2DP, also ensure notification volume is not too low compared to media when
7745 // intended to be played
François Gaffie43c73442018-11-08 08:21:55 +01007746 if ((volumeDb > -96.0f) &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01007747 (musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB > volumeDb)) {
jiabin9a3361e2019-10-01 09:38:30 -07007748 ALOGV("%s increasing volume for volume source=%d device=%s from %f to %f",
7749 __func__, volumeSource, dumpDeviceTypes(deviceTypes).c_str(), volumeDb,
François Gaffieaaac0fd2018-11-22 17:56:39 +01007750 musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB);
7751 volumeDb = musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB;
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07007752 }
7753 }
jiabin9a3361e2019-10-01 09:38:30 -07007754 } else if ((Volume::getDeviceForVolume(deviceTypes) != AUDIO_DEVICE_OUT_SPEAKER) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01007755 (!(volumeSource == alarmVolumeSrc || volumeSource == ringVolumeSrc))) {
François Gaffie43c73442018-11-08 08:21:55 +01007756 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07007757 }
7758 }
7759
François Gaffie43c73442018-11-08 08:21:55 +01007760 return volumeDb;
Eric Laurente552edb2014-03-10 17:42:56 -07007761}
7762
Eric Laurent3839bc02018-07-10 18:33:34 -07007763int AudioPolicyManager::rescaleVolumeIndex(int srcIndex,
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01007764 VolumeSource fromVolumeSource,
7765 VolumeSource toVolumeSource)
Eric Laurent3839bc02018-07-10 18:33:34 -07007766{
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01007767 if (fromVolumeSource == toVolumeSource) {
Eric Laurent3839bc02018-07-10 18:33:34 -07007768 return srcIndex;
7769 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01007770 auto &srcCurves = getVolumeCurves(fromVolumeSource);
7771 auto &dstCurves = getVolumeCurves(toVolumeSource);
Eric Laurentf5aa58d2019-02-22 18:20:11 -08007772 float minSrc = (float)srcCurves.getVolumeIndexMin();
7773 float maxSrc = (float)srcCurves.getVolumeIndexMax();
7774 float minDst = (float)dstCurves.getVolumeIndexMin();
7775 float maxDst = (float)dstCurves.getVolumeIndexMax();
Eric Laurent3839bc02018-07-10 18:33:34 -07007776
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08007777 // preserve mute request or correct range
7778 if (srcIndex < minSrc) {
7779 if (srcIndex == 0) {
7780 return 0;
7781 }
7782 srcIndex = minSrc;
7783 } else if (srcIndex > maxSrc) {
7784 srcIndex = maxSrc;
7785 }
Eric Laurent3839bc02018-07-10 18:33:34 -07007786 return (int)(minDst + ((srcIndex - minSrc) * (maxDst - minDst)) / (maxSrc - minSrc));
7787}
7788
François Gaffieaaac0fd2018-11-22 17:56:39 +01007789status_t AudioPolicyManager::checkAndSetVolume(IVolumeCurves &curves,
7790 VolumeSource volumeSource,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08007791 int index,
7792 const sp<AudioOutputDescriptor>& outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07007793 DeviceTypeSet deviceTypes,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08007794 int delayMs,
7795 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07007796{
François Gaffieaaac0fd2018-11-22 17:56:39 +01007797 // do not change actual attributes volume if the attributes is muted
7798 if (outputDesc->isMuted(volumeSource)) {
7799 ALOGVV("%s: volume source %d muted count %d active=%d", __func__, volumeSource,
7800 outputDesc->getMuteCount(volumeSource), outputDesc->isActive(volumeSource));
Eric Laurente552edb2014-03-10 17:42:56 -07007801 return NO_ERROR;
7802 }
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007803 VolumeSource callVolSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL, false);
7804 VolumeSource btScoVolSrc = toVolumeSource(AUDIO_STREAM_BLUETOOTH_SCO, false);
7805 bool isVoiceVolSrc = (volumeSource != VOLUME_SOURCE_NONE) && (callVolSrc == volumeSource);
7806 bool isBtScoVolSrc = (volumeSource != VOLUME_SOURCE_NONE) && (btScoVolSrc == volumeSource);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007807
Eric Laurent2517af32020-11-25 15:31:27 +01007808 bool isScoRequested = isScoRequestedForComm();
Eric Laurent1a8b45f2022-04-13 16:01:47 +02007809 bool isHAUsed = isHearingAidUsedForComm();
7810
Eric Laurente552edb2014-03-10 17:42:56 -07007811 // do not change in call volume if bluetooth is connected and vice versa
François Gaffieaaac0fd2018-11-22 17:56:39 +01007812 // if sco and call follow same curves, bypass forceUseForComm
7813 if ((callVolSrc != btScoVolSrc) &&
Eric Laurent2517af32020-11-25 15:31:27 +01007814 ((isVoiceVolSrc && isScoRequested) ||
Beibeif660a512023-02-28 17:00:34 +08007815 (isBtScoVolSrc && !(isScoRequested || isHAUsed))) &&
7816 !isSingleDeviceType(deviceTypes, AUDIO_DEVICE_OUT_TELEPHONY_TX)) {
Eric Laurent2517af32020-11-25 15:31:27 +01007817 ALOGV("%s cannot set volume group %d volume when is%srequested for comm", __func__,
Eric Laurent1a8b45f2022-04-13 16:01:47 +02007818 volumeSource, isScoRequested ? " " : " not ");
Eric Laurent571ef962020-07-24 11:43:48 -07007819 // Do not return an error here as AudioService will always set both voice call
7820 // and bluetooth SCO volumes due to stream aliasing.
7821 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07007822 }
jiabin9a3361e2019-10-01 09:38:30 -07007823 if (deviceTypes.empty()) {
7824 deviceTypes = outputDesc->devices().types();
Eric Laurentc75307b2015-03-17 15:29:32 -07007825 }
Eric Laurent275e8e92014-11-30 15:14:47 -08007826
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00007827 if (curves.getVolumeIndexMin() < 0 || curves.getVolumeIndexMax() < 0) {
7828 ALOGE("invalid volume index range");
7829 return BAD_VALUE;
7830 }
7831
jiabin9a3361e2019-10-01 09:38:30 -07007832 float volumeDb = computeVolume(curves, volumeSource, index, deviceTypes);
7833 if (outputDesc->isFixedVolume(deviceTypes) ||
Eric Laurent9698a4c2020-10-12 17:10:23 -07007834 // Force VoIP volume to max for bluetooth SCO device except if muted
7835 (index != 0 && (isVoiceVolSrc || isBtScoVolSrc) &&
jiabin9a3361e2019-10-01 09:38:30 -07007836 isSingleDeviceType(deviceTypes, audio_is_bluetooth_out_sco_device))) {
Eric Laurentffbc80f2015-03-18 18:30:19 -07007837 volumeDb = 0.0f;
Eric Laurent275e8e92014-11-30 15:14:47 -08007838 }
Francois Gaffie593634d2021-06-22 13:31:31 +02007839 const bool muted = (index == 0) && (volumeDb != 0.0f);
jiabin9a3361e2019-10-01 09:38:30 -07007840 outputDesc->setVolume(
Francois Gaffie593634d2021-06-22 13:31:31 +02007841 volumeDb, muted, volumeSource, curves.getStreamTypes(), deviceTypes, delayMs, force);
Eric Laurentc75307b2015-03-17 15:29:32 -07007842
Eric Laurente8f2c0f2021-08-17 11:17:19 +02007843 if (outputDesc == mPrimaryOutput && (isVoiceVolSrc || isBtScoVolSrc)) {
Eric Laurente552edb2014-03-10 17:42:56 -07007844 float voiceVolume;
Eric Laurentfad001d2019-06-11 19:17:57 -07007845 // 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 +01007846 if (isVoiceVolSrc) {
7847 voiceVolume = (float)index/(float)curves.getVolumeIndexMax();
Eric Laurente552edb2014-03-10 17:42:56 -07007848 } else {
Eric Laurentfad001d2019-06-11 19:17:57 -07007849 voiceVolume = index == 0 ? 0.0 : 1.0;
Eric Laurente552edb2014-03-10 17:42:56 -07007850 }
Eric Laurent18fba842016-03-31 14:41:26 -07007851 if (voiceVolume != mLastVoiceVolume) {
Eric Laurente552edb2014-03-10 17:42:56 -07007852 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
7853 mLastVoiceVolume = voiceVolume;
7854 }
7855 }
Eric Laurente552edb2014-03-10 17:42:56 -07007856 return NO_ERROR;
7857}
7858
Eric Laurentc75307b2015-03-17 15:29:32 -07007859void AudioPolicyManager::applyStreamVolumes(const sp<AudioOutputDescriptor>& outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07007860 const DeviceTypeSet& deviceTypes,
7861 int delayMs,
7862 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07007863{
jiabincd510522020-01-22 09:40:55 -08007864 ALOGVV("applyStreamVolumes() for device %s", dumpDeviceTypes(deviceTypes).c_str());
François Gaffieaaac0fd2018-11-22 17:56:39 +01007865 for (const auto &volumeGroup : mEngine->getVolumeGroups()) {
7866 auto &curves = getVolumeCurves(toVolumeSource(volumeGroup));
7867 checkAndSetVolume(curves, toVolumeSource(volumeGroup),
jiabin9a3361e2019-10-01 09:38:30 -07007868 curves.getVolumeIndex(deviceTypes),
7869 outputDesc, deviceTypes, delayMs, force);
Eric Laurente552edb2014-03-10 17:42:56 -07007870 }
7871}
7872
François Gaffiec005e562018-11-06 15:04:49 +01007873void AudioPolicyManager::setStrategyMute(product_strategy_t strategy,
7874 bool on,
7875 const sp<AudioOutputDescriptor>& outputDesc,
7876 int delayMs,
jiabin9a3361e2019-10-01 09:38:30 -07007877 DeviceTypeSet deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07007878{
François Gaffieaaac0fd2018-11-22 17:56:39 +01007879 std::vector<VolumeSource> sourcesToMute;
7880 for (auto attributes: mEngine->getAllAttributesForProductStrategy(strategy)) {
7881 ALOGVV("%s() attributes %s, mute %d, output ID %d", __func__,
7882 toString(attributes).c_str(), on, outputDesc->getId());
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007883 VolumeSource source = toVolumeSource(attributes, false);
7884 if ((source != VOLUME_SOURCE_NONE) &&
7885 (std::find(begin(sourcesToMute), end(sourcesToMute), source)
7886 == end(sourcesToMute))) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007887 sourcesToMute.push_back(source);
7888 }
Eric Laurente552edb2014-03-10 17:42:56 -07007889 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01007890 for (auto source : sourcesToMute) {
jiabin9a3361e2019-10-01 09:38:30 -07007891 setVolumeSourceMute(source, on, outputDesc, delayMs, deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007892 }
7893
Eric Laurente552edb2014-03-10 17:42:56 -07007894}
7895
François Gaffieaaac0fd2018-11-22 17:56:39 +01007896void AudioPolicyManager::setVolumeSourceMute(VolumeSource volumeSource,
7897 bool on,
7898 const sp<AudioOutputDescriptor>& outputDesc,
7899 int delayMs,
jiabin9a3361e2019-10-01 09:38:30 -07007900 DeviceTypeSet deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07007901{
jiabin9a3361e2019-10-01 09:38:30 -07007902 if (deviceTypes.empty()) {
7903 deviceTypes = outputDesc->devices().types();
Eric Laurente552edb2014-03-10 17:42:56 -07007904 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01007905 auto &curves = getVolumeCurves(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07007906 if (on) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007907 if (!outputDesc->isMuted(volumeSource)) {
Eric Laurentf5aa58d2019-02-22 18:20:11 -08007908 if (curves.canBeMuted() &&
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007909 (volumeSource != toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01007910 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) ==
7911 AUDIO_POLICY_FORCE_NONE))) {
jiabin9a3361e2019-10-01 09:38:30 -07007912 checkAndSetVolume(curves, volumeSource, 0, outputDesc, deviceTypes, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07007913 }
7914 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01007915 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not
7916 // ignored
7917 outputDesc->incMuteCount(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07007918 } else {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007919 if (!outputDesc->isMuted(volumeSource)) {
7920 ALOGV("%s unmuting non muted attributes!", __func__);
Eric Laurente552edb2014-03-10 17:42:56 -07007921 return;
7922 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01007923 if (outputDesc->decMuteCount(volumeSource) == 0) {
7924 checkAndSetVolume(curves, volumeSource,
jiabin9a3361e2019-10-01 09:38:30 -07007925 curves.getVolumeIndex(deviceTypes),
Eric Laurentc75307b2015-03-17 15:29:32 -07007926 outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07007927 deviceTypes,
Eric Laurente552edb2014-03-10 17:42:56 -07007928 delayMs);
7929 }
7930 }
7931}
7932
François Gaffie53615e22015-03-19 09:24:12 +01007933bool AudioPolicyManager::isValidAttributes(const audio_attributes_t *paa)
7934{
François Gaffiec005e562018-11-06 15:04:49 +01007935 // has flags that map to a stream type?
Eric Laurente83b55d2014-11-14 10:06:21 -08007936 if ((paa->flags & (AUDIO_FLAG_AUDIBILITY_ENFORCED | AUDIO_FLAG_SCO | AUDIO_FLAG_BEACON)) != 0) {
7937 return true;
7938 }
7939
7940 // has known usage?
7941 switch (paa->usage) {
7942 case AUDIO_USAGE_UNKNOWN:
7943 case AUDIO_USAGE_MEDIA:
7944 case AUDIO_USAGE_VOICE_COMMUNICATION:
7945 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
7946 case AUDIO_USAGE_ALARM:
7947 case AUDIO_USAGE_NOTIFICATION:
7948 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
7949 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
7950 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
7951 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
7952 case AUDIO_USAGE_NOTIFICATION_EVENT:
7953 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
7954 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
7955 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
7956 case AUDIO_USAGE_GAME:
Eric Laurent275e8e92014-11-30 15:14:47 -08007957 case AUDIO_USAGE_VIRTUAL_SOURCE:
Jean-Michel Trivi36867762016-12-29 12:03:28 -08007958 case AUDIO_USAGE_ASSISTANT:
Eric Laurent21777f82019-12-06 18:12:06 -08007959 case AUDIO_USAGE_CALL_ASSISTANT:
Hayden Gomes524159d2019-12-23 14:41:47 -08007960 case AUDIO_USAGE_EMERGENCY:
7961 case AUDIO_USAGE_SAFETY:
7962 case AUDIO_USAGE_VEHICLE_STATUS:
7963 case AUDIO_USAGE_ANNOUNCEMENT:
Eric Laurente83b55d2014-11-14 10:06:21 -08007964 break;
7965 default:
7966 return false;
7967 }
7968 return true;
7969}
7970
François Gaffie2110e042015-03-24 08:41:51 +01007971audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
7972{
7973 return mEngine->getForceUse(usage);
7974}
7975
Eric Laurent96d1dda2022-03-14 17:14:19 +01007976bool AudioPolicyManager::isInCall() const {
François Gaffie2110e042015-03-24 08:41:51 +01007977 return isStateInCall(mEngine->getPhoneState());
7978}
7979
Eric Laurent96d1dda2022-03-14 17:14:19 +01007980bool AudioPolicyManager::isStateInCall(int state) const {
François Gaffie2110e042015-03-24 08:41:51 +01007981 return is_state_in_call(state);
7982}
7983
Eric Laurentf9cccec2022-11-16 19:12:00 +01007984bool AudioPolicyManager::isCallAudioAccessible() const {
Eric Laurent74b71512019-11-06 17:21:57 -08007985 audio_mode_t mode = mEngine->getPhoneState();
7986 return (mode == AUDIO_MODE_IN_CALL)
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01007987 || (mode == AUDIO_MODE_CALL_SCREEN)
7988 || (mode == AUDIO_MODE_CALL_REDIRECT);
Eric Laurent74b71512019-11-06 17:21:57 -08007989}
7990
Eric Laurentf9cccec2022-11-16 19:12:00 +01007991bool AudioPolicyManager::isInCallOrScreening() const {
7992 audio_mode_t mode = mEngine->getPhoneState();
7993 return isStateInCall(mode) || mode == AUDIO_MODE_CALL_SCREEN;
7994}
7995
Eric Laurentd60560a2015-04-10 11:31:20 -07007996void AudioPolicyManager::cleanUpForDevice(const sp<DeviceDescriptor>& deviceDesc)
7997{
7998 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07007999 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008000 if (sourceDesc->isConnected() && (sourceDesc->srcDevice()->equals(deviceDesc) ||
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02008001 sourceDesc->sinkDevice()->equals(deviceDesc))
8002 && !isCallRxAudioSource(sourceDesc)) {
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008003 disconnectAudioSource(sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07008004 }
8005 }
8006
8007 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
8008 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
8009 bool release = false;
8010 for (size_t j = 0; j < patchDesc->mPatch.num_sources && !release; j++) {
8011 const struct audio_port_config *source = &patchDesc->mPatch.sources[j];
8012 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
8013 source->ext.device.type == deviceDesc->type()) {
8014 release = true;
8015 }
8016 }
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008017 const char *address = deviceDesc->address().c_str();
Eric Laurentd60560a2015-04-10 11:31:20 -07008018 for (size_t j = 0; j < patchDesc->mPatch.num_sinks && !release; j++) {
8019 const struct audio_port_config *sink = &patchDesc->mPatch.sinks[j];
8020 if (sink->type == AUDIO_PORT_TYPE_DEVICE &&
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008021 sink->ext.device.type == deviceDesc->type() &&
8022 (strnlen(address, AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0
8023 || strncmp(sink->ext.device.address, address,
8024 AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0)) {
Eric Laurentd60560a2015-04-10 11:31:20 -07008025 release = true;
8026 }
8027 }
8028 if (release) {
François Gaffieafd4cea2019-11-18 15:50:22 +01008029 ALOGV("%s releasing patch %u", __FUNCTION__, patchDesc->getHandle());
8030 releaseAudioPatch(patchDesc->getHandle(), patchDesc->getUid());
Eric Laurentd60560a2015-04-10 11:31:20 -07008031 }
8032 }
Francois Gaffie716e1432019-01-14 16:58:59 +01008033
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01008034 mInputs.clearSessionRoutesForDevice(deviceDesc);
8035
Francois Gaffie716e1432019-01-14 16:58:59 +01008036 mHwModules.cleanUpForDevice(deviceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07008037}
8038
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008039void AudioPolicyManager::modifySurroundFormats(
8040 const sp<DeviceDescriptor>& devDesc, FormatVector *formatsPtr) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008041 std::unordered_set<audio_format_t> enforcedSurround(
8042 devDesc->encodedFormats().begin(), devDesc->encodedFormats().end());
Mikhail Naganov100f0122018-11-29 11:22:16 -08008043 std::unordered_set<audio_format_t> allSurround; // A flat set of all known surround formats
Mikhail Naganov68e3f642023-04-28 13:06:32 -07008044 for (const auto& pair : mConfig->getSurroundFormats()) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008045 allSurround.insert(pair.first);
8046 for (const auto& subformat : pair.second) allSurround.insert(subformat);
8047 }
Phil Burk09bc4612016-02-24 15:58:15 -08008048
8049 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
8050 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Phil Burk0709b0a2016-03-31 12:54:57 -07008051 ALOGD("%s: forced use = %d", __FUNCTION__, forceUse);
Mikhail Naganov100f0122018-11-29 11:22:16 -08008052 // This is the resulting set of formats depending on the surround mode:
8053 // 'all surround' = allSurround
8054 // 'enforced surround' = enforcedSurround [may include IEC69137 which isn't raw surround fmt]
8055 // 'non-surround' = not in 'all surround' and not in 'enforced surround'
8056 // 'manual surround' = mManualSurroundFormats
8057 // AUTO: formats v 'enforced surround'
8058 // ALWAYS: formats v 'all surround' v 'enforced surround'
8059 // NEVER: formats ^ 'non-surround'
8060 // MANUAL: formats ^ ('non-surround' v 'manual surround' v (IEC69137 ^ 'enforced surround'))
Phil Burk09bc4612016-02-24 15:58:15 -08008061
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008062 std::unordered_set<audio_format_t> formatSet;
8063 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL
8064 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008065 // formatSet is (formats ^ 'non-surround')
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008066 for (auto formatIter = formatsPtr->begin(); formatIter != formatsPtr->end(); ++formatIter) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008067 if (allSurround.count(*formatIter) == 0 && enforcedSurround.count(*formatIter) == 0) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008068 formatSet.insert(*formatIter);
8069 }
8070 }
8071 } else {
8072 formatSet.insert(formatsPtr->begin(), formatsPtr->end());
8073 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08008074 formatsPtr->clear(); // Re-filled from the formatSet at the end.
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008075
jiabin81772902018-04-02 17:52:27 -07008076 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008077 formatSet.insert(mManualSurroundFormats.begin(), mManualSurroundFormats.end());
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008078 // Enable IEC61937 when in MANUAL mode if it's enforced for this device.
8079 if (enforcedSurround.count(AUDIO_FORMAT_IEC61937) != 0) {
8080 formatSet.insert(AUDIO_FORMAT_IEC61937);
Phil Burk09bc4612016-02-24 15:58:15 -08008081 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08008082 } else if (forceUse != AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) { // AUTO or ALWAYS
8083 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS) {
8084 formatSet.insert(allSurround.begin(), allSurround.end());
Phil Burk07ac1142016-03-25 13:39:29 -07008085 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08008086 formatSet.insert(enforcedSurround.begin(), enforcedSurround.end());
Phil Burk09bc4612016-02-24 15:58:15 -08008087 }
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008088 for (const auto& format : formatSet) {
jiabin06e4bab2019-07-29 10:13:34 -07008089 formatsPtr->push_back(format);
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008090 }
Phil Burk0709b0a2016-03-31 12:54:57 -07008091}
8092
jiabin06e4bab2019-07-29 10:13:34 -07008093void AudioPolicyManager::modifySurroundChannelMasks(ChannelMaskSet *channelMasksPtr) {
8094 ChannelMaskSet &channelMasks = *channelMasksPtr;
Phil Burk0709b0a2016-03-31 12:54:57 -07008095 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
8096 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
8097
8098 // If NEVER, then remove support for channelMasks > stereo.
8099 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
jiabin06e4bab2019-07-29 10:13:34 -07008100 for (auto it = channelMasks.begin(); it != channelMasks.end();) {
8101 audio_channel_mask_t channelMask = *it;
Phil Burk0709b0a2016-03-31 12:54:57 -07008102 if (channelMask & ~AUDIO_CHANNEL_OUT_STEREO) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01008103 ALOGV("%s: force NEVER, so remove channelMask 0x%08x", __FUNCTION__, channelMask);
jiabin06e4bab2019-07-29 10:13:34 -07008104 it = channelMasks.erase(it);
Phil Burk0709b0a2016-03-31 12:54:57 -07008105 } else {
jiabin06e4bab2019-07-29 10:13:34 -07008106 ++it;
Phil Burk0709b0a2016-03-31 12:54:57 -07008107 }
8108 }
jiabin81772902018-04-02 17:52:27 -07008109 // If ALWAYS or MANUAL, then make sure we at least support 5.1
8110 } else if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS
8111 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Phil Burk0709b0a2016-03-31 12:54:57 -07008112 bool supports5dot1 = false;
8113 // Are there any channel masks that can be considered "surround"?
Mikhail Naganovcf84e592017-12-07 11:25:11 -08008114 for (audio_channel_mask_t channelMask : channelMasks) {
Phil Burk0709b0a2016-03-31 12:54:57 -07008115 if ((channelMask & AUDIO_CHANNEL_OUT_5POINT1) == AUDIO_CHANNEL_OUT_5POINT1) {
8116 supports5dot1 = true;
8117 break;
8118 }
8119 }
8120 // If not then add 5.1 support.
8121 if (!supports5dot1) {
jiabin06e4bab2019-07-29 10:13:34 -07008122 channelMasks.insert(AUDIO_CHANNEL_OUT_5POINT1);
Eric Laurentfecbceb2021-02-09 14:46:43 +01008123 ALOGV("%s: force MANUAL or ALWAYS, so adding channelMask for 5.1 surround", __func__);
Phil Burk0709b0a2016-03-31 12:54:57 -07008124 }
Phil Burk09bc4612016-02-24 15:58:15 -08008125 }
8126}
8127
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008128void AudioPolicyManager::updateAudioProfiles(const sp<DeviceDescriptor>& devDesc,
Phil Burk00eeb322016-03-31 12:41:00 -07008129 audio_io_handle_t ioHandle,
François Gaffie112b0af2015-11-19 16:13:25 +01008130 AudioProfileVector &profiles)
8131{
8132 String8 reply;
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008133 audio_devices_t device = devDesc->type();
Phil Burk0709b0a2016-03-31 12:54:57 -07008134
François Gaffie112b0af2015-11-19 16:13:25 +01008135 // Format MUST be checked first to update the list of AudioProfile
8136 if (profiles.hasDynamicFormat()) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07008137 reply = mpClientInterface->getParameters(
8138 ioHandle, String8(AudioParameter::keyStreamSupportedFormats));
jiabin81772902018-04-02 17:52:27 -07008139 ALOGV("%s: supported formats %d, %s", __FUNCTION__, ioHandle, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08008140 AudioParameter repliedParameters(reply);
jiabinf26596b2023-04-12 18:56:39 +00008141 FormatVector formats;
Eric Laurent62e4bc52016-02-02 18:37:28 -08008142 if (repliedParameters.get(
jiabinf26596b2023-04-12 18:56:39 +00008143 String8(AudioParameter::keyStreamSupportedFormats), reply) == NO_ERROR) {
8144 formats = formatsFromString(reply.string());
8145 } else if (devDesc->hasValidAudioProfile()) {
8146 ALOGD("%s: using the device profiles", __func__);
8147 formats = devDesc->getAudioProfiles().getSupportedFormats();
8148 } else {
8149 ALOGE("%s: failed to retrieve format, bailing out", __func__);
François Gaffie112b0af2015-11-19 16:13:25 +01008150 return;
8151 }
Kriti Dangef6be8f2020-11-05 11:58:19 +01008152 mReportedFormatsMap[devDesc] = formats;
Mikhail Naganov100f0122018-11-29 11:22:16 -08008153 if (device == AUDIO_DEVICE_OUT_HDMI
8154 || isDeviceOfModule(devDesc, AUDIO_HARDWARE_MODULE_ID_MSD)) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008155 modifySurroundFormats(devDesc, &formats);
Phil Burk00eeb322016-03-31 12:41:00 -07008156 }
jiabin3e277cc2019-09-10 14:27:34 -07008157 addProfilesForFormats(profiles, formats);
François Gaffie112b0af2015-11-19 16:13:25 +01008158 }
François Gaffie112b0af2015-11-19 16:13:25 +01008159
Mikhail Naganovcf84e592017-12-07 11:25:11 -08008160 for (audio_format_t format : profiles.getSupportedFormats()) {
jiabinf26596b2023-04-12 18:56:39 +00008161 std::optional<ChannelMaskSet> channelMasks;
jiabin06e4bab2019-07-29 10:13:34 -07008162 SampleRateSet samplingRates;
François Gaffie112b0af2015-11-19 16:13:25 +01008163 AudioParameter requestedParameters;
Mikhail Naganov388360c2016-10-17 17:09:41 -07008164 requestedParameters.addInt(String8(AudioParameter::keyFormat), format);
François Gaffie112b0af2015-11-19 16:13:25 +01008165
8166 if (profiles.hasDynamicRateFor(format)) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07008167 reply = mpClientInterface->getParameters(
8168 ioHandle,
8169 requestedParameters.toString() + ";" +
8170 AudioParameter::keyStreamSupportedSamplingRates);
François Gaffie112b0af2015-11-19 16:13:25 +01008171 ALOGV("%s: supported sampling rates %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08008172 AudioParameter repliedParameters(reply);
8173 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07008174 String8(AudioParameter::keyStreamSupportedSamplingRates), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08008175 samplingRates = samplingRatesFromString(reply.string());
jiabinf26596b2023-04-12 18:56:39 +00008176 } else {
8177 samplingRates = devDesc->getAudioProfiles().getSampleRatesFor(format);
François Gaffie112b0af2015-11-19 16:13:25 +01008178 }
8179 }
8180 if (profiles.hasDynamicChannelsFor(format)) {
8181 reply = mpClientInterface->getParameters(ioHandle,
8182 requestedParameters.toString() + ";" +
Mikhail Naganov388360c2016-10-17 17:09:41 -07008183 AudioParameter::keyStreamSupportedChannels);
François Gaffie112b0af2015-11-19 16:13:25 +01008184 ALOGV("%s: supported channel masks %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08008185 AudioParameter repliedParameters(reply);
8186 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07008187 String8(AudioParameter::keyStreamSupportedChannels), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08008188 channelMasks = channelMasksFromString(reply.string());
jiabinf26596b2023-04-12 18:56:39 +00008189 } else {
8190 channelMasks = devDesc->getAudioProfiles().getChannelMasksFor(format);
8191 }
8192 if (channelMasks.has_value() && (device == AUDIO_DEVICE_OUT_HDMI
8193 || isDeviceOfModule(devDesc, AUDIO_HARDWARE_MODULE_ID_MSD))) {
8194 modifySurroundChannelMasks(&channelMasks.value());
François Gaffie112b0af2015-11-19 16:13:25 +01008195 }
8196 }
jiabin3e277cc2019-09-10 14:27:34 -07008197 addDynamicAudioProfileAndSort(
jiabinf26596b2023-04-12 18:56:39 +00008198 profiles, new AudioProfile(
8199 format, channelMasks.value_or(ChannelMaskSet()), samplingRates));
François Gaffie112b0af2015-11-19 16:13:25 +01008200 }
8201}
Eric Laurentd60560a2015-04-10 11:31:20 -07008202
Mikhail Naganovdc769682018-05-04 15:34:08 -07008203status_t AudioPolicyManager::installPatch(const char *caller,
8204 audio_patch_handle_t *patchHandle,
8205 AudioIODescriptorInterface *ioDescriptor,
8206 const struct audio_patch *patch,
8207 int delayMs)
8208{
8209 ssize_t index = mAudioPatches.indexOfKey(
8210 patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE ?
8211 *patchHandle : ioDescriptor->getPatchHandle());
8212 sp<AudioPatch> patchDesc;
8213 status_t status = installPatch(
8214 caller, index, patchHandle, patch, delayMs, mUidCached, &patchDesc);
8215 if (status == NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01008216 ioDescriptor->setPatchHandle(patchDesc->getHandle());
Mikhail Naganovdc769682018-05-04 15:34:08 -07008217 }
8218 return status;
8219}
8220
8221status_t AudioPolicyManager::installPatch(const char *caller,
8222 ssize_t index,
8223 audio_patch_handle_t *patchHandle,
8224 const struct audio_patch *patch,
8225 int delayMs,
8226 uid_t uid,
8227 sp<AudioPatch> *patchDescPtr)
8228{
8229 sp<AudioPatch> patchDesc;
8230 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
8231 if (index >= 0) {
8232 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01008233 afPatchHandle = patchDesc->getAfHandle();
Mikhail Naganovdc769682018-05-04 15:34:08 -07008234 }
8235
8236 status_t status = mpClientInterface->createAudioPatch(patch, &afPatchHandle, delayMs);
8237 ALOGV("%s() AF::createAudioPatch returned %d patchHandle %d num_sources %d num_sinks %d",
8238 caller, status, afPatchHandle, patch->num_sources, patch->num_sinks);
8239 if (status == NO_ERROR) {
8240 if (index < 0) {
8241 patchDesc = new AudioPatch(patch, uid);
François Gaffieafd4cea2019-11-18 15:50:22 +01008242 addAudioPatch(patchDesc->getHandle(), patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07008243 } else {
8244 patchDesc->mPatch = *patch;
8245 }
François Gaffieafd4cea2019-11-18 15:50:22 +01008246 patchDesc->setAfHandle(afPatchHandle);
Mikhail Naganovdc769682018-05-04 15:34:08 -07008247 if (patchHandle) {
François Gaffieafd4cea2019-11-18 15:50:22 +01008248 *patchHandle = patchDesc->getHandle();
Mikhail Naganovdc769682018-05-04 15:34:08 -07008249 }
8250 nextAudioPortGeneration();
8251 mpClientInterface->onAudioPatchListUpdate();
8252 }
8253 if (patchDescPtr) *patchDescPtr = patchDesc;
8254 return status;
8255}
8256
jiabinbce0c1d2020-10-05 11:20:18 -07008257bool AudioPolicyManager::areAllActiveTracksRerouted(const sp<SwAudioOutputDescriptor>& output)
8258{
8259 const TrackClientVector activeClients = output->getActiveClients();
8260 if (activeClients.empty()) {
8261 return true;
8262 }
8263 ssize_t index = mAudioPatches.indexOfKey(output->getPatchHandle());
8264 if (index < 0) {
8265 ALOGE("%s, no audio patch found while there are active clients on output %d",
8266 __func__, output->getId());
8267 return false;
8268 }
8269 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
8270 DeviceVector routedDevices;
8271 for (int i = 0; i < patchDesc->mPatch.num_sinks; ++i) {
8272 sp<DeviceDescriptor> device = mAvailableOutputDevices.getDeviceFromId(
8273 patchDesc->mPatch.sinks[i].id);
8274 if (device == nullptr) {
8275 ALOGE("%s, no audio device found with id(%d)",
8276 __func__, patchDesc->mPatch.sinks[i].id);
8277 return false;
8278 }
8279 routedDevices.add(device);
8280 }
8281 for (const auto& client : activeClients) {
jiabin49256852022-03-09 11:21:35 -08008282 if (client->isInvalid()) {
8283 // No need to take care about invalidated clients.
8284 continue;
8285 }
jiabinbce0c1d2020-10-05 11:20:18 -07008286 sp<DeviceDescriptor> preferredDevice =
8287 mAvailableOutputDevices.getDeviceFromId(client->preferredDeviceId());
8288 if (mEngine->getOutputDevicesForAttributes(
8289 client->attributes(), preferredDevice, false) == routedDevices) {
8290 return false;
8291 }
8292 }
8293 return true;
8294}
8295
8296sp<SwAudioOutputDescriptor> AudioPolicyManager::openOutputWithProfileAndDevice(
Eric Laurentb4f42a92022-01-17 17:37:31 +01008297 const sp<IOProfile>& profile, const DeviceVector& devices,
jiabina84c3d32022-12-02 18:59:55 +00008298 const audio_config_base_t *mixerConfig, const audio_config_t *halConfig,
8299 audio_output_flags_t flags)
jiabinbce0c1d2020-10-05 11:20:18 -07008300{
8301 for (const auto& device : devices) {
8302 // TODO: This should be checking if the profile supports the device combo.
8303 if (!profile->supportsDevice(device)) {
jiabina84c3d32022-12-02 18:59:55 +00008304 ALOGE("%s profile(%s) doesn't support device %#x", __func__, profile->getName().c_str(),
8305 device->type());
jiabinbce0c1d2020-10-05 11:20:18 -07008306 return nullptr;
8307 }
8308 }
8309 sp<SwAudioOutputDescriptor> desc = new SwAudioOutputDescriptor(profile, mpClientInterface);
8310 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
jiabina84c3d32022-12-02 18:59:55 +00008311 status_t status = desc->open(halConfig, mixerConfig, devices,
8312 AUDIO_STREAM_DEFAULT, flags, &output);
jiabinbce0c1d2020-10-05 11:20:18 -07008313 if (status != NO_ERROR) {
jiabina84c3d32022-12-02 18:59:55 +00008314 ALOGE("%s failed to open output %d", __func__, status);
jiabinbce0c1d2020-10-05 11:20:18 -07008315 return nullptr;
8316 }
8317
8318 // Here is where the out_set_parameters() for card & device gets called
8319 sp<DeviceDescriptor> device = devices.getDeviceForOpening();
8320 const audio_devices_t deviceType = device->type();
8321 const String8 &address = String8(device->address().c_str());
8322 if (!address.isEmpty()) {
8323 char *param = audio_device_address_to_parameter(deviceType, address.c_str());
8324 mpClientInterface->setParameters(output, String8(param));
8325 free(param);
8326 }
8327 updateAudioProfiles(device, output, profile->getAudioProfiles());
8328 if (!profile->hasValidAudioProfile()) {
8329 ALOGW("%s() missing param", __func__);
8330 desc->close();
8331 return nullptr;
jiabina84c3d32022-12-02 18:59:55 +00008332 } else if (profile->hasDynamicAudioProfile() && halConfig == nullptr) {
8333 // Reopen the output with the best audio profile picked by APM when the profile supports
8334 // dynamic audio profile and the hal config is not specified.
jiabinbce0c1d2020-10-05 11:20:18 -07008335 desc->close();
8336 output = AUDIO_IO_HANDLE_NONE;
8337 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
8338 profile->pickAudioProfile(
8339 config.sample_rate, config.channel_mask, config.format);
8340 config.offload_info.sample_rate = config.sample_rate;
8341 config.offload_info.channel_mask = config.channel_mask;
8342 config.offload_info.format = config.format;
8343
jiabina84c3d32022-12-02 18:59:55 +00008344 status = desc->open(&config, mixerConfig, devices, AUDIO_STREAM_DEFAULT, flags, &output);
jiabinbce0c1d2020-10-05 11:20:18 -07008345 if (status != NO_ERROR) {
8346 return nullptr;
8347 }
8348 }
8349
8350 addOutput(output, desc);
Eric Laurentb4f42a92022-01-17 17:37:31 +01008351
baek.kim -61c20122022-07-27 10:05:32 +00008352 sp<DeviceDescriptor> speaker = mAvailableOutputDevices.getDevice(
8353 AUDIO_DEVICE_OUT_SPEAKER, String8(""), AUDIO_FORMAT_DEFAULT);
8354
jiabinbce0c1d2020-10-05 11:20:18 -07008355 if (audio_is_remote_submix_device(deviceType) && address != "0") {
8356 sp<AudioPolicyMix> policyMix;
8357 if (mPolicyMixes.getAudioPolicyMix(deviceType, address, policyMix) == NO_ERROR) {
8358 policyMix->setOutput(desc);
8359 desc->mPolicyMix = policyMix;
8360 } else {
8361 ALOGW("checkOutputsForDevice() cannot find policy for address %s",
8362 address.string());
8363 }
8364
baek.kim -61c20122022-07-27 10:05:32 +00008365 } else if (hasPrimaryOutput() && speaker != nullptr
8366 && mPrimaryOutput->supportsDevice(speaker) && !desc->supportsDevice(speaker)
Eric Laurentb4f42a92022-01-17 17:37:31 +01008367 && ((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0)) {
8368 // no duplicated output for:
8369 // - direct outputs
8370 // - outputs used by dynamic policy mixes
baek.kim -61c20122022-07-27 10:05:32 +00008371 // - outputs that supports SPEAKER while the primary output does not.
jiabinbce0c1d2020-10-05 11:20:18 -07008372 audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE;
8373
8374 //TODO: configure audio effect output stage here
8375
8376 // open a duplicating output thread for the new output and the primary output
8377 sp<SwAudioOutputDescriptor> dupOutputDesc =
8378 new SwAudioOutputDescriptor(nullptr, mpClientInterface);
8379 status = dupOutputDesc->openDuplicating(mPrimaryOutput, desc, &duplicatedOutput);
8380 if (status == NO_ERROR) {
8381 // add duplicated output descriptor
8382 addOutput(duplicatedOutput, dupOutputDesc);
8383 } else {
8384 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
8385 mPrimaryOutput->mIoHandle, output);
8386 desc->close();
8387 removeOutput(output);
8388 nextAudioPortGeneration();
8389 return nullptr;
8390 }
8391 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02008392 if (mPrimaryOutput == nullptr && profile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
8393 ALOGV("%s(): re-assigning mPrimaryOutput", __func__);
8394 mPrimaryOutput = desc;
8395 }
jiabinbce0c1d2020-10-05 11:20:18 -07008396 return desc;
8397}
8398
jiabinf1c73972022-04-14 16:28:52 -07008399status_t AudioPolicyManager::getDevicesForAttributes(
8400 const audio_attributes_t &attr, DeviceVector &devices, bool forVolume) {
8401 // Devices are determined in the following precedence:
8402 //
8403 // 1) Devices associated with a dynamic policy matching the attributes. This is often
8404 // a remote submix from MIX_ROUTE_FLAG_LOOP_BACK.
8405 //
8406 // If no such dynamic policy then
8407 // 2) Devices containing an active client using setPreferredDevice
8408 // with same strategy as the attributes.
8409 // (from the default Engine::getOutputDevicesForAttributes() implementation).
8410 //
8411 // If no corresponding active client with setPreferredDevice then
8412 // 3) Devices associated with the strategy determined by the attributes
8413 // (from the default Engine::getOutputDevicesForAttributes() implementation).
8414 //
8415 // See related getOutputForAttrInt().
8416
8417 // check dynamic policies but only for primary descriptors (secondary not used for audible
8418 // audio routing, only used for duplication for playback capture)
8419 sp<AudioPolicyMix> policyMix;
Oscar Azucena873d10f2023-01-12 18:34:42 -08008420 bool unneededUsePrimaryOutputFromPolicyMixes = false;
jiabinf1c73972022-04-14 16:28:52 -07008421 status_t status = mPolicyMixes.getOutputForAttr(attr, AUDIO_CONFIG_BASE_INITIALIZER,
Oscar Azucena873d10f2023-01-12 18:34:42 -08008422 0 /*uid unknown here*/, AUDIO_SESSION_NONE, AUDIO_OUTPUT_FLAG_NONE,
8423 mAvailableOutputDevices, nullptr /* requestedDevice */, policyMix,
8424 nullptr /* secondaryMixes */, unneededUsePrimaryOutputFromPolicyMixes);
jiabinf1c73972022-04-14 16:28:52 -07008425 if (status != OK) {
8426 return status;
8427 }
8428
8429 if (policyMix != nullptr && policyMix->getOutput() != nullptr &&
8430 // For volume control, skip LOOPBACK mixes which use AUDIO_DEVICE_OUT_REMOTE_SUBMIX
8431 // as they are unaffected by device/stream volume
8432 // (per SwAudioOutputDescriptor::isFixedVolume()).
8433 (!forVolume || policyMix->mDeviceType != AUDIO_DEVICE_OUT_REMOTE_SUBMIX)
8434 ) {
8435 sp<DeviceDescriptor> deviceDesc = mAvailableOutputDevices.getDevice(
8436 policyMix->mDeviceType, policyMix->mDeviceAddress, AUDIO_FORMAT_DEFAULT);
8437 devices.add(deviceDesc);
8438 } else {
8439 // The default Engine::getOutputDevicesForAttributes() uses findPreferredDevice()
8440 // which selects setPreferredDevice if active. This means forVolume call
8441 // will take an active setPreferredDevice, if such exists.
8442
8443 devices = mEngine->getOutputDevicesForAttributes(
8444 attr, nullptr /* preferredDevice */, false /* fromCache */);
8445 }
8446
8447 if (forVolume) {
8448 // We alias the device AUDIO_DEVICE_OUT_SPEAKER_SAFE to AUDIO_DEVICE_OUT_SPEAKER
8449 // for single volume control in AudioService (such relationship should exist if
8450 // SPEAKER_SAFE is present).
8451 //
8452 // (This is unrelated to a different device grouping as Volume::getDeviceCategory)
8453 DeviceVector speakerSafeDevices =
8454 devices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER_SAFE);
8455 if (!speakerSafeDevices.isEmpty()) {
8456 devices.merge(mAvailableOutputDevices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER));
8457 devices.remove(speakerSafeDevices);
8458 }
8459 }
8460
8461 return NO_ERROR;
8462}
8463
8464status_t AudioPolicyManager::getProfilesForDevices(const DeviceVector& devices,
8465 AudioProfileVector& audioProfiles,
8466 uint32_t flags,
8467 bool isInput) {
8468 for (const auto& hwModule : mHwModules) {
8469 // the MSD module checks for different conditions
8470 if (strcmp(hwModule->getName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0) {
8471 continue;
8472 }
8473 IOProfileCollection ioProfiles = isInput ? hwModule->getInputProfiles()
8474 : hwModule->getOutputProfiles();
8475 for (const auto& profile : ioProfiles) {
8476 if (!profile->areAllDevicesSupported(devices) ||
8477 !profile->isCompatibleProfileForFlags(
8478 flags, false /*exactMatchRequiredForInputFlags*/)) {
8479 continue;
8480 }
8481 audioProfiles.addAllValidProfiles(profile->asAudioPort()->getAudioProfiles());
8482 }
8483 }
8484
8485 if (!isInput) {
8486 // add the direct profiles from MSD if present and has audio patches to all the output(s)
8487 const auto &msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
8488 if (msdModule != nullptr) {
8489 if (msdHasPatchesToAllDevices(devices.toTypeAddrVector())) {
8490 ALOGV("%s: MSD audio patches set to all output devices.", __func__);
8491 for (const auto &profile: msdModule->getOutputProfiles()) {
8492 if (!profile->asAudioPort()->isDirectOutput()) {
8493 continue;
8494 }
8495 audioProfiles.addAllValidProfiles(profile->asAudioPort()->getAudioProfiles());
8496 }
8497 } else {
8498 ALOGV("%s: MSD audio patches NOT set to all output devices.", __func__);
8499 }
8500 }
8501 }
8502
8503 return NO_ERROR;
8504}
8505
jiabin3ff8d7d2022-12-13 06:27:44 +00008506sp<SwAudioOutputDescriptor> AudioPolicyManager::reopenOutput(sp<SwAudioOutputDescriptor> outputDesc,
8507 const audio_config_t *config,
8508 audio_output_flags_t flags,
8509 const char* caller) {
jiabina84c3d32022-12-02 18:59:55 +00008510 closeOutput(outputDesc->mIoHandle);
8511 sp<SwAudioOutputDescriptor> preferredOutput = openOutputWithProfileAndDevice(
8512 outputDesc->mProfile, outputDesc->devices(), nullptr /*mixerConfig*/, config, flags);
8513 if (preferredOutput == nullptr) {
8514 ALOGE("%s failed to reopen output device=%d, caller=%s",
8515 __func__, outputDesc->devices()[0]->getId(), caller);
jiabina84c3d32022-12-02 18:59:55 +00008516 }
jiabin3ff8d7d2022-12-13 06:27:44 +00008517 return preferredOutput;
8518}
8519
8520void AudioPolicyManager::reopenOutputsWithDevices(
8521 const std::map<audio_io_handle_t, DeviceVector> &outputsToReopen) {
8522 for (const auto& [output, devices] : outputsToReopen) {
8523 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
8524 closeOutput(output);
8525 openOutputWithProfileAndDevice(desc->mProfile, devices);
8526 }
jiabina84c3d32022-12-02 18:59:55 +00008527}
8528
jiabinc44b3462022-12-08 12:52:31 -08008529PortHandleVector AudioPolicyManager::getClientsForStream(
8530 audio_stream_type_t streamType) const {
8531 PortHandleVector clients;
8532 for (size_t i = 0; i < mOutputs.size(); ++i) {
8533 PortHandleVector clientsForStream = mOutputs.valueAt(i)->getClientsForStream(streamType);
8534 clients.insert(clients.end(), clientsForStream.begin(), clientsForStream.end());
8535 }
8536 return clients;
8537}
8538
8539void AudioPolicyManager::invalidateStreams(StreamTypeVector streams) const {
8540 PortHandleVector clients;
8541 for (auto stream : streams) {
8542 PortHandleVector clientsForStream = getClientsForStream(stream);
8543 clients.insert(clients.end(), clientsForStream.begin(), clientsForStream.end());
8544 }
8545 mpClientInterface->invalidateTracks(clients);
8546}
8547
Mikhail Naganov1b2a7942017-12-08 10:18:09 -08008548} // namespace android