blob: b6786621618936767c92c775f6c4e72e7adbb255 [file] [log] [blame]
Eric Laurente552edb2014-03-10 17:42:56 -07001/*
2 * Copyright (C) 2009 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -070017#define LOG_TAG "APM_AudioPolicyManager"
Tomoharu Kasahara71c90912018-10-31 09:10:12 +090018
19// Need to keep the log statements even in production builds
20// to enable VERBOSE logging dynamically.
21// You can enable VERBOSE logging as follows:
22// adb shell setprop log.tag.APM_AudioPolicyManager V
23#define LOG_NDEBUG 0
Eric Laurente552edb2014-03-10 17:42:56 -070024
25//#define VERY_VERBOSE_LOGGING
26#ifdef VERY_VERBOSE_LOGGING
27#define ALOGVV ALOGV
28#else
29#define ALOGVV(a...) do { } while(0)
30#endif
31
Eric Laurent16c66dd2019-05-01 17:54:10 -070032#include <algorithm>
Eric Laurentd4692962014-05-05 18:13:44 -070033#include <inttypes.h>
jiabin10a03f12021-05-07 23:46:28 +000034#include <map>
Eric Laurente552edb2014-03-10 17:42:56 -070035#include <math.h>
Kevin Rocard153f92d2018-12-18 18:33:28 -080036#include <set>
Atneya Nair0f0a8032022-12-12 16:20:12 -080037#include <type_traits>
Mikhail Naganovd5e18052018-11-30 14:55:45 -080038#include <unordered_set>
Mikhail Naganov15be9d22017-11-08 14:18:13 +110039#include <vector>
Mikhail Naganov946c0032020-10-21 13:04:58 -070040
41#include <Serializer.h>
Nathalie Le Clair88fa2752021-11-23 13:03:41 +010042#include <android/media/audio/common/AudioPort.h>
Glenn Kasten76a13442020-07-01 12:10:59 -070043#include <cutils/bitops.h>
Eric Laurente552edb2014-03-10 17:42:56 -070044#include <cutils/properties.h>
Eric Laurent3b73df72014-03-11 09:06:29 -070045#include <media/AudioParameter.h>
Mikhail Naganov946c0032020-10-21 13:04:58 -070046#include <policy.h>
Andy Hung4ef19fa2018-05-15 19:35:29 -070047#include <private/android_filesystem_config.h>
Mikhail Naganovcbc8f612016-10-11 18:05:13 -070048#include <system/audio.h>
Mikhail Naganov27cf37c2020-04-14 14:47:01 -070049#include <system/audio_config.h>
jiabinebb6af42020-06-09 17:31:17 -070050#include <system/audio_effects/effect_hapticgenerator.h>
Mikhail Naganov946c0032020-10-21 13:04:58 -070051#include <utils/Log.h>
52
Eric Laurentd4692962014-05-05 18:13:44 -070053#include "AudioPolicyManager.h"
François Gaffiea8ecc2c2015-11-09 16:10:40 +010054#include "TypeConverter.h"
Eric Laurente552edb2014-03-10 17:42:56 -070055
Eric Laurent3b73df72014-03-11 09:06:29 -070056namespace android {
Eric Laurente552edb2014-03-10 17:42:56 -070057
Nathalie Le Clair88fa2752021-11-23 13:03:41 +010058using android::media::audio::common::AudioDevice;
59using android::media::audio::common::AudioDeviceAddress;
60using android::media::audio::common::AudioPortDeviceExt;
61using android::media::audio::common::AudioPortExt;
Svet Ganov3e5f14f2021-05-13 22:51:08 +000062using content::AttributionSourceState;
Philip P. Moltmannbda45752020-07-17 16:41:18 -070063
Eric Laurentdc462862016-07-19 12:29:53 -070064//FIXME: workaround for truncated touch sounds
65// to be removed when the problem is handled by system UI
66#define TOUCH_SOUND_FIXED_DELAY_MS 100
Jean-Michel Trivi719a9872017-08-05 13:51:35 -070067
68// Largest difference in dB on earpiece in call between the voice volume and another
69// media / notification / system volume.
70constexpr float IN_CALL_EARPIECE_HEADROOM_DB = 3.f;
71
jiabin06e4bab2019-07-29 10:13:34 -070072template <typename T>
73bool operator== (const SortedVector<T> &left, const SortedVector<T> &right)
74{
75 if (left.size() != right.size()) {
76 return false;
77 }
78 for (size_t index = 0; index < right.size(); index++) {
79 if (left[index] != right[index]) {
80 return false;
81 }
82 }
83 return true;
84}
85
86template <typename T>
87bool operator!= (const SortedVector<T> &left, const SortedVector<T> &right)
88{
89 return !(left == right);
90}
91
Eric Laurente552edb2014-03-10 17:42:56 -070092// ----------------------------------------------------------------------------
93// AudioPolicyInterface implementation
94// ----------------------------------------------------------------------------
95
Nathalie Le Clair88fa2752021-11-23 13:03:41 +010096status_t AudioPolicyManager::setDeviceConnectionState(audio_policy_dev_state_t state,
97 const android::media::audio::common::AudioPort& port, audio_format_t encodedFormat) {
98 status_t status = setDeviceConnectionStateInt(state, port, encodedFormat);
jiabina7b43792018-02-15 16:04:46 -080099 nextAudioPortGeneration();
100 return status;
Eric Laurentc73ca6e2014-12-12 14:34:22 -0800101}
102
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100103status_t AudioPolicyManager::setDeviceConnectionState(audio_devices_t device,
104 audio_policy_dev_state_t state,
105 const char* device_address,
106 const char* device_name,
107 audio_format_t encodedFormat) {
Atneya Nair638a6e42022-12-18 16:45:15 -0800108 media::AudioPortFw aidlPort;
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100109 if (status_t status = deviceToAudioPort(device, device_address, device_name, &aidlPort);
110 status == OK) {
111 return setDeviceConnectionState(state, aidlPort.hal, encodedFormat);
112 } else {
113 ALOGE("Failed to convert to AudioPort Parcelable: %s", statusToString(status).c_str());
114 return status;
115 }
116}
117
François Gaffie11d30102018-11-02 16:09:09 +0100118void AudioPolicyManager::broadcastDeviceConnectionState(const sp<DeviceDescriptor> &device,
jiabinc0048632023-04-27 22:04:31 +0000119 media::DeviceConnectedState state)
François Gaffie44481e72016-04-20 07:49:57 +0200120{
Mikhail Naganov516d3982022-02-01 23:53:59 +0000121 audio_port_v7 devicePort;
122 device->toAudioPort(&devicePort);
jiabinc0048632023-04-27 22:04:31 +0000123 if (status_t status = mpClientInterface->setDeviceConnectedState(&devicePort, state);
Mikhail Naganov516d3982022-02-01 23:53:59 +0000124 status != OK) {
jiabinc0048632023-04-27 22:04:31 +0000125 ALOGE("Error %d while setting connected state for device %s", state,
Mikhail Naganov516d3982022-02-01 23:53:59 +0000126 device->getDeviceTypeAddr().toString(false).c_str());
127 }
François Gaffie44481e72016-04-20 07:49:57 +0200128}
129
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100130status_t AudioPolicyManager::setDeviceConnectionStateInt(
131 audio_policy_dev_state_t state, const android::media::audio::common::AudioPort& port,
132 audio_format_t encodedFormat) {
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100133 if (port.ext.getTag() != AudioPortExt::device) {
134 return BAD_VALUE;
135 }
136 audio_devices_t device_type;
137 std::string device_address;
138 if (status_t status = aidl2legacy_AudioDevice_audio_device(
139 port.ext.get<AudioPortExt::device>().device, &device_type, &device_address);
140 status != OK) {
141 return status;
142 };
143 const char* device_name = port.name.c_str();
144 // connect/disconnect only 1 device at a time
145 if (!audio_is_output_device(device_type) && !audio_is_input_device(device_type))
146 return BAD_VALUE;
147
148 sp<DeviceDescriptor> device = mHwModules.getDeviceDescriptor(
149 device_type, device_address.c_str(), device_name, encodedFormat,
150 state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
Mikhail Naganovddc5f312022-06-11 00:47:52 +0000151 if (device == nullptr) {
152 return INVALID_OPERATION;
153 }
154 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
155 device->setExtraAudioDescriptors(port.extraAudioDescriptors);
156 }
157 return setDeviceConnectionStateInt(device, state);
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100158}
159
François Gaffie11d30102018-11-02 16:09:09 +0100160status_t AudioPolicyManager::setDeviceConnectionStateInt(audio_devices_t deviceType,
Eric Laurenta1d525f2015-01-29 13:36:45 -0800161 audio_policy_dev_state_t state,
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100162 const char* device_address,
163 const char* device_name,
164 audio_format_t encodedFormat) {
Atneya Nair638a6e42022-12-18 16:45:15 -0800165 media::AudioPortFw aidlPort;
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100166 if (status_t status = deviceToAudioPort(deviceType, device_address, device_name, &aidlPort);
167 status == OK) {
168 return setDeviceConnectionStateInt(state, aidlPort.hal, encodedFormat);
169 } else {
170 ALOGE("Failed to convert to AudioPort Parcelable: %s", statusToString(status).c_str());
171 return status;
172 }
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700173}
Paul McLeane743a472015-01-28 11:07:31 -0800174
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700175status_t AudioPolicyManager::setDeviceConnectionStateInt(const sp<DeviceDescriptor> &device,
176 audio_policy_dev_state_t state)
177{
Eric Laurente552edb2014-03-10 17:42:56 -0700178 // handle output devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700179 if (audio_is_output_device(device->type())) {
Eric Laurentd4692962014-05-05 18:13:44 -0700180 SortedVector <audio_io_handle_t> outputs;
181
François Gaffie11d30102018-11-02 16:09:09 +0100182 ssize_t index = mAvailableOutputDevices.indexOf(device);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700183
Eric Laurente552edb2014-03-10 17:42:56 -0700184 // save a copy of the opened output descriptors before any output is opened or closed
185 // by checkOutputsForDevice(). This will be needed by checkOutputForAllStrategies()
186 mPreviousOutputs = mOutputs;
Eric Laurent96d1dda2022-03-14 17:14:19 +0100187
188 bool wasLeUnicastActive = isLeUnicastActive();
189
Eric Laurente552edb2014-03-10 17:42:56 -0700190 switch (state)
191 {
192 // handle output device connection
Eric Laurent3ae5f312015-02-03 17:12:08 -0800193 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700194 if (index >= 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100195 ALOGW("%s() device already connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700196 return INVALID_OPERATION;
197 }
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800198 ALOGV("%s() connecting device %s format %x",
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700199 __func__, device->toString().c_str(), device->getEncodedFormat());
Eric Laurente552edb2014-03-10 17:42:56 -0700200
Eric Laurente552edb2014-03-10 17:42:56 -0700201 // register new device as available
Francois Gaffie993f3902019-04-10 15:39:27 +0200202 if (mAvailableOutputDevices.add(device) < 0) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700203 return NO_MEMORY;
Eric Laurente552edb2014-03-10 17:42:56 -0700204 }
205
François Gaffie44481e72016-04-20 07:49:57 +0200206 // Before checking outputs, broadcast connect event to allow HAL to retrieve dynamic
207 // parameters on newly connected devices (instead of opening the outputs...)
jiabinc0048632023-04-27 22:04:31 +0000208 broadcastDeviceConnectionState(device, media::DeviceConnectedState::CONNECTED);
François Gaffie44481e72016-04-20 07:49:57 +0200209
François Gaffie11d30102018-11-02 16:09:09 +0100210 if (checkOutputsForDevice(device, state, outputs) != NO_ERROR) {
211 mAvailableOutputDevices.remove(device);
François Gaffie44481e72016-04-20 07:49:57 +0200212
Francois Gaffie716e1432019-01-14 16:58:59 +0100213 mHwModules.cleanUpForDevice(device);
214
jiabinc0048632023-04-27 22:04:31 +0000215 broadcastDeviceConnectionState(device, media::DeviceConnectedState::DISCONNECTED);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700216 return INVALID_OPERATION;
217 }
François Gaffie2110e042015-03-24 08:41:51 +0100218
jiabin1c4794b2020-05-05 10:08:05 -0700219 // Populate encapsulation information when a output device is connected.
220 device->setEncapsulationInfoFromHal(mpClientInterface);
221
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700222 // outputs should never be empty here
223 ALOG_ASSERT(outputs.size() != 0, "setDeviceConnectionState():"
224 "checkOutputsForDevice() returned no outputs but status OK");
François Gaffie11d30102018-11-02 16:09:09 +0100225 ALOGV("%s() checkOutputsForDevice() returned %zu outputs", __func__, outputs.size());
Eric Laurent3ae5f312015-02-03 17:12:08 -0800226
Eric Laurent3ae5f312015-02-03 17:12:08 -0800227 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700228 // handle output device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700229 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700230 if (index < 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100231 ALOGW("%s() device not connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700232 return INVALID_OPERATION;
233 }
234
François Gaffie11d30102018-11-02 16:09:09 +0100235 ALOGV("%s() disconnecting output device %s", __func__, device->toString().c_str());
Paul McLean5c477aa2014-08-20 16:47:57 -0700236
jiabinc0048632023-04-27 22:04:31 +0000237 // Notify the HAL to prepare to disconnect device
238 broadcastDeviceConnectionState(
239 device, media::DeviceConnectedState::PREPARE_TO_DISCONNECT);
Paul McLean5c477aa2014-08-20 16:47:57 -0700240
Eric Laurente552edb2014-03-10 17:42:56 -0700241 // remove device from available output devices
François Gaffie11d30102018-11-02 16:09:09 +0100242 mAvailableOutputDevices.remove(device);
Eric Laurente552edb2014-03-10 17:42:56 -0700243
Francois Gaffieba2cf0f2018-12-12 16:40:25 +0100244 mOutputs.clearSessionRoutesForDevice(device);
245
François Gaffie11d30102018-11-02 16:09:09 +0100246 checkOutputsForDevice(device, state, outputs);
François Gaffie2110e042015-03-24 08:41:51 +0100247
jiabinc0048632023-04-27 22:04:31 +0000248 // Send Disconnect to HALs
249 broadcastDeviceConnectionState(device, media::DeviceConnectedState::DISCONNECTED);
250
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800251 // Reset active device codec
252 device->setEncodedFormat(AUDIO_FORMAT_DEFAULT);
253
Kriti Dangef6be8f2020-11-05 11:58:19 +0100254 // remove device from mReportedFormatsMap cache
255 mReportedFormatsMap.erase(device);
256
jiabina84c3d32022-12-02 18:59:55 +0000257 // remove preferred mixer configurations
258 mPreferredMixerAttrInfos.erase(device->getId());
259
Eric Laurente552edb2014-03-10 17:42:56 -0700260 } break;
261
262 default:
François Gaffie11d30102018-11-02 16:09:09 +0100263 ALOGE("%s() invalid state: %x", __func__, state);
Eric Laurente552edb2014-03-10 17:42:56 -0700264 return BAD_VALUE;
265 }
266
Eric Laurent736a1022019-03-27 18:28:46 -0700267 // Propagate device availability to Engine
268 setEngineDeviceConnectionState(device, state);
269
Eric Laurentae970022019-01-29 14:25:04 -0800270 // No need to evaluate playback routing when connecting a remote submix
271 // output device used by a dynamic policy of type recorder as no
272 // playback use case is affected.
273 bool doCheckForDeviceAndOutputChanges = true;
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700274 if (device->type() == AUDIO_DEVICE_OUT_REMOTE_SUBMIX && device->address() != "0") {
Eric Laurentae970022019-01-29 14:25:04 -0800275 for (audio_io_handle_t output : outputs) {
276 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
Mikhail Naganovbfac5832019-03-05 16:55:28 -0800277 sp<AudioPolicyMix> policyMix = desc->mPolicyMix.promote();
278 if (policyMix != nullptr
279 && policyMix->mMixType == MIX_TYPE_RECORDERS
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700280 && device->address() == policyMix->mDeviceAddress.string()) {
Eric Laurentae970022019-01-29 14:25:04 -0800281 doCheckForDeviceAndOutputChanges = false;
282 break;
283 }
284 }
285 }
286
287 auto checkCloseOutputs = [&]() {
Mikhail Naganov37977152018-07-11 15:54:44 -0700288 // outputs must be closed after checkOutputForAllStrategies() is executed
289 if (!outputs.isEmpty()) {
290 for (audio_io_handle_t output : outputs) {
291 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
François Gaffie11d30102018-11-02 16:09:09 +0100292 // close unused outputs after device disconnection or direct outputs that have
293 // been opened by checkOutputsForDevice() to query dynamic parameters
Eric Laurente191d1b2022-04-15 11:59:25 +0200294 // "outputs" vector never contains duplicated outputs
Eric Laurentcad6c0d2021-07-13 15:12:39 +0200295 if ((state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE)
296 || (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != 0) &&
Eric Laurente191d1b2022-04-15 11:59:25 +0200297 (desc->mDirectOpenCount == 0))
298 || (((desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0) &&
299 !isOutputOnlyAvailableRouteToSomeDevice(desc))) {
Francois Gaffieff1eb522020-05-06 18:37:04 +0200300 clearAudioSourcesForOutput(output);
Mikhail Naganov37977152018-07-11 15:54:44 -0700301 closeOutput(output);
302 }
Eric Laurente552edb2014-03-10 17:42:56 -0700303 }
Mikhail Naganov37977152018-07-11 15:54:44 -0700304 // check A2DP again after closing A2DP output to reset mA2dpSuspended if needed
305 return true;
Eric Laurente552edb2014-03-10 17:42:56 -0700306 }
Mikhail Naganov37977152018-07-11 15:54:44 -0700307 return false;
Eric Laurentae970022019-01-29 14:25:04 -0800308 };
309
310 if (doCheckForDeviceAndOutputChanges) {
311 checkForDeviceAndOutputChanges(checkCloseOutputs);
312 } else {
313 checkCloseOutputs();
314 }
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100315 (void)updateCallRouting(false /*fromCache*/);
François Gaffie11d30102018-11-02 16:09:09 +0100316 const DeviceVector msdOutDevices = getMsdAudioOutDevices();
jiabinbce0c1d2020-10-05 11:20:18 -0700317 const DeviceVector activeMediaDevices =
318 mEngine->getActiveMediaDevices(mAvailableOutputDevices);
jiabin3ff8d7d2022-12-13 06:27:44 +0000319 std::map<audio_io_handle_t, DeviceVector> outputsToReopenWithDevices;
Eric Laurente552edb2014-03-10 17:42:56 -0700320 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700321 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Jaideep Sharma89b5b852020-11-23 16:41:33 +0530322 if (desc->isActive() && ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) ||
323 (desc != mPrimaryOutput))) {
François Gaffie11d30102018-11-02 16:09:09 +0100324 DeviceVector newDevices = getNewOutputDevices(desc, true /*fromCache*/);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700325 // do not force device change on duplicated output because if device is 0, it will
326 // also force a device 0 for the two outputs it is duplicated to which may override
327 // a valid device selection on those outputs.
François Gaffie11d30102018-11-02 16:09:09 +0100328 bool force = (msdOutDevices.isEmpty() || msdOutDevices != desc->devices())
Mikhail Naganov15be9d22017-11-08 14:18:13 +1100329 && !desc->isDuplicated()
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700330 && (!device_distinguishes_on_address(device->type())
Eric Laurentc2730ba2014-07-20 15:47:07 -0700331 // always force when disconnecting (a non-duplicated device)
332 || (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE));
jiabin3ff8d7d2022-12-13 06:27:44 +0000333 if (desc->mUsePreferredMixerAttributes && newDevices != desc->devices()) {
334 // If the device is using preferred mixer attributes, the output need to reopen
335 // with default configuration when the new selected devices are different from
336 // current routing devices
337 outputsToReopenWithDevices.emplace(mOutputs.keyAt(i), newDevices);
338 continue;
339 }
François Gaffie11d30102018-11-02 16:09:09 +0100340 setOutputDevices(desc, newDevices, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700341 }
jiabinbce0c1d2020-10-05 11:20:18 -0700342 if (!desc->isDuplicated() && desc->mProfile->hasDynamicAudioProfile() &&
jiabin498d2152021-04-02 00:26:46 +0000343 !activeMediaDevices.empty() && desc->devices() != activeMediaDevices &&
jiabinbce0c1d2020-10-05 11:20:18 -0700344 desc->supportsDevicesForPlayback(activeMediaDevices)) {
345 // Reopen the output to query the dynamic profiles when there is not active
346 // clients or all active clients will be rerouted. Otherwise, set the flag
347 // `mPendingReopenToQueryProfiles` in the SwOutputDescriptor so that the output
348 // can be reopened to query dynamic profiles when all clients are inactive.
349 if (areAllActiveTracksRerouted(desc)) {
jiabin3ff8d7d2022-12-13 06:27:44 +0000350 outputsToReopenWithDevices.emplace(mOutputs.keyAt(i), activeMediaDevices);
jiabinbce0c1d2020-10-05 11:20:18 -0700351 } else {
352 desc->mPendingReopenToQueryProfiles = true;
353 }
354 }
355 if (!desc->supportsDevicesForPlayback(activeMediaDevices)) {
356 // Clear the flag that previously set for re-querying profiles.
357 desc->mPendingReopenToQueryProfiles = false;
358 }
359 }
jiabin3ff8d7d2022-12-13 06:27:44 +0000360 reopenOutputsWithDevices(outputsToReopenWithDevices);
Eric Laurente552edb2014-03-10 17:42:56 -0700361
Eric Laurentd60560a2015-04-10 11:31:20 -0700362 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
François Gaffie11d30102018-11-02 16:09:09 +0100363 cleanUpForDevice(device);
Eric Laurentd60560a2015-04-10 11:31:20 -0700364 }
365
Eric Laurent96d1dda2022-03-14 17:14:19 +0100366 checkLeBroadcastRoutes(wasLeUnicastActive, nullptr, 0);
367
Eric Laurent72aa32f2014-05-30 18:51:48 -0700368 mpClientInterface->onAudioPortListUpdate();
Eric Laurentb71e58b2014-05-29 16:08:11 -0700369 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700370 } // end if is output device
371
Eric Laurente552edb2014-03-10 17:42:56 -0700372 // handle input devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700373 if (audio_is_input_device(device->type())) {
François Gaffie11d30102018-11-02 16:09:09 +0100374 ssize_t index = mAvailableInputDevices.indexOf(device);
Eric Laurente552edb2014-03-10 17:42:56 -0700375 switch (state)
376 {
377 // handle input device connection
Eric Laurent3b73df72014-03-11 09:06:29 -0700378 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700379 if (index >= 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100380 ALOGW("%s() device already connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700381 return INVALID_OPERATION;
382 }
Eric Laurent0dd51852019-04-19 18:18:58 -0700383
384 if (mAvailableInputDevices.add(device) < 0) {
385 return NO_MEMORY;
386 }
387
François Gaffie44481e72016-04-20 07:49:57 +0200388 // Before checking intputs, broadcast connect event to allow HAL to retrieve dynamic
389 // parameters on newly connected devices (instead of opening the inputs...)
jiabinc0048632023-04-27 22:04:31 +0000390 broadcastDeviceConnectionState(device, media::DeviceConnectedState::CONNECTED);
François Gaffie44481e72016-04-20 07:49:57 +0200391
Eric Laurent0dd51852019-04-19 18:18:58 -0700392 if (checkInputsForDevice(device, state) != NO_ERROR) {
393 mAvailableInputDevices.remove(device);
394
jiabinc0048632023-04-27 22:04:31 +0000395 broadcastDeviceConnectionState(device, media::DeviceConnectedState::DISCONNECTED);
Francois Gaffie716e1432019-01-14 16:58:59 +0100396
397 mHwModules.cleanUpForDevice(device);
398
Eric Laurentd4692962014-05-05 18:13:44 -0700399 return INVALID_OPERATION;
400 }
401
Eric Laurentd4692962014-05-05 18:13:44 -0700402 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700403
404 // handle input device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700405 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700406 if (index < 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100407 ALOGW("%s() device not connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700408 return INVALID_OPERATION;
409 }
Paul McLean5c477aa2014-08-20 16:47:57 -0700410
François Gaffie11d30102018-11-02 16:09:09 +0100411 ALOGV("%s() disconnecting input device %s", __func__, device->toString().c_str());
Paul McLean5c477aa2014-08-20 16:47:57 -0700412
jiabinc0048632023-04-27 22:04:31 +0000413 // Notify the HAL to prepare to disconnect device
414 broadcastDeviceConnectionState(
415 device, media::DeviceConnectedState::PREPARE_TO_DISCONNECT);
Paul McLean5c477aa2014-08-20 16:47:57 -0700416
François Gaffie11d30102018-11-02 16:09:09 +0100417 mAvailableInputDevices.remove(device);
Eric Laurent0dd51852019-04-19 18:18:58 -0700418
419 checkInputsForDevice(device, state);
Kriti Dangef6be8f2020-11-05 11:58:19 +0100420
jiabinc0048632023-04-27 22:04:31 +0000421 // Set Disconnect to HALs
422 broadcastDeviceConnectionState(device, media::DeviceConnectedState::DISCONNECTED);
423
Kriti Dangef6be8f2020-11-05 11:58:19 +0100424 // remove device from mReportedFormatsMap cache
425 mReportedFormatsMap.erase(device);
Eric Laurentd4692962014-05-05 18:13:44 -0700426 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700427
428 default:
François Gaffie11d30102018-11-02 16:09:09 +0100429 ALOGE("%s() invalid state: %x", __func__, state);
Eric Laurente552edb2014-03-10 17:42:56 -0700430 return BAD_VALUE;
431 }
432
Eric Laurent736a1022019-03-27 18:28:46 -0700433 // Propagate device availability to Engine
434 setEngineDeviceConnectionState(device, state);
435
Eric Laurent0dd51852019-04-19 18:18:58 -0700436 checkCloseInputs();
Eric Laurent5f5fca52016-08-04 11:48:57 -0700437 // As the input device list can impact the output device selection, update
438 // getDeviceForStrategy() cache
439 updateDevicesAndOutputs();
Eric Laurente552edb2014-03-10 17:42:56 -0700440
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100441 (void)updateCallRouting(false /*fromCache*/);
Francois Gaffiea0e5c992020-09-29 16:05:07 +0200442 // Reconnect Audio Source
443 for (const auto &strategy : mEngine->getOrderedProductStrategies()) {
444 auto attributes = mEngine->getAllAttributesForProductStrategy(strategy).front();
445 checkAudioSourceForAttributes(attributes);
446 }
Eric Laurentd60560a2015-04-10 11:31:20 -0700447 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
François Gaffie11d30102018-11-02 16:09:09 +0100448 cleanUpForDevice(device);
Eric Laurentd60560a2015-04-10 11:31:20 -0700449 }
450
Eric Laurentb52c1522014-05-20 11:27:36 -0700451 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -0700452 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700453 } // end if is input device
Eric Laurente552edb2014-03-10 17:42:56 -0700454
François Gaffie11d30102018-11-02 16:09:09 +0100455 ALOGW("%s() invalid device: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700456 return BAD_VALUE;
457}
458
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100459status_t AudioPolicyManager::deviceToAudioPort(audio_devices_t device, const char* device_address,
460 const char* device_name,
Atneya Nair638a6e42022-12-18 16:45:15 -0800461 media::AudioPortFw* aidlPort) {
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100462 DeviceDescriptorBase devDescr(device, device_address);
463 devDescr.setName(device_name);
464 return devDescr.writeToParcelable(aidlPort);
465}
466
Eric Laurent736a1022019-03-27 18:28:46 -0700467void AudioPolicyManager::setEngineDeviceConnectionState(const sp<DeviceDescriptor> device,
468 audio_policy_dev_state_t state) {
469
470 // the Engine does not have to know about remote submix devices used by dynamic audio policies
471 if (audio_is_remote_submix_device(device->type()) && device->address() != "0") {
472 return;
473 }
474 mEngine->setDeviceConnectionState(device, state);
475}
476
477
Eric Laurente0720872014-03-11 09:30:41 -0700478audio_policy_dev_state_t AudioPolicyManager::getDeviceConnectionState(audio_devices_t device,
François Gaffie53615e22015-03-19 09:24:12 +0100479 const char *device_address)
Eric Laurente552edb2014-03-10 17:42:56 -0700480{
Eric Laurent634b7142016-04-20 13:48:02 -0700481 sp<DeviceDescriptor> devDesc =
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800482 mHwModules.getDeviceDescriptor(device, device_address, "", AUDIO_FORMAT_DEFAULT,
483 false /* allowToCreate */,
Eric Laurent634b7142016-04-20 13:48:02 -0700484 (strlen(device_address) != 0)/*matchAddress*/);
485
486 if (devDesc == 0) {
François Gaffie251c7f02018-11-07 10:41:08 +0100487 ALOGV("getDeviceConnectionState() undeclared device, type %08x, address: %s",
Eric Laurent634b7142016-04-20 13:48:02 -0700488 device, device_address);
489 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
490 }
François Gaffie53615e22015-03-19 09:24:12 +0100491
Eric Laurent3a4311c2014-03-17 12:00:47 -0700492 DeviceVector *deviceVector;
493
Eric Laurente552edb2014-03-10 17:42:56 -0700494 if (audio_is_output_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700495 deviceVector = &mAvailableOutputDevices;
Eric Laurente552edb2014-03-10 17:42:56 -0700496 } else if (audio_is_input_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700497 deviceVector = &mAvailableInputDevices;
498 } else {
François Gaffie11d30102018-11-02 16:09:09 +0100499 ALOGW("%s() invalid device type %08x", __func__, device);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700500 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurente552edb2014-03-10 17:42:56 -0700501 }
Eric Laurent634b7142016-04-20 13:48:02 -0700502
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800503 return (deviceVector->getDevice(
504 device, String8(device_address), AUDIO_FORMAT_DEFAULT) != 0) ?
Eric Laurent634b7142016-04-20 13:48:02 -0700505 AUDIO_POLICY_DEVICE_STATE_AVAILABLE : AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurenta1d525f2015-01-29 13:36:45 -0800506}
507
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800508status_t AudioPolicyManager::handleDeviceConfigChange(audio_devices_t device,
509 const char *device_address,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800510 const char *device_name,
511 audio_format_t encodedFormat)
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800512{
513 status_t status;
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700514 String8 reply;
515 AudioParameter param;
516 int isReconfigA2dpSupported = 0;
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800517
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800518 ALOGV("handleDeviceConfigChange(() device: 0x%X, address %s name %s encodedFormat: 0x%X",
519 device, device_address, device_name, encodedFormat);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800520
Pavlin Radoslavovc694ff42017-01-09 23:27:29 -0800521 // connect/disconnect only 1 device at a time
522 if (!audio_is_output_device(device) && !audio_is_input_device(device)) return BAD_VALUE;
523
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800524 // Check if the device is currently connected
jiabin9a3361e2019-10-01 09:38:30 -0700525 DeviceVector deviceList = mAvailableOutputDevices.getDevicesFromType(device);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800526 if (deviceList.empty()) {
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800527 // Nothing to do: device is not connected
528 return NO_ERROR;
529 }
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800530 sp<DeviceDescriptor> devDesc = deviceList.itemAt(0);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800531
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700532 // For offloaded A2DP, Hw modules may have the capability to
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800533 // configure codecs.
534 // Handle two specific cases by sending a set parameter to
535 // configure A2DP codecs. No need to toggle device state.
536 // Case 1: A2DP active device switches from primary to primary
537 // module
538 // Case 2: A2DP device config changes on primary module.
Francois Gaffiebce7cd42020-10-14 16:13:20 +0200539 if (audio_is_a2dp_out_device(device) && hasPrimaryOutput()) {
jiabin9a3361e2019-10-01 09:38:30 -0700540 sp<HwModule> module = mHwModules.getModuleForDeviceType(device, encodedFormat);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800541 audio_module_handle_t primaryHandle = mPrimaryOutput->getModuleHandle();
542 if (availablePrimaryOutputDevices().contains(devDesc) &&
543 (module != 0 && module->getHandle() == primaryHandle)) {
544 reply = mpClientInterface->getParameters(
545 AUDIO_IO_HANDLE_NONE,
546 String8(AudioParameter::keyReconfigA2dpSupported));
547 AudioParameter repliedParameters(reply);
548 repliedParameters.getInt(
549 String8(AudioParameter::keyReconfigA2dpSupported), isReconfigA2dpSupported);
550 if (isReconfigA2dpSupported) {
551 const String8 key(AudioParameter::keyReconfigA2dp);
552 param.add(key, String8("true"));
553 mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString());
554 devDesc->setEncodedFormat(encodedFormat);
555 return NO_ERROR;
556 }
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700557 }
558 }
cnx421bd2dcc42020-07-11 14:58:44 +0800559 auto musicStrategy = streamToStrategy(AUDIO_STREAM_MUSIC);
560 for (size_t i = 0; i < mOutputs.size(); i++) {
561 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
562 // mute media strategies and delay device switch by the largest
563 // This avoid sending the music tail into the earpiece or headset.
564 setStrategyMute(musicStrategy, true, desc);
565 setStrategyMute(musicStrategy, false, desc, MUTE_TIME_MS,
566 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
567 nullptr, true /*fromCache*/).types());
568 }
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800569 // Toggle the device state: UNAVAILABLE -> AVAILABLE
570 // This will force reading again the device configuration
571 status = setDeviceConnectionState(device,
572 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800573 device_address, device_name,
574 devDesc->getEncodedFormat());
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800575 if (status != NO_ERROR) {
576 ALOGW("handleDeviceConfigChange() error disabling connection state: %d",
577 status);
578 return status;
579 }
580
581 status = setDeviceConnectionState(device,
582 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800583 device_address, device_name, encodedFormat);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800584 if (status != NO_ERROR) {
585 ALOGW("handleDeviceConfigChange() error enabling connection state: %d",
586 status);
587 return status;
588 }
589
590 return NO_ERROR;
591}
592
Pattydd807582021-11-04 21:01:03 +0800593status_t AudioPolicyManager::getHwOffloadFormatsSupportedForBluetoothMedia(
594 audio_devices_t device, std::vector<audio_format_t> *formats)
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800595{
Pattydd807582021-11-04 21:01:03 +0800596 ALOGV("getHwOffloadFormatsSupportedForBluetoothMedia()");
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800597 status_t status = NO_ERROR;
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800598 std::unordered_set<audio_format_t> formatSet;
599 sp<HwModule> primaryModule =
600 mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_PRIMARY);
Aniket Kumar Latafedb5982019-07-03 11:20:36 -0700601 if (primaryModule == nullptr) {
602 ALOGE("%s() unable to get primary module", __func__);
603 return NO_INIT;
604 }
Pattydd807582021-11-04 21:01:03 +0800605
606 DeviceTypeSet audioDeviceSet;
607
608 switch(device) {
609 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP:
610 audioDeviceSet = getAudioDeviceOutAllA2dpSet();
611 break;
612 case AUDIO_DEVICE_OUT_BLE_HEADSET:
Patty Huang36028df2022-07-06 00:14:12 +0800613 audioDeviceSet = getAudioDeviceOutLeAudioUnicastSet();
614 break;
615 case AUDIO_DEVICE_OUT_BLE_BROADCAST:
616 audioDeviceSet = getAudioDeviceOutLeAudioBroadcastSet();
Pattydd807582021-11-04 21:01:03 +0800617 break;
618 default:
619 ALOGE("%s() device type 0x%08x not supported", __func__, device);
620 return BAD_VALUE;
621 }
622
jiabin9a3361e2019-10-01 09:38:30 -0700623 DeviceVector declaredDevices = primaryModule->getDeclaredDevices().getDevicesFromTypes(
Pattydd807582021-11-04 21:01:03 +0800624 audioDeviceSet);
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800625 for (const auto& device : declaredDevices) {
626 formatSet.insert(device->encodedFormats().begin(), device->encodedFormats().end());
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800627 }
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800628 formats->assign(formatSet.begin(), formatSet.end());
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800629 return status;
630}
631
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100632DeviceVector AudioPolicyManager::selectBestRxSinkDevicesForCall(bool fromCache)
633{
634 DeviceVector rxSinkdevices{};
635 rxSinkdevices = mEngine->getOutputDevicesForAttributes(
636 attributes_initializer(AUDIO_USAGE_VOICE_COMMUNICATION), nullptr, fromCache);
637 if (!rxSinkdevices.isEmpty() && mAvailableOutputDevices.contains(rxSinkdevices.itemAt(0))) {
638 auto rxSinkDevice = rxSinkdevices.itemAt(0);
639 auto telephonyRxModule = mHwModules.getModuleForDeviceType(
640 AUDIO_DEVICE_IN_TELEPHONY_RX, AUDIO_FORMAT_DEFAULT);
641 // retrieve Rx Source device descriptor
642 sp<DeviceDescriptor> rxSourceDevice = mAvailableInputDevices.getDevice(
643 AUDIO_DEVICE_IN_TELEPHONY_RX, String8(), AUDIO_FORMAT_DEFAULT);
644
645 // RX Telephony and Rx sink devices are declared by Primary Audio HAL
646 if (isPrimaryModule(telephonyRxModule) && (telephonyRxModule->getHalVersionMajor() >= 3) &&
647 telephonyRxModule->supportsPatch(rxSourceDevice, rxSinkDevice)) {
648 ALOGW("%s() device %s using HW Bridge", __func__, rxSinkDevice->toString().c_str());
649 return DeviceVector(rxSinkDevice);
650 }
651 }
652 // Note that despite the fact that getNewOutputDevices() is called on the primary output,
653 // the device returned is not necessarily reachable via this output
654 // (filter later by setOutputDevices())
655 return getNewOutputDevices(mPrimaryOutput, fromCache);
656}
657
658status_t AudioPolicyManager::updateCallRouting(bool fromCache, uint32_t delayMs, uint32_t *waitMs)
659{
660 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL && hasPrimaryOutput()) {
661 DeviceVector rxDevices = selectBestRxSinkDevicesForCall(fromCache);
662 return updateCallRoutingInternal(rxDevices, delayMs, waitMs);
663 }
664 return INVALID_OPERATION;
665}
666
667status_t AudioPolicyManager::updateCallRoutingInternal(
668 const DeviceVector &rxDevices, uint32_t delayMs, uint32_t *waitMs)
Eric Laurentc2730ba2014-07-20 15:47:07 -0700669{
670 bool createTxPatch = false;
François Gaffie9eb18552018-11-05 10:33:26 +0100671 bool createRxPatch = false;
Eric Laurentdc462862016-07-19 12:29:53 -0700672 uint32_t muteWaitMs = 0;
jiabin9a3361e2019-10-01 09:38:30 -0700673 if(!hasPrimaryOutput() ||
674 mPrimaryOutput->devices().onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_STUB)) {
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100675 return INVALID_OPERATION;
Eric Laurent87ffa392015-05-22 10:32:38 -0700676 }
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100677 ALOG_ASSERT(!rxDevices.isEmpty(), "%s() no selected output device", __func__);
François Gaffie11d30102018-11-02 16:09:09 +0100678
Francois Gaffie716e1432019-01-14 16:58:59 +0100679 audio_attributes_t attr = { .source = AUDIO_SOURCE_VOICE_COMMUNICATION };
François Gaffiec005e562018-11-06 15:04:49 +0100680 auto txSourceDevice = mEngine->getInputDeviceForAttributes(attr);
Eric Laurentcedd5b52023-03-22 00:03:31 +0000681 if (txSourceDevice == nullptr) {
682 ALOGE("%s() selected input device not available", __func__);
683 return INVALID_OPERATION;
684 }
François Gaffiec005e562018-11-06 15:04:49 +0100685
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100686 ALOGV("%s device rxDevice %s txDevice %s", __func__,
François Gaffie9eb18552018-11-05 10:33:26 +0100687 rxDevices.itemAt(0)->toString().c_str(), txSourceDevice->toString().c_str());
Eric Laurentc2730ba2014-07-20 15:47:07 -0700688
Francois Gaffie601801d2021-06-22 13:27:39 +0200689 disconnectTelephonyAudioSource(mCallRxSourceClient);
690 disconnectTelephonyAudioSource(mCallTxSourceClient);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700691
François Gaffie9eb18552018-11-05 10:33:26 +0100692 auto telephonyRxModule =
jiabin9a3361e2019-10-01 09:38:30 -0700693 mHwModules.getModuleForDeviceType(AUDIO_DEVICE_IN_TELEPHONY_RX, AUDIO_FORMAT_DEFAULT);
François Gaffie9eb18552018-11-05 10:33:26 +0100694 auto telephonyTxModule =
jiabin9a3361e2019-10-01 09:38:30 -0700695 mHwModules.getModuleForDeviceType(AUDIO_DEVICE_OUT_TELEPHONY_TX, AUDIO_FORMAT_DEFAULT);
François Gaffie9eb18552018-11-05 10:33:26 +0100696 // retrieve Rx Source and Tx Sink device descriptors
697 sp<DeviceDescriptor> rxSourceDevice =
698 mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_TELEPHONY_RX,
699 String8(),
700 AUDIO_FORMAT_DEFAULT);
701 sp<DeviceDescriptor> txSinkDevice =
702 mAvailableOutputDevices.getDevice(AUDIO_DEVICE_OUT_TELEPHONY_TX,
703 String8(),
704 AUDIO_FORMAT_DEFAULT);
705
706 // RX and TX Telephony device are declared by Primary Audio HAL
707 if (isPrimaryModule(telephonyRxModule) && isPrimaryModule(telephonyTxModule) &&
708 (telephonyRxModule->getHalVersionMajor() >= 3)) {
709 if (rxSourceDevice == 0 || txSinkDevice == 0) {
710 // RX / TX Telephony device(s) is(are) not currently available
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100711 ALOGE("%s() no telephony Tx and/or RX device", __func__);
712 return INVALID_OPERATION;
François Gaffie9eb18552018-11-05 10:33:26 +0100713 }
François Gaffieafd4cea2019-11-18 15:50:22 +0100714 // createAudioPatchInternal now supports both HW / SW bridging
715 createRxPatch = true;
716 createTxPatch = true;
François Gaffie9eb18552018-11-05 10:33:26 +0100717 } else {
718 // If the RX device is on the primary HW module, then use legacy routing method for
719 // voice calls via setOutputDevice() on primary output.
720 // Otherwise, create two audio patches for TX and RX path.
721 createRxPatch = !(availablePrimaryOutputDevices().contains(rxDevices.itemAt(0))) &&
722 (rxSourceDevice != 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700723 // If the TX device is also on the primary HW module, setOutputDevice() will take care
724 // of it due to legacy implementation. If not, create a patch.
François Gaffie9eb18552018-11-05 10:33:26 +0100725 createTxPatch = !(availablePrimaryModuleInputDevices().contains(txSourceDevice)) &&
726 (txSinkDevice != 0);
727 }
728 // Use legacy routing method for voice calls via setOutputDevice() on primary output.
729 // Otherwise, create two audio patches for TX and RX path.
730 if (!createRxPatch) {
731 muteWaitMs = setOutputDevices(mPrimaryOutput, rxDevices, true, delayMs);
Eric Laurent8ae73122016-04-12 10:13:29 -0700732 } else { // create RX path audio patch
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200733 connectTelephonyRxAudioSource();
juyuchen2224c5a2019-01-21 12:00:58 +0800734 // If the TX device is on the primary HW module but RX device is
735 // on other HW module, SinkMetaData of telephony input should handle it
736 // assuming the device uses audio HAL V5.0 and above
Eric Laurentc2730ba2014-07-20 15:47:07 -0700737 }
Eric Laurent8ae73122016-04-12 10:13:29 -0700738 if (createTxPatch) { // create TX path audio patch
François Gaffieafd4cea2019-11-18 15:50:22 +0100739 // terminate active capture if on the same HW module as the call TX source device
740 // FIXME: would be better to refine to only inputs whose profile connects to the
741 // call TX device but this information is not in the audio patch and logic here must be
742 // symmetric to the one in startInput()
743 for (const auto& activeDesc : mInputs.getActiveInputs()) {
744 if (activeDesc->hasSameHwModuleAs(txSourceDevice)) {
745 closeActiveClients(activeDesc);
746 }
747 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200748 connectTelephonyTxAudioSource(txSourceDevice, txSinkDevice, delayMs);
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800749 }
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100750 if (waitMs != nullptr) {
751 *waitMs = muteWaitMs;
752 }
753 return NO_ERROR;
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800754}
Eric Laurentc2730ba2014-07-20 15:47:07 -0700755
Mikhail Naganov100f0122018-11-29 11:22:16 -0800756bool AudioPolicyManager::isDeviceOfModule(
757 const sp<DeviceDescriptor>& devDesc, const char *moduleId) const {
758 sp<HwModule> module = mHwModules.getModuleFromName(moduleId);
759 if (module != 0) {
760 return mAvailableOutputDevices.getDevicesFromHwModule(module->getHandle())
761 .indexOf(devDesc) != NAME_NOT_FOUND
762 || mAvailableInputDevices.getDevicesFromHwModule(module->getHandle())
763 .indexOf(devDesc) != NAME_NOT_FOUND;
764 }
765 return false;
766}
767
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200768void AudioPolicyManager::connectTelephonyRxAudioSource()
769{
Francois Gaffie601801d2021-06-22 13:27:39 +0200770 disconnectTelephonyAudioSource(mCallRxSourceClient);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200771 const struct audio_port_config source = {
772 .role = AUDIO_PORT_ROLE_SOURCE, .type = AUDIO_PORT_TYPE_DEVICE,
773 .ext.device.type = AUDIO_DEVICE_IN_TELEPHONY_RX, .ext.device.address = ""
774 };
775 const auto aa = mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL);
Francois Gaffie601801d2021-06-22 13:27:39 +0200776 mCallRxSourceClient = startAudioSourceInternal(&source, &aa, 0/*uid*/);
777 ALOGE_IF(mCallRxSourceClient == nullptr,
778 "%s failed to start Telephony Rx AudioSource", __func__);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200779}
780
Francois Gaffie601801d2021-06-22 13:27:39 +0200781void AudioPolicyManager::disconnectTelephonyAudioSource(sp<SourceClientDescriptor> &clientDesc)
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200782{
Francois Gaffie601801d2021-06-22 13:27:39 +0200783 if (clientDesc == nullptr) {
784 return;
785 }
786 ALOGW_IF(stopAudioSource(clientDesc->portId()) != NO_ERROR,
787 "%s error stopping audio source", __func__);
788 clientDesc.clear();
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200789}
790
791void AudioPolicyManager::connectTelephonyTxAudioSource(
792 const sp<DeviceDescriptor> &srcDevice, const sp<DeviceDescriptor> &sinkDevice,
793 uint32_t delayMs)
794{
Francois Gaffie601801d2021-06-22 13:27:39 +0200795 disconnectTelephonyAudioSource(mCallTxSourceClient);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200796 if (srcDevice == nullptr || sinkDevice == nullptr) {
797 ALOGW("%s could not create patch, invalid sink and/or source device(s)", __func__);
798 return;
799 }
800 PatchBuilder patchBuilder;
801 patchBuilder.addSource(srcDevice).addSink(sinkDevice);
802 ALOGV("%s between source %s and sink %s", __func__,
803 srcDevice->toString().c_str(), sinkDevice->toString().c_str());
Francois Gaffie601801d2021-06-22 13:27:39 +0200804 auto callTxSourceClientPortId = PolicyAudioPort::getNextUniqueId();
Eric Laurent78b07302022-10-07 16:20:34 +0200805 const auto aa = mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL);
806
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200807 struct audio_port_config source = {};
808 srcDevice->toAudioPortConfig(&source);
Francois Gaffie601801d2021-06-22 13:27:39 +0200809 mCallTxSourceClient = new InternalSourceClientDescriptor(
810 callTxSourceClientPortId, mUidCached, aa, source, srcDevice, sinkDevice,
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200811 mCommunnicationStrategy, toVolumeSource(aa));
812 audio_patch_handle_t patchHandle = AUDIO_PATCH_HANDLE_NONE;
813 status_t status = connectAudioSourceToSink(
Francois Gaffie601801d2021-06-22 13:27:39 +0200814 mCallTxSourceClient, sinkDevice, patchBuilder.patch(), patchHandle, mUidCached,
815 delayMs);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200816 ALOGE_IF(status != NO_ERROR, "%s() error %d creating TX audio patch", __func__, status);
817 if (status == NO_ERROR) {
Francois Gaffie601801d2021-06-22 13:27:39 +0200818 mAudioSources.add(callTxSourceClientPortId, mCallTxSourceClient);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200819 }
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200820}
821
Eric Laurente0720872014-03-11 09:30:41 -0700822void AudioPolicyManager::setPhoneState(audio_mode_t state)
Eric Laurente552edb2014-03-10 17:42:56 -0700823{
824 ALOGV("setPhoneState() state %d", state);
François Gaffie2110e042015-03-24 08:41:51 +0100825 // store previous phone state for management of sonification strategy below
826 int oldState = mEngine->getPhoneState();
Eric Laurent96d1dda2022-03-14 17:14:19 +0100827 bool wasLeUnicastActive = isLeUnicastActive();
François Gaffie2110e042015-03-24 08:41:51 +0100828
829 if (mEngine->setPhoneState(state) != NO_ERROR) {
830 ALOGW("setPhoneState() invalid or same state %d", state);
Eric Laurente552edb2014-03-10 17:42:56 -0700831 return;
832 }
François Gaffie2110e042015-03-24 08:41:51 +0100833 /// Opens: can these line be executed after the switch of volume curves???
Eric Laurent63dea1d2015-07-02 17:10:28 -0700834 if (isStateInCall(oldState)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700835 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent63dea1d2015-07-02 17:10:28 -0700836 // force reevaluating accessibility routing when call stops
jiabinc44b3462022-12-08 12:52:31 -0800837 invalidateStreams({AUDIO_STREAM_ACCESSIBILITY});
Eric Laurente552edb2014-03-10 17:42:56 -0700838 }
839
François Gaffie2110e042015-03-24 08:41:51 +0100840 /**
841 * Switching to or from incall state or switching between telephony and VoIP lead to force
842 * routing command.
843 */
Eric Laurent74b71512019-11-06 17:21:57 -0800844 bool force = ((isStateInCall(oldState) != isStateInCall(state))
845 || (isStateInCall(state) && (state != oldState)));
Eric Laurente552edb2014-03-10 17:42:56 -0700846
847 // check for device and output changes triggered by new phone state
Mikhail Naganov37977152018-07-11 15:54:44 -0700848 checkForDeviceAndOutputChanges();
Eric Laurente552edb2014-03-10 17:42:56 -0700849
Eric Laurente552edb2014-03-10 17:42:56 -0700850 int delayMs = 0;
851 if (isStateInCall(state)) {
852 nsecs_t sysTime = systemTime();
François Gaffiec005e562018-11-06 15:04:49 +0100853 auto musicStrategy = streamToStrategy(AUDIO_STREAM_MUSIC);
854 auto sonificationStrategy = streamToStrategy(AUDIO_STREAM_ALARM);
Eric Laurente552edb2014-03-10 17:42:56 -0700855 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700856 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700857 // mute media and sonification strategies and delay device switch by the largest
858 // latency of any output where either strategy is active.
859 // This avoid sending the ring tone or music tail into the earpiece or headset.
François Gaffiec005e562018-11-06 15:04:49 +0100860 if ((desc->isStrategyActive(musicStrategy, SONIFICATION_HEADSET_MUSIC_DELAY, sysTime) ||
861 desc->isStrategyActive(sonificationStrategy, SONIFICATION_HEADSET_MUSIC_DELAY,
862 sysTime)) &&
Eric Laurentc75307b2015-03-17 15:29:32 -0700863 (delayMs < (int)desc->latency()*2)) {
864 delayMs = desc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -0700865 }
François Gaffiec005e562018-11-06 15:04:49 +0100866 setStrategyMute(musicStrategy, true, desc);
867 setStrategyMute(musicStrategy, false, desc, MUTE_TIME_MS,
868 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
869 nullptr, true /*fromCache*/).types());
870 setStrategyMute(sonificationStrategy, true, desc);
871 setStrategyMute(sonificationStrategy, false, desc, MUTE_TIME_MS,
872 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_ALARM),
873 nullptr, true /*fromCache*/).types());
Eric Laurente552edb2014-03-10 17:42:56 -0700874 }
875 }
876
Eric Laurent87ffa392015-05-22 10:32:38 -0700877 if (hasPrimaryOutput()) {
Eric Laurent87ffa392015-05-22 10:32:38 -0700878 if (state == AUDIO_MODE_IN_CALL) {
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100879 (void)updateCallRouting(false /*fromCache*/, delayMs);
Eric Laurent87ffa392015-05-22 10:32:38 -0700880 } else {
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100881 DeviceVector rxDevices = getNewOutputDevices(mPrimaryOutput, false /*fromCache*/);
882 // force routing command to audio hardware when ending call
883 // even if no device change is needed
884 if (isStateInCall(oldState) && rxDevices.isEmpty()) {
885 rxDevices = mPrimaryOutput->devices();
886 }
887 if (oldState == AUDIO_MODE_IN_CALL) {
Francois Gaffie601801d2021-06-22 13:27:39 +0200888 disconnectTelephonyAudioSource(mCallRxSourceClient);
889 disconnectTelephonyAudioSource(mCallTxSourceClient);
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100890 }
François Gaffie11d30102018-11-02 16:09:09 +0100891 setOutputDevices(mPrimaryOutput, rxDevices, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700892 }
Eric Laurentc2730ba2014-07-20 15:47:07 -0700893 }
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700894
jiabin3ff8d7d2022-12-13 06:27:44 +0000895 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700896 // reevaluate routing on all outputs in case tracks have been started during the call
897 for (size_t i = 0; i < mOutputs.size(); i++) {
898 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
François Gaffie11d30102018-11-02 16:09:09 +0100899 DeviceVector newDevices = getNewOutputDevices(desc, true /*fromCache*/);
Francois Gaffie601801d2021-06-22 13:27:39 +0200900 if (state != AUDIO_MODE_IN_CALL || (desc != mPrimaryOutput && !isTelephonyRxOrTx(desc))) {
901 bool forceRouting = !newDevices.isEmpty();
jiabin3ff8d7d2022-12-13 06:27:44 +0000902 if (desc->mUsePreferredMixerAttributes && newDevices != desc->devices()) {
903 // If the device is using preferred mixer attributes, the output need to reopen
904 // with default configuration when the new selected devices are different from
905 // current routing devices.
906 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices);
907 continue;
908 }
Francois Gaffie601801d2021-06-22 13:27:39 +0200909 setOutputDevices(desc, newDevices, forceRouting, 0 /*delayMs*/, nullptr,
910 true /*requiresMuteCheck*/, !forceRouting /*requiresVolumeCheck*/);
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700911 }
912 }
jiabin3ff8d7d2022-12-13 06:27:44 +0000913 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700914
Eric Laurent96d1dda2022-03-14 17:14:19 +0100915 checkLeBroadcastRoutes(wasLeUnicastActive, nullptr, delayMs);
916
Eric Laurente552edb2014-03-10 17:42:56 -0700917 if (isStateInCall(state)) {
918 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent63dea1d2015-07-02 17:10:28 -0700919 // force reevaluating accessibility routing when call starts
jiabinc44b3462022-12-08 12:52:31 -0800920 invalidateStreams({AUDIO_STREAM_ACCESSIBILITY});
Eric Laurente552edb2014-03-10 17:42:56 -0700921 }
922
923 // Flag that ringtone volume must be limited to music volume until we exit MODE_RINGTONE
François Gaffiec005e562018-11-06 15:04:49 +0100924 mLimitRingtoneVolume = (state == AUDIO_MODE_RINGTONE &&
925 isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY));
Eric Laurente552edb2014-03-10 17:42:56 -0700926}
927
Jean-Michel Trivi887a9ed2015-03-31 18:02:24 -0700928audio_mode_t AudioPolicyManager::getPhoneState() {
929 return mEngine->getPhoneState();
930}
931
Eric Laurente0720872014-03-11 09:30:41 -0700932void AudioPolicyManager::setForceUse(audio_policy_force_use_t usage,
François Gaffie11d30102018-11-02 16:09:09 +0100933 audio_policy_forced_cfg_t config)
Eric Laurente552edb2014-03-10 17:42:56 -0700934{
François Gaffie2110e042015-03-24 08:41:51 +0100935 ALOGV("setForceUse() usage %d, config %d, mPhoneState %d", usage, config, mEngine->getPhoneState());
Eric Laurent8dc87a62017-05-16 19:00:40 -0700936 if (config == mEngine->getForceUse(usage)) {
937 return;
938 }
Eric Laurente552edb2014-03-10 17:42:56 -0700939
François Gaffie2110e042015-03-24 08:41:51 +0100940 if (mEngine->setForceUse(usage, config) != NO_ERROR) {
941 ALOGW("setForceUse() could not set force cfg %d for usage %d", config, usage);
942 return;
Eric Laurente552edb2014-03-10 17:42:56 -0700943 }
François Gaffie2110e042015-03-24 08:41:51 +0100944 bool forceVolumeReeval = (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) ||
945 (usage == AUDIO_POLICY_FORCE_FOR_DOCK) ||
946 (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM);
Eric Laurente552edb2014-03-10 17:42:56 -0700947
948 // check for device and output changes triggered by new force usage
Mikhail Naganov37977152018-07-11 15:54:44 -0700949 checkForDeviceAndOutputChanges();
Phil Burk09bc4612016-02-24 15:58:15 -0800950
Eric Laurent22fcda22019-05-17 16:28:47 -0700951 // force client reconnection to reevaluate flag AUDIO_FLAG_AUDIBILITY_ENFORCED
952 if (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM) {
jiabinc44b3462022-12-08 12:52:31 -0800953 invalidateStreams({AUDIO_STREAM_SYSTEM, AUDIO_STREAM_ENFORCED_AUDIBLE});
Eric Laurent22fcda22019-05-17 16:28:47 -0700954 }
955
Eric Laurentdc462862016-07-19 12:29:53 -0700956 //FIXME: workaround for truncated touch sounds
957 // to be removed when the problem is handled by system UI
958 uint32_t delayMs = 0;
Eric Laurentdc462862016-07-19 12:29:53 -0700959 if (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) {
960 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
961 }
Jean-Michel Trivi30857152019-11-01 11:04:15 -0700962
963 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Eric Laurent2517af32020-11-25 15:31:27 +0100964 updateInputRouting();
Eric Laurente552edb2014-03-10 17:42:56 -0700965}
966
Eric Laurente0720872014-03-11 09:30:41 -0700967void AudioPolicyManager::setSystemProperty(const char* property, const char* value)
Eric Laurente552edb2014-03-10 17:42:56 -0700968{
969 ALOGV("setSystemProperty() property %s, value %s", property, value);
970}
971
Dorin Drimusecc9f422022-03-09 17:57:40 +0100972// Find an MSD output profile compatible with the parameters passed.
973// When "directOnly" is set, restrict search to profiles for direct outputs.
974sp<IOProfile> AudioPolicyManager::getMsdProfileForOutput(
975 const DeviceVector& devices,
976 uint32_t samplingRate,
977 audio_format_t format,
978 audio_channel_mask_t channelMask,
979 audio_output_flags_t flags,
980 bool directOnly)
981{
982 flags = getRelevantFlags(flags, directOnly);
983
984 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
985 if (msdModule != nullptr) {
986 // for the msd module check if there are patches to the output devices
987 if (msdHasPatchesToAllDevices(devices.toTypeAddrVector())) {
988 HwModuleCollection modules;
989 modules.add(msdModule);
990 return searchCompatibleProfileHwModules(
991 modules, getMsdAudioOutDevices(), samplingRate, format, channelMask,
992 flags, directOnly);
993 }
994 }
995 return nullptr;
996}
997
Michael Chana94fbb22018-04-24 14:31:19 +1000998// Find an output profile compatible with the parameters passed. When "directOnly" is set, restrict
999// search to profiles for direct outputs.
1000sp<IOProfile> AudioPolicyManager::getProfileForOutput(
François Gaffie11d30102018-11-02 16:09:09 +01001001 const DeviceVector& devices,
Michael Chana94fbb22018-04-24 14:31:19 +10001002 uint32_t samplingRate,
1003 audio_format_t format,
1004 audio_channel_mask_t channelMask,
1005 audio_output_flags_t flags,
1006 bool directOnly)
Eric Laurente552edb2014-03-10 17:42:56 -07001007{
Dorin Drimusecc9f422022-03-09 17:57:40 +01001008 flags = getRelevantFlags(flags, directOnly);
1009
1010 return searchCompatibleProfileHwModules(
1011 mHwModules, devices, samplingRate, format, channelMask, flags, directOnly);
1012}
1013
1014audio_output_flags_t AudioPolicyManager::getRelevantFlags (
1015 audio_output_flags_t flags, bool directOnly) {
Michael Chana94fbb22018-04-24 14:31:19 +10001016 if (directOnly) {
Dorin Drimusecc9f422022-03-09 17:57:40 +01001017 // only retain flags that will drive the direct output profile selection
1018 // if explicitly requested
1019 static const uint32_t kRelevantFlags =
Michael Chana94fbb22018-04-24 14:31:19 +10001020 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD |
Dorin Drimusecc9f422022-03-09 17:57:40 +01001021 AUDIO_OUTPUT_FLAG_VOIP_RX | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ);
1022 flags = (audio_output_flags_t)((flags & kRelevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
Michael Chana94fbb22018-04-24 14:31:19 +10001023 }
Dorin Drimusecc9f422022-03-09 17:57:40 +01001024 return flags;
1025}
Eric Laurent861a6282015-05-18 15:40:16 -07001026
Dorin Drimusecc9f422022-03-09 17:57:40 +01001027sp<IOProfile> AudioPolicyManager::searchCompatibleProfileHwModules (
1028 const HwModuleCollection& hwModules,
1029 const DeviceVector& devices,
1030 uint32_t samplingRate,
1031 audio_format_t format,
1032 audio_channel_mask_t channelMask,
1033 audio_output_flags_t flags,
1034 bool directOnly) {
Eric Laurent861a6282015-05-18 15:40:16 -07001035 sp<IOProfile> profile;
Dorin Drimusecc9f422022-03-09 17:57:40 +01001036 for (const auto& hwModule : hwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08001037 for (const auto& curProfile : hwModule->getOutputProfiles()) {
Dorin Drimusecc9f422022-03-09 17:57:40 +01001038 if (!curProfile->isCompatibleProfile(devices,
1039 samplingRate, NULL /*updatedSamplingRate*/,
1040 format, NULL /*updatedFormat*/,
1041 channelMask, NULL /*updatedChannelMask*/,
1042 flags)) {
1043 continue;
1044 }
1045 // reject profiles not corresponding to a device currently available
1046 if (!mAvailableOutputDevices.containsAtLeastOne(curProfile->getSupportedDevices())) {
1047 continue;
1048 }
1049 // reject profiles if connected device does not support codec
1050 if (!curProfile->devicesSupportEncodedFormats(devices.types())) {
1051 continue;
1052 }
1053 if (!directOnly) {
1054 return curProfile;
1055 }
1056
1057 // when searching for direct outputs, if several profiles are compatible, give priority
1058 // to one with offload capability
Patty Huang36028df2022-07-06 00:14:12 +08001059 if (profile != 0 &&
Dorin Drimusecc9f422022-03-09 17:57:40 +01001060 ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0)) {
Eric Laurent861a6282015-05-18 15:40:16 -07001061 continue;
Dorin Drimusecc9f422022-03-09 17:57:40 +01001062 }
1063 profile = curProfile;
1064 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1065 break;
1066 }
Eric Laurente552edb2014-03-10 17:42:56 -07001067 }
1068 }
Eric Laurent861a6282015-05-18 15:40:16 -07001069 return profile;
Eric Laurente552edb2014-03-10 17:42:56 -07001070}
1071
Eric Laurentfa0f6742021-08-17 18:39:44 +02001072sp<IOProfile> AudioPolicyManager::getSpatializerOutputProfile(
Eric Laurent39095982021-08-24 18:29:27 +02001073 const audio_config_t *config __unused, const AudioDeviceTypeAddrVector &devices) const
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001074{
1075 for (const auto& hwModule : mHwModules) {
1076 for (const auto& curProfile : hwModule->getOutputProfiles()) {
Eric Laurent1c5e2e32021-08-18 18:50:28 +02001077 if (curProfile->getFlags() != AUDIO_OUTPUT_FLAG_SPATIALIZER) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001078 continue;
1079 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001080 if (!devices.empty()) {
Eric Laurent0c8f7cc2022-06-24 14:32:36 +02001081 // reject profiles not corresponding to a device currently available
1082 DeviceVector supportedDevices = curProfile->getSupportedDevices();
1083 if (!mAvailableOutputDevices.containsAtLeastOne(supportedDevices)) {
1084 continue;
1085 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001086 if (supportedDevices.getDevicesFromDeviceTypeAddrVec(devices).size()
1087 != devices.size()) {
1088 continue;
1089 }
1090 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001091 ALOGV("%s found profile %s", __func__, curProfile->getName().c_str());
1092 return curProfile;
1093 }
1094 }
1095 return nullptr;
1096}
1097
Eric Laurentf4e63452017-11-06 19:31:46 +00001098audio_io_handle_t AudioPolicyManager::getOutput(audio_stream_type_t stream)
Eric Laurente552edb2014-03-10 17:42:56 -07001099{
François Gaffiec005e562018-11-06 15:04:49 +01001100 DeviceVector devices = mEngine->getOutputDevicesForStream(stream, false /*fromCache*/);
Andy Hungc9901522017-11-10 20:07:54 -08001101
1102 // Note that related method getOutputForAttr() uses getOutputForDevice() not selectOutput().
1103 // We use selectOutput() here since we don't have the desired AudioTrack sample rate,
1104 // format, flags, etc. This may result in some discrepancy for functions that utilize
1105 // getOutput() solely on audio_stream_type such as AudioSystem::getOutputFrameCount()
1106 // and AudioSystem::getOutputSamplingRate().
1107
François Gaffie11d30102018-11-02 16:09:09 +01001108 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurent16c66dd2019-05-01 17:54:10 -07001109 const audio_io_handle_t output = selectOutput(outputs);
Eric Laurente552edb2014-03-10 17:42:56 -07001110
François Gaffie11d30102018-11-02 16:09:09 +01001111 ALOGV("getOutput() stream %d selected devices %s, output %d", stream,
1112 devices.toString().c_str(), output);
Eric Laurentf4e63452017-11-06 19:31:46 +00001113 return output;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001114}
1115
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001116status_t AudioPolicyManager::getAudioAttributes(audio_attributes_t *dstAttr,
1117 const audio_attributes_t *srcAttr,
1118 audio_stream_type_t srcStream)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001119{
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001120 if (srcAttr != NULL) {
1121 if (!isValidAttributes(srcAttr)) {
1122 ALOGE("%s invalid attributes: usage=%d content=%d flags=0x%x tags=[%s]",
1123 __func__,
1124 srcAttr->usage, srcAttr->content_type, srcAttr->flags,
1125 srcAttr->tags);
1126 return BAD_VALUE;
1127 }
1128 *dstAttr = *srcAttr;
1129 } else {
1130 if (srcStream < AUDIO_STREAM_MIN || srcStream >= AUDIO_STREAM_PUBLIC_CNT) {
1131 ALOGE("%s: invalid stream type", __func__);
1132 return BAD_VALUE;
1133 }
François Gaffiec005e562018-11-06 15:04:49 +01001134 *dstAttr = mEngine->getAttributesForStreamType(srcStream);
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001135 }
Eric Laurent22fcda22019-05-17 16:28:47 -07001136
1137 // Only honor audibility enforced when required. The client will be
1138 // forced to reconnect if the forced usage changes.
1139 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Mikhail Naganov55773032020-10-01 15:08:13 -07001140 dstAttr->flags = static_cast<audio_flags_mask_t>(
1141 dstAttr->flags & ~AUDIO_FLAG_AUDIBILITY_ENFORCED);
Eric Laurent22fcda22019-05-17 16:28:47 -07001142 }
1143
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001144 return NO_ERROR;
1145}
1146
Kevin Rocard153f92d2018-12-18 18:33:28 -08001147status_t AudioPolicyManager::getOutputForAttrInt(
1148 audio_attributes_t *resultAttr,
1149 audio_io_handle_t *output,
1150 audio_session_t session,
1151 const audio_attributes_t *attr,
1152 audio_stream_type_t *stream,
1153 uid_t uid,
jiabinf1c73972022-04-14 16:28:52 -07001154 audio_config_t *config,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001155 audio_output_flags_t *flags,
1156 audio_port_handle_t *selectedDeviceId,
1157 bool *isRequestedDeviceForExclusiveUse,
Eric Laurentc529cf62020-04-17 18:19:10 -07001158 std::vector<sp<AudioPolicyMix>> *secondaryMixes,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001159 output_type_t *outputType,
jiabinc658e452022-10-21 20:52:21 +00001160 bool *isSpatialized,
1161 bool *isBitPerfect)
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001162{
François Gaffiec005e562018-11-06 15:04:49 +01001163 DeviceVector outputDevices;
Francois Gaffie716e1432019-01-14 16:58:59 +01001164 const audio_port_handle_t requestedPortId = *selectedDeviceId;
François Gaffie11d30102018-11-02 16:09:09 +01001165 DeviceVector msdDevices = getMsdAudioOutDevices();
François Gaffiec005e562018-11-06 15:04:49 +01001166 const sp<DeviceDescriptor> requestedDevice =
1167 mAvailableOutputDevices.getDeviceFromId(requestedPortId);
1168
Eric Laurent8a1095a2019-11-08 14:44:16 -08001169 *outputType = API_OUTPUT_INVALID;
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001170 *isSpatialized = false;
1171
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001172 status_t status = getAudioAttributes(resultAttr, attr, *stream);
1173 if (status != NO_ERROR) {
1174 return status;
Eric Laurent8f42ea12018-08-08 09:08:25 -07001175 }
Kevin Rocardb99cc752019-03-21 20:52:24 -07001176 if (auto it = mAllowedCapturePolicies.find(uid); it != end(mAllowedCapturePolicies)) {
Mikhail Naganov55773032020-10-01 15:08:13 -07001177 resultAttr->flags = static_cast<audio_flags_mask_t>(resultAttr->flags | it->second);
Kevin Rocardb99cc752019-03-21 20:52:24 -07001178 }
François Gaffiec005e562018-11-06 15:04:49 +01001179 *stream = mEngine->getStreamTypeForAttributes(*resultAttr);
Eric Laurent8f42ea12018-08-08 09:08:25 -07001180
François Gaffiec005e562018-11-06 15:04:49 +01001181 ALOGV("%s() attributes=%s stream=%s session %d selectedDeviceId %d", __func__,
1182 toString(*resultAttr).c_str(), toString(*stream).c_str(), session, requestedPortId);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001183
Oscar Azucena873d10f2023-01-12 18:34:42 -08001184 bool usePrimaryOutputFromPolicyMixes = false;
1185
Kevin Rocard153f92d2018-12-18 18:33:28 -08001186 // The primary output is the explicit routing (eg. setPreferredDevice) if specified,
1187 // otherwise, fallback to the dynamic policies, if none match, query the engine.
1188 // Secondary outputs are always found by dynamic policies as the engine do not support them
Eric Laurentc529cf62020-04-17 18:19:10 -07001189 sp<AudioPolicyMix> primaryMix;
Dean Wheatleyd082f472022-02-04 11:10:48 +11001190 const audio_config_base_t clientConfig = {.sample_rate = config->sample_rate,
1191 .channel_mask = config->channel_mask,
1192 .format = config->format,
1193 };
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02001194 status = mPolicyMixes.getOutputForAttr(*resultAttr, clientConfig, uid, session, *flags,
Oscar Azucena873d10f2023-01-12 18:34:42 -08001195 mAvailableOutputDevices, requestedDevice, primaryMix,
1196 secondaryMixes, usePrimaryOutputFromPolicyMixes);
Kevin Rocard94114a22019-04-01 19:38:23 -07001197 if (status != OK) {
1198 return status;
Kevin Rocard153f92d2018-12-18 18:33:28 -08001199 }
Kevin Rocard94114a22019-04-01 19:38:23 -07001200
Kevin Rocard153f92d2018-12-18 18:33:28 -08001201 // FIXME: in case of RENDER policy, the output capabilities should be checked
Dean Wheatleyd082f472022-02-04 11:10:48 +11001202 if ((secondaryMixes != nullptr && !secondaryMixes->empty())
1203 && !audio_is_linear_pcm(config->format)) {
1204 ALOGD("%s: rejecting request as secondary mixes only support pcm", __func__);
Kevin Rocard153f92d2018-12-18 18:33:28 -08001205 return BAD_VALUE;
1206 }
1207 if (usePrimaryOutputFromPolicyMixes) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001208 sp<DeviceDescriptor> deviceDesc =
1209 mAvailableOutputDevices.getDevice(primaryMix->mDeviceType,
1210 primaryMix->mDeviceAddress,
1211 AUDIO_FORMAT_DEFAULT);
1212 sp<SwAudioOutputDescriptor> policyDesc = primaryMix->getOutput();
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001213 bool tryDirectForFlags = policyDesc == nullptr ||
1214 (policyDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT);
1215 // if a direct output can be opened to deliver the track's multi-channel content to the
1216 // output rather than being downmixed by the primary output, then use this direct
1217 // output by by-passing the primary mix if possible, otherwise fall-through to primary
1218 // mix.
1219 bool tryDirectForChannelMask = policyDesc != nullptr
1220 && (audio_channel_count_from_out_mask(policyDesc->getConfig().channel_mask) <
1221 audio_channel_count_from_out_mask(config->channel_mask));
1222 if (deviceDesc != nullptr && (tryDirectForFlags || tryDirectForChannelMask)) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001223 audio_io_handle_t newOutput;
1224 status = openDirectOutput(
1225 *stream, session, config,
1226 (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT),
1227 DeviceVector(deviceDesc), &newOutput);
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001228 if (status == NO_ERROR) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001229 policyDesc = mOutputs.valueFor(newOutput);
1230 primaryMix->setOutput(policyDesc);
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001231 } else if (tryDirectForFlags) {
1232 policyDesc = nullptr;
1233 } // otherwise use primary if available.
Eric Laurentc529cf62020-04-17 18:19:10 -07001234 }
1235 if (policyDesc != nullptr) {
1236 policyDesc->mPolicyMix = primaryMix;
1237 *output = policyDesc->mIoHandle;
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08001238 *selectedDeviceId = deviceDesc != 0 ? deviceDesc->getId() : AUDIO_PORT_HANDLE_NONE;
Eric Laurent8a1095a2019-11-08 14:44:16 -08001239
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08001240 ALOGV("getOutputForAttr() returns output %d", *output);
1241 if (resultAttr->usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
1242 *outputType = API_OUT_MIX_PLAYBACK;
1243 } else {
1244 *outputType = API_OUTPUT_LEGACY;
1245 }
1246 return NO_ERROR;
Eric Laurent8a1095a2019-11-08 14:44:16 -08001247 }
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001248 }
François Gaffiec005e562018-11-06 15:04:49 +01001249 // Virtual sources must always be dynamicaly or explicitly routed
1250 if (resultAttr->usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
1251 ALOGW("getOutputForAttr() no policy mix found for usage AUDIO_USAGE_VIRTUAL_SOURCE");
1252 return BAD_VALUE;
1253 }
1254 // explicit routing managed by getDeviceForStrategy in APM is now handled by engine
1255 // in order to let the choice of the order to future vendor engine
1256 outputDevices = mEngine->getOutputDevicesForAttributes(*resultAttr, requestedDevice, false);
Scott Randolph7b1fd232018-06-18 15:33:03 -07001257
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001258 if ((resultAttr->flags & AUDIO_FLAG_HW_AV_SYNC) != 0) {
Nadav Bar766fb022018-01-07 12:18:03 +02001259 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
Eric Laurent93c3d412014-08-01 14:48:35 -07001260 }
1261
Nadav Barb2f18162018-07-18 13:01:53 +03001262 // Set incall music only if device was explicitly set, and fallback to the device which is
1263 // chosen by the engine if not.
1264 // FIXME: provide a more generic approach which is not device specific and move this back
1265 // to getOutputForDevice.
Nadav Bar20919492018-11-20 10:20:51 +02001266 // TODO: Remove check of AUDIO_STREAM_MUSIC once migration is completed on the app side.
jiabin9a3361e2019-10-01 09:38:30 -07001267 if (outputDevices.onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_TELEPHONY_TX) &&
François Gaffiec005e562018-11-06 15:04:49 +01001268 (*stream == AUDIO_STREAM_MUSIC || resultAttr->usage == AUDIO_USAGE_VOICE_COMMUNICATION) &&
Nadav Barb2f18162018-07-18 13:01:53 +03001269 audio_is_linear_pcm(config->format) &&
Eric Laurent74b71512019-11-06 17:21:57 -08001270 isCallAudioAccessible()) {
Francois Gaffie716e1432019-01-14 16:58:59 +01001271 if (requestedPortId != AUDIO_PORT_HANDLE_NONE) {
Nadav Barb2f18162018-07-18 13:01:53 +03001272 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_INCALL_MUSIC;
François Gaffief579db52018-11-13 11:25:16 +01001273 *isRequestedDeviceForExclusiveUse = true;
Nadav Barb2f18162018-07-18 13:01:53 +03001274 }
1275 }
1276
François Gaffiec005e562018-11-06 15:04:49 +01001277 ALOGV("%s() device %s, sampling rate %d, format %#x, channel mask %#x, flags %#x stream %s",
1278 __func__, outputDevices.toString().c_str(), config->sample_rate, config->format,
1279 config->channel_mask, *flags, toString(*stream).c_str());
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001280
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001281 *output = AUDIO_IO_HANDLE_NONE;
François Gaffie11d30102018-11-02 16:09:09 +01001282 if (!msdDevices.isEmpty()) {
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001283 *output = getOutputForDevices(msdDevices, session, resultAttr, config, flags, isSpatialized);
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001284 if (*output != AUDIO_IO_HANDLE_NONE && setMsdOutputPatches(&outputDevices) == NO_ERROR) {
François Gaffiec005e562018-11-06 15:04:49 +01001285 ALOGV("%s() Using MSD devices %s instead of devices %s",
1286 __func__, msdDevices.toString().c_str(), outputDevices.toString().c_str());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001287 } else {
1288 *output = AUDIO_IO_HANDLE_NONE;
1289 }
1290 }
1291 if (*output == AUDIO_IO_HANDLE_NONE) {
jiabina84c3d32022-12-02 18:59:55 +00001292 sp<PreferredMixerAttributesInfo> info = nullptr;
1293 if (outputDevices.size() == 1) {
1294 info = getPreferredMixerAttributesInfo(
1295 outputDevices.itemAt(0)->getId(),
1296 mEngine->getProductStrategyForAttributes(*resultAttr));
jiabin5eaf0962022-12-20 20:11:38 +00001297 // Only use preferred mixer if the uid matches or the preferred mixer is bit-perfect
1298 // and it is currently active.
1299 if (info != nullptr && info->getUid() != uid &&
1300 ((info->getFlags() & AUDIO_OUTPUT_FLAG_BIT_PERFECT) == AUDIO_OUTPUT_FLAG_NONE ||
1301 info->getActiveClientCount() == 0)) {
jiabina84c3d32022-12-02 18:59:55 +00001302 info = nullptr;
1303 }
1304 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001305 *output = getOutputForDevices(outputDevices, session, resultAttr, config,
jiabina84c3d32022-12-02 18:59:55 +00001306 flags, isSpatialized, info, resultAttr->flags & AUDIO_FLAG_MUTE_HAPTIC);
jiabin5eaf0962022-12-20 20:11:38 +00001307 // The client will be active if the client is currently preferred mixer owner and the
1308 // requested configuration matches the preferred mixer configuration.
jiabinc658e452022-10-21 20:52:21 +00001309 *isBitPerfect = (info != nullptr
1310 && (info->getFlags() & AUDIO_OUTPUT_FLAG_BIT_PERFECT) != AUDIO_OUTPUT_FLAG_NONE
jiabin5eaf0962022-12-20 20:11:38 +00001311 && info->getUid() == uid
1312 && *output != AUDIO_IO_HANDLE_NONE
1313 // When bit-perfect output is selected for the preferred mixer attributes owner,
1314 // only need to consider the config matches.
1315 && mOutputs.valueFor(*output)->isConfigurationMatched(
1316 clientConfig, AUDIO_OUTPUT_FLAG_NONE));
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001317 }
Eric Laurente83b55d2014-11-14 10:06:21 -08001318 if (*output == AUDIO_IO_HANDLE_NONE) {
jiabinf1c73972022-04-14 16:28:52 -07001319 AudioProfileVector profiles;
1320 status_t ret = getProfilesForDevices(outputDevices, profiles, *flags, false /*isInput*/);
1321 if (ret == NO_ERROR && !profiles.empty()) {
1322 config->channel_mask = profiles[0]->getChannels().empty() ? config->channel_mask
1323 : *profiles[0]->getChannels().begin();
1324 config->sample_rate = profiles[0]->getSampleRates().empty() ? config->sample_rate
1325 : *profiles[0]->getSampleRates().begin();
1326 config->format = profiles[0]->getFormat();
1327 }
Eric Laurente83b55d2014-11-14 10:06:21 -08001328 return INVALID_OPERATION;
1329 }
Paul McLeanaa981192015-03-21 09:55:15 -07001330
François Gaffiec005e562018-11-06 15:04:49 +01001331 *selectedDeviceId = getFirstDeviceId(outputDevices);
Michael Chan6fb34492020-12-08 15:44:49 +11001332 for (auto &outputDevice : outputDevices) {
1333 if (outputDevice->getId() == getConfig().getDefaultOutputDevice()->getId()) {
1334 *selectedDeviceId = outputDevice->getId();
1335 break;
1336 }
1337 }
Eric Laurent2ac76942017-06-22 17:17:09 -07001338
Eric Laurent8a1095a2019-11-08 14:44:16 -08001339 if (outputDevices.onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_TELEPHONY_TX)) {
1340 *outputType = API_OUTPUT_TELEPHONY_TX;
1341 } else {
1342 *outputType = API_OUTPUT_LEGACY;
1343 }
1344
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001345 ALOGV("%s returns output %d selectedDeviceId %d", __func__, *output, *selectedDeviceId);
1346
1347 return NO_ERROR;
1348}
1349
1350status_t AudioPolicyManager::getOutputForAttr(const audio_attributes_t *attr,
1351 audio_io_handle_t *output,
1352 audio_session_t session,
1353 audio_stream_type_t *stream,
Svet Ganov3e5f14f2021-05-13 22:51:08 +00001354 const AttributionSourceState& attributionSource,
jiabinf1c73972022-04-14 16:28:52 -07001355 audio_config_t *config,
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001356 audio_output_flags_t *flags,
1357 audio_port_handle_t *selectedDeviceId,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001358 audio_port_handle_t *portId,
Eric Laurent8a1095a2019-11-08 14:44:16 -08001359 std::vector<audio_io_handle_t> *secondaryOutputs,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001360 output_type_t *outputType,
jiabinc658e452022-10-21 20:52:21 +00001361 bool *isSpatialized,
1362 bool *isBitPerfect)
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001363{
1364 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
1365 if (*portId != AUDIO_PORT_HANDLE_NONE) {
1366 return INVALID_OPERATION;
1367 }
Philip P. Moltmannbda45752020-07-17 16:41:18 -07001368 const uid_t uid = VALUE_OR_RETURN_STATUS(
Svet Ganov3e5f14f2021-05-13 22:51:08 +00001369 aidl2legacy_int32_t_uid_t(attributionSource.uid));
Francois Gaffie716e1432019-01-14 16:58:59 +01001370 const audio_port_handle_t requestedPortId = *selectedDeviceId;
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001371 audio_attributes_t resultAttr;
François Gaffief579db52018-11-13 11:25:16 +01001372 bool isRequestedDeviceForExclusiveUse = false;
Eric Laurentc529cf62020-04-17 18:19:10 -07001373 std::vector<sp<AudioPolicyMix>> secondaryMixes;
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001374 const sp<DeviceDescriptor> requestedDevice =
1375 mAvailableOutputDevices.getDeviceFromId(requestedPortId);
1376
1377 // Prevent from storing invalid requested device id in clients
1378 const audio_port_handle_t sanitizedRequestedPortId =
1379 requestedDevice != nullptr ? requestedPortId : AUDIO_PORT_HANDLE_NONE;
1380 *selectedDeviceId = sanitizedRequestedPortId;
1381
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001382 status_t status = getOutputForAttrInt(&resultAttr, output, session, attr, stream, uid,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001383 config, flags, selectedDeviceId, &isRequestedDeviceForExclusiveUse,
jiabinc658e452022-10-21 20:52:21 +00001384 secondaryOutputs != nullptr ? &secondaryMixes : nullptr, outputType, isSpatialized,
1385 isBitPerfect);
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001386 if (status != NO_ERROR) {
1387 return status;
1388 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001389 std::vector<wp<SwAudioOutputDescriptor>> weakSecondaryOutputDescs;
Eric Laurentc529cf62020-04-17 18:19:10 -07001390 if (secondaryOutputs != nullptr) {
1391 for (auto &secondaryMix : secondaryMixes) {
1392 sp<SwAudioOutputDescriptor> outputDesc = secondaryMix->getOutput();
1393 if (outputDesc != nullptr &&
1394 outputDesc->mIoHandle != AUDIO_IO_HANDLE_NONE) {
1395 secondaryOutputs->push_back(outputDesc->mIoHandle);
1396 weakSecondaryOutputDescs.push_back(outputDesc);
1397 }
1398 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001399 }
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001400
Eric Laurent8fc147b2018-07-22 19:13:55 -07001401 audio_config_base_t clientConfig = {.sample_rate = config->sample_rate,
Nick Desaulniersa30e3202019-10-18 13:38:23 -07001402 .channel_mask = config->channel_mask,
Eric Laurent8fc147b2018-07-22 19:13:55 -07001403 .format = config->format,
Nick Desaulniersa30e3202019-10-18 13:38:23 -07001404 };
jiabin4ef93452019-09-10 14:29:54 -07001405 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurent8f42ea12018-08-08 09:08:25 -07001406
Eric Laurentc209fe42020-06-05 18:11:23 -07001407 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(*output);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001408 sp<TrackClientDescriptor> clientDesc =
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001409 new TrackClientDescriptor(*portId, uid, session, resultAttr, clientConfig,
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001410 sanitizedRequestedPortId, *stream,
François Gaffiec005e562018-11-06 15:04:49 +01001411 mEngine->getProductStrategyForAttributes(resultAttr),
François Gaffieaaac0fd2018-11-22 17:56:39 +01001412 toVolumeSource(resultAttr),
Kevin Rocard153f92d2018-12-18 18:33:28 -08001413 *flags, isRequestedDeviceForExclusiveUse,
Eric Laurentc209fe42020-06-05 18:11:23 -07001414 std::move(weakSecondaryOutputDescs),
1415 outputDesc->mPolicyMix);
Andy Hung39efb7a2018-09-26 15:39:28 -07001416 outputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001417
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001418 ALOGV("%s() returns output %d requestedPortId %d selectedDeviceId %d for port ID %d", __func__,
1419 *output, requestedPortId, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07001420
Eric Laurente83b55d2014-11-14 10:06:21 -08001421 return NO_ERROR;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001422}
1423
Eric Laurentc529cf62020-04-17 18:19:10 -07001424status_t AudioPolicyManager::openDirectOutput(audio_stream_type_t stream,
1425 audio_session_t session,
1426 const audio_config_t *config,
1427 audio_output_flags_t flags,
1428 const DeviceVector &devices,
1429 audio_io_handle_t *output) {
1430
1431 *output = AUDIO_IO_HANDLE_NONE;
1432
1433 // skip direct output selection if the request can obviously be attached to a mixed output
1434 // and not explicitly requested
1435 if (((flags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
1436 audio_is_linear_pcm(config->format) && config->sample_rate <= SAMPLE_RATE_HZ_MAX &&
1437 audio_channel_count_from_out_mask(config->channel_mask) <= 2) {
1438 return NAME_NOT_FOUND;
1439 }
1440
1441 // Do not allow offloading if one non offloadable effect is enabled or MasterMono is enabled.
1442 // This prevents creating an offloaded track and tearing it down immediately after start
1443 // when audioflinger detects there is an active non offloadable effect.
1444 // FIXME: We should check the audio session here but we do not have it in this context.
1445 // This may prevent offloading in rare situations where effects are left active by apps
1446 // in the background.
1447 sp<IOProfile> profile;
1448 if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) ||
1449 !(mEffects.isNonOffloadableEffectEnabled() || mMasterMono)) {
1450 profile = getProfileForOutput(
1451 devices, config->sample_rate, config->format, config->channel_mask,
1452 flags, true /* directOnly */);
1453 }
1454
1455 if (profile == nullptr) {
1456 return NAME_NOT_FOUND;
1457 }
1458
1459 // exclusive outputs for MMAP and Offload are enforced by different session ids.
1460 for (size_t i = 0; i < mOutputs.size(); i++) {
1461 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
1462 if (!desc->isDuplicated() && (profile == desc->mProfile)) {
1463 // reuse direct output if currently open by the same client
1464 // and configured with same parameters
1465 if ((config->sample_rate == desc->getSamplingRate()) &&
1466 (config->format == desc->getFormat()) &&
1467 (config->channel_mask == desc->getChannelMask()) &&
1468 (session == desc->mDirectClientSession)) {
1469 desc->mDirectOpenCount++;
Eric Laurentfecbceb2021-02-09 14:46:43 +01001470 ALOGV("%s reusing direct output %d for session %d", __func__,
Eric Laurentc529cf62020-04-17 18:19:10 -07001471 mOutputs.keyAt(i), session);
1472 *output = mOutputs.keyAt(i);
1473 return NO_ERROR;
1474 }
1475 }
1476 }
1477
1478 if (!profile->canOpenNewIo()) {
1479 return NAME_NOT_FOUND;
1480 }
1481
1482 sp<SwAudioOutputDescriptor> outputDesc =
1483 new SwAudioOutputDescriptor(profile, mpClientInterface);
1484
Michael Chan6fb34492020-12-08 15:44:49 +11001485 // An MSD patch may be using the only output stream that can service this request. Release
1486 // all MSD patches to prioritize this request over any active output on MSD.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001487 releaseMsdOutputPatches(devices);
Eric Laurentc529cf62020-04-17 18:19:10 -07001488
Eric Laurentf1f22e72021-07-13 14:04:14 +02001489 status_t status =
1490 outputDesc->open(config, nullptr /* mixerConfig */, devices, stream, flags, output);
Eric Laurentc529cf62020-04-17 18:19:10 -07001491
1492 // only accept an output with the requested parameters
1493 if (status != NO_ERROR ||
1494 (config->sample_rate != 0 && config->sample_rate != outputDesc->getSamplingRate()) ||
1495 (config->format != AUDIO_FORMAT_DEFAULT && config->format != outputDesc->getFormat()) ||
1496 (config->channel_mask != 0 && config->channel_mask != outputDesc->getChannelMask())) {
1497 ALOGV("%s failed opening direct output: output %d sample rate %d %d,"
1498 "format %d %d, channel mask %04x %04x", __func__, *output, config->sample_rate,
1499 outputDesc->getSamplingRate(), config->format, outputDesc->getFormat(),
1500 config->channel_mask, outputDesc->getChannelMask());
1501 if (*output != AUDIO_IO_HANDLE_NONE) {
1502 outputDesc->close();
1503 }
1504 // fall back to mixer output if possible when the direct output could not be open
1505 if (audio_is_linear_pcm(config->format) &&
1506 config->sample_rate <= SAMPLE_RATE_HZ_MAX) {
1507 return NAME_NOT_FOUND;
1508 }
1509 *output = AUDIO_IO_HANDLE_NONE;
1510 return BAD_VALUE;
1511 }
1512 outputDesc->mDirectOpenCount = 1;
1513 outputDesc->mDirectClientSession = session;
1514
1515 addOutput(*output, outputDesc);
1516 mPreviousOutputs = mOutputs;
1517 ALOGV("%s returns new direct output %d", __func__, *output);
1518 mpClientInterface->onAudioPortListUpdate();
1519 return NO_ERROR;
1520}
1521
François Gaffie11d30102018-11-02 16:09:09 +01001522audio_io_handle_t AudioPolicyManager::getOutputForDevices(
1523 const DeviceVector &devices,
Kevin Rocard169753c2017-03-06 14:18:23 -08001524 audio_session_t session,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001525 const audio_attributes_t *attr,
Eric Laurentfe231122017-11-17 17:48:06 -08001526 const audio_config_t *config,
jiabine375d412019-02-26 12:54:53 -08001527 audio_output_flags_t *flags,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001528 bool *isSpatialized,
jiabina84c3d32022-12-02 18:59:55 +00001529 sp<PreferredMixerAttributesInfo> prefMixerConfigInfo,
jiabine375d412019-02-26 12:54:53 -08001530 bool forceMutingHaptic)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001531{
Andy Hungc88b0642018-04-27 15:42:35 -07001532 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001533
jiabine375d412019-02-26 12:54:53 -08001534 // Discard haptic channel mask when forcing muting haptic channels.
1535 audio_channel_mask_t channelMask = forceMutingHaptic
Mikhail Naganov55773032020-10-01 15:08:13 -07001536 ? static_cast<audio_channel_mask_t>(config->channel_mask & ~AUDIO_CHANNEL_HAPTIC_ALL)
1537 : config->channel_mask;
jiabine375d412019-02-26 12:54:53 -08001538
Eric Laurente552edb2014-03-10 17:42:56 -07001539 // open a direct output if required by specified parameters
1540 //force direct flag if offload flag is set: offloading implies a direct output stream
1541 // and all common behaviors are driven by checking only the direct flag
1542 // this should normally be set appropriately in the policy configuration file
Nadav Bar766fb022018-01-07 12:18:03 +02001543 if ((*flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1544 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurente552edb2014-03-10 17:42:56 -07001545 }
Nadav Bar766fb022018-01-07 12:18:03 +02001546 if ((*flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
1547 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent93c3d412014-08-01 14:48:35 -07001548 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001549
1550 audio_stream_type_t stream = mEngine->getStreamTypeForAttributes(*attr);
1551
Eric Laurente83b55d2014-11-14 10:06:21 -08001552 // only allow deep buffering for music stream type
1553 if (stream != AUDIO_STREAM_MUSIC) {
Nadav Bar766fb022018-01-07 12:18:03 +02001554 *flags = (audio_output_flags_t)(*flags &~AUDIO_OUTPUT_FLAG_DEEP_BUFFER);
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -07001555 } else if (/* stream == AUDIO_STREAM_MUSIC && */
Nadav Bar766fb022018-01-07 12:18:03 +02001556 *flags == AUDIO_OUTPUT_FLAG_NONE &&
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -07001557 property_get_bool("audio.deep_buffer.media", false /* default_value */)) {
1558 // use DEEP_BUFFER as default output for music stream type
Nadav Bar766fb022018-01-07 12:18:03 +02001559 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
Eric Laurente83b55d2014-11-14 10:06:21 -08001560 }
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -07001561 if (stream == AUDIO_STREAM_TTS) {
Nadav Bar766fb022018-01-07 12:18:03 +02001562 *flags = AUDIO_OUTPUT_FLAG_TTS;
Haynes Mathew George84c621e2017-04-25 11:41:50 -07001563 } else if (stream == AUDIO_STREAM_VOICE_CALL &&
Nadav Bar20919492018-11-20 10:20:51 +02001564 audio_is_linear_pcm(config->format) &&
1565 (*flags & AUDIO_OUTPUT_FLAG_INCALL_MUSIC) == 0) {
Nadav Bar766fb022018-01-07 12:18:03 +02001566 *flags = (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_VOIP_RX |
Haynes Mathew George84c621e2017-04-25 11:41:50 -07001567 AUDIO_OUTPUT_FLAG_DIRECT);
1568 ALOGV("Set VoIP and Direct output flags for PCM format");
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -07001569 }
Eric Laurente552edb2014-03-10 17:42:56 -07001570
Carter Hsua3abb402021-10-26 11:11:20 +08001571 // Attach the Ultrasound flag for the AUDIO_CONTENT_TYPE_ULTRASOUND
1572 if (attr->content_type == AUDIO_CONTENT_TYPE_ULTRASOUND) {
1573 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_ULTRASOUND);
1574 }
1575
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001576 *isSpatialized = false;
Eric Laurentfa0f6742021-08-17 18:39:44 +02001577 if (mSpatializerOutput != nullptr
Andy Hung9dd1a5b2022-05-10 15:39:39 -07001578 && canBeSpatializedInt(attr, config, devices.toTypeAddrVector())) {
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001579 *isSpatialized = true;
Eric Laurentfa0f6742021-08-17 18:39:44 +02001580 return mSpatializerOutput->mIoHandle;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001581 }
1582
Eric Laurentc529cf62020-04-17 18:19:10 -07001583 audio_config_t directConfig = *config;
1584 directConfig.channel_mask = channelMask;
1585 status_t status = openDirectOutput(stream, session, &directConfig, *flags, devices, &output);
1586 if (status != NAME_NOT_FOUND) {
Eric Laurente552edb2014-03-10 17:42:56 -07001587 return output;
1588 }
1589
Eric Laurent14cbfca2016-03-17 09:42:16 -07001590 // A request for HW A/V sync cannot fallback to a mixed output because time
1591 // stamps are embedded in audio data
Phil Burk2d059932018-02-15 15:55:11 -08001592 if ((*flags & (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ)) != 0) {
Eric Laurent14cbfca2016-03-17 09:42:16 -07001593 return AUDIO_IO_HANDLE_NONE;
1594 }
Pierre Couillaude73496b2023-03-06 16:19:05 +00001595 // A request for Tuner cannot fallback to a mixed output
1596 if ((directConfig.offload_info.content_id || directConfig.offload_info.sync_id)) {
1597 return AUDIO_IO_HANDLE_NONE;
1598 }
Eric Laurent14cbfca2016-03-17 09:42:16 -07001599
Eric Laurente552edb2014-03-10 17:42:56 -07001600 // ignoring channel mask due to downmix capability in mixer
1601
1602 // open a non direct output
1603
1604 // for non direct outputs, only PCM is supported
Eric Laurentfe231122017-11-17 17:48:06 -08001605 if (audio_is_linear_pcm(config->format)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001606 // get which output is suitable for the specified stream. The actual
1607 // routing change will happen when startOutput() will be called
François Gaffie11d30102018-11-02 16:09:09 +01001608 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
jiabina84c3d32022-12-02 18:59:55 +00001609 if (prefMixerConfigInfo != nullptr) {
1610 for (audio_io_handle_t outputHandle : outputs) {
1611 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(outputHandle);
1612 if (outputDesc->mProfile == prefMixerConfigInfo->getProfile()) {
1613 output = outputHandle;
1614 break;
1615 }
1616 }
1617 if (output == AUDIO_IO_HANDLE_NONE) {
1618 // No output open with the preferred profile. Open a new one.
1619 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
1620 config.channel_mask = prefMixerConfigInfo->getConfigBase().channel_mask;
1621 config.sample_rate = prefMixerConfigInfo->getConfigBase().sample_rate;
1622 config.format = prefMixerConfigInfo->getConfigBase().format;
1623 sp<SwAudioOutputDescriptor> preferredOutput = openOutputWithProfileAndDevice(
1624 prefMixerConfigInfo->getProfile(), devices, nullptr /*mixerConfig*/,
1625 &config, prefMixerConfigInfo->getFlags());
1626 if (preferredOutput == nullptr) {
1627 ALOGE("%s failed to open output with preferred mixer config", __func__);
1628 } else {
1629 output = preferredOutput->mIoHandle;
1630 }
1631 }
1632 } else {
1633 // at this stage we should ignore the DIRECT flag as no direct output could be
1634 // found earlier
1635 *flags = (audio_output_flags_t) (*flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
1636 output = selectOutput(
1637 outputs, *flags, config->format, channelMask, config->sample_rate, session);
1638 }
Eric Laurente552edb2014-03-10 17:42:56 -07001639 }
François Gaffie11d30102018-11-02 16:09:09 +01001640 ALOGW_IF((output == 0), "getOutputForDevices() could not find output for stream %d, "
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001641 "sampling rate %d, format %#x, channels %#x, flags %#x",
jiabine375d412019-02-26 12:54:53 -08001642 stream, config->sample_rate, config->format, channelMask, *flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001643
Eric Laurente552edb2014-03-10 17:42:56 -07001644 return output;
1645}
1646
Mikhail Naganovf02f3672018-11-09 12:44:16 -08001647sp<DeviceDescriptor> AudioPolicyManager::getMsdAudioInDevice() const {
François Gaffie11d30102018-11-02 16:09:09 +01001648 auto msdInDevices = mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1649 mAvailableInputDevices);
1650 return msdInDevices.isEmpty()? nullptr : msdInDevices.itemAt(0);
1651}
1652
1653DeviceVector AudioPolicyManager::getMsdAudioOutDevices() const {
1654 return mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1655 mAvailableOutputDevices);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001656}
1657
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001658const AudioPatchCollection AudioPolicyManager::getMsdOutputPatches() const {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001659 AudioPatchCollection msdPatches;
Mikhail Naganov86112352018-10-04 09:02:49 -07001660 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1661 if (msdModule != 0) {
1662 for (size_t i = 0; i < mAudioPatches.size(); ++i) {
1663 sp<AudioPatch> patch = mAudioPatches.valueAt(i);
1664 for (size_t j = 0; j < patch->mPatch.num_sources; ++j) {
1665 const struct audio_port_config *source = &patch->mPatch.sources[j];
1666 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
1667 source->ext.device.hw_module == msdModule->getHandle()) {
François Gaffieafd4cea2019-11-18 15:50:22 +01001668 msdPatches.addAudioPatch(patch->getHandle(), patch);
Mikhail Naganov86112352018-10-04 09:02:49 -07001669 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001670 }
1671 }
1672 }
1673 return msdPatches;
1674}
1675
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02001676bool AudioPolicyManager::isMsdPatch(const audio_patch_handle_t &handle) const {
1677 ssize_t index = mAudioPatches.indexOfKey(handle);
1678 if (index < 0) {
1679 return false;
1680 }
1681 const sp<AudioPatch> patch = mAudioPatches.valueAt(index);
1682 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1683 if (msdModule == nullptr) {
1684 return false;
1685 }
1686 const struct audio_port_config *sink = &patch->mPatch.sinks[0];
1687 if (getMsdAudioOutDevices().contains(mAvailableOutputDevices.getDeviceFromId(sink->id))) {
1688 return true;
1689 }
1690 index = getMsdOutputPatches().indexOfKey(handle);
1691 if (index < 0) {
1692 return false;
1693 }
1694 return true;
1695}
1696
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001697status_t AudioPolicyManager::getMsdProfiles(bool hwAvSync,
1698 const InputProfileCollection &inputProfiles,
1699 const OutputProfileCollection &outputProfiles,
1700 const sp<DeviceDescriptor> &sourceDevice,
1701 const sp<DeviceDescriptor> &sinkDevice,
1702 AudioProfileVector& sourceProfiles,
1703 AudioProfileVector& sinkProfiles) const {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001704 if (inputProfiles.isEmpty()) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001705 ALOGE("%s() no input profiles for source module", __func__);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001706 return NO_INIT;
1707 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001708 if (outputProfiles.isEmpty()) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001709 ALOGE("%s() no output profiles for sink module", __func__);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001710 return NO_INIT;
1711 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001712 for (const auto &inProfile : inputProfiles) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001713 if (hwAvSync == ((inProfile->getFlags() & AUDIO_INPUT_FLAG_HW_AV_SYNC) != 0) &&
1714 inProfile->supportsDevice(sourceDevice)) {
1715 appendAudioProfiles(sourceProfiles, inProfile->getAudioProfiles());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001716 }
1717 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001718 for (const auto &outProfile : outputProfiles) {
Michael Chan6fb34492020-12-08 15:44:49 +11001719 if (hwAvSync == ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) &&
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001720 outProfile->supportsDevice(sinkDevice)) {
1721 appendAudioProfiles(sinkProfiles, outProfile->getAudioProfiles());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001722 }
1723 }
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001724 return NO_ERROR;
1725}
1726
1727status_t AudioPolicyManager::getBestMsdConfig(bool hwAvSync,
1728 const AudioProfileVector &sourceProfiles, const AudioProfileVector &sinkProfiles,
1729 audio_port_config *sourceConfig, audio_port_config *sinkConfig) const
1730{
Dean Wheatley16809da2022-12-09 14:55:46 +11001731 // Compressed formats for MSD module, ordered from most preferred to least preferred.
1732 static const std::vector<audio_format_t> formatsOrder = {{
1733 AUDIO_FORMAT_IEC60958, AUDIO_FORMAT_MAT_2_1, AUDIO_FORMAT_MAT_2_0, AUDIO_FORMAT_E_AC3,
1734 AUDIO_FORMAT_AC3, AUDIO_FORMAT_PCM_16_BIT }};
1735 static const std::vector<audio_channel_mask_t> channelMasksOrder = [](){
1736 // Channel position masks for MSD module, 3D > 2D > 1D ordering (most preferred to least
1737 // preferred).
1738 std::vector<audio_channel_mask_t> masks = {{
1739 AUDIO_CHANNEL_OUT_3POINT1POINT2, AUDIO_CHANNEL_OUT_3POINT0POINT2,
1740 AUDIO_CHANNEL_OUT_2POINT1POINT2, AUDIO_CHANNEL_OUT_2POINT0POINT2,
1741 AUDIO_CHANNEL_OUT_5POINT1, AUDIO_CHANNEL_OUT_STEREO }};
1742 // insert index masks (higher counts most preferred) as preferred over position masks
1743 for (int i = 1; i <= AUDIO_CHANNEL_COUNT_MAX; i++) {
1744 masks.insert(
1745 masks.begin(), audio_channel_mask_for_index_assignment_from_count(i));
1746 }
1747 return masks;
1748 }();
1749
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001750 struct audio_config_base bestSinkConfig;
Dean Wheatley16809da2022-12-09 14:55:46 +11001751 status_t result = findBestMatchingOutputConfig(sourceProfiles, sinkProfiles, formatsOrder,
1752 channelMasksOrder, true /*preferHigherSamplingRates*/, bestSinkConfig);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001753 if (result != NO_ERROR) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001754 ALOGD("%s() no matching config found for sink, hwAvSync: %d",
1755 __func__, hwAvSync);
Greg Kaiser83289652018-07-30 06:13:57 -07001756 return result;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001757 }
1758 sinkConfig->sample_rate = bestSinkConfig.sample_rate;
1759 sinkConfig->channel_mask = bestSinkConfig.channel_mask;
1760 sinkConfig->format = bestSinkConfig.format;
1761 // For encoded streams force direct flag to prevent downstream mixing.
1762 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1763 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_DIRECT);
Dean Wheatley5c9f0832019-11-21 13:39:31 +11001764 if (audio_is_iec61937_compatible(sinkConfig->format)) {
1765 // For formats compatible with IEC61937 encapsulation, assume that
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001766 // the input is IEC61937 framed (for proportional buffer sizing).
Dean Wheatley5c9f0832019-11-21 13:39:31 +11001767 // Add the AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO flag so downstream HAL can distinguish between
1768 // raw and IEC61937 framed streams.
1769 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1770 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO);
1771 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001772 sourceConfig->sample_rate = bestSinkConfig.sample_rate;
1773 // Specify exact channel mask to prevent guessing by bit count in PatchPanel.
Dean Wheatley16809da2022-12-09 14:55:46 +11001774 sourceConfig->channel_mask =
1775 audio_channel_mask_get_representation(bestSinkConfig.channel_mask)
1776 == AUDIO_CHANNEL_REPRESENTATION_INDEX ?
1777 bestSinkConfig.channel_mask : audio_channel_mask_out_to_in(bestSinkConfig.channel_mask);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001778 sourceConfig->format = bestSinkConfig.format;
1779 // Copy input stream directly without any processing (e.g. resampling).
1780 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1781 sourceConfig->flags.input | AUDIO_INPUT_FLAG_DIRECT);
1782 if (hwAvSync) {
1783 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1784 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
1785 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1786 sourceConfig->flags.input | AUDIO_INPUT_FLAG_HW_AV_SYNC);
1787 }
1788 const unsigned int config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE |
1789 AUDIO_PORT_CONFIG_CHANNEL_MASK | AUDIO_PORT_CONFIG_FORMAT | AUDIO_PORT_CONFIG_FLAGS;
1790 sinkConfig->config_mask |= config_mask;
1791 sourceConfig->config_mask |= config_mask;
1792 return NO_ERROR;
1793}
1794
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001795PatchBuilder AudioPolicyManager::buildMsdPatch(bool msdIsSource,
1796 const sp<DeviceDescriptor> &device) const
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001797{
1798 PatchBuilder patchBuilder;
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001799 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1800 ALOG_ASSERT(msdModule != nullptr, "MSD module not available");
1801 sp<HwModule> deviceModule = mHwModules.getModuleForDevice(device, AUDIO_FORMAT_DEFAULT);
1802 if (deviceModule == nullptr) {
1803 ALOGE("%s() unable to get module for %s", __func__, device->toString().c_str());
1804 return patchBuilder;
1805 }
1806 const InputProfileCollection inputProfiles = msdIsSource ?
1807 msdModule->getInputProfiles() : deviceModule->getInputProfiles();
1808 const OutputProfileCollection outputProfiles = msdIsSource ?
1809 deviceModule->getOutputProfiles() : msdModule->getOutputProfiles();
1810
1811 const sp<DeviceDescriptor> sourceDevice = msdIsSource ? getMsdAudioInDevice() : device;
1812 const sp<DeviceDescriptor> sinkDevice = msdIsSource ?
1813 device : getMsdAudioOutDevices().itemAt(0);
1814 patchBuilder.addSource(sourceDevice).addSink(sinkDevice);
1815
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001816 audio_port_config sourceConfig = patchBuilder.patch()->sources[0];
1817 audio_port_config sinkConfig = patchBuilder.patch()->sinks[0];
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001818 AudioProfileVector sourceProfiles;
1819 AudioProfileVector sinkProfiles;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001820 // TODO: Figure out whether MSD module has HW_AV_SYNC flag set in the AP config file.
1821 // For now, we just forcefully try with HwAvSync first.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001822 for (auto hwAvSync : { true, false }) {
1823 if (getMsdProfiles(hwAvSync, inputProfiles, outputProfiles, sourceDevice, sinkDevice,
1824 sourceProfiles, sinkProfiles) != NO_ERROR) {
1825 continue;
1826 }
1827 if (getBestMsdConfig(hwAvSync, sourceProfiles, sinkProfiles, &sourceConfig,
1828 &sinkConfig) == NO_ERROR) {
1829 // Found a matching config. Re-create PatchBuilder with this config.
1830 return (PatchBuilder()).addSource(sourceConfig).addSink(sinkConfig);
1831 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001832 }
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001833 ALOGV("%s() no matching config found. Fall through to default PCM patch"
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001834 " supporting PCM format conversion.", __func__);
1835 return patchBuilder;
1836}
1837
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001838status_t AudioPolicyManager::setMsdOutputPatches(const DeviceVector *outputDevices) {
Michael Chan6fb34492020-12-08 15:44:49 +11001839 DeviceVector devices;
1840 if (outputDevices != nullptr && outputDevices->size() > 0) {
1841 devices.add(*outputDevices);
1842 } else {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001843 // Use media strategy for unspecified output device. This should only
1844 // occur on checkForDeviceAndOutputChanges(). Device connection events may
1845 // therefore invalidate explicit routing requests.
Michael Chan6fb34492020-12-08 15:44:49 +11001846 devices = mEngine->getOutputDevicesForAttributes(
François Gaffiec005e562018-11-06 15:04:49 +01001847 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
Michael Chan6fb34492020-12-08 15:44:49 +11001848 LOG_ALWAYS_FATAL_IF(devices.isEmpty(), "no output device to set MSD patch");
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001849 }
Michael Chan6fb34492020-12-08 15:44:49 +11001850 std::vector<PatchBuilder> patchesToCreate;
1851 for (auto i = 0u; i < devices.size(); ++i) {
1852 ALOGV("%s() for device %s", __func__, devices[i]->toString().c_str());
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001853 patchesToCreate.push_back(buildMsdPatch(true /*msdIsSource*/, devices[i]));
Michael Chan6fb34492020-12-08 15:44:49 +11001854 }
1855 // Retain only the MSD patches associated with outputDevices request.
1856 // Tear down the others, and create new ones as needed.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001857 AudioPatchCollection patchesToRemove = getMsdOutputPatches();
Michael Chan6fb34492020-12-08 15:44:49 +11001858 for (auto it = patchesToCreate.begin(); it != patchesToCreate.end(); ) {
1859 auto retainedPatch = false;
1860 for (auto i = 0u; i < patchesToRemove.size(); ++i) {
1861 if (audio_patches_are_equal(it->patch(), &patchesToRemove[i]->mPatch)) {
1862 patchesToRemove.removeItemsAt(i);
1863 retainedPatch = true;
1864 break;
1865 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001866 }
Michael Chan6fb34492020-12-08 15:44:49 +11001867 if (retainedPatch) {
1868 it = patchesToCreate.erase(it);
1869 continue;
1870 }
1871 ++it;
1872 }
1873 if (patchesToCreate.size() == 0 && patchesToRemove.size() == 0) {
1874 return NO_ERROR;
1875 }
1876 for (auto i = 0u; i < patchesToRemove.size(); ++i) {
1877 auto &currentPatch = patchesToRemove.valueAt(i);
François Gaffieafd4cea2019-11-18 15:50:22 +01001878 releaseAudioPatch(currentPatch->getHandle(), mUidCached);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001879 }
Michael Chan6fb34492020-12-08 15:44:49 +11001880 status_t status = NO_ERROR;
1881 for (const auto &p : patchesToCreate) {
1882 auto currStatus = installPatch(__func__, -1 /*index*/, nullptr /*patchHandle*/,
1883 p.patch(), 0 /*delayMs*/, mUidCached, nullptr /*patchDescPtr*/);
1884 char message[256];
1885 snprintf(message, sizeof(message), "%s() %s: creating MSD patch from device:IN_BUS to "
1886 "device:%#x (format:%#x channels:%#x samplerate:%d)", __func__,
1887 currStatus == NO_ERROR ? "Success" : "Error",
1888 p.patch()->sinks[0].ext.device.type, p.patch()->sources[0].format,
1889 p.patch()->sources[0].channel_mask, p.patch()->sources[0].sample_rate);
1890 if (currStatus == NO_ERROR) {
1891 ALOGD("%s", message);
1892 } else {
1893 ALOGE("%s", message);
1894 if (status == NO_ERROR) {
1895 status = currStatus;
1896 }
1897 }
1898 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001899 return status;
1900}
1901
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001902void AudioPolicyManager::releaseMsdOutputPatches(const DeviceVector& devices) {
1903 AudioPatchCollection msdPatches = getMsdOutputPatches();
Michael Chan6fb34492020-12-08 15:44:49 +11001904 for (size_t i = 0; i < msdPatches.size(); i++) {
1905 const auto& patch = msdPatches[i];
1906 for (size_t j = 0; j < patch->mPatch.num_sinks; ++j) {
1907 const struct audio_port_config *sink = &patch->mPatch.sinks[j];
1908 if (sink->type == AUDIO_PORT_TYPE_DEVICE && devices.getDevice(sink->ext.device.type,
1909 String8(sink->ext.device.address), AUDIO_FORMAT_DEFAULT) != nullptr) {
1910 releaseAudioPatch(patch->getHandle(), mUidCached);
1911 break;
1912 }
1913 }
1914 }
1915}
1916
Dorin Drimus94d94412022-02-02 09:05:02 +01001917bool AudioPolicyManager::msdHasPatchesToAllDevices(const AudioDeviceTypeAddrVector& devices) {
1918 DeviceVector devicesToCheck = mOutputDevicesAll.getDevicesFromDeviceTypeAddrVec(devices);
1919 AudioPatchCollection msdPatches = getMsdOutputPatches();
1920 for (size_t i = 0; i < msdPatches.size(); i++) {
1921 const auto& patch = msdPatches[i];
1922 for (size_t j = 0; j < patch->mPatch.num_sinks; ++j) {
1923 const struct audio_port_config *sink = &patch->mPatch.sinks[j];
1924 if (sink->type == AUDIO_PORT_TYPE_DEVICE) {
1925 const auto& foundDevice = devicesToCheck.getDevice(
1926 sink->ext.device.type, String8(sink->ext.device.address), AUDIO_FORMAT_DEFAULT);
1927 if (foundDevice != nullptr) {
1928 devicesToCheck.remove(foundDevice);
1929 if (devicesToCheck.isEmpty()) {
1930 return true;
1931 }
1932 }
1933 }
1934 }
1935 }
1936 return false;
1937}
1938
Eric Laurente0720872014-03-11 09:30:41 -07001939audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
jiabinebb6af42020-06-09 17:31:17 -07001940 audio_output_flags_t flags,
1941 audio_format_t format,
1942 audio_channel_mask_t channelMask,
1943 uint32_t samplingRate,
1944 audio_session_t sessionId)
Eric Laurente552edb2014-03-10 17:42:56 -07001945{
Eric Laurent16c66dd2019-05-01 17:54:10 -07001946 LOG_ALWAYS_FATAL_IF(!(format == AUDIO_FORMAT_INVALID || audio_is_linear_pcm(format)),
1947 "%s called with format %#x", __func__, format);
1948
jiabinebb6af42020-06-09 17:31:17 -07001949 // Return the output that haptic-generating attached to when 1) session id is specified,
1950 // 2) haptic-generating effect exists for given session id and 3) the output that
1951 // haptic-generating effect attached to is in given outputs.
1952 if (sessionId != AUDIO_SESSION_NONE) {
1953 audio_io_handle_t hapticGeneratingOutput = mEffects.getIoForSession(
1954 sessionId, FX_IID_HAPTICGENERATOR);
1955 if (outputs.indexOf(hapticGeneratingOutput) >= 0) {
1956 return hapticGeneratingOutput;
1957 }
1958 }
1959
Eric Laurent16c66dd2019-05-01 17:54:10 -07001960 // Flags disqualifying an output: the match must happen before calling selectOutput()
1961 static const audio_output_flags_t kExcludedFlags = (audio_output_flags_t)
1962 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ | AUDIO_OUTPUT_FLAG_DIRECT);
1963
1964 // Flags expressing a functional request: must be honored in priority over
1965 // other criteria
1966 static const audio_output_flags_t kFunctionalFlags = (audio_output_flags_t)
1967 (AUDIO_OUTPUT_FLAG_VOIP_RX | AUDIO_OUTPUT_FLAG_INCALL_MUSIC |
Eric Laurente28c66d2022-01-21 13:40:41 +01001968 AUDIO_OUTPUT_FLAG_TTS | AUDIO_OUTPUT_FLAG_DIRECT_PCM | AUDIO_OUTPUT_FLAG_ULTRASOUND |
1969 AUDIO_OUTPUT_FLAG_SPATIALIZER);
Eric Laurent16c66dd2019-05-01 17:54:10 -07001970 // Flags expressing a performance request: have lower priority than serving
1971 // requested sampling rate or channel mask
1972 static const audio_output_flags_t kPerformanceFlags = (audio_output_flags_t)
1973 (AUDIO_OUTPUT_FLAG_FAST | AUDIO_OUTPUT_FLAG_DEEP_BUFFER |
1974 AUDIO_OUTPUT_FLAG_RAW | AUDIO_OUTPUT_FLAG_SYNC);
1975
1976 const audio_output_flags_t functionalFlags =
1977 (audio_output_flags_t)(flags & kFunctionalFlags);
1978 const audio_output_flags_t performanceFlags =
1979 (audio_output_flags_t)(flags & kPerformanceFlags);
1980
1981 audio_io_handle_t bestOutput = (outputs.size() == 0) ? AUDIO_IO_HANDLE_NONE : outputs[0];
1982
Eric Laurente552edb2014-03-10 17:42:56 -07001983 // select one output among several that provide a path to a particular device or set of
François Gaffie11d30102018-11-02 16:09:09 +01001984 // devices (the list was previously build by getOutputsForDevices()).
Eric Laurente552edb2014-03-10 17:42:56 -07001985 // The priority is as follows:
jiabin40573322018-11-08 12:08:02 -08001986 // 1: the output supporting haptic playback when requesting haptic playback
Eric Laurent16c66dd2019-05-01 17:54:10 -07001987 // 2: the output with the highest number of requested functional flags
Carter Hsu199f1892021-10-15 15:47:29 +08001988 // with tiebreak preferring the minimum number of extra functional flags
1989 // (see b/200293124, the incorrect selection of AUDIO_OUTPUT_FLAG_VOIP_RX).
Eric Laurent16c66dd2019-05-01 17:54:10 -07001990 // 3: the output supporting the exact channel mask
1991 // 4: the output with a higher channel count than requested
jiabinb12a6da2022-06-03 20:48:18 +00001992 // 5: the output with the highest sampling rate if the requested sample rate is
1993 // greater than default sampling rate
Eric Laurent16c66dd2019-05-01 17:54:10 -07001994 // 6: the output with the highest number of requested performance flags
1995 // 7: the output with the bit depth the closest to the requested one
1996 // 8: the primary output
1997 // 9: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07001998
Eric Laurent16c66dd2019-05-01 17:54:10 -07001999 // matching criteria values in priority order for best matching output so far
2000 std::vector<uint32_t> bestMatchCriteria(8, 0);
Eric Laurente552edb2014-03-10 17:42:56 -07002001
Eric Laurent16c66dd2019-05-01 17:54:10 -07002002 const uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
2003 const uint32_t hapticChannelCount = audio_channel_count_from_out_mask(
2004 channelMask & AUDIO_CHANNEL_HAPTIC_ALL);
Eric Laurente78b6762018-12-19 16:29:01 -08002005
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002006 for (audio_io_handle_t output : outputs) {
2007 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent16c66dd2019-05-01 17:54:10 -07002008 // matching criteria values in priority order for current output
2009 std::vector<uint32_t> currentMatchCriteria(8, 0);
jiabin40573322018-11-08 12:08:02 -08002010
Eric Laurent16c66dd2019-05-01 17:54:10 -07002011 if (outputDesc->isDuplicated()) {
2012 continue;
2013 }
2014 if ((kExcludedFlags & outputDesc->mFlags) != 0) {
2015 continue;
2016 }
Eric Laurent8838a382014-09-08 16:44:28 -07002017
Eric Laurent16c66dd2019-05-01 17:54:10 -07002018 // If haptic channel is specified, use the haptic output if present.
2019 // When using haptic output, same audio format and sample rate are required.
2020 const uint32_t outputHapticChannelCount = audio_channel_count_from_out_mask(
jiabin5740f082019-08-19 15:08:30 -07002021 outputDesc->getChannelMask() & AUDIO_CHANNEL_HAPTIC_ALL);
Eric Laurent16c66dd2019-05-01 17:54:10 -07002022 if ((hapticChannelCount == 0) != (outputHapticChannelCount == 0)) {
2023 continue;
2024 }
2025 if (outputHapticChannelCount >= hapticChannelCount
jiabin5740f082019-08-19 15:08:30 -07002026 && format == outputDesc->getFormat()
2027 && samplingRate == outputDesc->getSamplingRate()) {
Eric Laurent16c66dd2019-05-01 17:54:10 -07002028 currentMatchCriteria[0] = outputHapticChannelCount;
2029 }
2030
2031 // functional flags match
Carter Hsu199f1892021-10-15 15:47:29 +08002032 const int matchingFunctionalFlags =
2033 __builtin_popcount(outputDesc->mFlags & functionalFlags);
2034 const int totalFunctionalFlags =
2035 __builtin_popcount(outputDesc->mFlags & kFunctionalFlags);
2036 // Prefer matching functional flags, but subtract unnecessary functional flags.
2037 currentMatchCriteria[1] = 100 * (matchingFunctionalFlags + 1) - totalFunctionalFlags;
Eric Laurent16c66dd2019-05-01 17:54:10 -07002038
2039 // channel mask and channel count match
jiabin5740f082019-08-19 15:08:30 -07002040 uint32_t outputChannelCount = audio_channel_count_from_out_mask(
2041 outputDesc->getChannelMask());
Eric Laurent16c66dd2019-05-01 17:54:10 -07002042 if (channelMask != AUDIO_CHANNEL_NONE && channelCount > 2 &&
2043 channelCount <= outputChannelCount) {
2044 if ((audio_channel_mask_get_representation(channelMask) ==
jiabin5740f082019-08-19 15:08:30 -07002045 audio_channel_mask_get_representation(outputDesc->getChannelMask())) &&
2046 ((channelMask & outputDesc->getChannelMask()) == channelMask)) {
Eric Laurent16c66dd2019-05-01 17:54:10 -07002047 currentMatchCriteria[2] = outputChannelCount;
Eric Laurente552edb2014-03-10 17:42:56 -07002048 }
Eric Laurent16c66dd2019-05-01 17:54:10 -07002049 currentMatchCriteria[3] = outputChannelCount;
2050 }
2051
2052 // sampling rate match
jiabinb12a6da2022-06-03 20:48:18 +00002053 if (samplingRate > SAMPLE_RATE_HZ_DEFAULT) {
jiabin5740f082019-08-19 15:08:30 -07002054 currentMatchCriteria[4] = outputDesc->getSamplingRate();
Eric Laurent16c66dd2019-05-01 17:54:10 -07002055 }
2056
2057 // performance flags match
2058 currentMatchCriteria[5] = popcount(outputDesc->mFlags & performanceFlags);
2059
2060 // format match
2061 if (format != AUDIO_FORMAT_INVALID) {
2062 currentMatchCriteria[6] =
jiabin4ef93452019-09-10 14:29:54 -07002063 PolicyAudioPort::kFormatDistanceMax -
2064 PolicyAudioPort::formatDistance(format, outputDesc->getFormat());
Eric Laurent16c66dd2019-05-01 17:54:10 -07002065 }
2066
2067 // primary output match
2068 currentMatchCriteria[7] = outputDesc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY;
2069
2070 // compare match criteria by priority then value
2071 if (std::lexicographical_compare(bestMatchCriteria.begin(), bestMatchCriteria.end(),
2072 currentMatchCriteria.begin(), currentMatchCriteria.end())) {
2073 bestMatchCriteria = currentMatchCriteria;
2074 bestOutput = output;
2075
2076 std::stringstream result;
2077 std::copy(bestMatchCriteria.begin(), bestMatchCriteria.end(),
2078 std::ostream_iterator<int>(result, " "));
2079 ALOGV("%s new bestOutput %d criteria %s",
2080 __func__, bestOutput, result.str().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07002081 }
2082 }
2083
Eric Laurent16c66dd2019-05-01 17:54:10 -07002084 return bestOutput;
Eric Laurente552edb2014-03-10 17:42:56 -07002085}
2086
Eric Laurent8fc147b2018-07-22 19:13:55 -07002087status_t AudioPolicyManager::startOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002088{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002089 ALOGV("%s portId %d", __FUNCTION__, portId);
2090
2091 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2092 if (outputDesc == 0) {
2093 ALOGW("startOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002094 return BAD_VALUE;
2095 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002096 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002097
Eric Laurent8fc147b2018-07-22 19:13:55 -07002098 ALOGV("startOutput() output %d, stream %d, session %d",
Eric Laurent97ac8712018-07-27 18:59:02 -07002099 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurentc75307b2015-03-17 15:29:32 -07002100
Eric Laurent733ce942017-12-07 12:18:25 -08002101 status_t status = outputDesc->start();
2102 if (status != NO_ERROR) {
2103 return status;
Eric Laurent3974e3b2017-12-07 17:58:43 -08002104 }
2105
Eric Laurent97ac8712018-07-27 18:59:02 -07002106 uint32_t delayMs;
2107 status = startSource(outputDesc, client, &delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07002108
2109 if (status != NO_ERROR) {
Eric Laurent733ce942017-12-07 12:18:25 -08002110 outputDesc->stop();
jiabin3ff8d7d2022-12-13 06:27:44 +00002111 if (status == DEAD_OBJECT) {
2112 sp<SwAudioOutputDescriptor> desc =
2113 reopenOutput(outputDesc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
2114 if (desc == nullptr) {
2115 // This is not common, it may indicate something wrong with the HAL.
2116 ALOGE("%s unable to open output with default config", __func__);
2117 return status;
2118 }
2119 desc->mUsePreferredMixerAttributes = true;
2120 }
Eric Laurent8c7e6da2015-04-21 17:37:00 -07002121 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07002122 }
jiabina84c3d32022-12-02 18:59:55 +00002123
2124 // If the client is the first one active on preferred mixer parameters, reopen the output
2125 // if the current mixer parameters doesn't match the preferred one.
2126 if (outputDesc->devices().size() == 1) {
2127 sp<PreferredMixerAttributesInfo> info = getPreferredMixerAttributesInfo(
2128 outputDesc->devices()[0]->getId(), client->strategy());
2129 if (info != nullptr && info->getUid() == client->uid()) {
2130 if (info->getActiveClientCount() == 0 && !outputDesc->isConfigurationMatched(
2131 info->getConfigBase(), info->getFlags())) {
2132 stopSource(outputDesc, client);
2133 outputDesc->stop();
2134 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
2135 config.channel_mask = info->getConfigBase().channel_mask;
2136 config.sample_rate = info->getConfigBase().sample_rate;
2137 config.format = info->getConfigBase().format;
jiabin3ff8d7d2022-12-13 06:27:44 +00002138 sp<SwAudioOutputDescriptor> desc =
2139 reopenOutput(outputDesc, &config, info->getFlags(), __func__);
2140 if (desc == nullptr) {
2141 return BAD_VALUE;
jiabina84c3d32022-12-02 18:59:55 +00002142 }
jiabin3ff8d7d2022-12-13 06:27:44 +00002143 desc->mUsePreferredMixerAttributes = true;
jiabina84c3d32022-12-02 18:59:55 +00002144 // Intentionally return error to let the client side resending request for
2145 // creating and starting.
2146 return DEAD_OBJECT;
2147 }
2148 info->increaseActiveClient();
2149 }
2150 }
2151
Jean-Michel Trivib1f6e642023-02-07 20:49:04 +00002152 if (client->hasPreferredDevice()) {
2153 // playback activity with preferred device impacts routing occurred, inform upper layers
2154 mpClientInterface->onRoutingUpdated();
2155 }
Eric Laurentc75307b2015-03-17 15:29:32 -07002156 if (delayMs != 0) {
2157 usleep(delayMs * 1000);
2158 }
2159
2160 return status;
2161}
2162
Eric Laurent96d1dda2022-03-14 17:14:19 +01002163bool AudioPolicyManager::isLeUnicastActive() const {
2164 if (isInCall()) {
2165 return true;
2166 }
2167 return isAnyDeviceTypeActive(getAudioDeviceOutLeAudioUnicastSet());
2168}
2169
2170bool AudioPolicyManager::isAnyDeviceTypeActive(const DeviceTypeSet& deviceTypes) const {
2171 if (mAvailableOutputDevices.getDevicesFromTypes(deviceTypes).isEmpty()) {
2172 return false;
2173 }
2174 bool active = mOutputs.isAnyDeviceTypeActive(deviceTypes);
2175 ALOGV("%s active %d", __func__, active);
2176 return active;
2177}
2178
Eric Laurent97ac8712018-07-27 18:59:02 -07002179status_t AudioPolicyManager::startSource(const sp<SwAudioOutputDescriptor>& outputDesc,
2180 const sp<TrackClientDescriptor>& client,
2181 uint32_t *delayMs)
Eric Laurentc75307b2015-03-17 15:29:32 -07002182{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002183 // cannot start playback of STREAM_TTS if any other output is being used
2184 uint32_t beaconMuteLatency = 0;
Eric Laurentc75307b2015-03-17 15:29:32 -07002185
2186 *delayMs = 0;
Eric Laurent97ac8712018-07-27 18:59:02 -07002187 audio_stream_type_t stream = client->stream();
François Gaffie1c878552018-11-22 16:53:21 +01002188 auto clientVolSrc = client->volumeSource();
François Gaffiec005e562018-11-06 15:04:49 +01002189 auto clientStrategy = client->strategy();
2190 auto clientAttr = client->attributes();
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002191 if (stream == AUDIO_STREAM_TTS) {
2192 ALOGV("\t found BEACON stream");
François Gaffie1c878552018-11-22 16:53:21 +01002193 if (!mTtsOutputAvailable && mOutputs.isAnyOutputActive(
Francois Gaffie4404ddb2021-02-04 17:03:38 +01002194 toVolumeSource(AUDIO_STREAM_TTS, false) /*sourceToIgnore*/)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002195 return INVALID_OPERATION;
2196 } else {
2197 beaconMuteLatency = handleEventForBeacon(STARTING_BEACON);
2198 }
2199 } else {
2200 // some playback other than beacon starts
2201 beaconMuteLatency = handleEventForBeacon(STARTING_OUTPUT);
2202 }
2203
Eric Laurent77305a62016-07-25 16:39:22 -07002204 // force device change if the output is inactive and no audio patch is already present.
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002205 // check active before incrementing usage count
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02002206 bool force = !outputDesc->isActive() && !outputDesc->isRouted();
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002207
François Gaffie11d30102018-11-02 16:09:09 +01002208 DeviceVector devices;
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002209 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
Eric Laurent97ac8712018-07-27 18:59:02 -07002210 const char *address = NULL;
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002211 if (policyMix != nullptr) {
François Gaffie11d30102018-11-02 16:09:09 +01002212 audio_devices_t newDeviceType;
Eric Laurent97ac8712018-07-27 18:59:02 -07002213 address = policyMix->mDeviceAddress.string();
Kevin Rocard153f92d2018-12-18 18:33:28 -08002214 if ((policyMix->mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie11d30102018-11-02 16:09:09 +01002215 newDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Kevin Rocard153f92d2018-12-18 18:33:28 -08002216 } else {
2217 newDeviceType = policyMix->mDeviceType;
Eric Laurent97ac8712018-07-27 18:59:02 -07002218 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08002219 sp device = mAvailableOutputDevices.getDevice(newDeviceType, String8(address),
2220 AUDIO_FORMAT_DEFAULT);
2221 ALOG_ASSERT(device, "%s: no device found t=%u, a=%s", __func__, newDeviceType, address);
2222 devices.add(device);
Eric Laurent97ac8712018-07-27 18:59:02 -07002223 }
2224
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002225 // requiresMuteCheck is false when we can bypass mute strategy.
2226 // It covers a common case when there is no materially active audio
2227 // and muting would result in unnecessary delay and dropped audio.
2228 const uint32_t outputLatencyMs = outputDesc->latency();
2229 bool requiresMuteCheck = outputDesc->isActive(outputLatencyMs * 2); // account for drain
Eric Laurent96d1dda2022-03-14 17:14:19 +01002230 bool wasLeUnicastActive = isLeUnicastActive();
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002231
Eric Laurente552edb2014-03-10 17:42:56 -07002232 // increment usage count for this stream on the requested output:
2233 // NOTE that the usage count is the same for duplicated output and hardware output which is
2234 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
Eric Laurent592dd7b2018-08-05 18:58:48 -07002235 outputDesc->setClientActive(client, true);
Eric Laurent97ac8712018-07-27 18:59:02 -07002236
2237 if (client->hasPreferredDevice(true)) {
Eric Laurent72af8012023-03-15 17:36:22 +01002238 if (outputDesc->sameExclusivePreferredDevicesCount() > 0) {
François Gaffief96e5432019-04-09 17:13:56 +02002239 // Preferred device may be exclusive, use only if no other active clients on this output
2240 devices = DeviceVector(
2241 mAvailableOutputDevices.getDeviceFromId(client->preferredDeviceId()));
2242 } else {
2243 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
2244 }
François Gaffie11d30102018-11-02 16:09:09 +01002245 if (devices != outputDesc->devices()) {
François Gaffiec005e562018-11-06 15:04:49 +01002246 checkStrategyRoute(clientStrategy, outputDesc->mIoHandle);
Eric Laurent97ac8712018-07-27 18:59:02 -07002247 }
2248 }
Eric Laurente552edb2014-03-10 17:42:56 -07002249
François Gaffiec005e562018-11-06 15:04:49 +01002250 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07002251 selectOutputForMusicEffects();
2252 }
2253
François Gaffie1c878552018-11-22 16:53:21 +01002254 if (outputDesc->getActivityCount(clientVolSrc) == 1 || !devices.isEmpty()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08002255 // starting an output being rerouted?
François Gaffie11d30102018-11-02 16:09:09 +01002256 if (devices.isEmpty()) {
2257 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Eric Laurent275e8e92014-11-30 15:14:47 -08002258 }
François Gaffiec005e562018-11-06 15:04:49 +01002259 bool shouldWait =
2260 (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM)) ||
2261 followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_NOTIFICATION)) ||
2262 (beaconMuteLatency > 0));
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002263 uint32_t waitMs = beaconMuteLatency;
Eric Laurente552edb2014-03-10 17:42:56 -07002264 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01002265 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07002266 if (desc != outputDesc) {
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002267 // An output has a shared device if
2268 // - managed by the same hw module
2269 // - supports the currently selected device
2270 const bool sharedDevice = outputDesc->sharesHwModuleWith(desc)
François Gaffie11d30102018-11-02 16:09:09 +01002271 && (!desc->filterSupportedDevices(devices).isEmpty());
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002272
Eric Laurent77305a62016-07-25 16:39:22 -07002273 // force a device change if any other output is:
2274 // - managed by the same hw module
Jean-Michel Trivi4a5b4812018-02-08 17:22:32 +00002275 // - supports currently selected device
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002276 // - has a current device selection that differs from selected device.
Eric Laurent77305a62016-07-25 16:39:22 -07002277 // - has an active audio patch
Eric Laurente552edb2014-03-10 17:42:56 -07002278 // In this case, the audio HAL must receive the new device selection so that it can
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002279 // change the device currently selected by the other output.
2280 if (sharedDevice &&
François Gaffie11d30102018-11-02 16:09:09 +01002281 desc->devices() != devices &&
Eric Laurent77305a62016-07-25 16:39:22 -07002282 desc->getPatchHandle() != AUDIO_PATCH_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07002283 force = true;
2284 }
2285 // wait for audio on other active outputs to be presented when starting
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002286 // a notification so that audio focus effect can propagate, or that a mute/unmute
2287 // event occurred for beacon
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002288 const uint32_t latencyMs = desc->latency();
2289 const bool isActive = desc->isActive(latencyMs * 2); // account for drain
2290
2291 if (shouldWait && isActive && (waitMs < latencyMs)) {
2292 waitMs = latencyMs;
Eric Laurente552edb2014-03-10 17:42:56 -07002293 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002294
2295 // Require mute check if another output is on a shared device
2296 // and currently active to have proper drain and avoid pops.
2297 // Note restoring AudioTracks onto this output needs to invoke
2298 // a volume ramp if there is no mute.
2299 requiresMuteCheck |= sharedDevice && isActive;
Eric Laurente552edb2014-03-10 17:42:56 -07002300 }
2301 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002302
jiabin3ff8d7d2022-12-13 06:27:44 +00002303 if (outputDesc->mUsePreferredMixerAttributes && devices != outputDesc->devices()) {
2304 // If the output is open with preferred mixer attributes, but the routed device is
2305 // changed when calling this function, returning DEAD_OBJECT to indicate routing
2306 // changed.
2307 return DEAD_OBJECT;
2308 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002309 const uint32_t muteWaitMs =
jiabin3ff8d7d2022-12-13 06:27:44 +00002310 setOutputDevices(outputDesc, devices, force, 0, nullptr, requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07002311
Eric Laurente552edb2014-03-10 17:42:56 -07002312 // apply volume rules for current stream and device if necessary
François Gaffieaaac0fd2018-11-22 17:56:39 +01002313 auto &curves = getVolumeCurves(client->attributes());
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00002314 if (NO_ERROR != checkAndSetVolume(curves, client->volumeSource(),
François Gaffieaaac0fd2018-11-22 17:56:39 +01002315 curves.getVolumeIndex(outputDesc->devices().types()),
Eric Laurentc75307b2015-03-17 15:29:32 -07002316 outputDesc,
Francois Gaffied11442b2020-04-27 11:51:09 +02002317 outputDesc->devices().types(), 0 /*delay*/,
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00002318 outputDesc->useHwGain() /*force*/)) {
2319 // request AudioService to reinitialize the volume curves asynchronously
2320 ALOGE("checkAndSetVolume failed, requesting volume range init");
2321 mpClientInterface->onVolumeRangeInitRequest();
2322 };
Eric Laurente552edb2014-03-10 17:42:56 -07002323
2324 // update the outputs if starting an output with a stream that can affect notification
2325 // routing
2326 handleNotificationRoutingForStream(stream);
Eric Laurentc722f302014-12-10 11:21:49 -08002327
Eric Laurent2cbe89a2014-12-19 11:49:08 -08002328 // force reevaluating accessibility routing when ringtone or alarm starts
François Gaffiec005e562018-11-06 15:04:49 +01002329 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM))) {
jiabinc44b3462022-12-08 12:52:31 -08002330 invalidateStreams({AUDIO_STREAM_ACCESSIBILITY});
Eric Laurent2cbe89a2014-12-19 11:49:08 -08002331 }
Eric Laurentdc462862016-07-19 12:29:53 -07002332
2333 if (waitMs > muteWaitMs) {
2334 *delayMs = waitMs - muteWaitMs;
2335 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002336
2337 // FIXME: A device change (muteWaitMs > 0) likely introduces a volume change.
2338 // A volume change enacted by APM with 0 delay is not synchronous, as it goes
2339 // via AudioCommandThread to AudioFlinger. Hence it is possible that the volume
2340 // change occurs after the MixerThread starts and causes a stream volume
2341 // glitch.
2342 //
2343 // We do not introduce additional delay here.
Eric Laurente552edb2014-03-10 17:42:56 -07002344 }
Eric Laurentdc462862016-07-19 12:29:53 -07002345
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002346 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
jiabin9a3361e2019-10-01 09:38:30 -07002347 mEngine->getForceUse(
2348 AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
François Gaffiec005e562018-11-06 15:04:49 +01002349 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), true, outputDesc);
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002350 }
2351
Eric Laurent97ac8712018-07-27 18:59:02 -07002352 // Automatically enable the remote submix input when output is started on a re routing mix
2353 // of type MIX_TYPE_RECORDERS
jiabin9a3361e2019-10-01 09:38:30 -07002354 if (isSingleDeviceType(devices.types(), &audio_is_remote_submix_device) &&
2355 policyMix != NULL && policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002356 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2357 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2358 address,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002359 "remote-submix",
2360 AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07002361 }
2362
Eric Laurent96d1dda2022-03-14 17:14:19 +01002363 checkLeBroadcastRoutes(wasLeUnicastActive, outputDesc, *delayMs);
2364
Eric Laurente552edb2014-03-10 17:42:56 -07002365 return NO_ERROR;
2366}
2367
Eric Laurent96d1dda2022-03-14 17:14:19 +01002368void AudioPolicyManager::checkLeBroadcastRoutes(bool wasUnicastActive,
2369 sp<SwAudioOutputDescriptor> ignoredOutput, uint32_t delayMs) {
2370 bool isUnicastActive = isLeUnicastActive();
2371
2372 if (wasUnicastActive != isUnicastActive) {
jiabin3ff8d7d2022-12-13 06:27:44 +00002373 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent96d1dda2022-03-14 17:14:19 +01002374 //reroute all outputs routed to LE broadcast if LE unicast activy changed on any output
2375 for (size_t i = 0; i < mOutputs.size(); i++) {
2376 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
2377 if (desc != ignoredOutput && desc->isActive()
2378 && ((isUnicastActive &&
2379 !desc->devices().
2380 getDevicesFromType(AUDIO_DEVICE_OUT_BLE_BROADCAST).isEmpty())
2381 || (wasUnicastActive &&
2382 !desc->devices().getDevicesFromTypes(
2383 getAudioDeviceOutLeAudioUnicastSet()).isEmpty()))) {
2384 DeviceVector newDevices = getNewOutputDevices(desc, false /*fromCache*/);
2385 bool force = desc->devices() != newDevices;
jiabin3ff8d7d2022-12-13 06:27:44 +00002386 if (desc->mUsePreferredMixerAttributes && force) {
2387 // If the device is using preferred mixer attributes, the output need to reopen
2388 // with default configuration when the new selected devices are different from
2389 // current routing devices.
2390 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices);
2391 continue;
2392 }
Eric Laurent96d1dda2022-03-14 17:14:19 +01002393 setOutputDevices(desc, newDevices, force, delayMs);
2394 // re-apply device specific volume if not done by setOutputDevice()
2395 if (!force) {
2396 applyStreamVolumes(desc, newDevices.types(), delayMs);
2397 }
2398 }
2399 }
jiabin3ff8d7d2022-12-13 06:27:44 +00002400 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent96d1dda2022-03-14 17:14:19 +01002401 }
2402}
2403
Eric Laurent8fc147b2018-07-22 19:13:55 -07002404status_t AudioPolicyManager::stopOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002405{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002406 ALOGV("%s portId %d", __FUNCTION__, portId);
2407
2408 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2409 if (outputDesc == 0) {
2410 ALOGW("stopOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002411 return BAD_VALUE;
2412 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002413 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002414
Jean-Michel Trivib1f6e642023-02-07 20:49:04 +00002415 if (client->hasPreferredDevice(true)) {
2416 // playback activity with preferred device impacts routing occurred, inform upper layers
2417 mpClientInterface->onRoutingUpdated();
2418 }
2419
Eric Laurent97ac8712018-07-27 18:59:02 -07002420 ALOGV("stopOutput() output %d, stream %d, session %d",
2421 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurente552edb2014-03-10 17:42:56 -07002422
Eric Laurent97ac8712018-07-27 18:59:02 -07002423 status_t status = stopSource(outputDesc, client);
Eric Laurent3974e3b2017-12-07 17:58:43 -08002424
Eric Laurent733ce942017-12-07 12:18:25 -08002425 if (status == NO_ERROR ) {
2426 outputDesc->stop();
jiabina84c3d32022-12-02 18:59:55 +00002427 } else {
2428 return status;
2429 }
2430
2431 if (outputDesc->devices().size() == 1) {
2432 sp<PreferredMixerAttributesInfo> info = getPreferredMixerAttributesInfo(
2433 outputDesc->devices()[0]->getId(), client->strategy());
2434 if (info != nullptr && info->getUid() == client->uid()) {
2435 info->decreaseActiveClient();
2436 if (info->getActiveClientCount() == 0) {
2437 reopenOutput(outputDesc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
2438 }
2439 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002440 }
2441 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07002442}
2443
Eric Laurent97ac8712018-07-27 18:59:02 -07002444status_t AudioPolicyManager::stopSource(const sp<SwAudioOutputDescriptor>& outputDesc,
2445 const sp<TrackClientDescriptor>& client)
Eric Laurentc75307b2015-03-17 15:29:32 -07002446{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002447 // always handle stream stop, check which stream type is stopping
Eric Laurent97ac8712018-07-27 18:59:02 -07002448 audio_stream_type_t stream = client->stream();
François Gaffie1c878552018-11-22 16:53:21 +01002449 auto clientVolSrc = client->volumeSource();
Eric Laurent96d1dda2022-03-14 17:14:19 +01002450 bool wasLeUnicastActive = isLeUnicastActive();
Eric Laurent97ac8712018-07-27 18:59:02 -07002451
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002452 handleEventForBeacon(stream == AUDIO_STREAM_TTS ? STOPPING_BEACON : STOPPING_OUTPUT);
2453
François Gaffie1c878552018-11-22 16:53:21 +01002454 if (outputDesc->getActivityCount(clientVolSrc) > 0) {
2455 if (outputDesc->getActivityCount(clientVolSrc) == 1) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002456 // Automatically disable the remote submix input when output is stopped on a
2457 // re routing mix of type MIX_TYPE_RECORDERS
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002458 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
jiabin9a3361e2019-10-01 09:38:30 -07002459 if (isSingleDeviceType(
2460 outputDesc->devices().types(), &audio_is_remote_submix_device) &&
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002461 policyMix != nullptr &&
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002462 policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002463 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2464 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002465 policyMix->mDeviceAddress,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002466 "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07002467 }
2468 }
2469 bool forceDeviceUpdate = false;
Eric Laurent72af8012023-03-15 17:36:22 +01002470 if (client->hasPreferredDevice(true) &&
2471 outputDesc->sameExclusivePreferredDevicesCount() < 2) {
François Gaffiec005e562018-11-06 15:04:49 +01002472 checkStrategyRoute(client->strategy(), AUDIO_IO_HANDLE_NONE);
Eric Laurent97ac8712018-07-27 18:59:02 -07002473 forceDeviceUpdate = true;
2474 }
2475
Eric Laurente552edb2014-03-10 17:42:56 -07002476 // decrement usage count of this stream on the output
Eric Laurent592dd7b2018-08-05 18:58:48 -07002477 outputDesc->setClientActive(client, false);
Paul McLeanaa981192015-03-21 09:55:15 -07002478
Eric Laurente552edb2014-03-10 17:42:56 -07002479 // store time at which the stream was stopped - see isStreamActive()
François Gaffie1c878552018-11-22 16:53:21 +01002480 if (outputDesc->getActivityCount(clientVolSrc) == 0 || forceDeviceUpdate) {
François Gaffiec005e562018-11-06 15:04:49 +01002481 outputDesc->setStopTime(client, systemTime());
François Gaffie11d30102018-11-02 16:09:09 +01002482 DeviceVector newDevices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Francois Gaffie3523ab32021-06-22 13:24:34 +02002483
2484 // If the routing does not change, if an output is routed on a device using HwGain
2485 // (aka setAudioPortConfig) and there are still active clients following different
2486 // volume group(s), force reapply volume
2487 bool requiresVolumeCheck = outputDesc->getActivityCount(clientVolSrc) == 0 &&
2488 outputDesc->useHwGain() && outputDesc->isAnyActive(VOLUME_SOURCE_NONE);
2489
Eric Laurente552edb2014-03-10 17:42:56 -07002490 // delay the device switch by twice the latency because stopOutput() is executed when
2491 // the track stop() command is received and at that time the audio track buffer can
2492 // still contain data that needs to be drained. The latency only covers the audio HAL
2493 // and kernel buffers. Also the latency does not always include additional delay in the
2494 // audio path (audio DSP, CODEC ...)
Francois Gaffie3523ab32021-06-22 13:24:34 +02002495 setOutputDevices(outputDesc, newDevices, false, outputDesc->latency()*2,
2496 nullptr, true /*requiresMuteCheck*/, requiresVolumeCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07002497
2498 // force restoring the device selection on other active outputs if it differs from the
2499 // one being selected for this output
jiabin3ff8d7d2022-12-13 06:27:44 +00002500 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent57de36c2016-09-28 16:59:11 -07002501 uint32_t delayMs = outputDesc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -07002502 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01002503 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07002504 if (desc != outputDesc &&
Eric Laurente552edb2014-03-10 17:42:56 -07002505 desc->isActive() &&
2506 outputDesc->sharesHwModuleWith(desc) &&
François Gaffie11d30102018-11-02 16:09:09 +01002507 (newDevices != desc->devices())) {
2508 DeviceVector newDevices2 = getNewOutputDevices(desc, false /*fromCache*/);
2509 bool force = desc->devices() != newDevices2;
Eric Laurentf3a5a602018-05-22 18:42:55 -07002510
jiabin3ff8d7d2022-12-13 06:27:44 +00002511 if (desc->mUsePreferredMixerAttributes && force) {
2512 // If the device is using preferred mixer attributes, the output need to
2513 // reopen with default configuration when the new selected devices are
2514 // different from current routing devices.
2515 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices2);
2516 continue;
2517 }
François Gaffie11d30102018-11-02 16:09:09 +01002518 setOutputDevices(desc, newDevices2, force, delayMs);
2519
Eric Laurent57de36c2016-09-28 16:59:11 -07002520 // re-apply device specific volume if not done by setOutputDevice()
2521 if (!force) {
François Gaffie11d30102018-11-02 16:09:09 +01002522 applyStreamVolumes(desc, newDevices2.types(), delayMs);
Eric Laurent57de36c2016-09-28 16:59:11 -07002523 }
Eric Laurente552edb2014-03-10 17:42:56 -07002524 }
2525 }
jiabin3ff8d7d2022-12-13 06:27:44 +00002526 reopenOutputsWithDevices(outputsToReopen);
Eric Laurente552edb2014-03-10 17:42:56 -07002527 // update the outputs if stopping one with a stream that can affect notification routing
2528 handleNotificationRoutingForStream(stream);
2529 }
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002530
2531 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
2532 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Jean-Michel Trivi74e01fa2019-02-25 12:18:09 -08002533 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), false, outputDesc);
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002534 }
2535
François Gaffiec005e562018-11-06 15:04:49 +01002536 if (followsSameRouting(client->attributes(), attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07002537 selectOutputForMusicEffects();
2538 }
Eric Laurent96d1dda2022-03-14 17:14:19 +01002539
2540 checkLeBroadcastRoutes(wasLeUnicastActive, outputDesc, outputDesc->latency()*2);
2541
Eric Laurente552edb2014-03-10 17:42:56 -07002542 return NO_ERROR;
2543 } else {
Eric Laurentc75307b2015-03-17 15:29:32 -07002544 ALOGW("stopOutput() refcount is already 0");
Eric Laurente552edb2014-03-10 17:42:56 -07002545 return INVALID_OPERATION;
2546 }
2547}
2548
jiabinbce0c1d2020-10-05 11:20:18 -07002549bool AudioPolicyManager::releaseOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002550{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002551 ALOGV("%s portId %d", __FUNCTION__, portId);
2552
2553 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2554 if (outputDesc == 0) {
Andy Hung39efb7a2018-09-26 15:39:28 -07002555 // If an output descriptor is closed due to a device routing change,
2556 // then there are race conditions with releaseOutput from tracks
2557 // that may be destroyed (with no PlaybackThread) or a PlaybackThread
2558 // destroyed shortly thereafter.
2559 //
2560 // Here we just log a warning, instead of a fatal error.
Eric Laurent8fc147b2018-07-22 19:13:55 -07002561 ALOGW("releaseOutput() no output for client %d", portId);
jiabinbce0c1d2020-10-05 11:20:18 -07002562 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002563 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002564
2565 ALOGV("releaseOutput() %d", outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -07002566
Jaideep Sharma7bf382e2020-11-26 17:07:29 +05302567 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
2568 if (outputDesc->isClientActive(client)) {
2569 ALOGW("releaseOutput() inactivates portId %d in good faith", portId);
2570 stopOutput(portId);
2571 }
2572
Eric Laurent8fc147b2018-07-22 19:13:55 -07002573 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
2574 if (outputDesc->mDirectOpenCount <= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07002575 ALOGW("releaseOutput() invalid open count %d for output %d",
Eric Laurent8fc147b2018-07-22 19:13:55 -07002576 outputDesc->mDirectOpenCount, outputDesc->mIoHandle);
jiabinbce0c1d2020-10-05 11:20:18 -07002577 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002578 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002579 if (--outputDesc->mDirectOpenCount == 0) {
2580 closeOutput(outputDesc->mIoHandle);
Eric Laurentb52c1522014-05-20 11:27:36 -07002581 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07002582 }
2583 }
Jaideep Sharma7bf382e2020-11-26 17:07:29 +05302584
Andy Hung39efb7a2018-09-26 15:39:28 -07002585 outputDesc->removeClient(portId);
jiabinbce0c1d2020-10-05 11:20:18 -07002586 if (outputDesc->mPendingReopenToQueryProfiles && outputDesc->getClientCount() == 0) {
2587 // The output is pending reopened to query dynamic profiles and
2588 // there is no active clients
2589 closeOutput(outputDesc->mIoHandle);
2590 sp<SwAudioOutputDescriptor> newOutputDesc = openOutputWithProfileAndDevice(
2591 outputDesc->mProfile, mEngine->getActiveMediaDevices(mAvailableOutputDevices));
2592 if (newOutputDesc == nullptr) {
2593 ALOGE("%s failed to open output", __func__);
2594 }
2595 return true;
2596 }
2597 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002598}
2599
Eric Laurentcaf7f482014-11-25 17:50:47 -08002600status_t AudioPolicyManager::getInputForAttr(const audio_attributes_t *attr,
2601 audio_io_handle_t *input,
Mikhail Naganov2996f672019-04-18 12:29:59 -07002602 audio_unique_id_t riid,
Eric Laurentcaf7f482014-11-25 17:50:47 -08002603 audio_session_t session,
Svet Ganov3e5f14f2021-05-13 22:51:08 +00002604 const AttributionSourceState& attributionSource,
jiabinf1c73972022-04-14 16:28:52 -07002605 audio_config_base_t *config,
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002606 audio_input_flags_t flags,
Eric Laurent2ac76942017-06-22 17:17:09 -07002607 audio_port_handle_t *selectedDeviceId,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002608 input_type_t *inputType,
2609 audio_port_handle_t *portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002610{
François Gaffiec005e562018-11-06 15:04:49 +01002611 ALOGV("%s() source %d, sampling rate %d, format %#x, channel mask %#x, session %d, "
Eric Laurent2f2c1982021-06-02 14:03:11 +02002612 "flags %#x attributes=%s requested device ID %d",
2613 __func__, attr->source, config->sample_rate, config->format, config->channel_mask,
2614 session, flags, toString(*attr).c_str(), *selectedDeviceId);
Eric Laurente552edb2014-03-10 17:42:56 -07002615
Eric Laurentad2e7b92017-09-14 20:06:42 -07002616 status_t status = NO_ERROR;
Francois Gaffie716e1432019-01-14 16:58:59 +01002617 audio_attributes_t attributes = *attr;
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002618 sp<AudioPolicyMix> policyMix;
François Gaffie11d30102018-11-02 16:09:09 +01002619 sp<DeviceDescriptor> device;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002620 sp<AudioInputDescriptor> inputDesc;
2621 sp<RecordClientDescriptor> clientDesc;
2622 audio_port_handle_t requestedDeviceId = *selectedDeviceId;
Svet Ganov3e5f14f2021-05-13 22:51:08 +00002623 uid_t uid = VALUE_OR_RETURN_STATUS(aidl2legacy_int32_t_uid_t(attributionSource.uid));
Eric Laurent8f42ea12018-08-08 09:08:25 -07002624 bool isSoundTrigger;
Eric Laurent8f42ea12018-08-08 09:08:25 -07002625
2626 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
2627 if (*portId != AUDIO_PORT_HANDLE_NONE) {
2628 return INVALID_OPERATION;
2629 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08002630
Francois Gaffie716e1432019-01-14 16:58:59 +01002631 if (attr->source == AUDIO_SOURCE_DEFAULT) {
2632 attributes.source = AUDIO_SOURCE_MIC;
Eric Laurentfe231122017-11-17 17:48:06 -08002633 }
2634
Paul McLean466dc8e2015-04-17 13:15:36 -06002635 // Explicit routing?
Pattydd807582021-11-04 21:01:03 +08002636 sp<DeviceDescriptor> explicitRoutingDevice =
François Gaffie11d30102018-11-02 16:09:09 +01002637 mAvailableInputDevices.getDeviceFromId(*selectedDeviceId);
Paul McLean466dc8e2015-04-17 13:15:36 -06002638
Eric Laurentad2e7b92017-09-14 20:06:42 -07002639 // special case for mmap capture: if an input IO handle is specified, we reuse this input if
2640 // possible
2641 if ((flags & AUDIO_INPUT_FLAG_MMAP_NOIRQ) == AUDIO_INPUT_FLAG_MMAP_NOIRQ &&
2642 *input != AUDIO_IO_HANDLE_NONE) {
2643 ssize_t index = mInputs.indexOfKey(*input);
2644 if (index < 0) {
2645 ALOGW("getInputForAttr() unknown MMAP input %d", *input);
2646 status = BAD_VALUE;
2647 goto error;
2648 }
2649 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002650 RecordClientVector clients = inputDesc->getClientsForSession(session);
2651 if (clients.size() == 0) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07002652 ALOGW("getInputForAttr() unknown session %d on input %d", session, *input);
2653 status = BAD_VALUE;
2654 goto error;
2655 }
2656 // For MMAP mode, the first call to getInputForAttr() is made on behalf of audioflinger.
2657 // The second call is for the first active client and sets the UID. Any further call
Eric Laurent331679c2018-04-16 17:03:16 -07002658 // corresponds to a new client and is only permitted from the same UID.
2659 // If the first UID is silenced, allow a new UID connection and replace with new UID
Eric Laurent8f42ea12018-08-08 09:08:25 -07002660 if (clients.size() > 1) {
2661 for (const auto& client : clients) {
2662 // The client map is ordered by key values (portId) and portIds are allocated
2663 // incrementaly. So the first client in this list is the one opened by audio flinger
2664 // when the mmap stream is created and should be ignored as it does not correspond
2665 // to an actual client
2666 if (client == *clients.cbegin()) {
2667 continue;
2668 }
2669 if (uid != client->uid() && !client->isSilenced()) {
2670 ALOGW("getInputForAttr() bad uid %d for client %d uid %d",
2671 uid, client->portId(), client->uid());
2672 status = INVALID_OPERATION;
2673 goto error;
2674 }
Eric Laurent331679c2018-04-16 17:03:16 -07002675 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002676 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002677 *inputType = API_INPUT_LEGACY;
François Gaffie11d30102018-11-02 16:09:09 +01002678 device = inputDesc->getDevice();
Eric Laurentad2e7b92017-09-14 20:06:42 -07002679
Eric Laurentfecbceb2021-02-09 14:46:43 +01002680 ALOGV("%s reusing MMAP input %d for session %d", __FUNCTION__, *input, session);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002681 goto exit;
Eric Laurentad2e7b92017-09-14 20:06:42 -07002682 }
2683
2684 *input = AUDIO_IO_HANDLE_NONE;
2685 *inputType = API_INPUT_INVALID;
2686
Francois Gaffie716e1432019-01-14 16:58:59 +01002687 if (attributes.source == AUDIO_SOURCE_REMOTE_SUBMIX &&
Jan Sebechlebskybc56bcd2022-09-26 13:15:19 +02002688 extractAddressFromAudioAttributes(attributes).has_value()) {
Francois Gaffie716e1432019-01-14 16:58:59 +01002689 status = mPolicyMixes.getInputMixForAttr(attributes, &policyMix);
Eric Laurentad2e7b92017-09-14 20:06:42 -07002690 if (status != NO_ERROR) {
jiabinc1de2df2019-05-07 14:26:40 -07002691 ALOGW("%s could not find input mix for attr %s",
2692 __func__, toString(attributes).c_str());
Eric Laurentad2e7b92017-09-14 20:06:42 -07002693 goto error;
François Gaffie036e1e92015-03-19 10:16:24 +01002694 }
jiabinc1de2df2019-05-07 14:26:40 -07002695 device = mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2696 String8(attr->tags + strlen("addr=")),
2697 AUDIO_FORMAT_DEFAULT);
2698 if (device == nullptr) {
Kevin Rocard04ed0462019-05-02 17:53:24 -07002699 ALOGW("%s could not find in Remote Submix device for source %d, tags %s",
jiabinc1de2df2019-05-07 14:26:40 -07002700 __func__, attributes.source, attributes.tags);
2701 status = BAD_VALUE;
2702 goto error;
2703 }
2704
Kevin Rocard25f9b052019-02-27 15:08:54 -08002705 if (is_mix_loopback_render(policyMix->mRouteFlags)) {
2706 *inputType = API_INPUT_MIX_PUBLIC_CAPTURE_PLAYBACK;
2707 } else {
2708 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
2709 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002710 } else {
François Gaffie11d30102018-11-02 16:09:09 +01002711 if (explicitRoutingDevice != nullptr) {
2712 device = explicitRoutingDevice;
Eric Laurent97ac8712018-07-27 18:59:02 -07002713 } else {
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01002714 // Prevent from storing invalid requested device id in clients
2715 requestedDeviceId = AUDIO_PORT_HANDLE_NONE;
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02002716 device = mEngine->getInputDeviceForAttributes(attributes, uid, session, &policyMix);
yuanjiahsu4069d5d2021-04-19 07:54:27 +08002717 ALOGV_IF(device != nullptr, "%s found device type is 0x%X",
2718 __FUNCTION__, device->type());
Eric Laurent97ac8712018-07-27 18:59:02 -07002719 }
François Gaffie11d30102018-11-02 16:09:09 +01002720 if (device == nullptr) {
Francois Gaffie716e1432019-01-14 16:58:59 +01002721 ALOGW("getInputForAttr() could not find device for source %d", attributes.source);
Eric Laurentad2e7b92017-09-14 20:06:42 -07002722 status = BAD_VALUE;
2723 goto error;
Eric Laurent275e8e92014-11-30 15:14:47 -08002724 }
Alden DSouzab7d20782021-02-08 08:51:42 -08002725 if (device->type() == AUDIO_DEVICE_IN_ECHO_REFERENCE) {
2726 *inputType = API_INPUT_MIX_CAPTURE;
2727 } else if (policyMix) {
François Gaffie11d30102018-11-02 16:09:09 +01002728 ALOG_ASSERT(policyMix->mMixType == MIX_TYPE_RECORDERS, "Invalid Mix Type");
2729 // there is an external policy, but this input is attached to a mix of recorders,
2730 // meaning it receives audio injected into the framework, so the recorder doesn't
2731 // know about it and is therefore considered "legacy"
2732 *inputType = API_INPUT_LEGACY;
2733 } else if (audio_is_remote_submix_device(device->type())) {
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002734 *inputType = API_INPUT_MIX_CAPTURE;
François Gaffie11d30102018-11-02 16:09:09 +01002735 } else if (device->type() == AUDIO_DEVICE_IN_TELEPHONY_RX) {
Eric Laurent82db2692015-08-07 13:59:42 -07002736 *inputType = API_INPUT_TELEPHONY_RX;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002737 } else {
2738 *inputType = API_INPUT_LEGACY;
Eric Laurentc722f302014-12-10 11:21:49 -08002739 }
Ravi Kumar Alamandab367f5b2015-08-25 08:21:37 -07002740
Eric Laurent599c7582015-12-07 18:05:55 -08002741 }
2742
François Gaffiec005e562018-11-06 15:04:49 +01002743 *input = getInputForDevice(device, session, attributes, config, flags, policyMix);
Eric Laurent599c7582015-12-07 18:05:55 -08002744 if (*input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07002745 status = INVALID_OPERATION;
jiabinf1c73972022-04-14 16:28:52 -07002746 AudioProfileVector profiles;
2747 status_t ret = getProfilesForDevices(
2748 DeviceVector(device), profiles, flags, true /*isInput*/);
2749 if (ret == NO_ERROR && !profiles.empty()) {
2750 config->channel_mask = profiles[0]->getChannels().empty() ? config->channel_mask
2751 : *profiles[0]->getChannels().begin();
2752 config->sample_rate = profiles[0]->getSampleRates().empty() ? config->sample_rate
2753 : *profiles[0]->getSampleRates().begin();
2754 config->format = profiles[0]->getFormat();
2755 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002756 goto error;
Eric Laurent599c7582015-12-07 18:05:55 -08002757 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08002758
Eric Laurent8f42ea12018-08-08 09:08:25 -07002759exit:
2760
François Gaffiec005e562018-11-06 15:04:49 +01002761 *selectedDeviceId = mAvailableInputDevices.contains(device) ?
2762 device->getId() : AUDIO_PORT_HANDLE_NONE;
Eric Laurent2ac76942017-06-22 17:17:09 -07002763
Francois Gaffie716e1432019-01-14 16:58:59 +01002764 isSoundTrigger = attributes.source == AUDIO_SOURCE_HOTWORD &&
Carter Hsud0cce2e2019-05-03 17:36:28 +08002765 mSoundTriggerSessions.indexOfKey(session) >= 0;
jiabin4ef93452019-09-10 14:29:54 -07002766 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002767
Mikhail Naganov2996f672019-04-18 12:29:59 -07002768 clientDesc = new RecordClientDescriptor(*portId, riid, uid, session, attributes, *config,
Francois Gaffie716e1432019-01-14 16:58:59 +01002769 requestedDeviceId, attributes.source, flags,
2770 isSoundTrigger);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002771 inputDesc = mInputs.valueFor(*input);
Andy Hung39efb7a2018-09-26 15:39:28 -07002772 inputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002773
2774 ALOGV("getInputForAttr() returns input %d type %d selectedDeviceId %d for port ID %d",
2775 *input, *inputType, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07002776
Eric Laurent599c7582015-12-07 18:05:55 -08002777 return NO_ERROR;
Eric Laurentad2e7b92017-09-14 20:06:42 -07002778
2779error:
Eric Laurentad2e7b92017-09-14 20:06:42 -07002780 return status;
Eric Laurent599c7582015-12-07 18:05:55 -08002781}
2782
2783
François Gaffie11d30102018-11-02 16:09:09 +01002784audio_io_handle_t AudioPolicyManager::getInputForDevice(const sp<DeviceDescriptor> &device,
Eric Laurent599c7582015-12-07 18:05:55 -08002785 audio_session_t session,
François Gaffiec005e562018-11-06 15:04:49 +01002786 const audio_attributes_t &attributes,
jiabinf1c73972022-04-14 16:28:52 -07002787 audio_config_base_t *config,
Eric Laurent599c7582015-12-07 18:05:55 -08002788 audio_input_flags_t flags,
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002789 const sp<AudioPolicyMix> &policyMix)
Eric Laurent599c7582015-12-07 18:05:55 -08002790{
2791 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
François Gaffiec005e562018-11-06 15:04:49 +01002792 audio_source_t halInputSource = attributes.source;
Eric Laurent599c7582015-12-07 18:05:55 -08002793 bool isSoundTrigger = false;
2794
François Gaffiec005e562018-11-06 15:04:49 +01002795 if (attributes.source == AUDIO_SOURCE_HOTWORD) {
Eric Laurent599c7582015-12-07 18:05:55 -08002796 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
2797 if (index >= 0) {
2798 input = mSoundTriggerSessions.valueFor(session);
2799 isSoundTrigger = true;
2800 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_HW_HOTWORD);
2801 ALOGV("SoundTrigger capture on session %d input %d", session, input);
2802 } else {
2803 halInputSource = AUDIO_SOURCE_VOICE_RECOGNITION;
Eric Laurent5dbe4712014-09-19 19:04:57 -07002804 }
François Gaffiec005e562018-11-06 15:04:49 +01002805 } else if (attributes.source == AUDIO_SOURCE_VOICE_COMMUNICATION &&
Eric Laurentfe231122017-11-17 17:48:06 -08002806 audio_is_linear_pcm(config->format)) {
Haynes Mathew George851d3ff2017-06-19 20:01:57 -07002807 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_VOIP_TX);
Eric Laurent5dbe4712014-09-19 19:04:57 -07002808 }
2809
Carter Hsua3abb402021-10-26 11:11:20 +08002810 if (attributes.source == AUDIO_SOURCE_ULTRASOUND) {
2811 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_ULTRASOUND);
2812 }
2813
Eric Laurentfe231122017-11-17 17:48:06 -08002814 // sampling rate and flags may be updated by getInputProfile
2815 uint32_t profileSamplingRate = (config->sample_rate == 0) ?
2816 SAMPLE_RATE_HZ_DEFAULT : config->sample_rate;
jiabin2fd710d2022-05-02 23:20:22 +00002817 audio_format_t profileFormat = config->format;
Eric Laurentfe231122017-11-17 17:48:06 -08002818 audio_channel_mask_t profileChannelMask = config->channel_mask;
Andy Hungf129b032015-04-07 13:45:50 -07002819 audio_input_flags_t profileFlags = flags;
jiabin2fd710d2022-05-02 23:20:22 +00002820 // find a compatible input profile (not necessarily identical in parameters)
2821 sp<IOProfile> profile = getInputProfile(
2822 device, profileSamplingRate, profileFormat, profileChannelMask, profileFlags);
2823 if (profile == nullptr) {
2824 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07002825 }
jiabin2fd710d2022-05-02 23:20:22 +00002826
Glenn Kasten05ddca52016-02-11 08:17:12 -08002827 // Pick input sampling rate if not specified by client
Eric Laurentfe231122017-11-17 17:48:06 -08002828 uint32_t samplingRate = config->sample_rate;
Glenn Kasten05ddca52016-02-11 08:17:12 -08002829 if (samplingRate == 0) {
2830 samplingRate = profileSamplingRate;
2831 }
Eric Laurente552edb2014-03-10 17:42:56 -07002832
Eric Laurent322b4d22015-04-03 15:57:54 -07002833 if (profile->getModuleHandle() == 0) {
2834 ALOGE("getInputForAttr(): HW module %s not opened", profile->getModuleName());
Eric Laurent599c7582015-12-07 18:05:55 -08002835 return input;
Eric Laurentcf2c0212014-07-25 16:20:43 -07002836 }
2837
Eric Laurentec376dc2021-04-08 20:41:22 +02002838 // Reuse an already opened input if a client with the same session ID already exists
2839 // on that input
2840 for (size_t i = 0; i < mInputs.size(); i++) {
2841 sp <AudioInputDescriptor> desc = mInputs.valueAt(i);
2842 if (desc->mProfile != profile) {
2843 continue;
2844 }
2845 RecordClientVector clients = desc->clientsList();
2846 for (const auto &client : clients) {
2847 if (session == client->session()) {
2848 return desc->mIoHandle;
2849 }
2850 }
2851 }
2852
Eric Laurent3974e3b2017-12-07 17:58:43 -08002853 if (!profile->canOpenNewIo()) {
Eric Laurent4eb58f12018-12-07 16:41:02 -08002854 for (size_t i = 0; i < mInputs.size(); ) {
Eric Laurentc529cf62020-04-17 18:19:10 -07002855 sp<AudioInputDescriptor> desc = mInputs.valueAt(i);
Eric Laurent4eb58f12018-12-07 16:41:02 -08002856 if (desc->mProfile != profile) {
Carter Hsu9a645a92019-05-15 12:15:32 +08002857 i++;
Eric Laurent4eb58f12018-12-07 16:41:02 -08002858 continue;
2859 }
2860 // if sound trigger, reuse input if used by other sound trigger on same session
2861 // else
2862 // reuse input if active client app is not in IDLE state
2863 //
2864 RecordClientVector clients = desc->clientsList();
2865 bool doClose = false;
2866 for (const auto& client : clients) {
2867 if (isSoundTrigger != client->isSoundTrigger()) {
2868 continue;
2869 }
2870 if (client->isSoundTrigger()) {
2871 if (session == client->session()) {
2872 return desc->mIoHandle;
2873 }
2874 continue;
2875 }
2876 if (client->active() && client->appState() != APP_STATE_IDLE) {
2877 return desc->mIoHandle;
2878 }
2879 doClose = true;
2880 }
2881 if (doClose) {
2882 closeInput(desc->mIoHandle);
2883 } else {
2884 i++;
2885 }
2886 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002887 }
2888
Eric Laurentfe231122017-11-17 17:48:06 -08002889 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07002890
Eric Laurentfe231122017-11-17 17:48:06 -08002891 audio_config_t lConfig = AUDIO_CONFIG_INITIALIZER;
2892 lConfig.sample_rate = profileSamplingRate;
2893 lConfig.channel_mask = profileChannelMask;
2894 lConfig.format = profileFormat;
Eric Laurente3014102017-05-03 11:15:43 -07002895
François Gaffie11d30102018-11-02 16:09:09 +01002896 status_t status = inputDesc->open(&lConfig, device, halInputSource, profileFlags, &input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07002897
2898 // only accept input with the exact requested set of parameters
Eric Laurent599c7582015-12-07 18:05:55 -08002899 if (status != NO_ERROR || input == AUDIO_IO_HANDLE_NONE ||
Eric Laurentfe231122017-11-17 17:48:06 -08002900 (profileSamplingRate != lConfig.sample_rate) ||
2901 !audio_formats_match(profileFormat, lConfig.format) ||
2902 (profileChannelMask != lConfig.channel_mask)) {
2903 ALOGW("getInputForAttr() failed opening input: sampling rate %d"
Glenn Kasten49f36ba2017-12-06 13:02:02 -08002904 ", format %#x, channel mask %#x",
Eric Laurentfe231122017-11-17 17:48:06 -08002905 profileSamplingRate, profileFormat, profileChannelMask);
Eric Laurent599c7582015-12-07 18:05:55 -08002906 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfe231122017-11-17 17:48:06 -08002907 inputDesc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07002908 }
Eric Laurent599c7582015-12-07 18:05:55 -08002909 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07002910 }
2911
Eric Laurentc722f302014-12-10 11:21:49 -08002912 inputDesc->mPolicyMix = policyMix;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002913
Eric Laurent599c7582015-12-07 18:05:55 -08002914 addInput(input, inputDesc);
Eric Laurentb52c1522014-05-20 11:27:36 -07002915 mpClientInterface->onAudioPortListUpdate();
Paul McLean466dc8e2015-04-17 13:15:36 -06002916
Eric Laurent599c7582015-12-07 18:05:55 -08002917 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07002918}
2919
Eric Laurent4eb58f12018-12-07 16:41:02 -08002920status_t AudioPolicyManager::startInput(audio_port_handle_t portId)
Eric Laurentbb948092017-01-23 18:33:30 -08002921{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002922 ALOGV("%s portId %d", __FUNCTION__, portId);
2923
2924 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2925 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002926 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurentd52a28c2020-08-21 17:10:39 -07002927 return DEAD_OBJECT;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002928 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002929 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07002930 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002931 if (client->active()) {
2932 ALOGW("%s input %d client %d already started", __FUNCTION__, input, client->portId());
2933 return INVALID_OPERATION;
Eric Laurent4dc68062014-07-28 17:26:49 -07002934 }
2935
Eric Laurent8f42ea12018-08-08 09:08:25 -07002936 audio_session_t session = client->session();
2937
Eric Laurent4eb58f12018-12-07 16:41:02 -08002938 ALOGV("%s input:%d, session:%d)", __FUNCTION__, input, session);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002939
Eric Laurent4eb58f12018-12-07 16:41:02 -08002940 Vector<sp<AudioInputDescriptor>> activeInputs = mInputs.getActiveInputs();
Eric Laurent74708e72017-04-07 17:13:42 -07002941
Eric Laurent4eb58f12018-12-07 16:41:02 -08002942 status_t status = inputDesc->start();
2943 if (status != NO_ERROR) {
2944 return status;
Eric Laurent74708e72017-04-07 17:13:42 -07002945 }
Eric Laurente552edb2014-03-10 17:42:56 -07002946
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002947 // increment activity count before calling getNewInputDevice() below as only active sessions
Eric Laurent313d1e72016-01-29 09:56:57 -08002948 // are considered for device selection
Eric Laurent8f42ea12018-08-08 09:08:25 -07002949 inputDesc->setClientActive(client, true);
Eric Laurent313d1e72016-01-29 09:56:57 -08002950
Eric Laurent8f42ea12018-08-08 09:08:25 -07002951 // indicate active capture to sound trigger service if starting capture from a mic on
2952 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01002953 sp<DeviceDescriptor> device = getNewInputDevice(inputDesc);
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002954 if (device != nullptr) {
2955 status = setInputDevice(input, device, true /* force */);
2956 } else {
2957 ALOGW("%s no new input device can be found for descriptor %d",
2958 __FUNCTION__, inputDesc->getId());
2959 status = BAD_VALUE;
2960 }
Eric Laurente552edb2014-03-10 17:42:56 -07002961
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002962 if (status == NO_ERROR && inputDesc->activeCount() == 1) {
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002963 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002964 // if input maps to a dynamic policy with an activity listener, notify of state change
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002965 if ((policyMix != nullptr)
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002966 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
2967 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
Eric Laurent8f42ea12018-08-08 09:08:25 -07002968 MIX_STATE_MIXING);
Eric Laurent733ce942017-12-07 12:18:25 -08002969 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002970
François Gaffie11d30102018-11-02 16:09:09 +01002971 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
2972 if (primaryInputDevices.contains(device) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07002973 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 1) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07002974 mpClientInterface->setSoundTriggerCaptureState(true);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002975 }
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002976
Eric Laurent8f42ea12018-08-08 09:08:25 -07002977 // automatically enable the remote submix output when input is started if not
2978 // used by a policy mix of type MIX_TYPE_RECORDERS
2979 // For remote submix (a virtual device), we open only one input per capture request.
François Gaffie11d30102018-11-02 16:09:09 +01002980 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002981 String8 address = String8("");
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002982 if (policyMix == nullptr) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002983 address = String8("0");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002984 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
2985 address = policyMix->mDeviceAddress;
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002986 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07002987 if (address != "") {
2988 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2989 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002990 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurentc722f302014-12-10 11:21:49 -08002991 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07002992 }
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002993 } else if (status != NO_ERROR) {
2994 // Restore client activity state.
2995 inputDesc->setClientActive(client, false);
2996 inputDesc->stop();
Eric Laurente552edb2014-03-10 17:42:56 -07002997 }
2998
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002999 ALOGV("%s input %d source = %d status = %d exit",
3000 __FUNCTION__, input, client->source(), status);
Eric Laurente552edb2014-03-10 17:42:56 -07003001
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003002 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07003003}
3004
Eric Laurent8fc147b2018-07-22 19:13:55 -07003005status_t AudioPolicyManager::stopInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07003006{
Eric Laurent8fc147b2018-07-22 19:13:55 -07003007 ALOGV("%s portId %d", __FUNCTION__, portId);
3008
3009 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
3010 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003011 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07003012 return BAD_VALUE;
3013 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07003014 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07003015 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003016 if (!client->active()) {
3017 ALOGW("%s input %d client %d already stopped", __FUNCTION__, input, client->portId());
Eric Laurente552edb2014-03-10 17:42:56 -07003018 return INVALID_OPERATION;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003019 }
Carter Hsue6139d52021-07-08 10:30:20 +08003020 auto old_source = inputDesc->source();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003021 inputDesc->setClientActive(client, false);
Paul McLean466dc8e2015-04-17 13:15:36 -06003022
Eric Laurent8f42ea12018-08-08 09:08:25 -07003023 inputDesc->stop();
3024 if (inputDesc->isActive()) {
Carter Hsue6139d52021-07-08 10:30:20 +08003025 auto current_source = inputDesc->source();
3026 setInputDevice(input, getNewInputDevice(inputDesc),
3027 old_source != current_source /* force */);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003028 } else {
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003029 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003030 // if input maps to a dynamic policy with an activity listener, notify of state change
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003031 if ((policyMix != nullptr)
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003032 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
3033 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
Eric Laurent8f42ea12018-08-08 09:08:25 -07003034 MIX_STATE_IDLE);
Eric Laurent84332aa2016-01-28 22:19:18 +00003035 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07003036
3037 // automatically disable the remote submix output when input is stopped if not
3038 // used by a policy mix of type MIX_TYPE_RECORDERS
François Gaffie11d30102018-11-02 16:09:09 +01003039 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003040 String8 address = String8("");
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003041 if (policyMix == nullptr) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003042 address = String8("0");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003043 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
3044 address = policyMix->mDeviceAddress;
Eric Laurent8f42ea12018-08-08 09:08:25 -07003045 }
3046 if (address != "") {
3047 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
3048 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08003049 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003050 }
3051 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07003052 resetInputDevice(input);
3053
3054 // indicate inactive capture to sound trigger service if stopping capture from a mic on
3055 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01003056 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
3057 if (primaryInputDevices.contains(inputDesc->getDevice()) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07003058 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07003059 mpClientInterface->setSoundTriggerCaptureState(false);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003060 }
3061 inputDesc->clearPreemptedSessions();
Eric Laurente552edb2014-03-10 17:42:56 -07003062 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003063 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07003064}
3065
Eric Laurent8fc147b2018-07-22 19:13:55 -07003066void AudioPolicyManager::releaseInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07003067{
Eric Laurent8fc147b2018-07-22 19:13:55 -07003068 ALOGV("%s portId %d", __FUNCTION__, portId);
3069
3070 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
3071 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003072 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07003073 return;
3074 }
Andy Hung39efb7a2018-09-26 15:39:28 -07003075 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8fc147b2018-07-22 19:13:55 -07003076 audio_io_handle_t input = inputDesc->mIoHandle;
3077
Eric Laurent8f42ea12018-08-08 09:08:25 -07003078 ALOGV("%s %d", __FUNCTION__, input);
Paul McLean466dc8e2015-04-17 13:15:36 -06003079
Andy Hung39efb7a2018-09-26 15:39:28 -07003080 inputDesc->removeClient(portId);
Eric Laurent599c7582015-12-07 18:05:55 -08003081
Andy Hung39efb7a2018-09-26 15:39:28 -07003082 if (inputDesc->getClientCount() > 0) {
3083 ALOGV("%s(%d) %zu clients remaining", __func__, portId, inputDesc->getClientCount());
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003084 return;
3085 }
3086
Eric Laurent05b90f82014-08-27 15:32:29 -07003087 closeInput(input);
Eric Laurentb52c1522014-05-20 11:27:36 -07003088 mpClientInterface->onAudioPortListUpdate();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003089 ALOGV("%s exit", __FUNCTION__);
Eric Laurente552edb2014-03-10 17:42:56 -07003090}
3091
Eric Laurent8f42ea12018-08-08 09:08:25 -07003092void AudioPolicyManager::closeActiveClients(const sp<AudioInputDescriptor>& input)
Eric Laurent8fc147b2018-07-22 19:13:55 -07003093{
Eric Laurent8f42ea12018-08-08 09:08:25 -07003094 RecordClientVector clients = input->clientsList(true);
Eric Laurent8fc147b2018-07-22 19:13:55 -07003095
3096 for (const auto& client : clients) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003097 closeClient(client->portId());
Eric Laurent8fc147b2018-07-22 19:13:55 -07003098 }
3099}
3100
Eric Laurent8f42ea12018-08-08 09:08:25 -07003101void AudioPolicyManager::closeClient(audio_port_handle_t portId)
3102{
3103 stopInput(portId);
3104 releaseInput(portId);
3105}
Eric Laurent8fc147b2018-07-22 19:13:55 -07003106
Eric Laurent0dd51852019-04-19 18:18:58 -07003107void AudioPolicyManager::checkCloseInputs() {
3108 // After connecting or disconnecting an input device, close input if:
3109 // - it has no client (was just opened to check profile) OR
3110 // - none of its supported devices are connected anymore OR
3111 // - one of its clients cannot be routed to one of its supported
3112 // devices anymore. Otherwise update device selection
3113 std::vector<audio_io_handle_t> inputsToClose;
3114 for (size_t i = 0; i < mInputs.size(); i++) {
3115 const sp<AudioInputDescriptor> input = mInputs.valueAt(i);
3116 if (input->clientsList().size() == 0
Eric Laurent85732f42020-03-19 11:31:10 -07003117 || !mAvailableInputDevices.containsAtLeastOne(input->supportedDevices())) {
Eric Laurent0dd51852019-04-19 18:18:58 -07003118 inputsToClose.push_back(mInputs.keyAt(i));
3119 } else {
3120 bool close = false;
3121 for (const auto& client : input->clientsList()) {
3122 sp<DeviceDescriptor> device =
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02003123 mEngine->getInputDeviceForAttributes(client->attributes(), client->uid(),
3124 client->session());
Eric Laurent0dd51852019-04-19 18:18:58 -07003125 if (!input->supportedDevices().contains(device)) {
3126 close = true;
3127 break;
3128 }
3129 }
3130 if (close) {
3131 inputsToClose.push_back(mInputs.keyAt(i));
3132 } else {
3133 setInputDevice(input->mIoHandle, getNewInputDevice(input));
3134 }
3135 }
3136 }
3137
3138 for (const audio_io_handle_t handle : inputsToClose) {
3139 ALOGV("%s closing input %d", __func__, handle);
3140 closeInput(handle);
Eric Laurent05b90f82014-08-27 15:32:29 -07003141 }
Eric Laurentd4692962014-05-05 18:13:44 -07003142}
3143
François Gaffie251c7f02018-11-07 10:41:08 +01003144void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream, int indexMin, int indexMax)
Eric Laurente552edb2014-03-10 17:42:56 -07003145{
3146 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08003147 if (indexMin < 0 || indexMax < 0) {
3148 ALOGE("%s for stream %d: invalid min %d or max %d", __func__, stream , indexMin, indexMax);
3149 return;
3150 }
Eric Laurentf5aa58d2019-02-22 18:20:11 -08003151 getVolumeCurves(stream).initVolume(indexMin, indexMax);
Eric Laurent28d09f02016-03-08 10:43:05 -08003152
3153 // initialize other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08003154 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
3155 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08003156 continue;
3157 }
Eric Laurentf5aa58d2019-02-22 18:20:11 -08003158 getVolumeCurves((audio_stream_type_t)curStream).initVolume(indexMin, indexMax);
Eric Laurent223fd5c2014-11-11 13:43:36 -08003159 }
Eric Laurente552edb2014-03-10 17:42:56 -07003160}
3161
Eric Laurente0720872014-03-11 09:30:41 -07003162status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
François Gaffie53615e22015-03-19 09:24:12 +01003163 int index,
3164 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07003165{
François Gaffieaaac0fd2018-11-22 17:56:39 +01003166 auto attributes = mEngine->getAttributesForStreamType(stream);
Eric Laurent242a9f82020-03-23 15:57:04 -07003167 if (attributes == AUDIO_ATTRIBUTES_INITIALIZER) {
3168 ALOGW("%s: no group for stream %s, bailing out", __func__, toString(stream).c_str());
3169 return NO_ERROR;
3170 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01003171 ALOGV("%s: stream %s attributes=%s", __func__,
3172 toString(stream).c_str(), toString(attributes).c_str());
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003173 return setVolumeIndexForAttributes(attributes, index, device);
Eric Laurente552edb2014-03-10 17:42:56 -07003174}
3175
Eric Laurente0720872014-03-11 09:30:41 -07003176status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
François Gaffieaaac0fd2018-11-22 17:56:39 +01003177 int *index,
3178 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07003179{
François Gaffiec005e562018-11-06 15:04:49 +01003180 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
3181 // stream by the engine.
jiabin9a3361e2019-10-01 09:38:30 -07003182 DeviceTypeSet deviceTypes = {device};
Eric Laurent5a2b6292016-04-14 18:05:57 -07003183 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
jiabin9a3361e2019-10-01 09:38:30 -07003184 deviceTypes = mEngine->getOutputDevicesForStream(
3185 stream, true /*fromCache*/).types();
Eric Laurente552edb2014-03-10 17:42:56 -07003186 }
jiabin9a3361e2019-10-01 09:38:30 -07003187 return getVolumeIndex(getVolumeCurves(stream), *index, deviceTypes);
Eric Laurente552edb2014-03-10 17:42:56 -07003188}
3189
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003190status_t AudioPolicyManager::setVolumeIndexForAttributes(const audio_attributes_t &attributes,
François Gaffiecfe17322018-11-07 13:41:29 +01003191 int index,
3192 audio_devices_t device)
3193{
3194 // Get Volume group matching the Audio Attributes
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003195 auto group = mEngine->getVolumeGroupForAttributes(attributes);
3196 if (group == VOLUME_GROUP_NONE) {
3197 ALOGD("%s: no group matching with %s", __FUNCTION__, toString(attributes).c_str());
François Gaffiecfe17322018-11-07 13:41:29 +01003198 return BAD_VALUE;
3199 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003200 ALOGV("%s: group %d matching with %s", __FUNCTION__, group, toString(attributes).c_str());
François Gaffiecfe17322018-11-07 13:41:29 +01003201 status_t status = NO_ERROR;
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003202 IVolumeCurves &curves = getVolumeCurves(attributes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01003203 VolumeSource vs = toVolumeSource(group);
Eric Laurentf9cccec2022-11-16 19:12:00 +01003204 // AUDIO_STREAM_BLUETOOTH_SCO is only used for volume control so we remap
3205 // to AUDIO_STREAM_VOICE_CALL to match with relevant playback activity
3206 VolumeSource activityVs = (vs == toVolumeSource(AUDIO_STREAM_BLUETOOTH_SCO, false)) ?
3207 toVolumeSource(AUDIO_STREAM_VOICE_CALL, false) : vs;
François Gaffieaaac0fd2018-11-22 17:56:39 +01003208 product_strategy_t strategy = mEngine->getProductStrategyForAttributes(attributes);
3209
3210 status = setVolumeCurveIndex(index, device, curves);
3211 if (status != NO_ERROR) {
3212 ALOGE("%s failed to set curve index for group %d device 0x%X", __func__, group, device);
3213 return status;
3214 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003215
jiabin9a3361e2019-10-01 09:38:30 -07003216 DeviceTypeSet curSrcDevices;
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003217 auto curCurvAttrs = curves.getAttributes();
3218 if (!curCurvAttrs.empty() && curCurvAttrs.front() != defaultAttr) {
3219 auto attr = curCurvAttrs.front();
jiabin9a3361e2019-10-01 09:38:30 -07003220 curSrcDevices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false).types();
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003221 } else if (!curves.getStreamTypes().empty()) {
3222 auto stream = curves.getStreamTypes().front();
jiabin9a3361e2019-10-01 09:38:30 -07003223 curSrcDevices = mEngine->getOutputDevicesForStream(stream, false).types();
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003224 } else {
3225 ALOGE("%s: Invalid src %d: no valid attributes nor stream",__func__, vs);
3226 return BAD_VALUE;
3227 }
jiabin9a3361e2019-10-01 09:38:30 -07003228 audio_devices_t curSrcDevice = Volume::getDeviceForVolume(curSrcDevices);
3229 resetDeviceTypes(curSrcDevices, curSrcDevice);
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003230
François Gaffiecfe17322018-11-07 13:41:29 +01003231 // update volume on all outputs and streams matching the following:
3232 // - The requested stream (or a stream matching for volume control) is active on the output
3233 // - The device (or devices) selected by the engine for this stream includes
3234 // the requested device
3235 // - For non default requested device, currently selected device on the output is either the
3236 // requested device or one of the devices selected by the engine for this stream
3237 // - For default requested device (AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME), apply volume only if
3238 // no specific device volume value exists for currently selected device.
François Gaffieaaac0fd2018-11-22 17:56:39 +01003239 for (size_t i = 0; i < mOutputs.size(); i++) {
3240 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
jiabin9a3361e2019-10-01 09:38:30 -07003241 DeviceTypeSet curDevices = desc->devices().types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01003242
jiabin9a3361e2019-10-01 09:38:30 -07003243 if (curDevices.erase(AUDIO_DEVICE_OUT_SPEAKER_SAFE)) {
3244 curDevices.insert(AUDIO_DEVICE_OUT_SPEAKER);
Robert Lee5e66e792019-04-03 18:37:15 +08003245 }
Eric Laurentf9cccec2022-11-16 19:12:00 +01003246
3247 if (!(desc->isActive(activityVs) || isInCallOrScreening())) {
François Gaffieed91f582020-01-31 10:35:37 +01003248 continue;
3249 }
3250 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME &&
3251 curDevices.find(device) == curDevices.end()) {
3252 continue;
3253 }
3254 bool applyVolume = false;
3255 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
3256 curSrcDevices.insert(device);
3257 applyVolume = (curSrcDevices.find(
3258 Volume::getDeviceForVolume(curDevices)) != curSrcDevices.end());
3259 } else {
3260 applyVolume = !curves.hasVolumeIndexForDevice(curSrcDevice);
3261 }
3262 if (!applyVolume) {
3263 continue; // next output
3264 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01003265 // Inter / intra volume group priority management: Loop on strategies arranged by priority
3266 // If a higher priority strategy is active, and the output is routed to a device with a
3267 // HW Gain management, do not change the volume
François Gaffieaaac0fd2018-11-22 17:56:39 +01003268 if (desc->useHwGain()) {
François Gaffieed91f582020-01-31 10:35:37 +01003269 applyVolume = false;
Francois Gaffie593634d2021-06-22 13:31:31 +02003270 // If the volume source is active with higher priority source, ensure at least Sw Muted
3271 desc->setSwMute((index == 0), vs, curves.getStreamTypes(), curDevices, 0 /*delayMs*/);
François Gaffieaaac0fd2018-11-22 17:56:39 +01003272 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
3273 auto activeClients = desc->clientsList(true /*activeOnly*/, productStrategy,
3274 false /*preferredDevice*/);
3275 if (activeClients.empty()) {
3276 continue;
3277 }
3278 bool isPreempted = false;
3279 bool isHigherPriority = productStrategy < strategy;
3280 for (const auto &client : activeClients) {
Eric Laurentf9cccec2022-11-16 19:12:00 +01003281 if (isHigherPriority && (client->volumeSource() != activityVs)) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01003282 ALOGV("%s: Strategy=%d (\nrequester:\n"
3283 " group %d, volumeGroup=%d attributes=%s)\n"
3284 " higher priority source active:\n"
3285 " volumeGroup=%d attributes=%s) \n"
3286 " on output %zu, bailing out", __func__, productStrategy,
3287 group, group, toString(attributes).c_str(),
3288 client->volumeSource(), toString(client->attributes()).c_str(), i);
3289 applyVolume = false;
3290 isPreempted = true;
3291 break;
3292 }
3293 // However, continue for loop to ensure no higher prio clients running on output
Eric Laurentf9cccec2022-11-16 19:12:00 +01003294 if (client->volumeSource() == activityVs) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01003295 applyVolume = true;
3296 }
3297 }
3298 if (isPreempted || applyVolume) {
3299 break;
3300 }
3301 }
3302 if (!applyVolume) {
3303 continue; // next output
3304 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01003305 }
François Gaffieed91f582020-01-31 10:35:37 +01003306 //FIXME: workaround for truncated touch sounds
3307 // delayed volume change for system stream to be removed when the problem is
3308 // handled by system UI
3309 status_t volStatus = checkAndSetVolume(
3310 curves, vs, index, desc, curDevices,
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003311 ((vs == toVolumeSource(AUDIO_STREAM_SYSTEM, false))?
François Gaffieed91f582020-01-31 10:35:37 +01003312 TOUCH_SOUND_FIXED_DELAY_MS : 0));
3313 if (volStatus != NO_ERROR) {
3314 status = volStatus;
François Gaffieaaac0fd2018-11-22 17:56:39 +01003315 }
3316 }
François Gaffiecfe17322018-11-07 13:41:29 +01003317 mpClientInterface->onAudioVolumeGroupChanged(group, 0 /*flags*/);
3318 return status;
3319}
3320
François Gaffieaaac0fd2018-11-22 17:56:39 +01003321status_t AudioPolicyManager::setVolumeCurveIndex(int index,
François Gaffiecfe17322018-11-07 13:41:29 +01003322 audio_devices_t device,
3323 IVolumeCurves &volumeCurves)
3324{
3325 // VOICE_CALL stream has minVolumeIndex > 0 but can be muted directly by an
3326 // app that has MODIFY_PHONE_STATE permission.
François Gaffieaaac0fd2018-11-22 17:56:39 +01003327 bool hasVoice = hasVoiceStream(volumeCurves.getStreamTypes());
3328 if (((index < volumeCurves.getVolumeIndexMin()) && !(hasVoice && index == 0)) ||
François Gaffiecfe17322018-11-07 13:41:29 +01003329 (index > volumeCurves.getVolumeIndexMax())) {
3330 ALOGD("%s: wrong index %d min=%d max=%d", __FUNCTION__, index,
3331 volumeCurves.getVolumeIndexMin(), volumeCurves.getVolumeIndexMax());
3332 return BAD_VALUE;
3333 }
3334 if (!audio_is_output_device(device)) {
3335 return BAD_VALUE;
3336 }
3337
3338 // Force max volume if stream cannot be muted
3339 if (!volumeCurves.canBeMuted()) index = volumeCurves.getVolumeIndexMax();
3340
François Gaffieaaac0fd2018-11-22 17:56:39 +01003341 ALOGV("%s device %08x, index %d", __FUNCTION__ , device, index);
François Gaffiecfe17322018-11-07 13:41:29 +01003342 volumeCurves.addCurrentVolumeIndex(device, index);
3343 return NO_ERROR;
3344}
3345
3346status_t AudioPolicyManager::getVolumeIndexForAttributes(const audio_attributes_t &attr,
3347 int &index,
3348 audio_devices_t device)
3349{
3350 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
3351 // stream by the engine.
jiabin9a3361e2019-10-01 09:38:30 -07003352 DeviceTypeSet deviceTypes = {device};
François Gaffiecfe17322018-11-07 13:41:29 +01003353 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
Mikhail Naganovbb990f22022-06-15 00:46:43 +00003354 deviceTypes = mEngine->getOutputDevicesForAttributes(
jiabin9a3361e2019-10-01 09:38:30 -07003355 attr, nullptr, true /*fromCache*/).types();
François Gaffiecfe17322018-11-07 13:41:29 +01003356 }
jiabin9a3361e2019-10-01 09:38:30 -07003357 return getVolumeIndex(getVolumeCurves(attr), index, deviceTypes);
François Gaffiecfe17322018-11-07 13:41:29 +01003358}
3359
3360status_t AudioPolicyManager::getVolumeIndex(const IVolumeCurves &curves,
3361 int &index,
jiabin9a3361e2019-10-01 09:38:30 -07003362 const DeviceTypeSet& deviceTypes) const
François Gaffiecfe17322018-11-07 13:41:29 +01003363{
Mikhail Naganovbb990f22022-06-15 00:46:43 +00003364 if (!isSingleDeviceType(deviceTypes, audio_is_output_device)) {
François Gaffiecfe17322018-11-07 13:41:29 +01003365 return BAD_VALUE;
3366 }
jiabin9a3361e2019-10-01 09:38:30 -07003367 index = curves.getVolumeIndex(deviceTypes);
3368 ALOGV("%s: device %s index %d", __FUNCTION__, dumpDeviceTypes(deviceTypes).c_str(), index);
François Gaffiecfe17322018-11-07 13:41:29 +01003369 return NO_ERROR;
3370}
3371
3372status_t AudioPolicyManager::getMinVolumeIndexForAttributes(const audio_attributes_t &attr,
3373 int &index)
3374{
3375 index = getVolumeCurves(attr).getVolumeIndexMin();
3376 return NO_ERROR;
3377}
3378
3379status_t AudioPolicyManager::getMaxVolumeIndexForAttributes(const audio_attributes_t &attr,
3380 int &index)
3381{
3382 index = getVolumeCurves(attr).getVolumeIndexMax();
3383 return NO_ERROR;
3384}
3385
Eric Laurent36829f92017-04-07 19:04:42 -07003386audio_io_handle_t AudioPolicyManager::selectOutputForMusicEffects()
Eric Laurente552edb2014-03-10 17:42:56 -07003387{
3388 // select one output among several suitable for global effects.
3389 // The priority is as follows:
3390 // 1: An offloaded output. If the effect ends up not being offloadable,
3391 // AudioFlinger will invalidate the track and the offloaded output
3392 // will be closed causing the effect to be moved to a PCM output.
3393 // 2: A deep buffer output
Eric Laurent36829f92017-04-07 19:04:42 -07003394 // 3: The primary output
3395 // 4: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07003396
François Gaffiec005e562018-11-06 15:04:49 +01003397 DeviceVector devices = mEngine->getOutputDevicesForAttributes(
3398 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
François Gaffie11d30102018-11-02 16:09:09 +01003399 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07003400
Eric Laurent36829f92017-04-07 19:04:42 -07003401 if (outputs.size() == 0) {
3402 return AUDIO_IO_HANDLE_NONE;
3403 }
Eric Laurente552edb2014-03-10 17:42:56 -07003404
Eric Laurent36829f92017-04-07 19:04:42 -07003405 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
3406 bool activeOnly = true;
3407
3408 while (output == AUDIO_IO_HANDLE_NONE) {
3409 audio_io_handle_t outputOffloaded = AUDIO_IO_HANDLE_NONE;
3410 audio_io_handle_t outputDeepBuffer = AUDIO_IO_HANDLE_NONE;
3411 audio_io_handle_t outputPrimary = AUDIO_IO_HANDLE_NONE;
3412
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003413 for (audio_io_handle_t output : outputs) {
3414 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
Eric Laurent83d17c22019-04-02 17:10:01 -07003415 if (activeOnly && !desc->isActive(toVolumeSource(AUDIO_STREAM_MUSIC))) {
Eric Laurent36829f92017-04-07 19:04:42 -07003416 continue;
3417 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003418 ALOGV("selectOutputForMusicEffects activeOnly %d output %d flags 0x%08x",
3419 activeOnly, output, desc->mFlags);
Eric Laurent36829f92017-04-07 19:04:42 -07003420 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003421 outputOffloaded = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003422 }
3423 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003424 outputDeepBuffer = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003425 }
3426 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003427 outputPrimary = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003428 }
3429 }
3430 if (outputOffloaded != AUDIO_IO_HANDLE_NONE) {
3431 output = outputOffloaded;
3432 } else if (outputDeepBuffer != AUDIO_IO_HANDLE_NONE) {
3433 output = outputDeepBuffer;
3434 } else if (outputPrimary != AUDIO_IO_HANDLE_NONE) {
3435 output = outputPrimary;
3436 } else {
3437 output = outputs[0];
3438 }
3439 activeOnly = false;
3440 }
3441
3442 if (output != mMusicEffectOutput) {
Eric Laurent6c796322019-04-09 14:13:17 -07003443 mEffects.moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output);
Eric Laurent36829f92017-04-07 19:04:42 -07003444 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output);
3445 mMusicEffectOutput = output;
3446 }
3447
3448 ALOGV("selectOutputForMusicEffects selected output %d", output);
Eric Laurente552edb2014-03-10 17:42:56 -07003449 return output;
3450}
3451
Eric Laurent36829f92017-04-07 19:04:42 -07003452audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc __unused)
3453{
3454 return selectOutputForMusicEffects();
3455}
3456
Eric Laurente0720872014-03-11 09:30:41 -07003457status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07003458 audio_io_handle_t io,
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08003459 product_strategy_t strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07003460 int session,
3461 int id)
3462{
Eric Laurentb82e6b72019-11-22 17:25:04 -08003463 if (session != AUDIO_SESSION_DEVICE) {
3464 ssize_t index = mOutputs.indexOfKey(io);
Eric Laurente552edb2014-03-10 17:42:56 -07003465 if (index < 0) {
Eric Laurentb82e6b72019-11-22 17:25:04 -08003466 index = mInputs.indexOfKey(io);
3467 if (index < 0) {
3468 ALOGW("registerEffect() unknown io %d", io);
3469 return INVALID_OPERATION;
3470 }
Eric Laurente552edb2014-03-10 17:42:56 -07003471 }
3472 }
Eric Laurentbf8f69f2022-03-25 17:48:38 +01003473 bool isMusicEffect = (session != AUDIO_SESSION_OUTPUT_STAGE)
3474 && ((strategy == streamToStrategy(AUDIO_STREAM_MUSIC)
3475 || strategy == PRODUCT_STRATEGY_NONE));
3476 return mEffects.registerEffect(desc, io, session, id, isMusicEffect);
Eric Laurente552edb2014-03-10 17:42:56 -07003477}
3478
Eric Laurentc241b0d2018-11-28 09:08:49 -08003479status_t AudioPolicyManager::unregisterEffect(int id)
3480{
3481 if (mEffects.getEffect(id) == nullptr) {
3482 return INVALID_OPERATION;
3483 }
Eric Laurentc241b0d2018-11-28 09:08:49 -08003484 if (mEffects.isEffectEnabled(id)) {
3485 ALOGW("%s effect %d enabled", __FUNCTION__, id);
3486 setEffectEnabled(id, false);
3487 }
3488 return mEffects.unregisterEffect(id);
3489}
3490
3491status_t AudioPolicyManager::setEffectEnabled(int id, bool enabled)
3492{
3493 sp<EffectDescriptor> effect = mEffects.getEffect(id);
3494 if (effect == nullptr) {
3495 return INVALID_OPERATION;
3496 }
3497
3498 status_t status = mEffects.setEffectEnabled(id, enabled);
3499 if (status == NO_ERROR) {
3500 mInputs.trackEffectEnabled(effect, enabled);
3501 }
3502 return status;
3503}
3504
Eric Laurent6c796322019-04-09 14:13:17 -07003505
3506status_t AudioPolicyManager::moveEffectsToIo(const std::vector<int>& ids, audio_io_handle_t io)
3507{
3508 mEffects.moveEffects(ids, io);
3509 return NO_ERROR;
3510}
3511
Eric Laurentc75307b2015-03-17 15:29:32 -07003512bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
3513{
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003514 auto vs = toVolumeSource(stream, false);
3515 return vs != VOLUME_SOURCE_NONE ? mOutputs.isActive(vs, inPastMs) : false;
Eric Laurentc75307b2015-03-17 15:29:32 -07003516}
3517
3518bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream, uint32_t inPastMs) const
3519{
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003520 auto vs = toVolumeSource(stream, false);
3521 return vs != VOLUME_SOURCE_NONE ? mOutputs.isActiveRemotely(vs, inPastMs) : false;
Eric Laurentc75307b2015-03-17 15:29:32 -07003522}
3523
Eric Laurente0720872014-03-11 09:30:41 -07003524bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07003525{
3526 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003527 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08003528 if (inputDescriptor->isSourceActive(source)) {
Eric Laurente552edb2014-03-10 17:42:56 -07003529 return true;
3530 }
3531 }
3532 return false;
3533}
3534
Eric Laurent275e8e92014-11-30 15:14:47 -08003535// Register a list of custom mixes with their attributes and format.
3536// When a mix is registered, corresponding input and output profiles are
3537// added to the remote submix hw module. The profile contains only the
3538// parameters (sampling rate, format...) specified by the mix.
3539// The corresponding input remote submix device is also connected.
3540//
3541// When a remote submix device is connected, the address is checked to select the
3542// appropriate profile and the corresponding input or output stream is opened.
3543//
3544// When capture starts, getInputForAttr() will:
3545// - 1 look for a mix matching the address passed in attribtutes tags if any
3546// - 2 if none found, getDeviceForInputSource() will:
3547// - 2.1 look for a mix matching the attributes source
3548// - 2.2 if none found, default to device selection by policy rules
3549// At this time, the corresponding output remote submix device is also connected
3550// and active playback use cases can be transferred to this mix if needed when reconnecting
3551// after AudioTracks are invalidated
3552//
3553// When playback starts, getOutputForAttr() will:
3554// - 1 look for a mix matching the address passed in attribtutes tags if any
3555// - 2 if none found, look for a mix matching the attributes usage
3556// - 3 if none found, default to device and output selection by policy rules.
3557
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003558status_t AudioPolicyManager::registerPolicyMixes(const Vector<AudioMix>& mixes)
Eric Laurent275e8e92014-11-30 15:14:47 -08003559{
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003560 ALOGV("registerPolicyMixes() %zu mix(es)", mixes.size());
3561 status_t res = NO_ERROR;
Eric Laurentc209fe42020-06-05 18:11:23 -07003562 bool checkOutputs = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003563 sp<HwModule> rSubmixModule;
3564 // examine each mix's route type
3565 for (size_t i = 0; i < mixes.size(); i++) {
Eric Laurent97ac8712018-07-27 18:59:02 -07003566 AudioMix mix = mixes[i];
Kevin Rocard153f92d2018-12-18 18:33:28 -08003567 // Only capture of playback is allowed in LOOP_BACK & RENDER mode
3568 if (is_mix_loopback_render(mix.mRouteFlags) && mix.mMixType != MIX_TYPE_PLAYERS) {
3569 ALOGE("Unsupported Policy Mix %zu of %zu: "
3570 "Only capture of playback is allowed in LOOP_BACK & RENDER mode",
3571 i, mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003572 res = INVALID_OPERATION;
Eric Laurent275e8e92014-11-30 15:14:47 -08003573 break;
3574 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08003575 // LOOP_BACK and LOOP_BACK | RENDER have the same remote submix backend and are handled
3576 // in the same way.
Eric Laurent97ac8712018-07-27 18:59:02 -07003577 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003578 ALOGV("registerPolicyMixes() mix %zu of %zu is LOOP_BACK %d", i, mixes.size(),
3579 mix.mRouteFlags);
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003580 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003581 rSubmixModule = mHwModules.getModuleFromName(
3582 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
3583 if (rSubmixModule == 0) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003584 ALOGE("Unable to find audio module for submix, aborting mix %zu registration",
Mikhail Naganovd4120142017-12-06 15:49:22 -08003585 i);
3586 res = INVALID_OPERATION;
3587 break;
3588 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003589 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003590
Eric Laurent97ac8712018-07-27 18:59:02 -07003591 String8 address = mix.mDeviceAddress;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003592 audio_devices_t deviceTypeToMakeAvailable;
Eric Laurent97ac8712018-07-27 18:59:02 -07003593 if (mix.mMixType == MIX_TYPE_PLAYERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07003594 mix.mDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003595 deviceTypeToMakeAvailable = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
3596 } else {
3597 mix.mDeviceType = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
3598 deviceTypeToMakeAvailable = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Eric Laurent97ac8712018-07-27 18:59:02 -07003599 }
François Gaffie036e1e92015-03-19 10:16:24 +01003600
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003601 if (mPolicyMixes.registerMix(mix, 0 /*output desc*/) != NO_ERROR) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003602 ALOGE("Error registering mix %zu for address %s", i, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003603 res = INVALID_OPERATION;
3604 break;
3605 }
Eric Laurent97ac8712018-07-27 18:59:02 -07003606 audio_config_t outputConfig = mix.mFormat;
3607 audio_config_t inputConfig = mix.mFormat;
Eric Laurentc529cf62020-04-17 18:19:10 -07003608 // NOTE: audio flinger mixer does not support mono output: configure remote submix HAL
3609 // in stereo and let audio flinger do the channel conversion if needed.
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003610 outputConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
3611 inputConfig.channel_mask = AUDIO_CHANNEL_IN_STEREO;
jiabin5740f082019-08-19 15:08:30 -07003612 rSubmixModule->addOutputProfile(address.c_str(), &outputConfig,
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003613 AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address);
jiabin5740f082019-08-19 15:08:30 -07003614 rSubmixModule->addInputProfile(address.c_str(), &inputConfig,
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003615 AUDIO_DEVICE_IN_REMOTE_SUBMIX, address);
François Gaffie036e1e92015-03-19 10:16:24 +01003616
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003617 if ((res = setDeviceConnectionStateInt(deviceTypeToMakeAvailable,
jiabinc1de2df2019-05-07 14:26:40 -07003618 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
3619 address.string(), "remote-submix", AUDIO_FORMAT_DEFAULT)) != NO_ERROR) {
3620 ALOGE("Failed to set remote submix device available, type %u, address %s",
3621 mix.mDeviceType, address.string());
3622 break;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003623 }
Eric Laurent97ac8712018-07-27 18:59:02 -07003624 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
3625 String8 address = mix.mDeviceAddress;
Eric Laurent2c80be02019-01-23 18:06:37 -08003626 audio_devices_t type = mix.mDeviceType;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003627 ALOGV(" registerPolicyMixes() mix %zu of %zu is RENDER, dev=0x%X addr=%s",
Eric Laurent2c80be02019-01-23 18:06:37 -08003628 i, mixes.size(), type, address.string());
3629
3630 sp<DeviceDescriptor> device = mHwModules.getDeviceDescriptor(
3631 mix.mDeviceType, mix.mDeviceAddress,
3632 String8(), AUDIO_FORMAT_DEFAULT);
3633 if (device == nullptr) {
3634 res = INVALID_OPERATION;
3635 break;
3636 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003637
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003638 bool foundOutput = false;
Eric Laurentc529cf62020-04-17 18:19:10 -07003639 // First try to find an already opened output supporting the device
3640 for (size_t j = 0 ; j < mOutputs.size() && !foundOutput && res == NO_ERROR; j++) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003641 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurent2c80be02019-01-23 18:06:37 -08003642
Eric Laurentc529cf62020-04-17 18:19:10 -07003643 if (!desc->isDuplicated() && desc->supportedDevices().contains(device)) {
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003644 if (mPolicyMixes.registerMix(mix, desc) != NO_ERROR) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003645 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
3646 address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003647 res = INVALID_OPERATION;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003648 } else {
3649 foundOutput = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003650 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003651 }
3652 }
Eric Laurentc529cf62020-04-17 18:19:10 -07003653 // If no output found, try to find a direct output profile supporting the device
3654 for (size_t i = 0; i < mHwModules.size() && !foundOutput && res == NO_ERROR; i++) {
3655 sp<HwModule> module = mHwModules[i];
3656 for (size_t j = 0;
3657 j < module->getOutputProfiles().size() && !foundOutput && res == NO_ERROR;
3658 j++) {
3659 sp<IOProfile> profile = module->getOutputProfiles()[j];
3660 if (profile->isDirectOutput() && profile->supportsDevice(device)) {
3661 if (mPolicyMixes.registerMix(mix, nullptr) != NO_ERROR) {
3662 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
3663 address.string());
3664 res = INVALID_OPERATION;
3665 } else {
3666 foundOutput = true;
3667 }
3668 }
3669 }
3670 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003671 if (res != NO_ERROR) {
3672 ALOGE(" Error registering mix %zu for device 0x%X addr %s",
Eric Laurent2c80be02019-01-23 18:06:37 -08003673 i, type, address.string());
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003674 res = INVALID_OPERATION;
3675 break;
3676 } else if (!foundOutput) {
3677 ALOGE(" Output not found for mix %zu for device 0x%X addr %s",
Eric Laurent2c80be02019-01-23 18:06:37 -08003678 i, type, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003679 res = INVALID_OPERATION;
3680 break;
Eric Laurentc209fe42020-06-05 18:11:23 -07003681 } else {
3682 checkOutputs = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003683 }
Eric Laurentc722f302014-12-10 11:21:49 -08003684 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003685 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003686 if (res != NO_ERROR) {
3687 unregisterPolicyMixes(mixes);
Eric Laurentc209fe42020-06-05 18:11:23 -07003688 } else if (checkOutputs) {
3689 checkForDeviceAndOutputChanges();
3690 updateCallAndOutputRouting();
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003691 }
3692 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08003693}
3694
3695status_t AudioPolicyManager::unregisterPolicyMixes(Vector<AudioMix> mixes)
3696{
Eric Laurent7b279bb2015-12-14 10:18:23 -08003697 ALOGV("unregisterPolicyMixes() num mixes %zu", mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003698 status_t res = NO_ERROR;
Eric Laurentc209fe42020-06-05 18:11:23 -07003699 bool checkOutputs = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003700 sp<HwModule> rSubmixModule;
3701 // examine each mix's route type
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003702 for (const auto& mix : mixes) {
3703 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie036e1e92015-03-19 10:16:24 +01003704
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003705 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003706 rSubmixModule = mHwModules.getModuleFromName(
3707 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
3708 if (rSubmixModule == 0) {
3709 res = INVALID_OPERATION;
3710 continue;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003711 }
3712 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003713
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003714 String8 address = mix.mDeviceAddress;
Eric Laurent275e8e92014-11-30 15:14:47 -08003715
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003716 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003717 res = INVALID_OPERATION;
3718 continue;
3719 }
3720
Kevin Rocard04ed0462019-05-02 17:53:24 -07003721 for (auto device : {AUDIO_DEVICE_IN_REMOTE_SUBMIX, AUDIO_DEVICE_OUT_REMOTE_SUBMIX}) {
3722 if (getDeviceConnectionState(device, address.string()) ==
3723 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
3724 res = setDeviceConnectionStateInt(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
3725 address.string(), "remote-submix",
3726 AUDIO_FORMAT_DEFAULT);
3727 if (res != OK) {
3728 ALOGE("Error making RemoteSubmix device unavailable for mix "
3729 "with type %d, address %s", device, address.string());
3730 }
3731 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003732 }
jiabin5740f082019-08-19 15:08:30 -07003733 rSubmixModule->removeOutputProfile(address.c_str());
3734 rSubmixModule->removeInputProfile(address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003735
Kevin Rocard153f92d2018-12-18 18:33:28 -08003736 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003737 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003738 res = INVALID_OPERATION;
3739 continue;
Eric Laurentc209fe42020-06-05 18:11:23 -07003740 } else {
3741 checkOutputs = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003742 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003743 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003744 }
Eric Laurentc209fe42020-06-05 18:11:23 -07003745 if (res == NO_ERROR && checkOutputs) {
3746 checkForDeviceAndOutputChanges();
3747 updateCallAndOutputRouting();
3748 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003749 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08003750}
3751
Mikhail Naganov100f0122018-11-29 11:22:16 -08003752void AudioPolicyManager::dumpManualSurroundFormats(String8 *dst) const
3753{
3754 size_t i = 0;
3755 constexpr size_t audioFormatPrefixLen = sizeof("AUDIO_FORMAT_");
3756 for (const auto& fmt : mManualSurroundFormats) {
3757 if (i++ != 0) dst->append(", ");
3758 std::string sfmt;
3759 FormatConverter::toString(fmt, sfmt);
3760 dst->append(sfmt.size() >= audioFormatPrefixLen ?
3761 sfmt.c_str() + audioFormatPrefixLen - 1 : sfmt.c_str());
3762 }
3763}
3764
Eric Laurentc529cf62020-04-17 18:19:10 -07003765// Returns true if all devices types match the predicate and are supported by one HW module
3766bool AudioPolicyManager::areAllDevicesSupported(
jiabin6a02d532020-08-07 11:56:38 -07003767 const AudioDeviceTypeAddrVector& devices,
Eric Laurentc529cf62020-04-17 18:19:10 -07003768 std::function<bool(audio_devices_t)> predicate,
Eric Laurent78fedbf2023-03-09 14:40:44 +01003769 const char *context,
3770 bool matchAddress) {
Eric Laurentc529cf62020-04-17 18:19:10 -07003771 for (size_t i = 0; i < devices.size(); i++) {
3772 sp<DeviceDescriptor> devDesc = mHwModules.getDeviceDescriptor(
jiabin0a488932020-08-07 17:32:40 -07003773 devices[i].mType, devices[i].getAddress(), String8(),
Eric Laurent78fedbf2023-03-09 14:40:44 +01003774 AUDIO_FORMAT_DEFAULT, false /*allowToCreate*/, matchAddress);
Eric Laurentc529cf62020-04-17 18:19:10 -07003775 if (devDesc == nullptr || (predicate != nullptr && !predicate(devices[i].mType))) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003776 ALOGE("%s: device type %#x address %s not supported or not match predicate",
jiabin0a488932020-08-07 17:32:40 -07003777 context, devices[i].mType, devices[i].getAddress());
Eric Laurentc529cf62020-04-17 18:19:10 -07003778 return false;
3779 }
3780 }
3781 return true;
3782}
3783
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003784status_t AudioPolicyManager::setUidDeviceAffinities(uid_t uid,
jiabin6a02d532020-08-07 11:56:38 -07003785 const AudioDeviceTypeAddrVector& devices) {
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003786 ALOGV("%s() uid=%d num devices %zu", __FUNCTION__, uid, devices.size());
Eric Laurentc529cf62020-04-17 18:19:10 -07003787 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
3788 return BAD_VALUE;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003789 }
3790 status_t res = mPolicyMixes.setUidDeviceAffinities(uid, devices);
Eric Laurentc529cf62020-04-17 18:19:10 -07003791 if (res != NO_ERROR) {
3792 ALOGE("%s() Could not set all device affinities for uid = %d", __FUNCTION__, uid);
3793 return res;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003794 }
Eric Laurentc529cf62020-04-17 18:19:10 -07003795
3796 checkForDeviceAndOutputChanges();
3797 updateCallAndOutputRouting();
3798
3799 return NO_ERROR;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003800}
3801
3802status_t AudioPolicyManager::removeUidDeviceAffinities(uid_t uid) {
3803 ALOGV("%s() uid=%d", __FUNCTION__, uid);
Oscar Azucena4b2a8212019-04-26 23:48:59 -07003804 status_t res = mPolicyMixes.removeUidDeviceAffinities(uid);
3805 if (res != NO_ERROR) {
Eric Laurentc529cf62020-04-17 18:19:10 -07003806 ALOGE("%s() Could not remove all device affinities for uid = %d",
Oscar Azucena4b2a8212019-04-26 23:48:59 -07003807 __FUNCTION__, uid);
3808 return INVALID_OPERATION;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003809 }
3810
Eric Laurentc529cf62020-04-17 18:19:10 -07003811 checkForDeviceAndOutputChanges();
3812 updateCallAndOutputRouting();
3813
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003814 return res;
3815}
3816
Eric Laurent2517af32020-11-25 15:31:27 +01003817
jiabin0a488932020-08-07 17:32:40 -07003818status_t AudioPolicyManager::setDevicesRoleForStrategy(product_strategy_t strategy,
3819 device_role_t role,
3820 const AudioDeviceTypeAddrVector &devices) {
3821 ALOGV("%s() strategy=%d role=%d %s", __func__, strategy, role,
3822 dumpAudioDeviceTypeAddrVector(devices).c_str());
Eric Laurentc529cf62020-04-17 18:19:10 -07003823
Eric Laurentc529cf62020-04-17 18:19:10 -07003824 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003825 return BAD_VALUE;
3826 }
jiabin0a488932020-08-07 17:32:40 -07003827 status_t status = mEngine->setDevicesRoleForStrategy(strategy, role, devices);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003828 if (status != NO_ERROR) {
jiabin0a488932020-08-07 17:32:40 -07003829 ALOGW("Engine could not set preferred devices %s for strategy %d role %d",
3830 dumpAudioDeviceTypeAddrVector(devices).c_str(), strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003831 return status;
3832 }
3833
3834 checkForDeviceAndOutputChanges();
Eric Laurent2517af32020-11-25 15:31:27 +01003835
3836 bool forceVolumeReeval = false;
3837 // FIXME: workaround for truncated touch sounds
3838 // to be removed when the problem is handled by system UI
3839 uint32_t delayMs = 0;
3840 if (strategy == mCommunnicationStrategy) {
3841 forceVolumeReeval = true;
3842 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
3843 updateInputRouting();
3844 }
3845 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003846
3847 return NO_ERROR;
3848}
3849
3850void AudioPolicyManager::updateCallAndOutputRouting(bool forceVolumeReeval, uint32_t delayMs)
3851{
3852 uint32_t waitMs = 0;
Eric Laurent96d1dda2022-03-14 17:14:19 +01003853 bool wasLeUnicastActive = isLeUnicastActive();
Francois Gaffie19fd6c52021-02-04 17:02:59 +01003854 if (updateCallRouting(true /*fromCache*/, delayMs, &waitMs) == NO_ERROR) {
Eric Laurentb36b4ac2020-08-21 12:50:41 -07003855 // Only apply special touch sound delay once
3856 delayMs = 0;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003857 }
jiabin3ff8d7d2022-12-13 06:27:44 +00003858 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003859 for (size_t i = 0; i < mOutputs.size(); i++) {
3860 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
3861 DeviceVector newDevices = getNewOutputDevices(outputDesc, true /*fromCache*/);
Francois Gaffie601801d2021-06-22 13:27:39 +02003862 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) ||
3863 (outputDesc != mPrimaryOutput && !isTelephonyRxOrTx(outputDesc))) {
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003864 // As done in setDeviceConnectionState, we could also fix default device issue by
3865 // preventing the force re-routing in case of default dev that distinguishes on address.
3866 // Let's give back to engine full device choice decision however.
Francois Gaffie601801d2021-06-22 13:27:39 +02003867 bool forceRouting = !newDevices.isEmpty();
jiabin3ff8d7d2022-12-13 06:27:44 +00003868 if (outputDesc->mUsePreferredMixerAttributes && newDevices != outputDesc->devices()) {
3869 // If the device is using preferred mixer attributes, the output need to reopen
3870 // with default configuration when the new selected devices are different from
3871 // current routing devices.
3872 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices);
3873 continue;
3874 }
Francois Gaffie601801d2021-06-22 13:27:39 +02003875 waitMs = setOutputDevices(outputDesc, newDevices, forceRouting, delayMs, nullptr,
3876 true /*requiresMuteCheck*/,
3877 !forceRouting /*requiresVolumeCheck*/);
Eric Laurentb36b4ac2020-08-21 12:50:41 -07003878 // Only apply special touch sound delay once
3879 delayMs = 0;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003880 }
3881 if (forceVolumeReeval && !newDevices.isEmpty()) {
3882 applyStreamVolumes(outputDesc, newDevices.types(), waitMs, true);
3883 }
3884 }
jiabin3ff8d7d2022-12-13 06:27:44 +00003885 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent96d1dda2022-03-14 17:14:19 +01003886 checkLeBroadcastRoutes(wasLeUnicastActive, nullptr, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003887}
3888
Eric Laurent2517af32020-11-25 15:31:27 +01003889void AudioPolicyManager::updateInputRouting() {
3890 for (const auto& activeDesc : mInputs.getActiveInputs()) {
Jaideep Sharma408349a2020-11-27 14:47:17 +05303891 // Skip for hotword recording as the input device switch
3892 // is handled within sound trigger HAL
3893 if (activeDesc->isSoundTrigger() && activeDesc->source() == AUDIO_SOURCE_HOTWORD) {
3894 continue;
3895 }
Eric Laurent2517af32020-11-25 15:31:27 +01003896 auto newDevice = getNewInputDevice(activeDesc);
3897 // Force new input selection if the new device can not be reached via current input
3898 if (activeDesc->mProfile->getSupportedDevices().contains(newDevice)) {
3899 setInputDevice(activeDesc->mIoHandle, newDevice);
3900 } else {
3901 closeInput(activeDesc->mIoHandle);
3902 }
3903 }
3904}
3905
Paul Wang5d7cdb52022-11-22 09:45:06 +00003906status_t
3907AudioPolicyManager::removeDevicesRoleForStrategy(product_strategy_t strategy,
3908 device_role_t role,
3909 const AudioDeviceTypeAddrVector &devices) {
3910 ALOGV("%s() strategy=%d role=%d %s", __func__, strategy, role,
3911 dumpAudioDeviceTypeAddrVector(devices).c_str());
3912
Eric Laurent78fedbf2023-03-09 14:40:44 +01003913 if (!areAllDevicesSupported(
3914 devices, audio_is_output_device, __func__, /*matchAddress*/false)) {
Paul Wang5d7cdb52022-11-22 09:45:06 +00003915 return BAD_VALUE;
3916 }
3917 status_t status = mEngine->removeDevicesRoleForStrategy(strategy, role, devices);
3918 if (status != NO_ERROR) {
3919 ALOGW("Engine could not remove devices %s for strategy %d role %d",
3920 dumpAudioDeviceTypeAddrVector(devices).c_str(), strategy, role);
3921 return status;
3922 }
3923
3924 checkForDeviceAndOutputChanges();
3925
3926 bool forceVolumeReeval = false;
3927 // TODO(b/263479999): workaround for truncated touch sounds
3928 // to be removed when the problem is handled by system UI
3929 uint32_t delayMs = 0;
3930 if (strategy == mCommunnicationStrategy) {
3931 forceVolumeReeval = true;
3932 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
3933 updateInputRouting();
3934 }
3935 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
3936
3937 return NO_ERROR;
3938}
3939
3940status_t AudioPolicyManager::clearDevicesRoleForStrategy(product_strategy_t strategy,
3941 device_role_t role)
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003942{
Eric Laurentfecbceb2021-02-09 14:46:43 +01003943 ALOGV("%s() strategy=%d role=%d", __func__, strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003944
Paul Wang5d7cdb52022-11-22 09:45:06 +00003945 status_t status = mEngine->clearDevicesRoleForStrategy(strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003946 if (status != NO_ERROR) {
Eric Laurent9ae44f32022-12-14 16:17:02 +01003947 ALOGW_IF(status != NAME_NOT_FOUND,
3948 "Engine could not remove device role for strategy %d status %d",
Eric Laurent2517af32020-11-25 15:31:27 +01003949 strategy, status);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003950 return status;
3951 }
3952
3953 checkForDeviceAndOutputChanges();
Eric Laurent2517af32020-11-25 15:31:27 +01003954
3955 bool forceVolumeReeval = false;
3956 // FIXME: workaround for truncated touch sounds
3957 // to be removed when the problem is handled by system UI
3958 uint32_t delayMs = 0;
3959 if (strategy == mCommunnicationStrategy) {
3960 forceVolumeReeval = true;
3961 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
3962 updateInputRouting();
3963 }
3964 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003965
3966 return NO_ERROR;
3967}
3968
jiabin0a488932020-08-07 17:32:40 -07003969status_t AudioPolicyManager::getDevicesForRoleAndStrategy(product_strategy_t strategy,
3970 device_role_t role,
3971 AudioDeviceTypeAddrVector &devices) {
3972 return mEngine->getDevicesForRoleAndStrategy(strategy, role, devices);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003973}
3974
Jiabin Huang3b98d322020-09-03 17:54:16 +00003975status_t AudioPolicyManager::setDevicesRoleForCapturePreset(
3976 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices) {
3977 ALOGV("%s() audioSource=%d role=%d %s", __func__, audioSource, role,
3978 dumpAudioDeviceTypeAddrVector(devices).c_str());
3979
Mikhail Naganov55773032020-10-01 15:08:13 -07003980 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003981 return BAD_VALUE;
3982 }
3983 status_t status = mEngine->setDevicesRoleForCapturePreset(audioSource, role, devices);
3984 ALOGW_IF(status != NO_ERROR,
3985 "Engine could not set preferred devices %s for audio source %d role %d",
3986 dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
3987
3988 return status;
3989}
3990
3991status_t AudioPolicyManager::addDevicesRoleForCapturePreset(
3992 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices) {
3993 ALOGV("%s() audioSource=%d role=%d %s", __func__, audioSource, role,
3994 dumpAudioDeviceTypeAddrVector(devices).c_str());
3995
Mikhail Naganov55773032020-10-01 15:08:13 -07003996 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003997 return BAD_VALUE;
3998 }
3999 status_t status = mEngine->addDevicesRoleForCapturePreset(audioSource, role, devices);
4000 ALOGW_IF(status != NO_ERROR,
4001 "Engine could not add preferred devices %s for audio source %d role %d",
4002 dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
4003
Eric Laurent2517af32020-11-25 15:31:27 +01004004 updateInputRouting();
Jiabin Huang3b98d322020-09-03 17:54:16 +00004005 return status;
4006}
4007
4008status_t AudioPolicyManager::removeDevicesRoleForCapturePreset(
4009 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector& devices)
4010{
4011 ALOGV("%s() audioSource=%d role=%d devices=%s", __func__, audioSource, role,
4012 dumpAudioDeviceTypeAddrVector(devices).c_str());
4013
Eric Laurent78fedbf2023-03-09 14:40:44 +01004014 if (!areAllDevicesSupported(
4015 devices, audio_call_is_input_device, __func__, /*matchAddress*/false)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00004016 return BAD_VALUE;
4017 }
4018
4019 status_t status = mEngine->removeDevicesRoleForCapturePreset(
4020 audioSource, role, devices);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004021 ALOGW_IF(status != NO_ERROR && status != NAME_NOT_FOUND,
Jiabin Huang3b98d322020-09-03 17:54:16 +00004022 "Engine could not remove devices role (%d) for capture preset %d", role, audioSource);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004023 if (status == NO_ERROR) {
4024 updateInputRouting();
4025 }
Jiabin Huang3b98d322020-09-03 17:54:16 +00004026 return status;
4027}
4028
4029status_t AudioPolicyManager::clearDevicesRoleForCapturePreset(audio_source_t audioSource,
4030 device_role_t role) {
4031 ALOGV("%s() audioSource=%d role=%d", __func__, audioSource, role);
4032
4033 status_t status = mEngine->clearDevicesRoleForCapturePreset(audioSource, role);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004034 ALOGW_IF(status != NO_ERROR && status != NAME_NOT_FOUND,
Jiabin Huang3b98d322020-09-03 17:54:16 +00004035 "Engine could not clear devices role (%d) for capture preset %d", role, audioSource);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004036 if (status == NO_ERROR) {
4037 updateInputRouting();
4038 }
Jiabin Huang3b98d322020-09-03 17:54:16 +00004039 return status;
4040}
4041
4042status_t AudioPolicyManager::getDevicesForRoleAndCapturePreset(
4043 audio_source_t audioSource, device_role_t role, AudioDeviceTypeAddrVector &devices) {
4044 return mEngine->getDevicesForRoleAndCapturePreset(audioSource, role, devices);
4045}
4046
Oscar Azucena90e77632019-11-27 17:12:28 -08004047status_t AudioPolicyManager::setUserIdDeviceAffinities(int userId,
jiabin6a02d532020-08-07 11:56:38 -07004048 const AudioDeviceTypeAddrVector& devices) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01004049 ALOGV("%s() userId=%d num devices %zu", __func__, userId, devices.size());
Eric Laurentc529cf62020-04-17 18:19:10 -07004050 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
4051 return BAD_VALUE;
Oscar Azucena90e77632019-11-27 17:12:28 -08004052 }
Oscar Azucena90e77632019-11-27 17:12:28 -08004053 status_t status = mPolicyMixes.setUserIdDeviceAffinities(userId, devices);
4054 if (status != NO_ERROR) {
4055 ALOGE("%s() could not set device affinity for userId %d",
4056 __FUNCTION__, userId);
4057 return status;
4058 }
4059
4060 // reevaluate outputs for all devices
4061 checkForDeviceAndOutputChanges();
4062 updateCallAndOutputRouting();
4063
4064 return NO_ERROR;
4065}
4066
4067status_t AudioPolicyManager::removeUserIdDeviceAffinities(int userId) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01004068 ALOGV("%s() userId=%d", __FUNCTION__, userId);
Oscar Azucena90e77632019-11-27 17:12:28 -08004069 status_t status = mPolicyMixes.removeUserIdDeviceAffinities(userId);
4070 if (status != NO_ERROR) {
4071 ALOGE("%s() Could not remove all device affinities fo userId = %d",
4072 __FUNCTION__, userId);
4073 return status;
4074 }
4075
4076 // reevaluate outputs for all devices
4077 checkForDeviceAndOutputChanges();
4078 updateCallAndOutputRouting();
4079
4080 return NO_ERROR;
4081}
4082
Andy Hungc29d82b2018-10-05 12:23:17 -07004083void AudioPolicyManager::dump(String8 *dst) const
Eric Laurente552edb2014-03-10 17:42:56 -07004084{
Andy Hungc29d82b2018-10-05 12:23:17 -07004085 dst->appendFormat("\nAudioPolicyManager Dump: %p\n", this);
Mikhail Naganov0dbe87b2021-12-01 02:03:31 +00004086 dst->appendFormat(" Primary Output I/O handle: %d\n",
Eric Laurent87ffa392015-05-22 10:32:38 -07004087 hasPrimaryOutput() ? mPrimaryOutput->mIoHandle : AUDIO_IO_HANDLE_NONE);
Mikhail Naganov0d6a0332016-04-19 17:12:38 -07004088 std::string stateLiteral;
4089 AudioModeConverter::toString(mEngine->getPhoneState(), stateLiteral);
Andy Hungc29d82b2018-10-05 12:23:17 -07004090 dst->appendFormat(" Phone state: %s\n", stateLiteral.c_str());
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07004091 const char* forceUses[AUDIO_POLICY_FORCE_USE_CNT] = {
4092 "communications", "media", "record", "dock", "system",
4093 "HDMI system audio", "encoded surround output", "vibrate ringing" };
4094 for (audio_policy_force_use_t i = AUDIO_POLICY_FORCE_FOR_COMMUNICATION;
4095 i < AUDIO_POLICY_FORCE_USE_CNT; i = (audio_policy_force_use_t)((int)i + 1)) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08004096 audio_policy_forced_cfg_t forceUseValue = mEngine->getForceUse(i);
4097 dst->appendFormat(" Force use for %s: %d", forceUses[i], forceUseValue);
4098 if (i == AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND &&
4099 forceUseValue == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
4100 dst->append(" (MANUAL: ");
4101 dumpManualSurroundFormats(dst);
4102 dst->append(")");
4103 }
4104 dst->append("\n");
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07004105 }
Andy Hungc29d82b2018-10-05 12:23:17 -07004106 dst->appendFormat(" TTS output %savailable\n", mTtsOutputAvailable ? "" : "not ");
4107 dst->appendFormat(" Master mono: %s\n", mMasterMono ? "on" : "off");
Mikhail Naganovb3bcb4f2022-02-23 23:46:56 +00004108 dst->appendFormat(" Communication Strategy id: %d\n", mCommunnicationStrategy);
Andy Hungc29d82b2018-10-05 12:23:17 -07004109 dst->appendFormat(" Config source: %s\n", mConfig.getSource().c_str()); // getConfig not const
Eric Laurent2517af32020-11-25 15:31:27 +01004110
Mikhail Naganov0f413b22021-12-02 05:29:27 +00004111 dst->append("\n");
4112 mAvailableOutputDevices.dump(dst, String8("Available output"), 1);
4113 dst->append("\n");
4114 mAvailableInputDevices.dump(dst, String8("Available input"), 1);
Andy Hungc29d82b2018-10-05 12:23:17 -07004115 mHwModulesAll.dump(dst);
4116 mOutputs.dump(dst);
4117 mInputs.dump(dst);
Mikhail Naganov0f413b22021-12-02 05:29:27 +00004118 mEffects.dump(dst, 1);
Andy Hungc29d82b2018-10-05 12:23:17 -07004119 mAudioPatches.dump(dst);
4120 mPolicyMixes.dump(dst);
4121 mAudioSources.dump(dst);
François Gaffiec005e562018-11-06 15:04:49 +01004122
Kevin Rocardb99cc752019-03-21 20:52:24 -07004123 dst->appendFormat(" AllowedCapturePolicies:\n");
4124 for (auto& policy : mAllowedCapturePolicies) {
4125 dst->appendFormat(" - uid=%d flag_mask=%#x\n", policy.first, policy.second);
4126 }
4127
jiabina84c3d32022-12-02 18:59:55 +00004128 dst->appendFormat(" Preferred mixer audio configuration:\n");
4129 for (const auto it : mPreferredMixerAttrInfos) {
4130 dst->appendFormat(" - device port id: %d\n", it.first);
4131 for (const auto preferredMixerInfoIt : it.second) {
4132 dst->appendFormat(" - strategy: %d; ", preferredMixerInfoIt.first);
4133 preferredMixerInfoIt.second->dump(dst);
4134 }
4135 }
4136
François Gaffiec005e562018-11-06 15:04:49 +01004137 dst->appendFormat("\nPolicy Engine dump:\n");
4138 mEngine->dump(dst);
Andy Hungc29d82b2018-10-05 12:23:17 -07004139}
4140
4141status_t AudioPolicyManager::dump(int fd)
4142{
4143 String8 result;
4144 dump(&result);
Andy Hungbb54e202018-10-05 11:42:02 -07004145 write(fd, result.string(), result.size());
Eric Laurente552edb2014-03-10 17:42:56 -07004146 return NO_ERROR;
4147}
4148
Kevin Rocardb99cc752019-03-21 20:52:24 -07004149status_t AudioPolicyManager::setAllowedCapturePolicy(uid_t uid, audio_flags_mask_t capturePolicy)
4150{
4151 mAllowedCapturePolicies[uid] = capturePolicy;
4152 return NO_ERROR;
4153}
4154
Eric Laurente552edb2014-03-10 17:42:56 -07004155// This function checks for the parameters which can be offloaded.
4156// This can be enhanced depending on the capability of the DSP and policy
4157// of the system.
Eric Laurent90fe31c2020-11-26 20:06:35 +01004158audio_offload_mode_t AudioPolicyManager::getOffloadSupport(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07004159{
Eric Laurent90fe31c2020-11-26 20:06:35 +01004160 ALOGV("%s: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07004161 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurent90fe31c2020-11-26 20:06:35 +01004162 __func__, offloadInfo.sample_rate, offloadInfo.channel_mask,
Eric Laurente552edb2014-03-10 17:42:56 -07004163 offloadInfo.format,
4164 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
4165 offloadInfo.has_video);
4166
jiabin2b9d5a12021-12-10 01:06:29 +00004167 if (!isOffloadPossible(offloadInfo)) {
Eric Laurent90fe31c2020-11-26 20:06:35 +01004168 return AUDIO_OFFLOAD_NOT_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07004169 }
4170
4171 // See if there is a profile to support this.
4172 // AUDIO_DEVICE_NONE
François Gaffie11d30102018-11-02 16:09:09 +01004173 sp<IOProfile> profile = getProfileForOutput(DeviceVector() /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07004174 offloadInfo.sample_rate,
4175 offloadInfo.format,
4176 offloadInfo.channel_mask,
Michael Chana94fbb22018-04-24 14:31:19 +10004177 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD,
4178 true /* directOnly */);
Eric Laurent94365442021-01-08 18:36:05 +01004179 ALOGV("%s: profile %sfound%s", __func__, profile != nullptr ? "" : "NOT ",
4180 (profile != nullptr && (profile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD) != 0)
4181 ? ", supports gapless" : "");
Eric Laurent90fe31c2020-11-26 20:06:35 +01004182 if (profile == nullptr) {
4183 return AUDIO_OFFLOAD_NOT_SUPPORTED;
4184 }
4185 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD) != 0) {
4186 return AUDIO_OFFLOAD_GAPLESS_SUPPORTED;
4187 }
4188 return AUDIO_OFFLOAD_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07004189}
4190
Michael Chana94fbb22018-04-24 14:31:19 +10004191bool AudioPolicyManager::isDirectOutputSupported(const audio_config_base_t& config,
4192 const audio_attributes_t& attributes) {
4193 audio_output_flags_t output_flags = AUDIO_OUTPUT_FLAG_NONE;
François Gaffie58d4be52018-11-06 15:30:12 +01004194 audio_flags_to_audio_output_flags(attributes.flags, &output_flags);
Dorin Drimus9901eb02022-01-14 11:36:51 +00004195 DeviceVector outputDevices = mEngine->getOutputDevicesForAttributes(attributes);
4196 sp<IOProfile> profile = getProfileForOutput(outputDevices,
Michael Chana94fbb22018-04-24 14:31:19 +10004197 config.sample_rate,
4198 config.format,
4199 config.channel_mask,
4200 output_flags,
4201 true /* directOnly */);
4202 ALOGV("%s() profile %sfound with name: %s, "
4203 "sample rate: %u, format: 0x%x, channel_mask: 0x%x, output flags: 0x%x",
4204 __FUNCTION__, profile != 0 ? "" : "NOT ",
jiabin5740f082019-08-19 15:08:30 -07004205 (profile != 0 ? profile->getTagName().c_str() : "null"),
Michael Chana94fbb22018-04-24 14:31:19 +10004206 config.sample_rate, config.format, config.channel_mask, output_flags);
Dorin Drimusecc9f422022-03-09 17:57:40 +01004207
4208 // also try the MSD module if compatible profile not found
4209 if (profile == nullptr) {
4210 profile = getMsdProfileForOutput(outputDevices,
4211 config.sample_rate,
4212 config.format,
4213 config.channel_mask,
4214 output_flags,
4215 true /* directOnly */);
4216 ALOGV("%s() MSD profile %sfound with name: %s, "
4217 "sample rate: %u, format: 0x%x, channel_mask: 0x%x, output flags: 0x%x",
4218 __FUNCTION__, profile != 0 ? "" : "NOT ",
4219 (profile != 0 ? profile->getTagName().c_str() : "null"),
4220 config.sample_rate, config.format, config.channel_mask, output_flags);
4221 }
4222 return (profile != nullptr);
Michael Chana94fbb22018-04-24 14:31:19 +10004223}
4224
jiabin2b9d5a12021-12-10 01:06:29 +00004225bool AudioPolicyManager::isOffloadPossible(const audio_offload_info_t &offloadInfo,
4226 bool durationIgnored) {
4227 if (mMasterMono) {
4228 return false; // no offloading if mono is set.
4229 }
4230
4231 // Check if offload has been disabled
4232 if (property_get_bool("audio.offload.disable", false /* default_value */)) {
4233 ALOGV("%s: offload disabled by audio.offload.disable", __func__);
4234 return false;
4235 }
4236
4237 // Check if stream type is music, then only allow offload as of now.
4238 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
4239 {
4240 ALOGV("%s: stream_type != MUSIC, returning false", __func__);
4241 return false;
4242 }
4243
4244 //TODO: enable audio offloading with video when ready
4245 const bool allowOffloadWithVideo =
4246 property_get_bool("audio.offload.video", false /* default_value */);
4247 if (offloadInfo.has_video && !allowOffloadWithVideo) {
4248 ALOGV("%s: has_video == true, returning false", __func__);
4249 return false;
4250 }
4251
4252 //If duration is less than minimum value defined in property, return false
4253 const int min_duration_secs = property_get_int32(
4254 "audio.offload.min.duration.secs", -1 /* default_value */);
4255 if (!durationIgnored) {
4256 if (min_duration_secs >= 0) {
4257 if (offloadInfo.duration_us < min_duration_secs * 1000000LL) {
4258 ALOGV("%s: Offload denied by duration < audio.offload.min.duration.secs(=%d)",
4259 __func__, min_duration_secs);
4260 return false;
4261 }
4262 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
4263 ALOGV("%s: Offload denied by duration < default min(=%u)",
4264 __func__, OFFLOAD_DEFAULT_MIN_DURATION_SECS);
4265 return false;
4266 }
4267 }
4268
4269 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
4270 // creating an offloaded track and tearing it down immediately after start when audioflinger
4271 // detects there is an active non offloadable effect.
4272 // FIXME: We should check the audio session here but we do not have it in this context.
4273 // This may prevent offloading in rare situations where effects are left active by apps
4274 // in the background.
4275 if (mEffects.isNonOffloadableEffectEnabled()) {
4276 return false;
4277 }
4278
4279 return true;
4280}
4281
4282audio_direct_mode_t AudioPolicyManager::getDirectPlaybackSupport(const audio_attributes_t *attr,
4283 const audio_config_t *config) {
4284 audio_offload_info_t offloadInfo = AUDIO_INFO_INITIALIZER;
4285 offloadInfo.format = config->format;
4286 offloadInfo.sample_rate = config->sample_rate;
4287 offloadInfo.channel_mask = config->channel_mask;
4288 offloadInfo.stream_type = mEngine->getStreamTypeForAttributes(*attr);
4289 offloadInfo.has_video = false;
4290 offloadInfo.is_streaming = false;
4291 const bool offloadPossible = isOffloadPossible(offloadInfo, true /*durationIgnored*/);
4292
4293 audio_direct_mode_t directMode = AUDIO_DIRECT_NOT_SUPPORTED;
4294 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
4295 audio_flags_to_audio_output_flags(attr->flags, &flags);
4296 // only retain flags that will drive compressed offload or passthrough
4297 uint32_t relevantFlags = AUDIO_OUTPUT_FLAG_HW_AV_SYNC;
4298 if (offloadPossible) {
4299 relevantFlags |= AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD;
4300 }
4301 flags = (audio_output_flags_t)((flags & relevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
4302
Dorin Drimusfae3c642022-03-17 18:36:30 +01004303 DeviceVector engineOutputDevices = mEngine->getOutputDevicesForAttributes(*attr);
jiabin2b9d5a12021-12-10 01:06:29 +00004304 for (const auto& hwModule : mHwModules) {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004305 DeviceVector outputDevices = engineOutputDevices;
4306 // the MSD module checks for different conditions and output devices
4307 if (strcmp(hwModule->getName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0) {
4308 if (!msdHasPatchesToAllDevices(engineOutputDevices.toTypeAddrVector())) {
4309 continue;
4310 }
4311 outputDevices = getMsdAudioOutDevices();
4312 }
jiabin2b9d5a12021-12-10 01:06:29 +00004313 for (const auto& curProfile : hwModule->getOutputProfiles()) {
jiabinc8f7dfc2022-01-06 18:42:08 +00004314 if (!curProfile->isCompatibleProfile(outputDevices,
jiabin2b9d5a12021-12-10 01:06:29 +00004315 config->sample_rate, nullptr /*updatedSamplingRate*/,
4316 config->format, nullptr /*updatedFormat*/,
4317 config->channel_mask, nullptr /*updatedChannelMask*/,
4318 flags)) {
4319 continue;
4320 }
4321 // reject profiles not corresponding to a device currently available
4322 if (!mAvailableOutputDevices.containsAtLeastOne(curProfile->getSupportedDevices())) {
4323 continue;
4324 }
4325 if ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)
4326 != AUDIO_OUTPUT_FLAG_NONE) {
jiabinc6132d62022-01-01 07:36:31 +00004327 if ((directMode & AUDIO_DIRECT_OFFLOAD_GAPLESS_SUPPORTED)
jiabin2b9d5a12021-12-10 01:06:29 +00004328 != AUDIO_DIRECT_NOT_SUPPORTED) {
4329 // Already reports offload gapless supported. No need to report offload support.
4330 continue;
4331 }
4332 if ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD)
4333 != AUDIO_OUTPUT_FLAG_NONE) {
4334 // If offload gapless is reported, no need to report offload support.
4335 directMode = (audio_direct_mode_t) ((directMode &
4336 ~AUDIO_DIRECT_OFFLOAD_SUPPORTED) |
4337 AUDIO_DIRECT_OFFLOAD_GAPLESS_SUPPORTED);
4338 } else {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004339 directMode = (audio_direct_mode_t)(directMode | AUDIO_DIRECT_OFFLOAD_SUPPORTED);
jiabin2b9d5a12021-12-10 01:06:29 +00004340 }
4341 } else {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004342 directMode = (audio_direct_mode_t) (directMode | AUDIO_DIRECT_BITSTREAM_SUPPORTED);
jiabin2b9d5a12021-12-10 01:06:29 +00004343 }
4344 }
4345 }
4346 return directMode;
4347}
4348
Dorin Drimusf2196d82022-01-03 12:11:18 +01004349status_t AudioPolicyManager::getDirectProfilesForAttributes(const audio_attributes_t* attr,
4350 AudioProfileVector& audioProfilesVector) {
Dorin Drimus17112632022-09-23 15:28:51 +00004351 if (mEffects.isNonOffloadableEffectEnabled()) {
4352 return OK;
4353 }
jiabinf1c73972022-04-14 16:28:52 -07004354 DeviceVector devices;
4355 status_t status = getDevicesForAttributes(*attr, devices, false /* forVolume */);
Dorin Drimusf2196d82022-01-03 12:11:18 +01004356 if (status != OK) {
4357 return status;
4358 }
4359 ALOGV("%s: found %zu output devices for attributes.", __func__, devices.size());
4360 if (devices.empty()) {
4361 return OK; // no output devices for the attributes
4362 }
jiabinf1c73972022-04-14 16:28:52 -07004363 return getProfilesForDevices(devices, audioProfilesVector,
4364 AUDIO_OUTPUT_FLAG_DIRECT /*flags*/, false /*isInput*/);
Dorin Drimusf2196d82022-01-03 12:11:18 +01004365}
4366
jiabina84c3d32022-12-02 18:59:55 +00004367status_t AudioPolicyManager::getSupportedMixerAttributes(
4368 audio_port_handle_t portId, std::vector<audio_mixer_attributes_t> &mixerAttrs) {
4369 ALOGV("%s, portId=%d", __func__, portId);
4370 sp<DeviceDescriptor> deviceDescriptor = mAvailableOutputDevices.getDeviceFromId(portId);
4371 if (deviceDescriptor == nullptr) {
4372 ALOGE("%s the requested device is currently unavailable", __func__);
4373 return BAD_VALUE;
4374 }
4375 for (const auto& hwModule : mHwModules) {
4376 for (const auto& curProfile : hwModule->getOutputProfiles()) {
4377 if (curProfile->supportsDevice(deviceDescriptor)) {
4378 curProfile->toSupportedMixerAttributes(&mixerAttrs);
4379 }
4380 }
4381 }
4382 return NO_ERROR;
4383}
4384
4385status_t AudioPolicyManager::setPreferredMixerAttributes(
4386 const audio_attributes_t *attr,
4387 audio_port_handle_t portId,
4388 uid_t uid,
4389 const audio_mixer_attributes_t *mixerAttributes) {
4390 ALOGV("%s, attr=%s, mixerAttributes={format=%#x, channelMask=%#x, samplingRate=%u, "
4391 "mixerBehavior=%d}, uid=%d, portId=%u",
4392 __func__, toString(*attr).c_str(), mixerAttributes->config.format,
4393 mixerAttributes->config.channel_mask, mixerAttributes->config.sample_rate,
4394 mixerAttributes->mixer_behavior, uid, portId);
4395 if (attr->usage != AUDIO_USAGE_MEDIA) {
4396 ALOGE("%s failed, only media is allowed, the given usage is %d", __func__, attr->usage);
4397 return BAD_VALUE;
4398 }
4399 sp<DeviceDescriptor> deviceDescriptor = mAvailableOutputDevices.getDeviceFromId(portId);
4400 if (deviceDescriptor == nullptr) {
4401 ALOGE("%s the requested device is currently unavailable", __func__);
4402 return BAD_VALUE;
4403 }
4404 if (!audio_is_usb_out_device(deviceDescriptor->type())) {
4405 ALOGE("%s(%d), type=%d, is not a usb output device",
4406 __func__, portId, deviceDescriptor->type());
4407 return BAD_VALUE;
4408 }
4409
4410 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
4411 audio_flags_to_audio_output_flags(attr->flags, &flags);
4412 flags = (audio_output_flags_t) (flags |
4413 audio_output_flags_from_mixer_behavior(mixerAttributes->mixer_behavior));
4414 sp<IOProfile> profile = nullptr;
4415 DeviceVector devices(deviceDescriptor);
4416 for (const auto& hwModule : mHwModules) {
4417 for (const auto& curProfile : hwModule->getOutputProfiles()) {
4418 if (curProfile->hasDynamicAudioProfile()
4419 && curProfile->isCompatibleProfile(devices,
4420 mixerAttributes->config.sample_rate,
4421 nullptr /*updatedSamplingRate*/,
4422 mixerAttributes->config.format,
4423 nullptr /*updatedFormat*/,
4424 mixerAttributes->config.channel_mask,
4425 nullptr /*updatedChannelMask*/,
4426 flags,
4427 false /*exactMatchRequiredForInputFlags*/)) {
4428 profile = curProfile;
4429 break;
4430 }
4431 }
4432 }
4433 if (profile == nullptr) {
4434 ALOGE("%s, there is no compatible profile found", __func__);
4435 return BAD_VALUE;
4436 }
4437
4438 sp<PreferredMixerAttributesInfo> mixerAttrInfo =
4439 sp<PreferredMixerAttributesInfo>::make(
4440 uid, portId, profile, flags, *mixerAttributes);
4441 const product_strategy_t strategy = mEngine->getProductStrategyForAttributes(*attr);
4442 mPreferredMixerAttrInfos[portId][strategy] = mixerAttrInfo;
4443
4444 // If 1) there is any client from the preferred mixer configuration owner that is currently
4445 // active and matches the strategy and 2) current output is on the preferred device and the
4446 // mixer configuration doesn't match the preferred one, reopen output with preferred mixer
4447 // configuration.
4448 std::vector<audio_io_handle_t> outputsToReopen;
4449 for (size_t i = 0; i < mOutputs.size(); i++) {
4450 const auto output = mOutputs.valueAt(i);
jiabin3ff8d7d2022-12-13 06:27:44 +00004451 if (output->mProfile == profile && output->devices().onlyContainsDevice(deviceDescriptor)) {
4452 if (output->isConfigurationMatched(mixerAttributes->config, flags)) {
4453 output->mUsePreferredMixerAttributes = true;
4454 } else {
4455 for (const auto &client: output->getActiveClients()) {
4456 if (client->uid() == uid && client->strategy() == strategy) {
4457 client->setIsInvalid();
4458 outputsToReopen.push_back(output->mIoHandle);
4459 }
jiabina84c3d32022-12-02 18:59:55 +00004460 }
4461 }
4462 }
4463 }
4464 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
4465 config.sample_rate = mixerAttributes->config.sample_rate;
4466 config.channel_mask = mixerAttributes->config.channel_mask;
4467 config.format = mixerAttributes->config.format;
4468 for (const auto output : outputsToReopen) {
jiabin3ff8d7d2022-12-13 06:27:44 +00004469 sp<SwAudioOutputDescriptor> desc =
4470 reopenOutput(mOutputs.valueFor(output), &config, flags, __func__);
4471 if (desc == nullptr) {
4472 ALOGE("%s, failed to reopen output with preferred mixer attributes", __func__);
4473 continue;
4474 }
4475 desc->mUsePreferredMixerAttributes = true;
jiabina84c3d32022-12-02 18:59:55 +00004476 }
4477
4478 return NO_ERROR;
4479}
4480
4481sp<PreferredMixerAttributesInfo> AudioPolicyManager::getPreferredMixerAttributesInfo(
4482 audio_port_handle_t devicePortId, product_strategy_t strategy) {
4483 auto it = mPreferredMixerAttrInfos.find(devicePortId);
4484 if (it == mPreferredMixerAttrInfos.end()) {
4485 return nullptr;
4486 }
4487 auto mixerAttrInfoIt = it->second.find(strategy);
4488 if (mixerAttrInfoIt == it->second.end()) {
4489 return nullptr;
4490 }
4491 return mixerAttrInfoIt->second;
4492}
4493
4494status_t AudioPolicyManager::getPreferredMixerAttributes(
4495 const audio_attributes_t *attr,
4496 audio_port_handle_t portId,
4497 audio_mixer_attributes_t* mixerAttributes) {
4498 sp<PreferredMixerAttributesInfo> info = getPreferredMixerAttributesInfo(
4499 portId, mEngine->getProductStrategyForAttributes(*attr));
4500 if (info == nullptr) {
4501 return NAME_NOT_FOUND;
4502 }
4503 *mixerAttributes = info->getMixerAttributes();
4504 return NO_ERROR;
4505}
4506
4507status_t AudioPolicyManager::clearPreferredMixerAttributes(const audio_attributes_t *attr,
4508 audio_port_handle_t portId,
4509 uid_t uid) {
4510 const product_strategy_t strategy = mEngine->getProductStrategyForAttributes(*attr);
4511 const auto preferredMixerAttrInfo = getPreferredMixerAttributesInfo(portId, strategy);
4512 if (preferredMixerAttrInfo == nullptr) {
4513 return NAME_NOT_FOUND;
4514 }
4515 if (preferredMixerAttrInfo->getUid() != uid) {
4516 ALOGE("%s, requested uid=%d, owned uid=%d",
4517 __func__, uid, preferredMixerAttrInfo->getUid());
4518 return PERMISSION_DENIED;
4519 }
4520 mPreferredMixerAttrInfos[portId].erase(strategy);
4521 if (mPreferredMixerAttrInfos[portId].empty()) {
4522 mPreferredMixerAttrInfos.erase(portId);
4523 }
4524
4525 // Reconfig existing output
4526 std::vector<audio_io_handle_t> potentialOutputsToReopen;
4527 for (size_t i = 0; i < mOutputs.size(); i++) {
4528 if (mOutputs.valueAt(i)->mProfile == preferredMixerAttrInfo->getProfile()) {
4529 potentialOutputsToReopen.push_back(mOutputs.keyAt(i));
4530 }
4531 }
4532 for (const auto output : potentialOutputsToReopen) {
4533 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
4534 if (desc->isConfigurationMatched(preferredMixerAttrInfo->getConfigBase(),
4535 preferredMixerAttrInfo->getFlags())) {
4536 reopenOutput(desc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
4537 }
4538 }
4539 return NO_ERROR;
4540}
4541
Eric Laurent6a94d692014-05-20 11:18:06 -07004542status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
4543 audio_port_type_t type,
4544 unsigned int *num_ports,
jiabin19cdba52020-11-24 11:28:58 -08004545 struct audio_port_v7 *ports,
Eric Laurent6a94d692014-05-20 11:18:06 -07004546 unsigned int *generation)
4547{
jiabin19cdba52020-11-24 11:28:58 -08004548 if (num_ports == nullptr || (*num_ports != 0 && ports == nullptr) ||
4549 generation == nullptr) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004550 return BAD_VALUE;
4551 }
4552 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
jiabin19cdba52020-11-24 11:28:58 -08004553 if (ports == nullptr) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004554 *num_ports = 0;
4555 }
4556
4557 size_t portsWritten = 0;
4558 size_t portsMax = *num_ports;
4559 *num_ports = 0;
4560 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07004561 // do not report devices with type AUDIO_DEVICE_IN_STUB or AUDIO_DEVICE_OUT_STUB
4562 // as they are used by stub HALs by convention
Eric Laurent6a94d692014-05-20 11:18:06 -07004563 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004564 for (const auto& dev : mAvailableOutputDevices) {
4565 if (dev->type() == AUDIO_DEVICE_OUT_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07004566 continue;
4567 }
4568 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004569 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07004570 }
4571 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07004572 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004573 }
4574 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004575 for (const auto& dev : mAvailableInputDevices) {
4576 if (dev->type() == AUDIO_DEVICE_IN_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07004577 continue;
4578 }
4579 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004580 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07004581 }
4582 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07004583 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004584 }
4585 }
4586 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
4587 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
4588 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
4589 mInputs[i]->toAudioPort(&ports[portsWritten++]);
4590 }
4591 *num_ports += mInputs.size();
4592 }
4593 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent84c70242014-06-23 08:46:27 -07004594 size_t numOutputs = 0;
4595 for (size_t i = 0; i < mOutputs.size(); i++) {
4596 if (!mOutputs[i]->isDuplicated()) {
4597 numOutputs++;
4598 if (portsWritten < portsMax) {
4599 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
4600 }
4601 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004602 }
Eric Laurent84c70242014-06-23 08:46:27 -07004603 *num_ports += numOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07004604 }
4605 }
jiabina84c3d32022-12-02 18:59:55 +00004606
Eric Laurent6a94d692014-05-20 11:18:06 -07004607 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07004608 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
Eric Laurent6a94d692014-05-20 11:18:06 -07004609 return NO_ERROR;
4610}
4611
Mikhail Naganov5edc5ed2023-03-23 14:52:15 -07004612status_t AudioPolicyManager::listDeclaredDevicePorts(media::AudioPortRole role,
4613 std::vector<media::AudioPortFw>* _aidl_return) {
4614 auto pushPort = [&](const sp<DeviceDescriptor>& dev) -> status_t {
4615 audio_port_v7 port;
4616 dev->toAudioPort(&port);
4617 auto aidlPort = VALUE_OR_RETURN_STATUS(legacy2aidl_audio_port_v7_AudioPortFw(port));
4618 _aidl_return->push_back(std::move(aidlPort));
4619 return OK;
4620 };
4621
4622 for (const auto& module : mHwModulesAll) {
4623 for (const auto& dev : module->getDeclaredDevices()) {
4624 if (role == media::AudioPortRole::NONE ||
4625 ((role == media::AudioPortRole::SOURCE)
4626 == audio_is_input_device(dev->type()))) {
4627 RETURN_STATUS_IF_ERROR(pushPort(dev));
4628 }
4629 }
4630 }
4631 return OK;
4632}
4633
jiabin19cdba52020-11-24 11:28:58 -08004634status_t AudioPolicyManager::getAudioPort(struct audio_port_v7 *port)
Eric Laurent6a94d692014-05-20 11:18:06 -07004635{
Eric Laurent99fcae42018-05-17 16:59:18 -07004636 if (port == nullptr || port->id == AUDIO_PORT_HANDLE_NONE) {
4637 return BAD_VALUE;
4638 }
4639 sp<DeviceDescriptor> dev = mAvailableOutputDevices.getDeviceFromId(port->id);
4640 if (dev != 0) {
4641 dev->toAudioPort(port);
4642 return NO_ERROR;
4643 }
4644 dev = mAvailableInputDevices.getDeviceFromId(port->id);
4645 if (dev != 0) {
4646 dev->toAudioPort(port);
4647 return NO_ERROR;
4648 }
4649 sp<SwAudioOutputDescriptor> out = mOutputs.getOutputFromId(port->id);
4650 if (out != 0) {
4651 out->toAudioPort(port);
4652 return NO_ERROR;
4653 }
4654 sp<AudioInputDescriptor> in = mInputs.getInputFromId(port->id);
4655 if (in != 0) {
4656 in->toAudioPort(port);
4657 return NO_ERROR;
4658 }
4659 return BAD_VALUE;
Eric Laurent6a94d692014-05-20 11:18:06 -07004660}
4661
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004662status_t AudioPolicyManager::createAudioPatch(const struct audio_patch *patch,
4663 audio_patch_handle_t *handle,
4664 uid_t uid)
Eric Laurent6a94d692014-05-20 11:18:06 -07004665{
François Gaffieafd4cea2019-11-18 15:50:22 +01004666 ALOGV("%s", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004667 if (handle == NULL || patch == NULL) {
4668 return BAD_VALUE;
4669 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004670 ALOGV("%s num sources %d num sinks %d", __func__, patch->num_sources, patch->num_sinks);
Mikhail Naganovac9858b2018-06-15 13:12:37 -07004671 if (!audio_patch_is_valid(patch)) {
Eric Laurent874c42872014-08-08 15:13:39 -07004672 return BAD_VALUE;
4673 }
4674 // only one source per audio patch supported for now
4675 if (patch->num_sources > 1) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004676 return INVALID_OPERATION;
4677 }
Eric Laurent874c42872014-08-08 15:13:39 -07004678 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004679 return INVALID_OPERATION;
4680 }
Eric Laurent874c42872014-08-08 15:13:39 -07004681 for (size_t i = 0; i < patch->num_sinks; i++) {
4682 if (patch->sinks[i].role != AUDIO_PORT_ROLE_SINK) {
4683 return INVALID_OPERATION;
4684 }
4685 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004686
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004687 sp<DeviceDescriptor> srcDevice = mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
4688 sp<DeviceDescriptor> sinkDevice = mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id);
4689 if (srcDevice == nullptr || sinkDevice == nullptr) {
4690 ALOGW("%s could not create patch, invalid sink and/or source device(s)", __func__);
4691 return BAD_VALUE;
4692 }
4693 ALOGV("%s between source %s and sink %s", __func__,
4694 srcDevice->toString().c_str(), sinkDevice->toString().c_str());
4695 audio_port_handle_t portId = PolicyAudioPort::getNextUniqueId();
4696 // Default attributes, default volume priority, not to infer with non raw audio patches.
4697 audio_attributes_t attributes = attributes_initializer(AUDIO_USAGE_MEDIA);
4698 const struct audio_port_config *source = &patch->sources[0];
4699 sp<SourceClientDescriptor> sourceDesc =
4700 new InternalSourceClientDescriptor(
4701 portId, uid, attributes, *source, srcDevice, sinkDevice,
4702 mEngine->getProductStrategyForAttributes(attributes), toVolumeSource(attributes));
4703
4704 status_t status =
4705 connectAudioSourceToSink(sourceDesc, sinkDevice, patch, *handle, uid, 0 /* delayMs */);
4706
4707 if (status != NO_ERROR) {
4708 return INVALID_OPERATION;
4709 }
4710 mAudioSources.add(portId, sourceDesc);
4711 return NO_ERROR;
4712}
4713
4714status_t AudioPolicyManager::connectAudioSourceToSink(
4715 const sp<SourceClientDescriptor>& sourceDesc, const sp<DeviceDescriptor> &sinkDevice,
4716 const struct audio_patch *patch,
4717 audio_patch_handle_t &handle,
4718 uid_t uid, uint32_t delayMs)
4719{
4720 status_t status = createAudioPatchInternal(patch, &handle, uid, delayMs, sourceDesc);
4721 if (status != NO_ERROR || mAudioPatches.indexOfKey(handle) < 0) {
4722 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
4723 return INVALID_OPERATION;
4724 }
4725 sourceDesc->connect(handle, sinkDevice);
4726 if (isMsdPatch(handle)) {
4727 return NO_ERROR;
4728 }
4729 // SW Bridge? (@todo: HW bridge, keep track of HwOutput for device selection "reconsideration")
4730 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
4731 ALOG_ASSERT(swOutput != nullptr, "%s: a swOutput shall always be associated", __func__);
4732 if (swOutput->getClient(sourceDesc->portId()) != nullptr) {
4733 ALOGW("%s source portId has already been attached to outputDesc", __func__);
4734 goto FailurePatchAdded;
4735 }
4736 status = swOutput->start();
4737 if (status != NO_ERROR) {
4738 goto FailureSourceAdded;
4739 }
4740 swOutput->addClient(sourceDesc);
4741 status = startSource(swOutput, sourceDesc, &delayMs);
4742 if (status != NO_ERROR) {
4743 ALOGW("%s failed to start source, error %d", __FUNCTION__, status);
4744 goto FailureSourceActive;
4745 }
4746 if (delayMs != 0) {
4747 usleep(delayMs * 1000);
4748 }
4749 return NO_ERROR;
4750
4751FailureSourceActive:
4752 swOutput->stop();
4753 releaseOutput(sourceDesc->portId());
4754FailureSourceAdded:
4755 sourceDesc->setSwOutput(nullptr);
4756FailurePatchAdded:
4757 releaseAudioPatchInternal(handle);
4758 return INVALID_OPERATION;
4759}
4760
4761status_t AudioPolicyManager::createAudioPatchInternal(const struct audio_patch *patch,
4762 audio_patch_handle_t *handle,
4763 uid_t uid, uint32_t delayMs,
4764 const sp<SourceClientDescriptor>& sourceDesc)
4765{
4766 ALOGV("%s num sources %d num sinks %d", __func__, patch->num_sources, patch->num_sinks);
Eric Laurent6a94d692014-05-20 11:18:06 -07004767 sp<AudioPatch> patchDesc;
4768 ssize_t index = mAudioPatches.indexOfKey(*handle);
4769
François Gaffieafd4cea2019-11-18 15:50:22 +01004770 ALOGV("%s source id %d role %d type %d", __func__, patch->sources[0].id,
4771 patch->sources[0].role,
4772 patch->sources[0].type);
Eric Laurent874c42872014-08-08 15:13:39 -07004773#if LOG_NDEBUG == 0
4774 for (size_t i = 0; i < patch->num_sinks; i++) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004775 ALOGV("%s sink %zu: id %d role %d type %d", __func__ ,i, patch->sinks[i].id,
4776 patch->sinks[i].role,
4777 patch->sinks[i].type);
Eric Laurent874c42872014-08-08 15:13:39 -07004778 }
4779#endif
Eric Laurent6a94d692014-05-20 11:18:06 -07004780
4781 if (index >= 0) {
4782 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01004783 ALOGV("%s mUidCached %d patchDesc->mUid %d uid %d",
4784 __func__, mUidCached, patchDesc->getUid(), uid);
4785 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004786 return INVALID_OPERATION;
4787 }
4788 } else {
Glenn Kastena13cde92016-03-28 15:26:02 -07004789 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07004790 }
4791
4792 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004793 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004794 if (outputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004795 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004796 return BAD_VALUE;
4797 }
Eric Laurent84c70242014-06-23 08:46:27 -07004798 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
4799 outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004800 if (patchDesc != 0) {
4801 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004802 ALOGV("%s source id differs for patch current id %d new id %d",
4803 __func__, patchDesc->mPatch.sources[0].id, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004804 return BAD_VALUE;
4805 }
4806 }
Eric Laurent874c42872014-08-08 15:13:39 -07004807 DeviceVector devices;
4808 for (size_t i = 0; i < patch->num_sinks; i++) {
4809 // Only support mix to devices connection
4810 // TODO add support for mix to mix connection
4811 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004812 ALOGV("%s source mix but sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07004813 return INVALID_OPERATION;
4814 }
4815 sp<DeviceDescriptor> devDesc =
4816 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
4817 if (devDesc == 0) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004818 ALOGV("%s out device not found for id %d", __func__, patch->sinks[i].id);
Eric Laurent874c42872014-08-08 15:13:39 -07004819 return BAD_VALUE;
4820 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004821
François Gaffie11d30102018-11-02 16:09:09 +01004822 if (!outputDesc->mProfile->isCompatibleProfile(DeviceVector(devDesc),
Eric Laurent874c42872014-08-08 15:13:39 -07004823 patch->sources[0].sample_rate,
François Gaffie53615e22015-03-19 09:24:12 +01004824 NULL, // updatedSamplingRate
4825 patch->sources[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07004826 NULL, // updatedFormat
François Gaffie53615e22015-03-19 09:24:12 +01004827 patch->sources[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07004828 NULL, // updatedChannelMask
François Gaffie53615e22015-03-19 09:24:12 +01004829 AUDIO_OUTPUT_FLAG_NONE /*FIXME*/)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004830 ALOGV("%s profile not supported for device %08x", __func__, devDesc->type());
Eric Laurent874c42872014-08-08 15:13:39 -07004831 return INVALID_OPERATION;
4832 }
4833 devices.add(devDesc);
4834 }
4835 if (devices.size() == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004836 return INVALID_OPERATION;
4837 }
Eric Laurent874c42872014-08-08 15:13:39 -07004838
Eric Laurent6a94d692014-05-20 11:18:06 -07004839 // TODO: reconfigure output format and channels here
François Gaffieafd4cea2019-11-18 15:50:22 +01004840 ALOGV("%s setting device %s on output %d",
4841 __func__, dumpDeviceTypes(devices.types()).c_str(), outputDesc->mIoHandle);
François Gaffie11d30102018-11-02 16:09:09 +01004842 setOutputDevices(outputDesc, devices, true, 0, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004843 index = mAudioPatches.indexOfKey(*handle);
4844 if (index >= 0) {
4845 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004846 ALOGW("%s setOutputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004847 }
4848 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01004849 patchDesc->setUid(uid);
4850 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004851 } else {
François Gaffieafd4cea2019-11-18 15:50:22 +01004852 ALOGW("%s setOutputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004853 return INVALID_OPERATION;
4854 }
4855 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
4856 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
4857 // input device to input mix connection
Eric Laurent874c42872014-08-08 15:13:39 -07004858 // only one sink supported when connecting an input device to a mix
4859 if (patch->num_sinks > 1) {
4860 return INVALID_OPERATION;
4861 }
François Gaffie53615e22015-03-19 09:24:12 +01004862 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004863 if (inputDesc == NULL) {
4864 return BAD_VALUE;
4865 }
4866 if (patchDesc != 0) {
4867 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
4868 return BAD_VALUE;
4869 }
4870 }
François Gaffie11d30102018-11-02 16:09:09 +01004871 sp<DeviceDescriptor> device =
Eric Laurent6a94d692014-05-20 11:18:06 -07004872 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01004873 if (device == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004874 return BAD_VALUE;
4875 }
4876
François Gaffie11d30102018-11-02 16:09:09 +01004877 if (!inputDesc->mProfile->isCompatibleProfile(DeviceVector(device),
Eric Laurent275e8e92014-11-30 15:14:47 -08004878 patch->sinks[0].sample_rate,
4879 NULL, /*updatedSampleRate*/
4880 patch->sinks[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07004881 NULL, /*updatedFormat*/
Eric Laurent275e8e92014-11-30 15:14:47 -08004882 patch->sinks[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07004883 NULL, /*updatedChannelMask*/
Eric Laurent275e8e92014-11-30 15:14:47 -08004884 // FIXME for the parameter type,
4885 // and the NONE
4886 (audio_output_flags_t)
Glenn Kasten6a8ab052014-07-24 14:08:35 -07004887 AUDIO_INPUT_FLAG_NONE)) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004888 return INVALID_OPERATION;
4889 }
4890 // TODO: reconfigure output format and channels here
François Gaffieafd4cea2019-11-18 15:50:22 +01004891 ALOGV("%s setting device %s on output %d", __func__,
François Gaffie11d30102018-11-02 16:09:09 +01004892 device->toString().c_str(), inputDesc->mIoHandle);
4893 setInputDevice(inputDesc->mIoHandle, device, true, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004894 index = mAudioPatches.indexOfKey(*handle);
4895 if (index >= 0) {
4896 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004897 ALOGW("%s setInputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004898 }
4899 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01004900 patchDesc->setUid(uid);
4901 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004902 } else {
François Gaffieafd4cea2019-11-18 15:50:22 +01004903 ALOGW("%s setInputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004904 return INVALID_OPERATION;
4905 }
4906 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
4907 // device to device connection
4908 if (patchDesc != 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07004909 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004910 return BAD_VALUE;
4911 }
4912 }
François Gaffie11d30102018-11-02 16:09:09 +01004913 sp<DeviceDescriptor> srcDevice =
Eric Laurent6a94d692014-05-20 11:18:06 -07004914 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01004915 if (srcDevice == 0) {
Eric Laurent58f8eb72014-09-12 16:19:41 -07004916 return BAD_VALUE;
4917 }
Eric Laurent874c42872014-08-08 15:13:39 -07004918
Eric Laurent6a94d692014-05-20 11:18:06 -07004919 //update source and sink with our own data as the data passed in the patch may
4920 // be incomplete.
François Gaffieafd4cea2019-11-18 15:50:22 +01004921 PatchBuilder patchBuilder;
4922 audio_port_config sourcePortConfig = {};
Dean Wheatley8bee85a2021-02-10 16:02:23 +11004923
4924 // if first sink is to MSD, establish single MSD patch
4925 if (getMsdAudioOutDevices().contains(
4926 mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id))) {
4927 ALOGV("%s patching to MSD", __FUNCTION__);
4928 patchBuilder = buildMsdPatch(false /*msdIsSource*/, srcDevice);
4929 goto installPatch;
4930 }
4931
François Gaffieafd4cea2019-11-18 15:50:22 +01004932 srcDevice->toAudioPortConfig(&sourcePortConfig, &patch->sources[0]);
4933 patchBuilder.addSource(sourcePortConfig);
Eric Laurent6a94d692014-05-20 11:18:06 -07004934
Eric Laurent874c42872014-08-08 15:13:39 -07004935 for (size_t i = 0; i < patch->num_sinks; i++) {
4936 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004937 ALOGV("%s source device but one sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07004938 return INVALID_OPERATION;
4939 }
François Gaffie11d30102018-11-02 16:09:09 +01004940 sp<DeviceDescriptor> sinkDevice =
Eric Laurent874c42872014-08-08 15:13:39 -07004941 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
François Gaffie11d30102018-11-02 16:09:09 +01004942 if (sinkDevice == 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07004943 return BAD_VALUE;
4944 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004945 audio_port_config sinkPortConfig = {};
4946 sinkDevice->toAudioPortConfig(&sinkPortConfig, &patch->sinks[i]);
4947 patchBuilder.addSink(sinkPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07004948
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004949 // Whatever Sw or Hw bridge, we do attach an SwOutput to an Audio Source for
4950 // volume management purpose (tracking activity)
4951 // In case of Hw bridge, it is a Work Around. The mixPort used is the one declared
4952 // in config XML to reach the sink so that is can be declared as available.
4953 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurent78b07302022-10-07 16:20:34 +02004954 sp<SwAudioOutputDescriptor> outputDesc;
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004955 if (!sourceDesc->isInternal()) {
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004956 // take care of dynamic routing for SwOutput selection,
4957 audio_attributes_t attributes = sourceDesc->attributes();
4958 audio_stream_type_t stream = sourceDesc->stream();
4959 audio_attributes_t resultAttr;
4960 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
4961 config.sample_rate = sourceDesc->config().sample_rate;
François Gaffie2a24db42022-04-04 16:45:02 +02004962 audio_channel_mask_t sourceMask = sourceDesc->config().channel_mask;
4963 config.channel_mask =
4964 (audio_channel_mask_get_representation(sourceMask)
4965 == AUDIO_CHANNEL_REPRESENTATION_INDEX) ? sourceMask
4966 : audio_channel_mask_in_to_out(sourceMask);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004967 config.format = sourceDesc->config().format;
4968 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
4969 audio_port_handle_t selectedDeviceId = AUDIO_PORT_HANDLE_NONE;
4970 bool isRequestedDeviceForExclusiveUse = false;
4971 output_type_t outputType;
Eric Laurentb0a7bc92022-04-05 15:06:08 +02004972 bool isSpatialized;
jiabinc658e452022-10-21 20:52:21 +00004973 bool isBitPerfect;
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004974 getOutputForAttrInt(&resultAttr, &output, AUDIO_SESSION_NONE, &attributes,
4975 &stream, sourceDesc->uid(), &config, &flags,
4976 &selectedDeviceId, &isRequestedDeviceForExclusiveUse,
jiabinc658e452022-10-21 20:52:21 +00004977 nullptr, &outputType, &isSpatialized, &isBitPerfect);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004978 if (output == AUDIO_IO_HANDLE_NONE) {
4979 ALOGV("%s no output for device %s",
4980 __FUNCTION__, sinkDevice->toString().c_str());
4981 return INVALID_OPERATION;
4982 }
4983 outputDesc = mOutputs.valueFor(output);
4984 if (outputDesc->isDuplicated()) {
4985 ALOGE("%s output is duplicated", __func__);
4986 return INVALID_OPERATION;
4987 }
François Gaffie7e39df22022-04-26 12:48:49 +02004988 bool closeOutput = outputDesc->mDirectOpenCount != 0;
4989 sourceDesc->setSwOutput(outputDesc, closeOutput);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004990 } else {
4991 // Same for "raw patches" aka created from createAudioPatch API
4992 SortedVector<audio_io_handle_t> outputs =
4993 getOutputsForDevices(DeviceVector(sinkDevice), mOutputs);
4994 // if the sink device is reachable via an opened output stream, request to
4995 // go via this output stream by adding a second source to the patch
4996 // description
4997 output = selectOutput(outputs);
4998 if (output == AUDIO_IO_HANDLE_NONE) {
4999 ALOGE("%s no output available for internal patch sink", __func__);
5000 return INVALID_OPERATION;
5001 }
5002 outputDesc = mOutputs.valueFor(output);
5003 if (outputDesc->isDuplicated()) {
5004 ALOGV("%s output for device %s is duplicated",
5005 __func__, sinkDevice->toString().c_str());
5006 return INVALID_OPERATION;
5007 }
François Gaffie7e39df22022-04-26 12:48:49 +02005008 sourceDesc->setSwOutput(outputDesc, /* closeOutput= */ false);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005009 }
Eric Laurent3bcf8592015-04-03 12:13:24 -07005010 // create a software bridge in PatchPanel if:
Scott Randolphf3172402018-01-23 17:06:53 -08005011 // - source and sink devices are on different HW modules OR
Eric Laurent3bcf8592015-04-03 12:13:24 -07005012 // - audio HAL version is < 3.0
Francois Gaffie99896da2018-04-09 11:05:33 +02005013 // - audio HAL version is >= 3.0 but no route has been declared between devices
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005014 // - called from startAudioSource (aka sourceDesc is not internal) and source device
5015 // does not have a gain controller
François Gaffie11d30102018-11-02 16:09:09 +01005016 if (!srcDevice->hasSameHwModuleAs(sinkDevice) ||
5017 (srcDevice->getModuleVersionMajor() < 3) ||
François Gaffieafd4cea2019-11-18 15:50:22 +01005018 !srcDevice->getModule()->supportsPatch(srcDevice, sinkDevice) ||
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005019 (!sourceDesc->isInternal() &&
François Gaffieafd4cea2019-11-18 15:50:22 +01005020 srcDevice->getAudioPort()->getGains().size() == 0)) {
Eric Laurent3bcf8592015-04-03 12:13:24 -07005021 // support only one sink device for now to simplify output selection logic
Eric Laurent874c42872014-08-08 15:13:39 -07005022 if (patch->num_sinks > 1) {
Eric Laurent83b88082014-06-20 18:31:16 -07005023 return INVALID_OPERATION;
5024 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005025 sourceDesc->setUseSwBridge();
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005026 if (outputDesc != nullptr) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005027 audio_port_config srcMixPortConfig = {};
Ytai Ben-Tsvic9d2a912021-11-22 16:43:09 -08005028 outputDesc->toAudioPortConfig(&srcMixPortConfig, nullptr);
François Gaffieafd4cea2019-11-18 15:50:22 +01005029 // for volume control, we may need a valid stream
Eric Laurent78b07302022-10-07 16:20:34 +02005030 srcMixPortConfig.ext.mix.usecase.stream =
5031 (!sourceDesc->isInternal() || isCallTxAudioSource(sourceDesc)) ?
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005032 mEngine->getStreamTypeForAttributes(sourceDesc->attributes()) :
5033 AUDIO_STREAM_PATCH;
François Gaffieafd4cea2019-11-18 15:50:22 +01005034 patchBuilder.addSource(srcMixPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07005035 }
Eric Laurent83b88082014-06-20 18:31:16 -07005036 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005037 }
5038 // TODO: check from routing capabilities in config file and other conflicting patches
5039
Dean Wheatley8bee85a2021-02-10 16:02:23 +11005040installPatch:
François Gaffieafd4cea2019-11-18 15:50:22 +01005041 status_t status = installPatch(
5042 __func__, index, handle, patchBuilder.patch(), delayMs, uid, &patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07005043 if (status != NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005044 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
Eric Laurent6a94d692014-05-20 11:18:06 -07005045 return INVALID_OPERATION;
5046 }
5047 } else {
5048 return BAD_VALUE;
5049 }
5050 } else {
5051 return BAD_VALUE;
5052 }
5053 return NO_ERROR;
5054}
5055
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005056status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle, uid_t uid)
Eric Laurent6a94d692014-05-20 11:18:06 -07005057{
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005058 ALOGV("%s patch %d", __func__, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005059 ssize_t index = mAudioPatches.indexOfKey(handle);
5060
5061 if (index < 0) {
5062 return BAD_VALUE;
5063 }
5064 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005065 ALOGV("%s() mUidCached %d patchDesc->mUid %d uid %d",
5066 __func__, mUidCached, patchDesc->getUid(), uid);
5067 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005068 return INVALID_OPERATION;
5069 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005070 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
5071 for (size_t i = 0; i < mAudioSources.size(); i++) {
5072 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
5073 if (sourceDesc != nullptr && sourceDesc->getPatchHandle() == handle) {
5074 portId = sourceDesc->portId();
5075 break;
5076 }
5077 }
5078 return portId != AUDIO_PORT_HANDLE_NONE ?
5079 stopAudioSource(portId) : releaseAudioPatchInternal(handle);
François Gaffieafd4cea2019-11-18 15:50:22 +01005080}
Eric Laurent6a94d692014-05-20 11:18:06 -07005081
François Gaffieafd4cea2019-11-18 15:50:22 +01005082status_t AudioPolicyManager::releaseAudioPatchInternal(audio_patch_handle_t handle,
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005083 uint32_t delayMs,
5084 const sp<SourceClientDescriptor>& sourceDesc)
François Gaffieafd4cea2019-11-18 15:50:22 +01005085{
5086 ALOGV("%s patch %d", __func__, handle);
5087 if (mAudioPatches.indexOfKey(handle) < 0) {
5088 ALOGE("%s: no patch found with handle=%d", __func__, handle);
5089 return BAD_VALUE;
5090 }
5091 sp<AudioPatch> patchDesc = mAudioPatches.valueFor(handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005092 struct audio_patch *patch = &patchDesc->mPatch;
François Gaffieafd4cea2019-11-18 15:50:22 +01005093 patchDesc->setUid(mUidCached);
Eric Laurent6a94d692014-05-20 11:18:06 -07005094 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005095 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005096 if (outputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005097 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005098 return BAD_VALUE;
5099 }
5100
François Gaffie11d30102018-11-02 16:09:09 +01005101 setOutputDevices(outputDesc,
5102 getNewOutputDevices(outputDesc, true /*fromCache*/),
5103 true,
5104 0,
5105 NULL);
Eric Laurent6a94d692014-05-20 11:18:06 -07005106 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
5107 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
François Gaffie53615e22015-03-19 09:24:12 +01005108 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005109 if (inputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005110 ALOGV("%s input not found for id %d", __func__, patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005111 return BAD_VALUE;
5112 }
5113 setInputDevice(inputDesc->mIoHandle,
Eric Laurentfb66dd92016-01-28 18:32:03 -08005114 getNewInputDevice(inputDesc),
Eric Laurent6a94d692014-05-20 11:18:06 -07005115 true,
5116 NULL);
5117 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005118 status_t status =
5119 mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
5120 ALOGV("%s patch panel returned %d patchHandle %d",
5121 __func__, status, patchDesc->getAfHandle());
5122 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005123 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005124 mpClientInterface->onAudioPatchListUpdate();
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005125 // SW or HW Bridge
5126 sp<SwAudioOutputDescriptor> outputDesc = nullptr;
5127 audio_patch_handle_t patchHandle = AUDIO_PATCH_HANDLE_NONE;
Francois Gaffie7feb8542020-04-06 17:39:47 +02005128 if (patch->num_sources > 1 && patch->sources[1].type == AUDIO_PORT_TYPE_MIX) {
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005129 outputDesc = mOutputs.getOutputFromId(patch->sources[1].id);
5130 } else if (patch->num_sources == 1 && sourceDesc != nullptr) {
5131 outputDesc = sourceDesc->swOutput().promote();
5132 }
5133 if (outputDesc == nullptr) {
5134 ALOGW("%s no output for id %d", __func__, patch->sources[0].id);
5135 // releaseOutput has already called closeOutput in case of direct output
5136 return NO_ERROR;
5137 }
François Gaffie7e39df22022-04-26 12:48:49 +02005138 patchHandle = outputDesc->getPatchHandle();
5139 // When a Sw bridge is released, the mixer used by this bridge will release its
5140 // patch at AudioFlinger side. Hence, the mixer audio patch must be recreated
5141 // Reuse patch handle to force audio flinger removing initial mixer patch removal
5142 // updating hal patch handle (prevent leaks).
5143 // While using a HwBridge, force reconsidering device only if not reusing an existing
5144 // output and no more activity on output (will force to close).
5145 bool force = sourceDesc->useSwBridge() ||
5146 (sourceDesc->canCloseOutput() && !outputDesc->isActive());
5147 // APM pattern is to have always outputs opened / patch realized for reachable devices.
5148 // Update device may result to NONE (empty), coupled with force, it releases the patch.
5149 // Reconsider device only for cases:
5150 // 1 / Active Output
5151 // 2 / Inactive Output previously hosting HwBridge
5152 // 3 / Inactive Output previously hosting SwBridge that can be closed.
5153 bool updateDevice = outputDesc->isActive() || !sourceDesc->useSwBridge() ||
5154 sourceDesc->canCloseOutput();
5155 setOutputDevices(outputDesc,
5156 updateDevice ? getNewOutputDevices(outputDesc, true /*fromCache*/) :
5157 outputDesc->devices(),
5158 force,
5159 0,
5160 patchHandle == AUDIO_PATCH_HANDLE_NONE ? nullptr : &patchHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005161 } else {
5162 return BAD_VALUE;
5163 }
5164 } else {
5165 return BAD_VALUE;
5166 }
5167 return NO_ERROR;
5168}
5169
5170status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
5171 struct audio_patch *patches,
5172 unsigned int *generation)
5173{
François Gaffie53615e22015-03-19 09:24:12 +01005174 if (generation == NULL) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005175 return BAD_VALUE;
5176 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005177 *generation = curAudioPortGeneration();
François Gaffie53615e22015-03-19 09:24:12 +01005178 return mAudioPatches.listAudioPatches(num_patches, patches);
Eric Laurent6a94d692014-05-20 11:18:06 -07005179}
5180
Eric Laurente1715a42014-05-20 11:30:42 -07005181status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07005182{
Eric Laurente1715a42014-05-20 11:30:42 -07005183 ALOGV("setAudioPortConfig()");
5184
5185 if (config == NULL) {
5186 return BAD_VALUE;
5187 }
5188 ALOGV("setAudioPortConfig() on port handle %d", config->id);
5189 // Only support gain configuration for now
Eric Laurenta121f902014-06-03 13:32:54 -07005190 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
5191 return INVALID_OPERATION;
Eric Laurente1715a42014-05-20 11:30:42 -07005192 }
5193
Eric Laurenta121f902014-06-03 13:32:54 -07005194 sp<AudioPortConfig> audioPortConfig;
Eric Laurente1715a42014-05-20 11:30:42 -07005195 if (config->type == AUDIO_PORT_TYPE_MIX) {
5196 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005197 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07005198 if (outputDesc == NULL) {
5199 return BAD_VALUE;
5200 }
Eric Laurent84c70242014-06-23 08:46:27 -07005201 ALOG_ASSERT(!outputDesc->isDuplicated(),
5202 "setAudioPortConfig() called on duplicated output %d",
5203 outputDesc->mIoHandle);
Eric Laurenta121f902014-06-03 13:32:54 -07005204 audioPortConfig = outputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07005205 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
François Gaffie53615e22015-03-19 09:24:12 +01005206 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07005207 if (inputDesc == NULL) {
5208 return BAD_VALUE;
5209 }
Eric Laurenta121f902014-06-03 13:32:54 -07005210 audioPortConfig = inputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07005211 } else {
5212 return BAD_VALUE;
5213 }
5214 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
5215 sp<DeviceDescriptor> deviceDesc;
5216 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
5217 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
5218 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
5219 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
5220 } else {
5221 return BAD_VALUE;
5222 }
5223 if (deviceDesc == NULL) {
5224 return BAD_VALUE;
5225 }
Eric Laurenta121f902014-06-03 13:32:54 -07005226 audioPortConfig = deviceDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07005227 } else {
5228 return BAD_VALUE;
5229 }
5230
Mikhail Naganov7be71d22018-05-23 16:51:46 -07005231 struct audio_port_config backupConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07005232 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
5233 if (status == NO_ERROR) {
Mikhail Naganov7be71d22018-05-23 16:51:46 -07005234 struct audio_port_config newConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07005235 audioPortConfig->toAudioPortConfig(&newConfig, config);
5236 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
Eric Laurente1715a42014-05-20 11:30:42 -07005237 }
Eric Laurenta121f902014-06-03 13:32:54 -07005238 if (status != NO_ERROR) {
5239 audioPortConfig->applyAudioPortConfig(&backupConfig);
Eric Laurente1715a42014-05-20 11:30:42 -07005240 }
Eric Laurente1715a42014-05-20 11:30:42 -07005241
5242 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07005243}
5244
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005245void AudioPolicyManager::releaseResourcesForUid(uid_t uid)
5246{
Eric Laurentd60560a2015-04-10 11:31:20 -07005247 clearAudioSources(uid);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005248 clearAudioPatches(uid);
5249 clearSessionRoutes(uid);
5250}
5251
Eric Laurent6a94d692014-05-20 11:18:06 -07005252void AudioPolicyManager::clearAudioPatches(uid_t uid)
5253{
Eric Laurent0add0fd2014-12-04 18:58:14 -08005254 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005255 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
François Gaffieafd4cea2019-11-18 15:50:22 +01005256 if (patchDesc->getUid() == uid) {
Eric Laurent0add0fd2014-12-04 18:58:14 -08005257 releaseAudioPatch(mAudioPatches.keyAt(i), uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07005258 }
5259 }
5260}
5261
François Gaffiec005e562018-11-06 15:04:49 +01005262void AudioPolicyManager::checkStrategyRoute(product_strategy_t ps, audio_io_handle_t ouptutToSkip)
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005263{
François Gaffiec005e562018-11-06 15:04:49 +01005264 // Take the first attributes following the product strategy as it is used to retrieve the routed
5265 // device. All attributes wihin a strategy follows the same "routing strategy"
5266 auto attributes = mEngine->getAllAttributesForProductStrategy(ps).front();
5267 DeviceVector devices = mEngine->getOutputDevicesForAttributes(attributes, nullptr, false);
François Gaffie11d30102018-11-02 16:09:09 +01005268 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
jiabin3ff8d7d2022-12-13 06:27:44 +00005269 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005270 for (size_t j = 0; j < mOutputs.size(); j++) {
5271 if (mOutputs.keyAt(j) == ouptutToSkip) {
5272 continue;
5273 }
5274 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(j);
François Gaffiec005e562018-11-06 15:04:49 +01005275 if (!outputDesc->isStrategyActive(ps)) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005276 continue;
5277 }
5278 // If the default device for this strategy is on another output mix,
5279 // invalidate all tracks in this strategy to force re connection.
5280 // Otherwise select new device on the output mix.
5281 if (outputs.indexOf(mOutputs.keyAt(j)) < 0) {
jiabinc44b3462022-12-08 12:52:31 -08005282 invalidateStreams(mEngine->getStreamTypesForProductStrategy(ps));
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005283 } else {
jiabin3ff8d7d2022-12-13 06:27:44 +00005284 DeviceVector newDevices = getNewOutputDevices(outputDesc, false /*fromCache*/);
5285 if (outputDesc->mUsePreferredMixerAttributes && outputDesc->devices() != newDevices) {
5286 // If the device is using preferred mixer attributes, the output need to reopen
5287 // with default configuration when the new selected devices are different from
5288 // current routing devices.
5289 outputsToReopen.emplace(mOutputs.keyAt(j), newDevices);
5290 continue;
5291 }
5292 setOutputDevices(outputDesc, newDevices, false);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005293 }
5294 }
jiabin3ff8d7d2022-12-13 06:27:44 +00005295 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005296}
5297
5298void AudioPolicyManager::clearSessionRoutes(uid_t uid)
5299{
5300 // remove output routes associated with this uid
François Gaffiec005e562018-11-06 15:04:49 +01005301 std::vector<product_strategy_t> affectedStrategies;
Eric Laurent97ac8712018-07-27 18:59:02 -07005302 for (size_t i = 0; i < mOutputs.size(); i++) {
5303 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07005304 for (const auto& client : outputDesc->getClientIterable()) {
5305 if (client->hasPreferredDevice() && client->uid() == uid) {
5306 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
François Gaffiec005e562018-11-06 15:04:49 +01005307 auto clientStrategy = client->strategy();
5308 if (std::find(begin(affectedStrategies), end(affectedStrategies), clientStrategy) !=
5309 end(affectedStrategies)) {
5310 continue;
5311 }
5312 affectedStrategies.push_back(client->strategy());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005313 }
5314 }
5315 }
5316 // reroute outputs if necessary
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005317 for (const auto& strategy : affectedStrategies) {
5318 checkStrategyRoute(strategy, AUDIO_IO_HANDLE_NONE);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005319 }
5320
5321 // remove input routes associated with this uid
5322 SortedVector<audio_source_t> affectedSources;
Eric Laurent97ac8712018-07-27 18:59:02 -07005323 for (size_t i = 0; i < mInputs.size(); i++) {
5324 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07005325 for (const auto& client : inputDesc->getClientIterable()) {
5326 if (client->hasPreferredDevice() && client->uid() == uid) {
5327 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
5328 affectedSources.add(client->source());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005329 }
5330 }
5331 }
5332 // reroute inputs if necessary
5333 SortedVector<audio_io_handle_t> inputsToClose;
5334 for (size_t i = 0; i < mInputs.size(); i++) {
5335 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Eric Laurent4eb58f12018-12-07 16:41:02 -08005336 if (affectedSources.indexOf(inputDesc->source()) >= 0) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005337 inputsToClose.add(inputDesc->mIoHandle);
5338 }
5339 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005340 for (const auto& input : inputsToClose) {
5341 closeInput(input);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005342 }
5343}
5344
Eric Laurentd60560a2015-04-10 11:31:20 -07005345void AudioPolicyManager::clearAudioSources(uid_t uid)
5346{
5347 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005348 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
5349 if (sourceDesc->uid() == uid) {
Eric Laurentd60560a2015-04-10 11:31:20 -07005350 stopAudioSource(mAudioSources.keyAt(i));
5351 }
5352 }
5353}
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005354
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005355status_t AudioPolicyManager::acquireSoundTriggerSession(audio_session_t *session,
5356 audio_io_handle_t *ioHandle,
5357 audio_devices_t *device)
5358{
Glenn Kastenf0c6d7d2016-02-26 10:44:04 -08005359 *session = (audio_session_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
5360 *ioHandle = (audio_io_handle_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
Francois Gaffie716e1432019-01-14 16:58:59 +01005361 audio_attributes_t attr = { .source = AUDIO_SOURCE_HOTWORD };
Eric Laurentcedd5b52023-03-22 00:03:31 +00005362 sp<DeviceDescriptor> deviceDesc = mEngine->getInputDeviceForAttributes(attr);
5363 if (deviceDesc == nullptr) {
5364 return INVALID_OPERATION;
5365 }
5366 *device = deviceDesc->type();
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005367
François Gaffiedf372692015-03-19 10:43:27 +01005368 return mSoundTriggerSessions.acquireSession(*session, *ioHandle);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005369}
5370
Eric Laurentd60560a2015-04-10 11:31:20 -07005371status_t AudioPolicyManager::startAudioSource(const struct audio_port_config *source,
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005372 const audio_attributes_t *attributes,
5373 audio_port_handle_t *portId,
5374 uid_t uid)
Eric Laurent554a2772015-04-10 11:29:24 -07005375{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005376 ALOGV("%s", __FUNCTION__);
5377 *portId = AUDIO_PORT_HANDLE_NONE;
5378
5379 if (source == NULL || attributes == NULL || portId == NULL) {
5380 ALOGW("%s invalid argument: source %p attributes %p handle %p",
5381 __FUNCTION__, source, attributes, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005382 return BAD_VALUE;
5383 }
5384
Eric Laurentd60560a2015-04-10 11:31:20 -07005385 if (source->role != AUDIO_PORT_ROLE_SOURCE ||
5386 source->type != AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005387 ALOGW("%s INVALID_OPERATION source->role %d source->type %d",
5388 __FUNCTION__, source->role, source->type);
Eric Laurentd60560a2015-04-10 11:31:20 -07005389 return INVALID_OPERATION;
5390 }
5391
François Gaffie11d30102018-11-02 16:09:09 +01005392 sp<DeviceDescriptor> srcDevice =
Eric Laurentd60560a2015-04-10 11:31:20 -07005393 mAvailableInputDevices.getDevice(source->ext.device.type,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005394 String8(source->ext.device.address),
5395 AUDIO_FORMAT_DEFAULT);
François Gaffie11d30102018-11-02 16:09:09 +01005396 if (srcDevice == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005397 ALOGW("%s source->ext.device.type %08x not found", __FUNCTION__, source->ext.device.type);
Eric Laurentd60560a2015-04-10 11:31:20 -07005398 return BAD_VALUE;
5399 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005400
jiabin4ef93452019-09-10 14:29:54 -07005401 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurentd60560a2015-04-10 11:31:20 -07005402
François Gaffieaaac0fd2018-11-22 17:56:39 +01005403 sp<SourceClientDescriptor> sourceDesc =
François Gaffieafd4cea2019-11-18 15:50:22 +01005404 new SourceClientDescriptor(*portId, uid, *attributes, *source, srcDevice,
François Gaffieaaac0fd2018-11-22 17:56:39 +01005405 mEngine->getStreamTypeForAttributes(*attributes),
5406 mEngine->getProductStrategyForAttributes(*attributes),
5407 toVolumeSource(*attributes));
Eric Laurentd60560a2015-04-10 11:31:20 -07005408
5409 status_t status = connectAudioSource(sourceDesc);
5410 if (status == NO_ERROR) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005411 mAudioSources.add(*portId, sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07005412 }
5413 return status;
5414}
5415
Francois Gaffie601801d2021-06-22 13:27:39 +02005416sp<SourceClientDescriptor> AudioPolicyManager::startAudioSourceInternal(
5417 const struct audio_port_config *source, const audio_attributes_t *attributes, uid_t uid)
5418{
5419 ALOGV("%s", __FUNCTION__);
5420 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
5421
5422 status_t status = startAudioSource(source, attributes, &portId, uid);
5423 ALOGE_IF(status != OK, "%s: failed to start audio source (%d)", __func__, status);
5424 return mAudioSources.valueFor(portId);
5425}
5426
5427
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005428status_t AudioPolicyManager::connectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07005429{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005430 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->portId());
Eric Laurentd60560a2015-04-10 11:31:20 -07005431
5432 // make sure we only have one patch per source.
5433 disconnectAudioSource(sourceDesc);
5434
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005435 audio_attributes_t attributes = sourceDesc->attributes();
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005436 // May the device (dynamic) have been disconnected/reconnected, id has changed.
5437 sp<DeviceDescriptor> srcDevice = mAvailableInputDevices.getDevice(
5438 sourceDesc->srcDevice()->type(),
5439 String8(sourceDesc->srcDevice()->address().c_str()),
5440 AUDIO_FORMAT_DEFAULT);
François Gaffiec005e562018-11-06 15:04:49 +01005441 DeviceVector sinkDevices =
Francois Gaffieff1eb522020-05-06 18:37:04 +02005442 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false /*fromCache*/);
François Gaffiec005e562018-11-06 15:04:49 +01005443 ALOG_ASSERT(!sinkDevices.isEmpty(), "connectAudioSource(): no device found for attributes");
François Gaffie11d30102018-11-02 16:09:09 +01005444 sp<DeviceDescriptor> sinkDevice = sinkDevices.itemAt(0);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005445 if (!mAvailableOutputDevices.contains(sinkDevice)) {
5446 ALOGE("%s Device %s not available", __func__, sinkDevice->toString().c_str());
5447 return INVALID_OPERATION;
5448 }
François Gaffieafd4cea2019-11-18 15:50:22 +01005449 PatchBuilder patchBuilder;
5450 patchBuilder.addSink(sinkDevice).addSource(srcDevice);
5451 audio_patch_handle_t handle = AUDIO_PATCH_HANDLE_NONE;
François Gaffieafd4cea2019-11-18 15:50:22 +01005452
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005453 return connectAudioSourceToSink(
5454 sourceDesc, sinkDevice, patchBuilder.patch(), handle, mUidCached, 0 /*delayMs*/);
Eric Laurent554a2772015-04-10 11:29:24 -07005455}
5456
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005457status_t AudioPolicyManager::stopAudioSource(audio_port_handle_t portId)
Eric Laurent554a2772015-04-10 11:29:24 -07005458{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005459 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueFor(portId);
5460 ALOGV("%s port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005461 if (sourceDesc == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005462 ALOGW("%s unknown source for port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005463 return BAD_VALUE;
5464 }
5465 status_t status = disconnectAudioSource(sourceDesc);
5466
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005467 mAudioSources.removeItem(portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005468 return status;
5469}
5470
Andy Hung2ddee192015-12-18 17:34:44 -08005471status_t AudioPolicyManager::setMasterMono(bool mono)
5472{
5473 if (mMasterMono == mono) {
5474 return NO_ERROR;
5475 }
5476 mMasterMono = mono;
5477 // if enabling mono we close all offloaded devices, which will invalidate the
5478 // corresponding AudioTrack. The AudioTrack client/MediaPlayer is responsible
5479 // for recreating the new AudioTrack as non-offloaded PCM.
5480 //
5481 // If disabling mono, we leave all tracks as is: we don't know which clients
5482 // and tracks are able to be recreated as offloaded. The next "song" should
5483 // play back offloaded.
5484 if (mMasterMono) {
5485 Vector<audio_io_handle_t> offloaded;
5486 for (size_t i = 0; i < mOutputs.size(); ++i) {
5487 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
5488 if (desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
5489 offloaded.push(desc->mIoHandle);
5490 }
5491 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005492 for (const auto& handle : offloaded) {
5493 closeOutput(handle);
Andy Hung2ddee192015-12-18 17:34:44 -08005494 }
5495 }
5496 // update master mono for all remaining outputs
5497 for (size_t i = 0; i < mOutputs.size(); ++i) {
5498 updateMono(mOutputs.keyAt(i));
5499 }
5500 return NO_ERROR;
5501}
5502
5503status_t AudioPolicyManager::getMasterMono(bool *mono)
5504{
5505 *mono = mMasterMono;
5506 return NO_ERROR;
5507}
5508
Eric Laurentac9cef52017-06-09 15:46:26 -07005509float AudioPolicyManager::getStreamVolumeDB(
5510 audio_stream_type_t stream, int index, audio_devices_t device)
5511{
jiabin9a3361e2019-10-01 09:38:30 -07005512 return computeVolume(getVolumeCurves(stream), toVolumeSource(stream), index, {device});
Eric Laurentac9cef52017-06-09 15:46:26 -07005513}
5514
jiabin81772902018-04-02 17:52:27 -07005515status_t AudioPolicyManager::getSurroundFormats(unsigned int *numSurroundFormats,
5516 audio_format_t *surroundFormats,
Kriti Dang6537def2021-03-02 13:46:59 +01005517 bool *surroundFormatsEnabled)
jiabin81772902018-04-02 17:52:27 -07005518{
Kriti Dang6537def2021-03-02 13:46:59 +01005519 if (numSurroundFormats == nullptr || (*numSurroundFormats != 0 &&
5520 (surroundFormats == nullptr || surroundFormatsEnabled == nullptr))) {
jiabin81772902018-04-02 17:52:27 -07005521 return BAD_VALUE;
5522 }
Kriti Dang6537def2021-03-02 13:46:59 +01005523 ALOGV("%s() numSurroundFormats %d surroundFormats %p surroundFormatsEnabled %p",
5524 __func__, *numSurroundFormats, surroundFormats, surroundFormatsEnabled);
jiabin81772902018-04-02 17:52:27 -07005525
5526 size_t formatsWritten = 0;
5527 size_t formatsMax = *numSurroundFormats;
Kriti Dangef6be8f2020-11-05 11:58:19 +01005528
Kriti Dang6537def2021-03-02 13:46:59 +01005529 *numSurroundFormats = mConfig.getSurroundFormats().size();
Mikhail Naganov100f0122018-11-29 11:22:16 -08005530 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
5531 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Kriti Dang6537def2021-03-02 13:46:59 +01005532 for (const auto& format: mConfig.getSurroundFormats()) {
jiabin81772902018-04-02 17:52:27 -07005533 if (formatsWritten < formatsMax) {
Kriti Dang6537def2021-03-02 13:46:59 +01005534 surroundFormats[formatsWritten] = format.first;
Mikhail Naganov100f0122018-11-29 11:22:16 -08005535 bool formatEnabled = true;
5536 switch (forceUse) {
5537 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL:
Kriti Dang6537def2021-03-02 13:46:59 +01005538 formatEnabled = mManualSurroundFormats.count(format.first) != 0;
Mikhail Naganov100f0122018-11-29 11:22:16 -08005539 break;
5540 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER:
5541 formatEnabled = false;
5542 break;
5543 default: // AUTO or ALWAYS => true
5544 break;
jiabin81772902018-04-02 17:52:27 -07005545 }
5546 surroundFormatsEnabled[formatsWritten++] = formatEnabled;
5547 }
jiabin81772902018-04-02 17:52:27 -07005548 }
5549 return NO_ERROR;
5550}
5551
Kriti Dang6537def2021-03-02 13:46:59 +01005552status_t AudioPolicyManager::getReportedSurroundFormats(unsigned int *numSurroundFormats,
5553 audio_format_t *surroundFormats) {
5554 if (numSurroundFormats == nullptr || (*numSurroundFormats != 0 && surroundFormats == nullptr)) {
5555 return BAD_VALUE;
5556 }
5557 ALOGV("%s() numSurroundFormats %d surroundFormats %p",
5558 __func__, *numSurroundFormats, surroundFormats);
5559
5560 size_t formatsWritten = 0;
5561 size_t formatsMax = *numSurroundFormats;
5562 std::unordered_set<audio_format_t> formats; // Uses primary surround formats only
5563
5564 // Return formats from all device profiles that have already been resolved by
5565 // checkOutputsForDevice().
5566 for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
5567 sp<DeviceDescriptor> device = mAvailableOutputDevices[i];
5568 audio_devices_t deviceType = device->type();
5569 // Enabling/disabling formats are applied to only HDMI devices. So, this function
5570 // returns formats reported by HDMI devices.
5571 if (deviceType != AUDIO_DEVICE_OUT_HDMI) {
5572 continue;
5573 }
5574 // Formats reported by sink devices
5575 std::unordered_set<audio_format_t> formatset;
5576 if (auto it = mReportedFormatsMap.find(device); it != mReportedFormatsMap.end()) {
5577 formatset.insert(it->second.begin(), it->second.end());
5578 }
5579
5580 // Formats hard-coded in the in policy configuration file (if any).
5581 FormatVector encodedFormats = device->encodedFormats();
5582 formatset.insert(encodedFormats.begin(), encodedFormats.end());
5583 // Filter the formats which are supported by the vendor hardware.
5584 for (auto it = formatset.begin(); it != formatset.end(); ++it) {
5585 if (mConfig.getSurroundFormats().count(*it) != 0) {
5586 formats.insert(*it);
5587 } else {
5588 for (const auto& pair : mConfig.getSurroundFormats()) {
5589 if (pair.second.count(*it) != 0) {
5590 formats.insert(pair.first);
5591 break;
5592 }
5593 }
5594 }
5595 }
5596 }
5597 *numSurroundFormats = formats.size();
5598 for (const auto& format: formats) {
5599 if (formatsWritten < formatsMax) {
5600 surroundFormats[formatsWritten++] = format;
5601 }
5602 }
5603 return NO_ERROR;
5604}
5605
jiabin81772902018-04-02 17:52:27 -07005606status_t AudioPolicyManager::setSurroundFormatEnabled(audio_format_t audioFormat, bool enabled)
5607{
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005608 ALOGV("%s() format 0x%X enabled %d", __func__, audioFormat, enabled);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07005609 const auto& formatIter = mConfig.getSurroundFormats().find(audioFormat);
5610 if (formatIter == mConfig.getSurroundFormats().end()) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005611 ALOGW("%s() format 0x%X is not a known surround format", __func__, audioFormat);
jiabin81772902018-04-02 17:52:27 -07005612 return BAD_VALUE;
5613 }
5614
Mikhail Naganov100f0122018-11-29 11:22:16 -08005615 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND) !=
5616 AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005617 ALOGW("%s() not in manual mode for surround sound format selection", __func__);
jiabin81772902018-04-02 17:52:27 -07005618 return INVALID_OPERATION;
5619 }
5620
Mikhail Naganov100f0122018-11-29 11:22:16 -08005621 if ((mManualSurroundFormats.count(audioFormat) != 0) == enabled) {
jiabin81772902018-04-02 17:52:27 -07005622 return NO_ERROR;
5623 }
5624
Mikhail Naganov100f0122018-11-29 11:22:16 -08005625 std::unordered_set<audio_format_t> surroundFormatsBackup(mManualSurroundFormats);
jiabin81772902018-04-02 17:52:27 -07005626 if (enabled) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005627 mManualSurroundFormats.insert(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07005628 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005629 mManualSurroundFormats.insert(subFormat);
jiabin81772902018-04-02 17:52:27 -07005630 }
5631 } else {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005632 mManualSurroundFormats.erase(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07005633 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005634 mManualSurroundFormats.erase(subFormat);
jiabin81772902018-04-02 17:52:27 -07005635 }
5636 }
5637
5638 sp<SwAudioOutputDescriptor> outputDesc;
5639 bool profileUpdated = false;
jiabin9a3361e2019-10-01 09:38:30 -07005640 DeviceVector hdmiOutputDevices = mAvailableOutputDevices.getDevicesFromType(
5641 AUDIO_DEVICE_OUT_HDMI);
jiabin81772902018-04-02 17:52:27 -07005642 for (size_t i = 0; i < hdmiOutputDevices.size(); i++) {
5643 // Simulate reconnection to update enabled surround sound formats.
jiabince9f20e2019-09-12 16:29:15 -07005644 String8 address = String8(hdmiOutputDevices[i]->address().c_str());
jiabin5740f082019-08-19 15:08:30 -07005645 std::string name = hdmiOutputDevices[i]->getName();
jiabin81772902018-04-02 17:52:27 -07005646 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
5647 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
5648 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005649 name.c_str(),
5650 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005651 if (status != NO_ERROR) {
5652 continue;
5653 }
5654 status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
5655 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
5656 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005657 name.c_str(),
5658 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005659 profileUpdated |= (status == NO_ERROR);
5660 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08005661 // FIXME: Why doing this for input HDMI devices if we don't augment their reported formats?
jiabin9a3361e2019-10-01 09:38:30 -07005662 DeviceVector hdmiInputDevices = mAvailableInputDevices.getDevicesFromType(
jiabin81772902018-04-02 17:52:27 -07005663 AUDIO_DEVICE_IN_HDMI);
5664 for (size_t i = 0; i < hdmiInputDevices.size(); i++) {
5665 // Simulate reconnection to update enabled surround sound formats.
jiabince9f20e2019-09-12 16:29:15 -07005666 String8 address = String8(hdmiInputDevices[i]->address().c_str());
jiabin5740f082019-08-19 15:08:30 -07005667 std::string name = hdmiInputDevices[i]->getName();
jiabin81772902018-04-02 17:52:27 -07005668 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
5669 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
5670 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005671 name.c_str(),
5672 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005673 if (status != NO_ERROR) {
5674 continue;
5675 }
5676 status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
5677 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
5678 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005679 name.c_str(),
5680 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005681 profileUpdated |= (status == NO_ERROR);
5682 }
5683
jiabin81772902018-04-02 17:52:27 -07005684 if (!profileUpdated) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005685 ALOGW("%s() no audio profiles updated, undoing surround formats change", __func__);
Mikhail Naganov100f0122018-11-29 11:22:16 -08005686 mManualSurroundFormats = std::move(surroundFormatsBackup);
jiabin81772902018-04-02 17:52:27 -07005687 }
5688
5689 return profileUpdated ? NO_ERROR : INVALID_OPERATION;
5690}
5691
Eric Laurent5ada82e2019-08-29 17:53:54 -07005692void AudioPolicyManager::setAppState(audio_port_handle_t portId, app_state_t state)
Svet Ganovf4ddfef2018-01-16 07:37:58 -08005693{
Eric Laurent5ada82e2019-08-29 17:53:54 -07005694 ALOGV("%s(portId:%d, state:%d)", __func__, portId, state);
Eric Laurenta9f86652018-11-28 17:23:11 -08005695 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent5ada82e2019-08-29 17:53:54 -07005696 mInputs.valueAt(i)->setAppState(portId, state);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08005697 }
5698}
5699
jiabin6012f912018-11-02 17:06:30 -07005700bool AudioPolicyManager::isHapticPlaybackSupported()
5701{
5702 for (const auto& hwModule : mHwModules) {
5703 const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
5704 for (const auto &outProfile : outputProfiles) {
5705 struct audio_port audioPort;
5706 outProfile->toAudioPort(&audioPort);
5707 for (size_t i = 0; i < audioPort.num_channel_masks; i++) {
5708 if (audioPort.channel_masks[i] & AUDIO_CHANNEL_HAPTIC_ALL) {
5709 return true;
5710 }
5711 }
5712 }
5713 }
5714 return false;
5715}
5716
Carter Hsu325a8eb2022-01-19 19:56:51 +08005717bool AudioPolicyManager::isUltrasoundSupported()
5718{
5719 bool hasUltrasoundOutput = false;
5720 bool hasUltrasoundInput = false;
5721 for (const auto& hwModule : mHwModules) {
5722 const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
5723 if (!hasUltrasoundOutput) {
5724 for (const auto &outProfile : outputProfiles) {
5725 if (outProfile->getFlags() & AUDIO_OUTPUT_FLAG_ULTRASOUND) {
5726 hasUltrasoundOutput = true;
5727 break;
5728 }
5729 }
5730 }
5731
5732 const InputProfileCollection &inputProfiles = hwModule->getInputProfiles();
5733 if (!hasUltrasoundInput) {
5734 for (const auto &inputProfile : inputProfiles) {
5735 if (inputProfile->getFlags() & AUDIO_INPUT_FLAG_ULTRASOUND) {
5736 hasUltrasoundInput = true;
5737 break;
5738 }
5739 }
5740 }
5741
5742 if (hasUltrasoundOutput && hasUltrasoundInput)
5743 return true;
5744 }
5745 return false;
5746}
5747
Atneya Nair698f5ef2022-12-15 16:15:09 -08005748bool AudioPolicyManager::isHotwordStreamSupported(bool lookbackAudio)
5749{
5750 const auto mask = AUDIO_INPUT_FLAG_HOTWORD_TAP |
5751 (lookbackAudio ? AUDIO_INPUT_FLAG_HW_LOOKBACK : 0);
5752 for (const auto& hwModule : mHwModules) {
5753 const InputProfileCollection &inputProfiles = hwModule->getInputProfiles();
5754 for (const auto &inputProfile : inputProfiles) {
5755 if ((inputProfile->getFlags() & mask) == mask) {
5756 return true;
5757 }
5758 }
5759 }
5760 return false;
5761}
5762
Eric Laurent8340e672019-11-06 11:01:08 -08005763bool AudioPolicyManager::isCallScreenModeSupported()
5764{
5765 return getConfig().isCallScreenModeSupported();
5766}
5767
5768
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005769status_t AudioPolicyManager::disconnectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07005770{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005771 ALOGV("%s port Id %d", __FUNCTION__, sourceDesc->portId());
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005772 if (!sourceDesc->isConnected()) {
5773 ALOGV("%s port Id %d already disconnected", __FUNCTION__, sourceDesc->portId());
5774 return NO_ERROR;
5775 }
François Gaffieafd4cea2019-11-18 15:50:22 +01005776 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
5777 if (swOutput != 0) {
5778 status_t status = stopSource(swOutput, sourceDesc);
Eric Laurent733ce942017-12-07 12:18:25 -08005779 if (status == NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005780 swOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08005781 }
jiabinbce0c1d2020-10-05 11:20:18 -07005782 if (releaseOutput(sourceDesc->portId())) {
5783 // The output descriptor is reopened to query dynamic profiles. In that case, there is
5784 // no need to release audio patch here but just return NO_ERROR.
5785 return NO_ERROR;
5786 }
Eric Laurentd60560a2015-04-10 11:31:20 -07005787 } else {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005788 sp<HwAudioOutputDescriptor> hwOutputDesc = sourceDesc->hwOutput().promote();
Eric Laurentd60560a2015-04-10 11:31:20 -07005789 if (hwOutputDesc != 0) {
Eric Laurentd60560a2015-04-10 11:31:20 -07005790 // close Hwoutput and remove from mHwOutputs
5791 } else {
5792 ALOGW("%s source has neither SW nor HW output", __FUNCTION__);
5793 }
5794 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005795 status_t status = releaseAudioPatchInternal(sourceDesc->getPatchHandle(), 0, sourceDesc);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005796 sourceDesc->disconnect();
5797 return status;
Eric Laurentd60560a2015-04-10 11:31:20 -07005798}
5799
François Gaffiec005e562018-11-06 15:04:49 +01005800sp<SourceClientDescriptor> AudioPolicyManager::getSourceForAttributesOnOutput(
5801 audio_io_handle_t output, const audio_attributes_t &attr)
Eric Laurentd60560a2015-04-10 11:31:20 -07005802{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005803 sp<SourceClientDescriptor> source;
Eric Laurentd60560a2015-04-10 11:31:20 -07005804 for (size_t i = 0; i < mAudioSources.size(); i++) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005805 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005806 sp<SwAudioOutputDescriptor> outputDesc = sourceDesc->swOutput().promote();
François Gaffiec005e562018-11-06 15:04:49 +01005807 if (followsSameRouting(attr, sourceDesc->attributes()) &&
5808 outputDesc != 0 && outputDesc->mIoHandle == output) {
Eric Laurentd60560a2015-04-10 11:31:20 -07005809 source = sourceDesc;
5810 break;
5811 }
5812 }
5813 return source;
Eric Laurent554a2772015-04-10 11:29:24 -07005814}
5815
Eric Laurentb4f42a92022-01-17 17:37:31 +01005816bool AudioPolicyManager::canBeSpatializedInt(const audio_attributes_t *attr,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005817 const audio_config_t *config,
Andy Hung9dd1a5b2022-05-10 15:39:39 -07005818 const AudioDeviceTypeAddrVector &devices) const
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005819{
5820 // The caller can have the audio attributes criteria ignored by either passing a null ptr or
5821 // the AUDIO_ATTRIBUTES_INITIALIZER value.
Eric Laurentfa0f6742021-08-17 18:39:44 +02005822 // If attributes are specified, current policy is to only allow spatialization for media
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005823 // and game usages.
Eric Laurent39095982021-08-24 18:29:27 +02005824 if (attr != nullptr && *attr != AUDIO_ATTRIBUTES_INITIALIZER) {
5825 if (attr->usage != AUDIO_USAGE_MEDIA && attr->usage != AUDIO_USAGE_GAME) {
5826 return false;
5827 }
5828 if ((attr->flags & (AUDIO_FLAG_CONTENT_SPATIALIZED | AUDIO_FLAG_NEVER_SPATIALIZE)) != 0) {
5829 return false;
5830 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005831 }
5832
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005833 sp<IOProfile> profile =
Eric Laurent39095982021-08-24 18:29:27 +02005834 getSpatializerOutputProfile(config, devices);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005835 if (profile == nullptr) {
5836 return false;
5837 }
5838
5839 // The caller can have the audio config criteria ignored by either passing a null ptr or
5840 // the AUDIO_CONFIG_INITIALIZER value.
Eric Laurentfa0f6742021-08-17 18:39:44 +02005841 // If an audio config is specified, current policy is to only allow spatialization for
Eric Laurent39095982021-08-24 18:29:27 +02005842 // some positional channel masks.
Eric Laurent39095982021-08-24 18:29:27 +02005843
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005844 if (config != nullptr && *config != AUDIO_CONFIG_INITIALIZER) {
Andy Hung9dd1a5b2022-05-10 15:39:39 -07005845 if (!audio_is_channel_mask_spatialized(config->channel_mask)) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005846 return false;
5847 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005848 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005849 return true;
5850}
5851
5852void AudioPolicyManager::checkVirtualizerClientRoutes() {
5853 std::set<audio_stream_type_t> streamsToInvalidate;
5854 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent39095982021-08-24 18:29:27 +02005855 const sp<SwAudioOutputDescriptor>& desc = mOutputs[i];
5856 for (const sp<TrackClientDescriptor>& client : desc->getClientIterable()) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005857 audio_attributes_t attr = client->attributes();
5858 DeviceVector devices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false);
5859 AudioDeviceTypeAddrVector devicesTypeAddress = devices.toTypeAddrVector();
5860 audio_config_base_t clientConfig = client->config();
5861 audio_config_t config = audio_config_initializer(&clientConfig);
Eric Laurent39095982021-08-24 18:29:27 +02005862 if (desc != mSpatializerOutput
Andy Hung9dd1a5b2022-05-10 15:39:39 -07005863 && canBeSpatializedInt(&attr, &config, devicesTypeAddress)) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005864 streamsToInvalidate.insert(client->stream());
5865 }
5866 }
5867 }
5868
jiabinc44b3462022-12-08 12:52:31 -08005869 invalidateStreams(StreamTypeVector(streamsToInvalidate.begin(), streamsToInvalidate.end()));
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005870}
5871
Eric Laurente191d1b2022-04-15 11:59:25 +02005872
5873bool AudioPolicyManager::isOutputOnlyAvailableRouteToSomeDevice(
5874 const sp<SwAudioOutputDescriptor>& outputDesc) {
5875 if (outputDesc->isDuplicated()) {
5876 return false;
5877 }
5878 DeviceVector devices = outputDesc->supportedDevices();
5879 for (size_t i = 0; i < mOutputs.size(); i++) {
5880 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
5881 if (desc == outputDesc || desc->isDuplicated()) {
5882 continue;
5883 }
5884 DeviceVector sharedDevices = desc->filterSupportedDevices(devices);
5885 if (!sharedDevices.isEmpty()
5886 && (desc->devicesSupportEncodedFormats(sharedDevices.types())
5887 == outputDesc->devicesSupportEncodedFormats(sharedDevices.types()))) {
5888 return false;
5889 }
5890 }
5891 return true;
5892}
5893
5894
Eric Laurentfa0f6742021-08-17 18:39:44 +02005895status_t AudioPolicyManager::getSpatializerOutput(const audio_config_base_t *mixerConfig,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005896 const audio_attributes_t *attr,
5897 audio_io_handle_t *output) {
5898 *output = AUDIO_IO_HANDLE_NONE;
5899
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005900 DeviceVector devices = mEngine->getOutputDevicesForAttributes(*attr, nullptr, false);
5901 AudioDeviceTypeAddrVector devicesTypeAddress = devices.toTypeAddrVector();
5902 audio_config_t *configPtr = nullptr;
5903 audio_config_t config;
5904 if (mixerConfig != nullptr) {
5905 config = audio_config_initializer(mixerConfig);
5906 configPtr = &config;
5907 }
Andy Hung9dd1a5b2022-05-10 15:39:39 -07005908 if (!canBeSpatializedInt(attr, configPtr, devicesTypeAddress)) {
Eric Laurente191d1b2022-04-15 11:59:25 +02005909 ALOGV("%s provided attributes or mixer config cannot be spatialized", __func__);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005910 return BAD_VALUE;
5911 }
5912
5913 sp<IOProfile> profile =
Eric Laurent39095982021-08-24 18:29:27 +02005914 getSpatializerOutputProfile(configPtr, devicesTypeAddress);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005915 if (profile == nullptr) {
Eric Laurente191d1b2022-04-15 11:59:25 +02005916 ALOGV("%s no suitable output profile for provided attributes or mixer config", __func__);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005917 return BAD_VALUE;
5918 }
5919
Eric Laurente191d1b2022-04-15 11:59:25 +02005920 std::vector<sp<SwAudioOutputDescriptor>> spatializerOutputs;
Eric Laurent39095982021-08-24 18:29:27 +02005921 for (size_t i = 0; i < mOutputs.size(); i++) {
5922 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente191d1b2022-04-15 11:59:25 +02005923 if (!desc->isDuplicated()
5924 && (desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0) {
5925 spatializerOutputs.push_back(desc);
5926 ALOGV("%s adding opened spatializer Output %d", __func__, desc->mIoHandle);
Eric Laurent39095982021-08-24 18:29:27 +02005927 }
5928 }
Eric Laurente191d1b2022-04-15 11:59:25 +02005929 mSpatializerOutput.clear();
5930 bool outputsChanged = false;
5931 for (const auto& desc : spatializerOutputs) {
5932 if (desc->mProfile == profile
5933 && (configPtr == nullptr
5934 || configPtr->channel_mask == desc->mMixerChannelMask)) {
5935 mSpatializerOutput = desc;
5936 ALOGV("%s reusing current spatializer output %d", __func__, desc->mIoHandle);
5937 } else {
5938 ALOGV("%s closing spatializerOutput output %d to match channel mask %#x"
5939 " and devices %s", __func__, desc->mIoHandle,
5940 configPtr != nullptr ? configPtr->channel_mask : 0,
5941 devices.toString().c_str());
5942 closeOutput(desc->mIoHandle);
5943 outputsChanged = true;
5944 }
Eric Laurent39095982021-08-24 18:29:27 +02005945 }
5946
Eric Laurente191d1b2022-04-15 11:59:25 +02005947 if (mSpatializerOutput == nullptr) {
Eric Laurentb4f42a92022-01-17 17:37:31 +01005948 sp<SwAudioOutputDescriptor> desc =
5949 openOutputWithProfileAndDevice(profile, devices, mixerConfig);
Eric Laurente191d1b2022-04-15 11:59:25 +02005950 if (desc != nullptr) {
5951 mSpatializerOutput = desc;
5952 outputsChanged = true;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005953 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005954 }
5955
5956 checkVirtualizerClientRoutes();
5957
Eric Laurente191d1b2022-04-15 11:59:25 +02005958 if (outputsChanged) {
5959 mPreviousOutputs = mOutputs;
5960 mpClientInterface->onAudioPortListUpdate();
5961 }
5962
5963 if (mSpatializerOutput == nullptr) {
5964 ALOGV("%s could not open spatializer output with requested config", __func__);
5965 return BAD_VALUE;
5966 }
Eric Laurent39095982021-08-24 18:29:27 +02005967 *output = mSpatializerOutput->mIoHandle;
Eric Laurente191d1b2022-04-15 11:59:25 +02005968 ALOGV("%s returning new spatializer output %d", __func__, *output);
5969 return OK;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005970}
5971
Eric Laurentfa0f6742021-08-17 18:39:44 +02005972status_t AudioPolicyManager::releaseSpatializerOutput(audio_io_handle_t output) {
5973 if (mSpatializerOutput == nullptr) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005974 return INVALID_OPERATION;
5975 }
Eric Laurentfa0f6742021-08-17 18:39:44 +02005976 if (mSpatializerOutput->mIoHandle != output) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005977 return BAD_VALUE;
5978 }
Eric Laurent39095982021-08-24 18:29:27 +02005979
Eric Laurente191d1b2022-04-15 11:59:25 +02005980 if (!isOutputOnlyAvailableRouteToSomeDevice(mSpatializerOutput)) {
5981 ALOGV("%s closing spatializer output %d", __func__, mSpatializerOutput->mIoHandle);
5982 closeOutput(mSpatializerOutput->mIoHandle);
5983 //from now on mSpatializerOutput is null
5984 checkVirtualizerClientRoutes();
5985 }
Eric Laurent39095982021-08-24 18:29:27 +02005986
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005987 return NO_ERROR;
5988}
5989
Eric Laurente552edb2014-03-10 17:42:56 -07005990// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07005991// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07005992// ----------------------------------------------------------------------------
Eric Laurent6a94d692014-05-20 11:18:06 -07005993uint32_t AudioPolicyManager::nextAudioPortGeneration()
5994{
Mikhail Naganov2773dd72017-12-08 10:12:11 -08005995 return mAudioPortGeneration++;
Eric Laurent6a94d692014-05-20 11:18:06 -07005996}
5997
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09005998static status_t deserializeAudioPolicyXmlConfig(AudioPolicyConfig &config) {
Mikhail Naganov946c0032020-10-21 13:04:58 -07005999 if (std::string audioPolicyXmlConfigFile = audio_get_audio_policy_config_file();
6000 !audioPolicyXmlConfigFile.empty()) {
6001 status_t ret = deserializeAudioPolicyFile(audioPolicyXmlConfigFile.c_str(), &config);
6002 if (ret == NO_ERROR) {
6003 config.setSource(audioPolicyXmlConfigFile);
Cheney Ni6851adb2018-11-01 06:30:37 +08006004 }
Mikhail Naganov946c0032020-10-21 13:04:58 -07006005 return ret;
Petri Gyntherf497f292018-04-17 18:46:10 -07006006 }
Mikhail Naganov946c0032020-10-21 13:04:58 -07006007 return BAD_VALUE;
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09006008}
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09006009
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006010AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface,
6011 bool /*forTesting*/)
Eric Laurente552edb2014-03-10 17:42:56 -07006012 :
Andy Hung4ef19fa2018-05-15 19:35:29 -07006013 mUidCached(AID_AUDIOSERVER), // no need to call getuid(), there's only one of us running.
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006014 mpClientInterface(clientInterface),
Eric Laurente552edb2014-03-10 17:42:56 -07006015 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
Eric Laurent3a4311c2014-03-17 12:00:47 -07006016 mA2dpSuspended(false),
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006017 mConfig(mHwModulesAll, mOutputDevicesAll, mInputDevicesAll, mDefaultOutputDevice),
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006018 mAudioPortGeneration(1),
6019 mBeaconMuteRefCount(0),
6020 mBeaconPlayingRefCount(0),
Eric Laurent9459fb02015-08-12 18:36:32 -07006021 mBeaconMuted(false),
Andy Hung2ddee192015-12-18 17:34:44 -08006022 mTtsOutputAvailable(false),
Eric Laurent36829f92017-04-07 19:04:42 -07006023 mMasterMono(false),
Eric Laurent4eb58f12018-12-07 16:41:02 -08006024 mMusicEffectOutput(AUDIO_IO_HANDLE_NONE)
Eric Laurente552edb2014-03-10 17:42:56 -07006025{
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006026}
François Gaffied1ab2bd2015-12-02 18:20:06 +01006027
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006028AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface)
6029 : AudioPolicyManager(clientInterface, false /*forTesting*/)
6030{
6031 loadConfig();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006032}
François Gaffied1ab2bd2015-12-02 18:20:06 +01006033
Kevin Rocarddfa1e8a2018-10-26 16:42:07 -07006034void AudioPolicyManager::loadConfig() {
6035 if (deserializeAudioPolicyXmlConfig(getConfig()) != NO_ERROR) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01006036 ALOGE("could not load audio policy configuration file, setting defaults");
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006037 getConfig().setDefault();
François Gaffied1ab2bd2015-12-02 18:20:06 +01006038 }
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006039}
6040
6041status_t AudioPolicyManager::initialize() {
Mikhail Naganov47835552019-05-14 10:32:51 -07006042 {
6043 auto engLib = EngineLibrary::load(
6044 "libaudiopolicyengine" + getConfig().getEngineLibraryNameSuffix() + ".so");
6045 if (!engLib) {
6046 ALOGE("%s: Failed to load the engine library", __FUNCTION__);
6047 return NO_INIT;
6048 }
6049 mEngine = engLib->createEngine();
6050 if (mEngine == nullptr) {
6051 ALOGE("%s: Failed to instantiate the APM engine", __FUNCTION__);
6052 return NO_INIT;
6053 }
François Gaffie2110e042015-03-24 08:41:51 +01006054 }
6055 mEngine->setObserver(this);
6056 status_t status = mEngine->initCheck();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006057 if (status != NO_ERROR) {
6058 LOG_FATAL("Policy engine not initialized(err=%d)", status);
6059 return status;
6060 }
François Gaffie2110e042015-03-24 08:41:51 +01006061
Mikhail Naganove93ae282023-02-02 15:28:26 -08006062 // If microphones address is empty, set it according to device type
6063 for (size_t i = 0; i < mInputDevicesAll.size(); i++) {
6064 if (mInputDevicesAll[i]->address().empty()) {
6065 if (mInputDevicesAll[i]->type() == AUDIO_DEVICE_IN_BUILTIN_MIC) {
6066 mInputDevicesAll[i]->setAddress(AUDIO_BOTTOM_MICROPHONE_ADDRESS);
6067 } else if (mInputDevicesAll[i]->type() == AUDIO_DEVICE_IN_BACK_MIC) {
6068 mInputDevicesAll[i]->setAddress(AUDIO_BACK_MICROPHONE_ADDRESS);
6069 }
6070 }
6071 }
6072
jiabin29230182023-04-04 21:02:36 +00006073 // The actual device selection cache will be updated when calling `updateDevicesAndOutputs`
6074 // at the end of this function.
6075 mEngine->initializeDeviceSelectionCache();
Eric Laurent1d69c872021-01-11 18:53:01 +01006076 mCommunnicationStrategy = mEngine->getProductStrategyForAttributes(
6077 mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL));
6078
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006079 // after parsing the config, mOutputDevicesAll and mInputDevicesAll contain all known devices;
Eric Laurente552edb2014-03-10 17:42:56 -07006080 // open all output streams needed to access attached devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006081 onNewAudioModulesAvailableInt(nullptr /*newDevices*/);
François Gaffie11d30102018-11-02 16:09:09 +01006082
Eric Laurent3a4311c2014-03-17 12:00:47 -07006083 // make sure default device is reachable
François Gaffie11d30102018-11-02 16:09:09 +01006084 if (mDefaultOutputDevice == 0 || !mAvailableOutputDevices.contains(mDefaultOutputDevice)) {
6085 ALOGE_IF(mDefaultOutputDevice != 0, "Default device %s is unreachable",
6086 mDefaultOutputDevice->toString().c_str());
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006087 status = NO_INIT;
Eric Laurent3a4311c2014-03-17 12:00:47 -07006088 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02006089 ALOGW_IF(mPrimaryOutput == nullptr, "The policy configuration does not declare a primary output");
Eric Laurente552edb2014-03-10 17:42:56 -07006090
Tomoharu Kasahara71c90912018-10-31 09:10:12 +09006091 // Silence ALOGV statements
6092 property_set("log.tag." LOG_TAG, "D");
6093
Eric Laurente552edb2014-03-10 17:42:56 -07006094 updateDevicesAndOutputs();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006095 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07006096}
6097
Eric Laurente0720872014-03-11 09:30:41 -07006098AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07006099{
Eric Laurente552edb2014-03-10 17:42:56 -07006100 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08006101 mOutputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07006102 }
6103 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08006104 mInputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07006105 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07006106 mAvailableOutputDevices.clear();
6107 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07006108 mOutputs.clear();
6109 mInputs.clear();
6110 mHwModules.clear();
Mikhail Naganovd4120142017-12-06 15:49:22 -08006111 mHwModulesAll.clear();
Mikhail Naganov100f0122018-11-29 11:22:16 -08006112 mManualSurroundFormats.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07006113}
6114
Eric Laurente0720872014-03-11 09:30:41 -07006115status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07006116{
Eric Laurent87ffa392015-05-22 10:32:38 -07006117 return hasPrimaryOutput() ? NO_ERROR : NO_INIT;
Eric Laurente552edb2014-03-10 17:42:56 -07006118}
6119
Eric Laurente552edb2014-03-10 17:42:56 -07006120// ---
6121
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006122void AudioPolicyManager::onNewAudioModulesAvailable()
6123{
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006124 DeviceVector newDevices;
6125 onNewAudioModulesAvailableInt(&newDevices);
6126 if (!newDevices.empty()) {
6127 nextAudioPortGeneration();
6128 mpClientInterface->onAudioPortListUpdate();
6129 }
6130}
6131
6132void AudioPolicyManager::onNewAudioModulesAvailableInt(DeviceVector *newDevices)
6133{
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006134 for (const auto& hwModule : mHwModulesAll) {
6135 if (std::find(mHwModules.begin(), mHwModules.end(), hwModule) != mHwModules.end()) {
6136 continue;
6137 }
6138 hwModule->setHandle(mpClientInterface->loadHwModule(hwModule->getName()));
6139 if (hwModule->getHandle() == AUDIO_MODULE_HANDLE_NONE) {
6140 ALOGW("could not open HW module %s", hwModule->getName());
6141 continue;
6142 }
6143 mHwModules.push_back(hwModule);
Dean Wheatley12a87132021-04-16 10:08:49 +10006144 // open all output streams needed to access attached devices.
6145 // direct outputs are closed immediately after checking the availability of attached devices
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006146 // This also validates mAvailableOutputDevices list
6147 for (const auto& outProfile : hwModule->getOutputProfiles()) {
6148 if (!outProfile->canOpenNewIo()) {
6149 ALOGE("Invalid Output profile max open count %u for profile %s",
6150 outProfile->maxOpenCount, outProfile->getTagName().c_str());
6151 continue;
6152 }
6153 if (!outProfile->hasSupportedDevices()) {
6154 ALOGW("Output profile contains no device on module %s", hwModule->getName());
6155 continue;
6156 }
Carter Hsu1a3364a2022-01-21 15:32:56 +08006157 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_TTS) != 0 ||
6158 (outProfile->getFlags() & AUDIO_OUTPUT_FLAG_ULTRASOUND) != 0) {
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006159 mTtsOutputAvailable = true;
6160 }
6161
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006162 const DeviceVector &supportedDevices = outProfile->getSupportedDevices();
6163 DeviceVector availProfileDevices = supportedDevices.filter(mOutputDevicesAll);
6164 sp<DeviceDescriptor> supportedDevice = 0;
6165 if (supportedDevices.contains(mDefaultOutputDevice)) {
6166 supportedDevice = mDefaultOutputDevice;
6167 } else {
6168 // choose first device present in profile's SupportedDevices also part of
6169 // mAvailableOutputDevices.
6170 if (availProfileDevices.isEmpty()) {
6171 continue;
6172 }
6173 supportedDevice = availProfileDevices.itemAt(0);
6174 }
6175 if (!mOutputDevicesAll.contains(supportedDevice)) {
6176 continue;
6177 }
6178 sp<SwAudioOutputDescriptor> outputDesc = new SwAudioOutputDescriptor(outProfile,
6179 mpClientInterface);
6180 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentf1f22e72021-07-13 14:04:14 +02006181 status_t status = outputDesc->open(nullptr /* halConfig */, nullptr /* mixerConfig */,
6182 DeviceVector(supportedDevice),
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006183 AUDIO_STREAM_DEFAULT,
6184 AUDIO_OUTPUT_FLAG_NONE, &output);
6185 if (status != NO_ERROR) {
6186 ALOGW("Cannot open output stream for devices %s on hw module %s",
6187 supportedDevice->toString().c_str(), hwModule->getName());
6188 continue;
6189 }
6190 for (const auto &device : availProfileDevices) {
6191 // give a valid ID to an attached device once confirmed it is reachable
6192 if (!device->isAttached()) {
6193 device->attach(hwModule);
6194 mAvailableOutputDevices.add(device);
jiabin1c4794b2020-05-05 10:08:05 -07006195 device->setEncapsulationInfoFromHal(mpClientInterface);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006196 if (newDevices) newDevices->add(device);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006197 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
6198 }
6199 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02006200 if (mPrimaryOutput == nullptr &&
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006201 outProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
6202 mPrimaryOutput = outputDesc;
6203 }
Eric Laurent39095982021-08-24 18:29:27 +02006204 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
Eric Laurentc529cf62020-04-17 18:19:10 -07006205 outputDesc->close();
6206 } else {
6207 addOutput(output, outputDesc);
6208 setOutputDevices(outputDesc,
6209 DeviceVector(supportedDevice),
6210 true,
6211 0,
6212 NULL);
6213 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006214 }
6215 // open input streams needed to access attached devices to validate
6216 // mAvailableInputDevices list
6217 for (const auto& inProfile : hwModule->getInputProfiles()) {
6218 if (!inProfile->canOpenNewIo()) {
6219 ALOGE("Invalid Input profile max open count %u for profile %s",
6220 inProfile->maxOpenCount, inProfile->getTagName().c_str());
6221 continue;
6222 }
6223 if (!inProfile->hasSupportedDevices()) {
6224 ALOGW("Input profile contains no device on module %s", hwModule->getName());
6225 continue;
6226 }
6227 // chose first device present in profile's SupportedDevices also part of
6228 // available input devices
6229 const DeviceVector &supportedDevices = inProfile->getSupportedDevices();
6230 DeviceVector availProfileDevices = supportedDevices.filter(mInputDevicesAll);
6231 if (availProfileDevices.isEmpty()) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01006232 ALOGV("%s: Input device list is empty! for profile %s",
6233 __func__, inProfile->getTagName().c_str());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006234 continue;
6235 }
6236 sp<AudioInputDescriptor> inputDesc =
6237 new AudioInputDescriptor(inProfile, mpClientInterface);
6238
6239 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
6240 status_t status = inputDesc->open(nullptr,
6241 availProfileDevices.itemAt(0),
6242 AUDIO_SOURCE_MIC,
6243 AUDIO_INPUT_FLAG_NONE,
6244 &input);
6245 if (status != NO_ERROR) {
6246 ALOGW("Cannot open input stream for device %s on hw module %s",
6247 availProfileDevices.toString().c_str(),
6248 hwModule->getName());
6249 continue;
6250 }
6251 for (const auto &device : availProfileDevices) {
6252 // give a valid ID to an attached device once confirmed it is reachable
6253 if (!device->isAttached()) {
6254 device->attach(hwModule);
6255 device->importAudioPortAndPickAudioProfile(inProfile, true);
6256 mAvailableInputDevices.add(device);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006257 if (newDevices) newDevices->add(device);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006258 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
6259 }
6260 }
6261 inputDesc->close();
6262 }
6263 }
Eric Laurente191d1b2022-04-15 11:59:25 +02006264
6265 // Check if spatializer outputs can be closed until used.
6266 // mOutputs vector never contains duplicated outputs at this point.
6267 std::vector<audio_io_handle_t> outputsClosed;
6268 for (size_t i = 0; i < mOutputs.size(); i++) {
6269 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
6270 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0
6271 && !isOutputOnlyAvailableRouteToSomeDevice(desc)) {
6272 outputsClosed.push_back(desc->mIoHandle);
6273 desc->close();
6274 }
6275 }
6276 for (auto output : outputsClosed) {
6277 removeOutput(output);
6278 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006279}
6280
Eric Laurent98e38192018-02-15 18:31:53 -08006281void AudioPolicyManager::addOutput(audio_io_handle_t output,
6282 const sp<SwAudioOutputDescriptor>& outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07006283{
Eric Laurent1c333e22014-05-20 10:48:17 -07006284 mOutputs.add(output, outputDesc);
jiabin9a3361e2019-10-01 09:38:30 -07006285 applyStreamVolumes(outputDesc, DeviceTypeSet(), 0 /* delayMs */, true /* force */);
Andy Hung2ddee192015-12-18 17:34:44 -08006286 updateMono(output); // update mono status when adding to output list
Eric Laurent36829f92017-04-07 19:04:42 -07006287 selectOutputForMusicEffects();
Eric Laurent6a94d692014-05-20 11:18:06 -07006288 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07006289}
6290
François Gaffie53615e22015-03-19 09:24:12 +01006291void AudioPolicyManager::removeOutput(audio_io_handle_t output)
6292{
Francois Gaffiebce7cd42020-10-14 16:13:20 +02006293 if (mPrimaryOutput != 0 && mPrimaryOutput == mOutputs.valueFor(output)) {
6294 ALOGV("%s: removing primary output", __func__);
6295 mPrimaryOutput = nullptr;
6296 }
François Gaffie53615e22015-03-19 09:24:12 +01006297 mOutputs.removeItem(output);
Eric Laurent36829f92017-04-07 19:04:42 -07006298 selectOutputForMusicEffects();
François Gaffie53615e22015-03-19 09:24:12 +01006299}
6300
Eric Laurent98e38192018-02-15 18:31:53 -08006301void AudioPolicyManager::addInput(audio_io_handle_t input,
6302 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07006303{
Eric Laurent1c333e22014-05-20 10:48:17 -07006304 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07006305 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07006306}
Eric Laurente552edb2014-03-10 17:42:56 -07006307
François Gaffie11d30102018-11-02 16:09:09 +01006308status_t AudioPolicyManager::checkOutputsForDevice(const sp<DeviceDescriptor>& device,
François Gaffie53615e22015-03-19 09:24:12 +01006309 audio_policy_dev_state_t state,
François Gaffie11d30102018-11-02 16:09:09 +01006310 SortedVector<audio_io_handle_t>& outputs)
Eric Laurente552edb2014-03-10 17:42:56 -07006311{
François Gaffie11d30102018-11-02 16:09:09 +01006312 audio_devices_t deviceType = device->type();
jiabince9f20e2019-09-12 16:29:15 -07006313 const String8 &address = String8(device->address().c_str());
Eric Laurentc75307b2015-03-17 15:29:32 -07006314 sp<SwAudioOutputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07006315
François Gaffie11d30102018-11-02 16:09:09 +01006316 if (audio_device_is_digital(deviceType)) {
Eric Laurentcc750d32015-06-25 11:48:20 -07006317 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01006318 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07006319 }
Eric Laurente552edb2014-03-10 17:42:56 -07006320
Eric Laurent3b73df72014-03-11 09:06:29 -07006321 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
jiabinb4fed192020-09-22 14:45:40 -07006322 // first call getAudioPort to get the supported attributes from the HAL
6323 struct audio_port_v7 port = {};
6324 device->toAudioPort(&port);
6325 status_t status = mpClientInterface->getAudioPort(&port);
6326 if (status == NO_ERROR) {
6327 device->importAudioPort(port);
6328 }
6329
6330 // then list already open outputs that can be routed to this device
Eric Laurente552edb2014-03-10 17:42:56 -07006331 for (size_t i = 0; i < mOutputs.size(); i++) {
6332 desc = mOutputs.valueAt(i);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006333 if (!desc->isDuplicated() && desc->supportsDevice(device)
jiabin9a3361e2019-10-01 09:38:30 -07006334 && desc->devicesSupportEncodedFormats({deviceType})) {
François Gaffie11d30102018-11-02 16:09:09 +01006335 ALOGV("checkOutputsForDevice(): adding opened output %d on device %s",
6336 mOutputs.keyAt(i), device->toString().c_str());
6337 outputs.add(mOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07006338 }
6339 }
6340 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07006341 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006342 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006343 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
6344 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
François Gaffie11d30102018-11-02 16:09:09 +01006345 if (profile->supportsDevice(device)) {
6346 profiles.add(profile);
6347 ALOGV("checkOutputsForDevice(): adding profile %zu from module %s",
6348 j, hwModule->getName());
Eric Laurente552edb2014-03-10 17:42:56 -07006349 }
6350 }
6351 }
6352
Eric Laurent7b279bb2015-12-14 10:18:23 -08006353 ALOGV(" found %zu profiles, %zu outputs", profiles.size(), outputs.size());
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006354
Eric Laurente552edb2014-03-10 17:42:56 -07006355 if (profiles.isEmpty() && outputs.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006356 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07006357 return BAD_VALUE;
6358 }
6359
6360 // open outputs for matching profiles if needed. Direct outputs are also opened to
6361 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
6362 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07006363 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07006364
6365 // nothing to do if one output is already opened for this profile
6366 size_t j;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006367 for (j = 0; j < outputs.size(); j++) {
6368 desc = mOutputs.valueFor(outputs.itemAt(j));
Eric Laurente552edb2014-03-10 17:42:56 -07006369 if (!desc->isDuplicated() && desc->mProfile == profile) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07006370 // matching profile: save the sample rates, format and channel masks supported
6371 // by the profile in our device descriptor
François Gaffie11d30102018-11-02 16:09:09 +01006372 if (audio_device_is_digital(deviceType)) {
jiabin4ef93452019-09-10 14:29:54 -07006373 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006374 }
Eric Laurente552edb2014-03-10 17:42:56 -07006375 break;
6376 }
6377 }
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006378 if (j != outputs.size()) {
Eric Laurente552edb2014-03-10 17:42:56 -07006379 continue;
6380 }
6381
Eric Laurent3974e3b2017-12-07 17:58:43 -08006382 if (!profile->canOpenNewIo()) {
6383 ALOGW("Max Output number %u already opened for this profile %s",
6384 profile->maxOpenCount, profile->getTagName().c_str());
6385 continue;
6386 }
6387
Eric Laurent83efe1c2017-07-09 16:51:08 -07006388 ALOGV("opening output for device %08x with params %s profile %p name %s",
jiabin5740f082019-08-19 15:08:30 -07006389 deviceType, address.string(), profile.get(), profile->getName().c_str());
jiabinbce0c1d2020-10-05 11:20:18 -07006390 desc = openOutputWithProfileAndDevice(profile, DeviceVector(device));
6391 audio_io_handle_t output = desc == nullptr ? AUDIO_IO_HANDLE_NONE : desc->mIoHandle;
Eric Laurentcf2c0212014-07-25 16:20:43 -07006392 if (output == AUDIO_IO_HANDLE_NONE) {
François Gaffie11d30102018-11-02 16:09:09 +01006393 ALOGW("checkOutputsForDevice() could not open output for device %x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07006394 profiles.removeAt(profile_index);
6395 profile_index--;
6396 } else {
6397 outputs.add(output);
Paul McLean9080a4c2015-06-18 08:24:02 -07006398 // Load digital format info only for digital devices
François Gaffie11d30102018-11-02 16:09:09 +01006399 if (audio_device_is_digital(deviceType)) {
jiabinbce0c1d2020-10-05 11:20:18 -07006400 // TODO: when getAudioPort is ready, it may not be needed to import the audio
6401 // port but just pick audio profile
jiabin4ef93452019-09-10 14:29:54 -07006402 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006403 }
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07006404
François Gaffie11d30102018-11-02 16:09:09 +01006405 if (device_distinguishes_on_address(deviceType)) {
6406 ALOGV("checkOutputsForDevice(): setOutputDevices %s",
6407 device->toString().c_str());
6408 setOutputDevices(desc, DeviceVector(device), true/*force*/, 0/*delay*/,
6409 NULL/*patch handle*/);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006410 }
Eric Laurente552edb2014-03-10 17:42:56 -07006411 ALOGV("checkOutputsForDevice(): adding output %d", output);
6412 }
6413 }
6414
6415 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006416 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07006417 return BAD_VALUE;
6418 }
Eric Laurentd4692962014-05-05 18:13:44 -07006419 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07006420 // check if one opened output is not needed any more after disconnecting one device
6421 for (size_t i = 0; i < mOutputs.size(); i++) {
6422 desc = mOutputs.valueAt(i);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006423 if (!desc->isDuplicated()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08006424 // exact match on device
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006425 if (device_distinguishes_on_address(deviceType) && desc->supportsDevice(device)
Francois Gaffiec7d4c222021-12-02 11:12:52 +01006426 && desc->containsSingleDeviceSupportingEncodedFormats(device)) {
François Gaffie11d30102018-11-02 16:09:09 +01006427 outputs.add(mOutputs.keyAt(i));
Francois Gaffie716e1432019-01-14 16:58:59 +01006428 } else if (!mAvailableOutputDevices.containsAtLeastOne(desc->supportedDevices())) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006429 ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
6430 mOutputs.keyAt(i));
6431 outputs.add(mOutputs.keyAt(i));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006432 }
Eric Laurente552edb2014-03-10 17:42:56 -07006433 }
6434 }
Eric Laurentd4692962014-05-05 18:13:44 -07006435 // Clear any profiles associated with the disconnected device.
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006436 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006437 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
6438 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
jiabinbce0c1d2020-10-05 11:20:18 -07006439 if (!profile->supportsDevice(device)) {
6440 continue;
6441 }
6442 ALOGV("checkOutputsForDevice(): "
6443 "clearing direct output profile %zu on module %s",
6444 j, hwModule->getName());
6445 profile->clearAudioProfiles();
6446 if (!profile->hasDynamicAudioProfile()) {
6447 continue;
6448 }
6449 // When a device is disconnected, if there is an IOProfile that contains dynamic
6450 // profiles and supports the disconnected device, call getAudioPort to repopulate
6451 // the capabilities of the devices that is supported by the IOProfile.
6452 for (const auto& supportedDevice : profile->getSupportedDevices()) {
6453 if (supportedDevice == device ||
6454 !mAvailableOutputDevices.contains(supportedDevice)) {
6455 continue;
6456 }
6457 struct audio_port_v7 port;
6458 supportedDevice->toAudioPort(&port);
6459 status_t status = mpClientInterface->getAudioPort(&port);
6460 if (status == NO_ERROR) {
6461 supportedDevice->importAudioPort(port);
6462 }
Eric Laurente552edb2014-03-10 17:42:56 -07006463 }
6464 }
6465 }
6466 }
6467 return NO_ERROR;
6468}
6469
François Gaffie11d30102018-11-02 16:09:09 +01006470status_t AudioPolicyManager::checkInputsForDevice(const sp<DeviceDescriptor>& device,
Eric Laurent0dd51852019-04-19 18:18:58 -07006471 audio_policy_dev_state_t state)
Eric Laurentd4692962014-05-05 18:13:44 -07006472{
Eric Laurent1f2f2232014-06-02 12:01:23 -07006473 sp<AudioInputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07006474
François Gaffie11d30102018-11-02 16:09:09 +01006475 if (audio_device_is_digital(device->type())) {
Eric Laurentcc750d32015-06-25 11:48:20 -07006476 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01006477 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07006478 }
6479
Eric Laurentd4692962014-05-05 18:13:44 -07006480 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
jiabinbf5f4262023-04-12 21:48:34 +00006481 // first call getAudioPort to get the supported attributes from the HAL
6482 struct audio_port_v7 port = {};
6483 device->toAudioPort(&port);
6484 status_t status = mpClientInterface->getAudioPort(&port);
6485 if (status == NO_ERROR) {
6486 device->importAudioPort(port);
6487 }
6488
Eric Laurent0dd51852019-04-19 18:18:58 -07006489 // look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07006490 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006491 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07006492 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006493 profile_index < hwModule->getInputProfiles().size();
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006494 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006495 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Eric Laurent275e8e92014-11-30 15:14:47 -08006496
François Gaffie11d30102018-11-02 16:09:09 +01006497 if (profile->supportsDevice(device)) {
6498 profiles.add(profile);
6499 ALOGV("checkInputsForDevice(): adding profile %zu from module %s",
6500 profile_index, hwModule->getName());
Eric Laurentd4692962014-05-05 18:13:44 -07006501 }
6502 }
6503 }
6504
Eric Laurent0dd51852019-04-19 18:18:58 -07006505 if (profiles.isEmpty()) {
6506 ALOGW("%s: No input profile available for device %s",
6507 __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07006508 return BAD_VALUE;
6509 }
6510
6511 // open inputs for matching profiles if needed. Direct inputs are also opened to
6512 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
6513 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
6514
Eric Laurent1c333e22014-05-20 10:48:17 -07006515 sp<IOProfile> profile = profiles[profile_index];
Eric Laurent3974e3b2017-12-07 17:58:43 -08006516
Eric Laurentd4692962014-05-05 18:13:44 -07006517 // nothing to do if one input is already opened for this profile
6518 size_t input_index;
6519 for (input_index = 0; input_index < mInputs.size(); input_index++) {
6520 desc = mInputs.valueAt(input_index);
6521 if (desc->mProfile == profile) {
François Gaffie11d30102018-11-02 16:09:09 +01006522 if (audio_device_is_digital(device->type())) {
jiabin4ef93452019-09-10 14:29:54 -07006523 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006524 }
Eric Laurentd4692962014-05-05 18:13:44 -07006525 break;
6526 }
6527 }
6528 if (input_index != mInputs.size()) {
6529 continue;
6530 }
6531
Eric Laurent3974e3b2017-12-07 17:58:43 -08006532 if (!profile->canOpenNewIo()) {
6533 ALOGW("Max Input number %u already opened for this profile %s",
6534 profile->maxOpenCount, profile->getTagName().c_str());
6535 continue;
6536 }
6537
Eric Laurentfe231122017-11-17 17:48:06 -08006538 desc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentcf2c0212014-07-25 16:20:43 -07006539 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
jiabinbf5f4262023-04-12 21:48:34 +00006540 status = desc->open(nullptr, device, AUDIO_SOURCE_MIC, AUDIO_INPUT_FLAG_NONE, &input);
Eric Laurentd4692962014-05-05 18:13:44 -07006541
Eric Laurentcf2c0212014-07-25 16:20:43 -07006542 if (status == NO_ERROR) {
jiabince9f20e2019-09-12 16:29:15 -07006543 const String8& address = String8(device->address().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07006544 if (!address.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006545 char *param = audio_device_address_to_parameter(device->type(), address);
Eric Laurentcf2c0212014-07-25 16:20:43 -07006546 mpClientInterface->setParameters(input, String8(param));
6547 free(param);
Eric Laurentd4692962014-05-05 18:13:44 -07006548 }
François Gaffie11d30102018-11-02 16:09:09 +01006549 updateAudioProfiles(device, input, profile->getAudioProfiles());
François Gaffie112b0af2015-11-19 16:13:25 +01006550 if (!profile->hasValidAudioProfile()) {
Eric Laurentd4692962014-05-05 18:13:44 -07006551 ALOGW("checkInputsForDevice() direct input missing param");
Eric Laurentfe231122017-11-17 17:48:06 -08006552 desc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07006553 input = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07006554 }
6555
Eric Laurent0dd51852019-04-19 18:18:58 -07006556 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07006557 addInput(input, desc);
6558 }
6559 } // endif input != 0
6560
Eric Laurentcf2c0212014-07-25 16:20:43 -07006561 if (input == AUDIO_IO_HANDLE_NONE) {
Pattydd807582021-11-04 21:01:03 +08006562 ALOGW("%s could not open input for device %s", __func__,
François Gaffie11d30102018-11-02 16:09:09 +01006563 device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07006564 profiles.removeAt(profile_index);
6565 profile_index--;
6566 } else {
François Gaffie11d30102018-11-02 16:09:09 +01006567 if (audio_device_is_digital(device->type())) {
jiabin4ef93452019-09-10 14:29:54 -07006568 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006569 }
Eric Laurentd4692962014-05-05 18:13:44 -07006570 ALOGV("checkInputsForDevice(): adding input %d", input);
6571 }
6572 } // end scan profiles
6573
6574 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006575 ALOGW("%s: No input available for device %s", __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07006576 return BAD_VALUE;
6577 }
6578 } else {
6579 // Disconnect
Eric Laurentd4692962014-05-05 18:13:44 -07006580 // Clear any profiles associated with the disconnected device.
Mikhail Naganovd4120142017-12-06 15:49:22 -08006581 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07006582 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006583 profile_index < hwModule->getInputProfiles().size();
Eric Laurentd4692962014-05-05 18:13:44 -07006584 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006585 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Francois Gaffie716e1432019-01-14 16:58:59 +01006586 if (profile->supportsDevice(device)) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08006587 ALOGV("checkInputsForDevice(): clearing direct input profile %zu on module %s",
6588 profile_index, hwModule->getName());
François Gaffie112b0af2015-11-19 16:13:25 +01006589 profile->clearAudioProfiles();
Eric Laurentd4692962014-05-05 18:13:44 -07006590 }
6591 }
6592 }
6593 } // end disconnect
6594
6595 return NO_ERROR;
6596}
6597
6598
Eric Laurente0720872014-03-11 09:30:41 -07006599void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07006600{
6601 ALOGV("closeOutput(%d)", output);
6602
François Gaffie1c878552018-11-22 16:53:21 +01006603 sp<SwAudioOutputDescriptor> closingOutput = mOutputs.valueFor(output);
6604 if (closingOutput == NULL) {
Eric Laurente552edb2014-03-10 17:42:56 -07006605 ALOGW("closeOutput() unknown output %d", output);
6606 return;
6607 }
Mikhail Naganov32ebca32019-03-22 15:42:52 -07006608 const bool closingOutputWasActive = closingOutput->isActive();
François Gaffie1c878552018-11-22 16:53:21 +01006609 mPolicyMixes.closeOutput(closingOutput);
Eric Laurent275e8e92014-11-30 15:14:47 -08006610
Eric Laurente552edb2014-03-10 17:42:56 -07006611 // look for duplicated outputs connected to the output being removed.
6612 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie1c878552018-11-22 16:53:21 +01006613 sp<SwAudioOutputDescriptor> dupOutput = mOutputs.valueAt(i);
6614 if (dupOutput->isDuplicated() &&
6615 (dupOutput->mOutput1 == closingOutput || dupOutput->mOutput2 == closingOutput)) {
6616 sp<SwAudioOutputDescriptor> remainingOutput =
6617 dupOutput->mOutput1 == closingOutput ? dupOutput->mOutput2 : dupOutput->mOutput1;
Eric Laurente552edb2014-03-10 17:42:56 -07006618 // As all active tracks on duplicated output will be deleted,
6619 // and as they were also referenced on the other output, the reference
6620 // count for their stream type must be adjusted accordingly on
6621 // the other output.
François Gaffie1c878552018-11-22 16:53:21 +01006622 const bool wasActive = remainingOutput->isActive();
6623 // Note: no-op on the closing output where all clients has already been set inactive
6624 dupOutput->setAllClientsInactive();
Eric Laurent733ce942017-12-07 12:18:25 -08006625 // stop() will be a no op if the output is still active but is needed in case all
6626 // active streams refcounts where cleared above
6627 if (wasActive) {
François Gaffie1c878552018-11-22 16:53:21 +01006628 remainingOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08006629 }
Eric Laurente552edb2014-03-10 17:42:56 -07006630 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
6631 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
6632
6633 mpClientInterface->closeOutput(duplicatedOutput);
François Gaffie53615e22015-03-19 09:24:12 +01006634 removeOutput(duplicatedOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07006635 }
6636 }
6637
Eric Laurent05b90f82014-08-27 15:32:29 -07006638 nextAudioPortGeneration();
6639
François Gaffie1c878552018-11-22 16:53:21 +01006640 ssize_t index = mAudioPatches.indexOfKey(closingOutput->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07006641 if (index >= 0) {
6642 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006643 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
6644 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07006645 mAudioPatches.removeItemsAt(index);
6646 mpClientInterface->onAudioPatchListUpdate();
6647 }
6648
Mikhail Naganov32ebca32019-03-22 15:42:52 -07006649 if (closingOutputWasActive) {
6650 closingOutput->stop();
6651 }
François Gaffie1c878552018-11-22 16:53:21 +01006652 closingOutput->close();
Eric Laurente552edb2014-03-10 17:42:56 -07006653
François Gaffie53615e22015-03-19 09:24:12 +01006654 removeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07006655 mPreviousOutputs = mOutputs;
Eric Laurentb4f42a92022-01-17 17:37:31 +01006656 if (closingOutput == mSpatializerOutput) {
6657 mSpatializerOutput.clear();
6658 }
Dean Wheatley3023b382018-08-09 07:42:40 +10006659
6660 // MSD patches may have been released to support a non-MSD direct output. Reset MSD patch if
6661 // no direct outputs are open.
François Gaffie11d30102018-11-02 16:09:09 +01006662 if (!getMsdAudioOutDevices().isEmpty()) {
Dean Wheatley3023b382018-08-09 07:42:40 +10006663 bool directOutputOpen = false;
6664 for (size_t i = 0; i < mOutputs.size(); i++) {
6665 if (mOutputs[i]->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
6666 directOutputOpen = true;
6667 break;
6668 }
6669 }
6670 if (!directOutputOpen) {
Michael Chan6fb34492020-12-08 15:44:49 +11006671 ALOGV("no direct outputs open, reset MSD patches");
6672 // TODO: The MSD patches to be established here may differ to current MSD patches due to
6673 // how output devices for patching are resolved. Avoid by caching and reusing the
6674 // arguments to mEngine->getOutputDevicesForAttributes() when resolving which output
6675 // devices to patch to. This may be complicated by the fact that devices may become
6676 // unavailable.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11006677 setMsdOutputPatches();
Dean Wheatley3023b382018-08-09 07:42:40 +10006678 }
6679 }
Eric Laurent05b90f82014-08-27 15:32:29 -07006680}
6681
6682void AudioPolicyManager::closeInput(audio_io_handle_t input)
6683{
6684 ALOGV("closeInput(%d)", input);
6685
6686 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
6687 if (inputDesc == NULL) {
6688 ALOGW("closeInput() unknown input %d", input);
6689 return;
6690 }
6691
Eric Laurent6a94d692014-05-20 11:18:06 -07006692 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07006693
François Gaffie11d30102018-11-02 16:09:09 +01006694 sp<DeviceDescriptor> device = inputDesc->getDevice();
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08006695 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07006696 if (index >= 0) {
6697 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006698 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
6699 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07006700 mAudioPatches.removeItemsAt(index);
6701 mpClientInterface->onAudioPatchListUpdate();
6702 }
6703
Eric Laurentfe231122017-11-17 17:48:06 -08006704 inputDesc->close();
Eric Laurent05b90f82014-08-27 15:32:29 -07006705 mInputs.removeItem(input);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07006706
François Gaffie11d30102018-11-02 16:09:09 +01006707 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
6708 if (primaryInputDevices.contains(device) &&
Haynes Mathew George1d539d92018-03-16 11:40:49 -07006709 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07006710 mpClientInterface->setSoundTriggerCaptureState(false);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07006711 }
Eric Laurente552edb2014-03-10 17:42:56 -07006712}
6713
François Gaffie11d30102018-11-02 16:09:09 +01006714SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevices(
6715 const DeviceVector &devices,
6716 const SwAudioOutputCollection& openOutputs)
Eric Laurente552edb2014-03-10 17:42:56 -07006717{
6718 SortedVector<audio_io_handle_t> outputs;
6719
François Gaffie11d30102018-11-02 16:09:09 +01006720 ALOGVV("%s() devices %s", __func__, devices.toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07006721 for (size_t i = 0; i < openOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01006722 ALOGVV("output %zu isDuplicated=%d device=%s",
Eric Laurent8c7e6da2015-04-21 17:37:00 -07006723 i, openOutputs.valueAt(i)->isDuplicated(),
François Gaffie11d30102018-11-02 16:09:09 +01006724 openOutputs.valueAt(i)->supportedDevices().toString().c_str());
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006725 if (openOutputs.valueAt(i)->supportsAllDevices(devices)
jiabin9a3361e2019-10-01 09:38:30 -07006726 && openOutputs.valueAt(i)->devicesSupportEncodedFormats(devices.types())) {
François Gaffie11d30102018-11-02 16:09:09 +01006727 ALOGVV("%s() found output %d", __func__, openOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07006728 outputs.add(openOutputs.keyAt(i));
6729 }
6730 }
6731 return outputs;
6732}
6733
Mikhail Naganov37977152018-07-11 15:54:44 -07006734void AudioPolicyManager::checkForDeviceAndOutputChanges(std::function<bool()> onOutputsChecked)
6735{
6736 // checkA2dpSuspend must run before checkOutputForAllStrategies so that A2DP
6737 // output is suspended before any tracks are moved to it
6738 checkA2dpSuspend();
6739 checkOutputForAllStrategies();
Kevin Rocard153f92d2018-12-18 18:33:28 -08006740 checkSecondaryOutputs();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11006741 if (onOutputsChecked != nullptr && onOutputsChecked()) checkA2dpSuspend();
Mikhail Naganov37977152018-07-11 15:54:44 -07006742 updateDevicesAndOutputs();
Mikhail Naganov7bd9b8d2018-11-15 02:09:03 +00006743 if (mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD) != 0) {
Michael Chan6fb34492020-12-08 15:44:49 +11006744 // TODO: The MSD patches to be established here may differ to current MSD patches due to how
6745 // output devices for patching are resolved. Nevertheless, AudioTracks affected by device
6746 // configuration changes will ultimately be rerouted correctly. We can still avoid
6747 // unnecessary rerouting by caching and reusing the arguments to
6748 // mEngine->getOutputDevicesForAttributes() when resolving which output devices to patch to.
6749 // This may be complicated by the fact that devices may become unavailable.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11006750 setMsdOutputPatches();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11006751 }
Jean-Michel Trivi9a6b9ad2020-10-22 16:46:43 -07006752 // an event that changed routing likely occurred, inform upper layers
6753 mpClientInterface->onRoutingUpdated();
Mikhail Naganov37977152018-07-11 15:54:44 -07006754}
6755
François Gaffiec005e562018-11-06 15:04:49 +01006756bool AudioPolicyManager::followsSameRouting(const audio_attributes_t &lAttr,
6757 const audio_attributes_t &rAttr) const
Eric Laurente552edb2014-03-10 17:42:56 -07006758{
François Gaffiec005e562018-11-06 15:04:49 +01006759 return mEngine->getProductStrategyForAttributes(lAttr) ==
6760 mEngine->getProductStrategyForAttributes(rAttr);
6761}
6762
Francois Gaffieff1eb522020-05-06 18:37:04 +02006763void AudioPolicyManager::checkAudioSourceForAttributes(const audio_attributes_t &attr)
6764{
6765 for (size_t i = 0; i < mAudioSources.size(); i++) {
6766 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
6767 if (sourceDesc != nullptr && followsSameRouting(attr, sourceDesc->attributes())
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02006768 && sourceDesc->getPatchHandle() == AUDIO_PATCH_HANDLE_NONE
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02006769 && !isCallRxAudioSource(sourceDesc) && !sourceDesc->isInternal()) {
Francois Gaffieff1eb522020-05-06 18:37:04 +02006770 connectAudioSource(sourceDesc);
6771 }
6772 }
6773}
6774
6775void AudioPolicyManager::clearAudioSourcesForOutput(audio_io_handle_t output)
6776{
6777 for (size_t i = 0; i < mAudioSources.size(); i++) {
6778 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
6779 if (sourceDesc != nullptr && sourceDesc->swOutput().promote() != nullptr
6780 && sourceDesc->swOutput().promote()->mIoHandle == output) {
6781 disconnectAudioSource(sourceDesc);
6782 }
6783 }
6784}
6785
François Gaffiec005e562018-11-06 15:04:49 +01006786void AudioPolicyManager::checkOutputForAttributes(const audio_attributes_t &attr)
6787{
6788 auto psId = mEngine->getProductStrategyForAttributes(attr);
6789
6790 DeviceVector oldDevices = mEngine->getOutputDevicesForAttributes(attr, 0, true /*fromCache*/);
6791 DeviceVector newDevices = mEngine->getOutputDevicesForAttributes(attr, 0, false /*fromCache*/);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07006792
François Gaffie11d30102018-11-02 16:09:09 +01006793 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevices(oldDevices, mPreviousOutputs);
6794 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevices(newDevices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07006795
Eric Laurentc209fe42020-06-05 18:11:23 -07006796 uint32_t maxLatency = 0;
Oscar Azucena873d10f2023-01-12 18:34:42 -08006797 bool unneededUsePrimaryOutputFromPolicyMixes = false;
Eric Laurent56ed8842022-11-15 16:04:41 +01006798 std::vector<sp<SwAudioOutputDescriptor>> invalidatedOutputs;
Eric Laurentc209fe42020-06-05 18:11:23 -07006799 // take into account dynamic audio policies related changes: if a client is now associated
6800 // to a different policy mix than at creation time, invalidate corresponding stream
Eric Laurent56ed8842022-11-15 16:04:41 +01006801 for (size_t i = 0; i < mPreviousOutputs.size(); i++) {
Eric Laurentc209fe42020-06-05 18:11:23 -07006802 const sp<SwAudioOutputDescriptor>& desc = mPreviousOutputs.valueAt(i);
6803 if (desc->isDuplicated()) {
6804 continue;
Jean-Michel Trivife472e22014-12-16 14:23:13 -08006805 }
Eric Laurentc209fe42020-06-05 18:11:23 -07006806 for (const sp<TrackClientDescriptor>& client : desc->getClientIterable()) {
6807 if (mEngine->getProductStrategyForAttributes(client->attributes()) != psId) {
6808 continue;
6809 }
6810 sp<AudioPolicyMix> primaryMix;
Dean Wheatleyd082f472022-02-04 11:10:48 +11006811 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->config(),
Oscar Azucena873d10f2023-01-12 18:34:42 -08006812 client->uid(), client->session(), client->flags(), mAvailableOutputDevices,
6813 nullptr /* requestedDevice */, primaryMix, nullptr /* secondaryMixes */,
6814 unneededUsePrimaryOutputFromPolicyMixes);
Eric Laurentc209fe42020-06-05 18:11:23 -07006815 if (status != OK) {
6816 continue;
6817 }
yucliuf4de36d2020-09-14 14:57:56 -07006818 if (client->getPrimaryMix() != primaryMix || client->hasLostPrimaryMix()) {
Eric Laurent56ed8842022-11-15 16:04:41 +01006819 if (desc->isStrategyActive(psId) && maxLatency < desc->latency()) {
Eric Laurentc209fe42020-06-05 18:11:23 -07006820 maxLatency = desc->latency();
6821 }
Eric Laurent56ed8842022-11-15 16:04:41 +01006822 invalidatedOutputs.push_back(desc);
Eric Laurentc209fe42020-06-05 18:11:23 -07006823 }
Jean-Michel Trivife472e22014-12-16 14:23:13 -08006824 }
6825 }
6826
Eric Laurent56ed8842022-11-15 16:04:41 +01006827 if (srcOutputs != dstOutputs || !invalidatedOutputs.empty()) {
Eric Laurentac3a6902018-05-11 16:39:10 -07006828 // get maximum latency of all source outputs to determine the minimum mute time guaranteeing
6829 // audio from invalidated tracks will be rendered when unmuting
Eric Laurentac3a6902018-05-11 16:39:10 -07006830 for (audio_io_handle_t srcOut : srcOutputs) {
6831 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
Eric Laurentaa02db82019-09-05 17:31:49 -07006832 if (desc == nullptr) continue;
6833
6834 if (desc->isStrategyActive(psId) && maxLatency < desc->latency()) {
Eric Laurentac3a6902018-05-11 16:39:10 -07006835 maxLatency = desc->latency();
6836 }
Eric Laurentaa02db82019-09-05 17:31:49 -07006837
Eric Laurent56ed8842022-11-15 16:04:41 +01006838 bool invalidate = false;
Eric Laurentaa02db82019-09-05 17:31:49 -07006839 for (auto client : desc->clientsList(false /*activeOnly*/)) {
Eric Laurent78aade82019-09-13 18:55:08 -07006840 if (desc->isDuplicated() || !desc->mProfile->isDirectOutput()) {
Eric Laurentaa02db82019-09-05 17:31:49 -07006841 // a client on a non direct outputs has necessarily a linear PCM format
6842 // so we can call selectOutput() safely
6843 const audio_io_handle_t newOutput = selectOutput(dstOutputs,
6844 client->flags(),
6845 client->config().format,
6846 client->config().channel_mask,
jiabinebb6af42020-06-09 17:31:17 -07006847 client->config().sample_rate,
6848 client->session());
Eric Laurentaa02db82019-09-05 17:31:49 -07006849 if (newOutput != srcOut) {
6850 invalidate = true;
6851 break;
6852 }
6853 } else {
6854 sp<IOProfile> profile = getProfileForOutput(newDevices,
6855 client->config().sample_rate,
6856 client->config().format,
6857 client->config().channel_mask,
6858 client->flags(),
6859 true /* directOnly */);
6860 if (profile != desc->mProfile) {
6861 invalidate = true;
6862 break;
6863 }
6864 }
6865 }
Eric Laurent56ed8842022-11-15 16:04:41 +01006866 // mute strategy while moving tracks from one output to another
6867 if (invalidate) {
6868 invalidatedOutputs.push_back(desc);
6869 if (desc->isStrategyActive(psId)) {
6870 setStrategyMute(psId, true, desc);
6871 setStrategyMute(psId, false, desc, maxLatency * LATENCY_MUTE_FACTOR,
6872 newDevices.types());
6873 }
Eric Laurente552edb2014-03-10 17:42:56 -07006874 }
François Gaffiec005e562018-11-06 15:04:49 +01006875 sp<SourceClientDescriptor> source = getSourceForAttributesOnOutput(srcOut, attr);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02006876 if (source != nullptr && !isCallRxAudioSource(source) && !source->isInternal()) {
Eric Laurentd60560a2015-04-10 11:31:20 -07006877 connectAudioSource(source);
6878 }
Eric Laurente552edb2014-03-10 17:42:56 -07006879 }
6880
Eric Laurent56ed8842022-11-15 16:04:41 +01006881 ALOGV_IF(!(srcOutputs.isEmpty() || dstOutputs.isEmpty()),
6882 "%s: strategy %d, moving from output %s to output %s", __func__, psId,
6883 std::to_string(srcOutputs[0]).c_str(),
6884 std::to_string(dstOutputs[0]).c_str());
6885
François Gaffiec005e562018-11-06 15:04:49 +01006886 // Move effects associated to this stream from previous output to new output
6887 if (followsSameRouting(attr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07006888 selectOutputForMusicEffects();
Eric Laurente552edb2014-03-10 17:42:56 -07006889 }
François Gaffiec005e562018-11-06 15:04:49 +01006890 // Move tracks associated to this stream (and linked) from previous output to new output
Eric Laurent56ed8842022-11-15 16:04:41 +01006891 if (!invalidatedOutputs.empty()) {
jiabinc44b3462022-12-08 12:52:31 -08006892 invalidateStreams(mEngine->getStreamTypesForProductStrategy(psId));
Eric Laurent56ed8842022-11-15 16:04:41 +01006893 for (sp<SwAudioOutputDescriptor> desc : invalidatedOutputs) {
jiabin49256852022-03-09 11:21:35 -08006894 desc->setTracksInvalidatedStatusByStrategy(psId);
6895 }
Eric Laurente552edb2014-03-10 17:42:56 -07006896 }
6897 }
6898}
6899
Eric Laurente0720872014-03-11 09:30:41 -07006900void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07006901{
François Gaffiec005e562018-11-06 15:04:49 +01006902 for (const auto &strategy : mEngine->getOrderedProductStrategies()) {
6903 auto attributes = mEngine->getAllAttributesForProductStrategy(strategy).front();
6904 checkOutputForAttributes(attributes);
Francois Gaffieff1eb522020-05-06 18:37:04 +02006905 checkAudioSourceForAttributes(attributes);
François Gaffiec005e562018-11-06 15:04:49 +01006906 }
Eric Laurente552edb2014-03-10 17:42:56 -07006907}
6908
Kevin Rocard153f92d2018-12-18 18:33:28 -08006909void AudioPolicyManager::checkSecondaryOutputs() {
jiabinc44b3462022-12-08 12:52:31 -08006910 PortHandleVector clientsToInvalidate;
jiabin10a03f12021-05-07 23:46:28 +00006911 TrackSecondaryOutputsMap trackSecondaryOutputs;
Oscar Azucena873d10f2023-01-12 18:34:42 -08006912 bool unneededUsePrimaryOutputFromPolicyMixes = false;
Kevin Rocard153f92d2018-12-18 18:33:28 -08006913 for (size_t i = 0; i < mOutputs.size(); i++) {
6914 const sp<SwAudioOutputDescriptor>& outputDescriptor = mOutputs[i];
6915 for (const sp<TrackClientDescriptor>& client : outputDescriptor->getClientIterable()) {
Eric Laurentc529cf62020-04-17 18:19:10 -07006916 sp<AudioPolicyMix> primaryMix;
6917 std::vector<sp<AudioPolicyMix>> secondaryMixes;
Dean Wheatleyd082f472022-02-04 11:10:48 +11006918 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->config(),
Oscar Azucena873d10f2023-01-12 18:34:42 -08006919 client->uid(), client->session(), client->flags(), mAvailableOutputDevices,
6920 nullptr /* requestedDevice */, primaryMix, &secondaryMixes,
6921 unneededUsePrimaryOutputFromPolicyMixes);
Eric Laurentc529cf62020-04-17 18:19:10 -07006922 std::vector<sp<SwAudioOutputDescriptor>> secondaryDescs;
6923 for (auto &secondaryMix : secondaryMixes) {
6924 sp<SwAudioOutputDescriptor> outputDesc = secondaryMix->getOutput();
6925 if (outputDesc != nullptr &&
6926 outputDesc->mIoHandle != AUDIO_IO_HANDLE_NONE) {
6927 secondaryDescs.push_back(outputDesc);
6928 }
6929 }
6930
jiabinc44b3462022-12-08 12:52:31 -08006931 if (status != OK &&
6932 (client->flags() & AUDIO_OUTPUT_FLAG_MMAP_NOIRQ) == AUDIO_OUTPUT_FLAG_NONE) {
6933 // When it failed to query secondary output, only invalidate the client that is not
6934 // MMAP. The reason is that MMAP stream will not support secondary output.
6935 clientsToInvalidate.push_back(client->portId());
jiabin10a03f12021-05-07 23:46:28 +00006936 } else if (!std::equal(
6937 client->getSecondaryOutputs().begin(),
6938 client->getSecondaryOutputs().end(),
6939 secondaryDescs.begin(), secondaryDescs.end())) {
jiabina5281062021-11-23 00:10:23 +00006940 if (!audio_is_linear_pcm(client->config().format)) {
6941 // If the format is not PCM, the tracks should be invalidated to get correct
6942 // behavior when the secondary output is changed.
jiabinc44b3462022-12-08 12:52:31 -08006943 clientsToInvalidate.push_back(client->portId());
jiabina5281062021-11-23 00:10:23 +00006944 } else {
6945 std::vector<wp<SwAudioOutputDescriptor>> weakSecondaryDescs;
6946 std::vector<audio_io_handle_t> secondaryOutputIds;
6947 for (const auto &secondaryDesc: secondaryDescs) {
6948 secondaryOutputIds.push_back(secondaryDesc->mIoHandle);
6949 weakSecondaryDescs.push_back(secondaryDesc);
6950 }
6951 trackSecondaryOutputs.emplace(client->portId(), secondaryOutputIds);
6952 client->setSecondaryOutputs(std::move(weakSecondaryDescs));
jiabin10a03f12021-05-07 23:46:28 +00006953 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08006954 }
6955 }
6956 }
jiabin10a03f12021-05-07 23:46:28 +00006957 if (!trackSecondaryOutputs.empty()) {
6958 mpClientInterface->updateSecondaryOutputs(trackSecondaryOutputs);
6959 }
jiabinc44b3462022-12-08 12:52:31 -08006960 if (!clientsToInvalidate.empty()) {
6961 ALOGD("%s Invalidate clients due to fail getting output for attr", __func__);
6962 mpClientInterface->invalidateTracks(clientsToInvalidate);
Kevin Rocard153f92d2018-12-18 18:33:28 -08006963 }
6964}
6965
Eric Laurent2517af32020-11-25 15:31:27 +01006966bool AudioPolicyManager::isScoRequestedForComm() const {
6967 AudioDeviceTypeAddrVector devices;
6968 mEngine->getDevicesForRoleAndStrategy(mCommunnicationStrategy, DEVICE_ROLE_PREFERRED, devices);
6969 for (const auto &device : devices) {
6970 if (audio_is_bluetooth_out_sco_device(device.mType)) {
6971 return true;
6972 }
6973 }
6974 return false;
6975}
6976
Eric Laurent1a8b45f2022-04-13 16:01:47 +02006977bool AudioPolicyManager::isHearingAidUsedForComm() const {
6978 DeviceVector devices = mEngine->getOutputDevicesForStream(AUDIO_STREAM_VOICE_CALL,
6979 true /*fromCache*/);
6980 for (const auto &device : devices) {
6981 if (device->type() == AUDIO_DEVICE_OUT_HEARING_AID) {
6982 return true;
6983 }
6984 }
6985 return false;
6986}
6987
6988
Eric Laurente0720872014-03-11 09:30:41 -07006989void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07006990{
François Gaffie53615e22015-03-19 09:24:12 +01006991 audio_io_handle_t a2dpOutput = mOutputs.getA2dpOutput();
Aniket Kumar Lataa8ee9962018-01-31 20:24:23 -08006992 if (a2dpOutput == 0 || mOutputs.isA2dpOffloadedOnPrimary()) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07006993 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07006994 return;
6995 }
6996
Eric Laurent3a4311c2014-03-17 12:00:47 -07006997 bool isScoConnected =
jiabin9a3361e2019-10-01 09:38:30 -07006998 (mAvailableInputDevices.types().count(AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) != 0 ||
6999 !Intersection(mAvailableOutputDevices.types(), getAudioDeviceOutAllScoSet()).empty());
Eric Laurent2517af32020-11-25 15:31:27 +01007000 bool isScoRequested = isScoRequestedForComm();
Eric Laurentf732e072016-08-03 19:30:28 -07007001
7002 // if suspended, restore A2DP output if:
7003 // ((SCO device is NOT connected) ||
Eric Laurent2517af32020-11-25 15:31:27 +01007004 // ((SCO is not requested) &&
Eric Laurentf732e072016-08-03 19:30:28 -07007005 // (phone state is NOT in call) && (phone state is NOT ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07007006 //
Eric Laurentf732e072016-08-03 19:30:28 -07007007 // if not suspended, suspend A2DP output if:
7008 // (SCO device is connected) &&
Eric Laurent2517af32020-11-25 15:31:27 +01007009 // ((SCO is requested) ||
Eric Laurentf732e072016-08-03 19:30:28 -07007010 // ((phone state is in call) || (phone state is ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07007011 //
7012 if (mA2dpSuspended) {
Eric Laurentf732e072016-08-03 19:30:28 -07007013 if (!isScoConnected ||
Eric Laurent2517af32020-11-25 15:31:27 +01007014 (!isScoRequested &&
Eric Laurentf732e072016-08-03 19:30:28 -07007015 (mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) &&
François Gaffie2110e042015-03-24 08:41:51 +01007016 (mEngine->getPhoneState() != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07007017
7018 mpClientInterface->restoreOutput(a2dpOutput);
7019 mA2dpSuspended = false;
7020 }
7021 } else {
Eric Laurentf732e072016-08-03 19:30:28 -07007022 if (isScoConnected &&
Eric Laurent2517af32020-11-25 15:31:27 +01007023 (isScoRequested ||
Eric Laurentf732e072016-08-03 19:30:28 -07007024 (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) ||
François Gaffie2110e042015-03-24 08:41:51 +01007025 (mEngine->getPhoneState() == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07007026
7027 mpClientInterface->suspendOutput(a2dpOutput);
7028 mA2dpSuspended = true;
7029 }
7030 }
7031}
7032
François Gaffie11d30102018-11-02 16:09:09 +01007033DeviceVector AudioPolicyManager::getNewOutputDevices(const sp<SwAudioOutputDescriptor>& outputDesc,
7034 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07007035{
François Gaffie11d30102018-11-02 16:09:09 +01007036 DeviceVector devices;
7037
Jean-Michel Triviff155c62016-02-26 12:07:16 -08007038 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007039 if (index >= 0) {
7040 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007041 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01007042 ALOGV("%s device %s forced by patch %d", __func__,
7043 outputDesc->devices().toString().c_str(), outputDesc->getPatchHandle());
7044 return outputDesc->devices();
Eric Laurent6a94d692014-05-20 11:18:06 -07007045 }
7046 }
7047
Dean Wheatley514b4312020-06-17 21:45:00 +10007048 // Do not retrieve engine device for outputs through MSD
7049 // TODO: support explicit routing requests by resetting MSD patch to engine device.
7050 if (outputDesc->devices() == getMsdAudioOutDevices()) {
7051 return outputDesc->devices();
7052 }
7053
Eric Laurent97ac8712018-07-27 18:59:02 -07007054 // Honor explicit routing requests only if no client using default routing is active on this
7055 // input: a specific app can not force routing for other apps by setting a preferred device.
7056 bool active; // unused
François Gaffie11d30102018-11-02 16:09:09 +01007057 sp<DeviceDescriptor> device =
François Gaffiec005e562018-11-06 15:04:49 +01007058 findPreferredDevice(outputDesc, PRODUCT_STRATEGY_NONE, active, mAvailableOutputDevices);
François Gaffie11d30102018-11-02 16:09:09 +01007059 if (device != nullptr) {
7060 return DeviceVector(device);
Eric Laurentf3a5a602018-05-22 18:42:55 -07007061 }
7062
François Gaffiea807ef92018-11-05 10:44:33 +01007063 // Legacy Engine cannot take care of bus devices and mix, so we need to handle the conflict
7064 // of setForceUse / Default Bus device here
7065 device = mPolicyMixes.getDeviceAndMixForOutput(outputDesc, mAvailableOutputDevices);
7066 if (device != nullptr) {
7067 return DeviceVector(device);
7068 }
7069
François Gaffiec005e562018-11-06 15:04:49 +01007070 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
7071 StreamTypeVector streams = mEngine->getStreamTypesForProductStrategy(productStrategy);
7072 auto attr = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307073 auto hasStreamActive = [&](auto stream) {
7074 return hasStream(streams, stream) && isStreamActive(stream, 0);
7075 };
Eric Laurent484e9272018-06-07 17:29:23 -07007076
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307077 auto doGetOutputDevicesForVoice = [&]() {
7078 return hasVoiceStream(streams) && (outputDesc == mPrimaryOutput ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007079 outputDesc->isActive(toVolumeSource(AUDIO_STREAM_VOICE_CALL, false))) &&
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307080 (isInCall() ||
Henrik Backlund07c654a2021-10-14 15:57:10 +02007081 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc)) &&
7082 !isStreamActive(AUDIO_STREAM_ENFORCED_AUDIBLE, 0);
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307083 };
7084
7085 // With low-latency playing on speaker, music on WFD, when the first low-latency
7086 // output is stopped, getNewOutputDevices checks for a product strategy
7087 // from the list, as STRATEGY_SONIFICATION comes prior to STRATEGY_MEDIA.
Carter Hsucc58a6b2021-07-20 08:44:50 +00007088 // If an ALARM or ENFORCED_AUDIBLE stream is supported by the product strategy,
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307089 // devices are returned for STRATEGY_SONIFICATION without checking whether the
7090 // stream is associated to the output descriptor.
7091 if (doGetOutputDevicesForVoice() || outputDesc->isStrategyActive(productStrategy) ||
7092 ((hasStreamActive(AUDIO_STREAM_ALARM) ||
7093 hasStreamActive(AUDIO_STREAM_ENFORCED_AUDIBLE)) &&
7094 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc))) {
François Gaffiec005e562018-11-06 15:04:49 +01007095 // Retrieval of devices for voice DL is done on primary output profile, cannot
7096 // check the route (would force modifying configuration file for this profile)
7097 devices = mEngine->getOutputDevicesForAttributes(attr, nullptr, fromCache);
7098 break;
7099 }
Eric Laurente552edb2014-03-10 17:42:56 -07007100 }
François Gaffiec005e562018-11-06 15:04:49 +01007101 ALOGV("%s selected devices %s", __func__, devices.toString().c_str());
François Gaffie11d30102018-11-02 16:09:09 +01007102 return devices;
Eric Laurent1c333e22014-05-20 10:48:17 -07007103}
7104
François Gaffie11d30102018-11-02 16:09:09 +01007105sp<DeviceDescriptor> AudioPolicyManager::getNewInputDevice(
7106 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurent1c333e22014-05-20 10:48:17 -07007107{
François Gaffie11d30102018-11-02 16:09:09 +01007108 sp<DeviceDescriptor> device;
Eric Laurent6a94d692014-05-20 11:18:06 -07007109
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08007110 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007111 if (index >= 0) {
7112 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007113 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01007114 ALOGV("getNewInputDevice() device %s forced by patch %d",
7115 inputDesc->getDevice()->toString().c_str(), inputDesc->getPatchHandle());
7116 return inputDesc->getDevice();
Eric Laurent6a94d692014-05-20 11:18:06 -07007117 }
7118 }
7119
Eric Laurent97ac8712018-07-27 18:59:02 -07007120 // Honor explicit routing requests only if no client using default routing is active on this
7121 // input: a specific app can not force routing for other apps by setting a preferred device.
7122 bool active;
François Gaffie11d30102018-11-02 16:09:09 +01007123 device = findPreferredDevice(inputDesc, AUDIO_SOURCE_DEFAULT, active, mAvailableInputDevices);
7124 if (device != nullptr) {
7125 return device;
Eric Laurent97ac8712018-07-27 18:59:02 -07007126 }
7127
Eric Laurentdc95a252018-04-12 12:46:56 -07007128 // If we are not in call and no client is active on this input, this methods returns
Andy Hungf024a9e2019-01-30 16:01:02 -08007129 // a null sp<>, causing the patch on the input stream to be released.
yuanjiahsu0735bf32021-03-18 08:12:54 +08007130 audio_attributes_t attributes;
7131 uid_t uid;
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007132 audio_session_t session;
yuanjiahsu0735bf32021-03-18 08:12:54 +08007133 sp<RecordClientDescriptor> topClient = inputDesc->getHighestPriorityClient();
7134 if (topClient != nullptr) {
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01007135 attributes = topClient->attributes();
7136 uid = topClient->uid();
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007137 session = topClient->session();
yuanjiahsu0735bf32021-03-18 08:12:54 +08007138 } else {
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01007139 attributes = { .source = AUDIO_SOURCE_DEFAULT };
7140 uid = 0;
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007141 session = AUDIO_SESSION_NONE;
yuanjiahsu0735bf32021-03-18 08:12:54 +08007142 }
7143
Francois Gaffie716e1432019-01-14 16:58:59 +01007144 if (attributes.source == AUDIO_SOURCE_DEFAULT && isInCall()) {
7145 attributes.source = AUDIO_SOURCE_VOICE_COMMUNICATION;
Eric Laurentdc95a252018-04-12 12:46:56 -07007146 }
Francois Gaffie716e1432019-01-14 16:58:59 +01007147 if (attributes.source != AUDIO_SOURCE_DEFAULT) {
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007148 device = mEngine->getInputDeviceForAttributes(attributes, uid, session);
Eric Laurentfb66dd92016-01-28 18:32:03 -08007149 }
Eric Laurent1c333e22014-05-20 10:48:17 -07007150
Eric Laurente552edb2014-03-10 17:42:56 -07007151 return device;
7152}
7153
Eric Laurent794fde22016-03-11 09:50:45 -08007154bool AudioPolicyManager::streamsMatchForvolume(audio_stream_type_t stream1,
7155 audio_stream_type_t stream2) {
Jean-Michel Trivi99bb2f92016-11-23 15:52:07 -08007156 return (stream1 == stream2);
Eric Laurent28d09f02016-03-08 10:43:05 -08007157}
7158
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08007159status_t AudioPolicyManager::getDevicesForAttributes(
Andy Hung6d23c0f2022-02-16 09:37:15 -08007160 const audio_attributes_t &attr, AudioDeviceTypeAddrVector *devices, bool forVolume) {
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08007161 if (devices == nullptr) {
7162 return BAD_VALUE;
7163 }
Andy Hung6d23c0f2022-02-16 09:37:15 -08007164
Andy Hung6d23c0f2022-02-16 09:37:15 -08007165 DeviceVector curDevices;
jiabinf1c73972022-04-14 16:28:52 -07007166 if (status_t status = getDevicesForAttributes(attr, curDevices, forVolume); status != OK) {
7167 return status;
Andy Hung6d23c0f2022-02-16 09:37:15 -08007168 }
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08007169 for (const auto& device : curDevices) {
7170 devices->push_back(device->getDeviceTypeAddr());
7171 }
7172 return NO_ERROR;
7173}
7174
Eric Laurente0720872014-03-11 09:30:41 -07007175void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07007176 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07007177 case AUDIO_STREAM_MUSIC:
François Gaffiec005e562018-11-06 15:04:49 +01007178 checkOutputForAttributes(attributes_initializer(AUDIO_USAGE_NOTIFICATION));
Eric Laurente552edb2014-03-10 17:42:56 -07007179 updateDevicesAndOutputs();
7180 break;
7181 default:
7182 break;
7183 }
7184}
7185
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007186uint32_t AudioPolicyManager::handleEventForBeacon(int event) {
Eric Laurent9459fb02015-08-12 18:36:32 -07007187
7188 // skip beacon mute management if a dedicated TTS output is available
7189 if (mTtsOutputAvailable) {
7190 return 0;
7191 }
7192
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007193 switch(event) {
7194 case STARTING_OUTPUT:
7195 mBeaconMuteRefCount++;
7196 break;
7197 case STOPPING_OUTPUT:
7198 if (mBeaconMuteRefCount > 0) {
7199 mBeaconMuteRefCount--;
7200 }
7201 break;
7202 case STARTING_BEACON:
7203 mBeaconPlayingRefCount++;
7204 break;
7205 case STOPPING_BEACON:
7206 if (mBeaconPlayingRefCount > 0) {
7207 mBeaconPlayingRefCount--;
7208 }
7209 break;
7210 }
7211
7212 if (mBeaconMuteRefCount > 0) {
7213 // any playback causes beacon to be muted
7214 return setBeaconMute(true);
7215 } else {
7216 // no other playback: unmute when beacon starts playing, mute when it stops
7217 return setBeaconMute(mBeaconPlayingRefCount == 0);
7218 }
7219}
7220
7221uint32_t AudioPolicyManager::setBeaconMute(bool mute) {
7222 ALOGV("setBeaconMute(%d) mBeaconMuteRefCount=%d mBeaconPlayingRefCount=%d",
7223 mute, mBeaconMuteRefCount, mBeaconPlayingRefCount);
7224 // keep track of muted state to avoid repeating mute/unmute operations
7225 if (mBeaconMuted != mute) {
7226 // mute/unmute AUDIO_STREAM_TTS on all outputs
7227 ALOGV("\t muting %d", mute);
7228 uint32_t maxLatency = 0;
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007229 auto ttsVolumeSource = toVolumeSource(AUDIO_STREAM_TTS, false);
7230 if (ttsVolumeSource == VOLUME_SOURCE_NONE) {
7231 ALOGV("\t no tts volume source available");
7232 return 0;
7233 }
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007234 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07007235 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
jiabin9a3361e2019-10-01 09:38:30 -07007236 setVolumeSourceMute(ttsVolumeSource, mute/*on*/, desc, 0 /*delay*/, DeviceTypeSet());
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007237 const uint32_t latency = desc->latency() * 2;
Eric Laurentcdb2b352020-07-23 10:57:02 -07007238 if (desc->isActive(latency * 2) && latency > maxLatency) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007239 maxLatency = latency;
7240 }
7241 }
7242 mBeaconMuted = mute;
7243 return maxLatency;
7244 }
7245 return 0;
7246}
7247
Eric Laurente0720872014-03-11 09:30:41 -07007248void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07007249{
François Gaffiec005e562018-11-06 15:04:49 +01007250 mEngine->updateDeviceSelectionCache();
Eric Laurente552edb2014-03-10 17:42:56 -07007251 mPreviousOutputs = mOutputs;
7252}
7253
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07007254uint32_t AudioPolicyManager::checkDeviceMuteStrategies(const sp<AudioOutputDescriptor>& outputDesc,
François Gaffiec005e562018-11-06 15:04:49 +01007255 const DeviceVector &prevDevices,
Eric Laurente552edb2014-03-10 17:42:56 -07007256 uint32_t delayMs)
7257{
7258 // mute/unmute strategies using an incompatible device combination
7259 // if muting, wait for the audio in pcm buffer to be drained before proceeding
7260 // if unmuting, unmute only after the specified delay
7261 if (outputDesc->isDuplicated()) {
7262 return 0;
7263 }
7264
7265 uint32_t muteWaitMs = 0;
François Gaffiec005e562018-11-06 15:04:49 +01007266 DeviceVector devices = outputDesc->devices();
7267 bool shouldMute = outputDesc->isActive() && (devices.size() >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07007268
François Gaffiec005e562018-11-06 15:04:49 +01007269 auto productStrategies = mEngine->getOrderedProductStrategies();
7270 for (const auto &productStrategy : productStrategies) {
7271 auto attributes = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
7272 DeviceVector curDevices =
7273 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false/*fromCache*/);
7274 curDevices = curDevices.filter(outputDesc->supportedDevices());
7275 bool mute = shouldMute && curDevices.containsAtLeastOne(devices) && curDevices != devices;
Eric Laurente552edb2014-03-10 17:42:56 -07007276 bool doMute = false;
7277
François Gaffiec005e562018-11-06 15:04:49 +01007278 if (mute && !outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07007279 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01007280 outputDesc->setStrategyMutedByDevice(productStrategy, true);
7281 } else if (!mute && outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07007282 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01007283 outputDesc->setStrategyMutedByDevice(productStrategy, false);
Eric Laurente552edb2014-03-10 17:42:56 -07007284 }
Eric Laurent99401132014-05-07 19:48:15 -07007285 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07007286 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07007287 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07007288 // skip output if it does not share any device with current output
François Gaffie11d30102018-11-02 16:09:09 +01007289 if (!desc->supportedDevices().containsAtLeastOne(outputDesc->supportedDevices())) {
Eric Laurente552edb2014-03-10 17:42:56 -07007290 continue;
7291 }
François Gaffiec005e562018-11-06 15:04:49 +01007292 ALOGVV("%s() %s (curDevice %s)", __func__,
7293 mute ? "muting" : "unmuting", curDevices.toString().c_str());
7294 setStrategyMute(productStrategy, mute, desc, mute ? 0 : delayMs);
7295 if (desc->isStrategyActive(productStrategy)) {
Eric Laurent99401132014-05-07 19:48:15 -07007296 if (mute) {
7297 // FIXME: should not need to double latency if volume could be applied
7298 // immediately by the audioflinger mixer. We must account for the delay
7299 // between now and the next time the audioflinger thread for this output
7300 // will process a buffer (which corresponds to one buffer size,
7301 // usually 1/2 or 1/4 of the latency).
7302 if (muteWaitMs < desc->latency() * 2) {
7303 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07007304 }
7305 }
7306 }
7307 }
7308 }
7309 }
7310
Eric Laurent99401132014-05-07 19:48:15 -07007311 // temporary mute output if device selection changes to avoid volume bursts due to
7312 // different per device volumes
François Gaffiec005e562018-11-06 15:04:49 +01007313 if (outputDesc->isActive() && (devices != prevDevices)) {
Eric Laurentdc462862016-07-19 12:29:53 -07007314 uint32_t tempMuteWaitMs = outputDesc->latency() * 2;
Jasmine Chaf6074fe2021-08-17 13:44:31 +08007315
Eric Laurentdc462862016-07-19 12:29:53 -07007316 if (muteWaitMs < tempMuteWaitMs) {
7317 muteWaitMs = tempMuteWaitMs;
Eric Laurent99401132014-05-07 19:48:15 -07007318 }
Jasmine Chaf6074fe2021-08-17 13:44:31 +08007319
7320 // If recommended duration is defined, replace temporary mute duration to avoid
7321 // truncated notifications at beginning, which depends on duration of changing path in HAL.
7322 // Otherwise, temporary mute duration is conservatively set to 4 times the reported latency.
7323 uint32_t tempRecommendedMuteDuration = outputDesc->getRecommendedMuteDurationMs();
7324 uint32_t tempMuteDurationMs = tempRecommendedMuteDuration > 0 ?
7325 tempRecommendedMuteDuration : outputDesc->latency() * 4;
7326
François Gaffieaaac0fd2018-11-22 17:56:39 +01007327 for (const auto &activeVs : outputDesc->getActiveVolumeSources()) {
7328 // make sure that we do not start the temporary mute period too early in case of
7329 // delayed device change
7330 setVolumeSourceMute(activeVs, true, outputDesc, delayMs);
7331 setVolumeSourceMute(activeVs, false, outputDesc, delayMs + tempMuteDurationMs,
François Gaffiec005e562018-11-06 15:04:49 +01007332 devices.types());
Eric Laurent99401132014-05-07 19:48:15 -07007333 }
7334 }
7335
Eric Laurente552edb2014-03-10 17:42:56 -07007336 // wait for the PCM output buffers to empty before proceeding with the rest of the command
7337 if (muteWaitMs > delayMs) {
7338 muteWaitMs -= delayMs;
7339 usleep(muteWaitMs * 1000);
7340 return muteWaitMs;
7341 }
7342 return 0;
7343}
7344
François Gaffie11d30102018-11-02 16:09:09 +01007345uint32_t AudioPolicyManager::setOutputDevices(const sp<SwAudioOutputDescriptor>& outputDesc,
7346 const DeviceVector &devices,
7347 bool force,
7348 int delayMs,
7349 audio_patch_handle_t *patchHandle,
Francois Gaffie3523ab32021-06-22 13:24:34 +02007350 bool requiresMuteCheck, bool requiresVolumeCheck)
Eric Laurente552edb2014-03-10 17:42:56 -07007351{
jiabin3ff8d7d2022-12-13 06:27:44 +00007352 // TODO(b/262404095): Consider if the output need to be reopened.
François Gaffie11d30102018-11-02 16:09:09 +01007353 ALOGV("%s device %s delayMs %d", __func__, devices.toString().c_str(), delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07007354 uint32_t muteWaitMs;
7355
7356 if (outputDesc->isDuplicated()) {
François Gaffie11d30102018-11-02 16:09:09 +01007357 muteWaitMs = setOutputDevices(outputDesc->subOutput1(), devices, force, delayMs,
7358 nullptr /* patchHandle */, requiresMuteCheck);
7359 muteWaitMs += setOutputDevices(outputDesc->subOutput2(), devices, force, delayMs,
7360 nullptr /* patchHandle */, requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07007361 return muteWaitMs;
7362 }
Eric Laurente552edb2014-03-10 17:42:56 -07007363
7364 // filter devices according to output selected
Francois Gaffie716e1432019-01-14 16:58:59 +01007365 DeviceVector filteredDevices = outputDesc->filterSupportedDevices(devices);
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01007366 DeviceVector prevDevices = outputDesc->devices();
Francois Gaffie3523ab32021-06-22 13:24:34 +02007367 DeviceVector availPrevDevices = mAvailableOutputDevices.filter(prevDevices);
Eric Laurente552edb2014-03-10 17:42:56 -07007368
François Gaffie11d30102018-11-02 16:09:09 +01007369 ALOGV("setOutputDevices() prevDevice %s", prevDevices.toString().c_str());
7370
7371 if (!filteredDevices.isEmpty()) {
7372 outputDesc->setDevices(filteredDevices);
Eric Laurente552edb2014-03-10 17:42:56 -07007373 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00007374
7375 // if the outputs are not materially active, there is no need to mute.
7376 if (requiresMuteCheck) {
François Gaffiec005e562018-11-06 15:04:49 +01007377 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevices, delayMs);
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00007378 } else {
7379 ALOGV("%s: suppressing checkDeviceMuteStrategies", __func__);
7380 muteWaitMs = 0;
7381 }
Eric Laurente552edb2014-03-10 17:42:56 -07007382
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02007383 bool outputRouted = outputDesc->isRouted();
7384
Eric Laurent79ea9582020-06-11 18:49:24 -07007385 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
7386 // output profile or if new device is not supported AND previous device(s) is(are) still
7387 // available (otherwise reset device must be done on the output)
Francois Gaffie3523ab32021-06-22 13:24:34 +02007388 if (!devices.isEmpty() && filteredDevices.isEmpty() && !availPrevDevices.empty()) {
Eric Laurent79ea9582020-06-11 18:49:24 -07007389 ALOGV("%s: unsupported device %s for output", __func__, devices.toString().c_str());
7390 // restore previous device after evaluating strategy mute state
7391 outputDesc->setDevices(prevDevices);
7392 return muteWaitMs;
7393 }
7394
Eric Laurente552edb2014-03-10 17:42:56 -07007395 // Do not change the routing if:
Eric Laurentb80a2a82014-10-27 16:07:59 -07007396 // the requested device is AUDIO_DEVICE_NONE
7397 // OR the requested device is the same as current device
7398 // AND force is not specified
7399 // AND the output is connected by a valid audio patch.
François Gaffie11d30102018-11-02 16:09:09 +01007400 // Doing this check here allows the caller to call setOutputDevices() without conditions
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02007401 if ((filteredDevices.isEmpty() || filteredDevices == prevDevices) && !force && outputRouted) {
François Gaffie11d30102018-11-02 16:09:09 +01007402 ALOGV("%s setting same device %s or null device, force=%d, patch handle=%d", __func__,
7403 filteredDevices.toString().c_str(), force, outputDesc->getPatchHandle());
Francois Gaffie3523ab32021-06-22 13:24:34 +02007404 if (requiresVolumeCheck && !filteredDevices.isEmpty()) {
7405 ALOGV("%s setting same device on routed output, force apply volumes", __func__);
7406 applyStreamVolumes(outputDesc, filteredDevices.types(), delayMs, true /*force*/);
7407 }
Eric Laurente552edb2014-03-10 17:42:56 -07007408 return muteWaitMs;
7409 }
7410
François Gaffie11d30102018-11-02 16:09:09 +01007411 ALOGV("%s changing device to %s", __func__, filteredDevices.toString().c_str());
Eric Laurent1c333e22014-05-20 10:48:17 -07007412
Eric Laurente552edb2014-03-10 17:42:56 -07007413 // do the routing
Francois Gaffie3523ab32021-06-22 13:24:34 +02007414 if (filteredDevices.isEmpty() || mAvailableOutputDevices.filter(filteredDevices).empty()) {
Eric Laurentc75307b2015-03-17 15:29:32 -07007415 resetOutputDevice(outputDesc, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07007416 } else {
François Gaffie11d30102018-11-02 16:09:09 +01007417 PatchBuilder patchBuilder;
7418 patchBuilder.addSource(outputDesc);
7419 ALOG_ASSERT(filteredDevices.size() <= AUDIO_PATCH_PORTS_MAX, "Too many sink ports");
7420 for (const auto &filteredDevice : filteredDevices) {
7421 patchBuilder.addSink(filteredDevice);
Eric Laurentc40d9692016-04-13 19:14:13 -07007422 }
7423
Jasmine Cha7f82d1a2020-03-16 13:21:47 +08007424 // Add half reported latency to delayMs when muteWaitMs is null in order
7425 // to avoid disordered sequence of muting volume and changing devices.
7426 installPatch(__func__, patchHandle, outputDesc.get(), patchBuilder.patch(),
7427 muteWaitMs == 0 ? (delayMs + (outputDesc->latency() / 2)) : delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07007428 }
Eric Laurente552edb2014-03-10 17:42:56 -07007429
7430 // update stream volumes according to new device
François Gaffie11d30102018-11-02 16:09:09 +01007431 applyStreamVolumes(outputDesc, filteredDevices.types(), delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07007432
7433 return muteWaitMs;
7434}
7435
Eric Laurentc75307b2015-03-17 15:29:32 -07007436status_t AudioPolicyManager::resetOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurent6a94d692014-05-20 11:18:06 -07007437 int delayMs,
7438 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07007439{
Eric Laurent6a94d692014-05-20 11:18:06 -07007440 ssize_t index;
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02007441 if (patchHandle == nullptr && !outputDesc->isRouted()) {
7442 return INVALID_OPERATION;
7443 }
Eric Laurent6a94d692014-05-20 11:18:06 -07007444 if (patchHandle) {
7445 index = mAudioPatches.indexOfKey(*patchHandle);
7446 } else {
Jean-Michel Triviff155c62016-02-26 12:07:16 -08007447 index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007448 }
7449 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07007450 return INVALID_OPERATION;
7451 }
Eric Laurent6a94d692014-05-20 11:18:06 -07007452 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007453 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07007454 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07007455 outputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
François Gaffieafd4cea2019-11-18 15:50:22 +01007456 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007457 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07007458 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07007459 return status;
7460}
7461
7462status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
François Gaffie11d30102018-11-02 16:09:09 +01007463 const sp<DeviceDescriptor> &device,
Eric Laurent6a94d692014-05-20 11:18:06 -07007464 bool force,
7465 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07007466{
7467 status_t status = NO_ERROR;
7468
Eric Laurent1f2f2232014-06-02 12:01:23 -07007469 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
François Gaffie11d30102018-11-02 16:09:09 +01007470 if ((device != nullptr) && ((device != inputDesc->getDevice()) || force)) {
7471 inputDesc->setDevice(device);
Eric Laurent1c333e22014-05-20 10:48:17 -07007472
François Gaffie11d30102018-11-02 16:09:09 +01007473 if (mAvailableInputDevices.contains(device)) {
Mikhail Naganovdc769682018-05-04 15:34:08 -07007474 PatchBuilder patchBuilder;
7475 patchBuilder.addSink(inputDesc,
Eric Laurentdaf92cc2014-07-22 15:36:10 -07007476 // AUDIO_SOURCE_HOTWORD is for internal use only:
7477 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
Mikhail Naganovdc769682018-05-04 15:34:08 -07007478 [inputDesc](const PatchBuilder::mix_usecase_t& usecase) {
7479 auto result = usecase;
7480 if (result.source == AUDIO_SOURCE_HOTWORD && !inputDesc->isSoundTrigger()) {
7481 result.source = AUDIO_SOURCE_VOICE_RECOGNITION;
7482 }
7483 return result; }).
Eric Laurent1c333e22014-05-20 10:48:17 -07007484 //only one input device for now
François Gaffie11d30102018-11-02 16:09:09 +01007485 addSource(device);
Mikhail Naganovdc769682018-05-04 15:34:08 -07007486 status = installPatch(__func__, patchHandle, inputDesc.get(), patchBuilder.patch(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07007487 }
7488 }
7489 return status;
7490}
7491
Eric Laurent6a94d692014-05-20 11:18:06 -07007492status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
7493 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07007494{
Eric Laurent1f2f2232014-06-02 12:01:23 -07007495 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07007496 ssize_t index;
7497 if (patchHandle) {
7498 index = mAudioPatches.indexOfKey(*patchHandle);
7499 } else {
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08007500 index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007501 }
7502 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07007503 return INVALID_OPERATION;
7504 }
Eric Laurent6a94d692014-05-20 11:18:06 -07007505 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007506 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07007507 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07007508 inputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
François Gaffieafd4cea2019-11-18 15:50:22 +01007509 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007510 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07007511 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07007512 return status;
7513}
7514
François Gaffie11d30102018-11-02 16:09:09 +01007515sp<IOProfile> AudioPolicyManager::getInputProfile(const sp<DeviceDescriptor> &device,
François Gaffie53615e22015-03-19 09:24:12 +01007516 uint32_t& samplingRate,
Andy Hungf129b032015-04-07 13:45:50 -07007517 audio_format_t& format,
7518 audio_channel_mask_t& channelMask,
François Gaffie53615e22015-03-19 09:24:12 +01007519 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07007520{
7521 // Choose an input profile based on the requested capture parameters: select the first available
7522 // profile supporting all requested parameters.
jiabin2fd710d2022-05-02 23:20:22 +00007523 // The flags can be ignored if it doesn't contain a much match flag.
Andy Hungf129b032015-04-07 13:45:50 -07007524 //
7525 // TODO: perhaps isCompatibleProfile should return a "matching" score so we can return
7526 // the best matching profile, not the first one.
Eric Laurente552edb2014-03-10 17:42:56 -07007527
Atneya Nair0f0a8032022-12-12 16:20:12 -08007528 using underlying_input_flag_t = std::underlying_type_t<audio_input_flags_t>;
7529 const underlying_input_flag_t mustMatchFlag = AUDIO_INPUT_FLAG_MMAP_NOIRQ |
7530 AUDIO_INPUT_FLAG_HOTWORD_TAP | AUDIO_INPUT_FLAG_HW_LOOKBACK;
7531
7532 const underlying_input_flag_t oriFlags = flags;
Glenn Kasten730b9262018-03-29 15:01:26 -07007533
jiabin2fd710d2022-05-02 23:20:22 +00007534 for (;;) {
7535 sp<IOProfile> firstInexact = nullptr;
7536 uint32_t updatedSamplingRate = 0;
7537 audio_format_t updatedFormat = AUDIO_FORMAT_INVALID;
7538 audio_channel_mask_t updatedChannelMask = AUDIO_CHANNEL_INVALID;
7539 for (const auto& hwModule : mHwModules) {
7540 for (const auto& profile : hwModule->getInputProfiles()) {
7541 // profile->log();
7542 //updatedFormat = format;
7543 if (profile->isCompatibleProfile(DeviceVector(device), samplingRate,
7544 &samplingRate /*updatedSamplingRate*/,
7545 format,
7546 &format, /*updatedFormat*/
7547 channelMask,
7548 &channelMask /*updatedChannelMask*/,
7549 // FIXME ugly cast
7550 (audio_output_flags_t) flags,
7551 true /*exactMatchRequiredForInputFlags*/)) {
7552 return profile;
7553 }
7554 if (firstInexact == nullptr && profile->isCompatibleProfile(DeviceVector(device),
7555 samplingRate,
7556 &updatedSamplingRate,
7557 format,
7558 &updatedFormat,
7559 channelMask,
7560 &updatedChannelMask,
7561 // FIXME ugly cast
7562 (audio_output_flags_t) flags,
7563 false /*exactMatchRequiredForInputFlags*/)) {
7564 firstInexact = profile;
7565 }
7566 }
7567 }
7568
7569 if (firstInexact != nullptr) {
7570 samplingRate = updatedSamplingRate;
7571 format = updatedFormat;
7572 channelMask = updatedChannelMask;
7573 return firstInexact;
7574 } else if (flags & AUDIO_INPUT_FLAG_RAW) {
7575 flags = (audio_input_flags_t) (flags & ~AUDIO_INPUT_FLAG_RAW); // retry
7576 } else if ((flags & mustMatchFlag) == AUDIO_INPUT_FLAG_NONE &&
7577 flags != AUDIO_INPUT_FLAG_NONE && audio_is_linear_pcm(format)) {
7578 flags = AUDIO_INPUT_FLAG_NONE;
7579 } else { // fail
7580 ALOGW("%s could not find profile for device %s, sampling rate %u, format %#x, "
7581 "channel mask 0x%X, flags %#x", __func__, device->toString().c_str(),
7582 samplingRate, format, channelMask, oriFlags);
7583 break;
Eric Laurente552edb2014-03-10 17:42:56 -07007584 }
7585 }
jiabin2fd710d2022-05-02 23:20:22 +00007586
7587 return nullptr;
Eric Laurente552edb2014-03-10 17:42:56 -07007588}
7589
François Gaffieaaac0fd2018-11-22 17:56:39 +01007590float AudioPolicyManager::computeVolume(IVolumeCurves &curves,
7591 VolumeSource volumeSource,
François Gaffied1ab2bd2015-12-02 18:20:06 +01007592 int index,
jiabin9a3361e2019-10-01 09:38:30 -07007593 const DeviceTypeSet& deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07007594{
jiabin9a3361e2019-10-01 09:38:30 -07007595 float volumeDb = curves.volIndexToDb(Volume::getDeviceCategory(deviceTypes), index);
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07007596
7597 // handle the case of accessibility active while a ringtone is playing: if the ringtone is much
7598 // louder than the accessibility prompt, the prompt cannot be heard, thus masking the touch
7599 // exploration of the dialer UI. In this situation, bring the accessibility volume closer to
7600 // the ringtone volume
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007601 const auto callVolumeSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL, false);
7602 const auto ringVolumeSrc = toVolumeSource(AUDIO_STREAM_RING, false);
7603 const auto musicVolumeSrc = toVolumeSource(AUDIO_STREAM_MUSIC, false);
7604 const auto alarmVolumeSrc = toVolumeSource(AUDIO_STREAM_ALARM, false);
7605 const auto a11yVolumeSrc = toVolumeSource(AUDIO_STREAM_ACCESSIBILITY, false);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007606
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07007607 if (volumeSource == a11yVolumeSrc
François Gaffieaaac0fd2018-11-22 17:56:39 +01007608 && (AUDIO_MODE_RINGTONE == mEngine->getPhoneState()) &&
7609 mOutputs.isActive(ringVolumeSrc, 0)) {
7610 auto &ringCurves = getVolumeCurves(AUDIO_STREAM_RING);
jiabin9a3361e2019-10-01 09:38:30 -07007611 const float ringVolumeDb = computeVolume(ringCurves, ringVolumeSrc, index, deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007612 return ringVolumeDb - 4 > volumeDb ? ringVolumeDb - 4 : volumeDb;
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07007613 }
7614
Eric Laurentdcd4ab12018-06-29 17:45:13 -07007615 // in-call: always cap volume by voice volume + some low headroom
François Gaffieaaac0fd2018-11-22 17:56:39 +01007616 if ((volumeSource != callVolumeSrc && (isInCall() ||
7617 mOutputs.isActiveLocally(callVolumeSrc))) &&
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007618 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM, false) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01007619 volumeSource == ringVolumeSrc || volumeSource == musicVolumeSrc ||
7620 volumeSource == alarmVolumeSrc ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007621 volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION, false) ||
7622 volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false) ||
7623 volumeSource == toVolumeSource(AUDIO_STREAM_DTMF, false) ||
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07007624 volumeSource == a11yVolumeSrc)) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007625 auto &voiceCurves = getVolumeCurves(callVolumeSrc);
jiabin9a3361e2019-10-01 09:38:30 -07007626 int voiceVolumeIndex = voiceCurves.getVolumeIndex(deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007627 const float maxVoiceVolDb =
jiabin9a3361e2019-10-01 09:38:30 -07007628 computeVolume(voiceCurves, callVolumeSrc, voiceVolumeIndex, deviceTypes)
Eric Laurent7731b5a2018-04-06 15:47:22 -07007629 + IN_CALL_EARPIECE_HEADROOM_DB;
Abhijith Shastry329ddab2019-04-23 11:53:26 -07007630 // FIXME: Workaround for call screening applications until a proper audio mode is defined
7631 // to support this scenario : Exempt the RING stream from the audio cap if the audio was
7632 // programmatically muted.
7633 // VOICE_CALL stream has minVolumeIndex > 0 : Users cannot set the volume of voice calls to
7634 // 0. We don't want to cap volume when the system has programmatically muted the voice call
7635 // stream. See setVolumeCurveIndex() for more information.
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07007636 bool exemptFromCapping =
7637 ((volumeSource == ringVolumeSrc) || (volumeSource == a11yVolumeSrc))
7638 && (voiceVolumeIndex == 0);
Abhijith Shastry329ddab2019-04-23 11:53:26 -07007639 ALOGV_IF(exemptFromCapping, "%s volume source %d at vol=%f not capped", __func__,
7640 volumeSource, volumeDb);
7641 if ((volumeDb > maxVoiceVolDb) && !exemptFromCapping) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007642 ALOGV("%s volume source %d at vol=%f overriden by volume group %d at vol=%f", __func__,
7643 volumeSource, volumeDb, callVolumeSrc, maxVoiceVolDb);
7644 volumeDb = maxVoiceVolDb;
Jean-Michel Trivi719a9872017-08-05 13:51:35 -07007645 }
7646 }
Eric Laurente552edb2014-03-10 17:42:56 -07007647 // if a headset is connected, apply the following rules to ring tones and notifications
7648 // to avoid sound level bursts in user's ears:
Eric Laurent6af1c1d2016-04-14 11:20:44 -07007649 // - always attenuate notifications volume by 6dB
7650 // - attenuate ring tones volume by 6dB unless music is not playing and
7651 // speaker is part of the select devices
Eric Laurente552edb2014-03-10 17:42:56 -07007652 // - if music is playing, always limit the volume to current music volume,
7653 // with a minimum threshold at -36dB so that notification is always perceived.
jiabin9a3361e2019-10-01 09:38:30 -07007654 if (!Intersection(deviceTypes,
7655 {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP, AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES,
7656 AUDIO_DEVICE_OUT_WIRED_HEADSET, AUDIO_DEVICE_OUT_WIRED_HEADPHONE,
Eric Laurentc42df452020-08-07 10:51:53 -07007657 AUDIO_DEVICE_OUT_USB_HEADSET, AUDIO_DEVICE_OUT_HEARING_AID,
7658 AUDIO_DEVICE_OUT_BLE_HEADSET}).empty() &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01007659 ((volumeSource == alarmVolumeSrc ||
7660 volumeSource == ringVolumeSrc) ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007661 (volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION, false)) ||
7662 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM, false)) ||
7663 ((volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false)) &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01007664 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) &&
7665 curves.canBeMuted()) {
7666
Eric Laurente552edb2014-03-10 17:42:56 -07007667 // when the phone is ringing we must consider that music could have been paused just before
7668 // by the music application and behave as if music was active if the last music track was
7669 // just stopped
Eric Laurent3b73df72014-03-11 09:06:29 -07007670 if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY) ||
Eric Laurente552edb2014-03-10 17:42:56 -07007671 mLimitRingtoneVolume) {
François Gaffie43c73442018-11-08 08:21:55 +01007672 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
jiabin9a3361e2019-10-01 09:38:30 -07007673 DeviceTypeSet musicDevice =
François Gaffiec005e562018-11-06 15:04:49 +01007674 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
7675 nullptr, true /*fromCache*/).types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01007676 auto &musicCurves = getVolumeCurves(AUDIO_STREAM_MUSIC);
jiabin9a3361e2019-10-01 09:38:30 -07007677 float musicVolDb = computeVolume(musicCurves,
7678 musicVolumeSrc,
7679 musicCurves.getVolumeIndex(musicDevice),
7680 musicDevice);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007681 float minVolDb = (musicVolDb > SONIFICATION_HEADSET_VOLUME_MIN_DB) ?
7682 musicVolDb : SONIFICATION_HEADSET_VOLUME_MIN_DB;
7683 if (volumeDb > minVolDb) {
7684 volumeDb = minVolDb;
7685 ALOGV("computeVolume limiting volume to %f musicVol %f", minVolDb, musicVolDb);
Eric Laurente552edb2014-03-10 17:42:56 -07007686 }
Eric Laurent7b6385c2021-05-12 17:55:36 +02007687 if (Volume::getDeviceForVolume(deviceTypes) != AUDIO_DEVICE_OUT_SPEAKER
7688 && !Intersection(deviceTypes, {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP,
7689 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES}).empty()) {
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07007690 // on A2DP, also ensure notification volume is not too low compared to media when
7691 // intended to be played
François Gaffie43c73442018-11-08 08:21:55 +01007692 if ((volumeDb > -96.0f) &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01007693 (musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB > volumeDb)) {
jiabin9a3361e2019-10-01 09:38:30 -07007694 ALOGV("%s increasing volume for volume source=%d device=%s from %f to %f",
7695 __func__, volumeSource, dumpDeviceTypes(deviceTypes).c_str(), volumeDb,
François Gaffieaaac0fd2018-11-22 17:56:39 +01007696 musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB);
7697 volumeDb = musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB;
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07007698 }
7699 }
jiabin9a3361e2019-10-01 09:38:30 -07007700 } else if ((Volume::getDeviceForVolume(deviceTypes) != AUDIO_DEVICE_OUT_SPEAKER) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01007701 (!(volumeSource == alarmVolumeSrc || volumeSource == ringVolumeSrc))) {
François Gaffie43c73442018-11-08 08:21:55 +01007702 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07007703 }
7704 }
7705
François Gaffie43c73442018-11-08 08:21:55 +01007706 return volumeDb;
Eric Laurente552edb2014-03-10 17:42:56 -07007707}
7708
Eric Laurent3839bc02018-07-10 18:33:34 -07007709int AudioPolicyManager::rescaleVolumeIndex(int srcIndex,
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01007710 VolumeSource fromVolumeSource,
7711 VolumeSource toVolumeSource)
Eric Laurent3839bc02018-07-10 18:33:34 -07007712{
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01007713 if (fromVolumeSource == toVolumeSource) {
Eric Laurent3839bc02018-07-10 18:33:34 -07007714 return srcIndex;
7715 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01007716 auto &srcCurves = getVolumeCurves(fromVolumeSource);
7717 auto &dstCurves = getVolumeCurves(toVolumeSource);
Eric Laurentf5aa58d2019-02-22 18:20:11 -08007718 float minSrc = (float)srcCurves.getVolumeIndexMin();
7719 float maxSrc = (float)srcCurves.getVolumeIndexMax();
7720 float minDst = (float)dstCurves.getVolumeIndexMin();
7721 float maxDst = (float)dstCurves.getVolumeIndexMax();
Eric Laurent3839bc02018-07-10 18:33:34 -07007722
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08007723 // preserve mute request or correct range
7724 if (srcIndex < minSrc) {
7725 if (srcIndex == 0) {
7726 return 0;
7727 }
7728 srcIndex = minSrc;
7729 } else if (srcIndex > maxSrc) {
7730 srcIndex = maxSrc;
7731 }
Eric Laurent3839bc02018-07-10 18:33:34 -07007732 return (int)(minDst + ((srcIndex - minSrc) * (maxDst - minDst)) / (maxSrc - minSrc));
7733}
7734
François Gaffieaaac0fd2018-11-22 17:56:39 +01007735status_t AudioPolicyManager::checkAndSetVolume(IVolumeCurves &curves,
7736 VolumeSource volumeSource,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08007737 int index,
7738 const sp<AudioOutputDescriptor>& outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07007739 DeviceTypeSet deviceTypes,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08007740 int delayMs,
7741 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07007742{
François Gaffieaaac0fd2018-11-22 17:56:39 +01007743 // do not change actual attributes volume if the attributes is muted
7744 if (outputDesc->isMuted(volumeSource)) {
7745 ALOGVV("%s: volume source %d muted count %d active=%d", __func__, volumeSource,
7746 outputDesc->getMuteCount(volumeSource), outputDesc->isActive(volumeSource));
Eric Laurente552edb2014-03-10 17:42:56 -07007747 return NO_ERROR;
7748 }
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007749 VolumeSource callVolSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL, false);
7750 VolumeSource btScoVolSrc = toVolumeSource(AUDIO_STREAM_BLUETOOTH_SCO, false);
7751 bool isVoiceVolSrc = (volumeSource != VOLUME_SOURCE_NONE) && (callVolSrc == volumeSource);
7752 bool isBtScoVolSrc = (volumeSource != VOLUME_SOURCE_NONE) && (btScoVolSrc == volumeSource);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007753
Eric Laurent2517af32020-11-25 15:31:27 +01007754 bool isScoRequested = isScoRequestedForComm();
Eric Laurent1a8b45f2022-04-13 16:01:47 +02007755 bool isHAUsed = isHearingAidUsedForComm();
7756
Eric Laurente552edb2014-03-10 17:42:56 -07007757 // do not change in call volume if bluetooth is connected and vice versa
François Gaffieaaac0fd2018-11-22 17:56:39 +01007758 // if sco and call follow same curves, bypass forceUseForComm
7759 if ((callVolSrc != btScoVolSrc) &&
Eric Laurent2517af32020-11-25 15:31:27 +01007760 ((isVoiceVolSrc && isScoRequested) ||
Beibeif660a512023-02-28 17:00:34 +08007761 (isBtScoVolSrc && !(isScoRequested || isHAUsed))) &&
7762 !isSingleDeviceType(deviceTypes, AUDIO_DEVICE_OUT_TELEPHONY_TX)) {
Eric Laurent2517af32020-11-25 15:31:27 +01007763 ALOGV("%s cannot set volume group %d volume when is%srequested for comm", __func__,
Eric Laurent1a8b45f2022-04-13 16:01:47 +02007764 volumeSource, isScoRequested ? " " : " not ");
Eric Laurent571ef962020-07-24 11:43:48 -07007765 // Do not return an error here as AudioService will always set both voice call
7766 // and bluetooth SCO volumes due to stream aliasing.
7767 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07007768 }
jiabin9a3361e2019-10-01 09:38:30 -07007769 if (deviceTypes.empty()) {
7770 deviceTypes = outputDesc->devices().types();
Eric Laurentc75307b2015-03-17 15:29:32 -07007771 }
Eric Laurent275e8e92014-11-30 15:14:47 -08007772
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00007773 if (curves.getVolumeIndexMin() < 0 || curves.getVolumeIndexMax() < 0) {
7774 ALOGE("invalid volume index range");
7775 return BAD_VALUE;
7776 }
7777
jiabin9a3361e2019-10-01 09:38:30 -07007778 float volumeDb = computeVolume(curves, volumeSource, index, deviceTypes);
7779 if (outputDesc->isFixedVolume(deviceTypes) ||
Eric Laurent9698a4c2020-10-12 17:10:23 -07007780 // Force VoIP volume to max for bluetooth SCO device except if muted
7781 (index != 0 && (isVoiceVolSrc || isBtScoVolSrc) &&
jiabin9a3361e2019-10-01 09:38:30 -07007782 isSingleDeviceType(deviceTypes, audio_is_bluetooth_out_sco_device))) {
Eric Laurentffbc80f2015-03-18 18:30:19 -07007783 volumeDb = 0.0f;
Eric Laurent275e8e92014-11-30 15:14:47 -08007784 }
Francois Gaffie593634d2021-06-22 13:31:31 +02007785 const bool muted = (index == 0) && (volumeDb != 0.0f);
jiabin9a3361e2019-10-01 09:38:30 -07007786 outputDesc->setVolume(
Francois Gaffie593634d2021-06-22 13:31:31 +02007787 volumeDb, muted, volumeSource, curves.getStreamTypes(), deviceTypes, delayMs, force);
Eric Laurentc75307b2015-03-17 15:29:32 -07007788
Eric Laurente8f2c0f2021-08-17 11:17:19 +02007789 if (outputDesc == mPrimaryOutput && (isVoiceVolSrc || isBtScoVolSrc)) {
Eric Laurente552edb2014-03-10 17:42:56 -07007790 float voiceVolume;
Eric Laurentfad001d2019-06-11 19:17:57 -07007791 // 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 +01007792 if (isVoiceVolSrc) {
7793 voiceVolume = (float)index/(float)curves.getVolumeIndexMax();
Eric Laurente552edb2014-03-10 17:42:56 -07007794 } else {
Eric Laurentfad001d2019-06-11 19:17:57 -07007795 voiceVolume = index == 0 ? 0.0 : 1.0;
Eric Laurente552edb2014-03-10 17:42:56 -07007796 }
Eric Laurent18fba842016-03-31 14:41:26 -07007797 if (voiceVolume != mLastVoiceVolume) {
Eric Laurente552edb2014-03-10 17:42:56 -07007798 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
7799 mLastVoiceVolume = voiceVolume;
7800 }
7801 }
Eric Laurente552edb2014-03-10 17:42:56 -07007802 return NO_ERROR;
7803}
7804
Eric Laurentc75307b2015-03-17 15:29:32 -07007805void AudioPolicyManager::applyStreamVolumes(const sp<AudioOutputDescriptor>& outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07007806 const DeviceTypeSet& deviceTypes,
7807 int delayMs,
7808 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07007809{
jiabincd510522020-01-22 09:40:55 -08007810 ALOGVV("applyStreamVolumes() for device %s", dumpDeviceTypes(deviceTypes).c_str());
François Gaffieaaac0fd2018-11-22 17:56:39 +01007811 for (const auto &volumeGroup : mEngine->getVolumeGroups()) {
7812 auto &curves = getVolumeCurves(toVolumeSource(volumeGroup));
7813 checkAndSetVolume(curves, toVolumeSource(volumeGroup),
jiabin9a3361e2019-10-01 09:38:30 -07007814 curves.getVolumeIndex(deviceTypes),
7815 outputDesc, deviceTypes, delayMs, force);
Eric Laurente552edb2014-03-10 17:42:56 -07007816 }
7817}
7818
François Gaffiec005e562018-11-06 15:04:49 +01007819void AudioPolicyManager::setStrategyMute(product_strategy_t strategy,
7820 bool on,
7821 const sp<AudioOutputDescriptor>& outputDesc,
7822 int delayMs,
jiabin9a3361e2019-10-01 09:38:30 -07007823 DeviceTypeSet deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07007824{
François Gaffieaaac0fd2018-11-22 17:56:39 +01007825 std::vector<VolumeSource> sourcesToMute;
7826 for (auto attributes: mEngine->getAllAttributesForProductStrategy(strategy)) {
7827 ALOGVV("%s() attributes %s, mute %d, output ID %d", __func__,
7828 toString(attributes).c_str(), on, outputDesc->getId());
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007829 VolumeSource source = toVolumeSource(attributes, false);
7830 if ((source != VOLUME_SOURCE_NONE) &&
7831 (std::find(begin(sourcesToMute), end(sourcesToMute), source)
7832 == end(sourcesToMute))) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007833 sourcesToMute.push_back(source);
7834 }
Eric Laurente552edb2014-03-10 17:42:56 -07007835 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01007836 for (auto source : sourcesToMute) {
jiabin9a3361e2019-10-01 09:38:30 -07007837 setVolumeSourceMute(source, on, outputDesc, delayMs, deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007838 }
7839
Eric Laurente552edb2014-03-10 17:42:56 -07007840}
7841
François Gaffieaaac0fd2018-11-22 17:56:39 +01007842void AudioPolicyManager::setVolumeSourceMute(VolumeSource volumeSource,
7843 bool on,
7844 const sp<AudioOutputDescriptor>& outputDesc,
7845 int delayMs,
jiabin9a3361e2019-10-01 09:38:30 -07007846 DeviceTypeSet deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07007847{
jiabin9a3361e2019-10-01 09:38:30 -07007848 if (deviceTypes.empty()) {
7849 deviceTypes = outputDesc->devices().types();
Eric Laurente552edb2014-03-10 17:42:56 -07007850 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01007851 auto &curves = getVolumeCurves(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07007852 if (on) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007853 if (!outputDesc->isMuted(volumeSource)) {
Eric Laurentf5aa58d2019-02-22 18:20:11 -08007854 if (curves.canBeMuted() &&
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007855 (volumeSource != toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01007856 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) ==
7857 AUDIO_POLICY_FORCE_NONE))) {
jiabin9a3361e2019-10-01 09:38:30 -07007858 checkAndSetVolume(curves, volumeSource, 0, outputDesc, deviceTypes, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07007859 }
7860 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01007861 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not
7862 // ignored
7863 outputDesc->incMuteCount(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07007864 } else {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007865 if (!outputDesc->isMuted(volumeSource)) {
7866 ALOGV("%s unmuting non muted attributes!", __func__);
Eric Laurente552edb2014-03-10 17:42:56 -07007867 return;
7868 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01007869 if (outputDesc->decMuteCount(volumeSource) == 0) {
7870 checkAndSetVolume(curves, volumeSource,
jiabin9a3361e2019-10-01 09:38:30 -07007871 curves.getVolumeIndex(deviceTypes),
Eric Laurentc75307b2015-03-17 15:29:32 -07007872 outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07007873 deviceTypes,
Eric Laurente552edb2014-03-10 17:42:56 -07007874 delayMs);
7875 }
7876 }
7877}
7878
François Gaffie53615e22015-03-19 09:24:12 +01007879bool AudioPolicyManager::isValidAttributes(const audio_attributes_t *paa)
7880{
François Gaffiec005e562018-11-06 15:04:49 +01007881 // has flags that map to a stream type?
Eric Laurente83b55d2014-11-14 10:06:21 -08007882 if ((paa->flags & (AUDIO_FLAG_AUDIBILITY_ENFORCED | AUDIO_FLAG_SCO | AUDIO_FLAG_BEACON)) != 0) {
7883 return true;
7884 }
7885
7886 // has known usage?
7887 switch (paa->usage) {
7888 case AUDIO_USAGE_UNKNOWN:
7889 case AUDIO_USAGE_MEDIA:
7890 case AUDIO_USAGE_VOICE_COMMUNICATION:
7891 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
7892 case AUDIO_USAGE_ALARM:
7893 case AUDIO_USAGE_NOTIFICATION:
7894 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
7895 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
7896 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
7897 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
7898 case AUDIO_USAGE_NOTIFICATION_EVENT:
7899 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
7900 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
7901 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
7902 case AUDIO_USAGE_GAME:
Eric Laurent275e8e92014-11-30 15:14:47 -08007903 case AUDIO_USAGE_VIRTUAL_SOURCE:
Jean-Michel Trivi36867762016-12-29 12:03:28 -08007904 case AUDIO_USAGE_ASSISTANT:
Eric Laurent21777f82019-12-06 18:12:06 -08007905 case AUDIO_USAGE_CALL_ASSISTANT:
Hayden Gomes524159d2019-12-23 14:41:47 -08007906 case AUDIO_USAGE_EMERGENCY:
7907 case AUDIO_USAGE_SAFETY:
7908 case AUDIO_USAGE_VEHICLE_STATUS:
7909 case AUDIO_USAGE_ANNOUNCEMENT:
Eric Laurente83b55d2014-11-14 10:06:21 -08007910 break;
7911 default:
7912 return false;
7913 }
7914 return true;
7915}
7916
François Gaffie2110e042015-03-24 08:41:51 +01007917audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
7918{
7919 return mEngine->getForceUse(usage);
7920}
7921
Eric Laurent96d1dda2022-03-14 17:14:19 +01007922bool AudioPolicyManager::isInCall() const {
François Gaffie2110e042015-03-24 08:41:51 +01007923 return isStateInCall(mEngine->getPhoneState());
7924}
7925
Eric Laurent96d1dda2022-03-14 17:14:19 +01007926bool AudioPolicyManager::isStateInCall(int state) const {
François Gaffie2110e042015-03-24 08:41:51 +01007927 return is_state_in_call(state);
7928}
7929
Eric Laurentf9cccec2022-11-16 19:12:00 +01007930bool AudioPolicyManager::isCallAudioAccessible() const {
Eric Laurent74b71512019-11-06 17:21:57 -08007931 audio_mode_t mode = mEngine->getPhoneState();
7932 return (mode == AUDIO_MODE_IN_CALL)
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01007933 || (mode == AUDIO_MODE_CALL_SCREEN)
7934 || (mode == AUDIO_MODE_CALL_REDIRECT);
Eric Laurent74b71512019-11-06 17:21:57 -08007935}
7936
Eric Laurentf9cccec2022-11-16 19:12:00 +01007937bool AudioPolicyManager::isInCallOrScreening() const {
7938 audio_mode_t mode = mEngine->getPhoneState();
7939 return isStateInCall(mode) || mode == AUDIO_MODE_CALL_SCREEN;
7940}
7941
Eric Laurentd60560a2015-04-10 11:31:20 -07007942void AudioPolicyManager::cleanUpForDevice(const sp<DeviceDescriptor>& deviceDesc)
7943{
7944 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07007945 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02007946 if (sourceDesc->isConnected() && (sourceDesc->srcDevice()->equals(deviceDesc) ||
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02007947 sourceDesc->sinkDevice()->equals(deviceDesc))
7948 && !isCallRxAudioSource(sourceDesc)) {
Francois Gaffiea0e5c992020-09-29 16:05:07 +02007949 disconnectAudioSource(sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07007950 }
7951 }
7952
7953 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
7954 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
7955 bool release = false;
7956 for (size_t j = 0; j < patchDesc->mPatch.num_sources && !release; j++) {
7957 const struct audio_port_config *source = &patchDesc->mPatch.sources[j];
7958 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
7959 source->ext.device.type == deviceDesc->type()) {
7960 release = true;
7961 }
7962 }
Francois Gaffiea0e5c992020-09-29 16:05:07 +02007963 const char *address = deviceDesc->address().c_str();
Eric Laurentd60560a2015-04-10 11:31:20 -07007964 for (size_t j = 0; j < patchDesc->mPatch.num_sinks && !release; j++) {
7965 const struct audio_port_config *sink = &patchDesc->mPatch.sinks[j];
7966 if (sink->type == AUDIO_PORT_TYPE_DEVICE &&
Francois Gaffiea0e5c992020-09-29 16:05:07 +02007967 sink->ext.device.type == deviceDesc->type() &&
7968 (strnlen(address, AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0
7969 || strncmp(sink->ext.device.address, address,
7970 AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0)) {
Eric Laurentd60560a2015-04-10 11:31:20 -07007971 release = true;
7972 }
7973 }
7974 if (release) {
François Gaffieafd4cea2019-11-18 15:50:22 +01007975 ALOGV("%s releasing patch %u", __FUNCTION__, patchDesc->getHandle());
7976 releaseAudioPatch(patchDesc->getHandle(), patchDesc->getUid());
Eric Laurentd60560a2015-04-10 11:31:20 -07007977 }
7978 }
Francois Gaffie716e1432019-01-14 16:58:59 +01007979
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01007980 mInputs.clearSessionRoutesForDevice(deviceDesc);
7981
Francois Gaffie716e1432019-01-14 16:58:59 +01007982 mHwModules.cleanUpForDevice(deviceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07007983}
7984
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007985void AudioPolicyManager::modifySurroundFormats(
7986 const sp<DeviceDescriptor>& devDesc, FormatVector *formatsPtr) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007987 std::unordered_set<audio_format_t> enforcedSurround(
7988 devDesc->encodedFormats().begin(), devDesc->encodedFormats().end());
Mikhail Naganov100f0122018-11-29 11:22:16 -08007989 std::unordered_set<audio_format_t> allSurround; // A flat set of all known surround formats
7990 for (const auto& pair : mConfig.getSurroundFormats()) {
7991 allSurround.insert(pair.first);
7992 for (const auto& subformat : pair.second) allSurround.insert(subformat);
7993 }
Phil Burk09bc4612016-02-24 15:58:15 -08007994
7995 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
7996 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Phil Burk0709b0a2016-03-31 12:54:57 -07007997 ALOGD("%s: forced use = %d", __FUNCTION__, forceUse);
Mikhail Naganov100f0122018-11-29 11:22:16 -08007998 // This is the resulting set of formats depending on the surround mode:
7999 // 'all surround' = allSurround
8000 // 'enforced surround' = enforcedSurround [may include IEC69137 which isn't raw surround fmt]
8001 // 'non-surround' = not in 'all surround' and not in 'enforced surround'
8002 // 'manual surround' = mManualSurroundFormats
8003 // AUTO: formats v 'enforced surround'
8004 // ALWAYS: formats v 'all surround' v 'enforced surround'
8005 // NEVER: formats ^ 'non-surround'
8006 // MANUAL: formats ^ ('non-surround' v 'manual surround' v (IEC69137 ^ 'enforced surround'))
Phil Burk09bc4612016-02-24 15:58:15 -08008007
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008008 std::unordered_set<audio_format_t> formatSet;
8009 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL
8010 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008011 // formatSet is (formats ^ 'non-surround')
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008012 for (auto formatIter = formatsPtr->begin(); formatIter != formatsPtr->end(); ++formatIter) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008013 if (allSurround.count(*formatIter) == 0 && enforcedSurround.count(*formatIter) == 0) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008014 formatSet.insert(*formatIter);
8015 }
8016 }
8017 } else {
8018 formatSet.insert(formatsPtr->begin(), formatsPtr->end());
8019 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08008020 formatsPtr->clear(); // Re-filled from the formatSet at the end.
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008021
jiabin81772902018-04-02 17:52:27 -07008022 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008023 formatSet.insert(mManualSurroundFormats.begin(), mManualSurroundFormats.end());
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008024 // Enable IEC61937 when in MANUAL mode if it's enforced for this device.
8025 if (enforcedSurround.count(AUDIO_FORMAT_IEC61937) != 0) {
8026 formatSet.insert(AUDIO_FORMAT_IEC61937);
Phil Burk09bc4612016-02-24 15:58:15 -08008027 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08008028 } else if (forceUse != AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) { // AUTO or ALWAYS
8029 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS) {
8030 formatSet.insert(allSurround.begin(), allSurround.end());
Phil Burk07ac1142016-03-25 13:39:29 -07008031 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08008032 formatSet.insert(enforcedSurround.begin(), enforcedSurround.end());
Phil Burk09bc4612016-02-24 15:58:15 -08008033 }
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008034 for (const auto& format : formatSet) {
jiabin06e4bab2019-07-29 10:13:34 -07008035 formatsPtr->push_back(format);
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008036 }
Phil Burk0709b0a2016-03-31 12:54:57 -07008037}
8038
jiabin06e4bab2019-07-29 10:13:34 -07008039void AudioPolicyManager::modifySurroundChannelMasks(ChannelMaskSet *channelMasksPtr) {
8040 ChannelMaskSet &channelMasks = *channelMasksPtr;
Phil Burk0709b0a2016-03-31 12:54:57 -07008041 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
8042 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
8043
8044 // If NEVER, then remove support for channelMasks > stereo.
8045 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
jiabin06e4bab2019-07-29 10:13:34 -07008046 for (auto it = channelMasks.begin(); it != channelMasks.end();) {
8047 audio_channel_mask_t channelMask = *it;
Phil Burk0709b0a2016-03-31 12:54:57 -07008048 if (channelMask & ~AUDIO_CHANNEL_OUT_STEREO) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01008049 ALOGV("%s: force NEVER, so remove channelMask 0x%08x", __FUNCTION__, channelMask);
jiabin06e4bab2019-07-29 10:13:34 -07008050 it = channelMasks.erase(it);
Phil Burk0709b0a2016-03-31 12:54:57 -07008051 } else {
jiabin06e4bab2019-07-29 10:13:34 -07008052 ++it;
Phil Burk0709b0a2016-03-31 12:54:57 -07008053 }
8054 }
jiabin81772902018-04-02 17:52:27 -07008055 // If ALWAYS or MANUAL, then make sure we at least support 5.1
8056 } else if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS
8057 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Phil Burk0709b0a2016-03-31 12:54:57 -07008058 bool supports5dot1 = false;
8059 // Are there any channel masks that can be considered "surround"?
Mikhail Naganovcf84e592017-12-07 11:25:11 -08008060 for (audio_channel_mask_t channelMask : channelMasks) {
Phil Burk0709b0a2016-03-31 12:54:57 -07008061 if ((channelMask & AUDIO_CHANNEL_OUT_5POINT1) == AUDIO_CHANNEL_OUT_5POINT1) {
8062 supports5dot1 = true;
8063 break;
8064 }
8065 }
8066 // If not then add 5.1 support.
8067 if (!supports5dot1) {
jiabin06e4bab2019-07-29 10:13:34 -07008068 channelMasks.insert(AUDIO_CHANNEL_OUT_5POINT1);
Eric Laurentfecbceb2021-02-09 14:46:43 +01008069 ALOGV("%s: force MANUAL or ALWAYS, so adding channelMask for 5.1 surround", __func__);
Phil Burk0709b0a2016-03-31 12:54:57 -07008070 }
Phil Burk09bc4612016-02-24 15:58:15 -08008071 }
8072}
8073
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008074void AudioPolicyManager::updateAudioProfiles(const sp<DeviceDescriptor>& devDesc,
Phil Burk00eeb322016-03-31 12:41:00 -07008075 audio_io_handle_t ioHandle,
François Gaffie112b0af2015-11-19 16:13:25 +01008076 AudioProfileVector &profiles)
8077{
8078 String8 reply;
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008079 audio_devices_t device = devDesc->type();
Phil Burk0709b0a2016-03-31 12:54:57 -07008080
François Gaffie112b0af2015-11-19 16:13:25 +01008081 // Format MUST be checked first to update the list of AudioProfile
8082 if (profiles.hasDynamicFormat()) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07008083 reply = mpClientInterface->getParameters(
8084 ioHandle, String8(AudioParameter::keyStreamSupportedFormats));
jiabin81772902018-04-02 17:52:27 -07008085 ALOGV("%s: supported formats %d, %s", __FUNCTION__, ioHandle, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08008086 AudioParameter repliedParameters(reply);
jiabinf26596b2023-04-12 18:56:39 +00008087 FormatVector formats;
Eric Laurent62e4bc52016-02-02 18:37:28 -08008088 if (repliedParameters.get(
jiabinf26596b2023-04-12 18:56:39 +00008089 String8(AudioParameter::keyStreamSupportedFormats), reply) == NO_ERROR) {
8090 formats = formatsFromString(reply.string());
8091 } else if (devDesc->hasValidAudioProfile()) {
8092 ALOGD("%s: using the device profiles", __func__);
8093 formats = devDesc->getAudioProfiles().getSupportedFormats();
8094 } else {
8095 ALOGE("%s: failed to retrieve format, bailing out", __func__);
François Gaffie112b0af2015-11-19 16:13:25 +01008096 return;
8097 }
Kriti Dangef6be8f2020-11-05 11:58:19 +01008098 mReportedFormatsMap[devDesc] = formats;
Mikhail Naganov100f0122018-11-29 11:22:16 -08008099 if (device == AUDIO_DEVICE_OUT_HDMI
8100 || isDeviceOfModule(devDesc, AUDIO_HARDWARE_MODULE_ID_MSD)) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008101 modifySurroundFormats(devDesc, &formats);
Phil Burk00eeb322016-03-31 12:41:00 -07008102 }
jiabin3e277cc2019-09-10 14:27:34 -07008103 addProfilesForFormats(profiles, formats);
François Gaffie112b0af2015-11-19 16:13:25 +01008104 }
François Gaffie112b0af2015-11-19 16:13:25 +01008105
Mikhail Naganovcf84e592017-12-07 11:25:11 -08008106 for (audio_format_t format : profiles.getSupportedFormats()) {
jiabinf26596b2023-04-12 18:56:39 +00008107 std::optional<ChannelMaskSet> channelMasks;
jiabin06e4bab2019-07-29 10:13:34 -07008108 SampleRateSet samplingRates;
François Gaffie112b0af2015-11-19 16:13:25 +01008109 AudioParameter requestedParameters;
Mikhail Naganov388360c2016-10-17 17:09:41 -07008110 requestedParameters.addInt(String8(AudioParameter::keyFormat), format);
François Gaffie112b0af2015-11-19 16:13:25 +01008111
8112 if (profiles.hasDynamicRateFor(format)) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07008113 reply = mpClientInterface->getParameters(
8114 ioHandle,
8115 requestedParameters.toString() + ";" +
8116 AudioParameter::keyStreamSupportedSamplingRates);
François Gaffie112b0af2015-11-19 16:13:25 +01008117 ALOGV("%s: supported sampling rates %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08008118 AudioParameter repliedParameters(reply);
8119 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07008120 String8(AudioParameter::keyStreamSupportedSamplingRates), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08008121 samplingRates = samplingRatesFromString(reply.string());
jiabinf26596b2023-04-12 18:56:39 +00008122 } else {
8123 samplingRates = devDesc->getAudioProfiles().getSampleRatesFor(format);
François Gaffie112b0af2015-11-19 16:13:25 +01008124 }
8125 }
8126 if (profiles.hasDynamicChannelsFor(format)) {
8127 reply = mpClientInterface->getParameters(ioHandle,
8128 requestedParameters.toString() + ";" +
Mikhail Naganov388360c2016-10-17 17:09:41 -07008129 AudioParameter::keyStreamSupportedChannels);
François Gaffie112b0af2015-11-19 16:13:25 +01008130 ALOGV("%s: supported channel masks %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08008131 AudioParameter repliedParameters(reply);
8132 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07008133 String8(AudioParameter::keyStreamSupportedChannels), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08008134 channelMasks = channelMasksFromString(reply.string());
jiabinf26596b2023-04-12 18:56:39 +00008135 } else {
8136 channelMasks = devDesc->getAudioProfiles().getChannelMasksFor(format);
8137 }
8138 if (channelMasks.has_value() && (device == AUDIO_DEVICE_OUT_HDMI
8139 || isDeviceOfModule(devDesc, AUDIO_HARDWARE_MODULE_ID_MSD))) {
8140 modifySurroundChannelMasks(&channelMasks.value());
François Gaffie112b0af2015-11-19 16:13:25 +01008141 }
8142 }
jiabin3e277cc2019-09-10 14:27:34 -07008143 addDynamicAudioProfileAndSort(
jiabinf26596b2023-04-12 18:56:39 +00008144 profiles, new AudioProfile(
8145 format, channelMasks.value_or(ChannelMaskSet()), samplingRates));
François Gaffie112b0af2015-11-19 16:13:25 +01008146 }
8147}
Eric Laurentd60560a2015-04-10 11:31:20 -07008148
Mikhail Naganovdc769682018-05-04 15:34:08 -07008149status_t AudioPolicyManager::installPatch(const char *caller,
8150 audio_patch_handle_t *patchHandle,
8151 AudioIODescriptorInterface *ioDescriptor,
8152 const struct audio_patch *patch,
8153 int delayMs)
8154{
8155 ssize_t index = mAudioPatches.indexOfKey(
8156 patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE ?
8157 *patchHandle : ioDescriptor->getPatchHandle());
8158 sp<AudioPatch> patchDesc;
8159 status_t status = installPatch(
8160 caller, index, patchHandle, patch, delayMs, mUidCached, &patchDesc);
8161 if (status == NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01008162 ioDescriptor->setPatchHandle(patchDesc->getHandle());
Mikhail Naganovdc769682018-05-04 15:34:08 -07008163 }
8164 return status;
8165}
8166
8167status_t AudioPolicyManager::installPatch(const char *caller,
8168 ssize_t index,
8169 audio_patch_handle_t *patchHandle,
8170 const struct audio_patch *patch,
8171 int delayMs,
8172 uid_t uid,
8173 sp<AudioPatch> *patchDescPtr)
8174{
8175 sp<AudioPatch> patchDesc;
8176 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
8177 if (index >= 0) {
8178 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01008179 afPatchHandle = patchDesc->getAfHandle();
Mikhail Naganovdc769682018-05-04 15:34:08 -07008180 }
8181
8182 status_t status = mpClientInterface->createAudioPatch(patch, &afPatchHandle, delayMs);
8183 ALOGV("%s() AF::createAudioPatch returned %d patchHandle %d num_sources %d num_sinks %d",
8184 caller, status, afPatchHandle, patch->num_sources, patch->num_sinks);
8185 if (status == NO_ERROR) {
8186 if (index < 0) {
8187 patchDesc = new AudioPatch(patch, uid);
François Gaffieafd4cea2019-11-18 15:50:22 +01008188 addAudioPatch(patchDesc->getHandle(), patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07008189 } else {
8190 patchDesc->mPatch = *patch;
8191 }
François Gaffieafd4cea2019-11-18 15:50:22 +01008192 patchDesc->setAfHandle(afPatchHandle);
Mikhail Naganovdc769682018-05-04 15:34:08 -07008193 if (patchHandle) {
François Gaffieafd4cea2019-11-18 15:50:22 +01008194 *patchHandle = patchDesc->getHandle();
Mikhail Naganovdc769682018-05-04 15:34:08 -07008195 }
8196 nextAudioPortGeneration();
8197 mpClientInterface->onAudioPatchListUpdate();
8198 }
8199 if (patchDescPtr) *patchDescPtr = patchDesc;
8200 return status;
8201}
8202
jiabinbce0c1d2020-10-05 11:20:18 -07008203bool AudioPolicyManager::areAllActiveTracksRerouted(const sp<SwAudioOutputDescriptor>& output)
8204{
8205 const TrackClientVector activeClients = output->getActiveClients();
8206 if (activeClients.empty()) {
8207 return true;
8208 }
8209 ssize_t index = mAudioPatches.indexOfKey(output->getPatchHandle());
8210 if (index < 0) {
8211 ALOGE("%s, no audio patch found while there are active clients on output %d",
8212 __func__, output->getId());
8213 return false;
8214 }
8215 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
8216 DeviceVector routedDevices;
8217 for (int i = 0; i < patchDesc->mPatch.num_sinks; ++i) {
8218 sp<DeviceDescriptor> device = mAvailableOutputDevices.getDeviceFromId(
8219 patchDesc->mPatch.sinks[i].id);
8220 if (device == nullptr) {
8221 ALOGE("%s, no audio device found with id(%d)",
8222 __func__, patchDesc->mPatch.sinks[i].id);
8223 return false;
8224 }
8225 routedDevices.add(device);
8226 }
8227 for (const auto& client : activeClients) {
jiabin49256852022-03-09 11:21:35 -08008228 if (client->isInvalid()) {
8229 // No need to take care about invalidated clients.
8230 continue;
8231 }
jiabinbce0c1d2020-10-05 11:20:18 -07008232 sp<DeviceDescriptor> preferredDevice =
8233 mAvailableOutputDevices.getDeviceFromId(client->preferredDeviceId());
8234 if (mEngine->getOutputDevicesForAttributes(
8235 client->attributes(), preferredDevice, false) == routedDevices) {
8236 return false;
8237 }
8238 }
8239 return true;
8240}
8241
8242sp<SwAudioOutputDescriptor> AudioPolicyManager::openOutputWithProfileAndDevice(
Eric Laurentb4f42a92022-01-17 17:37:31 +01008243 const sp<IOProfile>& profile, const DeviceVector& devices,
jiabina84c3d32022-12-02 18:59:55 +00008244 const audio_config_base_t *mixerConfig, const audio_config_t *halConfig,
8245 audio_output_flags_t flags)
jiabinbce0c1d2020-10-05 11:20:18 -07008246{
8247 for (const auto& device : devices) {
8248 // TODO: This should be checking if the profile supports the device combo.
8249 if (!profile->supportsDevice(device)) {
jiabina84c3d32022-12-02 18:59:55 +00008250 ALOGE("%s profile(%s) doesn't support device %#x", __func__, profile->getName().c_str(),
8251 device->type());
jiabinbce0c1d2020-10-05 11:20:18 -07008252 return nullptr;
8253 }
8254 }
8255 sp<SwAudioOutputDescriptor> desc = new SwAudioOutputDescriptor(profile, mpClientInterface);
8256 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
jiabina84c3d32022-12-02 18:59:55 +00008257 status_t status = desc->open(halConfig, mixerConfig, devices,
8258 AUDIO_STREAM_DEFAULT, flags, &output);
jiabinbce0c1d2020-10-05 11:20:18 -07008259 if (status != NO_ERROR) {
jiabina84c3d32022-12-02 18:59:55 +00008260 ALOGE("%s failed to open output %d", __func__, status);
jiabinbce0c1d2020-10-05 11:20:18 -07008261 return nullptr;
8262 }
8263
8264 // Here is where the out_set_parameters() for card & device gets called
8265 sp<DeviceDescriptor> device = devices.getDeviceForOpening();
8266 const audio_devices_t deviceType = device->type();
8267 const String8 &address = String8(device->address().c_str());
8268 if (!address.isEmpty()) {
8269 char *param = audio_device_address_to_parameter(deviceType, address.c_str());
8270 mpClientInterface->setParameters(output, String8(param));
8271 free(param);
8272 }
8273 updateAudioProfiles(device, output, profile->getAudioProfiles());
8274 if (!profile->hasValidAudioProfile()) {
8275 ALOGW("%s() missing param", __func__);
8276 desc->close();
8277 return nullptr;
jiabina84c3d32022-12-02 18:59:55 +00008278 } else if (profile->hasDynamicAudioProfile() && halConfig == nullptr) {
8279 // Reopen the output with the best audio profile picked by APM when the profile supports
8280 // dynamic audio profile and the hal config is not specified.
jiabinbce0c1d2020-10-05 11:20:18 -07008281 desc->close();
8282 output = AUDIO_IO_HANDLE_NONE;
8283 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
8284 profile->pickAudioProfile(
8285 config.sample_rate, config.channel_mask, config.format);
8286 config.offload_info.sample_rate = config.sample_rate;
8287 config.offload_info.channel_mask = config.channel_mask;
8288 config.offload_info.format = config.format;
8289
jiabina84c3d32022-12-02 18:59:55 +00008290 status = desc->open(&config, mixerConfig, devices, AUDIO_STREAM_DEFAULT, flags, &output);
jiabinbce0c1d2020-10-05 11:20:18 -07008291 if (status != NO_ERROR) {
8292 return nullptr;
8293 }
8294 }
8295
8296 addOutput(output, desc);
Eric Laurentb4f42a92022-01-17 17:37:31 +01008297
baek.kim -61c20122022-07-27 10:05:32 +00008298 sp<DeviceDescriptor> speaker = mAvailableOutputDevices.getDevice(
8299 AUDIO_DEVICE_OUT_SPEAKER, String8(""), AUDIO_FORMAT_DEFAULT);
8300
jiabinbce0c1d2020-10-05 11:20:18 -07008301 if (audio_is_remote_submix_device(deviceType) && address != "0") {
8302 sp<AudioPolicyMix> policyMix;
8303 if (mPolicyMixes.getAudioPolicyMix(deviceType, address, policyMix) == NO_ERROR) {
8304 policyMix->setOutput(desc);
8305 desc->mPolicyMix = policyMix;
8306 } else {
8307 ALOGW("checkOutputsForDevice() cannot find policy for address %s",
8308 address.string());
8309 }
8310
baek.kim -61c20122022-07-27 10:05:32 +00008311 } else if (hasPrimaryOutput() && speaker != nullptr
8312 && mPrimaryOutput->supportsDevice(speaker) && !desc->supportsDevice(speaker)
Eric Laurentb4f42a92022-01-17 17:37:31 +01008313 && ((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0)) {
8314 // no duplicated output for:
8315 // - direct outputs
8316 // - outputs used by dynamic policy mixes
baek.kim -61c20122022-07-27 10:05:32 +00008317 // - outputs that supports SPEAKER while the primary output does not.
jiabinbce0c1d2020-10-05 11:20:18 -07008318 audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE;
8319
8320 //TODO: configure audio effect output stage here
8321
8322 // open a duplicating output thread for the new output and the primary output
8323 sp<SwAudioOutputDescriptor> dupOutputDesc =
8324 new SwAudioOutputDescriptor(nullptr, mpClientInterface);
8325 status = dupOutputDesc->openDuplicating(mPrimaryOutput, desc, &duplicatedOutput);
8326 if (status == NO_ERROR) {
8327 // add duplicated output descriptor
8328 addOutput(duplicatedOutput, dupOutputDesc);
8329 } else {
8330 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
8331 mPrimaryOutput->mIoHandle, output);
8332 desc->close();
8333 removeOutput(output);
8334 nextAudioPortGeneration();
8335 return nullptr;
8336 }
8337 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02008338 if (mPrimaryOutput == nullptr && profile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
8339 ALOGV("%s(): re-assigning mPrimaryOutput", __func__);
8340 mPrimaryOutput = desc;
8341 }
jiabinbce0c1d2020-10-05 11:20:18 -07008342 return desc;
8343}
8344
jiabinf1c73972022-04-14 16:28:52 -07008345status_t AudioPolicyManager::getDevicesForAttributes(
8346 const audio_attributes_t &attr, DeviceVector &devices, bool forVolume) {
8347 // Devices are determined in the following precedence:
8348 //
8349 // 1) Devices associated with a dynamic policy matching the attributes. This is often
8350 // a remote submix from MIX_ROUTE_FLAG_LOOP_BACK.
8351 //
8352 // If no such dynamic policy then
8353 // 2) Devices containing an active client using setPreferredDevice
8354 // with same strategy as the attributes.
8355 // (from the default Engine::getOutputDevicesForAttributes() implementation).
8356 //
8357 // If no corresponding active client with setPreferredDevice then
8358 // 3) Devices associated with the strategy determined by the attributes
8359 // (from the default Engine::getOutputDevicesForAttributes() implementation).
8360 //
8361 // See related getOutputForAttrInt().
8362
8363 // check dynamic policies but only for primary descriptors (secondary not used for audible
8364 // audio routing, only used for duplication for playback capture)
8365 sp<AudioPolicyMix> policyMix;
Oscar Azucena873d10f2023-01-12 18:34:42 -08008366 bool unneededUsePrimaryOutputFromPolicyMixes = false;
jiabinf1c73972022-04-14 16:28:52 -07008367 status_t status = mPolicyMixes.getOutputForAttr(attr, AUDIO_CONFIG_BASE_INITIALIZER,
Oscar Azucena873d10f2023-01-12 18:34:42 -08008368 0 /*uid unknown here*/, AUDIO_SESSION_NONE, AUDIO_OUTPUT_FLAG_NONE,
8369 mAvailableOutputDevices, nullptr /* requestedDevice */, policyMix,
8370 nullptr /* secondaryMixes */, unneededUsePrimaryOutputFromPolicyMixes);
jiabinf1c73972022-04-14 16:28:52 -07008371 if (status != OK) {
8372 return status;
8373 }
8374
8375 if (policyMix != nullptr && policyMix->getOutput() != nullptr &&
8376 // For volume control, skip LOOPBACK mixes which use AUDIO_DEVICE_OUT_REMOTE_SUBMIX
8377 // as they are unaffected by device/stream volume
8378 // (per SwAudioOutputDescriptor::isFixedVolume()).
8379 (!forVolume || policyMix->mDeviceType != AUDIO_DEVICE_OUT_REMOTE_SUBMIX)
8380 ) {
8381 sp<DeviceDescriptor> deviceDesc = mAvailableOutputDevices.getDevice(
8382 policyMix->mDeviceType, policyMix->mDeviceAddress, AUDIO_FORMAT_DEFAULT);
8383 devices.add(deviceDesc);
8384 } else {
8385 // The default Engine::getOutputDevicesForAttributes() uses findPreferredDevice()
8386 // which selects setPreferredDevice if active. This means forVolume call
8387 // will take an active setPreferredDevice, if such exists.
8388
8389 devices = mEngine->getOutputDevicesForAttributes(
8390 attr, nullptr /* preferredDevice */, false /* fromCache */);
8391 }
8392
8393 if (forVolume) {
8394 // We alias the device AUDIO_DEVICE_OUT_SPEAKER_SAFE to AUDIO_DEVICE_OUT_SPEAKER
8395 // for single volume control in AudioService (such relationship should exist if
8396 // SPEAKER_SAFE is present).
8397 //
8398 // (This is unrelated to a different device grouping as Volume::getDeviceCategory)
8399 DeviceVector speakerSafeDevices =
8400 devices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER_SAFE);
8401 if (!speakerSafeDevices.isEmpty()) {
8402 devices.merge(mAvailableOutputDevices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER));
8403 devices.remove(speakerSafeDevices);
8404 }
8405 }
8406
8407 return NO_ERROR;
8408}
8409
8410status_t AudioPolicyManager::getProfilesForDevices(const DeviceVector& devices,
8411 AudioProfileVector& audioProfiles,
8412 uint32_t flags,
8413 bool isInput) {
8414 for (const auto& hwModule : mHwModules) {
8415 // the MSD module checks for different conditions
8416 if (strcmp(hwModule->getName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0) {
8417 continue;
8418 }
8419 IOProfileCollection ioProfiles = isInput ? hwModule->getInputProfiles()
8420 : hwModule->getOutputProfiles();
8421 for (const auto& profile : ioProfiles) {
8422 if (!profile->areAllDevicesSupported(devices) ||
8423 !profile->isCompatibleProfileForFlags(
8424 flags, false /*exactMatchRequiredForInputFlags*/)) {
8425 continue;
8426 }
8427 audioProfiles.addAllValidProfiles(profile->asAudioPort()->getAudioProfiles());
8428 }
8429 }
8430
8431 if (!isInput) {
8432 // add the direct profiles from MSD if present and has audio patches to all the output(s)
8433 const auto &msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
8434 if (msdModule != nullptr) {
8435 if (msdHasPatchesToAllDevices(devices.toTypeAddrVector())) {
8436 ALOGV("%s: MSD audio patches set to all output devices.", __func__);
8437 for (const auto &profile: msdModule->getOutputProfiles()) {
8438 if (!profile->asAudioPort()->isDirectOutput()) {
8439 continue;
8440 }
8441 audioProfiles.addAllValidProfiles(profile->asAudioPort()->getAudioProfiles());
8442 }
8443 } else {
8444 ALOGV("%s: MSD audio patches NOT set to all output devices.", __func__);
8445 }
8446 }
8447 }
8448
8449 return NO_ERROR;
8450}
8451
jiabin3ff8d7d2022-12-13 06:27:44 +00008452sp<SwAudioOutputDescriptor> AudioPolicyManager::reopenOutput(sp<SwAudioOutputDescriptor> outputDesc,
8453 const audio_config_t *config,
8454 audio_output_flags_t flags,
8455 const char* caller) {
jiabina84c3d32022-12-02 18:59:55 +00008456 closeOutput(outputDesc->mIoHandle);
8457 sp<SwAudioOutputDescriptor> preferredOutput = openOutputWithProfileAndDevice(
8458 outputDesc->mProfile, outputDesc->devices(), nullptr /*mixerConfig*/, config, flags);
8459 if (preferredOutput == nullptr) {
8460 ALOGE("%s failed to reopen output device=%d, caller=%s",
8461 __func__, outputDesc->devices()[0]->getId(), caller);
jiabina84c3d32022-12-02 18:59:55 +00008462 }
jiabin3ff8d7d2022-12-13 06:27:44 +00008463 return preferredOutput;
8464}
8465
8466void AudioPolicyManager::reopenOutputsWithDevices(
8467 const std::map<audio_io_handle_t, DeviceVector> &outputsToReopen) {
8468 for (const auto& [output, devices] : outputsToReopen) {
8469 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
8470 closeOutput(output);
8471 openOutputWithProfileAndDevice(desc->mProfile, devices);
8472 }
jiabina84c3d32022-12-02 18:59:55 +00008473}
8474
jiabinc44b3462022-12-08 12:52:31 -08008475PortHandleVector AudioPolicyManager::getClientsForStream(
8476 audio_stream_type_t streamType) const {
8477 PortHandleVector clients;
8478 for (size_t i = 0; i < mOutputs.size(); ++i) {
8479 PortHandleVector clientsForStream = mOutputs.valueAt(i)->getClientsForStream(streamType);
8480 clients.insert(clients.end(), clientsForStream.begin(), clientsForStream.end());
8481 }
8482 return clients;
8483}
8484
8485void AudioPolicyManager::invalidateStreams(StreamTypeVector streams) const {
8486 PortHandleVector clients;
8487 for (auto stream : streams) {
8488 PortHandleVector clientsForStream = getClientsForStream(stream);
8489 clients.insert(clients.end(), clientsForStream.begin(), clientsForStream.end());
8490 }
8491 mpClientInterface->invalidateTracks(clients);
8492}
8493
Mikhail Naganov1b2a7942017-12-08 10:18:09 -08008494} // namespace android