blob: c20145335a6244400ef35cbc7a0bfcca6fe7a8c5 [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 Nairc18e9a12022-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,
jiabin872de702023-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);
jiabin872de702023-04-27 22:04:31 +0000123 if (status_t status = mpClientInterface->setDeviceConnectedState(&devicePort, state);
Mikhail Naganov516d3982022-02-01 23:53:59 +0000124 status != OK) {
jiabin872de702023-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 Naganov0566bac2022-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 Nairc18e9a12022-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...)
jiabin872de702023-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
jiabin872de702023-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
jiabin872de702023-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
jiabin872de702023-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
Tomasz Wasilczyk8f36f6e2023-08-15 20:59:35 +0000280 && device->address() == policyMix->mDeviceAddress.c_str()) {
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...)
jiabin872de702023-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
jiabin872de702023-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
jiabin872de702023-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
jiabin872de702023-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 Nairc18e9a12022-12-18 16:45:15 -0800461 media::AudioPortFw* aidlPort) {
Andy Hunged722372023-09-18 22:00:21 +0000462 const auto devDescr = sp<DeviceDescriptorBase>::make(device, device_address);
463 devDescr->setName(device_name);
464 return devDescr->writeToParcelable(aidlPort);
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100465}
466
Eric Laurent736a1022019-03-27 18:28:46 -0700467void AudioPolicyManager::setEngineDeviceConnectionState(const sp<DeviceDescriptor> device,
468 audio_policy_dev_state_t state) {
469
470 // the Engine does not have to know about remote submix devices used by dynamic audio policies
471 if (audio_is_remote_submix_device(device->type()) && device->address() != "0") {
472 return;
473 }
474 mEngine->setDeviceConnectionState(device, state);
475}
476
477
Eric Laurente0720872014-03-11 09:30:41 -0700478audio_policy_dev_state_t AudioPolicyManager::getDeviceConnectionState(audio_devices_t device,
François Gaffie53615e22015-03-19 09:24:12 +0100479 const char *device_address)
Eric Laurente552edb2014-03-10 17:42:56 -0700480{
Eric Laurent634b7142016-04-20 13:48:02 -0700481 sp<DeviceDescriptor> devDesc =
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800482 mHwModules.getDeviceDescriptor(device, device_address, "", AUDIO_FORMAT_DEFAULT,
483 false /* allowToCreate */,
Eric Laurent634b7142016-04-20 13:48:02 -0700484 (strlen(device_address) != 0)/*matchAddress*/);
485
486 if (devDesc == 0) {
François Gaffie251c7f02018-11-07 10:41:08 +0100487 ALOGV("getDeviceConnectionState() undeclared device, type %08x, address: %s",
Eric Laurent634b7142016-04-20 13:48:02 -0700488 device, device_address);
489 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
490 }
François Gaffie53615e22015-03-19 09:24:12 +0100491
Eric Laurent3a4311c2014-03-17 12:00:47 -0700492 DeviceVector *deviceVector;
493
Eric Laurente552edb2014-03-10 17:42:56 -0700494 if (audio_is_output_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700495 deviceVector = &mAvailableOutputDevices;
Eric Laurente552edb2014-03-10 17:42:56 -0700496 } else if (audio_is_input_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700497 deviceVector = &mAvailableInputDevices;
498 } else {
François Gaffie11d30102018-11-02 16:09:09 +0100499 ALOGW("%s() invalid device type %08x", __func__, device);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700500 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurente552edb2014-03-10 17:42:56 -0700501 }
Eric Laurent634b7142016-04-20 13:48:02 -0700502
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800503 return (deviceVector->getDevice(
504 device, String8(device_address), AUDIO_FORMAT_DEFAULT) != 0) ?
Eric Laurent634b7142016-04-20 13:48:02 -0700505 AUDIO_POLICY_DEVICE_STATE_AVAILABLE : AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurenta1d525f2015-01-29 13:36:45 -0800506}
507
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800508status_t AudioPolicyManager::handleDeviceConfigChange(audio_devices_t device,
509 const char *device_address,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800510 const char *device_name,
511 audio_format_t encodedFormat)
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800512{
513 status_t status;
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700514 String8 reply;
515 AudioParameter param;
516 int isReconfigA2dpSupported = 0;
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800517
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800518 ALOGV("handleDeviceConfigChange(() device: 0x%X, address %s name %s encodedFormat: 0x%X",
519 device, device_address, device_name, encodedFormat);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800520
Pavlin Radoslavovc694ff42017-01-09 23:27:29 -0800521 // connect/disconnect only 1 device at a time
522 if (!audio_is_output_device(device) && !audio_is_input_device(device)) return BAD_VALUE;
523
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800524 // Check if the device is currently connected
jiabin9a3361e2019-10-01 09:38:30 -0700525 DeviceVector deviceList = mAvailableOutputDevices.getDevicesFromType(device);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800526 if (deviceList.empty()) {
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800527 // Nothing to do: device is not connected
528 return NO_ERROR;
529 }
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800530 sp<DeviceDescriptor> devDesc = deviceList.itemAt(0);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800531
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700532 // For offloaded A2DP, Hw modules may have the capability to
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800533 // configure codecs.
534 // Handle two specific cases by sending a set parameter to
535 // configure A2DP codecs. No need to toggle device state.
536 // Case 1: A2DP active device switches from primary to primary
537 // module
538 // Case 2: A2DP device config changes on primary module.
Francois Gaffiebce7cd42020-10-14 16:13:20 +0200539 if (audio_is_a2dp_out_device(device) && hasPrimaryOutput()) {
jiabin9a3361e2019-10-01 09:38:30 -0700540 sp<HwModule> module = mHwModules.getModuleForDeviceType(device, encodedFormat);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800541 audio_module_handle_t primaryHandle = mPrimaryOutput->getModuleHandle();
542 if (availablePrimaryOutputDevices().contains(devDesc) &&
543 (module != 0 && module->getHandle() == primaryHandle)) {
544 reply = mpClientInterface->getParameters(
545 AUDIO_IO_HANDLE_NONE,
546 String8(AudioParameter::keyReconfigA2dpSupported));
547 AudioParameter repliedParameters(reply);
548 repliedParameters.getInt(
549 String8(AudioParameter::keyReconfigA2dpSupported), isReconfigA2dpSupported);
550 if (isReconfigA2dpSupported) {
551 const String8 key(AudioParameter::keyReconfigA2dp);
552 param.add(key, String8("true"));
553 mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString());
554 devDesc->setEncodedFormat(encodedFormat);
555 return NO_ERROR;
556 }
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700557 }
558 }
cnx421bd2dcc42020-07-11 14:58:44 +0800559 auto musicStrategy = streamToStrategy(AUDIO_STREAM_MUSIC);
560 for (size_t i = 0; i < mOutputs.size(); i++) {
561 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
562 // mute media strategies and delay device switch by the largest
563 // This avoid sending the music tail into the earpiece or headset.
564 setStrategyMute(musicStrategy, true, desc);
565 setStrategyMute(musicStrategy, false, desc, MUTE_TIME_MS,
566 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
567 nullptr, true /*fromCache*/).types());
568 }
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800569 // Toggle the device state: UNAVAILABLE -> AVAILABLE
570 // This will force reading again the device configuration
571 status = setDeviceConnectionState(device,
572 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800573 device_address, device_name,
574 devDesc->getEncodedFormat());
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800575 if (status != NO_ERROR) {
576 ALOGW("handleDeviceConfigChange() error disabling connection state: %d",
577 status);
578 return status;
579 }
580
581 status = setDeviceConnectionState(device,
582 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800583 device_address, device_name, encodedFormat);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800584 if (status != NO_ERROR) {
585 ALOGW("handleDeviceConfigChange() error enabling connection state: %d",
586 status);
587 return status;
588 }
589
590 return NO_ERROR;
591}
592
Pattydd807582021-11-04 21:01:03 +0800593status_t AudioPolicyManager::getHwOffloadFormatsSupportedForBluetoothMedia(
594 audio_devices_t device, std::vector<audio_format_t> *formats)
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800595{
Pattydd807582021-11-04 21:01:03 +0800596 ALOGV("getHwOffloadFormatsSupportedForBluetoothMedia()");
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800597 status_t status = NO_ERROR;
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800598 std::unordered_set<audio_format_t> formatSet;
599 sp<HwModule> primaryModule =
600 mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_PRIMARY);
Aniket Kumar Latafedb5982019-07-03 11:20:36 -0700601 if (primaryModule == nullptr) {
602 ALOGE("%s() unable to get primary module", __func__);
603 return NO_INIT;
604 }
Pattydd807582021-11-04 21:01:03 +0800605
606 DeviceTypeSet audioDeviceSet;
607
608 switch(device) {
609 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP:
610 audioDeviceSet = getAudioDeviceOutAllA2dpSet();
611 break;
612 case AUDIO_DEVICE_OUT_BLE_HEADSET:
Patty Huangf5082dd2022-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 Huangf5082dd2022-07-06 00:14:12 +08001059 if (profile != 0 &&
Dorin Drimusecc9f422022-03-09 17:57:40 +01001060 ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0)) {
Eric Laurent861a6282015-05-18 15:40:16 -07001061 continue;
Dorin Drimusecc9f422022-03-09 17:57:40 +01001062 }
1063 profile = curProfile;
1064 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1065 break;
1066 }
Eric Laurente552edb2014-03-10 17:42:56 -07001067 }
1068 }
Eric Laurent861a6282015-05-18 15:40:16 -07001069 return profile;
Eric Laurente552edb2014-03-10 17:42:56 -07001070}
1071
Eric Laurentfa0f6742021-08-17 18:39:44 +02001072sp<IOProfile> AudioPolicyManager::getSpatializerOutputProfile(
Eric Laurent39095982021-08-24 18:29:27 +02001073 const audio_config_t *config __unused, const AudioDeviceTypeAddrVector &devices) const
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001074{
1075 for (const auto& hwModule : mHwModules) {
1076 for (const auto& curProfile : hwModule->getOutputProfiles()) {
Eric Laurent1c5e2e32021-08-18 18:50:28 +02001077 if (curProfile->getFlags() != AUDIO_OUTPUT_FLAG_SPATIALIZER) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001078 continue;
1079 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001080 if (!devices.empty()) {
Eric Laurent0c8f7cc2022-06-24 14:32:36 +02001081 // reject profiles not corresponding to a device currently available
1082 DeviceVector supportedDevices = curProfile->getSupportedDevices();
1083 if (!mAvailableOutputDevices.containsAtLeastOne(supportedDevices)) {
1084 continue;
1085 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001086 if (supportedDevices.getDevicesFromDeviceTypeAddrVec(devices).size()
1087 != devices.size()) {
1088 continue;
1089 }
1090 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001091 ALOGV("%s found profile %s", __func__, curProfile->getName().c_str());
1092 return curProfile;
1093 }
1094 }
1095 return nullptr;
1096}
1097
Eric Laurentf4e63452017-11-06 19:31:46 +00001098audio_io_handle_t AudioPolicyManager::getOutput(audio_stream_type_t stream)
Eric Laurente552edb2014-03-10 17:42:56 -07001099{
François Gaffiec005e562018-11-06 15:04:49 +01001100 DeviceVector devices = mEngine->getOutputDevicesForStream(stream, false /*fromCache*/);
Andy Hungc9901522017-11-10 20:07:54 -08001101
1102 // Note that related method getOutputForAttr() uses getOutputForDevice() not selectOutput().
1103 // We use selectOutput() here since we don't have the desired AudioTrack sample rate,
1104 // format, flags, etc. This may result in some discrepancy for functions that utilize
1105 // getOutput() solely on audio_stream_type such as AudioSystem::getOutputFrameCount()
1106 // and AudioSystem::getOutputSamplingRate().
1107
François Gaffie11d30102018-11-02 16:09:09 +01001108 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Mingyu Shih75563d32023-05-24 04:47:40 +08001109 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
1110 if (stream == AUDIO_STREAM_MUSIC &&
1111 property_get_bool("audio.deep_buffer.media", false /* default_value */)) {
1112 flags = AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
1113 }
1114 const audio_io_handle_t output = selectOutput(outputs, flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001115
François Gaffie11d30102018-11-02 16:09:09 +01001116 ALOGV("getOutput() stream %d selected devices %s, output %d", stream,
1117 devices.toString().c_str(), output);
Eric Laurentf4e63452017-11-06 19:31:46 +00001118 return output;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001119}
1120
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001121status_t AudioPolicyManager::getAudioAttributes(audio_attributes_t *dstAttr,
1122 const audio_attributes_t *srcAttr,
1123 audio_stream_type_t srcStream)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001124{
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001125 if (srcAttr != NULL) {
1126 if (!isValidAttributes(srcAttr)) {
1127 ALOGE("%s invalid attributes: usage=%d content=%d flags=0x%x tags=[%s]",
1128 __func__,
1129 srcAttr->usage, srcAttr->content_type, srcAttr->flags,
1130 srcAttr->tags);
1131 return BAD_VALUE;
1132 }
1133 *dstAttr = *srcAttr;
1134 } else {
1135 if (srcStream < AUDIO_STREAM_MIN || srcStream >= AUDIO_STREAM_PUBLIC_CNT) {
1136 ALOGE("%s: invalid stream type", __func__);
1137 return BAD_VALUE;
1138 }
François Gaffiec005e562018-11-06 15:04:49 +01001139 *dstAttr = mEngine->getAttributesForStreamType(srcStream);
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001140 }
Eric Laurent22fcda22019-05-17 16:28:47 -07001141
1142 // Only honor audibility enforced when required. The client will be
1143 // forced to reconnect if the forced usage changes.
1144 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Mikhail Naganov55773032020-10-01 15:08:13 -07001145 dstAttr->flags = static_cast<audio_flags_mask_t>(
1146 dstAttr->flags & ~AUDIO_FLAG_AUDIBILITY_ENFORCED);
Eric Laurent22fcda22019-05-17 16:28:47 -07001147 }
1148
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001149 return NO_ERROR;
1150}
1151
Kevin Rocard153f92d2018-12-18 18:33:28 -08001152status_t AudioPolicyManager::getOutputForAttrInt(
1153 audio_attributes_t *resultAttr,
1154 audio_io_handle_t *output,
1155 audio_session_t session,
1156 const audio_attributes_t *attr,
1157 audio_stream_type_t *stream,
1158 uid_t uid,
jiabinf1c73972022-04-14 16:28:52 -07001159 audio_config_t *config,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001160 audio_output_flags_t *flags,
1161 audio_port_handle_t *selectedDeviceId,
1162 bool *isRequestedDeviceForExclusiveUse,
Eric Laurentc529cf62020-04-17 18:19:10 -07001163 std::vector<sp<AudioPolicyMix>> *secondaryMixes,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001164 output_type_t *outputType,
jiabinc658e452022-10-21 20:52:21 +00001165 bool *isSpatialized,
1166 bool *isBitPerfect)
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001167{
François Gaffiec005e562018-11-06 15:04:49 +01001168 DeviceVector outputDevices;
Francois Gaffie716e1432019-01-14 16:58:59 +01001169 const audio_port_handle_t requestedPortId = *selectedDeviceId;
François Gaffie11d30102018-11-02 16:09:09 +01001170 DeviceVector msdDevices = getMsdAudioOutDevices();
François Gaffiec005e562018-11-06 15:04:49 +01001171 const sp<DeviceDescriptor> requestedDevice =
1172 mAvailableOutputDevices.getDeviceFromId(requestedPortId);
1173
Eric Laurent8a1095a2019-11-08 14:44:16 -08001174 *outputType = API_OUTPUT_INVALID;
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001175 *isSpatialized = false;
1176
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001177 status_t status = getAudioAttributes(resultAttr, attr, *stream);
1178 if (status != NO_ERROR) {
1179 return status;
Eric Laurent8f42ea12018-08-08 09:08:25 -07001180 }
Kevin Rocardb99cc752019-03-21 20:52:24 -07001181 if (auto it = mAllowedCapturePolicies.find(uid); it != end(mAllowedCapturePolicies)) {
Mikhail Naganov55773032020-10-01 15:08:13 -07001182 resultAttr->flags = static_cast<audio_flags_mask_t>(resultAttr->flags | it->second);
Kevin Rocardb99cc752019-03-21 20:52:24 -07001183 }
François Gaffiec005e562018-11-06 15:04:49 +01001184 *stream = mEngine->getStreamTypeForAttributes(*resultAttr);
Eric Laurent8f42ea12018-08-08 09:08:25 -07001185
François Gaffiec005e562018-11-06 15:04:49 +01001186 ALOGV("%s() attributes=%s stream=%s session %d selectedDeviceId %d", __func__,
1187 toString(*resultAttr).c_str(), toString(*stream).c_str(), session, requestedPortId);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001188
Oscar Azucena873d10f2023-01-12 18:34:42 -08001189 bool usePrimaryOutputFromPolicyMixes = false;
1190
Kevin Rocard153f92d2018-12-18 18:33:28 -08001191 // The primary output is the explicit routing (eg. setPreferredDevice) if specified,
1192 // otherwise, fallback to the dynamic policies, if none match, query the engine.
1193 // Secondary outputs are always found by dynamic policies as the engine do not support them
Eric Laurentc529cf62020-04-17 18:19:10 -07001194 sp<AudioPolicyMix> primaryMix;
Dean Wheatleyd082f472022-02-04 11:10:48 +11001195 const audio_config_base_t clientConfig = {.sample_rate = config->sample_rate,
1196 .channel_mask = config->channel_mask,
1197 .format = config->format,
1198 };
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02001199 status = mPolicyMixes.getOutputForAttr(*resultAttr, clientConfig, uid, session, *flags,
Oscar Azucena873d10f2023-01-12 18:34:42 -08001200 mAvailableOutputDevices, requestedDevice, primaryMix,
1201 secondaryMixes, usePrimaryOutputFromPolicyMixes);
Kevin Rocard94114a22019-04-01 19:38:23 -07001202 if (status != OK) {
1203 return status;
Kevin Rocard153f92d2018-12-18 18:33:28 -08001204 }
Kevin Rocard94114a22019-04-01 19:38:23 -07001205
Kevin Rocard153f92d2018-12-18 18:33:28 -08001206 // FIXME: in case of RENDER policy, the output capabilities should be checked
Dean Wheatleyd082f472022-02-04 11:10:48 +11001207 if ((secondaryMixes != nullptr && !secondaryMixes->empty())
1208 && !audio_is_linear_pcm(config->format)) {
1209 ALOGD("%s: rejecting request as secondary mixes only support pcm", __func__);
Kevin Rocard153f92d2018-12-18 18:33:28 -08001210 return BAD_VALUE;
1211 }
1212 if (usePrimaryOutputFromPolicyMixes) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001213 sp<DeviceDescriptor> deviceDesc =
1214 mAvailableOutputDevices.getDevice(primaryMix->mDeviceType,
1215 primaryMix->mDeviceAddress,
1216 AUDIO_FORMAT_DEFAULT);
1217 sp<SwAudioOutputDescriptor> policyDesc = primaryMix->getOutput();
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001218 bool tryDirectForFlags = policyDesc == nullptr ||
1219 (policyDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT);
1220 // if a direct output can be opened to deliver the track's multi-channel content to the
1221 // output rather than being downmixed by the primary output, then use this direct
1222 // output by by-passing the primary mix if possible, otherwise fall-through to primary
1223 // mix.
1224 bool tryDirectForChannelMask = policyDesc != nullptr
1225 && (audio_channel_count_from_out_mask(policyDesc->getConfig().channel_mask) <
1226 audio_channel_count_from_out_mask(config->channel_mask));
1227 if (deviceDesc != nullptr && (tryDirectForFlags || tryDirectForChannelMask)) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001228 audio_io_handle_t newOutput;
1229 status = openDirectOutput(
1230 *stream, session, config,
1231 (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT),
1232 DeviceVector(deviceDesc), &newOutput);
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001233 if (status == NO_ERROR) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001234 policyDesc = mOutputs.valueFor(newOutput);
1235 primaryMix->setOutput(policyDesc);
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001236 } else if (tryDirectForFlags) {
1237 policyDesc = nullptr;
1238 } // otherwise use primary if available.
Eric Laurentc529cf62020-04-17 18:19:10 -07001239 }
1240 if (policyDesc != nullptr) {
1241 policyDesc->mPolicyMix = primaryMix;
1242 *output = policyDesc->mIoHandle;
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08001243 *selectedDeviceId = deviceDesc != 0 ? deviceDesc->getId() : AUDIO_PORT_HANDLE_NONE;
Eric Laurent8a1095a2019-11-08 14:44:16 -08001244
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08001245 ALOGV("getOutputForAttr() returns output %d", *output);
1246 if (resultAttr->usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
1247 *outputType = API_OUT_MIX_PLAYBACK;
1248 } else {
1249 *outputType = API_OUTPUT_LEGACY;
1250 }
1251 return NO_ERROR;
Eric Laurent8a1095a2019-11-08 14:44:16 -08001252 }
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001253 }
François Gaffiec005e562018-11-06 15:04:49 +01001254 // Virtual sources must always be dynamicaly or explicitly routed
1255 if (resultAttr->usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
1256 ALOGW("getOutputForAttr() no policy mix found for usage AUDIO_USAGE_VIRTUAL_SOURCE");
1257 return BAD_VALUE;
1258 }
1259 // explicit routing managed by getDeviceForStrategy in APM is now handled by engine
1260 // in order to let the choice of the order to future vendor engine
1261 outputDevices = mEngine->getOutputDevicesForAttributes(*resultAttr, requestedDevice, false);
Scott Randolph7b1fd232018-06-18 15:33:03 -07001262
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001263 if ((resultAttr->flags & AUDIO_FLAG_HW_AV_SYNC) != 0) {
Nadav Bar766fb022018-01-07 12:18:03 +02001264 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
Eric Laurent93c3d412014-08-01 14:48:35 -07001265 }
1266
Nadav Barb2f18162018-07-18 13:01:53 +03001267 // Set incall music only if device was explicitly set, and fallback to the device which is
1268 // chosen by the engine if not.
1269 // FIXME: provide a more generic approach which is not device specific and move this back
1270 // to getOutputForDevice.
Nadav Bar20919492018-11-20 10:20:51 +02001271 // TODO: Remove check of AUDIO_STREAM_MUSIC once migration is completed on the app side.
jiabin9a3361e2019-10-01 09:38:30 -07001272 if (outputDevices.onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_TELEPHONY_TX) &&
François Gaffiec005e562018-11-06 15:04:49 +01001273 (*stream == AUDIO_STREAM_MUSIC || resultAttr->usage == AUDIO_USAGE_VOICE_COMMUNICATION) &&
Nadav Barb2f18162018-07-18 13:01:53 +03001274 audio_is_linear_pcm(config->format) &&
Eric Laurent74b71512019-11-06 17:21:57 -08001275 isCallAudioAccessible()) {
Francois Gaffie716e1432019-01-14 16:58:59 +01001276 if (requestedPortId != AUDIO_PORT_HANDLE_NONE) {
Nadav Barb2f18162018-07-18 13:01:53 +03001277 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_INCALL_MUSIC;
François Gaffief579db52018-11-13 11:25:16 +01001278 *isRequestedDeviceForExclusiveUse = true;
Nadav Barb2f18162018-07-18 13:01:53 +03001279 }
1280 }
1281
François Gaffiec005e562018-11-06 15:04:49 +01001282 ALOGV("%s() device %s, sampling rate %d, format %#x, channel mask %#x, flags %#x stream %s",
1283 __func__, outputDevices.toString().c_str(), config->sample_rate, config->format,
1284 config->channel_mask, *flags, toString(*stream).c_str());
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001285
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001286 *output = AUDIO_IO_HANDLE_NONE;
François Gaffie11d30102018-11-02 16:09:09 +01001287 if (!msdDevices.isEmpty()) {
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001288 *output = getOutputForDevices(msdDevices, session, resultAttr, config, flags, isSpatialized);
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001289 if (*output != AUDIO_IO_HANDLE_NONE && setMsdOutputPatches(&outputDevices) == NO_ERROR) {
François Gaffiec005e562018-11-06 15:04:49 +01001290 ALOGV("%s() Using MSD devices %s instead of devices %s",
1291 __func__, msdDevices.toString().c_str(), outputDevices.toString().c_str());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001292 } else {
1293 *output = AUDIO_IO_HANDLE_NONE;
1294 }
1295 }
1296 if (*output == AUDIO_IO_HANDLE_NONE) {
jiabina84c3d32022-12-02 18:59:55 +00001297 sp<PreferredMixerAttributesInfo> info = nullptr;
1298 if (outputDevices.size() == 1) {
1299 info = getPreferredMixerAttributesInfo(
1300 outputDevices.itemAt(0)->getId(),
1301 mEngine->getProductStrategyForAttributes(*resultAttr));
jiabin5eaf0962022-12-20 20:11:38 +00001302 // Only use preferred mixer if the uid matches or the preferred mixer is bit-perfect
1303 // and it is currently active.
1304 if (info != nullptr && info->getUid() != uid &&
1305 ((info->getFlags() & AUDIO_OUTPUT_FLAG_BIT_PERFECT) == AUDIO_OUTPUT_FLAG_NONE ||
1306 info->getActiveClientCount() == 0)) {
jiabina84c3d32022-12-02 18:59:55 +00001307 info = nullptr;
1308 }
1309 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001310 *output = getOutputForDevices(outputDevices, session, resultAttr, config,
jiabina84c3d32022-12-02 18:59:55 +00001311 flags, isSpatialized, info, resultAttr->flags & AUDIO_FLAG_MUTE_HAPTIC);
jiabin5eaf0962022-12-20 20:11:38 +00001312 // The client will be active if the client is currently preferred mixer owner and the
1313 // requested configuration matches the preferred mixer configuration.
jiabinc658e452022-10-21 20:52:21 +00001314 *isBitPerfect = (info != nullptr
1315 && (info->getFlags() & AUDIO_OUTPUT_FLAG_BIT_PERFECT) != AUDIO_OUTPUT_FLAG_NONE
jiabin5eaf0962022-12-20 20:11:38 +00001316 && info->getUid() == uid
1317 && *output != AUDIO_IO_HANDLE_NONE
1318 // When bit-perfect output is selected for the preferred mixer attributes owner,
1319 // only need to consider the config matches.
1320 && mOutputs.valueFor(*output)->isConfigurationMatched(
1321 clientConfig, AUDIO_OUTPUT_FLAG_NONE));
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001322 }
Eric Laurente83b55d2014-11-14 10:06:21 -08001323 if (*output == AUDIO_IO_HANDLE_NONE) {
jiabinf1c73972022-04-14 16:28:52 -07001324 AudioProfileVector profiles;
1325 status_t ret = getProfilesForDevices(outputDevices, profiles, *flags, false /*isInput*/);
1326 if (ret == NO_ERROR && !profiles.empty()) {
1327 config->channel_mask = profiles[0]->getChannels().empty() ? config->channel_mask
1328 : *profiles[0]->getChannels().begin();
1329 config->sample_rate = profiles[0]->getSampleRates().empty() ? config->sample_rate
1330 : *profiles[0]->getSampleRates().begin();
1331 config->format = profiles[0]->getFormat();
1332 }
Eric Laurente83b55d2014-11-14 10:06:21 -08001333 return INVALID_OPERATION;
1334 }
Paul McLeanaa981192015-03-21 09:55:15 -07001335
François Gaffiec005e562018-11-06 15:04:49 +01001336 *selectedDeviceId = getFirstDeviceId(outputDevices);
Michael Chan6fb34492020-12-08 15:44:49 +11001337 for (auto &outputDevice : outputDevices) {
Mikhail Naganovb0fbc1b2023-04-28 13:06:32 -07001338 if (outputDevice->getId() == mConfig->getDefaultOutputDevice()->getId()) {
Michael Chan6fb34492020-12-08 15:44:49 +11001339 *selectedDeviceId = outputDevice->getId();
1340 break;
1341 }
1342 }
Eric Laurent2ac76942017-06-22 17:17:09 -07001343
Eric Laurent8a1095a2019-11-08 14:44:16 -08001344 if (outputDevices.onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_TELEPHONY_TX)) {
1345 *outputType = API_OUTPUT_TELEPHONY_TX;
1346 } else {
1347 *outputType = API_OUTPUT_LEGACY;
1348 }
1349
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001350 ALOGV("%s returns output %d selectedDeviceId %d", __func__, *output, *selectedDeviceId);
1351
1352 return NO_ERROR;
1353}
1354
1355status_t AudioPolicyManager::getOutputForAttr(const audio_attributes_t *attr,
1356 audio_io_handle_t *output,
1357 audio_session_t session,
1358 audio_stream_type_t *stream,
Svet Ganov3e5f14f2021-05-13 22:51:08 +00001359 const AttributionSourceState& attributionSource,
jiabinf1c73972022-04-14 16:28:52 -07001360 audio_config_t *config,
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001361 audio_output_flags_t *flags,
1362 audio_port_handle_t *selectedDeviceId,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001363 audio_port_handle_t *portId,
Eric Laurent8a1095a2019-11-08 14:44:16 -08001364 std::vector<audio_io_handle_t> *secondaryOutputs,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001365 output_type_t *outputType,
jiabinc658e452022-10-21 20:52:21 +00001366 bool *isSpatialized,
1367 bool *isBitPerfect)
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001368{
1369 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
1370 if (*portId != AUDIO_PORT_HANDLE_NONE) {
1371 return INVALID_OPERATION;
1372 }
Philip P. Moltmannbda45752020-07-17 16:41:18 -07001373 const uid_t uid = VALUE_OR_RETURN_STATUS(
Svet Ganov3e5f14f2021-05-13 22:51:08 +00001374 aidl2legacy_int32_t_uid_t(attributionSource.uid));
Francois Gaffie716e1432019-01-14 16:58:59 +01001375 const audio_port_handle_t requestedPortId = *selectedDeviceId;
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001376 audio_attributes_t resultAttr;
François Gaffief579db52018-11-13 11:25:16 +01001377 bool isRequestedDeviceForExclusiveUse = false;
Eric Laurentc529cf62020-04-17 18:19:10 -07001378 std::vector<sp<AudioPolicyMix>> secondaryMixes;
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001379 const sp<DeviceDescriptor> requestedDevice =
1380 mAvailableOutputDevices.getDeviceFromId(requestedPortId);
1381
1382 // Prevent from storing invalid requested device id in clients
1383 const audio_port_handle_t sanitizedRequestedPortId =
1384 requestedDevice != nullptr ? requestedPortId : AUDIO_PORT_HANDLE_NONE;
1385 *selectedDeviceId = sanitizedRequestedPortId;
1386
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001387 status_t status = getOutputForAttrInt(&resultAttr, output, session, attr, stream, uid,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001388 config, flags, selectedDeviceId, &isRequestedDeviceForExclusiveUse,
jiabinc658e452022-10-21 20:52:21 +00001389 secondaryOutputs != nullptr ? &secondaryMixes : nullptr, outputType, isSpatialized,
1390 isBitPerfect);
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001391 if (status != NO_ERROR) {
1392 return status;
1393 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001394 std::vector<wp<SwAudioOutputDescriptor>> weakSecondaryOutputDescs;
Eric Laurentc529cf62020-04-17 18:19:10 -07001395 if (secondaryOutputs != nullptr) {
1396 for (auto &secondaryMix : secondaryMixes) {
1397 sp<SwAudioOutputDescriptor> outputDesc = secondaryMix->getOutput();
1398 if (outputDesc != nullptr &&
1399 outputDesc->mIoHandle != AUDIO_IO_HANDLE_NONE) {
1400 secondaryOutputs->push_back(outputDesc->mIoHandle);
1401 weakSecondaryOutputDescs.push_back(outputDesc);
1402 }
1403 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001404 }
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001405
Eric Laurent8fc147b2018-07-22 19:13:55 -07001406 audio_config_base_t clientConfig = {.sample_rate = config->sample_rate,
Nick Desaulniersa30e3202019-10-18 13:38:23 -07001407 .channel_mask = config->channel_mask,
Eric Laurent8fc147b2018-07-22 19:13:55 -07001408 .format = config->format,
Nick Desaulniersa30e3202019-10-18 13:38:23 -07001409 };
jiabin4ef93452019-09-10 14:29:54 -07001410 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurent8f42ea12018-08-08 09:08:25 -07001411
Eric Laurentc209fe42020-06-05 18:11:23 -07001412 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(*output);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001413 sp<TrackClientDescriptor> clientDesc =
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001414 new TrackClientDescriptor(*portId, uid, session, resultAttr, clientConfig,
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001415 sanitizedRequestedPortId, *stream,
François Gaffiec005e562018-11-06 15:04:49 +01001416 mEngine->getProductStrategyForAttributes(resultAttr),
François Gaffieaaac0fd2018-11-22 17:56:39 +01001417 toVolumeSource(resultAttr),
Kevin Rocard153f92d2018-12-18 18:33:28 -08001418 *flags, isRequestedDeviceForExclusiveUse,
Eric Laurentc209fe42020-06-05 18:11:23 -07001419 std::move(weakSecondaryOutputDescs),
1420 outputDesc->mPolicyMix);
Andy Hung39efb7a2018-09-26 15:39:28 -07001421 outputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001422
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001423 ALOGV("%s() returns output %d requestedPortId %d selectedDeviceId %d for port ID %d", __func__,
1424 *output, requestedPortId, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07001425
Eric Laurente83b55d2014-11-14 10:06:21 -08001426 return NO_ERROR;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001427}
1428
Eric Laurentc529cf62020-04-17 18:19:10 -07001429status_t AudioPolicyManager::openDirectOutput(audio_stream_type_t stream,
1430 audio_session_t session,
1431 const audio_config_t *config,
1432 audio_output_flags_t flags,
1433 const DeviceVector &devices,
1434 audio_io_handle_t *output) {
1435
1436 *output = AUDIO_IO_HANDLE_NONE;
1437
1438 // skip direct output selection if the request can obviously be attached to a mixed output
1439 // and not explicitly requested
1440 if (((flags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
1441 audio_is_linear_pcm(config->format) && config->sample_rate <= SAMPLE_RATE_HZ_MAX &&
1442 audio_channel_count_from_out_mask(config->channel_mask) <= 2) {
1443 return NAME_NOT_FOUND;
1444 }
1445
1446 // Do not allow offloading if one non offloadable effect is enabled or MasterMono is enabled.
1447 // This prevents creating an offloaded track and tearing it down immediately after start
1448 // when audioflinger detects there is an active non offloadable effect.
1449 // FIXME: We should check the audio session here but we do not have it in this context.
1450 // This may prevent offloading in rare situations where effects are left active by apps
1451 // in the background.
1452 sp<IOProfile> profile;
1453 if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) ||
1454 !(mEffects.isNonOffloadableEffectEnabled() || mMasterMono)) {
1455 profile = getProfileForOutput(
1456 devices, config->sample_rate, config->format, config->channel_mask,
1457 flags, true /* directOnly */);
1458 }
1459
1460 if (profile == nullptr) {
1461 return NAME_NOT_FOUND;
1462 }
1463
1464 // exclusive outputs for MMAP and Offload are enforced by different session ids.
1465 for (size_t i = 0; i < mOutputs.size(); i++) {
1466 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
1467 if (!desc->isDuplicated() && (profile == desc->mProfile)) {
1468 // reuse direct output if currently open by the same client
1469 // and configured with same parameters
1470 if ((config->sample_rate == desc->getSamplingRate()) &&
1471 (config->format == desc->getFormat()) &&
1472 (config->channel_mask == desc->getChannelMask()) &&
1473 (session == desc->mDirectClientSession)) {
1474 desc->mDirectOpenCount++;
Eric Laurentfecbceb2021-02-09 14:46:43 +01001475 ALOGV("%s reusing direct output %d for session %d", __func__,
Eric Laurentc529cf62020-04-17 18:19:10 -07001476 mOutputs.keyAt(i), session);
1477 *output = mOutputs.keyAt(i);
1478 return NO_ERROR;
1479 }
1480 }
1481 }
1482
1483 if (!profile->canOpenNewIo()) {
1484 return NAME_NOT_FOUND;
1485 }
1486
1487 sp<SwAudioOutputDescriptor> outputDesc =
1488 new SwAudioOutputDescriptor(profile, mpClientInterface);
1489
Michael Chan6fb34492020-12-08 15:44:49 +11001490 // An MSD patch may be using the only output stream that can service this request. Release
1491 // all MSD patches to prioritize this request over any active output on MSD.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001492 releaseMsdOutputPatches(devices);
Eric Laurentc529cf62020-04-17 18:19:10 -07001493
Eric Laurentf1f22e72021-07-13 14:04:14 +02001494 status_t status =
1495 outputDesc->open(config, nullptr /* mixerConfig */, devices, stream, flags, output);
Eric Laurentc529cf62020-04-17 18:19:10 -07001496
1497 // only accept an output with the requested parameters
1498 if (status != NO_ERROR ||
1499 (config->sample_rate != 0 && config->sample_rate != outputDesc->getSamplingRate()) ||
1500 (config->format != AUDIO_FORMAT_DEFAULT && config->format != outputDesc->getFormat()) ||
1501 (config->channel_mask != 0 && config->channel_mask != outputDesc->getChannelMask())) {
1502 ALOGV("%s failed opening direct output: output %d sample rate %d %d,"
1503 "format %d %d, channel mask %04x %04x", __func__, *output, config->sample_rate,
1504 outputDesc->getSamplingRate(), config->format, outputDesc->getFormat(),
1505 config->channel_mask, outputDesc->getChannelMask());
1506 if (*output != AUDIO_IO_HANDLE_NONE) {
1507 outputDesc->close();
1508 }
1509 // fall back to mixer output if possible when the direct output could not be open
1510 if (audio_is_linear_pcm(config->format) &&
1511 config->sample_rate <= SAMPLE_RATE_HZ_MAX) {
1512 return NAME_NOT_FOUND;
1513 }
1514 *output = AUDIO_IO_HANDLE_NONE;
1515 return BAD_VALUE;
1516 }
1517 outputDesc->mDirectOpenCount = 1;
1518 outputDesc->mDirectClientSession = session;
1519
1520 addOutput(*output, outputDesc);
1521 mPreviousOutputs = mOutputs;
1522 ALOGV("%s returns new direct output %d", __func__, *output);
1523 mpClientInterface->onAudioPortListUpdate();
1524 return NO_ERROR;
1525}
1526
François Gaffie11d30102018-11-02 16:09:09 +01001527audio_io_handle_t AudioPolicyManager::getOutputForDevices(
1528 const DeviceVector &devices,
Kevin Rocard169753c2017-03-06 14:18:23 -08001529 audio_session_t session,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001530 const audio_attributes_t *attr,
Eric Laurentfe231122017-11-17 17:48:06 -08001531 const audio_config_t *config,
jiabine375d412019-02-26 12:54:53 -08001532 audio_output_flags_t *flags,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001533 bool *isSpatialized,
jiabina84c3d32022-12-02 18:59:55 +00001534 sp<PreferredMixerAttributesInfo> prefMixerConfigInfo,
jiabine375d412019-02-26 12:54:53 -08001535 bool forceMutingHaptic)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001536{
Andy Hungc88b0642018-04-27 15:42:35 -07001537 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001538
jiabine375d412019-02-26 12:54:53 -08001539 // Discard haptic channel mask when forcing muting haptic channels.
1540 audio_channel_mask_t channelMask = forceMutingHaptic
Mikhail Naganov55773032020-10-01 15:08:13 -07001541 ? static_cast<audio_channel_mask_t>(config->channel_mask & ~AUDIO_CHANNEL_HAPTIC_ALL)
1542 : config->channel_mask;
jiabine375d412019-02-26 12:54:53 -08001543
Eric Laurente552edb2014-03-10 17:42:56 -07001544 // open a direct output if required by specified parameters
1545 //force direct flag if offload flag is set: offloading implies a direct output stream
1546 // and all common behaviors are driven by checking only the direct flag
1547 // this should normally be set appropriately in the policy configuration file
Nadav Bar766fb022018-01-07 12:18:03 +02001548 if ((*flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1549 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurente552edb2014-03-10 17:42:56 -07001550 }
Nadav Bar766fb022018-01-07 12:18:03 +02001551 if ((*flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
1552 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent93c3d412014-08-01 14:48:35 -07001553 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001554
1555 audio_stream_type_t stream = mEngine->getStreamTypeForAttributes(*attr);
1556
Eric Laurente83b55d2014-11-14 10:06:21 -08001557 // only allow deep buffering for music stream type
1558 if (stream != AUDIO_STREAM_MUSIC) {
Nadav Bar766fb022018-01-07 12:18:03 +02001559 *flags = (audio_output_flags_t)(*flags &~AUDIO_OUTPUT_FLAG_DEEP_BUFFER);
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -07001560 } else if (/* stream == AUDIO_STREAM_MUSIC && */
Nadav Bar766fb022018-01-07 12:18:03 +02001561 *flags == AUDIO_OUTPUT_FLAG_NONE &&
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -07001562 property_get_bool("audio.deep_buffer.media", false /* default_value */)) {
1563 // use DEEP_BUFFER as default output for music stream type
Nadav Bar766fb022018-01-07 12:18:03 +02001564 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
Eric Laurente83b55d2014-11-14 10:06:21 -08001565 }
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -07001566 if (stream == AUDIO_STREAM_TTS) {
Nadav Bar766fb022018-01-07 12:18:03 +02001567 *flags = AUDIO_OUTPUT_FLAG_TTS;
Haynes Mathew George84c621e2017-04-25 11:41:50 -07001568 } else if (stream == AUDIO_STREAM_VOICE_CALL &&
Nadav Bar20919492018-11-20 10:20:51 +02001569 audio_is_linear_pcm(config->format) &&
1570 (*flags & AUDIO_OUTPUT_FLAG_INCALL_MUSIC) == 0) {
Nadav Bar766fb022018-01-07 12:18:03 +02001571 *flags = (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_VOIP_RX |
Haynes Mathew George84c621e2017-04-25 11:41:50 -07001572 AUDIO_OUTPUT_FLAG_DIRECT);
1573 ALOGV("Set VoIP and Direct output flags for PCM format");
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -07001574 }
Eric Laurente552edb2014-03-10 17:42:56 -07001575
Carter Hsua3abb402021-10-26 11:11:20 +08001576 // Attach the Ultrasound flag for the AUDIO_CONTENT_TYPE_ULTRASOUND
1577 if (attr->content_type == AUDIO_CONTENT_TYPE_ULTRASOUND) {
1578 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_ULTRASOUND);
1579 }
1580
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001581 *isSpatialized = false;
Eric Laurentfa0f6742021-08-17 18:39:44 +02001582 if (mSpatializerOutput != nullptr
Andy Hung9dd1a5b2022-05-10 15:39:39 -07001583 && canBeSpatializedInt(attr, config, devices.toTypeAddrVector())) {
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001584 *isSpatialized = true;
Eric Laurentfa0f6742021-08-17 18:39:44 +02001585 return mSpatializerOutput->mIoHandle;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001586 }
1587
Eric Laurentc529cf62020-04-17 18:19:10 -07001588 audio_config_t directConfig = *config;
1589 directConfig.channel_mask = channelMask;
1590 status_t status = openDirectOutput(stream, session, &directConfig, *flags, devices, &output);
1591 if (status != NAME_NOT_FOUND) {
Eric Laurente552edb2014-03-10 17:42:56 -07001592 return output;
1593 }
1594
Eric Laurent14cbfca2016-03-17 09:42:16 -07001595 // A request for HW A/V sync cannot fallback to a mixed output because time
1596 // stamps are embedded in audio data
Phil Burk2d059932018-02-15 15:55:11 -08001597 if ((*flags & (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ)) != 0) {
Eric Laurent14cbfca2016-03-17 09:42:16 -07001598 return AUDIO_IO_HANDLE_NONE;
1599 }
Pierre Couillaude73496b2023-03-06 16:19:05 +00001600 // A request for Tuner cannot fallback to a mixed output
1601 if ((directConfig.offload_info.content_id || directConfig.offload_info.sync_id)) {
1602 return AUDIO_IO_HANDLE_NONE;
1603 }
Eric Laurent14cbfca2016-03-17 09:42:16 -07001604
Eric Laurente552edb2014-03-10 17:42:56 -07001605 // ignoring channel mask due to downmix capability in mixer
1606
1607 // open a non direct output
1608
1609 // for non direct outputs, only PCM is supported
Eric Laurentfe231122017-11-17 17:48:06 -08001610 if (audio_is_linear_pcm(config->format)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001611 // get which output is suitable for the specified stream. The actual
1612 // routing change will happen when startOutput() will be called
François Gaffie11d30102018-11-02 16:09:09 +01001613 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
jiabina84c3d32022-12-02 18:59:55 +00001614 if (prefMixerConfigInfo != nullptr) {
1615 for (audio_io_handle_t outputHandle : outputs) {
1616 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(outputHandle);
1617 if (outputDesc->mProfile == prefMixerConfigInfo->getProfile()) {
1618 output = outputHandle;
1619 break;
1620 }
1621 }
1622 if (output == AUDIO_IO_HANDLE_NONE) {
1623 // No output open with the preferred profile. Open a new one.
1624 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
1625 config.channel_mask = prefMixerConfigInfo->getConfigBase().channel_mask;
1626 config.sample_rate = prefMixerConfigInfo->getConfigBase().sample_rate;
1627 config.format = prefMixerConfigInfo->getConfigBase().format;
1628 sp<SwAudioOutputDescriptor> preferredOutput = openOutputWithProfileAndDevice(
1629 prefMixerConfigInfo->getProfile(), devices, nullptr /*mixerConfig*/,
1630 &config, prefMixerConfigInfo->getFlags());
1631 if (preferredOutput == nullptr) {
1632 ALOGE("%s failed to open output with preferred mixer config", __func__);
1633 } else {
1634 output = preferredOutput->mIoHandle;
1635 }
1636 }
1637 } else {
1638 // at this stage we should ignore the DIRECT flag as no direct output could be
1639 // found earlier
1640 *flags = (audio_output_flags_t) (*flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
1641 output = selectOutput(
1642 outputs, *flags, config->format, channelMask, config->sample_rate, session);
1643 }
Eric Laurente552edb2014-03-10 17:42:56 -07001644 }
François Gaffie11d30102018-11-02 16:09:09 +01001645 ALOGW_IF((output == 0), "getOutputForDevices() could not find output for stream %d, "
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001646 "sampling rate %d, format %#x, channels %#x, flags %#x",
jiabine375d412019-02-26 12:54:53 -08001647 stream, config->sample_rate, config->format, channelMask, *flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001648
Eric Laurente552edb2014-03-10 17:42:56 -07001649 return output;
1650}
1651
Mikhail Naganovf02f3672018-11-09 12:44:16 -08001652sp<DeviceDescriptor> AudioPolicyManager::getMsdAudioInDevice() const {
François Gaffie11d30102018-11-02 16:09:09 +01001653 auto msdInDevices = mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1654 mAvailableInputDevices);
1655 return msdInDevices.isEmpty()? nullptr : msdInDevices.itemAt(0);
1656}
1657
1658DeviceVector AudioPolicyManager::getMsdAudioOutDevices() const {
1659 return mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1660 mAvailableOutputDevices);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001661}
1662
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001663const AudioPatchCollection AudioPolicyManager::getMsdOutputPatches() const {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001664 AudioPatchCollection msdPatches;
Mikhail Naganov86112352018-10-04 09:02:49 -07001665 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1666 if (msdModule != 0) {
1667 for (size_t i = 0; i < mAudioPatches.size(); ++i) {
1668 sp<AudioPatch> patch = mAudioPatches.valueAt(i);
1669 for (size_t j = 0; j < patch->mPatch.num_sources; ++j) {
1670 const struct audio_port_config *source = &patch->mPatch.sources[j];
1671 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
1672 source->ext.device.hw_module == msdModule->getHandle()) {
François Gaffieafd4cea2019-11-18 15:50:22 +01001673 msdPatches.addAudioPatch(patch->getHandle(), patch);
Mikhail Naganov86112352018-10-04 09:02:49 -07001674 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001675 }
1676 }
1677 }
1678 return msdPatches;
1679}
1680
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02001681bool AudioPolicyManager::isMsdPatch(const audio_patch_handle_t &handle) const {
1682 ssize_t index = mAudioPatches.indexOfKey(handle);
1683 if (index < 0) {
1684 return false;
1685 }
1686 const sp<AudioPatch> patch = mAudioPatches.valueAt(index);
1687 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1688 if (msdModule == nullptr) {
1689 return false;
1690 }
1691 const struct audio_port_config *sink = &patch->mPatch.sinks[0];
1692 if (getMsdAudioOutDevices().contains(mAvailableOutputDevices.getDeviceFromId(sink->id))) {
1693 return true;
1694 }
1695 index = getMsdOutputPatches().indexOfKey(handle);
1696 if (index < 0) {
1697 return false;
1698 }
1699 return true;
1700}
1701
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001702status_t AudioPolicyManager::getMsdProfiles(bool hwAvSync,
1703 const InputProfileCollection &inputProfiles,
1704 const OutputProfileCollection &outputProfiles,
1705 const sp<DeviceDescriptor> &sourceDevice,
1706 const sp<DeviceDescriptor> &sinkDevice,
1707 AudioProfileVector& sourceProfiles,
1708 AudioProfileVector& sinkProfiles) const {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001709 if (inputProfiles.isEmpty()) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001710 ALOGE("%s() no input profiles for source module", __func__);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001711 return NO_INIT;
1712 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001713 if (outputProfiles.isEmpty()) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001714 ALOGE("%s() no output profiles for sink module", __func__);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001715 return NO_INIT;
1716 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001717 for (const auto &inProfile : inputProfiles) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001718 if (hwAvSync == ((inProfile->getFlags() & AUDIO_INPUT_FLAG_HW_AV_SYNC) != 0) &&
1719 inProfile->supportsDevice(sourceDevice)) {
1720 appendAudioProfiles(sourceProfiles, inProfile->getAudioProfiles());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001721 }
1722 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001723 for (const auto &outProfile : outputProfiles) {
Michael Chan6fb34492020-12-08 15:44:49 +11001724 if (hwAvSync == ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) &&
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001725 outProfile->supportsDevice(sinkDevice)) {
1726 appendAudioProfiles(sinkProfiles, outProfile->getAudioProfiles());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001727 }
1728 }
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001729 return NO_ERROR;
1730}
1731
1732status_t AudioPolicyManager::getBestMsdConfig(bool hwAvSync,
1733 const AudioProfileVector &sourceProfiles, const AudioProfileVector &sinkProfiles,
1734 audio_port_config *sourceConfig, audio_port_config *sinkConfig) const
1735{
Dean Wheatley16809da2022-12-09 14:55:46 +11001736 // Compressed formats for MSD module, ordered from most preferred to least preferred.
1737 static const std::vector<audio_format_t> formatsOrder = {{
1738 AUDIO_FORMAT_IEC60958, AUDIO_FORMAT_MAT_2_1, AUDIO_FORMAT_MAT_2_0, AUDIO_FORMAT_E_AC3,
1739 AUDIO_FORMAT_AC3, AUDIO_FORMAT_PCM_16_BIT }};
1740 static const std::vector<audio_channel_mask_t> channelMasksOrder = [](){
1741 // Channel position masks for MSD module, 3D > 2D > 1D ordering (most preferred to least
1742 // preferred).
1743 std::vector<audio_channel_mask_t> masks = {{
1744 AUDIO_CHANNEL_OUT_3POINT1POINT2, AUDIO_CHANNEL_OUT_3POINT0POINT2,
1745 AUDIO_CHANNEL_OUT_2POINT1POINT2, AUDIO_CHANNEL_OUT_2POINT0POINT2,
1746 AUDIO_CHANNEL_OUT_5POINT1, AUDIO_CHANNEL_OUT_STEREO }};
1747 // insert index masks (higher counts most preferred) as preferred over position masks
1748 for (int i = 1; i <= AUDIO_CHANNEL_COUNT_MAX; i++) {
1749 masks.insert(
1750 masks.begin(), audio_channel_mask_for_index_assignment_from_count(i));
1751 }
1752 return masks;
1753 }();
1754
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001755 struct audio_config_base bestSinkConfig;
Dean Wheatley16809da2022-12-09 14:55:46 +11001756 status_t result = findBestMatchingOutputConfig(sourceProfiles, sinkProfiles, formatsOrder,
1757 channelMasksOrder, true /*preferHigherSamplingRates*/, bestSinkConfig);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001758 if (result != NO_ERROR) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001759 ALOGD("%s() no matching config found for sink, hwAvSync: %d",
1760 __func__, hwAvSync);
Greg Kaiser83289652018-07-30 06:13:57 -07001761 return result;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001762 }
1763 sinkConfig->sample_rate = bestSinkConfig.sample_rate;
1764 sinkConfig->channel_mask = bestSinkConfig.channel_mask;
1765 sinkConfig->format = bestSinkConfig.format;
1766 // For encoded streams force direct flag to prevent downstream mixing.
1767 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1768 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_DIRECT);
Dean Wheatley5c9f0832019-11-21 13:39:31 +11001769 if (audio_is_iec61937_compatible(sinkConfig->format)) {
1770 // For formats compatible with IEC61937 encapsulation, assume that
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001771 // the input is IEC61937 framed (for proportional buffer sizing).
Dean Wheatley5c9f0832019-11-21 13:39:31 +11001772 // Add the AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO flag so downstream HAL can distinguish between
1773 // raw and IEC61937 framed streams.
1774 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1775 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO);
1776 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001777 sourceConfig->sample_rate = bestSinkConfig.sample_rate;
1778 // Specify exact channel mask to prevent guessing by bit count in PatchPanel.
Dean Wheatley16809da2022-12-09 14:55:46 +11001779 sourceConfig->channel_mask =
1780 audio_channel_mask_get_representation(bestSinkConfig.channel_mask)
1781 == AUDIO_CHANNEL_REPRESENTATION_INDEX ?
1782 bestSinkConfig.channel_mask : audio_channel_mask_out_to_in(bestSinkConfig.channel_mask);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001783 sourceConfig->format = bestSinkConfig.format;
1784 // Copy input stream directly without any processing (e.g. resampling).
1785 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1786 sourceConfig->flags.input | AUDIO_INPUT_FLAG_DIRECT);
1787 if (hwAvSync) {
1788 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1789 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
1790 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1791 sourceConfig->flags.input | AUDIO_INPUT_FLAG_HW_AV_SYNC);
1792 }
1793 const unsigned int config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE |
1794 AUDIO_PORT_CONFIG_CHANNEL_MASK | AUDIO_PORT_CONFIG_FORMAT | AUDIO_PORT_CONFIG_FLAGS;
1795 sinkConfig->config_mask |= config_mask;
1796 sourceConfig->config_mask |= config_mask;
1797 return NO_ERROR;
1798}
1799
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001800PatchBuilder AudioPolicyManager::buildMsdPatch(bool msdIsSource,
1801 const sp<DeviceDescriptor> &device) const
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001802{
1803 PatchBuilder patchBuilder;
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001804 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1805 ALOG_ASSERT(msdModule != nullptr, "MSD module not available");
1806 sp<HwModule> deviceModule = mHwModules.getModuleForDevice(device, AUDIO_FORMAT_DEFAULT);
1807 if (deviceModule == nullptr) {
1808 ALOGE("%s() unable to get module for %s", __func__, device->toString().c_str());
1809 return patchBuilder;
1810 }
1811 const InputProfileCollection inputProfiles = msdIsSource ?
1812 msdModule->getInputProfiles() : deviceModule->getInputProfiles();
1813 const OutputProfileCollection outputProfiles = msdIsSource ?
1814 deviceModule->getOutputProfiles() : msdModule->getOutputProfiles();
1815
1816 const sp<DeviceDescriptor> sourceDevice = msdIsSource ? getMsdAudioInDevice() : device;
1817 const sp<DeviceDescriptor> sinkDevice = msdIsSource ?
1818 device : getMsdAudioOutDevices().itemAt(0);
1819 patchBuilder.addSource(sourceDevice).addSink(sinkDevice);
1820
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001821 audio_port_config sourceConfig = patchBuilder.patch()->sources[0];
1822 audio_port_config sinkConfig = patchBuilder.patch()->sinks[0];
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001823 AudioProfileVector sourceProfiles;
1824 AudioProfileVector sinkProfiles;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001825 // TODO: Figure out whether MSD module has HW_AV_SYNC flag set in the AP config file.
1826 // For now, we just forcefully try with HwAvSync first.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001827 for (auto hwAvSync : { true, false }) {
1828 if (getMsdProfiles(hwAvSync, inputProfiles, outputProfiles, sourceDevice, sinkDevice,
1829 sourceProfiles, sinkProfiles) != NO_ERROR) {
1830 continue;
1831 }
1832 if (getBestMsdConfig(hwAvSync, sourceProfiles, sinkProfiles, &sourceConfig,
1833 &sinkConfig) == NO_ERROR) {
1834 // Found a matching config. Re-create PatchBuilder with this config.
1835 return (PatchBuilder()).addSource(sourceConfig).addSink(sinkConfig);
1836 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001837 }
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001838 ALOGV("%s() no matching config found. Fall through to default PCM patch"
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001839 " supporting PCM format conversion.", __func__);
1840 return patchBuilder;
1841}
1842
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001843status_t AudioPolicyManager::setMsdOutputPatches(const DeviceVector *outputDevices) {
Michael Chan6fb34492020-12-08 15:44:49 +11001844 DeviceVector devices;
1845 if (outputDevices != nullptr && outputDevices->size() > 0) {
1846 devices.add(*outputDevices);
1847 } else {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001848 // Use media strategy for unspecified output device. This should only
1849 // occur on checkForDeviceAndOutputChanges(). Device connection events may
1850 // therefore invalidate explicit routing requests.
Michael Chan6fb34492020-12-08 15:44:49 +11001851 devices = mEngine->getOutputDevicesForAttributes(
François Gaffiec005e562018-11-06 15:04:49 +01001852 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
Michael Chan6fb34492020-12-08 15:44:49 +11001853 LOG_ALWAYS_FATAL_IF(devices.isEmpty(), "no output device to set MSD patch");
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001854 }
Michael Chan6fb34492020-12-08 15:44:49 +11001855 std::vector<PatchBuilder> patchesToCreate;
1856 for (auto i = 0u; i < devices.size(); ++i) {
1857 ALOGV("%s() for device %s", __func__, devices[i]->toString().c_str());
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001858 patchesToCreate.push_back(buildMsdPatch(true /*msdIsSource*/, devices[i]));
Michael Chan6fb34492020-12-08 15:44:49 +11001859 }
1860 // Retain only the MSD patches associated with outputDevices request.
1861 // Tear down the others, and create new ones as needed.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001862 AudioPatchCollection patchesToRemove = getMsdOutputPatches();
Michael Chan6fb34492020-12-08 15:44:49 +11001863 for (auto it = patchesToCreate.begin(); it != patchesToCreate.end(); ) {
1864 auto retainedPatch = false;
1865 for (auto i = 0u; i < patchesToRemove.size(); ++i) {
1866 if (audio_patches_are_equal(it->patch(), &patchesToRemove[i]->mPatch)) {
1867 patchesToRemove.removeItemsAt(i);
1868 retainedPatch = true;
1869 break;
1870 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001871 }
Michael Chan6fb34492020-12-08 15:44:49 +11001872 if (retainedPatch) {
1873 it = patchesToCreate.erase(it);
1874 continue;
1875 }
1876 ++it;
1877 }
1878 if (patchesToCreate.size() == 0 && patchesToRemove.size() == 0) {
1879 return NO_ERROR;
1880 }
1881 for (auto i = 0u; i < patchesToRemove.size(); ++i) {
1882 auto &currentPatch = patchesToRemove.valueAt(i);
François Gaffieafd4cea2019-11-18 15:50:22 +01001883 releaseAudioPatch(currentPatch->getHandle(), mUidCached);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001884 }
Michael Chan6fb34492020-12-08 15:44:49 +11001885 status_t status = NO_ERROR;
1886 for (const auto &p : patchesToCreate) {
1887 auto currStatus = installPatch(__func__, -1 /*index*/, nullptr /*patchHandle*/,
1888 p.patch(), 0 /*delayMs*/, mUidCached, nullptr /*patchDescPtr*/);
1889 char message[256];
1890 snprintf(message, sizeof(message), "%s() %s: creating MSD patch from device:IN_BUS to "
1891 "device:%#x (format:%#x channels:%#x samplerate:%d)", __func__,
1892 currStatus == NO_ERROR ? "Success" : "Error",
1893 p.patch()->sinks[0].ext.device.type, p.patch()->sources[0].format,
1894 p.patch()->sources[0].channel_mask, p.patch()->sources[0].sample_rate);
1895 if (currStatus == NO_ERROR) {
1896 ALOGD("%s", message);
1897 } else {
1898 ALOGE("%s", message);
1899 if (status == NO_ERROR) {
1900 status = currStatus;
1901 }
1902 }
1903 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001904 return status;
1905}
1906
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001907void AudioPolicyManager::releaseMsdOutputPatches(const DeviceVector& devices) {
1908 AudioPatchCollection msdPatches = getMsdOutputPatches();
Michael Chan6fb34492020-12-08 15:44:49 +11001909 for (size_t i = 0; i < msdPatches.size(); i++) {
1910 const auto& patch = msdPatches[i];
1911 for (size_t j = 0; j < patch->mPatch.num_sinks; ++j) {
1912 const struct audio_port_config *sink = &patch->mPatch.sinks[j];
1913 if (sink->type == AUDIO_PORT_TYPE_DEVICE && devices.getDevice(sink->ext.device.type,
1914 String8(sink->ext.device.address), AUDIO_FORMAT_DEFAULT) != nullptr) {
1915 releaseAudioPatch(patch->getHandle(), mUidCached);
1916 break;
1917 }
1918 }
1919 }
1920}
1921
Dorin Drimus94d94412022-02-02 09:05:02 +01001922bool AudioPolicyManager::msdHasPatchesToAllDevices(const AudioDeviceTypeAddrVector& devices) {
Mikhail Naganovb0fbc1b2023-04-28 13:06:32 -07001923 DeviceVector devicesToCheck =
1924 mConfig->getOutputDevices().getDevicesFromDeviceTypeAddrVec(devices);
Dorin Drimus94d94412022-02-02 09:05:02 +01001925 AudioPatchCollection msdPatches = getMsdOutputPatches();
1926 for (size_t i = 0; i < msdPatches.size(); i++) {
1927 const auto& patch = msdPatches[i];
1928 for (size_t j = 0; j < patch->mPatch.num_sinks; ++j) {
1929 const struct audio_port_config *sink = &patch->mPatch.sinks[j];
1930 if (sink->type == AUDIO_PORT_TYPE_DEVICE) {
1931 const auto& foundDevice = devicesToCheck.getDevice(
1932 sink->ext.device.type, String8(sink->ext.device.address), AUDIO_FORMAT_DEFAULT);
1933 if (foundDevice != nullptr) {
1934 devicesToCheck.remove(foundDevice);
1935 if (devicesToCheck.isEmpty()) {
1936 return true;
1937 }
1938 }
1939 }
1940 }
1941 }
1942 return false;
1943}
1944
Eric Laurente0720872014-03-11 09:30:41 -07001945audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
jiabinebb6af42020-06-09 17:31:17 -07001946 audio_output_flags_t flags,
1947 audio_format_t format,
1948 audio_channel_mask_t channelMask,
1949 uint32_t samplingRate,
1950 audio_session_t sessionId)
Eric Laurente552edb2014-03-10 17:42:56 -07001951{
Eric Laurent16c66dd2019-05-01 17:54:10 -07001952 LOG_ALWAYS_FATAL_IF(!(format == AUDIO_FORMAT_INVALID || audio_is_linear_pcm(format)),
1953 "%s called with format %#x", __func__, format);
1954
jiabinebb6af42020-06-09 17:31:17 -07001955 // Return the output that haptic-generating attached to when 1) session id is specified,
1956 // 2) haptic-generating effect exists for given session id and 3) the output that
1957 // haptic-generating effect attached to is in given outputs.
1958 if (sessionId != AUDIO_SESSION_NONE) {
1959 audio_io_handle_t hapticGeneratingOutput = mEffects.getIoForSession(
1960 sessionId, FX_IID_HAPTICGENERATOR);
1961 if (outputs.indexOf(hapticGeneratingOutput) >= 0) {
1962 return hapticGeneratingOutput;
1963 }
1964 }
1965
Eric Laurent16c66dd2019-05-01 17:54:10 -07001966 // Flags disqualifying an output: the match must happen before calling selectOutput()
1967 static const audio_output_flags_t kExcludedFlags = (audio_output_flags_t)
1968 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ | AUDIO_OUTPUT_FLAG_DIRECT);
1969
1970 // Flags expressing a functional request: must be honored in priority over
1971 // other criteria
1972 static const audio_output_flags_t kFunctionalFlags = (audio_output_flags_t)
1973 (AUDIO_OUTPUT_FLAG_VOIP_RX | AUDIO_OUTPUT_FLAG_INCALL_MUSIC |
Eric Laurente28c66d2022-01-21 13:40:41 +01001974 AUDIO_OUTPUT_FLAG_TTS | AUDIO_OUTPUT_FLAG_DIRECT_PCM | AUDIO_OUTPUT_FLAG_ULTRASOUND |
1975 AUDIO_OUTPUT_FLAG_SPATIALIZER);
Eric Laurent16c66dd2019-05-01 17:54:10 -07001976 // Flags expressing a performance request: have lower priority than serving
1977 // requested sampling rate or channel mask
1978 static const audio_output_flags_t kPerformanceFlags = (audio_output_flags_t)
1979 (AUDIO_OUTPUT_FLAG_FAST | AUDIO_OUTPUT_FLAG_DEEP_BUFFER |
1980 AUDIO_OUTPUT_FLAG_RAW | AUDIO_OUTPUT_FLAG_SYNC);
1981
1982 const audio_output_flags_t functionalFlags =
1983 (audio_output_flags_t)(flags & kFunctionalFlags);
1984 const audio_output_flags_t performanceFlags =
1985 (audio_output_flags_t)(flags & kPerformanceFlags);
1986
1987 audio_io_handle_t bestOutput = (outputs.size() == 0) ? AUDIO_IO_HANDLE_NONE : outputs[0];
1988
Eric Laurente552edb2014-03-10 17:42:56 -07001989 // select one output among several that provide a path to a particular device or set of
François Gaffie11d30102018-11-02 16:09:09 +01001990 // devices (the list was previously build by getOutputsForDevices()).
Eric Laurente552edb2014-03-10 17:42:56 -07001991 // The priority is as follows:
jiabin40573322018-11-08 12:08:02 -08001992 // 1: the output supporting haptic playback when requesting haptic playback
Eric Laurent16c66dd2019-05-01 17:54:10 -07001993 // 2: the output with the highest number of requested functional flags
Carter Hsu199f1892021-10-15 15:47:29 +08001994 // with tiebreak preferring the minimum number of extra functional flags
1995 // (see b/200293124, the incorrect selection of AUDIO_OUTPUT_FLAG_VOIP_RX).
Eric Laurent16c66dd2019-05-01 17:54:10 -07001996 // 3: the output supporting the exact channel mask
1997 // 4: the output with a higher channel count than requested
jiabind1785f72022-06-03 20:48:18 +00001998 // 5: the output with the highest sampling rate if the requested sample rate is
1999 // greater than default sampling rate
Eric Laurent16c66dd2019-05-01 17:54:10 -07002000 // 6: the output with the highest number of requested performance flags
2001 // 7: the output with the bit depth the closest to the requested one
2002 // 8: the primary output
2003 // 9: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07002004
Eric Laurent16c66dd2019-05-01 17:54:10 -07002005 // matching criteria values in priority order for best matching output so far
2006 std::vector<uint32_t> bestMatchCriteria(8, 0);
Eric Laurente552edb2014-03-10 17:42:56 -07002007
Eric Laurent16c66dd2019-05-01 17:54:10 -07002008 const uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
2009 const uint32_t hapticChannelCount = audio_channel_count_from_out_mask(
2010 channelMask & AUDIO_CHANNEL_HAPTIC_ALL);
Eric Laurente78b6762018-12-19 16:29:01 -08002011
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002012 for (audio_io_handle_t output : outputs) {
2013 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent16c66dd2019-05-01 17:54:10 -07002014 // matching criteria values in priority order for current output
2015 std::vector<uint32_t> currentMatchCriteria(8, 0);
jiabin40573322018-11-08 12:08:02 -08002016
Eric Laurent16c66dd2019-05-01 17:54:10 -07002017 if (outputDesc->isDuplicated()) {
2018 continue;
2019 }
2020 if ((kExcludedFlags & outputDesc->mFlags) != 0) {
2021 continue;
2022 }
Eric Laurent8838a382014-09-08 16:44:28 -07002023
Eric Laurent16c66dd2019-05-01 17:54:10 -07002024 // If haptic channel is specified, use the haptic output if present.
2025 // When using haptic output, same audio format and sample rate are required.
2026 const uint32_t outputHapticChannelCount = audio_channel_count_from_out_mask(
jiabin5740f082019-08-19 15:08:30 -07002027 outputDesc->getChannelMask() & AUDIO_CHANNEL_HAPTIC_ALL);
Eric Laurent16c66dd2019-05-01 17:54:10 -07002028 if ((hapticChannelCount == 0) != (outputHapticChannelCount == 0)) {
2029 continue;
2030 }
2031 if (outputHapticChannelCount >= hapticChannelCount
jiabin5740f082019-08-19 15:08:30 -07002032 && format == outputDesc->getFormat()
2033 && samplingRate == outputDesc->getSamplingRate()) {
Eric Laurent16c66dd2019-05-01 17:54:10 -07002034 currentMatchCriteria[0] = outputHapticChannelCount;
2035 }
2036
2037 // functional flags match
Carter Hsu199f1892021-10-15 15:47:29 +08002038 const int matchingFunctionalFlags =
2039 __builtin_popcount(outputDesc->mFlags & functionalFlags);
2040 const int totalFunctionalFlags =
2041 __builtin_popcount(outputDesc->mFlags & kFunctionalFlags);
2042 // Prefer matching functional flags, but subtract unnecessary functional flags.
2043 currentMatchCriteria[1] = 100 * (matchingFunctionalFlags + 1) - totalFunctionalFlags;
Eric Laurent16c66dd2019-05-01 17:54:10 -07002044
2045 // channel mask and channel count match
jiabin5740f082019-08-19 15:08:30 -07002046 uint32_t outputChannelCount = audio_channel_count_from_out_mask(
2047 outputDesc->getChannelMask());
Eric Laurent16c66dd2019-05-01 17:54:10 -07002048 if (channelMask != AUDIO_CHANNEL_NONE && channelCount > 2 &&
2049 channelCount <= outputChannelCount) {
2050 if ((audio_channel_mask_get_representation(channelMask) ==
jiabin5740f082019-08-19 15:08:30 -07002051 audio_channel_mask_get_representation(outputDesc->getChannelMask())) &&
2052 ((channelMask & outputDesc->getChannelMask()) == channelMask)) {
Eric Laurent16c66dd2019-05-01 17:54:10 -07002053 currentMatchCriteria[2] = outputChannelCount;
Eric Laurente552edb2014-03-10 17:42:56 -07002054 }
Eric Laurent16c66dd2019-05-01 17:54:10 -07002055 currentMatchCriteria[3] = outputChannelCount;
2056 }
2057
2058 // sampling rate match
jiabind1785f72022-06-03 20:48:18 +00002059 if (samplingRate > SAMPLE_RATE_HZ_DEFAULT) {
jiabin5740f082019-08-19 15:08:30 -07002060 currentMatchCriteria[4] = outputDesc->getSamplingRate();
Eric Laurent16c66dd2019-05-01 17:54:10 -07002061 }
2062
2063 // performance flags match
2064 currentMatchCriteria[5] = popcount(outputDesc->mFlags & performanceFlags);
2065
2066 // format match
2067 if (format != AUDIO_FORMAT_INVALID) {
2068 currentMatchCriteria[6] =
jiabin4ef93452019-09-10 14:29:54 -07002069 PolicyAudioPort::kFormatDistanceMax -
2070 PolicyAudioPort::formatDistance(format, outputDesc->getFormat());
Eric Laurent16c66dd2019-05-01 17:54:10 -07002071 }
2072
2073 // primary output match
2074 currentMatchCriteria[7] = outputDesc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY;
2075
2076 // compare match criteria by priority then value
2077 if (std::lexicographical_compare(bestMatchCriteria.begin(), bestMatchCriteria.end(),
2078 currentMatchCriteria.begin(), currentMatchCriteria.end())) {
2079 bestMatchCriteria = currentMatchCriteria;
2080 bestOutput = output;
2081
2082 std::stringstream result;
2083 std::copy(bestMatchCriteria.begin(), bestMatchCriteria.end(),
2084 std::ostream_iterator<int>(result, " "));
2085 ALOGV("%s new bestOutput %d criteria %s",
2086 __func__, bestOutput, result.str().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07002087 }
2088 }
2089
Eric Laurent16c66dd2019-05-01 17:54:10 -07002090 return bestOutput;
Eric Laurente552edb2014-03-10 17:42:56 -07002091}
2092
Eric Laurent8fc147b2018-07-22 19:13:55 -07002093status_t AudioPolicyManager::startOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002094{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002095 ALOGV("%s portId %d", __FUNCTION__, portId);
2096
2097 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2098 if (outputDesc == 0) {
2099 ALOGW("startOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002100 return BAD_VALUE;
2101 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002102 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002103
Eric Laurent8fc147b2018-07-22 19:13:55 -07002104 ALOGV("startOutput() output %d, stream %d, session %d",
Eric Laurent97ac8712018-07-27 18:59:02 -07002105 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurentc75307b2015-03-17 15:29:32 -07002106
Eric Laurent733ce942017-12-07 12:18:25 -08002107 status_t status = outputDesc->start();
2108 if (status != NO_ERROR) {
2109 return status;
Eric Laurent3974e3b2017-12-07 17:58:43 -08002110 }
2111
Eric Laurent97ac8712018-07-27 18:59:02 -07002112 uint32_t delayMs;
2113 status = startSource(outputDesc, client, &delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07002114
2115 if (status != NO_ERROR) {
Eric Laurent733ce942017-12-07 12:18:25 -08002116 outputDesc->stop();
jiabin3ff8d7d2022-12-13 06:27:44 +00002117 if (status == DEAD_OBJECT) {
2118 sp<SwAudioOutputDescriptor> desc =
2119 reopenOutput(outputDesc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
2120 if (desc == nullptr) {
2121 // This is not common, it may indicate something wrong with the HAL.
2122 ALOGE("%s unable to open output with default config", __func__);
2123 return status;
2124 }
2125 desc->mUsePreferredMixerAttributes = true;
2126 }
Eric Laurent8c7e6da2015-04-21 17:37:00 -07002127 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07002128 }
jiabina84c3d32022-12-02 18:59:55 +00002129
2130 // If the client is the first one active on preferred mixer parameters, reopen the output
2131 // if the current mixer parameters doesn't match the preferred one.
2132 if (outputDesc->devices().size() == 1) {
2133 sp<PreferredMixerAttributesInfo> info = getPreferredMixerAttributesInfo(
2134 outputDesc->devices()[0]->getId(), client->strategy());
2135 if (info != nullptr && info->getUid() == client->uid()) {
2136 if (info->getActiveClientCount() == 0 && !outputDesc->isConfigurationMatched(
2137 info->getConfigBase(), info->getFlags())) {
2138 stopSource(outputDesc, client);
2139 outputDesc->stop();
2140 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
2141 config.channel_mask = info->getConfigBase().channel_mask;
2142 config.sample_rate = info->getConfigBase().sample_rate;
2143 config.format = info->getConfigBase().format;
jiabin3ff8d7d2022-12-13 06:27:44 +00002144 sp<SwAudioOutputDescriptor> desc =
2145 reopenOutput(outputDesc, &config, info->getFlags(), __func__);
2146 if (desc == nullptr) {
2147 return BAD_VALUE;
jiabina84c3d32022-12-02 18:59:55 +00002148 }
jiabin3ff8d7d2022-12-13 06:27:44 +00002149 desc->mUsePreferredMixerAttributes = true;
jiabina84c3d32022-12-02 18:59:55 +00002150 // Intentionally return error to let the client side resending request for
2151 // creating and starting.
2152 return DEAD_OBJECT;
2153 }
2154 info->increaseActiveClient();
2155 }
2156 }
2157
Jean-Michel Trivi32b7a102023-02-07 20:49:04 +00002158 if (client->hasPreferredDevice()) {
2159 // playback activity with preferred device impacts routing occurred, inform upper layers
2160 mpClientInterface->onRoutingUpdated();
2161 }
Eric Laurentc75307b2015-03-17 15:29:32 -07002162 if (delayMs != 0) {
2163 usleep(delayMs * 1000);
2164 }
2165
2166 return status;
2167}
2168
Eric Laurent96d1dda2022-03-14 17:14:19 +01002169bool AudioPolicyManager::isLeUnicastActive() const {
2170 if (isInCall()) {
2171 return true;
2172 }
2173 return isAnyDeviceTypeActive(getAudioDeviceOutLeAudioUnicastSet());
2174}
2175
2176bool AudioPolicyManager::isAnyDeviceTypeActive(const DeviceTypeSet& deviceTypes) const {
2177 if (mAvailableOutputDevices.getDevicesFromTypes(deviceTypes).isEmpty()) {
2178 return false;
2179 }
2180 bool active = mOutputs.isAnyDeviceTypeActive(deviceTypes);
2181 ALOGV("%s active %d", __func__, active);
2182 return active;
2183}
2184
Eric Laurent97ac8712018-07-27 18:59:02 -07002185status_t AudioPolicyManager::startSource(const sp<SwAudioOutputDescriptor>& outputDesc,
2186 const sp<TrackClientDescriptor>& client,
2187 uint32_t *delayMs)
Eric Laurentc75307b2015-03-17 15:29:32 -07002188{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002189 // cannot start playback of STREAM_TTS if any other output is being used
2190 uint32_t beaconMuteLatency = 0;
Eric Laurentc75307b2015-03-17 15:29:32 -07002191
2192 *delayMs = 0;
Eric Laurent97ac8712018-07-27 18:59:02 -07002193 audio_stream_type_t stream = client->stream();
François Gaffie1c878552018-11-22 16:53:21 +01002194 auto clientVolSrc = client->volumeSource();
François Gaffiec005e562018-11-06 15:04:49 +01002195 auto clientStrategy = client->strategy();
2196 auto clientAttr = client->attributes();
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002197 if (stream == AUDIO_STREAM_TTS) {
2198 ALOGV("\t found BEACON stream");
François Gaffie1c878552018-11-22 16:53:21 +01002199 if (!mTtsOutputAvailable && mOutputs.isAnyOutputActive(
Francois Gaffie4404ddb2021-02-04 17:03:38 +01002200 toVolumeSource(AUDIO_STREAM_TTS, false) /*sourceToIgnore*/)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002201 return INVALID_OPERATION;
2202 } else {
2203 beaconMuteLatency = handleEventForBeacon(STARTING_BEACON);
2204 }
2205 } else {
2206 // some playback other than beacon starts
2207 beaconMuteLatency = handleEventForBeacon(STARTING_OUTPUT);
2208 }
2209
Eric Laurent77305a62016-07-25 16:39:22 -07002210 // force device change if the output is inactive and no audio patch is already present.
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002211 // check active before incrementing usage count
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02002212 bool force = !outputDesc->isActive() && !outputDesc->isRouted();
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002213
François Gaffie11d30102018-11-02 16:09:09 +01002214 DeviceVector devices;
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002215 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
Eric Laurent97ac8712018-07-27 18:59:02 -07002216 const char *address = NULL;
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002217 if (policyMix != nullptr) {
François Gaffie11d30102018-11-02 16:09:09 +01002218 audio_devices_t newDeviceType;
Tomasz Wasilczyk8f36f6e2023-08-15 20:59:35 +00002219 address = policyMix->mDeviceAddress.c_str();
Kevin Rocard153f92d2018-12-18 18:33:28 -08002220 if ((policyMix->mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie11d30102018-11-02 16:09:09 +01002221 newDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Kevin Rocard153f92d2018-12-18 18:33:28 -08002222 } else {
2223 newDeviceType = policyMix->mDeviceType;
Eric Laurent97ac8712018-07-27 18:59:02 -07002224 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08002225 sp device = mAvailableOutputDevices.getDevice(newDeviceType, String8(address),
2226 AUDIO_FORMAT_DEFAULT);
2227 ALOG_ASSERT(device, "%s: no device found t=%u, a=%s", __func__, newDeviceType, address);
2228 devices.add(device);
Eric Laurent97ac8712018-07-27 18:59:02 -07002229 }
2230
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002231 // requiresMuteCheck is false when we can bypass mute strategy.
2232 // It covers a common case when there is no materially active audio
2233 // and muting would result in unnecessary delay and dropped audio.
2234 const uint32_t outputLatencyMs = outputDesc->latency();
2235 bool requiresMuteCheck = outputDesc->isActive(outputLatencyMs * 2); // account for drain
Eric Laurent96d1dda2022-03-14 17:14:19 +01002236 bool wasLeUnicastActive = isLeUnicastActive();
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002237
Eric Laurente552edb2014-03-10 17:42:56 -07002238 // increment usage count for this stream on the requested output:
2239 // NOTE that the usage count is the same for duplicated output and hardware output which is
2240 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
Eric Laurent592dd7b2018-08-05 18:58:48 -07002241 outputDesc->setClientActive(client, true);
Eric Laurent97ac8712018-07-27 18:59:02 -07002242
2243 if (client->hasPreferredDevice(true)) {
Eric Laurent72af8012023-03-15 17:36:22 +01002244 if (outputDesc->sameExclusivePreferredDevicesCount() > 0) {
François Gaffief96e5432019-04-09 17:13:56 +02002245 // Preferred device may be exclusive, use only if no other active clients on this output
2246 devices = DeviceVector(
2247 mAvailableOutputDevices.getDeviceFromId(client->preferredDeviceId()));
2248 } else {
2249 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
2250 }
François Gaffie11d30102018-11-02 16:09:09 +01002251 if (devices != outputDesc->devices()) {
François Gaffiec005e562018-11-06 15:04:49 +01002252 checkStrategyRoute(clientStrategy, outputDesc->mIoHandle);
Eric Laurent97ac8712018-07-27 18:59:02 -07002253 }
2254 }
Eric Laurente552edb2014-03-10 17:42:56 -07002255
François Gaffiec005e562018-11-06 15:04:49 +01002256 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07002257 selectOutputForMusicEffects();
2258 }
2259
François Gaffie1c878552018-11-22 16:53:21 +01002260 if (outputDesc->getActivityCount(clientVolSrc) == 1 || !devices.isEmpty()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08002261 // starting an output being rerouted?
François Gaffie11d30102018-11-02 16:09:09 +01002262 if (devices.isEmpty()) {
2263 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Eric Laurent275e8e92014-11-30 15:14:47 -08002264 }
François Gaffiec005e562018-11-06 15:04:49 +01002265 bool shouldWait =
2266 (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM)) ||
2267 followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_NOTIFICATION)) ||
2268 (beaconMuteLatency > 0));
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002269 uint32_t waitMs = beaconMuteLatency;
Eric Laurente552edb2014-03-10 17:42:56 -07002270 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01002271 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07002272 if (desc != outputDesc) {
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002273 // An output has a shared device if
2274 // - managed by the same hw module
2275 // - supports the currently selected device
2276 const bool sharedDevice = outputDesc->sharesHwModuleWith(desc)
François Gaffie11d30102018-11-02 16:09:09 +01002277 && (!desc->filterSupportedDevices(devices).isEmpty());
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002278
Eric Laurent77305a62016-07-25 16:39:22 -07002279 // force a device change if any other output is:
2280 // - managed by the same hw module
Jean-Michel Trivi4a5b4812018-02-08 17:22:32 +00002281 // - supports currently selected device
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002282 // - has a current device selection that differs from selected device.
Eric Laurent77305a62016-07-25 16:39:22 -07002283 // - has an active audio patch
Eric Laurente552edb2014-03-10 17:42:56 -07002284 // In this case, the audio HAL must receive the new device selection so that it can
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002285 // change the device currently selected by the other output.
2286 if (sharedDevice &&
François Gaffie11d30102018-11-02 16:09:09 +01002287 desc->devices() != devices &&
Eric Laurent77305a62016-07-25 16:39:22 -07002288 desc->getPatchHandle() != AUDIO_PATCH_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07002289 force = true;
2290 }
2291 // wait for audio on other active outputs to be presented when starting
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002292 // a notification so that audio focus effect can propagate, or that a mute/unmute
2293 // event occurred for beacon
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002294 const uint32_t latencyMs = desc->latency();
2295 const bool isActive = desc->isActive(latencyMs * 2); // account for drain
2296
2297 if (shouldWait && isActive && (waitMs < latencyMs)) {
2298 waitMs = latencyMs;
Eric Laurente552edb2014-03-10 17:42:56 -07002299 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002300
2301 // Require mute check if another output is on a shared device
2302 // and currently active to have proper drain and avoid pops.
2303 // Note restoring AudioTracks onto this output needs to invoke
2304 // a volume ramp if there is no mute.
2305 requiresMuteCheck |= sharedDevice && isActive;
Eric Laurente552edb2014-03-10 17:42:56 -07002306 }
2307 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002308
jiabin3ff8d7d2022-12-13 06:27:44 +00002309 if (outputDesc->mUsePreferredMixerAttributes && devices != outputDesc->devices()) {
2310 // If the output is open with preferred mixer attributes, but the routed device is
2311 // changed when calling this function, returning DEAD_OBJECT to indicate routing
2312 // changed.
2313 return DEAD_OBJECT;
2314 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002315 const uint32_t muteWaitMs =
jiabin3ff8d7d2022-12-13 06:27:44 +00002316 setOutputDevices(outputDesc, devices, force, 0, nullptr, requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07002317
Eric Laurente552edb2014-03-10 17:42:56 -07002318 // apply volume rules for current stream and device if necessary
François Gaffieaaac0fd2018-11-22 17:56:39 +01002319 auto &curves = getVolumeCurves(client->attributes());
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00002320 if (NO_ERROR != checkAndSetVolume(curves, client->volumeSource(),
François Gaffieaaac0fd2018-11-22 17:56:39 +01002321 curves.getVolumeIndex(outputDesc->devices().types()),
Eric Laurentc75307b2015-03-17 15:29:32 -07002322 outputDesc,
Francois Gaffied11442b2020-04-27 11:51:09 +02002323 outputDesc->devices().types(), 0 /*delay*/,
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00002324 outputDesc->useHwGain() /*force*/)) {
2325 // request AudioService to reinitialize the volume curves asynchronously
2326 ALOGE("checkAndSetVolume failed, requesting volume range init");
2327 mpClientInterface->onVolumeRangeInitRequest();
2328 };
Eric Laurente552edb2014-03-10 17:42:56 -07002329
2330 // update the outputs if starting an output with a stream that can affect notification
2331 // routing
2332 handleNotificationRoutingForStream(stream);
Eric Laurentc722f302014-12-10 11:21:49 -08002333
Eric Laurent2cbe89a2014-12-19 11:49:08 -08002334 // force reevaluating accessibility routing when ringtone or alarm starts
François Gaffiec005e562018-11-06 15:04:49 +01002335 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM))) {
jiabinc44b3462022-12-08 12:52:31 -08002336 invalidateStreams({AUDIO_STREAM_ACCESSIBILITY});
Eric Laurent2cbe89a2014-12-19 11:49:08 -08002337 }
Eric Laurentdc462862016-07-19 12:29:53 -07002338
2339 if (waitMs > muteWaitMs) {
2340 *delayMs = waitMs - muteWaitMs;
2341 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002342
2343 // FIXME: A device change (muteWaitMs > 0) likely introduces a volume change.
2344 // A volume change enacted by APM with 0 delay is not synchronous, as it goes
2345 // via AudioCommandThread to AudioFlinger. Hence it is possible that the volume
2346 // change occurs after the MixerThread starts and causes a stream volume
2347 // glitch.
2348 //
2349 // We do not introduce additional delay here.
Eric Laurente552edb2014-03-10 17:42:56 -07002350 }
Eric Laurentdc462862016-07-19 12:29:53 -07002351
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002352 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
jiabin9a3361e2019-10-01 09:38:30 -07002353 mEngine->getForceUse(
2354 AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
François Gaffiec005e562018-11-06 15:04:49 +01002355 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), true, outputDesc);
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002356 }
2357
Eric Laurent97ac8712018-07-27 18:59:02 -07002358 // Automatically enable the remote submix input when output is started on a re routing mix
2359 // of type MIX_TYPE_RECORDERS
jiabin9a3361e2019-10-01 09:38:30 -07002360 if (isSingleDeviceType(devices.types(), &audio_is_remote_submix_device) &&
2361 policyMix != NULL && policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002362 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2363 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2364 address,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002365 "remote-submix",
2366 AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07002367 }
2368
Eric Laurent96d1dda2022-03-14 17:14:19 +01002369 checkLeBroadcastRoutes(wasLeUnicastActive, outputDesc, *delayMs);
2370
Eric Laurente552edb2014-03-10 17:42:56 -07002371 return NO_ERROR;
2372}
2373
Eric Laurent96d1dda2022-03-14 17:14:19 +01002374void AudioPolicyManager::checkLeBroadcastRoutes(bool wasUnicastActive,
2375 sp<SwAudioOutputDescriptor> ignoredOutput, uint32_t delayMs) {
2376 bool isUnicastActive = isLeUnicastActive();
2377
2378 if (wasUnicastActive != isUnicastActive) {
jiabin3ff8d7d2022-12-13 06:27:44 +00002379 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent96d1dda2022-03-14 17:14:19 +01002380 //reroute all outputs routed to LE broadcast if LE unicast activy changed on any output
2381 for (size_t i = 0; i < mOutputs.size(); i++) {
2382 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
2383 if (desc != ignoredOutput && desc->isActive()
2384 && ((isUnicastActive &&
2385 !desc->devices().
2386 getDevicesFromType(AUDIO_DEVICE_OUT_BLE_BROADCAST).isEmpty())
2387 || (wasUnicastActive &&
2388 !desc->devices().getDevicesFromTypes(
2389 getAudioDeviceOutLeAudioUnicastSet()).isEmpty()))) {
2390 DeviceVector newDevices = getNewOutputDevices(desc, false /*fromCache*/);
2391 bool force = desc->devices() != newDevices;
jiabin3ff8d7d2022-12-13 06:27:44 +00002392 if (desc->mUsePreferredMixerAttributes && force) {
2393 // If the device is using preferred mixer attributes, the output need to reopen
2394 // with default configuration when the new selected devices are different from
2395 // current routing devices.
2396 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices);
2397 continue;
2398 }
Eric Laurent96d1dda2022-03-14 17:14:19 +01002399 setOutputDevices(desc, newDevices, force, delayMs);
2400 // re-apply device specific volume if not done by setOutputDevice()
2401 if (!force) {
2402 applyStreamVolumes(desc, newDevices.types(), delayMs);
2403 }
2404 }
2405 }
jiabin3ff8d7d2022-12-13 06:27:44 +00002406 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent96d1dda2022-03-14 17:14:19 +01002407 }
2408}
2409
Eric Laurent8fc147b2018-07-22 19:13:55 -07002410status_t AudioPolicyManager::stopOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002411{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002412 ALOGV("%s portId %d", __FUNCTION__, portId);
2413
2414 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2415 if (outputDesc == 0) {
2416 ALOGW("stopOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002417 return BAD_VALUE;
2418 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002419 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002420
Jean-Michel Trivi32b7a102023-02-07 20:49:04 +00002421 if (client->hasPreferredDevice(true)) {
2422 // playback activity with preferred device impacts routing occurred, inform upper layers
2423 mpClientInterface->onRoutingUpdated();
2424 }
2425
Eric Laurent97ac8712018-07-27 18:59:02 -07002426 ALOGV("stopOutput() output %d, stream %d, session %d",
2427 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurente552edb2014-03-10 17:42:56 -07002428
Eric Laurent97ac8712018-07-27 18:59:02 -07002429 status_t status = stopSource(outputDesc, client);
Eric Laurent3974e3b2017-12-07 17:58:43 -08002430
Eric Laurent733ce942017-12-07 12:18:25 -08002431 if (status == NO_ERROR ) {
2432 outputDesc->stop();
jiabina84c3d32022-12-02 18:59:55 +00002433 } else {
2434 return status;
2435 }
2436
2437 if (outputDesc->devices().size() == 1) {
2438 sp<PreferredMixerAttributesInfo> info = getPreferredMixerAttributesInfo(
2439 outputDesc->devices()[0]->getId(), client->strategy());
2440 if (info != nullptr && info->getUid() == client->uid()) {
2441 info->decreaseActiveClient();
2442 if (info->getActiveClientCount() == 0) {
2443 reopenOutput(outputDesc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
2444 }
2445 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002446 }
2447 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07002448}
2449
Eric Laurent97ac8712018-07-27 18:59:02 -07002450status_t AudioPolicyManager::stopSource(const sp<SwAudioOutputDescriptor>& outputDesc,
2451 const sp<TrackClientDescriptor>& client)
Eric Laurentc75307b2015-03-17 15:29:32 -07002452{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002453 // always handle stream stop, check which stream type is stopping
Eric Laurent97ac8712018-07-27 18:59:02 -07002454 audio_stream_type_t stream = client->stream();
François Gaffie1c878552018-11-22 16:53:21 +01002455 auto clientVolSrc = client->volumeSource();
Eric Laurent96d1dda2022-03-14 17:14:19 +01002456 bool wasLeUnicastActive = isLeUnicastActive();
Eric Laurent97ac8712018-07-27 18:59:02 -07002457
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002458 handleEventForBeacon(stream == AUDIO_STREAM_TTS ? STOPPING_BEACON : STOPPING_OUTPUT);
2459
François Gaffie1c878552018-11-22 16:53:21 +01002460 if (outputDesc->getActivityCount(clientVolSrc) > 0) {
2461 if (outputDesc->getActivityCount(clientVolSrc) == 1) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002462 // Automatically disable the remote submix input when output is stopped on a
2463 // re routing mix of type MIX_TYPE_RECORDERS
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002464 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
jiabin9a3361e2019-10-01 09:38:30 -07002465 if (isSingleDeviceType(
2466 outputDesc->devices().types(), &audio_is_remote_submix_device) &&
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002467 policyMix != nullptr &&
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002468 policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002469 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2470 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002471 policyMix->mDeviceAddress,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002472 "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07002473 }
2474 }
2475 bool forceDeviceUpdate = false;
Eric Laurent72af8012023-03-15 17:36:22 +01002476 if (client->hasPreferredDevice(true) &&
2477 outputDesc->sameExclusivePreferredDevicesCount() < 2) {
François Gaffiec005e562018-11-06 15:04:49 +01002478 checkStrategyRoute(client->strategy(), AUDIO_IO_HANDLE_NONE);
Eric Laurent97ac8712018-07-27 18:59:02 -07002479 forceDeviceUpdate = true;
2480 }
2481
Eric Laurente552edb2014-03-10 17:42:56 -07002482 // decrement usage count of this stream on the output
Eric Laurent592dd7b2018-08-05 18:58:48 -07002483 outputDesc->setClientActive(client, false);
Paul McLeanaa981192015-03-21 09:55:15 -07002484
Eric Laurente552edb2014-03-10 17:42:56 -07002485 // store time at which the stream was stopped - see isStreamActive()
François Gaffie1c878552018-11-22 16:53:21 +01002486 if (outputDesc->getActivityCount(clientVolSrc) == 0 || forceDeviceUpdate) {
François Gaffiec005e562018-11-06 15:04:49 +01002487 outputDesc->setStopTime(client, systemTime());
François Gaffie11d30102018-11-02 16:09:09 +01002488 DeviceVector newDevices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Francois Gaffie3523ab32021-06-22 13:24:34 +02002489
2490 // If the routing does not change, if an output is routed on a device using HwGain
2491 // (aka setAudioPortConfig) and there are still active clients following different
2492 // volume group(s), force reapply volume
2493 bool requiresVolumeCheck = outputDesc->getActivityCount(clientVolSrc) == 0 &&
2494 outputDesc->useHwGain() && outputDesc->isAnyActive(VOLUME_SOURCE_NONE);
2495
Eric Laurente552edb2014-03-10 17:42:56 -07002496 // delay the device switch by twice the latency because stopOutput() is executed when
2497 // the track stop() command is received and at that time the audio track buffer can
2498 // still contain data that needs to be drained. The latency only covers the audio HAL
2499 // and kernel buffers. Also the latency does not always include additional delay in the
2500 // audio path (audio DSP, CODEC ...)
Francois Gaffie3523ab32021-06-22 13:24:34 +02002501 setOutputDevices(outputDesc, newDevices, false, outputDesc->latency()*2,
2502 nullptr, true /*requiresMuteCheck*/, requiresVolumeCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07002503
2504 // force restoring the device selection on other active outputs if it differs from the
2505 // one being selected for this output
jiabin3ff8d7d2022-12-13 06:27:44 +00002506 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent57de36c2016-09-28 16:59:11 -07002507 uint32_t delayMs = outputDesc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -07002508 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01002509 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07002510 if (desc != outputDesc &&
Eric Laurente552edb2014-03-10 17:42:56 -07002511 desc->isActive() &&
2512 outputDesc->sharesHwModuleWith(desc) &&
François Gaffie11d30102018-11-02 16:09:09 +01002513 (newDevices != desc->devices())) {
2514 DeviceVector newDevices2 = getNewOutputDevices(desc, false /*fromCache*/);
2515 bool force = desc->devices() != newDevices2;
Eric Laurentf3a5a602018-05-22 18:42:55 -07002516
jiabin3ff8d7d2022-12-13 06:27:44 +00002517 if (desc->mUsePreferredMixerAttributes && force) {
2518 // If the device is using preferred mixer attributes, the output need to
2519 // reopen with default configuration when the new selected devices are
2520 // different from current routing devices.
2521 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices2);
2522 continue;
2523 }
François Gaffie11d30102018-11-02 16:09:09 +01002524 setOutputDevices(desc, newDevices2, force, delayMs);
2525
Eric Laurent57de36c2016-09-28 16:59:11 -07002526 // re-apply device specific volume if not done by setOutputDevice()
2527 if (!force) {
François Gaffie11d30102018-11-02 16:09:09 +01002528 applyStreamVolumes(desc, newDevices2.types(), delayMs);
Eric Laurent57de36c2016-09-28 16:59:11 -07002529 }
Eric Laurente552edb2014-03-10 17:42:56 -07002530 }
2531 }
jiabin3ff8d7d2022-12-13 06:27:44 +00002532 reopenOutputsWithDevices(outputsToReopen);
Eric Laurente552edb2014-03-10 17:42:56 -07002533 // update the outputs if stopping one with a stream that can affect notification routing
2534 handleNotificationRoutingForStream(stream);
2535 }
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002536
2537 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
2538 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Jean-Michel Trivi74e01fa2019-02-25 12:18:09 -08002539 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), false, outputDesc);
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002540 }
2541
François Gaffiec005e562018-11-06 15:04:49 +01002542 if (followsSameRouting(client->attributes(), attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07002543 selectOutputForMusicEffects();
2544 }
Eric Laurent96d1dda2022-03-14 17:14:19 +01002545
2546 checkLeBroadcastRoutes(wasLeUnicastActive, outputDesc, outputDesc->latency()*2);
2547
Eric Laurente552edb2014-03-10 17:42:56 -07002548 return NO_ERROR;
2549 } else {
Eric Laurentc75307b2015-03-17 15:29:32 -07002550 ALOGW("stopOutput() refcount is already 0");
Eric Laurente552edb2014-03-10 17:42:56 -07002551 return INVALID_OPERATION;
2552 }
2553}
2554
jiabinbce0c1d2020-10-05 11:20:18 -07002555bool AudioPolicyManager::releaseOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002556{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002557 ALOGV("%s portId %d", __FUNCTION__, portId);
2558
2559 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2560 if (outputDesc == 0) {
Andy Hung39efb7a2018-09-26 15:39:28 -07002561 // If an output descriptor is closed due to a device routing change,
2562 // then there are race conditions with releaseOutput from tracks
2563 // that may be destroyed (with no PlaybackThread) or a PlaybackThread
2564 // destroyed shortly thereafter.
2565 //
2566 // Here we just log a warning, instead of a fatal error.
Eric Laurent8fc147b2018-07-22 19:13:55 -07002567 ALOGW("releaseOutput() no output for client %d", portId);
jiabinbce0c1d2020-10-05 11:20:18 -07002568 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002569 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002570
2571 ALOGV("releaseOutput() %d", outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -07002572
Jaideep Sharma7bf382e2020-11-26 17:07:29 +05302573 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
2574 if (outputDesc->isClientActive(client)) {
2575 ALOGW("releaseOutput() inactivates portId %d in good faith", portId);
2576 stopOutput(portId);
2577 }
2578
Eric Laurent8fc147b2018-07-22 19:13:55 -07002579 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
2580 if (outputDesc->mDirectOpenCount <= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07002581 ALOGW("releaseOutput() invalid open count %d for output %d",
Eric Laurent8fc147b2018-07-22 19:13:55 -07002582 outputDesc->mDirectOpenCount, outputDesc->mIoHandle);
jiabinbce0c1d2020-10-05 11:20:18 -07002583 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002584 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002585 if (--outputDesc->mDirectOpenCount == 0) {
2586 closeOutput(outputDesc->mIoHandle);
Eric Laurentb52c1522014-05-20 11:27:36 -07002587 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07002588 }
2589 }
Jaideep Sharma7bf382e2020-11-26 17:07:29 +05302590
Andy Hung39efb7a2018-09-26 15:39:28 -07002591 outputDesc->removeClient(portId);
jiabinbce0c1d2020-10-05 11:20:18 -07002592 if (outputDesc->mPendingReopenToQueryProfiles && outputDesc->getClientCount() == 0) {
2593 // The output is pending reopened to query dynamic profiles and
2594 // there is no active clients
2595 closeOutput(outputDesc->mIoHandle);
2596 sp<SwAudioOutputDescriptor> newOutputDesc = openOutputWithProfileAndDevice(
2597 outputDesc->mProfile, mEngine->getActiveMediaDevices(mAvailableOutputDevices));
2598 if (newOutputDesc == nullptr) {
2599 ALOGE("%s failed to open output", __func__);
2600 }
2601 return true;
2602 }
2603 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002604}
2605
Eric Laurentcaf7f482014-11-25 17:50:47 -08002606status_t AudioPolicyManager::getInputForAttr(const audio_attributes_t *attr,
2607 audio_io_handle_t *input,
Mikhail Naganov2996f672019-04-18 12:29:59 -07002608 audio_unique_id_t riid,
Eric Laurentcaf7f482014-11-25 17:50:47 -08002609 audio_session_t session,
Svet Ganov3e5f14f2021-05-13 22:51:08 +00002610 const AttributionSourceState& attributionSource,
jiabinf1c73972022-04-14 16:28:52 -07002611 audio_config_base_t *config,
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002612 audio_input_flags_t flags,
Eric Laurent2ac76942017-06-22 17:17:09 -07002613 audio_port_handle_t *selectedDeviceId,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002614 input_type_t *inputType,
2615 audio_port_handle_t *portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002616{
François Gaffiec005e562018-11-06 15:04:49 +01002617 ALOGV("%s() source %d, sampling rate %d, format %#x, channel mask %#x, session %d, "
Eric Laurent2f2c1982021-06-02 14:03:11 +02002618 "flags %#x attributes=%s requested device ID %d",
2619 __func__, attr->source, config->sample_rate, config->format, config->channel_mask,
2620 session, flags, toString(*attr).c_str(), *selectedDeviceId);
Eric Laurente552edb2014-03-10 17:42:56 -07002621
Eric Laurentad2e7b92017-09-14 20:06:42 -07002622 status_t status = NO_ERROR;
Francois Gaffie716e1432019-01-14 16:58:59 +01002623 audio_attributes_t attributes = *attr;
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002624 sp<AudioPolicyMix> policyMix;
François Gaffie11d30102018-11-02 16:09:09 +01002625 sp<DeviceDescriptor> device;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002626 sp<AudioInputDescriptor> inputDesc;
2627 sp<RecordClientDescriptor> clientDesc;
2628 audio_port_handle_t requestedDeviceId = *selectedDeviceId;
Svet Ganov3e5f14f2021-05-13 22:51:08 +00002629 uid_t uid = VALUE_OR_RETURN_STATUS(aidl2legacy_int32_t_uid_t(attributionSource.uid));
Eric Laurent8f42ea12018-08-08 09:08:25 -07002630 bool isSoundTrigger;
Eric Laurent8f42ea12018-08-08 09:08:25 -07002631
2632 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
2633 if (*portId != AUDIO_PORT_HANDLE_NONE) {
2634 return INVALID_OPERATION;
2635 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08002636
Francois Gaffie716e1432019-01-14 16:58:59 +01002637 if (attr->source == AUDIO_SOURCE_DEFAULT) {
2638 attributes.source = AUDIO_SOURCE_MIC;
Eric Laurentfe231122017-11-17 17:48:06 -08002639 }
2640
Paul McLean466dc8e2015-04-17 13:15:36 -06002641 // Explicit routing?
Pattydd807582021-11-04 21:01:03 +08002642 sp<DeviceDescriptor> explicitRoutingDevice =
François Gaffie11d30102018-11-02 16:09:09 +01002643 mAvailableInputDevices.getDeviceFromId(*selectedDeviceId);
Paul McLean466dc8e2015-04-17 13:15:36 -06002644
Eric Laurentad2e7b92017-09-14 20:06:42 -07002645 // special case for mmap capture: if an input IO handle is specified, we reuse this input if
2646 // possible
2647 if ((flags & AUDIO_INPUT_FLAG_MMAP_NOIRQ) == AUDIO_INPUT_FLAG_MMAP_NOIRQ &&
2648 *input != AUDIO_IO_HANDLE_NONE) {
2649 ssize_t index = mInputs.indexOfKey(*input);
2650 if (index < 0) {
2651 ALOGW("getInputForAttr() unknown MMAP input %d", *input);
2652 status = BAD_VALUE;
2653 goto error;
2654 }
2655 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002656 RecordClientVector clients = inputDesc->getClientsForSession(session);
2657 if (clients.size() == 0) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07002658 ALOGW("getInputForAttr() unknown session %d on input %d", session, *input);
2659 status = BAD_VALUE;
2660 goto error;
2661 }
2662 // For MMAP mode, the first call to getInputForAttr() is made on behalf of audioflinger.
2663 // The second call is for the first active client and sets the UID. Any further call
Eric Laurent331679c2018-04-16 17:03:16 -07002664 // corresponds to a new client and is only permitted from the same UID.
2665 // If the first UID is silenced, allow a new UID connection and replace with new UID
Eric Laurent8f42ea12018-08-08 09:08:25 -07002666 if (clients.size() > 1) {
2667 for (const auto& client : clients) {
2668 // The client map is ordered by key values (portId) and portIds are allocated
2669 // incrementaly. So the first client in this list is the one opened by audio flinger
2670 // when the mmap stream is created and should be ignored as it does not correspond
2671 // to an actual client
2672 if (client == *clients.cbegin()) {
2673 continue;
2674 }
2675 if (uid != client->uid() && !client->isSilenced()) {
2676 ALOGW("getInputForAttr() bad uid %d for client %d uid %d",
2677 uid, client->portId(), client->uid());
2678 status = INVALID_OPERATION;
2679 goto error;
2680 }
Eric Laurent331679c2018-04-16 17:03:16 -07002681 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002682 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002683 *inputType = API_INPUT_LEGACY;
François Gaffie11d30102018-11-02 16:09:09 +01002684 device = inputDesc->getDevice();
Eric Laurentad2e7b92017-09-14 20:06:42 -07002685
Eric Laurentfecbceb2021-02-09 14:46:43 +01002686 ALOGV("%s reusing MMAP input %d for session %d", __FUNCTION__, *input, session);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002687 goto exit;
Eric Laurentad2e7b92017-09-14 20:06:42 -07002688 }
2689
2690 *input = AUDIO_IO_HANDLE_NONE;
2691 *inputType = API_INPUT_INVALID;
2692
Francois Gaffie716e1432019-01-14 16:58:59 +01002693 if (attributes.source == AUDIO_SOURCE_REMOTE_SUBMIX &&
Jan Sebechlebskybc56bcd2022-09-26 13:15:19 +02002694 extractAddressFromAudioAttributes(attributes).has_value()) {
Francois Gaffie716e1432019-01-14 16:58:59 +01002695 status = mPolicyMixes.getInputMixForAttr(attributes, &policyMix);
Eric Laurentad2e7b92017-09-14 20:06:42 -07002696 if (status != NO_ERROR) {
jiabinc1de2df2019-05-07 14:26:40 -07002697 ALOGW("%s could not find input mix for attr %s",
2698 __func__, toString(attributes).c_str());
Eric Laurentad2e7b92017-09-14 20:06:42 -07002699 goto error;
François Gaffie036e1e92015-03-19 10:16:24 +01002700 }
jiabinc1de2df2019-05-07 14:26:40 -07002701 device = mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2702 String8(attr->tags + strlen("addr=")),
2703 AUDIO_FORMAT_DEFAULT);
2704 if (device == nullptr) {
Kevin Rocard04ed0462019-05-02 17:53:24 -07002705 ALOGW("%s could not find in Remote Submix device for source %d, tags %s",
jiabinc1de2df2019-05-07 14:26:40 -07002706 __func__, attributes.source, attributes.tags);
2707 status = BAD_VALUE;
2708 goto error;
2709 }
2710
Kevin Rocard25f9b052019-02-27 15:08:54 -08002711 if (is_mix_loopback_render(policyMix->mRouteFlags)) {
2712 *inputType = API_INPUT_MIX_PUBLIC_CAPTURE_PLAYBACK;
2713 } else {
2714 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
2715 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002716 } else {
François Gaffie11d30102018-11-02 16:09:09 +01002717 if (explicitRoutingDevice != nullptr) {
2718 device = explicitRoutingDevice;
Eric Laurent97ac8712018-07-27 18:59:02 -07002719 } else {
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01002720 // Prevent from storing invalid requested device id in clients
2721 requestedDeviceId = AUDIO_PORT_HANDLE_NONE;
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02002722 device = mEngine->getInputDeviceForAttributes(attributes, uid, session, &policyMix);
yuanjiahsu4069d5d2021-04-19 07:54:27 +08002723 ALOGV_IF(device != nullptr, "%s found device type is 0x%X",
2724 __FUNCTION__, device->type());
Eric Laurent97ac8712018-07-27 18:59:02 -07002725 }
François Gaffie11d30102018-11-02 16:09:09 +01002726 if (device == nullptr) {
Francois Gaffie716e1432019-01-14 16:58:59 +01002727 ALOGW("getInputForAttr() could not find device for source %d", attributes.source);
Eric Laurentad2e7b92017-09-14 20:06:42 -07002728 status = BAD_VALUE;
2729 goto error;
Eric Laurent275e8e92014-11-30 15:14:47 -08002730 }
Alden DSouzab7d20782021-02-08 08:51:42 -08002731 if (device->type() == AUDIO_DEVICE_IN_ECHO_REFERENCE) {
2732 *inputType = API_INPUT_MIX_CAPTURE;
2733 } else if (policyMix) {
François Gaffie11d30102018-11-02 16:09:09 +01002734 ALOG_ASSERT(policyMix->mMixType == MIX_TYPE_RECORDERS, "Invalid Mix Type");
2735 // there is an external policy, but this input is attached to a mix of recorders,
2736 // meaning it receives audio injected into the framework, so the recorder doesn't
2737 // know about it and is therefore considered "legacy"
2738 *inputType = API_INPUT_LEGACY;
2739 } else if (audio_is_remote_submix_device(device->type())) {
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002740 *inputType = API_INPUT_MIX_CAPTURE;
François Gaffie11d30102018-11-02 16:09:09 +01002741 } else if (device->type() == AUDIO_DEVICE_IN_TELEPHONY_RX) {
Eric Laurent82db2692015-08-07 13:59:42 -07002742 *inputType = API_INPUT_TELEPHONY_RX;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002743 } else {
2744 *inputType = API_INPUT_LEGACY;
Eric Laurentc722f302014-12-10 11:21:49 -08002745 }
Ravi Kumar Alamandab367f5b2015-08-25 08:21:37 -07002746
Eric Laurent599c7582015-12-07 18:05:55 -08002747 }
2748
François Gaffiec005e562018-11-06 15:04:49 +01002749 *input = getInputForDevice(device, session, attributes, config, flags, policyMix);
Eric Laurent599c7582015-12-07 18:05:55 -08002750 if (*input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07002751 status = INVALID_OPERATION;
jiabinf1c73972022-04-14 16:28:52 -07002752 AudioProfileVector profiles;
2753 status_t ret = getProfilesForDevices(
2754 DeviceVector(device), profiles, flags, true /*isInput*/);
2755 if (ret == NO_ERROR && !profiles.empty()) {
2756 config->channel_mask = profiles[0]->getChannels().empty() ? config->channel_mask
2757 : *profiles[0]->getChannels().begin();
2758 config->sample_rate = profiles[0]->getSampleRates().empty() ? config->sample_rate
2759 : *profiles[0]->getSampleRates().begin();
2760 config->format = profiles[0]->getFormat();
2761 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002762 goto error;
Eric Laurent599c7582015-12-07 18:05:55 -08002763 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08002764
Eric Laurent8f42ea12018-08-08 09:08:25 -07002765exit:
2766
François Gaffiec005e562018-11-06 15:04:49 +01002767 *selectedDeviceId = mAvailableInputDevices.contains(device) ?
2768 device->getId() : AUDIO_PORT_HANDLE_NONE;
Eric Laurent2ac76942017-06-22 17:17:09 -07002769
Francois Gaffie716e1432019-01-14 16:58:59 +01002770 isSoundTrigger = attributes.source == AUDIO_SOURCE_HOTWORD &&
Carter Hsud0cce2e2019-05-03 17:36:28 +08002771 mSoundTriggerSessions.indexOfKey(session) >= 0;
jiabin4ef93452019-09-10 14:29:54 -07002772 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002773
Mikhail Naganov2996f672019-04-18 12:29:59 -07002774 clientDesc = new RecordClientDescriptor(*portId, riid, uid, session, attributes, *config,
Francois Gaffie716e1432019-01-14 16:58:59 +01002775 requestedDeviceId, attributes.source, flags,
2776 isSoundTrigger);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002777 inputDesc = mInputs.valueFor(*input);
Andy Hung39efb7a2018-09-26 15:39:28 -07002778 inputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002779
2780 ALOGV("getInputForAttr() returns input %d type %d selectedDeviceId %d for port ID %d",
2781 *input, *inputType, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07002782
Eric Laurent599c7582015-12-07 18:05:55 -08002783 return NO_ERROR;
Eric Laurentad2e7b92017-09-14 20:06:42 -07002784
2785error:
Eric Laurentad2e7b92017-09-14 20:06:42 -07002786 return status;
Eric Laurent599c7582015-12-07 18:05:55 -08002787}
2788
2789
François Gaffie11d30102018-11-02 16:09:09 +01002790audio_io_handle_t AudioPolicyManager::getInputForDevice(const sp<DeviceDescriptor> &device,
Eric Laurent599c7582015-12-07 18:05:55 -08002791 audio_session_t session,
François Gaffiec005e562018-11-06 15:04:49 +01002792 const audio_attributes_t &attributes,
jiabinf1c73972022-04-14 16:28:52 -07002793 audio_config_base_t *config,
Eric Laurent599c7582015-12-07 18:05:55 -08002794 audio_input_flags_t flags,
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002795 const sp<AudioPolicyMix> &policyMix)
Eric Laurent599c7582015-12-07 18:05:55 -08002796{
2797 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
François Gaffiec005e562018-11-06 15:04:49 +01002798 audio_source_t halInputSource = attributes.source;
Eric Laurent599c7582015-12-07 18:05:55 -08002799 bool isSoundTrigger = false;
2800
François Gaffiec005e562018-11-06 15:04:49 +01002801 if (attributes.source == AUDIO_SOURCE_HOTWORD) {
Eric Laurent599c7582015-12-07 18:05:55 -08002802 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
2803 if (index >= 0) {
2804 input = mSoundTriggerSessions.valueFor(session);
2805 isSoundTrigger = true;
2806 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_HW_HOTWORD);
2807 ALOGV("SoundTrigger capture on session %d input %d", session, input);
2808 } else {
2809 halInputSource = AUDIO_SOURCE_VOICE_RECOGNITION;
Eric Laurent5dbe4712014-09-19 19:04:57 -07002810 }
François Gaffiec005e562018-11-06 15:04:49 +01002811 } else if (attributes.source == AUDIO_SOURCE_VOICE_COMMUNICATION &&
Eric Laurentfe231122017-11-17 17:48:06 -08002812 audio_is_linear_pcm(config->format)) {
Haynes Mathew George851d3ff2017-06-19 20:01:57 -07002813 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_VOIP_TX);
Eric Laurent5dbe4712014-09-19 19:04:57 -07002814 }
2815
Carter Hsua3abb402021-10-26 11:11:20 +08002816 if (attributes.source == AUDIO_SOURCE_ULTRASOUND) {
2817 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_ULTRASOUND);
2818 }
2819
Eric Laurentfe231122017-11-17 17:48:06 -08002820 // sampling rate and flags may be updated by getInputProfile
2821 uint32_t profileSamplingRate = (config->sample_rate == 0) ?
2822 SAMPLE_RATE_HZ_DEFAULT : config->sample_rate;
jiabin2fd710d2022-05-02 23:20:22 +00002823 audio_format_t profileFormat = config->format;
Eric Laurentfe231122017-11-17 17:48:06 -08002824 audio_channel_mask_t profileChannelMask = config->channel_mask;
Andy Hungf129b032015-04-07 13:45:50 -07002825 audio_input_flags_t profileFlags = flags;
jiabin2fd710d2022-05-02 23:20:22 +00002826 // find a compatible input profile (not necessarily identical in parameters)
2827 sp<IOProfile> profile = getInputProfile(
2828 device, profileSamplingRate, profileFormat, profileChannelMask, profileFlags);
2829 if (profile == nullptr) {
2830 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07002831 }
jiabin2fd710d2022-05-02 23:20:22 +00002832
Glenn Kasten05ddca52016-02-11 08:17:12 -08002833 // Pick input sampling rate if not specified by client
Eric Laurentfe231122017-11-17 17:48:06 -08002834 uint32_t samplingRate = config->sample_rate;
Glenn Kasten05ddca52016-02-11 08:17:12 -08002835 if (samplingRate == 0) {
2836 samplingRate = profileSamplingRate;
2837 }
Eric Laurente552edb2014-03-10 17:42:56 -07002838
Eric Laurent322b4d22015-04-03 15:57:54 -07002839 if (profile->getModuleHandle() == 0) {
2840 ALOGE("getInputForAttr(): HW module %s not opened", profile->getModuleName());
Eric Laurent599c7582015-12-07 18:05:55 -08002841 return input;
Eric Laurentcf2c0212014-07-25 16:20:43 -07002842 }
2843
Eric Laurentec376dc2021-04-08 20:41:22 +02002844 // Reuse an already opened input if a client with the same session ID already exists
2845 // on that input
2846 for (size_t i = 0; i < mInputs.size(); i++) {
2847 sp <AudioInputDescriptor> desc = mInputs.valueAt(i);
2848 if (desc->mProfile != profile) {
2849 continue;
2850 }
2851 RecordClientVector clients = desc->clientsList();
2852 for (const auto &client : clients) {
2853 if (session == client->session()) {
2854 return desc->mIoHandle;
2855 }
2856 }
2857 }
2858
Eric Laurent3974e3b2017-12-07 17:58:43 -08002859 if (!profile->canOpenNewIo()) {
Eric Laurent4eb58f12018-12-07 16:41:02 -08002860 for (size_t i = 0; i < mInputs.size(); ) {
Eric Laurentc529cf62020-04-17 18:19:10 -07002861 sp<AudioInputDescriptor> desc = mInputs.valueAt(i);
Eric Laurent4eb58f12018-12-07 16:41:02 -08002862 if (desc->mProfile != profile) {
Carter Hsu9a645a92019-05-15 12:15:32 +08002863 i++;
Eric Laurent4eb58f12018-12-07 16:41:02 -08002864 continue;
2865 }
2866 // if sound trigger, reuse input if used by other sound trigger on same session
2867 // else
2868 // reuse input if active client app is not in IDLE state
2869 //
2870 RecordClientVector clients = desc->clientsList();
2871 bool doClose = false;
2872 for (const auto& client : clients) {
2873 if (isSoundTrigger != client->isSoundTrigger()) {
2874 continue;
2875 }
2876 if (client->isSoundTrigger()) {
2877 if (session == client->session()) {
2878 return desc->mIoHandle;
2879 }
2880 continue;
2881 }
2882 if (client->active() && client->appState() != APP_STATE_IDLE) {
2883 return desc->mIoHandle;
2884 }
2885 doClose = true;
2886 }
2887 if (doClose) {
2888 closeInput(desc->mIoHandle);
2889 } else {
2890 i++;
2891 }
2892 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002893 }
2894
Eric Laurentfe231122017-11-17 17:48:06 -08002895 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07002896
Eric Laurentfe231122017-11-17 17:48:06 -08002897 audio_config_t lConfig = AUDIO_CONFIG_INITIALIZER;
2898 lConfig.sample_rate = profileSamplingRate;
2899 lConfig.channel_mask = profileChannelMask;
2900 lConfig.format = profileFormat;
Eric Laurente3014102017-05-03 11:15:43 -07002901
François Gaffie11d30102018-11-02 16:09:09 +01002902 status_t status = inputDesc->open(&lConfig, device, halInputSource, profileFlags, &input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07002903
2904 // only accept input with the exact requested set of parameters
Eric Laurent599c7582015-12-07 18:05:55 -08002905 if (status != NO_ERROR || input == AUDIO_IO_HANDLE_NONE ||
Eric Laurentfe231122017-11-17 17:48:06 -08002906 (profileSamplingRate != lConfig.sample_rate) ||
2907 !audio_formats_match(profileFormat, lConfig.format) ||
2908 (profileChannelMask != lConfig.channel_mask)) {
2909 ALOGW("getInputForAttr() failed opening input: sampling rate %d"
Glenn Kasten49f36ba2017-12-06 13:02:02 -08002910 ", format %#x, channel mask %#x",
Eric Laurentfe231122017-11-17 17:48:06 -08002911 profileSamplingRate, profileFormat, profileChannelMask);
Eric Laurent599c7582015-12-07 18:05:55 -08002912 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfe231122017-11-17 17:48:06 -08002913 inputDesc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07002914 }
Eric Laurent599c7582015-12-07 18:05:55 -08002915 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07002916 }
2917
Eric Laurentc722f302014-12-10 11:21:49 -08002918 inputDesc->mPolicyMix = policyMix;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002919
Eric Laurent599c7582015-12-07 18:05:55 -08002920 addInput(input, inputDesc);
Eric Laurentb52c1522014-05-20 11:27:36 -07002921 mpClientInterface->onAudioPortListUpdate();
Paul McLean466dc8e2015-04-17 13:15:36 -06002922
Eric Laurent599c7582015-12-07 18:05:55 -08002923 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07002924}
2925
Eric Laurent4eb58f12018-12-07 16:41:02 -08002926status_t AudioPolicyManager::startInput(audio_port_handle_t portId)
Eric Laurentbb948092017-01-23 18:33:30 -08002927{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002928 ALOGV("%s portId %d", __FUNCTION__, portId);
2929
2930 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2931 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002932 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurentd52a28c2020-08-21 17:10:39 -07002933 return DEAD_OBJECT;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002934 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002935 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07002936 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002937 if (client->active()) {
2938 ALOGW("%s input %d client %d already started", __FUNCTION__, input, client->portId());
2939 return INVALID_OPERATION;
Eric Laurent4dc68062014-07-28 17:26:49 -07002940 }
2941
Eric Laurent8f42ea12018-08-08 09:08:25 -07002942 audio_session_t session = client->session();
2943
Eric Laurent4eb58f12018-12-07 16:41:02 -08002944 ALOGV("%s input:%d, session:%d)", __FUNCTION__, input, session);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002945
Eric Laurent4eb58f12018-12-07 16:41:02 -08002946 Vector<sp<AudioInputDescriptor>> activeInputs = mInputs.getActiveInputs();
Eric Laurent74708e72017-04-07 17:13:42 -07002947
Eric Laurent4eb58f12018-12-07 16:41:02 -08002948 status_t status = inputDesc->start();
2949 if (status != NO_ERROR) {
2950 return status;
Eric Laurent74708e72017-04-07 17:13:42 -07002951 }
Eric Laurente552edb2014-03-10 17:42:56 -07002952
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002953 // increment activity count before calling getNewInputDevice() below as only active sessions
Eric Laurent313d1e72016-01-29 09:56:57 -08002954 // are considered for device selection
Eric Laurent8f42ea12018-08-08 09:08:25 -07002955 inputDesc->setClientActive(client, true);
Eric Laurent313d1e72016-01-29 09:56:57 -08002956
Eric Laurent8f42ea12018-08-08 09:08:25 -07002957 // indicate active capture to sound trigger service if starting capture from a mic on
2958 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01002959 sp<DeviceDescriptor> device = getNewInputDevice(inputDesc);
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002960 if (device != nullptr) {
2961 status = setInputDevice(input, device, true /* force */);
2962 } else {
2963 ALOGW("%s no new input device can be found for descriptor %d",
2964 __FUNCTION__, inputDesc->getId());
2965 status = BAD_VALUE;
2966 }
Eric Laurente552edb2014-03-10 17:42:56 -07002967
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002968 if (status == NO_ERROR && inputDesc->activeCount() == 1) {
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002969 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002970 // if input maps to a dynamic policy with an activity listener, notify of state change
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002971 if ((policyMix != nullptr)
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002972 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
2973 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
Eric Laurent8f42ea12018-08-08 09:08:25 -07002974 MIX_STATE_MIXING);
Eric Laurent733ce942017-12-07 12:18:25 -08002975 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002976
François Gaffie11d30102018-11-02 16:09:09 +01002977 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
2978 if (primaryInputDevices.contains(device) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07002979 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 1) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07002980 mpClientInterface->setSoundTriggerCaptureState(true);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002981 }
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002982
Eric Laurent8f42ea12018-08-08 09:08:25 -07002983 // automatically enable the remote submix output when input is started if not
2984 // used by a policy mix of type MIX_TYPE_RECORDERS
2985 // For remote submix (a virtual device), we open only one input per capture request.
François Gaffie11d30102018-11-02 16:09:09 +01002986 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002987 String8 address = String8("");
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002988 if (policyMix == nullptr) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002989 address = String8("0");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002990 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
2991 address = policyMix->mDeviceAddress;
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002992 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07002993 if (address != "") {
2994 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2995 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002996 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurentc722f302014-12-10 11:21:49 -08002997 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07002998 }
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002999 } else if (status != NO_ERROR) {
3000 // Restore client activity state.
3001 inputDesc->setClientActive(client, false);
3002 inputDesc->stop();
Eric Laurente552edb2014-03-10 17:42:56 -07003003 }
3004
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003005 ALOGV("%s input %d source = %d status = %d exit",
3006 __FUNCTION__, input, client->source(), status);
Eric Laurente552edb2014-03-10 17:42:56 -07003007
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003008 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07003009}
3010
Eric Laurent8fc147b2018-07-22 19:13:55 -07003011status_t AudioPolicyManager::stopInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07003012{
Eric Laurent8fc147b2018-07-22 19:13:55 -07003013 ALOGV("%s portId %d", __FUNCTION__, portId);
3014
3015 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
3016 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003017 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07003018 return BAD_VALUE;
3019 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07003020 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07003021 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003022 if (!client->active()) {
3023 ALOGW("%s input %d client %d already stopped", __FUNCTION__, input, client->portId());
Eric Laurente552edb2014-03-10 17:42:56 -07003024 return INVALID_OPERATION;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003025 }
Carter Hsue6139d52021-07-08 10:30:20 +08003026 auto old_source = inputDesc->source();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003027 inputDesc->setClientActive(client, false);
Paul McLean466dc8e2015-04-17 13:15:36 -06003028
Eric Laurent8f42ea12018-08-08 09:08:25 -07003029 inputDesc->stop();
3030 if (inputDesc->isActive()) {
Carter Hsue6139d52021-07-08 10:30:20 +08003031 auto current_source = inputDesc->source();
3032 setInputDevice(input, getNewInputDevice(inputDesc),
3033 old_source != current_source /* force */);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003034 } else {
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003035 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003036 // if input maps to a dynamic policy with an activity listener, notify of state change
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003037 if ((policyMix != nullptr)
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003038 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
3039 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
Eric Laurent8f42ea12018-08-08 09:08:25 -07003040 MIX_STATE_IDLE);
Eric Laurent84332aa2016-01-28 22:19:18 +00003041 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07003042
3043 // automatically disable the remote submix output when input is stopped if not
3044 // used by a policy mix of type MIX_TYPE_RECORDERS
François Gaffie11d30102018-11-02 16:09:09 +01003045 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003046 String8 address = String8("");
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003047 if (policyMix == nullptr) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003048 address = String8("0");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003049 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
3050 address = policyMix->mDeviceAddress;
Eric Laurent8f42ea12018-08-08 09:08:25 -07003051 }
3052 if (address != "") {
3053 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
3054 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08003055 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003056 }
3057 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07003058 resetInputDevice(input);
3059
3060 // indicate inactive capture to sound trigger service if stopping capture from a mic on
3061 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01003062 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
3063 if (primaryInputDevices.contains(inputDesc->getDevice()) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07003064 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07003065 mpClientInterface->setSoundTriggerCaptureState(false);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003066 }
3067 inputDesc->clearPreemptedSessions();
Eric Laurente552edb2014-03-10 17:42:56 -07003068 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003069 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07003070}
3071
Eric Laurent8fc147b2018-07-22 19:13:55 -07003072void AudioPolicyManager::releaseInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07003073{
Eric Laurent8fc147b2018-07-22 19:13:55 -07003074 ALOGV("%s portId %d", __FUNCTION__, portId);
3075
3076 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
3077 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003078 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07003079 return;
3080 }
Andy Hung39efb7a2018-09-26 15:39:28 -07003081 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8fc147b2018-07-22 19:13:55 -07003082 audio_io_handle_t input = inputDesc->mIoHandle;
3083
Eric Laurent8f42ea12018-08-08 09:08:25 -07003084 ALOGV("%s %d", __FUNCTION__, input);
Paul McLean466dc8e2015-04-17 13:15:36 -06003085
Andy Hung39efb7a2018-09-26 15:39:28 -07003086 inputDesc->removeClient(portId);
Eric Laurent599c7582015-12-07 18:05:55 -08003087
Andy Hung39efb7a2018-09-26 15:39:28 -07003088 if (inputDesc->getClientCount() > 0) {
3089 ALOGV("%s(%d) %zu clients remaining", __func__, portId, inputDesc->getClientCount());
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003090 return;
3091 }
3092
Eric Laurent05b90f82014-08-27 15:32:29 -07003093 closeInput(input);
Eric Laurentb52c1522014-05-20 11:27:36 -07003094 mpClientInterface->onAudioPortListUpdate();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003095 ALOGV("%s exit", __FUNCTION__);
Eric Laurente552edb2014-03-10 17:42:56 -07003096}
3097
Eric Laurent8f42ea12018-08-08 09:08:25 -07003098void AudioPolicyManager::closeActiveClients(const sp<AudioInputDescriptor>& input)
Eric Laurent8fc147b2018-07-22 19:13:55 -07003099{
Eric Laurent8f42ea12018-08-08 09:08:25 -07003100 RecordClientVector clients = input->clientsList(true);
Eric Laurent8fc147b2018-07-22 19:13:55 -07003101
3102 for (const auto& client : clients) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003103 closeClient(client->portId());
Eric Laurent8fc147b2018-07-22 19:13:55 -07003104 }
3105}
3106
Eric Laurent8f42ea12018-08-08 09:08:25 -07003107void AudioPolicyManager::closeClient(audio_port_handle_t portId)
3108{
3109 stopInput(portId);
3110 releaseInput(portId);
3111}
Eric Laurent8fc147b2018-07-22 19:13:55 -07003112
Eric Laurent0dd51852019-04-19 18:18:58 -07003113void AudioPolicyManager::checkCloseInputs() {
3114 // After connecting or disconnecting an input device, close input if:
3115 // - it has no client (was just opened to check profile) OR
3116 // - none of its supported devices are connected anymore OR
3117 // - one of its clients cannot be routed to one of its supported
3118 // devices anymore. Otherwise update device selection
3119 std::vector<audio_io_handle_t> inputsToClose;
3120 for (size_t i = 0; i < mInputs.size(); i++) {
3121 const sp<AudioInputDescriptor> input = mInputs.valueAt(i);
3122 if (input->clientsList().size() == 0
Eric Laurent85732f42020-03-19 11:31:10 -07003123 || !mAvailableInputDevices.containsAtLeastOne(input->supportedDevices())) {
Eric Laurent0dd51852019-04-19 18:18:58 -07003124 inputsToClose.push_back(mInputs.keyAt(i));
3125 } else {
3126 bool close = false;
3127 for (const auto& client : input->clientsList()) {
3128 sp<DeviceDescriptor> device =
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02003129 mEngine->getInputDeviceForAttributes(client->attributes(), client->uid(),
3130 client->session());
Eric Laurent0dd51852019-04-19 18:18:58 -07003131 if (!input->supportedDevices().contains(device)) {
3132 close = true;
3133 break;
3134 }
3135 }
3136 if (close) {
3137 inputsToClose.push_back(mInputs.keyAt(i));
3138 } else {
3139 setInputDevice(input->mIoHandle, getNewInputDevice(input));
3140 }
3141 }
3142 }
3143
3144 for (const audio_io_handle_t handle : inputsToClose) {
3145 ALOGV("%s closing input %d", __func__, handle);
3146 closeInput(handle);
Eric Laurent05b90f82014-08-27 15:32:29 -07003147 }
Eric Laurentd4692962014-05-05 18:13:44 -07003148}
3149
François Gaffie251c7f02018-11-07 10:41:08 +01003150void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream, int indexMin, int indexMax)
Eric Laurente552edb2014-03-10 17:42:56 -07003151{
3152 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08003153 if (indexMin < 0 || indexMax < 0) {
3154 ALOGE("%s for stream %d: invalid min %d or max %d", __func__, stream , indexMin, indexMax);
3155 return;
3156 }
Eric Laurentf5aa58d2019-02-22 18:20:11 -08003157 getVolumeCurves(stream).initVolume(indexMin, indexMax);
Eric Laurent28d09f02016-03-08 10:43:05 -08003158
3159 // initialize other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08003160 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
3161 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08003162 continue;
3163 }
Eric Laurentf5aa58d2019-02-22 18:20:11 -08003164 getVolumeCurves((audio_stream_type_t)curStream).initVolume(indexMin, indexMax);
Eric Laurent223fd5c2014-11-11 13:43:36 -08003165 }
Eric Laurente552edb2014-03-10 17:42:56 -07003166}
3167
Eric Laurente0720872014-03-11 09:30:41 -07003168status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
François Gaffie53615e22015-03-19 09:24:12 +01003169 int index,
3170 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07003171{
François Gaffieaaac0fd2018-11-22 17:56:39 +01003172 auto attributes = mEngine->getAttributesForStreamType(stream);
Eric Laurent242a9f82020-03-23 15:57:04 -07003173 if (attributes == AUDIO_ATTRIBUTES_INITIALIZER) {
3174 ALOGW("%s: no group for stream %s, bailing out", __func__, toString(stream).c_str());
3175 return NO_ERROR;
3176 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01003177 ALOGV("%s: stream %s attributes=%s", __func__,
3178 toString(stream).c_str(), toString(attributes).c_str());
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003179 return setVolumeIndexForAttributes(attributes, index, device);
Eric Laurente552edb2014-03-10 17:42:56 -07003180}
3181
Eric Laurente0720872014-03-11 09:30:41 -07003182status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
François Gaffieaaac0fd2018-11-22 17:56:39 +01003183 int *index,
3184 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07003185{
François Gaffiec005e562018-11-06 15:04:49 +01003186 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
3187 // stream by the engine.
jiabin9a3361e2019-10-01 09:38:30 -07003188 DeviceTypeSet deviceTypes = {device};
Eric Laurent5a2b6292016-04-14 18:05:57 -07003189 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
jiabin9a3361e2019-10-01 09:38:30 -07003190 deviceTypes = mEngine->getOutputDevicesForStream(
3191 stream, true /*fromCache*/).types();
Eric Laurente552edb2014-03-10 17:42:56 -07003192 }
jiabin9a3361e2019-10-01 09:38:30 -07003193 return getVolumeIndex(getVolumeCurves(stream), *index, deviceTypes);
Eric Laurente552edb2014-03-10 17:42:56 -07003194}
3195
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003196status_t AudioPolicyManager::setVolumeIndexForAttributes(const audio_attributes_t &attributes,
François Gaffiecfe17322018-11-07 13:41:29 +01003197 int index,
3198 audio_devices_t device)
3199{
3200 // Get Volume group matching the Audio Attributes
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003201 auto group = mEngine->getVolumeGroupForAttributes(attributes);
3202 if (group == VOLUME_GROUP_NONE) {
3203 ALOGD("%s: no group matching with %s", __FUNCTION__, toString(attributes).c_str());
François Gaffiecfe17322018-11-07 13:41:29 +01003204 return BAD_VALUE;
3205 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003206 ALOGV("%s: group %d matching with %s", __FUNCTION__, group, toString(attributes).c_str());
François Gaffiecfe17322018-11-07 13:41:29 +01003207 status_t status = NO_ERROR;
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003208 IVolumeCurves &curves = getVolumeCurves(attributes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01003209 VolumeSource vs = toVolumeSource(group);
Eric Laurentf9cccec2022-11-16 19:12:00 +01003210 // AUDIO_STREAM_BLUETOOTH_SCO is only used for volume control so we remap
3211 // to AUDIO_STREAM_VOICE_CALL to match with relevant playback activity
3212 VolumeSource activityVs = (vs == toVolumeSource(AUDIO_STREAM_BLUETOOTH_SCO, false)) ?
3213 toVolumeSource(AUDIO_STREAM_VOICE_CALL, false) : vs;
François Gaffieaaac0fd2018-11-22 17:56:39 +01003214 product_strategy_t strategy = mEngine->getProductStrategyForAttributes(attributes);
3215
3216 status = setVolumeCurveIndex(index, device, curves);
3217 if (status != NO_ERROR) {
3218 ALOGE("%s failed to set curve index for group %d device 0x%X", __func__, group, device);
3219 return status;
3220 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003221
jiabin9a3361e2019-10-01 09:38:30 -07003222 DeviceTypeSet curSrcDevices;
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003223 auto curCurvAttrs = curves.getAttributes();
3224 if (!curCurvAttrs.empty() && curCurvAttrs.front() != defaultAttr) {
3225 auto attr = curCurvAttrs.front();
jiabin9a3361e2019-10-01 09:38:30 -07003226 curSrcDevices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false).types();
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003227 } else if (!curves.getStreamTypes().empty()) {
3228 auto stream = curves.getStreamTypes().front();
jiabin9a3361e2019-10-01 09:38:30 -07003229 curSrcDevices = mEngine->getOutputDevicesForStream(stream, false).types();
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003230 } else {
3231 ALOGE("%s: Invalid src %d: no valid attributes nor stream",__func__, vs);
3232 return BAD_VALUE;
3233 }
jiabin9a3361e2019-10-01 09:38:30 -07003234 audio_devices_t curSrcDevice = Volume::getDeviceForVolume(curSrcDevices);
3235 resetDeviceTypes(curSrcDevices, curSrcDevice);
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003236
François Gaffiecfe17322018-11-07 13:41:29 +01003237 // update volume on all outputs and streams matching the following:
3238 // - The requested stream (or a stream matching for volume control) is active on the output
3239 // - The device (or devices) selected by the engine for this stream includes
3240 // the requested device
3241 // - For non default requested device, currently selected device on the output is either the
3242 // requested device or one of the devices selected by the engine for this stream
3243 // - For default requested device (AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME), apply volume only if
3244 // no specific device volume value exists for currently selected device.
François Gaffieaaac0fd2018-11-22 17:56:39 +01003245 for (size_t i = 0; i < mOutputs.size(); i++) {
3246 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
jiabin9a3361e2019-10-01 09:38:30 -07003247 DeviceTypeSet curDevices = desc->devices().types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01003248
jiabin9a3361e2019-10-01 09:38:30 -07003249 if (curDevices.erase(AUDIO_DEVICE_OUT_SPEAKER_SAFE)) {
3250 curDevices.insert(AUDIO_DEVICE_OUT_SPEAKER);
Robert Lee5e66e792019-04-03 18:37:15 +08003251 }
Eric Laurentf9cccec2022-11-16 19:12:00 +01003252
3253 if (!(desc->isActive(activityVs) || isInCallOrScreening())) {
François Gaffieed91f582020-01-31 10:35:37 +01003254 continue;
3255 }
3256 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME &&
3257 curDevices.find(device) == curDevices.end()) {
3258 continue;
3259 }
3260 bool applyVolume = false;
3261 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
3262 curSrcDevices.insert(device);
3263 applyVolume = (curSrcDevices.find(
3264 Volume::getDeviceForVolume(curDevices)) != curSrcDevices.end());
3265 } else {
3266 applyVolume = !curves.hasVolumeIndexForDevice(curSrcDevice);
3267 }
3268 if (!applyVolume) {
3269 continue; // next output
3270 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01003271 // Inter / intra volume group priority management: Loop on strategies arranged by priority
3272 // If a higher priority strategy is active, and the output is routed to a device with a
3273 // HW Gain management, do not change the volume
François Gaffieaaac0fd2018-11-22 17:56:39 +01003274 if (desc->useHwGain()) {
François Gaffieed91f582020-01-31 10:35:37 +01003275 applyVolume = false;
Francois Gaffie593634d2021-06-22 13:31:31 +02003276 // If the volume source is active with higher priority source, ensure at least Sw Muted
3277 desc->setSwMute((index == 0), vs, curves.getStreamTypes(), curDevices, 0 /*delayMs*/);
François Gaffieaaac0fd2018-11-22 17:56:39 +01003278 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
3279 auto activeClients = desc->clientsList(true /*activeOnly*/, productStrategy,
3280 false /*preferredDevice*/);
3281 if (activeClients.empty()) {
3282 continue;
3283 }
3284 bool isPreempted = false;
3285 bool isHigherPriority = productStrategy < strategy;
3286 for (const auto &client : activeClients) {
Eric Laurentf9cccec2022-11-16 19:12:00 +01003287 if (isHigherPriority && (client->volumeSource() != activityVs)) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01003288 ALOGV("%s: Strategy=%d (\nrequester:\n"
3289 " group %d, volumeGroup=%d attributes=%s)\n"
3290 " higher priority source active:\n"
3291 " volumeGroup=%d attributes=%s) \n"
3292 " on output %zu, bailing out", __func__, productStrategy,
3293 group, group, toString(attributes).c_str(),
3294 client->volumeSource(), toString(client->attributes()).c_str(), i);
3295 applyVolume = false;
3296 isPreempted = true;
3297 break;
3298 }
3299 // However, continue for loop to ensure no higher prio clients running on output
Eric Laurentf9cccec2022-11-16 19:12:00 +01003300 if (client->volumeSource() == activityVs) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01003301 applyVolume = true;
3302 }
3303 }
3304 if (isPreempted || applyVolume) {
3305 break;
3306 }
3307 }
3308 if (!applyVolume) {
3309 continue; // next output
3310 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01003311 }
François Gaffieed91f582020-01-31 10:35:37 +01003312 //FIXME: workaround for truncated touch sounds
3313 // delayed volume change for system stream to be removed when the problem is
3314 // handled by system UI
3315 status_t volStatus = checkAndSetVolume(
3316 curves, vs, index, desc, curDevices,
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003317 ((vs == toVolumeSource(AUDIO_STREAM_SYSTEM, false))?
François Gaffieed91f582020-01-31 10:35:37 +01003318 TOUCH_SOUND_FIXED_DELAY_MS : 0));
3319 if (volStatus != NO_ERROR) {
3320 status = volStatus;
François Gaffieaaac0fd2018-11-22 17:56:39 +01003321 }
3322 }
François Gaffiecfe17322018-11-07 13:41:29 +01003323 mpClientInterface->onAudioVolumeGroupChanged(group, 0 /*flags*/);
3324 return status;
3325}
3326
François Gaffieaaac0fd2018-11-22 17:56:39 +01003327status_t AudioPolicyManager::setVolumeCurveIndex(int index,
François Gaffiecfe17322018-11-07 13:41:29 +01003328 audio_devices_t device,
3329 IVolumeCurves &volumeCurves)
3330{
3331 // VOICE_CALL stream has minVolumeIndex > 0 but can be muted directly by an
3332 // app that has MODIFY_PHONE_STATE permission.
François Gaffieaaac0fd2018-11-22 17:56:39 +01003333 bool hasVoice = hasVoiceStream(volumeCurves.getStreamTypes());
3334 if (((index < volumeCurves.getVolumeIndexMin()) && !(hasVoice && index == 0)) ||
François Gaffiecfe17322018-11-07 13:41:29 +01003335 (index > volumeCurves.getVolumeIndexMax())) {
3336 ALOGD("%s: wrong index %d min=%d max=%d", __FUNCTION__, index,
3337 volumeCurves.getVolumeIndexMin(), volumeCurves.getVolumeIndexMax());
3338 return BAD_VALUE;
3339 }
3340 if (!audio_is_output_device(device)) {
3341 return BAD_VALUE;
3342 }
3343
3344 // Force max volume if stream cannot be muted
3345 if (!volumeCurves.canBeMuted()) index = volumeCurves.getVolumeIndexMax();
3346
François Gaffieaaac0fd2018-11-22 17:56:39 +01003347 ALOGV("%s device %08x, index %d", __FUNCTION__ , device, index);
François Gaffiecfe17322018-11-07 13:41:29 +01003348 volumeCurves.addCurrentVolumeIndex(device, index);
3349 return NO_ERROR;
3350}
3351
3352status_t AudioPolicyManager::getVolumeIndexForAttributes(const audio_attributes_t &attr,
3353 int &index,
3354 audio_devices_t device)
3355{
3356 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
3357 // stream by the engine.
jiabin9a3361e2019-10-01 09:38:30 -07003358 DeviceTypeSet deviceTypes = {device};
François Gaffiecfe17322018-11-07 13:41:29 +01003359 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
Mikhail Naganovbb990f22022-06-15 00:46:43 +00003360 deviceTypes = mEngine->getOutputDevicesForAttributes(
jiabin9a3361e2019-10-01 09:38:30 -07003361 attr, nullptr, true /*fromCache*/).types();
François Gaffiecfe17322018-11-07 13:41:29 +01003362 }
jiabin9a3361e2019-10-01 09:38:30 -07003363 return getVolumeIndex(getVolumeCurves(attr), index, deviceTypes);
François Gaffiecfe17322018-11-07 13:41:29 +01003364}
3365
3366status_t AudioPolicyManager::getVolumeIndex(const IVolumeCurves &curves,
3367 int &index,
jiabin9a3361e2019-10-01 09:38:30 -07003368 const DeviceTypeSet& deviceTypes) const
François Gaffiecfe17322018-11-07 13:41:29 +01003369{
Mikhail Naganovbb990f22022-06-15 00:46:43 +00003370 if (!isSingleDeviceType(deviceTypes, audio_is_output_device)) {
François Gaffiecfe17322018-11-07 13:41:29 +01003371 return BAD_VALUE;
3372 }
jiabin9a3361e2019-10-01 09:38:30 -07003373 index = curves.getVolumeIndex(deviceTypes);
3374 ALOGV("%s: device %s index %d", __FUNCTION__, dumpDeviceTypes(deviceTypes).c_str(), index);
François Gaffiecfe17322018-11-07 13:41:29 +01003375 return NO_ERROR;
3376}
3377
3378status_t AudioPolicyManager::getMinVolumeIndexForAttributes(const audio_attributes_t &attr,
3379 int &index)
3380{
3381 index = getVolumeCurves(attr).getVolumeIndexMin();
3382 return NO_ERROR;
3383}
3384
3385status_t AudioPolicyManager::getMaxVolumeIndexForAttributes(const audio_attributes_t &attr,
3386 int &index)
3387{
3388 index = getVolumeCurves(attr).getVolumeIndexMax();
3389 return NO_ERROR;
3390}
3391
Eric Laurent36829f92017-04-07 19:04:42 -07003392audio_io_handle_t AudioPolicyManager::selectOutputForMusicEffects()
Eric Laurente552edb2014-03-10 17:42:56 -07003393{
3394 // select one output among several suitable for global effects.
3395 // The priority is as follows:
3396 // 1: An offloaded output. If the effect ends up not being offloadable,
3397 // AudioFlinger will invalidate the track and the offloaded output
3398 // will be closed causing the effect to be moved to a PCM output.
3399 // 2: A deep buffer output
Eric Laurent36829f92017-04-07 19:04:42 -07003400 // 3: The primary output
3401 // 4: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07003402
François Gaffiec005e562018-11-06 15:04:49 +01003403 DeviceVector devices = mEngine->getOutputDevicesForAttributes(
3404 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
François Gaffie11d30102018-11-02 16:09:09 +01003405 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07003406
Eric Laurent36829f92017-04-07 19:04:42 -07003407 if (outputs.size() == 0) {
3408 return AUDIO_IO_HANDLE_NONE;
3409 }
Eric Laurente552edb2014-03-10 17:42:56 -07003410
Eric Laurent36829f92017-04-07 19:04:42 -07003411 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
3412 bool activeOnly = true;
3413
3414 while (output == AUDIO_IO_HANDLE_NONE) {
3415 audio_io_handle_t outputOffloaded = AUDIO_IO_HANDLE_NONE;
3416 audio_io_handle_t outputDeepBuffer = AUDIO_IO_HANDLE_NONE;
3417 audio_io_handle_t outputPrimary = AUDIO_IO_HANDLE_NONE;
3418
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003419 for (audio_io_handle_t output : outputs) {
3420 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
Eric Laurent83d17c22019-04-02 17:10:01 -07003421 if (activeOnly && !desc->isActive(toVolumeSource(AUDIO_STREAM_MUSIC))) {
Eric Laurent36829f92017-04-07 19:04:42 -07003422 continue;
3423 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003424 ALOGV("selectOutputForMusicEffects activeOnly %d output %d flags 0x%08x",
3425 activeOnly, output, desc->mFlags);
Eric Laurent36829f92017-04-07 19:04:42 -07003426 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003427 outputOffloaded = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003428 }
3429 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003430 outputDeepBuffer = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003431 }
3432 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003433 outputPrimary = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003434 }
3435 }
3436 if (outputOffloaded != AUDIO_IO_HANDLE_NONE) {
3437 output = outputOffloaded;
3438 } else if (outputDeepBuffer != AUDIO_IO_HANDLE_NONE) {
3439 output = outputDeepBuffer;
3440 } else if (outputPrimary != AUDIO_IO_HANDLE_NONE) {
3441 output = outputPrimary;
3442 } else {
3443 output = outputs[0];
3444 }
3445 activeOnly = false;
3446 }
3447
3448 if (output != mMusicEffectOutput) {
Eric Laurent6c796322019-04-09 14:13:17 -07003449 mEffects.moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output);
Eric Laurent36829f92017-04-07 19:04:42 -07003450 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output);
3451 mMusicEffectOutput = output;
3452 }
3453
3454 ALOGV("selectOutputForMusicEffects selected output %d", output);
Eric Laurente552edb2014-03-10 17:42:56 -07003455 return output;
3456}
3457
Eric Laurent36829f92017-04-07 19:04:42 -07003458audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc __unused)
3459{
3460 return selectOutputForMusicEffects();
3461}
3462
Eric Laurente0720872014-03-11 09:30:41 -07003463status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07003464 audio_io_handle_t io,
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08003465 product_strategy_t strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07003466 int session,
3467 int id)
3468{
Eric Laurentb82e6b72019-11-22 17:25:04 -08003469 if (session != AUDIO_SESSION_DEVICE) {
3470 ssize_t index = mOutputs.indexOfKey(io);
Eric Laurente552edb2014-03-10 17:42:56 -07003471 if (index < 0) {
Eric Laurentb82e6b72019-11-22 17:25:04 -08003472 index = mInputs.indexOfKey(io);
3473 if (index < 0) {
3474 ALOGW("registerEffect() unknown io %d", io);
3475 return INVALID_OPERATION;
3476 }
Eric Laurente552edb2014-03-10 17:42:56 -07003477 }
3478 }
Eric Laurentbf8f69f2022-03-25 17:48:38 +01003479 bool isMusicEffect = (session != AUDIO_SESSION_OUTPUT_STAGE)
3480 && ((strategy == streamToStrategy(AUDIO_STREAM_MUSIC)
3481 || strategy == PRODUCT_STRATEGY_NONE));
3482 return mEffects.registerEffect(desc, io, session, id, isMusicEffect);
Eric Laurente552edb2014-03-10 17:42:56 -07003483}
3484
Eric Laurentc241b0d2018-11-28 09:08:49 -08003485status_t AudioPolicyManager::unregisterEffect(int id)
3486{
3487 if (mEffects.getEffect(id) == nullptr) {
3488 return INVALID_OPERATION;
3489 }
Eric Laurentc241b0d2018-11-28 09:08:49 -08003490 if (mEffects.isEffectEnabled(id)) {
3491 ALOGW("%s effect %d enabled", __FUNCTION__, id);
3492 setEffectEnabled(id, false);
3493 }
3494 return mEffects.unregisterEffect(id);
3495}
3496
3497status_t AudioPolicyManager::setEffectEnabled(int id, bool enabled)
3498{
3499 sp<EffectDescriptor> effect = mEffects.getEffect(id);
3500 if (effect == nullptr) {
3501 return INVALID_OPERATION;
3502 }
3503
3504 status_t status = mEffects.setEffectEnabled(id, enabled);
3505 if (status == NO_ERROR) {
3506 mInputs.trackEffectEnabled(effect, enabled);
3507 }
3508 return status;
3509}
3510
Eric Laurent6c796322019-04-09 14:13:17 -07003511
3512status_t AudioPolicyManager::moveEffectsToIo(const std::vector<int>& ids, audio_io_handle_t io)
3513{
3514 mEffects.moveEffects(ids, io);
3515 return NO_ERROR;
3516}
3517
Eric Laurentc75307b2015-03-17 15:29:32 -07003518bool AudioPolicyManager::isStreamActive(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.isActive(vs, inPastMs) : false;
Eric Laurentc75307b2015-03-17 15:29:32 -07003522}
3523
3524bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream, uint32_t inPastMs) const
3525{
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003526 auto vs = toVolumeSource(stream, false);
3527 return vs != VOLUME_SOURCE_NONE ? mOutputs.isActiveRemotely(vs, inPastMs) : false;
Eric Laurentc75307b2015-03-17 15:29:32 -07003528}
3529
Eric Laurente0720872014-03-11 09:30:41 -07003530bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07003531{
3532 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003533 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08003534 if (inputDescriptor->isSourceActive(source)) {
Eric Laurente552edb2014-03-10 17:42:56 -07003535 return true;
3536 }
3537 }
3538 return false;
3539}
3540
Eric Laurent275e8e92014-11-30 15:14:47 -08003541// Register a list of custom mixes with their attributes and format.
3542// When a mix is registered, corresponding input and output profiles are
3543// added to the remote submix hw module. The profile contains only the
3544// parameters (sampling rate, format...) specified by the mix.
3545// The corresponding input remote submix device is also connected.
3546//
3547// When a remote submix device is connected, the address is checked to select the
3548// appropriate profile and the corresponding input or output stream is opened.
3549//
3550// When capture starts, getInputForAttr() will:
3551// - 1 look for a mix matching the address passed in attribtutes tags if any
3552// - 2 if none found, getDeviceForInputSource() will:
3553// - 2.1 look for a mix matching the attributes source
3554// - 2.2 if none found, default to device selection by policy rules
3555// At this time, the corresponding output remote submix device is also connected
3556// and active playback use cases can be transferred to this mix if needed when reconnecting
3557// after AudioTracks are invalidated
3558//
3559// When playback starts, getOutputForAttr() will:
3560// - 1 look for a mix matching the address passed in attribtutes tags if any
3561// - 2 if none found, look for a mix matching the attributes usage
3562// - 3 if none found, default to device and output selection by policy rules.
3563
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003564status_t AudioPolicyManager::registerPolicyMixes(const Vector<AudioMix>& mixes)
Eric Laurent275e8e92014-11-30 15:14:47 -08003565{
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003566 ALOGV("registerPolicyMixes() %zu mix(es)", mixes.size());
3567 status_t res = NO_ERROR;
Eric Laurentc209fe42020-06-05 18:11:23 -07003568 bool checkOutputs = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003569 sp<HwModule> rSubmixModule;
3570 // examine each mix's route type
3571 for (size_t i = 0; i < mixes.size(); i++) {
Eric Laurent97ac8712018-07-27 18:59:02 -07003572 AudioMix mix = mixes[i];
Kevin Rocard153f92d2018-12-18 18:33:28 -08003573 // Only capture of playback is allowed in LOOP_BACK & RENDER mode
3574 if (is_mix_loopback_render(mix.mRouteFlags) && mix.mMixType != MIX_TYPE_PLAYERS) {
3575 ALOGE("Unsupported Policy Mix %zu of %zu: "
3576 "Only capture of playback is allowed in LOOP_BACK & RENDER mode",
3577 i, mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003578 res = INVALID_OPERATION;
Eric Laurent275e8e92014-11-30 15:14:47 -08003579 break;
3580 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08003581 // LOOP_BACK and LOOP_BACK | RENDER have the same remote submix backend and are handled
3582 // in the same way.
Eric Laurent97ac8712018-07-27 18:59:02 -07003583 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003584 ALOGV("registerPolicyMixes() mix %zu of %zu is LOOP_BACK %d", i, mixes.size(),
3585 mix.mRouteFlags);
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003586 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003587 rSubmixModule = mHwModules.getModuleFromName(
3588 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
3589 if (rSubmixModule == 0) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003590 ALOGE("Unable to find audio module for submix, aborting mix %zu registration",
Mikhail Naganovd4120142017-12-06 15:49:22 -08003591 i);
3592 res = INVALID_OPERATION;
3593 break;
3594 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003595 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003596
Eric Laurent97ac8712018-07-27 18:59:02 -07003597 String8 address = mix.mDeviceAddress;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003598 audio_devices_t deviceTypeToMakeAvailable;
Eric Laurent97ac8712018-07-27 18:59:02 -07003599 if (mix.mMixType == MIX_TYPE_PLAYERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07003600 mix.mDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003601 deviceTypeToMakeAvailable = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
3602 } else {
3603 mix.mDeviceType = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
3604 deviceTypeToMakeAvailable = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Eric Laurent97ac8712018-07-27 18:59:02 -07003605 }
François Gaffie036e1e92015-03-19 10:16:24 +01003606
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003607 if (mPolicyMixes.registerMix(mix, 0 /*output desc*/) != NO_ERROR) {
Tomasz Wasilczyk8f36f6e2023-08-15 20:59:35 +00003608 ALOGE("Error registering mix %zu for address %s", i, address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003609 res = INVALID_OPERATION;
3610 break;
3611 }
Eric Laurent97ac8712018-07-27 18:59:02 -07003612 audio_config_t outputConfig = mix.mFormat;
3613 audio_config_t inputConfig = mix.mFormat;
Eric Laurentc529cf62020-04-17 18:19:10 -07003614 // NOTE: audio flinger mixer does not support mono output: configure remote submix HAL
3615 // in stereo and let audio flinger do the channel conversion if needed.
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003616 outputConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
3617 inputConfig.channel_mask = AUDIO_CHANNEL_IN_STEREO;
jiabin5740f082019-08-19 15:08:30 -07003618 rSubmixModule->addOutputProfile(address.c_str(), &outputConfig,
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003619 AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address);
jiabin5740f082019-08-19 15:08:30 -07003620 rSubmixModule->addInputProfile(address.c_str(), &inputConfig,
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003621 AUDIO_DEVICE_IN_REMOTE_SUBMIX, address);
François Gaffie036e1e92015-03-19 10:16:24 +01003622
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003623 if ((res = setDeviceConnectionStateInt(deviceTypeToMakeAvailable,
jiabinc1de2df2019-05-07 14:26:40 -07003624 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Tomasz Wasilczyk8f36f6e2023-08-15 20:59:35 +00003625 address.c_str(), "remote-submix", AUDIO_FORMAT_DEFAULT)) != NO_ERROR) {
jiabinc1de2df2019-05-07 14:26:40 -07003626 ALOGE("Failed to set remote submix device available, type %u, address %s",
Tomasz Wasilczyk8f36f6e2023-08-15 20:59:35 +00003627 mix.mDeviceType, address.c_str());
jiabinc1de2df2019-05-07 14:26:40 -07003628 break;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003629 }
Eric Laurent97ac8712018-07-27 18:59:02 -07003630 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
3631 String8 address = mix.mDeviceAddress;
Eric Laurent2c80be02019-01-23 18:06:37 -08003632 audio_devices_t type = mix.mDeviceType;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003633 ALOGV(" registerPolicyMixes() mix %zu of %zu is RENDER, dev=0x%X addr=%s",
Tomasz Wasilczyk8f36f6e2023-08-15 20:59:35 +00003634 i, mixes.size(), type, address.c_str());
Eric Laurent2c80be02019-01-23 18:06:37 -08003635
3636 sp<DeviceDescriptor> device = mHwModules.getDeviceDescriptor(
3637 mix.mDeviceType, mix.mDeviceAddress,
3638 String8(), AUDIO_FORMAT_DEFAULT);
3639 if (device == nullptr) {
3640 res = INVALID_OPERATION;
3641 break;
3642 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003643
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003644 bool foundOutput = false;
Eric Laurentc529cf62020-04-17 18:19:10 -07003645 // First try to find an already opened output supporting the device
3646 for (size_t j = 0 ; j < mOutputs.size() && !foundOutput && res == NO_ERROR; j++) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003647 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurent2c80be02019-01-23 18:06:37 -08003648
Eric Laurentc529cf62020-04-17 18:19:10 -07003649 if (!desc->isDuplicated() && desc->supportedDevices().contains(device)) {
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003650 if (mPolicyMixes.registerMix(mix, desc) != NO_ERROR) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003651 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
Tomasz Wasilczyk8f36f6e2023-08-15 20:59:35 +00003652 address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003653 res = INVALID_OPERATION;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003654 } else {
3655 foundOutput = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003656 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003657 }
3658 }
Eric Laurentc529cf62020-04-17 18:19:10 -07003659 // If no output found, try to find a direct output profile supporting the device
3660 for (size_t i = 0; i < mHwModules.size() && !foundOutput && res == NO_ERROR; i++) {
3661 sp<HwModule> module = mHwModules[i];
3662 for (size_t j = 0;
3663 j < module->getOutputProfiles().size() && !foundOutput && res == NO_ERROR;
3664 j++) {
3665 sp<IOProfile> profile = module->getOutputProfiles()[j];
3666 if (profile->isDirectOutput() && profile->supportsDevice(device)) {
3667 if (mPolicyMixes.registerMix(mix, nullptr) != NO_ERROR) {
3668 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
Tomasz Wasilczyk8f36f6e2023-08-15 20:59:35 +00003669 address.c_str());
Eric Laurentc529cf62020-04-17 18:19:10 -07003670 res = INVALID_OPERATION;
3671 } else {
3672 foundOutput = true;
3673 }
3674 }
3675 }
3676 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003677 if (res != NO_ERROR) {
3678 ALOGE(" Error registering mix %zu for device 0x%X addr %s",
Tomasz Wasilczyk8f36f6e2023-08-15 20:59:35 +00003679 i, type, address.c_str());
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003680 res = INVALID_OPERATION;
3681 break;
3682 } else if (!foundOutput) {
3683 ALOGE(" Output not found for mix %zu for device 0x%X addr %s",
Tomasz Wasilczyk8f36f6e2023-08-15 20:59:35 +00003684 i, type, address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003685 res = INVALID_OPERATION;
3686 break;
Eric Laurentc209fe42020-06-05 18:11:23 -07003687 } else {
3688 checkOutputs = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003689 }
Eric Laurentc722f302014-12-10 11:21:49 -08003690 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003691 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003692 if (res != NO_ERROR) {
3693 unregisterPolicyMixes(mixes);
Eric Laurentc209fe42020-06-05 18:11:23 -07003694 } else if (checkOutputs) {
3695 checkForDeviceAndOutputChanges();
3696 updateCallAndOutputRouting();
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003697 }
3698 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08003699}
3700
3701status_t AudioPolicyManager::unregisterPolicyMixes(Vector<AudioMix> mixes)
3702{
Eric Laurent7b279bb2015-12-14 10:18:23 -08003703 ALOGV("unregisterPolicyMixes() num mixes %zu", mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003704 status_t res = NO_ERROR;
Eric Laurentc209fe42020-06-05 18:11:23 -07003705 bool checkOutputs = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003706 sp<HwModule> rSubmixModule;
3707 // examine each mix's route type
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003708 for (const auto& mix : mixes) {
3709 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie036e1e92015-03-19 10:16:24 +01003710
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003711 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003712 rSubmixModule = mHwModules.getModuleFromName(
3713 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
3714 if (rSubmixModule == 0) {
3715 res = INVALID_OPERATION;
3716 continue;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003717 }
3718 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003719
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003720 String8 address = mix.mDeviceAddress;
Eric Laurent275e8e92014-11-30 15:14:47 -08003721
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003722 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003723 res = INVALID_OPERATION;
3724 continue;
3725 }
3726
Kevin Rocard04ed0462019-05-02 17:53:24 -07003727 for (auto device : {AUDIO_DEVICE_IN_REMOTE_SUBMIX, AUDIO_DEVICE_OUT_REMOTE_SUBMIX}) {
Tomasz Wasilczyk8f36f6e2023-08-15 20:59:35 +00003728 if (getDeviceConnectionState(device, address.c_str()) ==
Kevin Rocard04ed0462019-05-02 17:53:24 -07003729 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
3730 res = setDeviceConnectionStateInt(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Tomasz Wasilczyk8f36f6e2023-08-15 20:59:35 +00003731 address.c_str(), "remote-submix",
Kevin Rocard04ed0462019-05-02 17:53:24 -07003732 AUDIO_FORMAT_DEFAULT);
3733 if (res != OK) {
3734 ALOGE("Error making RemoteSubmix device unavailable for mix "
Tomasz Wasilczyk8f36f6e2023-08-15 20:59:35 +00003735 "with type %d, address %s", device, address.c_str());
Kevin Rocard04ed0462019-05-02 17:53:24 -07003736 }
3737 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003738 }
jiabin5740f082019-08-19 15:08:30 -07003739 rSubmixModule->removeOutputProfile(address.c_str());
3740 rSubmixModule->removeInputProfile(address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003741
Kevin Rocard153f92d2018-12-18 18:33:28 -08003742 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003743 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003744 res = INVALID_OPERATION;
3745 continue;
Eric Laurentc209fe42020-06-05 18:11:23 -07003746 } else {
3747 checkOutputs = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003748 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003749 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003750 }
Eric Laurentc209fe42020-06-05 18:11:23 -07003751 if (res == NO_ERROR && checkOutputs) {
3752 checkForDeviceAndOutputChanges();
3753 updateCallAndOutputRouting();
3754 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003755 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08003756}
3757
Mikhail Naganov100f0122018-11-29 11:22:16 -08003758void AudioPolicyManager::dumpManualSurroundFormats(String8 *dst) const
3759{
3760 size_t i = 0;
3761 constexpr size_t audioFormatPrefixLen = sizeof("AUDIO_FORMAT_");
3762 for (const auto& fmt : mManualSurroundFormats) {
3763 if (i++ != 0) dst->append(", ");
3764 std::string sfmt;
3765 FormatConverter::toString(fmt, sfmt);
3766 dst->append(sfmt.size() >= audioFormatPrefixLen ?
3767 sfmt.c_str() + audioFormatPrefixLen - 1 : sfmt.c_str());
3768 }
3769}
3770
Eric Laurentc529cf62020-04-17 18:19:10 -07003771// Returns true if all devices types match the predicate and are supported by one HW module
3772bool AudioPolicyManager::areAllDevicesSupported(
jiabin6a02d532020-08-07 11:56:38 -07003773 const AudioDeviceTypeAddrVector& devices,
Eric Laurentc529cf62020-04-17 18:19:10 -07003774 std::function<bool(audio_devices_t)> predicate,
Eric Laurent78fedbf2023-03-09 14:40:44 +01003775 const char *context,
3776 bool matchAddress) {
Eric Laurentc529cf62020-04-17 18:19:10 -07003777 for (size_t i = 0; i < devices.size(); i++) {
3778 sp<DeviceDescriptor> devDesc = mHwModules.getDeviceDescriptor(
jiabin0a488932020-08-07 17:32:40 -07003779 devices[i].mType, devices[i].getAddress(), String8(),
Eric Laurent78fedbf2023-03-09 14:40:44 +01003780 AUDIO_FORMAT_DEFAULT, false /*allowToCreate*/, matchAddress);
Eric Laurentc529cf62020-04-17 18:19:10 -07003781 if (devDesc == nullptr || (predicate != nullptr && !predicate(devices[i].mType))) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003782 ALOGE("%s: device type %#x address %s not supported or not match predicate",
jiabin0a488932020-08-07 17:32:40 -07003783 context, devices[i].mType, devices[i].getAddress());
Eric Laurentc529cf62020-04-17 18:19:10 -07003784 return false;
3785 }
3786 }
3787 return true;
3788}
3789
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003790status_t AudioPolicyManager::setUidDeviceAffinities(uid_t uid,
jiabin6a02d532020-08-07 11:56:38 -07003791 const AudioDeviceTypeAddrVector& devices) {
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003792 ALOGV("%s() uid=%d num devices %zu", __FUNCTION__, uid, devices.size());
Eric Laurentc529cf62020-04-17 18:19:10 -07003793 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
3794 return BAD_VALUE;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003795 }
3796 status_t res = mPolicyMixes.setUidDeviceAffinities(uid, devices);
Eric Laurentc529cf62020-04-17 18:19:10 -07003797 if (res != NO_ERROR) {
3798 ALOGE("%s() Could not set all device affinities for uid = %d", __FUNCTION__, uid);
3799 return res;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003800 }
Eric Laurentc529cf62020-04-17 18:19:10 -07003801
3802 checkForDeviceAndOutputChanges();
3803 updateCallAndOutputRouting();
3804
3805 return NO_ERROR;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003806}
3807
3808status_t AudioPolicyManager::removeUidDeviceAffinities(uid_t uid) {
3809 ALOGV("%s() uid=%d", __FUNCTION__, uid);
Oscar Azucena4b2a8212019-04-26 23:48:59 -07003810 status_t res = mPolicyMixes.removeUidDeviceAffinities(uid);
3811 if (res != NO_ERROR) {
Eric Laurentc529cf62020-04-17 18:19:10 -07003812 ALOGE("%s() Could not remove all device affinities for uid = %d",
Oscar Azucena4b2a8212019-04-26 23:48:59 -07003813 __FUNCTION__, uid);
3814 return INVALID_OPERATION;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003815 }
3816
Eric Laurentc529cf62020-04-17 18:19:10 -07003817 checkForDeviceAndOutputChanges();
3818 updateCallAndOutputRouting();
3819
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003820 return res;
3821}
3822
Eric Laurent2517af32020-11-25 15:31:27 +01003823
jiabin0a488932020-08-07 17:32:40 -07003824status_t AudioPolicyManager::setDevicesRoleForStrategy(product_strategy_t strategy,
3825 device_role_t role,
3826 const AudioDeviceTypeAddrVector &devices) {
3827 ALOGV("%s() strategy=%d role=%d %s", __func__, strategy, role,
3828 dumpAudioDeviceTypeAddrVector(devices).c_str());
Eric Laurentc529cf62020-04-17 18:19:10 -07003829
Eric Laurentc529cf62020-04-17 18:19:10 -07003830 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003831 return BAD_VALUE;
3832 }
jiabin0a488932020-08-07 17:32:40 -07003833 status_t status = mEngine->setDevicesRoleForStrategy(strategy, role, devices);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003834 if (status != NO_ERROR) {
jiabin0a488932020-08-07 17:32:40 -07003835 ALOGW("Engine could not set preferred devices %s for strategy %d role %d",
3836 dumpAudioDeviceTypeAddrVector(devices).c_str(), strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003837 return status;
3838 }
3839
3840 checkForDeviceAndOutputChanges();
Eric Laurent2517af32020-11-25 15:31:27 +01003841
3842 bool forceVolumeReeval = false;
3843 // FIXME: workaround for truncated touch sounds
3844 // to be removed when the problem is handled by system UI
3845 uint32_t delayMs = 0;
3846 if (strategy == mCommunnicationStrategy) {
3847 forceVolumeReeval = true;
3848 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
3849 updateInputRouting();
3850 }
3851 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003852
3853 return NO_ERROR;
3854}
3855
3856void AudioPolicyManager::updateCallAndOutputRouting(bool forceVolumeReeval, uint32_t delayMs)
3857{
3858 uint32_t waitMs = 0;
Eric Laurent96d1dda2022-03-14 17:14:19 +01003859 bool wasLeUnicastActive = isLeUnicastActive();
Francois Gaffie19fd6c52021-02-04 17:02:59 +01003860 if (updateCallRouting(true /*fromCache*/, delayMs, &waitMs) == NO_ERROR) {
Eric Laurentb36b4ac2020-08-21 12:50:41 -07003861 // Only apply special touch sound delay once
3862 delayMs = 0;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003863 }
jiabin3ff8d7d2022-12-13 06:27:44 +00003864 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003865 for (size_t i = 0; i < mOutputs.size(); i++) {
3866 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
3867 DeviceVector newDevices = getNewOutputDevices(outputDesc, true /*fromCache*/);
Francois Gaffie601801d2021-06-22 13:27:39 +02003868 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) ||
3869 (outputDesc != mPrimaryOutput && !isTelephonyRxOrTx(outputDesc))) {
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003870 // As done in setDeviceConnectionState, we could also fix default device issue by
3871 // preventing the force re-routing in case of default dev that distinguishes on address.
3872 // Let's give back to engine full device choice decision however.
Francois Gaffie601801d2021-06-22 13:27:39 +02003873 bool forceRouting = !newDevices.isEmpty();
jiabin3ff8d7d2022-12-13 06:27:44 +00003874 if (outputDesc->mUsePreferredMixerAttributes && newDevices != outputDesc->devices()) {
3875 // If the device is using preferred mixer attributes, the output need to reopen
3876 // with default configuration when the new selected devices are different from
3877 // current routing devices.
3878 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices);
3879 continue;
3880 }
Francois Gaffie601801d2021-06-22 13:27:39 +02003881 waitMs = setOutputDevices(outputDesc, newDevices, forceRouting, delayMs, nullptr,
3882 true /*requiresMuteCheck*/,
3883 !forceRouting /*requiresVolumeCheck*/);
Eric Laurentb36b4ac2020-08-21 12:50:41 -07003884 // Only apply special touch sound delay once
3885 delayMs = 0;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003886 }
3887 if (forceVolumeReeval && !newDevices.isEmpty()) {
3888 applyStreamVolumes(outputDesc, newDevices.types(), waitMs, true);
3889 }
3890 }
jiabin3ff8d7d2022-12-13 06:27:44 +00003891 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent96d1dda2022-03-14 17:14:19 +01003892 checkLeBroadcastRoutes(wasLeUnicastActive, nullptr, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003893}
3894
Eric Laurent2517af32020-11-25 15:31:27 +01003895void AudioPolicyManager::updateInputRouting() {
3896 for (const auto& activeDesc : mInputs.getActiveInputs()) {
Jaideep Sharma408349a2020-11-27 14:47:17 +05303897 // Skip for hotword recording as the input device switch
3898 // is handled within sound trigger HAL
3899 if (activeDesc->isSoundTrigger() && activeDesc->source() == AUDIO_SOURCE_HOTWORD) {
3900 continue;
3901 }
Eric Laurent2517af32020-11-25 15:31:27 +01003902 auto newDevice = getNewInputDevice(activeDesc);
3903 // Force new input selection if the new device can not be reached via current input
3904 if (activeDesc->mProfile->getSupportedDevices().contains(newDevice)) {
3905 setInputDevice(activeDesc->mIoHandle, newDevice);
3906 } else {
3907 closeInput(activeDesc->mIoHandle);
3908 }
3909 }
3910}
3911
Paul Wang5d7cdb52022-11-22 09:45:06 +00003912status_t
3913AudioPolicyManager::removeDevicesRoleForStrategy(product_strategy_t strategy,
3914 device_role_t role,
3915 const AudioDeviceTypeAddrVector &devices) {
3916 ALOGV("%s() strategy=%d role=%d %s", __func__, strategy, role,
3917 dumpAudioDeviceTypeAddrVector(devices).c_str());
3918
Eric Laurent78fedbf2023-03-09 14:40:44 +01003919 if (!areAllDevicesSupported(
3920 devices, audio_is_output_device, __func__, /*matchAddress*/false)) {
Paul Wang5d7cdb52022-11-22 09:45:06 +00003921 return BAD_VALUE;
3922 }
3923 status_t status = mEngine->removeDevicesRoleForStrategy(strategy, role, devices);
3924 if (status != NO_ERROR) {
3925 ALOGW("Engine could not remove devices %s for strategy %d role %d",
3926 dumpAudioDeviceTypeAddrVector(devices).c_str(), strategy, role);
3927 return status;
3928 }
3929
3930 checkForDeviceAndOutputChanges();
3931
3932 bool forceVolumeReeval = false;
3933 // TODO(b/263479999): workaround for truncated touch sounds
3934 // to be removed when the problem is handled by system UI
3935 uint32_t delayMs = 0;
3936 if (strategy == mCommunnicationStrategy) {
3937 forceVolumeReeval = true;
3938 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
3939 updateInputRouting();
3940 }
3941 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
3942
3943 return NO_ERROR;
3944}
3945
3946status_t AudioPolicyManager::clearDevicesRoleForStrategy(product_strategy_t strategy,
3947 device_role_t role)
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003948{
Eric Laurentfecbceb2021-02-09 14:46:43 +01003949 ALOGV("%s() strategy=%d role=%d", __func__, strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003950
Paul Wang5d7cdb52022-11-22 09:45:06 +00003951 status_t status = mEngine->clearDevicesRoleForStrategy(strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003952 if (status != NO_ERROR) {
Eric Laurent9ae44f32022-12-14 16:17:02 +01003953 ALOGW_IF(status != NAME_NOT_FOUND,
3954 "Engine could not remove device role for strategy %d status %d",
Eric Laurent2517af32020-11-25 15:31:27 +01003955 strategy, status);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003956 return status;
3957 }
3958
3959 checkForDeviceAndOutputChanges();
Eric Laurent2517af32020-11-25 15:31:27 +01003960
3961 bool forceVolumeReeval = false;
3962 // FIXME: workaround for truncated touch sounds
3963 // to be removed when the problem is handled by system UI
3964 uint32_t delayMs = 0;
3965 if (strategy == mCommunnicationStrategy) {
3966 forceVolumeReeval = true;
3967 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
3968 updateInputRouting();
3969 }
3970 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003971
3972 return NO_ERROR;
3973}
3974
jiabin0a488932020-08-07 17:32:40 -07003975status_t AudioPolicyManager::getDevicesForRoleAndStrategy(product_strategy_t strategy,
3976 device_role_t role,
3977 AudioDeviceTypeAddrVector &devices) {
3978 return mEngine->getDevicesForRoleAndStrategy(strategy, role, devices);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003979}
3980
Jiabin Huang3b98d322020-09-03 17:54:16 +00003981status_t AudioPolicyManager::setDevicesRoleForCapturePreset(
3982 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices) {
3983 ALOGV("%s() audioSource=%d role=%d %s", __func__, audioSource, role,
3984 dumpAudioDeviceTypeAddrVector(devices).c_str());
3985
Mikhail Naganov55773032020-10-01 15:08:13 -07003986 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003987 return BAD_VALUE;
3988 }
3989 status_t status = mEngine->setDevicesRoleForCapturePreset(audioSource, role, devices);
3990 ALOGW_IF(status != NO_ERROR,
3991 "Engine could not set preferred devices %s for audio source %d role %d",
3992 dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
3993
3994 return status;
3995}
3996
3997status_t AudioPolicyManager::addDevicesRoleForCapturePreset(
3998 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices) {
3999 ALOGV("%s() audioSource=%d role=%d %s", __func__, audioSource, role,
4000 dumpAudioDeviceTypeAddrVector(devices).c_str());
4001
Mikhail Naganov55773032020-10-01 15:08:13 -07004002 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00004003 return BAD_VALUE;
4004 }
4005 status_t status = mEngine->addDevicesRoleForCapturePreset(audioSource, role, devices);
4006 ALOGW_IF(status != NO_ERROR,
4007 "Engine could not add preferred devices %s for audio source %d role %d",
4008 dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
4009
Eric Laurent2517af32020-11-25 15:31:27 +01004010 updateInputRouting();
Jiabin Huang3b98d322020-09-03 17:54:16 +00004011 return status;
4012}
4013
4014status_t AudioPolicyManager::removeDevicesRoleForCapturePreset(
4015 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector& devices)
4016{
4017 ALOGV("%s() audioSource=%d role=%d devices=%s", __func__, audioSource, role,
4018 dumpAudioDeviceTypeAddrVector(devices).c_str());
4019
Eric Laurent78fedbf2023-03-09 14:40:44 +01004020 if (!areAllDevicesSupported(
4021 devices, audio_call_is_input_device, __func__, /*matchAddress*/false)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00004022 return BAD_VALUE;
4023 }
4024
4025 status_t status = mEngine->removeDevicesRoleForCapturePreset(
4026 audioSource, role, devices);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004027 ALOGW_IF(status != NO_ERROR && status != NAME_NOT_FOUND,
Jiabin Huang3b98d322020-09-03 17:54:16 +00004028 "Engine could not remove devices role (%d) for capture preset %d", role, audioSource);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004029 if (status == NO_ERROR) {
4030 updateInputRouting();
4031 }
Jiabin Huang3b98d322020-09-03 17:54:16 +00004032 return status;
4033}
4034
4035status_t AudioPolicyManager::clearDevicesRoleForCapturePreset(audio_source_t audioSource,
4036 device_role_t role) {
4037 ALOGV("%s() audioSource=%d role=%d", __func__, audioSource, role);
4038
4039 status_t status = mEngine->clearDevicesRoleForCapturePreset(audioSource, role);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004040 ALOGW_IF(status != NO_ERROR && status != NAME_NOT_FOUND,
Jiabin Huang3b98d322020-09-03 17:54:16 +00004041 "Engine could not clear devices role (%d) for capture preset %d", role, audioSource);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004042 if (status == NO_ERROR) {
4043 updateInputRouting();
4044 }
Jiabin Huang3b98d322020-09-03 17:54:16 +00004045 return status;
4046}
4047
4048status_t AudioPolicyManager::getDevicesForRoleAndCapturePreset(
4049 audio_source_t audioSource, device_role_t role, AudioDeviceTypeAddrVector &devices) {
4050 return mEngine->getDevicesForRoleAndCapturePreset(audioSource, role, devices);
4051}
4052
Oscar Azucena90e77632019-11-27 17:12:28 -08004053status_t AudioPolicyManager::setUserIdDeviceAffinities(int userId,
jiabin6a02d532020-08-07 11:56:38 -07004054 const AudioDeviceTypeAddrVector& devices) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01004055 ALOGV("%s() userId=%d num devices %zu", __func__, userId, devices.size());
Eric Laurentc529cf62020-04-17 18:19:10 -07004056 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
4057 return BAD_VALUE;
Oscar Azucena90e77632019-11-27 17:12:28 -08004058 }
Oscar Azucena90e77632019-11-27 17:12:28 -08004059 status_t status = mPolicyMixes.setUserIdDeviceAffinities(userId, devices);
4060 if (status != NO_ERROR) {
4061 ALOGE("%s() could not set device affinity for userId %d",
4062 __FUNCTION__, userId);
4063 return status;
4064 }
4065
4066 // reevaluate outputs for all devices
4067 checkForDeviceAndOutputChanges();
4068 updateCallAndOutputRouting();
4069
4070 return NO_ERROR;
4071}
4072
4073status_t AudioPolicyManager::removeUserIdDeviceAffinities(int userId) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01004074 ALOGV("%s() userId=%d", __FUNCTION__, userId);
Oscar Azucena90e77632019-11-27 17:12:28 -08004075 status_t status = mPolicyMixes.removeUserIdDeviceAffinities(userId);
4076 if (status != NO_ERROR) {
4077 ALOGE("%s() Could not remove all device affinities fo userId = %d",
4078 __FUNCTION__, userId);
4079 return status;
4080 }
4081
4082 // reevaluate outputs for all devices
4083 checkForDeviceAndOutputChanges();
4084 updateCallAndOutputRouting();
4085
4086 return NO_ERROR;
4087}
4088
Andy Hungc29d82b2018-10-05 12:23:17 -07004089void AudioPolicyManager::dump(String8 *dst) const
Eric Laurente552edb2014-03-10 17:42:56 -07004090{
Andy Hungc29d82b2018-10-05 12:23:17 -07004091 dst->appendFormat("\nAudioPolicyManager Dump: %p\n", this);
Mikhail Naganov0dbe87b2021-12-01 02:03:31 +00004092 dst->appendFormat(" Primary Output I/O handle: %d\n",
Eric Laurent87ffa392015-05-22 10:32:38 -07004093 hasPrimaryOutput() ? mPrimaryOutput->mIoHandle : AUDIO_IO_HANDLE_NONE);
Mikhail Naganov0d6a0332016-04-19 17:12:38 -07004094 std::string stateLiteral;
4095 AudioModeConverter::toString(mEngine->getPhoneState(), stateLiteral);
Andy Hungc29d82b2018-10-05 12:23:17 -07004096 dst->appendFormat(" Phone state: %s\n", stateLiteral.c_str());
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07004097 const char* forceUses[AUDIO_POLICY_FORCE_USE_CNT] = {
4098 "communications", "media", "record", "dock", "system",
4099 "HDMI system audio", "encoded surround output", "vibrate ringing" };
4100 for (audio_policy_force_use_t i = AUDIO_POLICY_FORCE_FOR_COMMUNICATION;
4101 i < AUDIO_POLICY_FORCE_USE_CNT; i = (audio_policy_force_use_t)((int)i + 1)) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08004102 audio_policy_forced_cfg_t forceUseValue = mEngine->getForceUse(i);
4103 dst->appendFormat(" Force use for %s: %d", forceUses[i], forceUseValue);
4104 if (i == AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND &&
4105 forceUseValue == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
4106 dst->append(" (MANUAL: ");
4107 dumpManualSurroundFormats(dst);
4108 dst->append(")");
4109 }
4110 dst->append("\n");
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07004111 }
Andy Hungc29d82b2018-10-05 12:23:17 -07004112 dst->appendFormat(" TTS output %savailable\n", mTtsOutputAvailable ? "" : "not ");
4113 dst->appendFormat(" Master mono: %s\n", mMasterMono ? "on" : "off");
Mikhail Naganovb3bcb4f2022-02-23 23:46:56 +00004114 dst->appendFormat(" Communication Strategy id: %d\n", mCommunnicationStrategy);
Mikhail Naganovb0fbc1b2023-04-28 13:06:32 -07004115 dst->appendFormat(" Config source: %s\n", mConfig->getSource().c_str());
Eric Laurent2517af32020-11-25 15:31:27 +01004116
Mikhail Naganov0f413b22021-12-02 05:29:27 +00004117 dst->append("\n");
4118 mAvailableOutputDevices.dump(dst, String8("Available output"), 1);
4119 dst->append("\n");
4120 mAvailableInputDevices.dump(dst, String8("Available input"), 1);
Mikhail Naganovb0fbc1b2023-04-28 13:06:32 -07004121 mHwModules.dump(dst);
Andy Hungc29d82b2018-10-05 12:23:17 -07004122 mOutputs.dump(dst);
4123 mInputs.dump(dst);
Mikhail Naganov0f413b22021-12-02 05:29:27 +00004124 mEffects.dump(dst, 1);
Andy Hungc29d82b2018-10-05 12:23:17 -07004125 mAudioPatches.dump(dst);
4126 mPolicyMixes.dump(dst);
4127 mAudioSources.dump(dst);
François Gaffiec005e562018-11-06 15:04:49 +01004128
Kevin Rocardb99cc752019-03-21 20:52:24 -07004129 dst->appendFormat(" AllowedCapturePolicies:\n");
4130 for (auto& policy : mAllowedCapturePolicies) {
4131 dst->appendFormat(" - uid=%d flag_mask=%#x\n", policy.first, policy.second);
4132 }
4133
jiabina84c3d32022-12-02 18:59:55 +00004134 dst->appendFormat(" Preferred mixer audio configuration:\n");
4135 for (const auto it : mPreferredMixerAttrInfos) {
4136 dst->appendFormat(" - device port id: %d\n", it.first);
4137 for (const auto preferredMixerInfoIt : it.second) {
4138 dst->appendFormat(" - strategy: %d; ", preferredMixerInfoIt.first);
4139 preferredMixerInfoIt.second->dump(dst);
4140 }
4141 }
4142
François Gaffiec005e562018-11-06 15:04:49 +01004143 dst->appendFormat("\nPolicy Engine dump:\n");
4144 mEngine->dump(dst);
Andy Hungc29d82b2018-10-05 12:23:17 -07004145}
4146
4147status_t AudioPolicyManager::dump(int fd)
4148{
4149 String8 result;
4150 dump(&result);
Tomasz Wasilczyk8f36f6e2023-08-15 20:59:35 +00004151 write(fd, result.c_str(), result.size());
Eric Laurente552edb2014-03-10 17:42:56 -07004152 return NO_ERROR;
4153}
4154
Kevin Rocardb99cc752019-03-21 20:52:24 -07004155status_t AudioPolicyManager::setAllowedCapturePolicy(uid_t uid, audio_flags_mask_t capturePolicy)
4156{
4157 mAllowedCapturePolicies[uid] = capturePolicy;
4158 return NO_ERROR;
4159}
4160
Eric Laurente552edb2014-03-10 17:42:56 -07004161// This function checks for the parameters which can be offloaded.
4162// This can be enhanced depending on the capability of the DSP and policy
4163// of the system.
Eric Laurent90fe31c2020-11-26 20:06:35 +01004164audio_offload_mode_t AudioPolicyManager::getOffloadSupport(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07004165{
Eric Laurent90fe31c2020-11-26 20:06:35 +01004166 ALOGV("%s: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07004167 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurent90fe31c2020-11-26 20:06:35 +01004168 __func__, offloadInfo.sample_rate, offloadInfo.channel_mask,
Eric Laurente552edb2014-03-10 17:42:56 -07004169 offloadInfo.format,
4170 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
4171 offloadInfo.has_video);
4172
jiabin2b9d5a12021-12-10 01:06:29 +00004173 if (!isOffloadPossible(offloadInfo)) {
Eric Laurent90fe31c2020-11-26 20:06:35 +01004174 return AUDIO_OFFLOAD_NOT_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07004175 }
4176
4177 // See if there is a profile to support this.
4178 // AUDIO_DEVICE_NONE
François Gaffie11d30102018-11-02 16:09:09 +01004179 sp<IOProfile> profile = getProfileForOutput(DeviceVector() /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07004180 offloadInfo.sample_rate,
4181 offloadInfo.format,
4182 offloadInfo.channel_mask,
Michael Chana94fbb22018-04-24 14:31:19 +10004183 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD,
4184 true /* directOnly */);
Eric Laurent94365442021-01-08 18:36:05 +01004185 ALOGV("%s: profile %sfound%s", __func__, profile != nullptr ? "" : "NOT ",
4186 (profile != nullptr && (profile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD) != 0)
4187 ? ", supports gapless" : "");
Eric Laurent90fe31c2020-11-26 20:06:35 +01004188 if (profile == nullptr) {
4189 return AUDIO_OFFLOAD_NOT_SUPPORTED;
4190 }
4191 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD) != 0) {
4192 return AUDIO_OFFLOAD_GAPLESS_SUPPORTED;
4193 }
4194 return AUDIO_OFFLOAD_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07004195}
4196
Michael Chana94fbb22018-04-24 14:31:19 +10004197bool AudioPolicyManager::isDirectOutputSupported(const audio_config_base_t& config,
4198 const audio_attributes_t& attributes) {
4199 audio_output_flags_t output_flags = AUDIO_OUTPUT_FLAG_NONE;
François Gaffie58d4be52018-11-06 15:30:12 +01004200 audio_flags_to_audio_output_flags(attributes.flags, &output_flags);
Dorin Drimus9901eb02022-01-14 11:36:51 +00004201 DeviceVector outputDevices = mEngine->getOutputDevicesForAttributes(attributes);
4202 sp<IOProfile> profile = getProfileForOutput(outputDevices,
Michael Chana94fbb22018-04-24 14:31:19 +10004203 config.sample_rate,
4204 config.format,
4205 config.channel_mask,
4206 output_flags,
4207 true /* directOnly */);
4208 ALOGV("%s() profile %sfound with name: %s, "
4209 "sample rate: %u, format: 0x%x, channel_mask: 0x%x, output flags: 0x%x",
4210 __FUNCTION__, profile != 0 ? "" : "NOT ",
jiabin5740f082019-08-19 15:08:30 -07004211 (profile != 0 ? profile->getTagName().c_str() : "null"),
Michael Chana94fbb22018-04-24 14:31:19 +10004212 config.sample_rate, config.format, config.channel_mask, output_flags);
Dorin Drimusecc9f422022-03-09 17:57:40 +01004213
4214 // also try the MSD module if compatible profile not found
4215 if (profile == nullptr) {
4216 profile = getMsdProfileForOutput(outputDevices,
4217 config.sample_rate,
4218 config.format,
4219 config.channel_mask,
4220 output_flags,
4221 true /* directOnly */);
4222 ALOGV("%s() MSD profile %sfound with name: %s, "
4223 "sample rate: %u, format: 0x%x, channel_mask: 0x%x, output flags: 0x%x",
4224 __FUNCTION__, profile != 0 ? "" : "NOT ",
4225 (profile != 0 ? profile->getTagName().c_str() : "null"),
4226 config.sample_rate, config.format, config.channel_mask, output_flags);
4227 }
4228 return (profile != nullptr);
Michael Chana94fbb22018-04-24 14:31:19 +10004229}
4230
jiabin2b9d5a12021-12-10 01:06:29 +00004231bool AudioPolicyManager::isOffloadPossible(const audio_offload_info_t &offloadInfo,
4232 bool durationIgnored) {
4233 if (mMasterMono) {
4234 return false; // no offloading if mono is set.
4235 }
4236
4237 // Check if offload has been disabled
4238 if (property_get_bool("audio.offload.disable", false /* default_value */)) {
4239 ALOGV("%s: offload disabled by audio.offload.disable", __func__);
4240 return false;
4241 }
4242
4243 // Check if stream type is music, then only allow offload as of now.
4244 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
4245 {
4246 ALOGV("%s: stream_type != MUSIC, returning false", __func__);
4247 return false;
4248 }
4249
4250 //TODO: enable audio offloading with video when ready
4251 const bool allowOffloadWithVideo =
4252 property_get_bool("audio.offload.video", false /* default_value */);
4253 if (offloadInfo.has_video && !allowOffloadWithVideo) {
4254 ALOGV("%s: has_video == true, returning false", __func__);
4255 return false;
4256 }
4257
4258 //If duration is less than minimum value defined in property, return false
4259 const int min_duration_secs = property_get_int32(
4260 "audio.offload.min.duration.secs", -1 /* default_value */);
4261 if (!durationIgnored) {
4262 if (min_duration_secs >= 0) {
4263 if (offloadInfo.duration_us < min_duration_secs * 1000000LL) {
4264 ALOGV("%s: Offload denied by duration < audio.offload.min.duration.secs(=%d)",
4265 __func__, min_duration_secs);
4266 return false;
4267 }
4268 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
4269 ALOGV("%s: Offload denied by duration < default min(=%u)",
4270 __func__, OFFLOAD_DEFAULT_MIN_DURATION_SECS);
4271 return false;
4272 }
4273 }
4274
4275 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
4276 // creating an offloaded track and tearing it down immediately after start when audioflinger
4277 // detects there is an active non offloadable effect.
4278 // FIXME: We should check the audio session here but we do not have it in this context.
4279 // This may prevent offloading in rare situations where effects are left active by apps
4280 // in the background.
4281 if (mEffects.isNonOffloadableEffectEnabled()) {
4282 return false;
4283 }
4284
4285 return true;
4286}
4287
4288audio_direct_mode_t AudioPolicyManager::getDirectPlaybackSupport(const audio_attributes_t *attr,
4289 const audio_config_t *config) {
4290 audio_offload_info_t offloadInfo = AUDIO_INFO_INITIALIZER;
4291 offloadInfo.format = config->format;
4292 offloadInfo.sample_rate = config->sample_rate;
4293 offloadInfo.channel_mask = config->channel_mask;
4294 offloadInfo.stream_type = mEngine->getStreamTypeForAttributes(*attr);
4295 offloadInfo.has_video = false;
4296 offloadInfo.is_streaming = false;
4297 const bool offloadPossible = isOffloadPossible(offloadInfo, true /*durationIgnored*/);
4298
4299 audio_direct_mode_t directMode = AUDIO_DIRECT_NOT_SUPPORTED;
4300 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
4301 audio_flags_to_audio_output_flags(attr->flags, &flags);
4302 // only retain flags that will drive compressed offload or passthrough
4303 uint32_t relevantFlags = AUDIO_OUTPUT_FLAG_HW_AV_SYNC;
4304 if (offloadPossible) {
4305 relevantFlags |= AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD;
4306 }
4307 flags = (audio_output_flags_t)((flags & relevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
4308
Dorin Drimusfae3c642022-03-17 18:36:30 +01004309 DeviceVector engineOutputDevices = mEngine->getOutputDevicesForAttributes(*attr);
jiabin2b9d5a12021-12-10 01:06:29 +00004310 for (const auto& hwModule : mHwModules) {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004311 DeviceVector outputDevices = engineOutputDevices;
4312 // the MSD module checks for different conditions and output devices
4313 if (strcmp(hwModule->getName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0) {
4314 if (!msdHasPatchesToAllDevices(engineOutputDevices.toTypeAddrVector())) {
4315 continue;
4316 }
4317 outputDevices = getMsdAudioOutDevices();
4318 }
jiabin2b9d5a12021-12-10 01:06:29 +00004319 for (const auto& curProfile : hwModule->getOutputProfiles()) {
jiabinc8f7dfc2022-01-06 18:42:08 +00004320 if (!curProfile->isCompatibleProfile(outputDevices,
jiabin2b9d5a12021-12-10 01:06:29 +00004321 config->sample_rate, nullptr /*updatedSamplingRate*/,
4322 config->format, nullptr /*updatedFormat*/,
4323 config->channel_mask, nullptr /*updatedChannelMask*/,
4324 flags)) {
4325 continue;
4326 }
4327 // reject profiles not corresponding to a device currently available
4328 if (!mAvailableOutputDevices.containsAtLeastOne(curProfile->getSupportedDevices())) {
4329 continue;
4330 }
Yinchu Chen9f667582023-10-10 09:44:54 +00004331 if (offloadPossible && ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)
4332 != AUDIO_OUTPUT_FLAG_NONE)) {
jiabinc6132d62022-01-01 07:36:31 +00004333 if ((directMode & AUDIO_DIRECT_OFFLOAD_GAPLESS_SUPPORTED)
jiabin2b9d5a12021-12-10 01:06:29 +00004334 != AUDIO_DIRECT_NOT_SUPPORTED) {
4335 // Already reports offload gapless supported. No need to report offload support.
4336 continue;
4337 }
4338 if ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD)
4339 != AUDIO_OUTPUT_FLAG_NONE) {
4340 // If offload gapless is reported, no need to report offload support.
4341 directMode = (audio_direct_mode_t) ((directMode &
4342 ~AUDIO_DIRECT_OFFLOAD_SUPPORTED) |
4343 AUDIO_DIRECT_OFFLOAD_GAPLESS_SUPPORTED);
4344 } else {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004345 directMode = (audio_direct_mode_t)(directMode | AUDIO_DIRECT_OFFLOAD_SUPPORTED);
jiabin2b9d5a12021-12-10 01:06:29 +00004346 }
4347 } else {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004348 directMode = (audio_direct_mode_t) (directMode | AUDIO_DIRECT_BITSTREAM_SUPPORTED);
jiabin2b9d5a12021-12-10 01:06:29 +00004349 }
4350 }
4351 }
4352 return directMode;
4353}
4354
Dorin Drimusf2196d82022-01-03 12:11:18 +01004355status_t AudioPolicyManager::getDirectProfilesForAttributes(const audio_attributes_t* attr,
4356 AudioProfileVector& audioProfilesVector) {
Dorin Drimus76e69572022-09-23 15:28:51 +00004357 if (mEffects.isNonOffloadableEffectEnabled()) {
4358 return OK;
4359 }
jiabinf1c73972022-04-14 16:28:52 -07004360 DeviceVector devices;
4361 status_t status = getDevicesForAttributes(*attr, devices, false /* forVolume */);
Dorin Drimusf2196d82022-01-03 12:11:18 +01004362 if (status != OK) {
4363 return status;
4364 }
4365 ALOGV("%s: found %zu output devices for attributes.", __func__, devices.size());
4366 if (devices.empty()) {
4367 return OK; // no output devices for the attributes
4368 }
jiabinf1c73972022-04-14 16:28:52 -07004369 return getProfilesForDevices(devices, audioProfilesVector,
4370 AUDIO_OUTPUT_FLAG_DIRECT /*flags*/, false /*isInput*/);
Dorin Drimusf2196d82022-01-03 12:11:18 +01004371}
Dorin Drimusf2196d82022-01-03 12:11:18 +01004372
jiabina84c3d32022-12-02 18:59:55 +00004373status_t AudioPolicyManager::getSupportedMixerAttributes(
4374 audio_port_handle_t portId, std::vector<audio_mixer_attributes_t> &mixerAttrs) {
4375 ALOGV("%s, portId=%d", __func__, portId);
4376 sp<DeviceDescriptor> deviceDescriptor = mAvailableOutputDevices.getDeviceFromId(portId);
4377 if (deviceDescriptor == nullptr) {
4378 ALOGE("%s the requested device is currently unavailable", __func__);
4379 return BAD_VALUE;
4380 }
jiabin96daffc2023-05-11 17:51:55 +00004381 if (!audio_is_usb_out_device(deviceDescriptor->type())) {
4382 ALOGE("%s the requested device(type=%#x) is not usb device", __func__,
4383 deviceDescriptor->type());
4384 return BAD_VALUE;
4385 }
Dorin Drimusf2196d82022-01-03 12:11:18 +01004386 for (const auto& hwModule : mHwModules) {
jiabina84c3d32022-12-02 18:59:55 +00004387 for (const auto& curProfile : hwModule->getOutputProfiles()) {
4388 if (curProfile->supportsDevice(deviceDescriptor)) {
4389 curProfile->toSupportedMixerAttributes(&mixerAttrs);
4390 }
4391 }
4392 }
4393 return NO_ERROR;
4394}
4395
4396status_t AudioPolicyManager::setPreferredMixerAttributes(
4397 const audio_attributes_t *attr,
4398 audio_port_handle_t portId,
4399 uid_t uid,
4400 const audio_mixer_attributes_t *mixerAttributes) {
4401 ALOGV("%s, attr=%s, mixerAttributes={format=%#x, channelMask=%#x, samplingRate=%u, "
4402 "mixerBehavior=%d}, uid=%d, portId=%u",
4403 __func__, toString(*attr).c_str(), mixerAttributes->config.format,
4404 mixerAttributes->config.channel_mask, mixerAttributes->config.sample_rate,
4405 mixerAttributes->mixer_behavior, uid, portId);
4406 if (attr->usage != AUDIO_USAGE_MEDIA) {
4407 ALOGE("%s failed, only media is allowed, the given usage is %d", __func__, attr->usage);
4408 return BAD_VALUE;
4409 }
4410 sp<DeviceDescriptor> deviceDescriptor = mAvailableOutputDevices.getDeviceFromId(portId);
4411 if (deviceDescriptor == nullptr) {
4412 ALOGE("%s the requested device is currently unavailable", __func__);
4413 return BAD_VALUE;
4414 }
4415 if (!audio_is_usb_out_device(deviceDescriptor->type())) {
4416 ALOGE("%s(%d), type=%d, is not a usb output device",
4417 __func__, portId, deviceDescriptor->type());
4418 return BAD_VALUE;
4419 }
4420
4421 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
4422 audio_flags_to_audio_output_flags(attr->flags, &flags);
4423 flags = (audio_output_flags_t) (flags |
4424 audio_output_flags_from_mixer_behavior(mixerAttributes->mixer_behavior));
4425 sp<IOProfile> profile = nullptr;
4426 DeviceVector devices(deviceDescriptor);
4427 for (const auto& hwModule : mHwModules) {
4428 for (const auto& curProfile : hwModule->getOutputProfiles()) {
4429 if (curProfile->hasDynamicAudioProfile()
4430 && curProfile->isCompatibleProfile(devices,
4431 mixerAttributes->config.sample_rate,
4432 nullptr /*updatedSamplingRate*/,
4433 mixerAttributes->config.format,
4434 nullptr /*updatedFormat*/,
4435 mixerAttributes->config.channel_mask,
4436 nullptr /*updatedChannelMask*/,
4437 flags,
4438 false /*exactMatchRequiredForInputFlags*/)) {
4439 profile = curProfile;
4440 break;
4441 }
4442 }
4443 }
4444 if (profile == nullptr) {
4445 ALOGE("%s, there is no compatible profile found", __func__);
4446 return BAD_VALUE;
4447 }
4448
4449 sp<PreferredMixerAttributesInfo> mixerAttrInfo =
4450 sp<PreferredMixerAttributesInfo>::make(
4451 uid, portId, profile, flags, *mixerAttributes);
4452 const product_strategy_t strategy = mEngine->getProductStrategyForAttributes(*attr);
4453 mPreferredMixerAttrInfos[portId][strategy] = mixerAttrInfo;
4454
4455 // If 1) there is any client from the preferred mixer configuration owner that is currently
4456 // active and matches the strategy and 2) current output is on the preferred device and the
4457 // mixer configuration doesn't match the preferred one, reopen output with preferred mixer
4458 // configuration.
4459 std::vector<audio_io_handle_t> outputsToReopen;
4460 for (size_t i = 0; i < mOutputs.size(); i++) {
4461 const auto output = mOutputs.valueAt(i);
jiabin3ff8d7d2022-12-13 06:27:44 +00004462 if (output->mProfile == profile && output->devices().onlyContainsDevice(deviceDescriptor)) {
4463 if (output->isConfigurationMatched(mixerAttributes->config, flags)) {
4464 output->mUsePreferredMixerAttributes = true;
4465 } else {
4466 for (const auto &client: output->getActiveClients()) {
4467 if (client->uid() == uid && client->strategy() == strategy) {
4468 client->setIsInvalid();
4469 outputsToReopen.push_back(output->mIoHandle);
4470 }
jiabina84c3d32022-12-02 18:59:55 +00004471 }
4472 }
4473 }
4474 }
4475 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
4476 config.sample_rate = mixerAttributes->config.sample_rate;
4477 config.channel_mask = mixerAttributes->config.channel_mask;
4478 config.format = mixerAttributes->config.format;
4479 for (const auto output : outputsToReopen) {
jiabin3ff8d7d2022-12-13 06:27:44 +00004480 sp<SwAudioOutputDescriptor> desc =
4481 reopenOutput(mOutputs.valueFor(output), &config, flags, __func__);
4482 if (desc == nullptr) {
4483 ALOGE("%s, failed to reopen output with preferred mixer attributes", __func__);
Dorin Drimusf2196d82022-01-03 12:11:18 +01004484 continue;
4485 }
jiabin3ff8d7d2022-12-13 06:27:44 +00004486 desc->mUsePreferredMixerAttributes = true;
Eric Laurent6a94d692014-05-20 11:18:06 -07004487 }
jiabin19cdba52020-11-24 11:28:58 -08004488
jiabina84c3d32022-12-02 18:59:55 +00004489 return NO_ERROR;
4490}
4491
4492sp<PreferredMixerAttributesInfo> AudioPolicyManager::getPreferredMixerAttributesInfo(
4493 audio_port_handle_t devicePortId, product_strategy_t strategy) {
4494 auto it = mPreferredMixerAttrInfos.find(devicePortId);
4495 if (it == mPreferredMixerAttrInfos.end()) {
4496 return nullptr;
4497 }
4498 auto mixerAttrInfoIt = it->second.find(strategy);
4499 if (mixerAttrInfoIt == it->second.end()) {
4500 return nullptr;
4501 }
4502 return mixerAttrInfoIt->second;
4503}
4504
4505status_t AudioPolicyManager::getPreferredMixerAttributes(
4506 const audio_attributes_t *attr,
4507 audio_port_handle_t portId,
4508 audio_mixer_attributes_t* mixerAttributes) {
4509 sp<PreferredMixerAttributesInfo> info = getPreferredMixerAttributesInfo(
4510 portId, mEngine->getProductStrategyForAttributes(*attr));
4511 if (info == nullptr) {
4512 return NAME_NOT_FOUND;
4513 }
4514 *mixerAttributes = info->getMixerAttributes();
4515 return NO_ERROR;
4516}
4517
4518status_t AudioPolicyManager::clearPreferredMixerAttributes(const audio_attributes_t *attr,
4519 audio_port_handle_t portId,
4520 uid_t uid) {
4521 const product_strategy_t strategy = mEngine->getProductStrategyForAttributes(*attr);
4522 const auto preferredMixerAttrInfo = getPreferredMixerAttributesInfo(portId, strategy);
4523 if (preferredMixerAttrInfo == nullptr) {
4524 return NAME_NOT_FOUND;
4525 }
4526 if (preferredMixerAttrInfo->getUid() != uid) {
4527 ALOGE("%s, requested uid=%d, owned uid=%d",
4528 __func__, uid, preferredMixerAttrInfo->getUid());
4529 return PERMISSION_DENIED;
4530 }
4531 mPreferredMixerAttrInfos[portId].erase(strategy);
4532 if (mPreferredMixerAttrInfos[portId].empty()) {
4533 mPreferredMixerAttrInfos.erase(portId);
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004534 }
Eric Laurent5a2b6292016-04-14 18:05:57 -07004535
jiabina84c3d32022-12-02 18:59:55 +00004536 // Reconfig existing output
4537 std::vector<audio_io_handle_t> potentialOutputsToReopen;
4538 for (size_t i = 0; i < mOutputs.size(); i++) {
4539 if (mOutputs.valueAt(i)->mProfile == preferredMixerAttrInfo->getProfile()) {
4540 potentialOutputsToReopen.push_back(mOutputs.keyAt(i));
4541 }
4542 }
4543 for (const auto output : potentialOutputsToReopen) {
4544 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
4545 if (desc->isConfigurationMatched(preferredMixerAttrInfo->getConfigBase(),
4546 preferredMixerAttrInfo->getFlags())) {
4547 reopenOutput(desc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
4548 }
4549 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004550 return NO_ERROR;
4551}
jiabin19cdba52020-11-24 11:28:58 -08004552
Eric Laurent6a94d692014-05-20 11:18:06 -07004553status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
Eric Laurent99fcae42018-05-17 16:59:18 -07004554 audio_port_type_t type,
4555 unsigned int *num_ports,
4556 struct audio_port_v7 *ports,
4557 unsigned int *generation)
4558{
4559 if (num_ports == nullptr || (*num_ports != 0 && ports == nullptr) ||
4560 generation == nullptr) {
4561 return BAD_VALUE;
4562 }
4563 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
4564 if (ports == nullptr) {
4565 *num_ports = 0;
4566 }
4567
4568 size_t portsWritten = 0;
4569 size_t portsMax = *num_ports;
4570 *num_ports = 0;
4571 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
4572 // do not report devices with type AUDIO_DEVICE_IN_STUB or AUDIO_DEVICE_OUT_STUB
4573 // as they are used by stub HALs by convention
4574 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
4575 for (const auto& dev : mAvailableOutputDevices) {
4576 if (dev->type() == AUDIO_DEVICE_OUT_STUB) {
4577 continue;
Eric Laurent6a94d692014-05-20 11:18:06 -07004578 }
4579 if (portsWritten < portsMax) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004580 dev->toAudioPort(&ports[portsWritten++]);
4581 }
4582 (*num_ports)++;
4583 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004584 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004585 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004586 for (const auto& dev : mAvailableInputDevices) {
4587 if (dev->type() == AUDIO_DEVICE_IN_STUB) {
4588 continue;
François Gaffieafd4cea2019-11-18 15:50:22 +01004589 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004590 if (portsWritten < portsMax) {
Mikhail Naganovac9858b2018-06-15 13:12:37 -07004591 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent874c42872014-08-08 15:13:39 -07004592 }
4593 (*num_ports)++;
4594 }
4595 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004596 }
4597 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
Eric Laurent874c42872014-08-08 15:13:39 -07004598 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
4599 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004600 mInputs[i]->toAudioPort(&ports[portsWritten++]);
4601 }
Eric Laurent874c42872014-08-08 15:13:39 -07004602 *num_ports += mInputs.size();
4603 }
4604 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
4605 size_t numOutputs = 0;
4606 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004607 if (!mOutputs[i]->isDuplicated()) {
4608 numOutputs++;
4609 if (portsWritten < portsMax) {
4610 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
François Gaffieafd4cea2019-11-18 15:50:22 +01004611 }
4612 }
4613 }
Eric Laurent874c42872014-08-08 15:13:39 -07004614 *num_ports += numOutputs;
4615 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004616 }
jiabina84c3d32022-12-02 18:59:55 +00004617
Eric Laurent6a94d692014-05-20 11:18:06 -07004618 *generation = curAudioPortGeneration();
4619 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
4620 return NO_ERROR;
4621}
4622
Mikhail Naganov15f46712023-03-23 14:52:15 -07004623status_t AudioPolicyManager::listDeclaredDevicePorts(media::AudioPortRole role,
4624 std::vector<media::AudioPortFw>* _aidl_return) {
4625 auto pushPort = [&](const sp<DeviceDescriptor>& dev) -> status_t {
4626 audio_port_v7 port;
4627 dev->toAudioPort(&port);
4628 auto aidlPort = VALUE_OR_RETURN_STATUS(legacy2aidl_audio_port_v7_AudioPortFw(port));
4629 _aidl_return->push_back(std::move(aidlPort));
4630 return OK;
4631 };
4632
Mikhail Naganovb0fbc1b2023-04-28 13:06:32 -07004633 for (const auto& module : mHwModules) {
Mikhail Naganov15f46712023-03-23 14:52:15 -07004634 for (const auto& dev : module->getDeclaredDevices()) {
4635 if (role == media::AudioPortRole::NONE ||
4636 ((role == media::AudioPortRole::SOURCE)
4637 == audio_is_input_device(dev->type()))) {
4638 RETURN_STATUS_IF_ERROR(pushPort(dev));
4639 }
4640 }
4641 }
4642 return OK;
4643}
4644
Eric Laurent6a94d692014-05-20 11:18:06 -07004645status_t AudioPolicyManager::getAudioPort(struct audio_port_v7 *port)
4646{
4647 if (port == nullptr || port->id == AUDIO_PORT_HANDLE_NONE) {
4648 return BAD_VALUE;
4649 }
4650 sp<DeviceDescriptor> dev = mAvailableOutputDevices.getDeviceFromId(port->id);
4651 if (dev != 0) {
4652 dev->toAudioPort(port);
4653 return NO_ERROR;
4654 }
4655 dev = mAvailableInputDevices.getDeviceFromId(port->id);
4656 if (dev != 0) {
4657 dev->toAudioPort(port);
4658 return NO_ERROR;
4659 }
4660 sp<SwAudioOutputDescriptor> out = mOutputs.getOutputFromId(port->id);
4661 if (out != 0) {
4662 out->toAudioPort(port);
4663 return NO_ERROR;
4664 }
4665 sp<AudioInputDescriptor> in = mInputs.getInputFromId(port->id);
4666 if (in != 0) {
4667 in->toAudioPort(port);
4668 return NO_ERROR;
4669 }
4670 return BAD_VALUE;
4671}
4672
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004673status_t AudioPolicyManager::createAudioPatch(const struct audio_patch *patch,
4674 audio_patch_handle_t *handle,
4675 uid_t uid)
Eric Laurent6a94d692014-05-20 11:18:06 -07004676{
4677 ALOGV("%s", __func__);
4678 if (handle == NULL || patch == NULL) {
4679 return BAD_VALUE;
4680 }
4681 ALOGV("%s num sources %d num sinks %d", __func__, patch->num_sources, patch->num_sinks);
Eric Laurent6a94d692014-05-20 11:18:06 -07004682 if (!audio_patch_is_valid(patch)) {
4683 return BAD_VALUE;
4684 }
4685 // only one source per audio patch supported for now
4686 if (patch->num_sources > 1) {
4687 return INVALID_OPERATION;
4688 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004689 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE) {
4690 return INVALID_OPERATION;
4691 }
4692 for (size_t i = 0; i < patch->num_sinks; i++) {
4693 if (patch->sinks[i].role != AUDIO_PORT_ROLE_SINK) {
4694 return INVALID_OPERATION;
4695 }
4696 }
4697
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004698 sp<DeviceDescriptor> srcDevice = mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
4699 sp<DeviceDescriptor> sinkDevice = mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id);
4700 if (srcDevice == nullptr || sinkDevice == nullptr) {
4701 ALOGW("%s could not create patch, invalid sink and/or source device(s)", __func__);
4702 return BAD_VALUE;
4703 }
4704 ALOGV("%s between source %s and sink %s", __func__,
4705 srcDevice->toString().c_str(), sinkDevice->toString().c_str());
4706 audio_port_handle_t portId = PolicyAudioPort::getNextUniqueId();
4707 // Default attributes, default volume priority, not to infer with non raw audio patches.
4708 audio_attributes_t attributes = attributes_initializer(AUDIO_USAGE_MEDIA);
4709 const struct audio_port_config *source = &patch->sources[0];
4710 sp<SourceClientDescriptor> sourceDesc =
4711 new InternalSourceClientDescriptor(
4712 portId, uid, attributes, *source, srcDevice, sinkDevice,
4713 mEngine->getProductStrategyForAttributes(attributes), toVolumeSource(attributes));
4714
4715 status_t status =
4716 connectAudioSourceToSink(sourceDesc, sinkDevice, patch, *handle, uid, 0 /* delayMs */);
4717
4718 if (status != NO_ERROR) {
4719 return INVALID_OPERATION;
4720 }
4721 mAudioSources.add(portId, sourceDesc);
4722 return NO_ERROR;
4723}
4724
4725status_t AudioPolicyManager::connectAudioSourceToSink(
4726 const sp<SourceClientDescriptor>& sourceDesc, const sp<DeviceDescriptor> &sinkDevice,
4727 const struct audio_patch *patch,
4728 audio_patch_handle_t &handle,
4729 uid_t uid, uint32_t delayMs)
4730{
4731 status_t status = createAudioPatchInternal(patch, &handle, uid, delayMs, sourceDesc);
4732 if (status != NO_ERROR || mAudioPatches.indexOfKey(handle) < 0) {
4733 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
4734 return INVALID_OPERATION;
4735 }
4736 sourceDesc->connect(handle, sinkDevice);
4737 if (isMsdPatch(handle)) {
4738 return NO_ERROR;
4739 }
4740 // SW Bridge? (@todo: HW bridge, keep track of HwOutput for device selection "reconsideration")
4741 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
4742 ALOG_ASSERT(swOutput != nullptr, "%s: a swOutput shall always be associated", __func__);
4743 if (swOutput->getClient(sourceDesc->portId()) != nullptr) {
4744 ALOGW("%s source portId has already been attached to outputDesc", __func__);
4745 goto FailurePatchAdded;
4746 }
4747 status = swOutput->start();
4748 if (status != NO_ERROR) {
4749 goto FailureSourceAdded;
4750 }
4751 swOutput->addClient(sourceDesc);
4752 status = startSource(swOutput, sourceDesc, &delayMs);
4753 if (status != NO_ERROR) {
4754 ALOGW("%s failed to start source, error %d", __FUNCTION__, status);
4755 goto FailureSourceActive;
4756 }
4757 if (delayMs != 0) {
4758 usleep(delayMs * 1000);
4759 }
4760 return NO_ERROR;
4761
4762FailureSourceActive:
4763 swOutput->stop();
4764 releaseOutput(sourceDesc->portId());
4765FailureSourceAdded:
4766 sourceDesc->setSwOutput(nullptr);
4767FailurePatchAdded:
4768 releaseAudioPatchInternal(handle);
4769 return INVALID_OPERATION;
4770}
4771
4772status_t AudioPolicyManager::createAudioPatchInternal(const struct audio_patch *patch,
4773 audio_patch_handle_t *handle,
4774 uid_t uid, uint32_t delayMs,
4775 const sp<SourceClientDescriptor>& sourceDesc)
4776{
4777 ALOGV("%s num sources %d num sinks %d", __func__, patch->num_sources, patch->num_sinks);
Eric Laurent6a94d692014-05-20 11:18:06 -07004778 sp<AudioPatch> patchDesc;
4779 ssize_t index = mAudioPatches.indexOfKey(*handle);
4780
4781 ALOGV("%s source id %d role %d type %d", __func__, patch->sources[0].id,
4782 patch->sources[0].role,
4783 patch->sources[0].type);
Eric Laurent874c42872014-08-08 15:13:39 -07004784#if LOG_NDEBUG == 0
4785 for (size_t i = 0; i < patch->num_sinks; i++) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004786 ALOGV("%s sink %zu: id %d role %d type %d", __func__ ,i, patch->sinks[i].id,
4787 patch->sinks[i].role,
4788 patch->sinks[i].type);
Eric Laurent874c42872014-08-08 15:13:39 -07004789 }
4790#endif
Eric Laurent6a94d692014-05-20 11:18:06 -07004791
4792 if (index >= 0) {
4793 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01004794 ALOGV("%s mUidCached %d patchDesc->mUid %d uid %d",
4795 __func__, mUidCached, patchDesc->getUid(), uid);
4796 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004797 return INVALID_OPERATION;
4798 }
4799 } else {
Glenn Kastena13cde92016-03-28 15:26:02 -07004800 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07004801 }
4802
4803 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004804 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004805 if (outputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004806 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004807 return BAD_VALUE;
4808 }
Eric Laurent84c70242014-06-23 08:46:27 -07004809 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
4810 outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004811 if (patchDesc != 0) {
4812 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004813 ALOGV("%s source id differs for patch current id %d new id %d",
4814 __func__, patchDesc->mPatch.sources[0].id, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004815 return BAD_VALUE;
4816 }
4817 }
Eric Laurent874c42872014-08-08 15:13:39 -07004818 DeviceVector devices;
4819 for (size_t i = 0; i < patch->num_sinks; i++) {
4820 // Only support mix to devices connection
4821 // TODO add support for mix to mix connection
4822 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004823 ALOGV("%s source mix but sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07004824 return INVALID_OPERATION;
4825 }
4826 sp<DeviceDescriptor> devDesc =
4827 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
4828 if (devDesc == 0) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004829 ALOGV("%s out device not found for id %d", __func__, patch->sinks[i].id);
Eric Laurent874c42872014-08-08 15:13:39 -07004830 return BAD_VALUE;
4831 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004832
François Gaffie11d30102018-11-02 16:09:09 +01004833 if (!outputDesc->mProfile->isCompatibleProfile(DeviceVector(devDesc),
Eric Laurent874c42872014-08-08 15:13:39 -07004834 patch->sources[0].sample_rate,
François Gaffie53615e22015-03-19 09:24:12 +01004835 NULL, // updatedSamplingRate
4836 patch->sources[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07004837 NULL, // updatedFormat
François Gaffie53615e22015-03-19 09:24:12 +01004838 patch->sources[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07004839 NULL, // updatedChannelMask
François Gaffie53615e22015-03-19 09:24:12 +01004840 AUDIO_OUTPUT_FLAG_NONE /*FIXME*/)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004841 ALOGV("%s profile not supported for device %08x", __func__, devDesc->type());
Eric Laurent874c42872014-08-08 15:13:39 -07004842 return INVALID_OPERATION;
4843 }
4844 devices.add(devDesc);
4845 }
4846 if (devices.size() == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004847 return INVALID_OPERATION;
4848 }
Eric Laurent874c42872014-08-08 15:13:39 -07004849
Eric Laurent6a94d692014-05-20 11:18:06 -07004850 // TODO: reconfigure output format and channels here
François Gaffieafd4cea2019-11-18 15:50:22 +01004851 ALOGV("%s setting device %s on output %d",
4852 __func__, dumpDeviceTypes(devices.types()).c_str(), outputDesc->mIoHandle);
François Gaffie11d30102018-11-02 16:09:09 +01004853 setOutputDevices(outputDesc, devices, true, 0, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004854 index = mAudioPatches.indexOfKey(*handle);
4855 if (index >= 0) {
4856 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004857 ALOGW("%s setOutputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004858 }
4859 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01004860 patchDesc->setUid(uid);
4861 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004862 } else {
François Gaffieafd4cea2019-11-18 15:50:22 +01004863 ALOGW("%s setOutputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004864 return INVALID_OPERATION;
4865 }
4866 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
4867 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
4868 // input device to input mix connection
Eric Laurent874c42872014-08-08 15:13:39 -07004869 // only one sink supported when connecting an input device to a mix
4870 if (patch->num_sinks > 1) {
4871 return INVALID_OPERATION;
4872 }
François Gaffie53615e22015-03-19 09:24:12 +01004873 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004874 if (inputDesc == NULL) {
4875 return BAD_VALUE;
4876 }
4877 if (patchDesc != 0) {
4878 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
4879 return BAD_VALUE;
4880 }
4881 }
François Gaffie11d30102018-11-02 16:09:09 +01004882 sp<DeviceDescriptor> device =
Eric Laurent6a94d692014-05-20 11:18:06 -07004883 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01004884 if (device == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004885 return BAD_VALUE;
4886 }
4887
François Gaffie11d30102018-11-02 16:09:09 +01004888 if (!inputDesc->mProfile->isCompatibleProfile(DeviceVector(device),
Eric Laurent275e8e92014-11-30 15:14:47 -08004889 patch->sinks[0].sample_rate,
4890 NULL, /*updatedSampleRate*/
4891 patch->sinks[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07004892 NULL, /*updatedFormat*/
Eric Laurent275e8e92014-11-30 15:14:47 -08004893 patch->sinks[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07004894 NULL, /*updatedChannelMask*/
Eric Laurent275e8e92014-11-30 15:14:47 -08004895 // FIXME for the parameter type,
4896 // and the NONE
4897 (audio_output_flags_t)
Glenn Kasten6a8ab052014-07-24 14:08:35 -07004898 AUDIO_INPUT_FLAG_NONE)) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004899 return INVALID_OPERATION;
4900 }
4901 // TODO: reconfigure output format and channels here
François Gaffieafd4cea2019-11-18 15:50:22 +01004902 ALOGV("%s setting device %s on output %d", __func__,
François Gaffie11d30102018-11-02 16:09:09 +01004903 device->toString().c_str(), inputDesc->mIoHandle);
4904 setInputDevice(inputDesc->mIoHandle, device, true, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004905 index = mAudioPatches.indexOfKey(*handle);
4906 if (index >= 0) {
4907 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004908 ALOGW("%s setInputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004909 }
4910 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01004911 patchDesc->setUid(uid);
4912 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004913 } else {
François Gaffieafd4cea2019-11-18 15:50:22 +01004914 ALOGW("%s setInputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004915 return INVALID_OPERATION;
4916 }
4917 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
4918 // device to device connection
4919 if (patchDesc != 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07004920 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004921 return BAD_VALUE;
4922 }
4923 }
François Gaffie11d30102018-11-02 16:09:09 +01004924 sp<DeviceDescriptor> srcDevice =
Eric Laurent6a94d692014-05-20 11:18:06 -07004925 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01004926 if (srcDevice == 0) {
Eric Laurent58f8eb72014-09-12 16:19:41 -07004927 return BAD_VALUE;
4928 }
Eric Laurent874c42872014-08-08 15:13:39 -07004929
Eric Laurent6a94d692014-05-20 11:18:06 -07004930 //update source and sink with our own data as the data passed in the patch may
4931 // be incomplete.
François Gaffieafd4cea2019-11-18 15:50:22 +01004932 PatchBuilder patchBuilder;
4933 audio_port_config sourcePortConfig = {};
Dean Wheatley8bee85a2021-02-10 16:02:23 +11004934
4935 // if first sink is to MSD, establish single MSD patch
4936 if (getMsdAudioOutDevices().contains(
4937 mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id))) {
4938 ALOGV("%s patching to MSD", __FUNCTION__);
4939 patchBuilder = buildMsdPatch(false /*msdIsSource*/, srcDevice);
4940 goto installPatch;
4941 }
4942
François Gaffieafd4cea2019-11-18 15:50:22 +01004943 srcDevice->toAudioPortConfig(&sourcePortConfig, &patch->sources[0]);
4944 patchBuilder.addSource(sourcePortConfig);
Eric Laurent6a94d692014-05-20 11:18:06 -07004945
Eric Laurent874c42872014-08-08 15:13:39 -07004946 for (size_t i = 0; i < patch->num_sinks; i++) {
4947 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004948 ALOGV("%s source device but one sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07004949 return INVALID_OPERATION;
4950 }
François Gaffie11d30102018-11-02 16:09:09 +01004951 sp<DeviceDescriptor> sinkDevice =
Eric Laurent874c42872014-08-08 15:13:39 -07004952 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
François Gaffie11d30102018-11-02 16:09:09 +01004953 if (sinkDevice == 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07004954 return BAD_VALUE;
4955 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004956 audio_port_config sinkPortConfig = {};
4957 sinkDevice->toAudioPortConfig(&sinkPortConfig, &patch->sinks[i]);
4958 patchBuilder.addSink(sinkPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07004959
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004960 // Whatever Sw or Hw bridge, we do attach an SwOutput to an Audio Source for
4961 // volume management purpose (tracking activity)
4962 // In case of Hw bridge, it is a Work Around. The mixPort used is the one declared
4963 // in config XML to reach the sink so that is can be declared as available.
4964 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurent78b07302022-10-07 16:20:34 +02004965 sp<SwAudioOutputDescriptor> outputDesc;
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004966 if (!sourceDesc->isInternal()) {
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004967 // take care of dynamic routing for SwOutput selection,
4968 audio_attributes_t attributes = sourceDesc->attributes();
4969 audio_stream_type_t stream = sourceDesc->stream();
4970 audio_attributes_t resultAttr;
4971 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
4972 config.sample_rate = sourceDesc->config().sample_rate;
François Gaffie2a24db42022-04-04 16:45:02 +02004973 audio_channel_mask_t sourceMask = sourceDesc->config().channel_mask;
4974 config.channel_mask =
4975 (audio_channel_mask_get_representation(sourceMask)
4976 == AUDIO_CHANNEL_REPRESENTATION_INDEX) ? sourceMask
4977 : audio_channel_mask_in_to_out(sourceMask);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004978 config.format = sourceDesc->config().format;
4979 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
4980 audio_port_handle_t selectedDeviceId = AUDIO_PORT_HANDLE_NONE;
4981 bool isRequestedDeviceForExclusiveUse = false;
4982 output_type_t outputType;
Eric Laurentb0a7bc92022-04-05 15:06:08 +02004983 bool isSpatialized;
jiabinc658e452022-10-21 20:52:21 +00004984 bool isBitPerfect;
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004985 getOutputForAttrInt(&resultAttr, &output, AUDIO_SESSION_NONE, &attributes,
4986 &stream, sourceDesc->uid(), &config, &flags,
4987 &selectedDeviceId, &isRequestedDeviceForExclusiveUse,
jiabinc658e452022-10-21 20:52:21 +00004988 nullptr, &outputType, &isSpatialized, &isBitPerfect);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004989 if (output == AUDIO_IO_HANDLE_NONE) {
4990 ALOGV("%s no output for device %s",
4991 __FUNCTION__, sinkDevice->toString().c_str());
4992 return INVALID_OPERATION;
4993 }
4994 outputDesc = mOutputs.valueFor(output);
4995 if (outputDesc->isDuplicated()) {
4996 ALOGE("%s output is duplicated", __func__);
4997 return INVALID_OPERATION;
4998 }
François Gaffie1765c5b2022-04-26 12:48:49 +02004999 bool closeOutput = outputDesc->mDirectOpenCount != 0;
5000 sourceDesc->setSwOutput(outputDesc, closeOutput);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005001 } else {
5002 // Same for "raw patches" aka created from createAudioPatch API
5003 SortedVector<audio_io_handle_t> outputs =
5004 getOutputsForDevices(DeviceVector(sinkDevice), mOutputs);
5005 // if the sink device is reachable via an opened output stream, request to
5006 // go via this output stream by adding a second source to the patch
5007 // description
5008 output = selectOutput(outputs);
5009 if (output == AUDIO_IO_HANDLE_NONE) {
5010 ALOGE("%s no output available for internal patch sink", __func__);
5011 return INVALID_OPERATION;
5012 }
5013 outputDesc = mOutputs.valueFor(output);
5014 if (outputDesc->isDuplicated()) {
5015 ALOGV("%s output for device %s is duplicated",
5016 __func__, sinkDevice->toString().c_str());
5017 return INVALID_OPERATION;
5018 }
François Gaffie1765c5b2022-04-26 12:48:49 +02005019 sourceDesc->setSwOutput(outputDesc, /* closeOutput= */ false);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005020 }
Eric Laurent3bcf8592015-04-03 12:13:24 -07005021 // create a software bridge in PatchPanel if:
Scott Randolphf3172402018-01-23 17:06:53 -08005022 // - source and sink devices are on different HW modules OR
Eric Laurent3bcf8592015-04-03 12:13:24 -07005023 // - audio HAL version is < 3.0
Francois Gaffie99896da2018-04-09 11:05:33 +02005024 // - audio HAL version is >= 3.0 but no route has been declared between devices
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005025 // - called from startAudioSource (aka sourceDesc is not internal) and source device
5026 // does not have a gain controller
François Gaffie11d30102018-11-02 16:09:09 +01005027 if (!srcDevice->hasSameHwModuleAs(sinkDevice) ||
5028 (srcDevice->getModuleVersionMajor() < 3) ||
François Gaffieafd4cea2019-11-18 15:50:22 +01005029 !srcDevice->getModule()->supportsPatch(srcDevice, sinkDevice) ||
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005030 (!sourceDesc->isInternal() &&
François Gaffieafd4cea2019-11-18 15:50:22 +01005031 srcDevice->getAudioPort()->getGains().size() == 0)) {
Eric Laurent3bcf8592015-04-03 12:13:24 -07005032 // support only one sink device for now to simplify output selection logic
Eric Laurent874c42872014-08-08 15:13:39 -07005033 if (patch->num_sinks > 1) {
Eric Laurent83b88082014-06-20 18:31:16 -07005034 return INVALID_OPERATION;
5035 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005036 sourceDesc->setUseSwBridge();
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005037 if (outputDesc != nullptr) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005038 audio_port_config srcMixPortConfig = {};
Ytai Ben-Tsvic9d2a912021-11-22 16:43:09 -08005039 outputDesc->toAudioPortConfig(&srcMixPortConfig, nullptr);
François Gaffieafd4cea2019-11-18 15:50:22 +01005040 // for volume control, we may need a valid stream
Eric Laurent78b07302022-10-07 16:20:34 +02005041 srcMixPortConfig.ext.mix.usecase.stream =
5042 (!sourceDesc->isInternal() || isCallTxAudioSource(sourceDesc)) ?
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005043 mEngine->getStreamTypeForAttributes(sourceDesc->attributes()) :
5044 AUDIO_STREAM_PATCH;
François Gaffieafd4cea2019-11-18 15:50:22 +01005045 patchBuilder.addSource(srcMixPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07005046 }
Eric Laurent83b88082014-06-20 18:31:16 -07005047 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005048 }
5049 // TODO: check from routing capabilities in config file and other conflicting patches
5050
Dean Wheatley8bee85a2021-02-10 16:02:23 +11005051installPatch:
François Gaffieafd4cea2019-11-18 15:50:22 +01005052 status_t status = installPatch(
5053 __func__, index, handle, patchBuilder.patch(), delayMs, uid, &patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07005054 if (status != NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005055 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
Eric Laurent6a94d692014-05-20 11:18:06 -07005056 return INVALID_OPERATION;
5057 }
5058 } else {
5059 return BAD_VALUE;
5060 }
5061 } else {
5062 return BAD_VALUE;
5063 }
5064 return NO_ERROR;
5065}
5066
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005067status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle, uid_t uid)
Eric Laurent6a94d692014-05-20 11:18:06 -07005068{
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005069 ALOGV("%s patch %d", __func__, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005070 ssize_t index = mAudioPatches.indexOfKey(handle);
5071
5072 if (index < 0) {
5073 return BAD_VALUE;
5074 }
5075 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005076 ALOGV("%s() mUidCached %d patchDesc->mUid %d uid %d",
5077 __func__, mUidCached, patchDesc->getUid(), uid);
5078 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005079 return INVALID_OPERATION;
5080 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005081 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
5082 for (size_t i = 0; i < mAudioSources.size(); i++) {
5083 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
5084 if (sourceDesc != nullptr && sourceDesc->getPatchHandle() == handle) {
5085 portId = sourceDesc->portId();
5086 break;
5087 }
5088 }
5089 return portId != AUDIO_PORT_HANDLE_NONE ?
5090 stopAudioSource(portId) : releaseAudioPatchInternal(handle);
François Gaffieafd4cea2019-11-18 15:50:22 +01005091}
Eric Laurent6a94d692014-05-20 11:18:06 -07005092
François Gaffieafd4cea2019-11-18 15:50:22 +01005093status_t AudioPolicyManager::releaseAudioPatchInternal(audio_patch_handle_t handle,
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005094 uint32_t delayMs,
5095 const sp<SourceClientDescriptor>& sourceDesc)
François Gaffieafd4cea2019-11-18 15:50:22 +01005096{
5097 ALOGV("%s patch %d", __func__, handle);
5098 if (mAudioPatches.indexOfKey(handle) < 0) {
5099 ALOGE("%s: no patch found with handle=%d", __func__, handle);
5100 return BAD_VALUE;
5101 }
5102 sp<AudioPatch> patchDesc = mAudioPatches.valueFor(handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005103 struct audio_patch *patch = &patchDesc->mPatch;
François Gaffieafd4cea2019-11-18 15:50:22 +01005104 patchDesc->setUid(mUidCached);
Eric Laurent6a94d692014-05-20 11:18:06 -07005105 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005106 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005107 if (outputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005108 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005109 return BAD_VALUE;
5110 }
5111
François Gaffie11d30102018-11-02 16:09:09 +01005112 setOutputDevices(outputDesc,
5113 getNewOutputDevices(outputDesc, true /*fromCache*/),
5114 true,
5115 0,
5116 NULL);
Eric Laurent6a94d692014-05-20 11:18:06 -07005117 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
5118 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
François Gaffie53615e22015-03-19 09:24:12 +01005119 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005120 if (inputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005121 ALOGV("%s input not found for id %d", __func__, patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005122 return BAD_VALUE;
5123 }
5124 setInputDevice(inputDesc->mIoHandle,
Eric Laurentfb66dd92016-01-28 18:32:03 -08005125 getNewInputDevice(inputDesc),
Eric Laurent6a94d692014-05-20 11:18:06 -07005126 true,
5127 NULL);
5128 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005129 status_t status =
5130 mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
5131 ALOGV("%s patch panel returned %d patchHandle %d",
5132 __func__, status, patchDesc->getAfHandle());
5133 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005134 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005135 mpClientInterface->onAudioPatchListUpdate();
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005136 // SW or HW Bridge
5137 sp<SwAudioOutputDescriptor> outputDesc = nullptr;
5138 audio_patch_handle_t patchHandle = AUDIO_PATCH_HANDLE_NONE;
Francois Gaffie7feb8542020-04-06 17:39:47 +02005139 if (patch->num_sources > 1 && patch->sources[1].type == AUDIO_PORT_TYPE_MIX) {
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005140 outputDesc = mOutputs.getOutputFromId(patch->sources[1].id);
5141 } else if (patch->num_sources == 1 && sourceDesc != nullptr) {
5142 outputDesc = sourceDesc->swOutput().promote();
5143 }
5144 if (outputDesc == nullptr) {
5145 ALOGW("%s no output for id %d", __func__, patch->sources[0].id);
5146 // releaseOutput has already called closeOutput in case of direct output
5147 return NO_ERROR;
5148 }
François Gaffie1765c5b2022-04-26 12:48:49 +02005149 patchHandle = outputDesc->getPatchHandle();
5150 // When a Sw bridge is released, the mixer used by this bridge will release its
5151 // patch at AudioFlinger side. Hence, the mixer audio patch must be recreated
5152 // Reuse patch handle to force audio flinger removing initial mixer patch removal
5153 // updating hal patch handle (prevent leaks).
5154 // While using a HwBridge, force reconsidering device only if not reusing an existing
5155 // output and no more activity on output (will force to close).
5156 bool force = sourceDesc->useSwBridge() ||
5157 (sourceDesc->canCloseOutput() && !outputDesc->isActive());
5158 // APM pattern is to have always outputs opened / patch realized for reachable devices.
5159 // Update device may result to NONE (empty), coupled with force, it releases the patch.
5160 // Reconsider device only for cases:
5161 // 1 / Active Output
5162 // 2 / Inactive Output previously hosting HwBridge
5163 // 3 / Inactive Output previously hosting SwBridge that can be closed.
5164 bool updateDevice = outputDesc->isActive() || !sourceDesc->useSwBridge() ||
5165 sourceDesc->canCloseOutput();
5166 setOutputDevices(outputDesc,
5167 updateDevice ? getNewOutputDevices(outputDesc, true /*fromCache*/) :
5168 outputDesc->devices(),
5169 force,
5170 0,
5171 patchHandle == AUDIO_PATCH_HANDLE_NONE ? nullptr : &patchHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005172 } else {
5173 return BAD_VALUE;
5174 }
5175 } else {
5176 return BAD_VALUE;
5177 }
5178 return NO_ERROR;
5179}
5180
5181status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
5182 struct audio_patch *patches,
5183 unsigned int *generation)
5184{
François Gaffie53615e22015-03-19 09:24:12 +01005185 if (generation == NULL) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005186 return BAD_VALUE;
5187 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005188 *generation = curAudioPortGeneration();
François Gaffie53615e22015-03-19 09:24:12 +01005189 return mAudioPatches.listAudioPatches(num_patches, patches);
Eric Laurent6a94d692014-05-20 11:18:06 -07005190}
5191
Eric Laurente1715a42014-05-20 11:30:42 -07005192status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07005193{
Eric Laurente1715a42014-05-20 11:30:42 -07005194 ALOGV("setAudioPortConfig()");
5195
5196 if (config == NULL) {
5197 return BAD_VALUE;
5198 }
5199 ALOGV("setAudioPortConfig() on port handle %d", config->id);
5200 // Only support gain configuration for now
Eric Laurenta121f902014-06-03 13:32:54 -07005201 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
5202 return INVALID_OPERATION;
Eric Laurente1715a42014-05-20 11:30:42 -07005203 }
5204
Eric Laurenta121f902014-06-03 13:32:54 -07005205 sp<AudioPortConfig> audioPortConfig;
Eric Laurente1715a42014-05-20 11:30:42 -07005206 if (config->type == AUDIO_PORT_TYPE_MIX) {
5207 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005208 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07005209 if (outputDesc == NULL) {
5210 return BAD_VALUE;
5211 }
Eric Laurent84c70242014-06-23 08:46:27 -07005212 ALOG_ASSERT(!outputDesc->isDuplicated(),
5213 "setAudioPortConfig() called on duplicated output %d",
5214 outputDesc->mIoHandle);
Eric Laurenta121f902014-06-03 13:32:54 -07005215 audioPortConfig = outputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07005216 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
François Gaffie53615e22015-03-19 09:24:12 +01005217 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07005218 if (inputDesc == NULL) {
5219 return BAD_VALUE;
5220 }
Eric Laurenta121f902014-06-03 13:32:54 -07005221 audioPortConfig = inputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07005222 } else {
5223 return BAD_VALUE;
5224 }
5225 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
5226 sp<DeviceDescriptor> deviceDesc;
5227 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
5228 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
5229 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
5230 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
5231 } else {
5232 return BAD_VALUE;
5233 }
5234 if (deviceDesc == NULL) {
5235 return BAD_VALUE;
5236 }
Eric Laurenta121f902014-06-03 13:32:54 -07005237 audioPortConfig = deviceDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07005238 } else {
5239 return BAD_VALUE;
5240 }
5241
Mikhail Naganov7be71d22018-05-23 16:51:46 -07005242 struct audio_port_config backupConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07005243 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
5244 if (status == NO_ERROR) {
Mikhail Naganov7be71d22018-05-23 16:51:46 -07005245 struct audio_port_config newConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07005246 audioPortConfig->toAudioPortConfig(&newConfig, config);
5247 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
Eric Laurente1715a42014-05-20 11:30:42 -07005248 }
Eric Laurenta121f902014-06-03 13:32:54 -07005249 if (status != NO_ERROR) {
5250 audioPortConfig->applyAudioPortConfig(&backupConfig);
Eric Laurente1715a42014-05-20 11:30:42 -07005251 }
Eric Laurente1715a42014-05-20 11:30:42 -07005252
5253 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07005254}
5255
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005256void AudioPolicyManager::releaseResourcesForUid(uid_t uid)
5257{
Eric Laurentd60560a2015-04-10 11:31:20 -07005258 clearAudioSources(uid);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005259 clearAudioPatches(uid);
5260 clearSessionRoutes(uid);
5261}
5262
Eric Laurent6a94d692014-05-20 11:18:06 -07005263void AudioPolicyManager::clearAudioPatches(uid_t uid)
5264{
Eric Laurent0add0fd2014-12-04 18:58:14 -08005265 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005266 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
François Gaffieafd4cea2019-11-18 15:50:22 +01005267 if (patchDesc->getUid() == uid) {
Eric Laurent0add0fd2014-12-04 18:58:14 -08005268 releaseAudioPatch(mAudioPatches.keyAt(i), uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07005269 }
5270 }
5271}
5272
François Gaffiec005e562018-11-06 15:04:49 +01005273void AudioPolicyManager::checkStrategyRoute(product_strategy_t ps, audio_io_handle_t ouptutToSkip)
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005274{
François Gaffiec005e562018-11-06 15:04:49 +01005275 // Take the first attributes following the product strategy as it is used to retrieve the routed
5276 // device. All attributes wihin a strategy follows the same "routing strategy"
5277 auto attributes = mEngine->getAllAttributesForProductStrategy(ps).front();
5278 DeviceVector devices = mEngine->getOutputDevicesForAttributes(attributes, nullptr, false);
François Gaffie11d30102018-11-02 16:09:09 +01005279 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
jiabin3ff8d7d2022-12-13 06:27:44 +00005280 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005281 for (size_t j = 0; j < mOutputs.size(); j++) {
5282 if (mOutputs.keyAt(j) == ouptutToSkip) {
5283 continue;
5284 }
5285 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(j);
François Gaffiec005e562018-11-06 15:04:49 +01005286 if (!outputDesc->isStrategyActive(ps)) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005287 continue;
5288 }
5289 // If the default device for this strategy is on another output mix,
5290 // invalidate all tracks in this strategy to force re connection.
5291 // Otherwise select new device on the output mix.
5292 if (outputs.indexOf(mOutputs.keyAt(j)) < 0) {
jiabinc44b3462022-12-08 12:52:31 -08005293 invalidateStreams(mEngine->getStreamTypesForProductStrategy(ps));
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005294 } else {
jiabin3ff8d7d2022-12-13 06:27:44 +00005295 DeviceVector newDevices = getNewOutputDevices(outputDesc, false /*fromCache*/);
5296 if (outputDesc->mUsePreferredMixerAttributes && outputDesc->devices() != newDevices) {
5297 // If the device is using preferred mixer attributes, the output need to reopen
5298 // with default configuration when the new selected devices are different from
5299 // current routing devices.
5300 outputsToReopen.emplace(mOutputs.keyAt(j), newDevices);
5301 continue;
5302 }
5303 setOutputDevices(outputDesc, newDevices, false);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005304 }
5305 }
jiabin3ff8d7d2022-12-13 06:27:44 +00005306 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005307}
5308
5309void AudioPolicyManager::clearSessionRoutes(uid_t uid)
5310{
5311 // remove output routes associated with this uid
François Gaffiec005e562018-11-06 15:04:49 +01005312 std::vector<product_strategy_t> affectedStrategies;
Eric Laurent97ac8712018-07-27 18:59:02 -07005313 for (size_t i = 0; i < mOutputs.size(); i++) {
5314 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07005315 for (const auto& client : outputDesc->getClientIterable()) {
5316 if (client->hasPreferredDevice() && client->uid() == uid) {
5317 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
François Gaffiec005e562018-11-06 15:04:49 +01005318 auto clientStrategy = client->strategy();
5319 if (std::find(begin(affectedStrategies), end(affectedStrategies), clientStrategy) !=
5320 end(affectedStrategies)) {
5321 continue;
5322 }
5323 affectedStrategies.push_back(client->strategy());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005324 }
5325 }
5326 }
5327 // reroute outputs if necessary
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005328 for (const auto& strategy : affectedStrategies) {
5329 checkStrategyRoute(strategy, AUDIO_IO_HANDLE_NONE);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005330 }
5331
5332 // remove input routes associated with this uid
5333 SortedVector<audio_source_t> affectedSources;
Eric Laurent97ac8712018-07-27 18:59:02 -07005334 for (size_t i = 0; i < mInputs.size(); i++) {
5335 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07005336 for (const auto& client : inputDesc->getClientIterable()) {
5337 if (client->hasPreferredDevice() && client->uid() == uid) {
5338 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
5339 affectedSources.add(client->source());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005340 }
5341 }
5342 }
5343 // reroute inputs if necessary
5344 SortedVector<audio_io_handle_t> inputsToClose;
5345 for (size_t i = 0; i < mInputs.size(); i++) {
5346 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Eric Laurent4eb58f12018-12-07 16:41:02 -08005347 if (affectedSources.indexOf(inputDesc->source()) >= 0) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005348 inputsToClose.add(inputDesc->mIoHandle);
5349 }
5350 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005351 for (const auto& input : inputsToClose) {
5352 closeInput(input);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005353 }
5354}
5355
Eric Laurentd60560a2015-04-10 11:31:20 -07005356void AudioPolicyManager::clearAudioSources(uid_t uid)
5357{
5358 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005359 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
5360 if (sourceDesc->uid() == uid) {
Eric Laurentd60560a2015-04-10 11:31:20 -07005361 stopAudioSource(mAudioSources.keyAt(i));
5362 }
5363 }
5364}
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005365
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005366status_t AudioPolicyManager::acquireSoundTriggerSession(audio_session_t *session,
5367 audio_io_handle_t *ioHandle,
5368 audio_devices_t *device)
5369{
Glenn Kastenf0c6d7d2016-02-26 10:44:04 -08005370 *session = (audio_session_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
5371 *ioHandle = (audio_io_handle_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
Francois Gaffie716e1432019-01-14 16:58:59 +01005372 audio_attributes_t attr = { .source = AUDIO_SOURCE_HOTWORD };
Eric Laurentcedd5b52023-03-22 00:03:31 +00005373 sp<DeviceDescriptor> deviceDesc = mEngine->getInputDeviceForAttributes(attr);
5374 if (deviceDesc == nullptr) {
5375 return INVALID_OPERATION;
5376 }
5377 *device = deviceDesc->type();
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005378
François Gaffiedf372692015-03-19 10:43:27 +01005379 return mSoundTriggerSessions.acquireSession(*session, *ioHandle);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005380}
5381
Eric Laurentd60560a2015-04-10 11:31:20 -07005382status_t AudioPolicyManager::startAudioSource(const struct audio_port_config *source,
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005383 const audio_attributes_t *attributes,
5384 audio_port_handle_t *portId,
5385 uid_t uid)
Eric Laurent554a2772015-04-10 11:29:24 -07005386{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005387 ALOGV("%s", __FUNCTION__);
5388 *portId = AUDIO_PORT_HANDLE_NONE;
5389
5390 if (source == NULL || attributes == NULL || portId == NULL) {
5391 ALOGW("%s invalid argument: source %p attributes %p handle %p",
5392 __FUNCTION__, source, attributes, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005393 return BAD_VALUE;
5394 }
5395
Eric Laurentd60560a2015-04-10 11:31:20 -07005396 if (source->role != AUDIO_PORT_ROLE_SOURCE ||
5397 source->type != AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005398 ALOGW("%s INVALID_OPERATION source->role %d source->type %d",
5399 __FUNCTION__, source->role, source->type);
Eric Laurentd60560a2015-04-10 11:31:20 -07005400 return INVALID_OPERATION;
5401 }
5402
François Gaffie11d30102018-11-02 16:09:09 +01005403 sp<DeviceDescriptor> srcDevice =
Eric Laurentd60560a2015-04-10 11:31:20 -07005404 mAvailableInputDevices.getDevice(source->ext.device.type,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005405 String8(source->ext.device.address),
5406 AUDIO_FORMAT_DEFAULT);
François Gaffie11d30102018-11-02 16:09:09 +01005407 if (srcDevice == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005408 ALOGW("%s source->ext.device.type %08x not found", __FUNCTION__, source->ext.device.type);
Eric Laurentd60560a2015-04-10 11:31:20 -07005409 return BAD_VALUE;
5410 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005411
jiabin4ef93452019-09-10 14:29:54 -07005412 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurentd60560a2015-04-10 11:31:20 -07005413
François Gaffieaaac0fd2018-11-22 17:56:39 +01005414 sp<SourceClientDescriptor> sourceDesc =
François Gaffieafd4cea2019-11-18 15:50:22 +01005415 new SourceClientDescriptor(*portId, uid, *attributes, *source, srcDevice,
François Gaffieaaac0fd2018-11-22 17:56:39 +01005416 mEngine->getStreamTypeForAttributes(*attributes),
5417 mEngine->getProductStrategyForAttributes(*attributes),
5418 toVolumeSource(*attributes));
Eric Laurentd60560a2015-04-10 11:31:20 -07005419
5420 status_t status = connectAudioSource(sourceDesc);
5421 if (status == NO_ERROR) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005422 mAudioSources.add(*portId, sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07005423 }
5424 return status;
5425}
5426
Francois Gaffie601801d2021-06-22 13:27:39 +02005427sp<SourceClientDescriptor> AudioPolicyManager::startAudioSourceInternal(
5428 const struct audio_port_config *source, const audio_attributes_t *attributes, uid_t uid)
5429{
5430 ALOGV("%s", __FUNCTION__);
5431 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
5432
5433 status_t status = startAudioSource(source, attributes, &portId, uid);
5434 ALOGE_IF(status != OK, "%s: failed to start audio source (%d)", __func__, status);
5435 return mAudioSources.valueFor(portId);
5436}
5437
5438
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005439status_t AudioPolicyManager::connectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07005440{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005441 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->portId());
Eric Laurentd60560a2015-04-10 11:31:20 -07005442
5443 // make sure we only have one patch per source.
5444 disconnectAudioSource(sourceDesc);
5445
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005446 audio_attributes_t attributes = sourceDesc->attributes();
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005447 // May the device (dynamic) have been disconnected/reconnected, id has changed.
5448 sp<DeviceDescriptor> srcDevice = mAvailableInputDevices.getDevice(
5449 sourceDesc->srcDevice()->type(),
5450 String8(sourceDesc->srcDevice()->address().c_str()),
5451 AUDIO_FORMAT_DEFAULT);
François Gaffiec005e562018-11-06 15:04:49 +01005452 DeviceVector sinkDevices =
Francois Gaffieff1eb522020-05-06 18:37:04 +02005453 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false /*fromCache*/);
François Gaffiec005e562018-11-06 15:04:49 +01005454 ALOG_ASSERT(!sinkDevices.isEmpty(), "connectAudioSource(): no device found for attributes");
François Gaffie11d30102018-11-02 16:09:09 +01005455 sp<DeviceDescriptor> sinkDevice = sinkDevices.itemAt(0);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005456 if (!mAvailableOutputDevices.contains(sinkDevice)) {
5457 ALOGE("%s Device %s not available", __func__, sinkDevice->toString().c_str());
5458 return INVALID_OPERATION;
5459 }
François Gaffieafd4cea2019-11-18 15:50:22 +01005460 PatchBuilder patchBuilder;
5461 patchBuilder.addSink(sinkDevice).addSource(srcDevice);
5462 audio_patch_handle_t handle = AUDIO_PATCH_HANDLE_NONE;
François Gaffieafd4cea2019-11-18 15:50:22 +01005463
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005464 return connectAudioSourceToSink(
5465 sourceDesc, sinkDevice, patchBuilder.patch(), handle, mUidCached, 0 /*delayMs*/);
Eric Laurent554a2772015-04-10 11:29:24 -07005466}
5467
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005468status_t AudioPolicyManager::stopAudioSource(audio_port_handle_t portId)
Eric Laurent554a2772015-04-10 11:29:24 -07005469{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005470 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueFor(portId);
5471 ALOGV("%s port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005472 if (sourceDesc == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005473 ALOGW("%s unknown source for port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005474 return BAD_VALUE;
5475 }
5476 status_t status = disconnectAudioSource(sourceDesc);
5477
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005478 mAudioSources.removeItem(portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005479 return status;
5480}
5481
Andy Hung2ddee192015-12-18 17:34:44 -08005482status_t AudioPolicyManager::setMasterMono(bool mono)
5483{
5484 if (mMasterMono == mono) {
5485 return NO_ERROR;
5486 }
5487 mMasterMono = mono;
5488 // if enabling mono we close all offloaded devices, which will invalidate the
5489 // corresponding AudioTrack. The AudioTrack client/MediaPlayer is responsible
5490 // for recreating the new AudioTrack as non-offloaded PCM.
5491 //
5492 // If disabling mono, we leave all tracks as is: we don't know which clients
5493 // and tracks are able to be recreated as offloaded. The next "song" should
5494 // play back offloaded.
5495 if (mMasterMono) {
5496 Vector<audio_io_handle_t> offloaded;
5497 for (size_t i = 0; i < mOutputs.size(); ++i) {
5498 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
5499 if (desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
5500 offloaded.push(desc->mIoHandle);
5501 }
5502 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005503 for (const auto& handle : offloaded) {
5504 closeOutput(handle);
Andy Hung2ddee192015-12-18 17:34:44 -08005505 }
5506 }
5507 // update master mono for all remaining outputs
5508 for (size_t i = 0; i < mOutputs.size(); ++i) {
5509 updateMono(mOutputs.keyAt(i));
5510 }
5511 return NO_ERROR;
5512}
5513
5514status_t AudioPolicyManager::getMasterMono(bool *mono)
5515{
5516 *mono = mMasterMono;
5517 return NO_ERROR;
5518}
5519
Eric Laurentac9cef52017-06-09 15:46:26 -07005520float AudioPolicyManager::getStreamVolumeDB(
5521 audio_stream_type_t stream, int index, audio_devices_t device)
5522{
jiabin9a3361e2019-10-01 09:38:30 -07005523 return computeVolume(getVolumeCurves(stream), toVolumeSource(stream), index, {device});
Eric Laurentac9cef52017-06-09 15:46:26 -07005524}
5525
jiabin81772902018-04-02 17:52:27 -07005526status_t AudioPolicyManager::getSurroundFormats(unsigned int *numSurroundFormats,
5527 audio_format_t *surroundFormats,
Kriti Dang6537def2021-03-02 13:46:59 +01005528 bool *surroundFormatsEnabled)
jiabin81772902018-04-02 17:52:27 -07005529{
Kriti Dang6537def2021-03-02 13:46:59 +01005530 if (numSurroundFormats == nullptr || (*numSurroundFormats != 0 &&
5531 (surroundFormats == nullptr || surroundFormatsEnabled == nullptr))) {
jiabin81772902018-04-02 17:52:27 -07005532 return BAD_VALUE;
5533 }
Kriti Dang6537def2021-03-02 13:46:59 +01005534 ALOGV("%s() numSurroundFormats %d surroundFormats %p surroundFormatsEnabled %p",
5535 __func__, *numSurroundFormats, surroundFormats, surroundFormatsEnabled);
jiabin81772902018-04-02 17:52:27 -07005536
5537 size_t formatsWritten = 0;
5538 size_t formatsMax = *numSurroundFormats;
Kriti Dangef6be8f2020-11-05 11:58:19 +01005539
Mikhail Naganovb0fbc1b2023-04-28 13:06:32 -07005540 *numSurroundFormats = mConfig->getSurroundFormats().size();
Mikhail Naganov100f0122018-11-29 11:22:16 -08005541 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
5542 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Mikhail Naganovb0fbc1b2023-04-28 13:06:32 -07005543 for (const auto& format: mConfig->getSurroundFormats()) {
jiabin81772902018-04-02 17:52:27 -07005544 if (formatsWritten < formatsMax) {
Kriti Dang6537def2021-03-02 13:46:59 +01005545 surroundFormats[formatsWritten] = format.first;
Mikhail Naganov100f0122018-11-29 11:22:16 -08005546 bool formatEnabled = true;
5547 switch (forceUse) {
5548 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL:
Kriti Dang6537def2021-03-02 13:46:59 +01005549 formatEnabled = mManualSurroundFormats.count(format.first) != 0;
Mikhail Naganov100f0122018-11-29 11:22:16 -08005550 break;
5551 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER:
5552 formatEnabled = false;
5553 break;
5554 default: // AUTO or ALWAYS => true
5555 break;
jiabin81772902018-04-02 17:52:27 -07005556 }
5557 surroundFormatsEnabled[formatsWritten++] = formatEnabled;
5558 }
jiabin81772902018-04-02 17:52:27 -07005559 }
5560 return NO_ERROR;
5561}
5562
Kriti Dang6537def2021-03-02 13:46:59 +01005563status_t AudioPolicyManager::getReportedSurroundFormats(unsigned int *numSurroundFormats,
5564 audio_format_t *surroundFormats) {
5565 if (numSurroundFormats == nullptr || (*numSurroundFormats != 0 && surroundFormats == nullptr)) {
5566 return BAD_VALUE;
5567 }
5568 ALOGV("%s() numSurroundFormats %d surroundFormats %p",
5569 __func__, *numSurroundFormats, surroundFormats);
5570
5571 size_t formatsWritten = 0;
5572 size_t formatsMax = *numSurroundFormats;
5573 std::unordered_set<audio_format_t> formats; // Uses primary surround formats only
5574
5575 // Return formats from all device profiles that have already been resolved by
5576 // checkOutputsForDevice().
5577 for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
5578 sp<DeviceDescriptor> device = mAvailableOutputDevices[i];
5579 audio_devices_t deviceType = device->type();
5580 // Enabling/disabling formats are applied to only HDMI devices. So, this function
5581 // returns formats reported by HDMI devices.
5582 if (deviceType != AUDIO_DEVICE_OUT_HDMI) {
5583 continue;
5584 }
5585 // Formats reported by sink devices
5586 std::unordered_set<audio_format_t> formatset;
5587 if (auto it = mReportedFormatsMap.find(device); it != mReportedFormatsMap.end()) {
5588 formatset.insert(it->second.begin(), it->second.end());
5589 }
5590
5591 // Formats hard-coded in the in policy configuration file (if any).
5592 FormatVector encodedFormats = device->encodedFormats();
5593 formatset.insert(encodedFormats.begin(), encodedFormats.end());
5594 // Filter the formats which are supported by the vendor hardware.
5595 for (auto it = formatset.begin(); it != formatset.end(); ++it) {
Mikhail Naganovb0fbc1b2023-04-28 13:06:32 -07005596 if (mConfig->getSurroundFormats().count(*it) != 0) {
Kriti Dang6537def2021-03-02 13:46:59 +01005597 formats.insert(*it);
5598 } else {
Mikhail Naganovb0fbc1b2023-04-28 13:06:32 -07005599 for (const auto& pair : mConfig->getSurroundFormats()) {
Kriti Dang6537def2021-03-02 13:46:59 +01005600 if (pair.second.count(*it) != 0) {
5601 formats.insert(pair.first);
5602 break;
5603 }
5604 }
5605 }
5606 }
5607 }
5608 *numSurroundFormats = formats.size();
5609 for (const auto& format: formats) {
5610 if (formatsWritten < formatsMax) {
5611 surroundFormats[formatsWritten++] = format;
5612 }
5613 }
5614 return NO_ERROR;
5615}
5616
jiabin81772902018-04-02 17:52:27 -07005617status_t AudioPolicyManager::setSurroundFormatEnabled(audio_format_t audioFormat, bool enabled)
5618{
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005619 ALOGV("%s() format 0x%X enabled %d", __func__, audioFormat, enabled);
Mikhail Naganovb0fbc1b2023-04-28 13:06:32 -07005620 const auto& formatIter = mConfig->getSurroundFormats().find(audioFormat);
5621 if (formatIter == mConfig->getSurroundFormats().end()) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005622 ALOGW("%s() format 0x%X is not a known surround format", __func__, audioFormat);
jiabin81772902018-04-02 17:52:27 -07005623 return BAD_VALUE;
5624 }
5625
Mikhail Naganov100f0122018-11-29 11:22:16 -08005626 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND) !=
5627 AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005628 ALOGW("%s() not in manual mode for surround sound format selection", __func__);
jiabin81772902018-04-02 17:52:27 -07005629 return INVALID_OPERATION;
5630 }
5631
Mikhail Naganov100f0122018-11-29 11:22:16 -08005632 if ((mManualSurroundFormats.count(audioFormat) != 0) == enabled) {
jiabin81772902018-04-02 17:52:27 -07005633 return NO_ERROR;
5634 }
5635
Mikhail Naganov100f0122018-11-29 11:22:16 -08005636 std::unordered_set<audio_format_t> surroundFormatsBackup(mManualSurroundFormats);
jiabin81772902018-04-02 17:52:27 -07005637 if (enabled) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005638 mManualSurroundFormats.insert(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07005639 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005640 mManualSurroundFormats.insert(subFormat);
jiabin81772902018-04-02 17:52:27 -07005641 }
5642 } else {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005643 mManualSurroundFormats.erase(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07005644 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005645 mManualSurroundFormats.erase(subFormat);
jiabin81772902018-04-02 17:52:27 -07005646 }
5647 }
5648
5649 sp<SwAudioOutputDescriptor> outputDesc;
5650 bool profileUpdated = false;
jiabin9a3361e2019-10-01 09:38:30 -07005651 DeviceVector hdmiOutputDevices = mAvailableOutputDevices.getDevicesFromType(
5652 AUDIO_DEVICE_OUT_HDMI);
jiabin81772902018-04-02 17:52:27 -07005653 for (size_t i = 0; i < hdmiOutputDevices.size(); i++) {
5654 // Simulate reconnection to update enabled surround sound formats.
jiabince9f20e2019-09-12 16:29:15 -07005655 String8 address = String8(hdmiOutputDevices[i]->address().c_str());
jiabin5740f082019-08-19 15:08:30 -07005656 std::string name = hdmiOutputDevices[i]->getName();
jiabin81772902018-04-02 17:52:27 -07005657 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
5658 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
5659 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005660 name.c_str(),
5661 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005662 if (status != NO_ERROR) {
5663 continue;
5664 }
5665 status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
5666 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
5667 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005668 name.c_str(),
5669 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005670 profileUpdated |= (status == NO_ERROR);
5671 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08005672 // FIXME: Why doing this for input HDMI devices if we don't augment their reported formats?
jiabin9a3361e2019-10-01 09:38:30 -07005673 DeviceVector hdmiInputDevices = mAvailableInputDevices.getDevicesFromType(
jiabin81772902018-04-02 17:52:27 -07005674 AUDIO_DEVICE_IN_HDMI);
5675 for (size_t i = 0; i < hdmiInputDevices.size(); i++) {
5676 // Simulate reconnection to update enabled surround sound formats.
jiabince9f20e2019-09-12 16:29:15 -07005677 String8 address = String8(hdmiInputDevices[i]->address().c_str());
jiabin5740f082019-08-19 15:08:30 -07005678 std::string name = hdmiInputDevices[i]->getName();
jiabin81772902018-04-02 17:52:27 -07005679 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
5680 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
5681 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005682 name.c_str(),
5683 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005684 if (status != NO_ERROR) {
5685 continue;
5686 }
5687 status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
5688 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
5689 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005690 name.c_str(),
5691 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005692 profileUpdated |= (status == NO_ERROR);
5693 }
5694
jiabin81772902018-04-02 17:52:27 -07005695 if (!profileUpdated) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005696 ALOGW("%s() no audio profiles updated, undoing surround formats change", __func__);
Mikhail Naganov100f0122018-11-29 11:22:16 -08005697 mManualSurroundFormats = std::move(surroundFormatsBackup);
jiabin81772902018-04-02 17:52:27 -07005698 }
5699
5700 return profileUpdated ? NO_ERROR : INVALID_OPERATION;
5701}
5702
Eric Laurent5ada82e2019-08-29 17:53:54 -07005703void AudioPolicyManager::setAppState(audio_port_handle_t portId, app_state_t state)
Svet Ganovf4ddfef2018-01-16 07:37:58 -08005704{
Eric Laurent5ada82e2019-08-29 17:53:54 -07005705 ALOGV("%s(portId:%d, state:%d)", __func__, portId, state);
Eric Laurenta9f86652018-11-28 17:23:11 -08005706 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent5ada82e2019-08-29 17:53:54 -07005707 mInputs.valueAt(i)->setAppState(portId, state);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08005708 }
5709}
5710
jiabin6012f912018-11-02 17:06:30 -07005711bool AudioPolicyManager::isHapticPlaybackSupported()
5712{
5713 for (const auto& hwModule : mHwModules) {
5714 const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
5715 for (const auto &outProfile : outputProfiles) {
5716 struct audio_port audioPort;
5717 outProfile->toAudioPort(&audioPort);
5718 for (size_t i = 0; i < audioPort.num_channel_masks; i++) {
5719 if (audioPort.channel_masks[i] & AUDIO_CHANNEL_HAPTIC_ALL) {
5720 return true;
5721 }
5722 }
5723 }
5724 }
5725 return false;
5726}
5727
Carter Hsu325a8eb2022-01-19 19:56:51 +08005728bool AudioPolicyManager::isUltrasoundSupported()
5729{
5730 bool hasUltrasoundOutput = false;
5731 bool hasUltrasoundInput = false;
5732 for (const auto& hwModule : mHwModules) {
5733 const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
5734 if (!hasUltrasoundOutput) {
5735 for (const auto &outProfile : outputProfiles) {
5736 if (outProfile->getFlags() & AUDIO_OUTPUT_FLAG_ULTRASOUND) {
5737 hasUltrasoundOutput = true;
5738 break;
5739 }
5740 }
5741 }
5742
5743 const InputProfileCollection &inputProfiles = hwModule->getInputProfiles();
5744 if (!hasUltrasoundInput) {
5745 for (const auto &inputProfile : inputProfiles) {
5746 if (inputProfile->getFlags() & AUDIO_INPUT_FLAG_ULTRASOUND) {
5747 hasUltrasoundInput = true;
5748 break;
5749 }
5750 }
5751 }
5752
5753 if (hasUltrasoundOutput && hasUltrasoundInput)
5754 return true;
5755 }
5756 return false;
5757}
5758
Atneya Nair698f5ef2022-12-15 16:15:09 -08005759bool AudioPolicyManager::isHotwordStreamSupported(bool lookbackAudio)
5760{
5761 const auto mask = AUDIO_INPUT_FLAG_HOTWORD_TAP |
5762 (lookbackAudio ? AUDIO_INPUT_FLAG_HW_LOOKBACK : 0);
5763 for (const auto& hwModule : mHwModules) {
5764 const InputProfileCollection &inputProfiles = hwModule->getInputProfiles();
5765 for (const auto &inputProfile : inputProfiles) {
5766 if ((inputProfile->getFlags() & mask) == mask) {
5767 return true;
5768 }
5769 }
5770 }
5771 return false;
5772}
5773
Eric Laurent8340e672019-11-06 11:01:08 -08005774bool AudioPolicyManager::isCallScreenModeSupported()
5775{
Mikhail Naganovb0fbc1b2023-04-28 13:06:32 -07005776 return mConfig->isCallScreenModeSupported();
Eric Laurent8340e672019-11-06 11:01:08 -08005777}
5778
5779
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005780status_t AudioPolicyManager::disconnectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07005781{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005782 ALOGV("%s port Id %d", __FUNCTION__, sourceDesc->portId());
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005783 if (!sourceDesc->isConnected()) {
5784 ALOGV("%s port Id %d already disconnected", __FUNCTION__, sourceDesc->portId());
5785 return NO_ERROR;
5786 }
François Gaffieafd4cea2019-11-18 15:50:22 +01005787 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
5788 if (swOutput != 0) {
5789 status_t status = stopSource(swOutput, sourceDesc);
Eric Laurent733ce942017-12-07 12:18:25 -08005790 if (status == NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005791 swOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08005792 }
jiabinbce0c1d2020-10-05 11:20:18 -07005793 if (releaseOutput(sourceDesc->portId())) {
5794 // The output descriptor is reopened to query dynamic profiles. In that case, there is
5795 // no need to release audio patch here but just return NO_ERROR.
5796 return NO_ERROR;
5797 }
Eric Laurentd60560a2015-04-10 11:31:20 -07005798 } else {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005799 sp<HwAudioOutputDescriptor> hwOutputDesc = sourceDesc->hwOutput().promote();
Eric Laurentd60560a2015-04-10 11:31:20 -07005800 if (hwOutputDesc != 0) {
Eric Laurentd60560a2015-04-10 11:31:20 -07005801 // close Hwoutput and remove from mHwOutputs
5802 } else {
5803 ALOGW("%s source has neither SW nor HW output", __FUNCTION__);
5804 }
5805 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005806 status_t status = releaseAudioPatchInternal(sourceDesc->getPatchHandle(), 0, sourceDesc);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005807 sourceDesc->disconnect();
5808 return status;
Eric Laurentd60560a2015-04-10 11:31:20 -07005809}
5810
François Gaffiec005e562018-11-06 15:04:49 +01005811sp<SourceClientDescriptor> AudioPolicyManager::getSourceForAttributesOnOutput(
5812 audio_io_handle_t output, const audio_attributes_t &attr)
Eric Laurentd60560a2015-04-10 11:31:20 -07005813{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005814 sp<SourceClientDescriptor> source;
Eric Laurentd60560a2015-04-10 11:31:20 -07005815 for (size_t i = 0; i < mAudioSources.size(); i++) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005816 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005817 sp<SwAudioOutputDescriptor> outputDesc = sourceDesc->swOutput().promote();
François Gaffiec005e562018-11-06 15:04:49 +01005818 if (followsSameRouting(attr, sourceDesc->attributes()) &&
5819 outputDesc != 0 && outputDesc->mIoHandle == output) {
Eric Laurentd60560a2015-04-10 11:31:20 -07005820 source = sourceDesc;
5821 break;
5822 }
5823 }
5824 return source;
Eric Laurent554a2772015-04-10 11:29:24 -07005825}
5826
Eric Laurentb4f42a92022-01-17 17:37:31 +01005827bool AudioPolicyManager::canBeSpatializedInt(const audio_attributes_t *attr,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005828 const audio_config_t *config,
Andy Hung9dd1a5b2022-05-10 15:39:39 -07005829 const AudioDeviceTypeAddrVector &devices) const
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005830{
5831 // The caller can have the audio attributes criteria ignored by either passing a null ptr or
5832 // the AUDIO_ATTRIBUTES_INITIALIZER value.
Eric Laurentfa0f6742021-08-17 18:39:44 +02005833 // If attributes are specified, current policy is to only allow spatialization for media
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005834 // and game usages.
Eric Laurent39095982021-08-24 18:29:27 +02005835 if (attr != nullptr && *attr != AUDIO_ATTRIBUTES_INITIALIZER) {
5836 if (attr->usage != AUDIO_USAGE_MEDIA && attr->usage != AUDIO_USAGE_GAME) {
5837 return false;
5838 }
5839 if ((attr->flags & (AUDIO_FLAG_CONTENT_SPATIALIZED | AUDIO_FLAG_NEVER_SPATIALIZE)) != 0) {
5840 return false;
5841 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005842 }
5843
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005844 sp<IOProfile> profile =
Eric Laurent39095982021-08-24 18:29:27 +02005845 getSpatializerOutputProfile(config, devices);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005846 if (profile == nullptr) {
5847 return false;
5848 }
5849
5850 // The caller can have the audio config criteria ignored by either passing a null ptr or
5851 // the AUDIO_CONFIG_INITIALIZER value.
Eric Laurentfa0f6742021-08-17 18:39:44 +02005852 // If an audio config is specified, current policy is to only allow spatialization for
Eric Laurent39095982021-08-24 18:29:27 +02005853 // some positional channel masks.
Eric Laurent39095982021-08-24 18:29:27 +02005854
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005855 if (config != nullptr && *config != AUDIO_CONFIG_INITIALIZER) {
Andy Hung9dd1a5b2022-05-10 15:39:39 -07005856 if (!audio_is_channel_mask_spatialized(config->channel_mask)) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005857 return false;
5858 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005859 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005860 return true;
5861}
5862
5863void AudioPolicyManager::checkVirtualizerClientRoutes() {
5864 std::set<audio_stream_type_t> streamsToInvalidate;
5865 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent39095982021-08-24 18:29:27 +02005866 const sp<SwAudioOutputDescriptor>& desc = mOutputs[i];
5867 for (const sp<TrackClientDescriptor>& client : desc->getClientIterable()) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005868 audio_attributes_t attr = client->attributes();
5869 DeviceVector devices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false);
5870 AudioDeviceTypeAddrVector devicesTypeAddress = devices.toTypeAddrVector();
5871 audio_config_base_t clientConfig = client->config();
5872 audio_config_t config = audio_config_initializer(&clientConfig);
Eric Laurent39095982021-08-24 18:29:27 +02005873 if (desc != mSpatializerOutput
Andy Hung9dd1a5b2022-05-10 15:39:39 -07005874 && canBeSpatializedInt(&attr, &config, devicesTypeAddress)) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005875 streamsToInvalidate.insert(client->stream());
5876 }
5877 }
5878 }
5879
jiabinc44b3462022-12-08 12:52:31 -08005880 invalidateStreams(StreamTypeVector(streamsToInvalidate.begin(), streamsToInvalidate.end()));
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005881}
5882
Eric Laurente191d1b2022-04-15 11:59:25 +02005883
5884bool AudioPolicyManager::isOutputOnlyAvailableRouteToSomeDevice(
5885 const sp<SwAudioOutputDescriptor>& outputDesc) {
5886 if (outputDesc->isDuplicated()) {
5887 return false;
5888 }
5889 DeviceVector devices = outputDesc->supportedDevices();
5890 for (size_t i = 0; i < mOutputs.size(); i++) {
5891 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
5892 if (desc == outputDesc || desc->isDuplicated()) {
5893 continue;
5894 }
5895 DeviceVector sharedDevices = desc->filterSupportedDevices(devices);
5896 if (!sharedDevices.isEmpty()
5897 && (desc->devicesSupportEncodedFormats(sharedDevices.types())
5898 == outputDesc->devicesSupportEncodedFormats(sharedDevices.types()))) {
5899 return false;
5900 }
5901 }
5902 return true;
5903}
5904
5905
Eric Laurentfa0f6742021-08-17 18:39:44 +02005906status_t AudioPolicyManager::getSpatializerOutput(const audio_config_base_t *mixerConfig,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005907 const audio_attributes_t *attr,
5908 audio_io_handle_t *output) {
5909 *output = AUDIO_IO_HANDLE_NONE;
5910
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005911 DeviceVector devices = mEngine->getOutputDevicesForAttributes(*attr, nullptr, false);
5912 AudioDeviceTypeAddrVector devicesTypeAddress = devices.toTypeAddrVector();
5913 audio_config_t *configPtr = nullptr;
5914 audio_config_t config;
5915 if (mixerConfig != nullptr) {
5916 config = audio_config_initializer(mixerConfig);
5917 configPtr = &config;
5918 }
Andy Hung9dd1a5b2022-05-10 15:39:39 -07005919 if (!canBeSpatializedInt(attr, configPtr, devicesTypeAddress)) {
Eric Laurente191d1b2022-04-15 11:59:25 +02005920 ALOGV("%s provided attributes or mixer config cannot be spatialized", __func__);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005921 return BAD_VALUE;
5922 }
5923
5924 sp<IOProfile> profile =
Eric Laurent39095982021-08-24 18:29:27 +02005925 getSpatializerOutputProfile(configPtr, devicesTypeAddress);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005926 if (profile == nullptr) {
Eric Laurente191d1b2022-04-15 11:59:25 +02005927 ALOGV("%s no suitable output profile for provided attributes or mixer config", __func__);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005928 return BAD_VALUE;
5929 }
5930
Eric Laurente191d1b2022-04-15 11:59:25 +02005931 std::vector<sp<SwAudioOutputDescriptor>> spatializerOutputs;
Eric Laurent39095982021-08-24 18:29:27 +02005932 for (size_t i = 0; i < mOutputs.size(); i++) {
5933 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente191d1b2022-04-15 11:59:25 +02005934 if (!desc->isDuplicated()
5935 && (desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0) {
5936 spatializerOutputs.push_back(desc);
5937 ALOGV("%s adding opened spatializer Output %d", __func__, desc->mIoHandle);
Eric Laurent39095982021-08-24 18:29:27 +02005938 }
5939 }
Eric Laurente191d1b2022-04-15 11:59:25 +02005940 mSpatializerOutput.clear();
5941 bool outputsChanged = false;
5942 for (const auto& desc : spatializerOutputs) {
5943 if (desc->mProfile == profile
5944 && (configPtr == nullptr
5945 || configPtr->channel_mask == desc->mMixerChannelMask)) {
5946 mSpatializerOutput = desc;
5947 ALOGV("%s reusing current spatializer output %d", __func__, desc->mIoHandle);
5948 } else {
5949 ALOGV("%s closing spatializerOutput output %d to match channel mask %#x"
5950 " and devices %s", __func__, desc->mIoHandle,
5951 configPtr != nullptr ? configPtr->channel_mask : 0,
5952 devices.toString().c_str());
5953 closeOutput(desc->mIoHandle);
5954 outputsChanged = true;
5955 }
Eric Laurent39095982021-08-24 18:29:27 +02005956 }
5957
Eric Laurente191d1b2022-04-15 11:59:25 +02005958 if (mSpatializerOutput == nullptr) {
Eric Laurentb4f42a92022-01-17 17:37:31 +01005959 sp<SwAudioOutputDescriptor> desc =
5960 openOutputWithProfileAndDevice(profile, devices, mixerConfig);
Eric Laurente191d1b2022-04-15 11:59:25 +02005961 if (desc != nullptr) {
5962 mSpatializerOutput = desc;
5963 outputsChanged = true;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005964 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005965 }
5966
5967 checkVirtualizerClientRoutes();
5968
Eric Laurente191d1b2022-04-15 11:59:25 +02005969 if (outputsChanged) {
5970 mPreviousOutputs = mOutputs;
5971 mpClientInterface->onAudioPortListUpdate();
5972 }
5973
5974 if (mSpatializerOutput == nullptr) {
5975 ALOGV("%s could not open spatializer output with requested config", __func__);
5976 return BAD_VALUE;
5977 }
Eric Laurent39095982021-08-24 18:29:27 +02005978 *output = mSpatializerOutput->mIoHandle;
Eric Laurente191d1b2022-04-15 11:59:25 +02005979 ALOGV("%s returning new spatializer output %d", __func__, *output);
5980 return OK;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005981}
5982
Eric Laurentfa0f6742021-08-17 18:39:44 +02005983status_t AudioPolicyManager::releaseSpatializerOutput(audio_io_handle_t output) {
5984 if (mSpatializerOutput == nullptr) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005985 return INVALID_OPERATION;
5986 }
Eric Laurentfa0f6742021-08-17 18:39:44 +02005987 if (mSpatializerOutput->mIoHandle != output) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005988 return BAD_VALUE;
5989 }
Eric Laurent39095982021-08-24 18:29:27 +02005990
Eric Laurente191d1b2022-04-15 11:59:25 +02005991 if (!isOutputOnlyAvailableRouteToSomeDevice(mSpatializerOutput)) {
5992 ALOGV("%s closing spatializer output %d", __func__, mSpatializerOutput->mIoHandle);
5993 closeOutput(mSpatializerOutput->mIoHandle);
5994 //from now on mSpatializerOutput is null
5995 checkVirtualizerClientRoutes();
5996 }
Eric Laurent39095982021-08-24 18:29:27 +02005997
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005998 return NO_ERROR;
5999}
6000
Eric Laurente552edb2014-03-10 17:42:56 -07006001// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07006002// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07006003// ----------------------------------------------------------------------------
Eric Laurent6a94d692014-05-20 11:18:06 -07006004uint32_t AudioPolicyManager::nextAudioPortGeneration()
6005{
Mikhail Naganov2773dd72017-12-08 10:12:11 -08006006 return mAudioPortGeneration++;
Eric Laurent6a94d692014-05-20 11:18:06 -07006007}
6008
Mikhail Naganovb0fbc1b2023-04-28 13:06:32 -07006009AudioPolicyManager::AudioPolicyManager(const sp<const AudioPolicyConfig>& config,
Mikhail Naganovabb04782023-05-02 13:56:01 -07006010 EngineInstance&& engine,
Mikhail Naganovb0fbc1b2023-04-28 13:06:32 -07006011 AudioPolicyClientInterface *clientInterface)
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 Naganovb0fbc1b2023-04-28 13:06:32 -07006014 mConfig(config),
Mikhail Naganovabb04782023-05-02 13:56:01 -07006015 mEngine(std::move(engine)),
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006016 mpClientInterface(clientInterface),
Eric Laurente552edb2014-03-10 17:42:56 -07006017 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
Eric Laurent3a4311c2014-03-17 12:00:47 -07006018 mA2dpSuspended(false),
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006019 mAudioPortGeneration(1),
6020 mBeaconMuteRefCount(0),
6021 mBeaconPlayingRefCount(0),
Eric Laurent9459fb02015-08-12 18:36:32 -07006022 mBeaconMuted(false),
Andy Hung2ddee192015-12-18 17:34:44 -08006023 mTtsOutputAvailable(false),
Eric Laurent36829f92017-04-07 19:04:42 -07006024 mMasterMono(false),
Eric Laurent4eb58f12018-12-07 16:41:02 -08006025 mMusicEffectOutput(AUDIO_IO_HANDLE_NONE)
Eric Laurente552edb2014-03-10 17:42:56 -07006026{
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006027}
François Gaffied1ab2bd2015-12-02 18:20:06 +01006028
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006029status_t AudioPolicyManager::initialize() {
Mikhail Naganovabb04782023-05-02 13:56:01 -07006030 if (mEngine == nullptr) {
6031 return NO_INIT;
François Gaffie2110e042015-03-24 08:41:51 +01006032 }
6033 mEngine->setObserver(this);
6034 status_t status = mEngine->initCheck();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006035 if (status != NO_ERROR) {
6036 LOG_FATAL("Policy engine not initialized(err=%d)", status);
6037 return status;
6038 }
François Gaffie2110e042015-03-24 08:41:51 +01006039
jiabin76e829d2023-04-04 21:02:36 +00006040 // The actual device selection cache will be updated when calling `updateDevicesAndOutputs`
6041 // at the end of this function.
6042 mEngine->initializeDeviceSelectionCache();
Eric Laurent1d69c872021-01-11 18:53:01 +01006043 mCommunnicationStrategy = mEngine->getProductStrategyForAttributes(
6044 mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL));
6045
Mikhail Naganovb0fbc1b2023-04-28 13:06:32 -07006046 // after parsing the config, mConfig contain all known devices;
Eric Laurente552edb2014-03-10 17:42:56 -07006047 // open all output streams needed to access attached devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006048 onNewAudioModulesAvailableInt(nullptr /*newDevices*/);
François Gaffie11d30102018-11-02 16:09:09 +01006049
Eric Laurent3a4311c2014-03-17 12:00:47 -07006050 // make sure default device is reachable
Mikhail Naganovb0fbc1b2023-04-28 13:06:32 -07006051 if (const auto defaultOutputDevice = mConfig->getDefaultOutputDevice();
6052 defaultOutputDevice == nullptr ||
6053 !mAvailableOutputDevices.contains(defaultOutputDevice)) {
6054 ALOGE_IF(defaultOutputDevice != nullptr, "Default device %s is unreachable",
6055 defaultOutputDevice->toString().c_str());
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006056 status = NO_INIT;
Eric Laurent3a4311c2014-03-17 12:00:47 -07006057 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02006058 ALOGW_IF(mPrimaryOutput == nullptr, "The policy configuration does not declare a primary output");
Eric Laurente552edb2014-03-10 17:42:56 -07006059
Tomoharu Kasahara71c90912018-10-31 09:10:12 +09006060 // Silence ALOGV statements
6061 property_set("log.tag." LOG_TAG, "D");
6062
Eric Laurente552edb2014-03-10 17:42:56 -07006063 updateDevicesAndOutputs();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006064 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07006065}
6066
Eric Laurente0720872014-03-11 09:30:41 -07006067AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07006068{
Eric Laurente552edb2014-03-10 17:42:56 -07006069 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08006070 mOutputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07006071 }
6072 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08006073 mInputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07006074 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07006075 mAvailableOutputDevices.clear();
6076 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07006077 mOutputs.clear();
6078 mInputs.clear();
6079 mHwModules.clear();
Mikhail Naganov100f0122018-11-29 11:22:16 -08006080 mManualSurroundFormats.clear();
Mikhail Naganovb0fbc1b2023-04-28 13:06:32 -07006081 mConfig.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07006082}
6083
Eric Laurente0720872014-03-11 09:30:41 -07006084status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07006085{
Eric Laurent87ffa392015-05-22 10:32:38 -07006086 return hasPrimaryOutput() ? NO_ERROR : NO_INIT;
Eric Laurente552edb2014-03-10 17:42:56 -07006087}
6088
Eric Laurente552edb2014-03-10 17:42:56 -07006089// ---
6090
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006091void AudioPolicyManager::onNewAudioModulesAvailable()
6092{
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006093 DeviceVector newDevices;
6094 onNewAudioModulesAvailableInt(&newDevices);
6095 if (!newDevices.empty()) {
6096 nextAudioPortGeneration();
6097 mpClientInterface->onAudioPortListUpdate();
6098 }
6099}
6100
6101void AudioPolicyManager::onNewAudioModulesAvailableInt(DeviceVector *newDevices)
6102{
Mikhail Naganovb0fbc1b2023-04-28 13:06:32 -07006103 for (const auto& hwModule : mConfig->getHwModules()) {
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006104 if (std::find(mHwModules.begin(), mHwModules.end(), hwModule) != mHwModules.end()) {
6105 continue;
6106 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006107 if (hwModule->getHandle() == AUDIO_MODULE_HANDLE_NONE) {
Mikhail Naganov1fba38c2023-05-03 17:45:36 -07006108 if (audio_module_handle_t handle = mpClientInterface->loadHwModule(hwModule->getName());
6109 handle != AUDIO_MODULE_HANDLE_NONE) {
6110 hwModule->setHandle(handle);
6111 } else {
6112 ALOGW("could not load HW module %s", hwModule->getName());
6113 continue;
6114 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006115 }
6116 mHwModules.push_back(hwModule);
Dean Wheatley12a87132021-04-16 10:08:49 +10006117 // open all output streams needed to access attached devices.
6118 // direct outputs are closed immediately after checking the availability of attached devices
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006119 // This also validates mAvailableOutputDevices list
6120 for (const auto& outProfile : hwModule->getOutputProfiles()) {
6121 if (!outProfile->canOpenNewIo()) {
6122 ALOGE("Invalid Output profile max open count %u for profile %s",
6123 outProfile->maxOpenCount, outProfile->getTagName().c_str());
6124 continue;
6125 }
6126 if (!outProfile->hasSupportedDevices()) {
6127 ALOGW("Output profile contains no device on module %s", hwModule->getName());
6128 continue;
6129 }
Carter Hsu1a3364a2022-01-21 15:32:56 +08006130 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_TTS) != 0 ||
6131 (outProfile->getFlags() & AUDIO_OUTPUT_FLAG_ULTRASOUND) != 0) {
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006132 mTtsOutputAvailable = true;
6133 }
6134
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006135 const DeviceVector &supportedDevices = outProfile->getSupportedDevices();
Mikhail Naganovb0fbc1b2023-04-28 13:06:32 -07006136 DeviceVector availProfileDevices = supportedDevices.filter(mConfig->getOutputDevices());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006137 sp<DeviceDescriptor> supportedDevice = 0;
Mikhail Naganovb0fbc1b2023-04-28 13:06:32 -07006138 if (supportedDevices.contains(mConfig->getDefaultOutputDevice())) {
6139 supportedDevice = mConfig->getDefaultOutputDevice();
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006140 } else {
6141 // choose first device present in profile's SupportedDevices also part of
6142 // mAvailableOutputDevices.
6143 if (availProfileDevices.isEmpty()) {
6144 continue;
6145 }
6146 supportedDevice = availProfileDevices.itemAt(0);
6147 }
Mikhail Naganovb0fbc1b2023-04-28 13:06:32 -07006148 if (!mConfig->getOutputDevices().contains(supportedDevice)) {
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006149 continue;
6150 }
6151 sp<SwAudioOutputDescriptor> outputDesc = new SwAudioOutputDescriptor(outProfile,
6152 mpClientInterface);
6153 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentf1f22e72021-07-13 14:04:14 +02006154 status_t status = outputDesc->open(nullptr /* halConfig */, nullptr /* mixerConfig */,
6155 DeviceVector(supportedDevice),
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006156 AUDIO_STREAM_DEFAULT,
6157 AUDIO_OUTPUT_FLAG_NONE, &output);
6158 if (status != NO_ERROR) {
6159 ALOGW("Cannot open output stream for devices %s on hw module %s",
6160 supportedDevice->toString().c_str(), hwModule->getName());
6161 continue;
6162 }
6163 for (const auto &device : availProfileDevices) {
6164 // give a valid ID to an attached device once confirmed it is reachable
6165 if (!device->isAttached()) {
6166 device->attach(hwModule);
6167 mAvailableOutputDevices.add(device);
jiabin1c4794b2020-05-05 10:08:05 -07006168 device->setEncapsulationInfoFromHal(mpClientInterface);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006169 if (newDevices) newDevices->add(device);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006170 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
6171 }
6172 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02006173 if (mPrimaryOutput == nullptr &&
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006174 outProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
6175 mPrimaryOutput = outputDesc;
6176 }
Eric Laurent39095982021-08-24 18:29:27 +02006177 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
Eric Laurentc529cf62020-04-17 18:19:10 -07006178 outputDesc->close();
6179 } else {
6180 addOutput(output, outputDesc);
6181 setOutputDevices(outputDesc,
6182 DeviceVector(supportedDevice),
6183 true,
6184 0,
6185 NULL);
6186 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006187 }
6188 // open input streams needed to access attached devices to validate
6189 // mAvailableInputDevices list
6190 for (const auto& inProfile : hwModule->getInputProfiles()) {
6191 if (!inProfile->canOpenNewIo()) {
6192 ALOGE("Invalid Input profile max open count %u for profile %s",
6193 inProfile->maxOpenCount, inProfile->getTagName().c_str());
6194 continue;
6195 }
6196 if (!inProfile->hasSupportedDevices()) {
6197 ALOGW("Input profile contains no device on module %s", hwModule->getName());
6198 continue;
6199 }
6200 // chose first device present in profile's SupportedDevices also part of
6201 // available input devices
6202 const DeviceVector &supportedDevices = inProfile->getSupportedDevices();
Mikhail Naganovb0fbc1b2023-04-28 13:06:32 -07006203 DeviceVector availProfileDevices = supportedDevices.filter(mConfig->getInputDevices());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006204 if (availProfileDevices.isEmpty()) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01006205 ALOGV("%s: Input device list is empty! for profile %s",
6206 __func__, inProfile->getTagName().c_str());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006207 continue;
6208 }
6209 sp<AudioInputDescriptor> inputDesc =
6210 new AudioInputDescriptor(inProfile, mpClientInterface);
6211
6212 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
6213 status_t status = inputDesc->open(nullptr,
6214 availProfileDevices.itemAt(0),
6215 AUDIO_SOURCE_MIC,
6216 AUDIO_INPUT_FLAG_NONE,
6217 &input);
6218 if (status != NO_ERROR) {
6219 ALOGW("Cannot open input stream for device %s on hw module %s",
6220 availProfileDevices.toString().c_str(),
6221 hwModule->getName());
6222 continue;
6223 }
6224 for (const auto &device : availProfileDevices) {
6225 // give a valid ID to an attached device once confirmed it is reachable
6226 if (!device->isAttached()) {
6227 device->attach(hwModule);
6228 device->importAudioPortAndPickAudioProfile(inProfile, true);
6229 mAvailableInputDevices.add(device);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006230 if (newDevices) newDevices->add(device);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006231 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
6232 }
6233 }
6234 inputDesc->close();
6235 }
6236 }
Eric Laurente191d1b2022-04-15 11:59:25 +02006237
6238 // Check if spatializer outputs can be closed until used.
6239 // mOutputs vector never contains duplicated outputs at this point.
6240 std::vector<audio_io_handle_t> outputsClosed;
6241 for (size_t i = 0; i < mOutputs.size(); i++) {
6242 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
6243 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0
6244 && !isOutputOnlyAvailableRouteToSomeDevice(desc)) {
6245 outputsClosed.push_back(desc->mIoHandle);
6246 desc->close();
6247 }
6248 }
6249 for (auto output : outputsClosed) {
6250 removeOutput(output);
6251 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006252}
6253
Eric Laurent98e38192018-02-15 18:31:53 -08006254void AudioPolicyManager::addOutput(audio_io_handle_t output,
6255 const sp<SwAudioOutputDescriptor>& outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07006256{
Eric Laurent1c333e22014-05-20 10:48:17 -07006257 mOutputs.add(output, outputDesc);
jiabin9a3361e2019-10-01 09:38:30 -07006258 applyStreamVolumes(outputDesc, DeviceTypeSet(), 0 /* delayMs */, true /* force */);
Andy Hung2ddee192015-12-18 17:34:44 -08006259 updateMono(output); // update mono status when adding to output list
Eric Laurent36829f92017-04-07 19:04:42 -07006260 selectOutputForMusicEffects();
Eric Laurent6a94d692014-05-20 11:18:06 -07006261 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07006262}
6263
François Gaffie53615e22015-03-19 09:24:12 +01006264void AudioPolicyManager::removeOutput(audio_io_handle_t output)
6265{
Francois Gaffiebce7cd42020-10-14 16:13:20 +02006266 if (mPrimaryOutput != 0 && mPrimaryOutput == mOutputs.valueFor(output)) {
6267 ALOGV("%s: removing primary output", __func__);
6268 mPrimaryOutput = nullptr;
6269 }
François Gaffie53615e22015-03-19 09:24:12 +01006270 mOutputs.removeItem(output);
Eric Laurent36829f92017-04-07 19:04:42 -07006271 selectOutputForMusicEffects();
François Gaffie53615e22015-03-19 09:24:12 +01006272}
6273
Eric Laurent98e38192018-02-15 18:31:53 -08006274void AudioPolicyManager::addInput(audio_io_handle_t input,
6275 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07006276{
Eric Laurent1c333e22014-05-20 10:48:17 -07006277 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07006278 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07006279}
Eric Laurente552edb2014-03-10 17:42:56 -07006280
François Gaffie11d30102018-11-02 16:09:09 +01006281status_t AudioPolicyManager::checkOutputsForDevice(const sp<DeviceDescriptor>& device,
François Gaffie53615e22015-03-19 09:24:12 +01006282 audio_policy_dev_state_t state,
François Gaffie11d30102018-11-02 16:09:09 +01006283 SortedVector<audio_io_handle_t>& outputs)
Eric Laurente552edb2014-03-10 17:42:56 -07006284{
François Gaffie11d30102018-11-02 16:09:09 +01006285 audio_devices_t deviceType = device->type();
jiabince9f20e2019-09-12 16:29:15 -07006286 const String8 &address = String8(device->address().c_str());
Eric Laurentc75307b2015-03-17 15:29:32 -07006287 sp<SwAudioOutputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07006288
François Gaffie11d30102018-11-02 16:09:09 +01006289 if (audio_device_is_digital(deviceType)) {
Eric Laurentcc750d32015-06-25 11:48:20 -07006290 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01006291 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07006292 }
Eric Laurente552edb2014-03-10 17:42:56 -07006293
Eric Laurent3b73df72014-03-11 09:06:29 -07006294 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
jiabinb4fed192020-09-22 14:45:40 -07006295 // first call getAudioPort to get the supported attributes from the HAL
6296 struct audio_port_v7 port = {};
6297 device->toAudioPort(&port);
6298 status_t status = mpClientInterface->getAudioPort(&port);
6299 if (status == NO_ERROR) {
6300 device->importAudioPort(port);
6301 }
6302
6303 // then list already open outputs that can be routed to this device
Eric Laurente552edb2014-03-10 17:42:56 -07006304 for (size_t i = 0; i < mOutputs.size(); i++) {
6305 desc = mOutputs.valueAt(i);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006306 if (!desc->isDuplicated() && desc->supportsDevice(device)
jiabin9a3361e2019-10-01 09:38:30 -07006307 && desc->devicesSupportEncodedFormats({deviceType})) {
François Gaffie11d30102018-11-02 16:09:09 +01006308 ALOGV("checkOutputsForDevice(): adding opened output %d on device %s",
6309 mOutputs.keyAt(i), device->toString().c_str());
6310 outputs.add(mOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07006311 }
6312 }
6313 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07006314 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006315 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006316 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
6317 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
François Gaffie11d30102018-11-02 16:09:09 +01006318 if (profile->supportsDevice(device)) {
6319 profiles.add(profile);
6320 ALOGV("checkOutputsForDevice(): adding profile %zu from module %s",
6321 j, hwModule->getName());
Eric Laurente552edb2014-03-10 17:42:56 -07006322 }
6323 }
6324 }
6325
Eric Laurent7b279bb2015-12-14 10:18:23 -08006326 ALOGV(" found %zu profiles, %zu outputs", profiles.size(), outputs.size());
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006327
Eric Laurente552edb2014-03-10 17:42:56 -07006328 if (profiles.isEmpty() && outputs.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006329 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07006330 return BAD_VALUE;
6331 }
6332
6333 // open outputs for matching profiles if needed. Direct outputs are also opened to
6334 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
6335 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07006336 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07006337
6338 // nothing to do if one output is already opened for this profile
6339 size_t j;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006340 for (j = 0; j < outputs.size(); j++) {
6341 desc = mOutputs.valueFor(outputs.itemAt(j));
Eric Laurente552edb2014-03-10 17:42:56 -07006342 if (!desc->isDuplicated() && desc->mProfile == profile) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07006343 // matching profile: save the sample rates, format and channel masks supported
6344 // by the profile in our device descriptor
François Gaffie11d30102018-11-02 16:09:09 +01006345 if (audio_device_is_digital(deviceType)) {
jiabin4ef93452019-09-10 14:29:54 -07006346 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006347 }
Eric Laurente552edb2014-03-10 17:42:56 -07006348 break;
6349 }
6350 }
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006351 if (j != outputs.size()) {
Eric Laurente552edb2014-03-10 17:42:56 -07006352 continue;
6353 }
6354
Eric Laurent3974e3b2017-12-07 17:58:43 -08006355 if (!profile->canOpenNewIo()) {
6356 ALOGW("Max Output number %u already opened for this profile %s",
6357 profile->maxOpenCount, profile->getTagName().c_str());
6358 continue;
6359 }
6360
Eric Laurent83efe1c2017-07-09 16:51:08 -07006361 ALOGV("opening output for device %08x with params %s profile %p name %s",
Tomasz Wasilczyk8f36f6e2023-08-15 20:59:35 +00006362 deviceType, address.c_str(), profile.get(), profile->getName().c_str());
jiabinbce0c1d2020-10-05 11:20:18 -07006363 desc = openOutputWithProfileAndDevice(profile, DeviceVector(device));
6364 audio_io_handle_t output = desc == nullptr ? AUDIO_IO_HANDLE_NONE : desc->mIoHandle;
Eric Laurentcf2c0212014-07-25 16:20:43 -07006365 if (output == AUDIO_IO_HANDLE_NONE) {
François Gaffie11d30102018-11-02 16:09:09 +01006366 ALOGW("checkOutputsForDevice() could not open output for device %x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07006367 profiles.removeAt(profile_index);
6368 profile_index--;
6369 } else {
6370 outputs.add(output);
Paul McLean9080a4c2015-06-18 08:24:02 -07006371 // Load digital format info only for digital devices
François Gaffie11d30102018-11-02 16:09:09 +01006372 if (audio_device_is_digital(deviceType)) {
jiabinbce0c1d2020-10-05 11:20:18 -07006373 // TODO: when getAudioPort is ready, it may not be needed to import the audio
6374 // port but just pick audio profile
jiabin4ef93452019-09-10 14:29:54 -07006375 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006376 }
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07006377
François Gaffie11d30102018-11-02 16:09:09 +01006378 if (device_distinguishes_on_address(deviceType)) {
6379 ALOGV("checkOutputsForDevice(): setOutputDevices %s",
6380 device->toString().c_str());
6381 setOutputDevices(desc, DeviceVector(device), true/*force*/, 0/*delay*/,
6382 NULL/*patch handle*/);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006383 }
Eric Laurente552edb2014-03-10 17:42:56 -07006384 ALOGV("checkOutputsForDevice(): adding output %d", output);
6385 }
6386 }
6387
6388 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006389 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07006390 return BAD_VALUE;
6391 }
Eric Laurentd4692962014-05-05 18:13:44 -07006392 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07006393 // check if one opened output is not needed any more after disconnecting one device
6394 for (size_t i = 0; i < mOutputs.size(); i++) {
6395 desc = mOutputs.valueAt(i);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006396 if (!desc->isDuplicated()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08006397 // exact match on device
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006398 if (device_distinguishes_on_address(deviceType) && desc->supportsDevice(device)
Francois Gaffiec7d4c222021-12-02 11:12:52 +01006399 && desc->containsSingleDeviceSupportingEncodedFormats(device)) {
François Gaffie11d30102018-11-02 16:09:09 +01006400 outputs.add(mOutputs.keyAt(i));
Francois Gaffie716e1432019-01-14 16:58:59 +01006401 } else if (!mAvailableOutputDevices.containsAtLeastOne(desc->supportedDevices())) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006402 ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
6403 mOutputs.keyAt(i));
6404 outputs.add(mOutputs.keyAt(i));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006405 }
Eric Laurente552edb2014-03-10 17:42:56 -07006406 }
6407 }
Eric Laurentd4692962014-05-05 18:13:44 -07006408 // Clear any profiles associated with the disconnected device.
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006409 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006410 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
6411 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
jiabinbce0c1d2020-10-05 11:20:18 -07006412 if (!profile->supportsDevice(device)) {
6413 continue;
6414 }
6415 ALOGV("checkOutputsForDevice(): "
6416 "clearing direct output profile %zu on module %s",
6417 j, hwModule->getName());
6418 profile->clearAudioProfiles();
6419 if (!profile->hasDynamicAudioProfile()) {
6420 continue;
6421 }
6422 // When a device is disconnected, if there is an IOProfile that contains dynamic
6423 // profiles and supports the disconnected device, call getAudioPort to repopulate
6424 // the capabilities of the devices that is supported by the IOProfile.
6425 for (const auto& supportedDevice : profile->getSupportedDevices()) {
6426 if (supportedDevice == device ||
6427 !mAvailableOutputDevices.contains(supportedDevice)) {
6428 continue;
6429 }
6430 struct audio_port_v7 port;
6431 supportedDevice->toAudioPort(&port);
6432 status_t status = mpClientInterface->getAudioPort(&port);
6433 if (status == NO_ERROR) {
6434 supportedDevice->importAudioPort(port);
6435 }
Eric Laurente552edb2014-03-10 17:42:56 -07006436 }
6437 }
6438 }
6439 }
6440 return NO_ERROR;
6441}
6442
François Gaffie11d30102018-11-02 16:09:09 +01006443status_t AudioPolicyManager::checkInputsForDevice(const sp<DeviceDescriptor>& device,
Eric Laurent0dd51852019-04-19 18:18:58 -07006444 audio_policy_dev_state_t state)
Eric Laurentd4692962014-05-05 18:13:44 -07006445{
Eric Laurent1f2f2232014-06-02 12:01:23 -07006446 sp<AudioInputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07006447
François Gaffie11d30102018-11-02 16:09:09 +01006448 if (audio_device_is_digital(device->type())) {
Eric Laurentcc750d32015-06-25 11:48:20 -07006449 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01006450 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07006451 }
6452
Eric Laurentd4692962014-05-05 18:13:44 -07006453 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
jiabinbf5f4262023-04-12 21:48:34 +00006454 // first call getAudioPort to get the supported attributes from the HAL
6455 struct audio_port_v7 port = {};
6456 device->toAudioPort(&port);
6457 status_t status = mpClientInterface->getAudioPort(&port);
6458 if (status == NO_ERROR) {
6459 device->importAudioPort(port);
6460 }
6461
Eric Laurent0dd51852019-04-19 18:18:58 -07006462 // look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07006463 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006464 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07006465 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006466 profile_index < hwModule->getInputProfiles().size();
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006467 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006468 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Eric Laurent275e8e92014-11-30 15:14:47 -08006469
François Gaffie11d30102018-11-02 16:09:09 +01006470 if (profile->supportsDevice(device)) {
6471 profiles.add(profile);
6472 ALOGV("checkInputsForDevice(): adding profile %zu from module %s",
6473 profile_index, hwModule->getName());
Eric Laurentd4692962014-05-05 18:13:44 -07006474 }
6475 }
6476 }
6477
Eric Laurent0dd51852019-04-19 18:18:58 -07006478 if (profiles.isEmpty()) {
6479 ALOGW("%s: No input profile available for device %s",
6480 __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07006481 return BAD_VALUE;
6482 }
6483
6484 // open inputs for matching profiles if needed. Direct inputs are also opened to
6485 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
6486 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
6487
Eric Laurent1c333e22014-05-20 10:48:17 -07006488 sp<IOProfile> profile = profiles[profile_index];
Eric Laurent3974e3b2017-12-07 17:58:43 -08006489
Eric Laurentd4692962014-05-05 18:13:44 -07006490 // nothing to do if one input is already opened for this profile
6491 size_t input_index;
6492 for (input_index = 0; input_index < mInputs.size(); input_index++) {
6493 desc = mInputs.valueAt(input_index);
6494 if (desc->mProfile == profile) {
François Gaffie11d30102018-11-02 16:09:09 +01006495 if (audio_device_is_digital(device->type())) {
jiabin4ef93452019-09-10 14:29:54 -07006496 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006497 }
Eric Laurentd4692962014-05-05 18:13:44 -07006498 break;
6499 }
6500 }
6501 if (input_index != mInputs.size()) {
6502 continue;
6503 }
6504
Eric Laurent3974e3b2017-12-07 17:58:43 -08006505 if (!profile->canOpenNewIo()) {
6506 ALOGW("Max Input number %u already opened for this profile %s",
6507 profile->maxOpenCount, profile->getTagName().c_str());
6508 continue;
6509 }
6510
Eric Laurentfe231122017-11-17 17:48:06 -08006511 desc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentcf2c0212014-07-25 16:20:43 -07006512 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
jiabinbf5f4262023-04-12 21:48:34 +00006513 status = desc->open(nullptr, device, AUDIO_SOURCE_MIC, AUDIO_INPUT_FLAG_NONE, &input);
Eric Laurentd4692962014-05-05 18:13:44 -07006514
Eric Laurentcf2c0212014-07-25 16:20:43 -07006515 if (status == NO_ERROR) {
jiabince9f20e2019-09-12 16:29:15 -07006516 const String8& address = String8(device->address().c_str());
Tomasz Wasilczykfd9ffd12023-08-14 17:56:22 +00006517 if (!address.empty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006518 char *param = audio_device_address_to_parameter(device->type(), address);
Eric Laurentcf2c0212014-07-25 16:20:43 -07006519 mpClientInterface->setParameters(input, String8(param));
6520 free(param);
Eric Laurentd4692962014-05-05 18:13:44 -07006521 }
François Gaffie11d30102018-11-02 16:09:09 +01006522 updateAudioProfiles(device, input, profile->getAudioProfiles());
François Gaffie112b0af2015-11-19 16:13:25 +01006523 if (!profile->hasValidAudioProfile()) {
Eric Laurentd4692962014-05-05 18:13:44 -07006524 ALOGW("checkInputsForDevice() direct input missing param");
Eric Laurentfe231122017-11-17 17:48:06 -08006525 desc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07006526 input = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07006527 }
6528
Eric Laurent0dd51852019-04-19 18:18:58 -07006529 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07006530 addInput(input, desc);
6531 }
6532 } // endif input != 0
6533
Eric Laurentcf2c0212014-07-25 16:20:43 -07006534 if (input == AUDIO_IO_HANDLE_NONE) {
Pattydd807582021-11-04 21:01:03 +08006535 ALOGW("%s could not open input for device %s", __func__,
François Gaffie11d30102018-11-02 16:09:09 +01006536 device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07006537 profiles.removeAt(profile_index);
6538 profile_index--;
6539 } else {
François Gaffie11d30102018-11-02 16:09:09 +01006540 if (audio_device_is_digital(device->type())) {
jiabin4ef93452019-09-10 14:29:54 -07006541 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006542 }
Eric Laurentd4692962014-05-05 18:13:44 -07006543 ALOGV("checkInputsForDevice(): adding input %d", input);
6544 }
6545 } // end scan profiles
6546
6547 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006548 ALOGW("%s: No input available for device %s", __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07006549 return BAD_VALUE;
6550 }
6551 } else {
6552 // Disconnect
Eric Laurentd4692962014-05-05 18:13:44 -07006553 // Clear any profiles associated with the disconnected device.
Mikhail Naganovd4120142017-12-06 15:49:22 -08006554 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07006555 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006556 profile_index < hwModule->getInputProfiles().size();
Eric Laurentd4692962014-05-05 18:13:44 -07006557 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006558 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Francois Gaffie716e1432019-01-14 16:58:59 +01006559 if (profile->supportsDevice(device)) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08006560 ALOGV("checkInputsForDevice(): clearing direct input profile %zu on module %s",
6561 profile_index, hwModule->getName());
François Gaffie112b0af2015-11-19 16:13:25 +01006562 profile->clearAudioProfiles();
Eric Laurentd4692962014-05-05 18:13:44 -07006563 }
6564 }
6565 }
6566 } // end disconnect
6567
6568 return NO_ERROR;
6569}
6570
6571
Eric Laurente0720872014-03-11 09:30:41 -07006572void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07006573{
6574 ALOGV("closeOutput(%d)", output);
6575
François Gaffie1c878552018-11-22 16:53:21 +01006576 sp<SwAudioOutputDescriptor> closingOutput = mOutputs.valueFor(output);
6577 if (closingOutput == NULL) {
Eric Laurente552edb2014-03-10 17:42:56 -07006578 ALOGW("closeOutput() unknown output %d", output);
6579 return;
6580 }
Mikhail Naganov32ebca32019-03-22 15:42:52 -07006581 const bool closingOutputWasActive = closingOutput->isActive();
François Gaffie1c878552018-11-22 16:53:21 +01006582 mPolicyMixes.closeOutput(closingOutput);
Eric Laurent275e8e92014-11-30 15:14:47 -08006583
Eric Laurente552edb2014-03-10 17:42:56 -07006584 // look for duplicated outputs connected to the output being removed.
6585 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie1c878552018-11-22 16:53:21 +01006586 sp<SwAudioOutputDescriptor> dupOutput = mOutputs.valueAt(i);
6587 if (dupOutput->isDuplicated() &&
6588 (dupOutput->mOutput1 == closingOutput || dupOutput->mOutput2 == closingOutput)) {
6589 sp<SwAudioOutputDescriptor> remainingOutput =
6590 dupOutput->mOutput1 == closingOutput ? dupOutput->mOutput2 : dupOutput->mOutput1;
Eric Laurente552edb2014-03-10 17:42:56 -07006591 // As all active tracks on duplicated output will be deleted,
6592 // and as they were also referenced on the other output, the reference
6593 // count for their stream type must be adjusted accordingly on
6594 // the other output.
François Gaffie1c878552018-11-22 16:53:21 +01006595 const bool wasActive = remainingOutput->isActive();
6596 // Note: no-op on the closing output where all clients has already been set inactive
6597 dupOutput->setAllClientsInactive();
Eric Laurent733ce942017-12-07 12:18:25 -08006598 // stop() will be a no op if the output is still active but is needed in case all
6599 // active streams refcounts where cleared above
6600 if (wasActive) {
François Gaffie1c878552018-11-22 16:53:21 +01006601 remainingOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08006602 }
Eric Laurente552edb2014-03-10 17:42:56 -07006603 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
6604 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
6605
6606 mpClientInterface->closeOutput(duplicatedOutput);
François Gaffie53615e22015-03-19 09:24:12 +01006607 removeOutput(duplicatedOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07006608 }
6609 }
6610
Eric Laurent05b90f82014-08-27 15:32:29 -07006611 nextAudioPortGeneration();
6612
François Gaffie1c878552018-11-22 16:53:21 +01006613 ssize_t index = mAudioPatches.indexOfKey(closingOutput->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07006614 if (index >= 0) {
6615 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006616 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
6617 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07006618 mAudioPatches.removeItemsAt(index);
6619 mpClientInterface->onAudioPatchListUpdate();
6620 }
6621
Mikhail Naganov32ebca32019-03-22 15:42:52 -07006622 if (closingOutputWasActive) {
6623 closingOutput->stop();
6624 }
François Gaffie1c878552018-11-22 16:53:21 +01006625 closingOutput->close();
Eric Laurente552edb2014-03-10 17:42:56 -07006626
François Gaffie53615e22015-03-19 09:24:12 +01006627 removeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07006628 mPreviousOutputs = mOutputs;
Eric Laurentb4f42a92022-01-17 17:37:31 +01006629 if (closingOutput == mSpatializerOutput) {
6630 mSpatializerOutput.clear();
6631 }
Dean Wheatley3023b382018-08-09 07:42:40 +10006632
6633 // MSD patches may have been released to support a non-MSD direct output. Reset MSD patch if
6634 // no direct outputs are open.
François Gaffie11d30102018-11-02 16:09:09 +01006635 if (!getMsdAudioOutDevices().isEmpty()) {
Dean Wheatley3023b382018-08-09 07:42:40 +10006636 bool directOutputOpen = false;
6637 for (size_t i = 0; i < mOutputs.size(); i++) {
6638 if (mOutputs[i]->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
6639 directOutputOpen = true;
6640 break;
6641 }
6642 }
6643 if (!directOutputOpen) {
Michael Chan6fb34492020-12-08 15:44:49 +11006644 ALOGV("no direct outputs open, reset MSD patches");
6645 // TODO: The MSD patches to be established here may differ to current MSD patches due to
6646 // how output devices for patching are resolved. Avoid by caching and reusing the
6647 // arguments to mEngine->getOutputDevicesForAttributes() when resolving which output
6648 // devices to patch to. This may be complicated by the fact that devices may become
6649 // unavailable.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11006650 setMsdOutputPatches();
Dean Wheatley3023b382018-08-09 07:42:40 +10006651 }
6652 }
Eric Laurent05b90f82014-08-27 15:32:29 -07006653}
6654
6655void AudioPolicyManager::closeInput(audio_io_handle_t input)
6656{
6657 ALOGV("closeInput(%d)", input);
6658
6659 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
6660 if (inputDesc == NULL) {
6661 ALOGW("closeInput() unknown input %d", input);
6662 return;
6663 }
6664
Eric Laurent6a94d692014-05-20 11:18:06 -07006665 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07006666
François Gaffie11d30102018-11-02 16:09:09 +01006667 sp<DeviceDescriptor> device = inputDesc->getDevice();
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08006668 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07006669 if (index >= 0) {
6670 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006671 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
6672 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07006673 mAudioPatches.removeItemsAt(index);
6674 mpClientInterface->onAudioPatchListUpdate();
6675 }
6676
Eric Laurentfe231122017-11-17 17:48:06 -08006677 inputDesc->close();
Eric Laurent05b90f82014-08-27 15:32:29 -07006678 mInputs.removeItem(input);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07006679
François Gaffie11d30102018-11-02 16:09:09 +01006680 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
6681 if (primaryInputDevices.contains(device) &&
Haynes Mathew George1d539d92018-03-16 11:40:49 -07006682 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07006683 mpClientInterface->setSoundTriggerCaptureState(false);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07006684 }
Eric Laurente552edb2014-03-10 17:42:56 -07006685}
6686
François Gaffie11d30102018-11-02 16:09:09 +01006687SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevices(
6688 const DeviceVector &devices,
6689 const SwAudioOutputCollection& openOutputs)
Eric Laurente552edb2014-03-10 17:42:56 -07006690{
6691 SortedVector<audio_io_handle_t> outputs;
6692
François Gaffie11d30102018-11-02 16:09:09 +01006693 ALOGVV("%s() devices %s", __func__, devices.toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07006694 for (size_t i = 0; i < openOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01006695 ALOGVV("output %zu isDuplicated=%d device=%s",
Eric Laurent8c7e6da2015-04-21 17:37:00 -07006696 i, openOutputs.valueAt(i)->isDuplicated(),
François Gaffie11d30102018-11-02 16:09:09 +01006697 openOutputs.valueAt(i)->supportedDevices().toString().c_str());
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006698 if (openOutputs.valueAt(i)->supportsAllDevices(devices)
jiabin9a3361e2019-10-01 09:38:30 -07006699 && openOutputs.valueAt(i)->devicesSupportEncodedFormats(devices.types())) {
François Gaffie11d30102018-11-02 16:09:09 +01006700 ALOGVV("%s() found output %d", __func__, openOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07006701 outputs.add(openOutputs.keyAt(i));
6702 }
6703 }
6704 return outputs;
6705}
6706
Mikhail Naganov37977152018-07-11 15:54:44 -07006707void AudioPolicyManager::checkForDeviceAndOutputChanges(std::function<bool()> onOutputsChecked)
6708{
6709 // checkA2dpSuspend must run before checkOutputForAllStrategies so that A2DP
6710 // output is suspended before any tracks are moved to it
6711 checkA2dpSuspend();
6712 checkOutputForAllStrategies();
Kevin Rocard153f92d2018-12-18 18:33:28 -08006713 checkSecondaryOutputs();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11006714 if (onOutputsChecked != nullptr && onOutputsChecked()) checkA2dpSuspend();
Mikhail Naganov37977152018-07-11 15:54:44 -07006715 updateDevicesAndOutputs();
Mikhail Naganov7bd9b8d2018-11-15 02:09:03 +00006716 if (mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD) != 0) {
Michael Chan6fb34492020-12-08 15:44:49 +11006717 // TODO: The MSD patches to be established here may differ to current MSD patches due to how
6718 // output devices for patching are resolved. Nevertheless, AudioTracks affected by device
6719 // configuration changes will ultimately be rerouted correctly. We can still avoid
6720 // unnecessary rerouting by caching and reusing the arguments to
6721 // mEngine->getOutputDevicesForAttributes() when resolving which output devices to patch to.
6722 // This may be complicated by the fact that devices may become unavailable.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11006723 setMsdOutputPatches();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11006724 }
Jean-Michel Trivi9a6b9ad2020-10-22 16:46:43 -07006725 // an event that changed routing likely occurred, inform upper layers
6726 mpClientInterface->onRoutingUpdated();
Mikhail Naganov37977152018-07-11 15:54:44 -07006727}
6728
François Gaffiec005e562018-11-06 15:04:49 +01006729bool AudioPolicyManager::followsSameRouting(const audio_attributes_t &lAttr,
6730 const audio_attributes_t &rAttr) const
Eric Laurente552edb2014-03-10 17:42:56 -07006731{
François Gaffiec005e562018-11-06 15:04:49 +01006732 return mEngine->getProductStrategyForAttributes(lAttr) ==
6733 mEngine->getProductStrategyForAttributes(rAttr);
6734}
6735
Francois Gaffieff1eb522020-05-06 18:37:04 +02006736void AudioPolicyManager::checkAudioSourceForAttributes(const audio_attributes_t &attr)
6737{
6738 for (size_t i = 0; i < mAudioSources.size(); i++) {
6739 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
6740 if (sourceDesc != nullptr && followsSameRouting(attr, sourceDesc->attributes())
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02006741 && sourceDesc->getPatchHandle() == AUDIO_PATCH_HANDLE_NONE
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02006742 && !isCallRxAudioSource(sourceDesc) && !sourceDesc->isInternal()) {
Francois Gaffieff1eb522020-05-06 18:37:04 +02006743 connectAudioSource(sourceDesc);
6744 }
6745 }
6746}
6747
6748void AudioPolicyManager::clearAudioSourcesForOutput(audio_io_handle_t output)
6749{
6750 for (size_t i = 0; i < mAudioSources.size(); i++) {
6751 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
6752 if (sourceDesc != nullptr && sourceDesc->swOutput().promote() != nullptr
6753 && sourceDesc->swOutput().promote()->mIoHandle == output) {
6754 disconnectAudioSource(sourceDesc);
6755 }
6756 }
6757}
6758
François Gaffiec005e562018-11-06 15:04:49 +01006759void AudioPolicyManager::checkOutputForAttributes(const audio_attributes_t &attr)
6760{
6761 auto psId = mEngine->getProductStrategyForAttributes(attr);
6762
6763 DeviceVector oldDevices = mEngine->getOutputDevicesForAttributes(attr, 0, true /*fromCache*/);
6764 DeviceVector newDevices = mEngine->getOutputDevicesForAttributes(attr, 0, false /*fromCache*/);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07006765
François Gaffie11d30102018-11-02 16:09:09 +01006766 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevices(oldDevices, mPreviousOutputs);
6767 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevices(newDevices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07006768
Eric Laurentc209fe42020-06-05 18:11:23 -07006769 uint32_t maxLatency = 0;
Oscar Azucena873d10f2023-01-12 18:34:42 -08006770 bool unneededUsePrimaryOutputFromPolicyMixes = false;
Eric Laurent56ed8842022-11-15 16:04:41 +01006771 std::vector<sp<SwAudioOutputDescriptor>> invalidatedOutputs;
Eric Laurentc209fe42020-06-05 18:11:23 -07006772 // take into account dynamic audio policies related changes: if a client is now associated
6773 // to a different policy mix than at creation time, invalidate corresponding stream
Eric Laurent56ed8842022-11-15 16:04:41 +01006774 for (size_t i = 0; i < mPreviousOutputs.size(); i++) {
Eric Laurentc209fe42020-06-05 18:11:23 -07006775 const sp<SwAudioOutputDescriptor>& desc = mPreviousOutputs.valueAt(i);
6776 if (desc->isDuplicated()) {
6777 continue;
Jean-Michel Trivife472e22014-12-16 14:23:13 -08006778 }
Eric Laurentc209fe42020-06-05 18:11:23 -07006779 for (const sp<TrackClientDescriptor>& client : desc->getClientIterable()) {
6780 if (mEngine->getProductStrategyForAttributes(client->attributes()) != psId) {
6781 continue;
6782 }
6783 sp<AudioPolicyMix> primaryMix;
Dean Wheatleyd082f472022-02-04 11:10:48 +11006784 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->config(),
Oscar Azucena873d10f2023-01-12 18:34:42 -08006785 client->uid(), client->session(), client->flags(), mAvailableOutputDevices,
6786 nullptr /* requestedDevice */, primaryMix, nullptr /* secondaryMixes */,
6787 unneededUsePrimaryOutputFromPolicyMixes);
Eric Laurentc209fe42020-06-05 18:11:23 -07006788 if (status != OK) {
6789 continue;
6790 }
yucliuf4de36d2020-09-14 14:57:56 -07006791 if (client->getPrimaryMix() != primaryMix || client->hasLostPrimaryMix()) {
Eric Laurent56ed8842022-11-15 16:04:41 +01006792 if (desc->isStrategyActive(psId) && maxLatency < desc->latency()) {
Eric Laurentc209fe42020-06-05 18:11:23 -07006793 maxLatency = desc->latency();
6794 }
Eric Laurent56ed8842022-11-15 16:04:41 +01006795 invalidatedOutputs.push_back(desc);
Eric Laurentc209fe42020-06-05 18:11:23 -07006796 }
Jean-Michel Trivife472e22014-12-16 14:23:13 -08006797 }
6798 }
6799
Eric Laurent56ed8842022-11-15 16:04:41 +01006800 if (srcOutputs != dstOutputs || !invalidatedOutputs.empty()) {
Eric Laurentac3a6902018-05-11 16:39:10 -07006801 // get maximum latency of all source outputs to determine the minimum mute time guaranteeing
6802 // audio from invalidated tracks will be rendered when unmuting
Eric Laurentac3a6902018-05-11 16:39:10 -07006803 for (audio_io_handle_t srcOut : srcOutputs) {
6804 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
Eric Laurentaa02db82019-09-05 17:31:49 -07006805 if (desc == nullptr) continue;
6806
6807 if (desc->isStrategyActive(psId) && maxLatency < desc->latency()) {
Eric Laurentac3a6902018-05-11 16:39:10 -07006808 maxLatency = desc->latency();
6809 }
Eric Laurentaa02db82019-09-05 17:31:49 -07006810
Eric Laurent56ed8842022-11-15 16:04:41 +01006811 bool invalidate = false;
Eric Laurentaa02db82019-09-05 17:31:49 -07006812 for (auto client : desc->clientsList(false /*activeOnly*/)) {
Eric Laurent78aade82019-09-13 18:55:08 -07006813 if (desc->isDuplicated() || !desc->mProfile->isDirectOutput()) {
Eric Laurentaa02db82019-09-05 17:31:49 -07006814 // a client on a non direct outputs has necessarily a linear PCM format
6815 // so we can call selectOutput() safely
6816 const audio_io_handle_t newOutput = selectOutput(dstOutputs,
6817 client->flags(),
6818 client->config().format,
6819 client->config().channel_mask,
jiabinebb6af42020-06-09 17:31:17 -07006820 client->config().sample_rate,
6821 client->session());
Eric Laurentaa02db82019-09-05 17:31:49 -07006822 if (newOutput != srcOut) {
6823 invalidate = true;
6824 break;
6825 }
6826 } else {
6827 sp<IOProfile> profile = getProfileForOutput(newDevices,
6828 client->config().sample_rate,
6829 client->config().format,
6830 client->config().channel_mask,
6831 client->flags(),
6832 true /* directOnly */);
6833 if (profile != desc->mProfile) {
6834 invalidate = true;
6835 break;
6836 }
6837 }
6838 }
Eric Laurent56ed8842022-11-15 16:04:41 +01006839 // mute strategy while moving tracks from one output to another
6840 if (invalidate) {
6841 invalidatedOutputs.push_back(desc);
6842 if (desc->isStrategyActive(psId)) {
6843 setStrategyMute(psId, true, desc);
6844 setStrategyMute(psId, false, desc, maxLatency * LATENCY_MUTE_FACTOR,
6845 newDevices.types());
6846 }
Eric Laurente552edb2014-03-10 17:42:56 -07006847 }
François Gaffiec005e562018-11-06 15:04:49 +01006848 sp<SourceClientDescriptor> source = getSourceForAttributesOnOutput(srcOut, attr);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02006849 if (source != nullptr && !isCallRxAudioSource(source) && !source->isInternal()) {
Eric Laurentd60560a2015-04-10 11:31:20 -07006850 connectAudioSource(source);
6851 }
Eric Laurente552edb2014-03-10 17:42:56 -07006852 }
6853
Eric Laurent56ed8842022-11-15 16:04:41 +01006854 ALOGV_IF(!(srcOutputs.isEmpty() || dstOutputs.isEmpty()),
6855 "%s: strategy %d, moving from output %s to output %s", __func__, psId,
6856 std::to_string(srcOutputs[0]).c_str(),
6857 std::to_string(dstOutputs[0]).c_str());
6858
François Gaffiec005e562018-11-06 15:04:49 +01006859 // Move effects associated to this stream from previous output to new output
6860 if (followsSameRouting(attr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07006861 selectOutputForMusicEffects();
Eric Laurente552edb2014-03-10 17:42:56 -07006862 }
François Gaffiec005e562018-11-06 15:04:49 +01006863 // Move tracks associated to this stream (and linked) from previous output to new output
Eric Laurent56ed8842022-11-15 16:04:41 +01006864 if (!invalidatedOutputs.empty()) {
jiabinc44b3462022-12-08 12:52:31 -08006865 invalidateStreams(mEngine->getStreamTypesForProductStrategy(psId));
Eric Laurent56ed8842022-11-15 16:04:41 +01006866 for (sp<SwAudioOutputDescriptor> desc : invalidatedOutputs) {
jiabin49256852022-03-09 11:21:35 -08006867 desc->setTracksInvalidatedStatusByStrategy(psId);
6868 }
Eric Laurente552edb2014-03-10 17:42:56 -07006869 }
6870 }
6871}
6872
Eric Laurente0720872014-03-11 09:30:41 -07006873void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07006874{
François Gaffiec005e562018-11-06 15:04:49 +01006875 for (const auto &strategy : mEngine->getOrderedProductStrategies()) {
6876 auto attributes = mEngine->getAllAttributesForProductStrategy(strategy).front();
6877 checkOutputForAttributes(attributes);
Francois Gaffieff1eb522020-05-06 18:37:04 +02006878 checkAudioSourceForAttributes(attributes);
François Gaffiec005e562018-11-06 15:04:49 +01006879 }
Eric Laurente552edb2014-03-10 17:42:56 -07006880}
6881
Kevin Rocard153f92d2018-12-18 18:33:28 -08006882void AudioPolicyManager::checkSecondaryOutputs() {
jiabinc44b3462022-12-08 12:52:31 -08006883 PortHandleVector clientsToInvalidate;
jiabin10a03f12021-05-07 23:46:28 +00006884 TrackSecondaryOutputsMap trackSecondaryOutputs;
Oscar Azucena873d10f2023-01-12 18:34:42 -08006885 bool unneededUsePrimaryOutputFromPolicyMixes = false;
Kevin Rocard153f92d2018-12-18 18:33:28 -08006886 for (size_t i = 0; i < mOutputs.size(); i++) {
6887 const sp<SwAudioOutputDescriptor>& outputDescriptor = mOutputs[i];
6888 for (const sp<TrackClientDescriptor>& client : outputDescriptor->getClientIterable()) {
Eric Laurentc529cf62020-04-17 18:19:10 -07006889 sp<AudioPolicyMix> primaryMix;
6890 std::vector<sp<AudioPolicyMix>> secondaryMixes;
Dean Wheatleyd082f472022-02-04 11:10:48 +11006891 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->config(),
Oscar Azucena873d10f2023-01-12 18:34:42 -08006892 client->uid(), client->session(), client->flags(), mAvailableOutputDevices,
6893 nullptr /* requestedDevice */, primaryMix, &secondaryMixes,
6894 unneededUsePrimaryOutputFromPolicyMixes);
Eric Laurentc529cf62020-04-17 18:19:10 -07006895 std::vector<sp<SwAudioOutputDescriptor>> secondaryDescs;
6896 for (auto &secondaryMix : secondaryMixes) {
6897 sp<SwAudioOutputDescriptor> outputDesc = secondaryMix->getOutput();
6898 if (outputDesc != nullptr &&
6899 outputDesc->mIoHandle != AUDIO_IO_HANDLE_NONE) {
6900 secondaryDescs.push_back(outputDesc);
6901 }
6902 }
6903
jiabinc44b3462022-12-08 12:52:31 -08006904 if (status != OK &&
6905 (client->flags() & AUDIO_OUTPUT_FLAG_MMAP_NOIRQ) == AUDIO_OUTPUT_FLAG_NONE) {
6906 // When it failed to query secondary output, only invalidate the client that is not
6907 // MMAP. The reason is that MMAP stream will not support secondary output.
6908 clientsToInvalidate.push_back(client->portId());
jiabin10a03f12021-05-07 23:46:28 +00006909 } else if (!std::equal(
6910 client->getSecondaryOutputs().begin(),
6911 client->getSecondaryOutputs().end(),
6912 secondaryDescs.begin(), secondaryDescs.end())) {
jiabina5281062021-11-23 00:10:23 +00006913 if (!audio_is_linear_pcm(client->config().format)) {
6914 // If the format is not PCM, the tracks should be invalidated to get correct
6915 // behavior when the secondary output is changed.
jiabinc44b3462022-12-08 12:52:31 -08006916 clientsToInvalidate.push_back(client->portId());
jiabina5281062021-11-23 00:10:23 +00006917 } else {
6918 std::vector<wp<SwAudioOutputDescriptor>> weakSecondaryDescs;
6919 std::vector<audio_io_handle_t> secondaryOutputIds;
6920 for (const auto &secondaryDesc: secondaryDescs) {
6921 secondaryOutputIds.push_back(secondaryDesc->mIoHandle);
6922 weakSecondaryDescs.push_back(secondaryDesc);
6923 }
6924 trackSecondaryOutputs.emplace(client->portId(), secondaryOutputIds);
6925 client->setSecondaryOutputs(std::move(weakSecondaryDescs));
jiabin10a03f12021-05-07 23:46:28 +00006926 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08006927 }
6928 }
6929 }
jiabin10a03f12021-05-07 23:46:28 +00006930 if (!trackSecondaryOutputs.empty()) {
6931 mpClientInterface->updateSecondaryOutputs(trackSecondaryOutputs);
6932 }
jiabinc44b3462022-12-08 12:52:31 -08006933 if (!clientsToInvalidate.empty()) {
6934 ALOGD("%s Invalidate clients due to fail getting output for attr", __func__);
6935 mpClientInterface->invalidateTracks(clientsToInvalidate);
Kevin Rocard153f92d2018-12-18 18:33:28 -08006936 }
6937}
6938
Eric Laurent2517af32020-11-25 15:31:27 +01006939bool AudioPolicyManager::isScoRequestedForComm() const {
6940 AudioDeviceTypeAddrVector devices;
6941 mEngine->getDevicesForRoleAndStrategy(mCommunnicationStrategy, DEVICE_ROLE_PREFERRED, devices);
6942 for (const auto &device : devices) {
6943 if (audio_is_bluetooth_out_sco_device(device.mType)) {
6944 return true;
6945 }
6946 }
6947 return false;
6948}
6949
Eric Laurent1a8b45f2022-04-13 16:01:47 +02006950bool AudioPolicyManager::isHearingAidUsedForComm() const {
6951 DeviceVector devices = mEngine->getOutputDevicesForStream(AUDIO_STREAM_VOICE_CALL,
6952 true /*fromCache*/);
6953 for (const auto &device : devices) {
6954 if (device->type() == AUDIO_DEVICE_OUT_HEARING_AID) {
6955 return true;
6956 }
6957 }
6958 return false;
6959}
6960
6961
Eric Laurente0720872014-03-11 09:30:41 -07006962void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07006963{
François Gaffie53615e22015-03-19 09:24:12 +01006964 audio_io_handle_t a2dpOutput = mOutputs.getA2dpOutput();
Aniket Kumar Lataa8ee9962018-01-31 20:24:23 -08006965 if (a2dpOutput == 0 || mOutputs.isA2dpOffloadedOnPrimary()) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07006966 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07006967 return;
6968 }
6969
Eric Laurent3a4311c2014-03-17 12:00:47 -07006970 bool isScoConnected =
jiabin9a3361e2019-10-01 09:38:30 -07006971 (mAvailableInputDevices.types().count(AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) != 0 ||
6972 !Intersection(mAvailableOutputDevices.types(), getAudioDeviceOutAllScoSet()).empty());
Eric Laurent2517af32020-11-25 15:31:27 +01006973 bool isScoRequested = isScoRequestedForComm();
Eric Laurentf732e072016-08-03 19:30:28 -07006974
6975 // if suspended, restore A2DP output if:
6976 // ((SCO device is NOT connected) ||
Eric Laurent2517af32020-11-25 15:31:27 +01006977 // ((SCO is not requested) &&
Eric Laurentf732e072016-08-03 19:30:28 -07006978 // (phone state is NOT in call) && (phone state is NOT ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07006979 //
Eric Laurentf732e072016-08-03 19:30:28 -07006980 // if not suspended, suspend A2DP output if:
6981 // (SCO device is connected) &&
Eric Laurent2517af32020-11-25 15:31:27 +01006982 // ((SCO is requested) ||
Eric Laurentf732e072016-08-03 19:30:28 -07006983 // ((phone state is in call) || (phone state is ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07006984 //
6985 if (mA2dpSuspended) {
Eric Laurentf732e072016-08-03 19:30:28 -07006986 if (!isScoConnected ||
Eric Laurent2517af32020-11-25 15:31:27 +01006987 (!isScoRequested &&
Eric Laurentf732e072016-08-03 19:30:28 -07006988 (mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) &&
François Gaffie2110e042015-03-24 08:41:51 +01006989 (mEngine->getPhoneState() != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07006990
6991 mpClientInterface->restoreOutput(a2dpOutput);
6992 mA2dpSuspended = false;
6993 }
6994 } else {
Eric Laurentf732e072016-08-03 19:30:28 -07006995 if (isScoConnected &&
Eric Laurent2517af32020-11-25 15:31:27 +01006996 (isScoRequested ||
Eric Laurentf732e072016-08-03 19:30:28 -07006997 (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) ||
François Gaffie2110e042015-03-24 08:41:51 +01006998 (mEngine->getPhoneState() == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07006999
7000 mpClientInterface->suspendOutput(a2dpOutput);
7001 mA2dpSuspended = true;
7002 }
7003 }
7004}
7005
François Gaffie11d30102018-11-02 16:09:09 +01007006DeviceVector AudioPolicyManager::getNewOutputDevices(const sp<SwAudioOutputDescriptor>& outputDesc,
7007 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07007008{
François Gaffie11d30102018-11-02 16:09:09 +01007009 DeviceVector devices;
7010
Jean-Michel Triviff155c62016-02-26 12:07:16 -08007011 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007012 if (index >= 0) {
7013 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007014 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01007015 ALOGV("%s device %s forced by patch %d", __func__,
7016 outputDesc->devices().toString().c_str(), outputDesc->getPatchHandle());
7017 return outputDesc->devices();
Eric Laurent6a94d692014-05-20 11:18:06 -07007018 }
7019 }
7020
Dean Wheatley514b4312020-06-17 21:45:00 +10007021 // Do not retrieve engine device for outputs through MSD
7022 // TODO: support explicit routing requests by resetting MSD patch to engine device.
7023 if (outputDesc->devices() == getMsdAudioOutDevices()) {
7024 return outputDesc->devices();
7025 }
7026
Eric Laurent97ac8712018-07-27 18:59:02 -07007027 // Honor explicit routing requests only if no client using default routing is active on this
7028 // input: a specific app can not force routing for other apps by setting a preferred device.
7029 bool active; // unused
François Gaffie11d30102018-11-02 16:09:09 +01007030 sp<DeviceDescriptor> device =
François Gaffiec005e562018-11-06 15:04:49 +01007031 findPreferredDevice(outputDesc, PRODUCT_STRATEGY_NONE, active, mAvailableOutputDevices);
François Gaffie11d30102018-11-02 16:09:09 +01007032 if (device != nullptr) {
7033 return DeviceVector(device);
Eric Laurentf3a5a602018-05-22 18:42:55 -07007034 }
7035
François Gaffiea807ef92018-11-05 10:44:33 +01007036 // Legacy Engine cannot take care of bus devices and mix, so we need to handle the conflict
7037 // of setForceUse / Default Bus device here
7038 device = mPolicyMixes.getDeviceAndMixForOutput(outputDesc, mAvailableOutputDevices);
7039 if (device != nullptr) {
7040 return DeviceVector(device);
7041 }
7042
François Gaffiec005e562018-11-06 15:04:49 +01007043 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
7044 StreamTypeVector streams = mEngine->getStreamTypesForProductStrategy(productStrategy);
7045 auto attr = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307046 auto hasStreamActive = [&](auto stream) {
7047 return hasStream(streams, stream) && isStreamActive(stream, 0);
7048 };
Eric Laurent484e9272018-06-07 17:29:23 -07007049
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307050 auto doGetOutputDevicesForVoice = [&]() {
7051 return hasVoiceStream(streams) && (outputDesc == mPrimaryOutput ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007052 outputDesc->isActive(toVolumeSource(AUDIO_STREAM_VOICE_CALL, false))) &&
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307053 (isInCall() ||
Henrik Backlund07c654a2021-10-14 15:57:10 +02007054 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc)) &&
7055 !isStreamActive(AUDIO_STREAM_ENFORCED_AUDIBLE, 0);
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307056 };
7057
7058 // With low-latency playing on speaker, music on WFD, when the first low-latency
7059 // output is stopped, getNewOutputDevices checks for a product strategy
7060 // from the list, as STRATEGY_SONIFICATION comes prior to STRATEGY_MEDIA.
Carter Hsucc58a6b2021-07-20 08:44:50 +00007061 // If an ALARM or ENFORCED_AUDIBLE stream is supported by the product strategy,
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307062 // devices are returned for STRATEGY_SONIFICATION without checking whether the
7063 // stream is associated to the output descriptor.
7064 if (doGetOutputDevicesForVoice() || outputDesc->isStrategyActive(productStrategy) ||
7065 ((hasStreamActive(AUDIO_STREAM_ALARM) ||
7066 hasStreamActive(AUDIO_STREAM_ENFORCED_AUDIBLE)) &&
7067 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc))) {
François Gaffiec005e562018-11-06 15:04:49 +01007068 // Retrieval of devices for voice DL is done on primary output profile, cannot
7069 // check the route (would force modifying configuration file for this profile)
7070 devices = mEngine->getOutputDevicesForAttributes(attr, nullptr, fromCache);
7071 break;
7072 }
Eric Laurente552edb2014-03-10 17:42:56 -07007073 }
François Gaffiec005e562018-11-06 15:04:49 +01007074 ALOGV("%s selected devices %s", __func__, devices.toString().c_str());
François Gaffie11d30102018-11-02 16:09:09 +01007075 return devices;
Eric Laurent1c333e22014-05-20 10:48:17 -07007076}
7077
François Gaffie11d30102018-11-02 16:09:09 +01007078sp<DeviceDescriptor> AudioPolicyManager::getNewInputDevice(
7079 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurent1c333e22014-05-20 10:48:17 -07007080{
François Gaffie11d30102018-11-02 16:09:09 +01007081 sp<DeviceDescriptor> device;
Eric Laurent6a94d692014-05-20 11:18:06 -07007082
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08007083 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007084 if (index >= 0) {
7085 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007086 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01007087 ALOGV("getNewInputDevice() device %s forced by patch %d",
7088 inputDesc->getDevice()->toString().c_str(), inputDesc->getPatchHandle());
7089 return inputDesc->getDevice();
Eric Laurent6a94d692014-05-20 11:18:06 -07007090 }
7091 }
7092
Eric Laurent97ac8712018-07-27 18:59:02 -07007093 // Honor explicit routing requests only if no client using default routing is active on this
7094 // input: a specific app can not force routing for other apps by setting a preferred device.
7095 bool active;
François Gaffie11d30102018-11-02 16:09:09 +01007096 device = findPreferredDevice(inputDesc, AUDIO_SOURCE_DEFAULT, active, mAvailableInputDevices);
7097 if (device != nullptr) {
7098 return device;
Eric Laurent97ac8712018-07-27 18:59:02 -07007099 }
7100
Eric Laurentdc95a252018-04-12 12:46:56 -07007101 // If we are not in call and no client is active on this input, this methods returns
Andy Hungf024a9e2019-01-30 16:01:02 -08007102 // a null sp<>, causing the patch on the input stream to be released.
yuanjiahsu0735bf32021-03-18 08:12:54 +08007103 audio_attributes_t attributes;
7104 uid_t uid;
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007105 audio_session_t session;
yuanjiahsu0735bf32021-03-18 08:12:54 +08007106 sp<RecordClientDescriptor> topClient = inputDesc->getHighestPriorityClient();
7107 if (topClient != nullptr) {
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01007108 attributes = topClient->attributes();
7109 uid = topClient->uid();
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007110 session = topClient->session();
yuanjiahsu0735bf32021-03-18 08:12:54 +08007111 } else {
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01007112 attributes = { .source = AUDIO_SOURCE_DEFAULT };
7113 uid = 0;
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007114 session = AUDIO_SESSION_NONE;
yuanjiahsu0735bf32021-03-18 08:12:54 +08007115 }
7116
Francois Gaffie716e1432019-01-14 16:58:59 +01007117 if (attributes.source == AUDIO_SOURCE_DEFAULT && isInCall()) {
7118 attributes.source = AUDIO_SOURCE_VOICE_COMMUNICATION;
Eric Laurentdc95a252018-04-12 12:46:56 -07007119 }
Francois Gaffie716e1432019-01-14 16:58:59 +01007120 if (attributes.source != AUDIO_SOURCE_DEFAULT) {
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007121 device = mEngine->getInputDeviceForAttributes(attributes, uid, session);
Eric Laurentfb66dd92016-01-28 18:32:03 -08007122 }
Eric Laurent1c333e22014-05-20 10:48:17 -07007123
Eric Laurente552edb2014-03-10 17:42:56 -07007124 return device;
7125}
7126
Eric Laurent794fde22016-03-11 09:50:45 -08007127bool AudioPolicyManager::streamsMatchForvolume(audio_stream_type_t stream1,
7128 audio_stream_type_t stream2) {
Jean-Michel Trivi99bb2f92016-11-23 15:52:07 -08007129 return (stream1 == stream2);
Eric Laurent28d09f02016-03-08 10:43:05 -08007130}
7131
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08007132status_t AudioPolicyManager::getDevicesForAttributes(
Andy Hung6d23c0f2022-02-16 09:37:15 -08007133 const audio_attributes_t &attr, AudioDeviceTypeAddrVector *devices, bool forVolume) {
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08007134 if (devices == nullptr) {
7135 return BAD_VALUE;
7136 }
Andy Hung6d23c0f2022-02-16 09:37:15 -08007137
Andy Hung6d23c0f2022-02-16 09:37:15 -08007138 DeviceVector curDevices;
jiabinf1c73972022-04-14 16:28:52 -07007139 if (status_t status = getDevicesForAttributes(attr, curDevices, forVolume); status != OK) {
7140 return status;
Andy Hung6d23c0f2022-02-16 09:37:15 -08007141 }
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08007142 for (const auto& device : curDevices) {
7143 devices->push_back(device->getDeviceTypeAddr());
7144 }
7145 return NO_ERROR;
7146}
7147
Eric Laurente0720872014-03-11 09:30:41 -07007148void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07007149 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07007150 case AUDIO_STREAM_MUSIC:
François Gaffiec005e562018-11-06 15:04:49 +01007151 checkOutputForAttributes(attributes_initializer(AUDIO_USAGE_NOTIFICATION));
Eric Laurente552edb2014-03-10 17:42:56 -07007152 updateDevicesAndOutputs();
7153 break;
7154 default:
7155 break;
7156 }
7157}
7158
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007159uint32_t AudioPolicyManager::handleEventForBeacon(int event) {
Eric Laurent9459fb02015-08-12 18:36:32 -07007160
7161 // skip beacon mute management if a dedicated TTS output is available
7162 if (mTtsOutputAvailable) {
7163 return 0;
7164 }
7165
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007166 switch(event) {
7167 case STARTING_OUTPUT:
7168 mBeaconMuteRefCount++;
7169 break;
7170 case STOPPING_OUTPUT:
7171 if (mBeaconMuteRefCount > 0) {
7172 mBeaconMuteRefCount--;
7173 }
7174 break;
7175 case STARTING_BEACON:
7176 mBeaconPlayingRefCount++;
7177 break;
7178 case STOPPING_BEACON:
7179 if (mBeaconPlayingRefCount > 0) {
7180 mBeaconPlayingRefCount--;
7181 }
7182 break;
7183 }
7184
7185 if (mBeaconMuteRefCount > 0) {
7186 // any playback causes beacon to be muted
7187 return setBeaconMute(true);
7188 } else {
7189 // no other playback: unmute when beacon starts playing, mute when it stops
7190 return setBeaconMute(mBeaconPlayingRefCount == 0);
7191 }
7192}
7193
7194uint32_t AudioPolicyManager::setBeaconMute(bool mute) {
7195 ALOGV("setBeaconMute(%d) mBeaconMuteRefCount=%d mBeaconPlayingRefCount=%d",
7196 mute, mBeaconMuteRefCount, mBeaconPlayingRefCount);
7197 // keep track of muted state to avoid repeating mute/unmute operations
7198 if (mBeaconMuted != mute) {
7199 // mute/unmute AUDIO_STREAM_TTS on all outputs
7200 ALOGV("\t muting %d", mute);
7201 uint32_t maxLatency = 0;
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007202 auto ttsVolumeSource = toVolumeSource(AUDIO_STREAM_TTS, false);
7203 if (ttsVolumeSource == VOLUME_SOURCE_NONE) {
7204 ALOGV("\t no tts volume source available");
7205 return 0;
7206 }
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007207 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07007208 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
jiabin9a3361e2019-10-01 09:38:30 -07007209 setVolumeSourceMute(ttsVolumeSource, mute/*on*/, desc, 0 /*delay*/, DeviceTypeSet());
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007210 const uint32_t latency = desc->latency() * 2;
Eric Laurentcdb2b352020-07-23 10:57:02 -07007211 if (desc->isActive(latency * 2) && latency > maxLatency) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007212 maxLatency = latency;
7213 }
7214 }
7215 mBeaconMuted = mute;
7216 return maxLatency;
7217 }
7218 return 0;
7219}
7220
Eric Laurente0720872014-03-11 09:30:41 -07007221void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07007222{
François Gaffiec005e562018-11-06 15:04:49 +01007223 mEngine->updateDeviceSelectionCache();
Eric Laurente552edb2014-03-10 17:42:56 -07007224 mPreviousOutputs = mOutputs;
7225}
7226
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07007227uint32_t AudioPolicyManager::checkDeviceMuteStrategies(const sp<AudioOutputDescriptor>& outputDesc,
François Gaffiec005e562018-11-06 15:04:49 +01007228 const DeviceVector &prevDevices,
Eric Laurente552edb2014-03-10 17:42:56 -07007229 uint32_t delayMs)
7230{
7231 // mute/unmute strategies using an incompatible device combination
7232 // if muting, wait for the audio in pcm buffer to be drained before proceeding
7233 // if unmuting, unmute only after the specified delay
7234 if (outputDesc->isDuplicated()) {
7235 return 0;
7236 }
7237
7238 uint32_t muteWaitMs = 0;
François Gaffiec005e562018-11-06 15:04:49 +01007239 DeviceVector devices = outputDesc->devices();
7240 bool shouldMute = outputDesc->isActive() && (devices.size() >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07007241
François Gaffiec005e562018-11-06 15:04:49 +01007242 auto productStrategies = mEngine->getOrderedProductStrategies();
7243 for (const auto &productStrategy : productStrategies) {
7244 auto attributes = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
7245 DeviceVector curDevices =
7246 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false/*fromCache*/);
7247 curDevices = curDevices.filter(outputDesc->supportedDevices());
7248 bool mute = shouldMute && curDevices.containsAtLeastOne(devices) && curDevices != devices;
Eric Laurente552edb2014-03-10 17:42:56 -07007249 bool doMute = false;
7250
François Gaffiec005e562018-11-06 15:04:49 +01007251 if (mute && !outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07007252 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01007253 outputDesc->setStrategyMutedByDevice(productStrategy, true);
7254 } else if (!mute && outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07007255 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01007256 outputDesc->setStrategyMutedByDevice(productStrategy, false);
Eric Laurente552edb2014-03-10 17:42:56 -07007257 }
Eric Laurent99401132014-05-07 19:48:15 -07007258 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07007259 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07007260 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07007261 // skip output if it does not share any device with current output
François Gaffie11d30102018-11-02 16:09:09 +01007262 if (!desc->supportedDevices().containsAtLeastOne(outputDesc->supportedDevices())) {
Eric Laurente552edb2014-03-10 17:42:56 -07007263 continue;
7264 }
François Gaffiec005e562018-11-06 15:04:49 +01007265 ALOGVV("%s() %s (curDevice %s)", __func__,
7266 mute ? "muting" : "unmuting", curDevices.toString().c_str());
7267 setStrategyMute(productStrategy, mute, desc, mute ? 0 : delayMs);
7268 if (desc->isStrategyActive(productStrategy)) {
Eric Laurent99401132014-05-07 19:48:15 -07007269 if (mute) {
7270 // FIXME: should not need to double latency if volume could be applied
7271 // immediately by the audioflinger mixer. We must account for the delay
7272 // between now and the next time the audioflinger thread for this output
7273 // will process a buffer (which corresponds to one buffer size,
7274 // usually 1/2 or 1/4 of the latency).
7275 if (muteWaitMs < desc->latency() * 2) {
7276 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07007277 }
7278 }
7279 }
7280 }
7281 }
7282 }
7283
Eric Laurent99401132014-05-07 19:48:15 -07007284 // temporary mute output if device selection changes to avoid volume bursts due to
7285 // different per device volumes
François Gaffiec005e562018-11-06 15:04:49 +01007286 if (outputDesc->isActive() && (devices != prevDevices)) {
Eric Laurentdc462862016-07-19 12:29:53 -07007287 uint32_t tempMuteWaitMs = outputDesc->latency() * 2;
Jasmine Chaf6074fe2021-08-17 13:44:31 +08007288
Eric Laurentdc462862016-07-19 12:29:53 -07007289 if (muteWaitMs < tempMuteWaitMs) {
7290 muteWaitMs = tempMuteWaitMs;
Eric Laurent99401132014-05-07 19:48:15 -07007291 }
Jasmine Chaf6074fe2021-08-17 13:44:31 +08007292
7293 // If recommended duration is defined, replace temporary mute duration to avoid
7294 // truncated notifications at beginning, which depends on duration of changing path in HAL.
7295 // Otherwise, temporary mute duration is conservatively set to 4 times the reported latency.
7296 uint32_t tempRecommendedMuteDuration = outputDesc->getRecommendedMuteDurationMs();
7297 uint32_t tempMuteDurationMs = tempRecommendedMuteDuration > 0 ?
7298 tempRecommendedMuteDuration : outputDesc->latency() * 4;
7299
François Gaffieaaac0fd2018-11-22 17:56:39 +01007300 for (const auto &activeVs : outputDesc->getActiveVolumeSources()) {
7301 // make sure that we do not start the temporary mute period too early in case of
7302 // delayed device change
7303 setVolumeSourceMute(activeVs, true, outputDesc, delayMs);
7304 setVolumeSourceMute(activeVs, false, outputDesc, delayMs + tempMuteDurationMs,
François Gaffiec005e562018-11-06 15:04:49 +01007305 devices.types());
Eric Laurent99401132014-05-07 19:48:15 -07007306 }
7307 }
7308
Eric Laurente552edb2014-03-10 17:42:56 -07007309 // wait for the PCM output buffers to empty before proceeding with the rest of the command
7310 if (muteWaitMs > delayMs) {
7311 muteWaitMs -= delayMs;
7312 usleep(muteWaitMs * 1000);
7313 return muteWaitMs;
7314 }
7315 return 0;
7316}
7317
François Gaffie11d30102018-11-02 16:09:09 +01007318uint32_t AudioPolicyManager::setOutputDevices(const sp<SwAudioOutputDescriptor>& outputDesc,
7319 const DeviceVector &devices,
7320 bool force,
7321 int delayMs,
7322 audio_patch_handle_t *patchHandle,
Francois Gaffie3523ab32021-06-22 13:24:34 +02007323 bool requiresMuteCheck, bool requiresVolumeCheck)
Eric Laurente552edb2014-03-10 17:42:56 -07007324{
jiabin3ff8d7d2022-12-13 06:27:44 +00007325 // TODO(b/262404095): Consider if the output need to be reopened.
François Gaffie11d30102018-11-02 16:09:09 +01007326 ALOGV("%s device %s delayMs %d", __func__, devices.toString().c_str(), delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07007327 uint32_t muteWaitMs;
7328
7329 if (outputDesc->isDuplicated()) {
François Gaffie11d30102018-11-02 16:09:09 +01007330 muteWaitMs = setOutputDevices(outputDesc->subOutput1(), devices, force, delayMs,
7331 nullptr /* patchHandle */, requiresMuteCheck);
7332 muteWaitMs += setOutputDevices(outputDesc->subOutput2(), devices, force, delayMs,
7333 nullptr /* patchHandle */, requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07007334 return muteWaitMs;
7335 }
Eric Laurente552edb2014-03-10 17:42:56 -07007336
7337 // filter devices according to output selected
Francois Gaffie716e1432019-01-14 16:58:59 +01007338 DeviceVector filteredDevices = outputDesc->filterSupportedDevices(devices);
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01007339 DeviceVector prevDevices = outputDesc->devices();
Francois Gaffie3523ab32021-06-22 13:24:34 +02007340 DeviceVector availPrevDevices = mAvailableOutputDevices.filter(prevDevices);
Eric Laurente552edb2014-03-10 17:42:56 -07007341
François Gaffie11d30102018-11-02 16:09:09 +01007342 ALOGV("setOutputDevices() prevDevice %s", prevDevices.toString().c_str());
7343
7344 if (!filteredDevices.isEmpty()) {
7345 outputDesc->setDevices(filteredDevices);
Eric Laurente552edb2014-03-10 17:42:56 -07007346 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00007347
7348 // if the outputs are not materially active, there is no need to mute.
7349 if (requiresMuteCheck) {
François Gaffiec005e562018-11-06 15:04:49 +01007350 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevices, delayMs);
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00007351 } else {
7352 ALOGV("%s: suppressing checkDeviceMuteStrategies", __func__);
7353 muteWaitMs = 0;
7354 }
Eric Laurente552edb2014-03-10 17:42:56 -07007355
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02007356 bool outputRouted = outputDesc->isRouted();
7357
Eric Laurent79ea9582020-06-11 18:49:24 -07007358 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
7359 // output profile or if new device is not supported AND previous device(s) is(are) still
7360 // available (otherwise reset device must be done on the output)
Francois Gaffie3523ab32021-06-22 13:24:34 +02007361 if (!devices.isEmpty() && filteredDevices.isEmpty() && !availPrevDevices.empty()) {
Eric Laurent79ea9582020-06-11 18:49:24 -07007362 ALOGV("%s: unsupported device %s for output", __func__, devices.toString().c_str());
7363 // restore previous device after evaluating strategy mute state
7364 outputDesc->setDevices(prevDevices);
7365 return muteWaitMs;
7366 }
7367
Eric Laurente552edb2014-03-10 17:42:56 -07007368 // Do not change the routing if:
Eric Laurentb80a2a82014-10-27 16:07:59 -07007369 // the requested device is AUDIO_DEVICE_NONE
7370 // OR the requested device is the same as current device
7371 // AND force is not specified
7372 // AND the output is connected by a valid audio patch.
François Gaffie11d30102018-11-02 16:09:09 +01007373 // Doing this check here allows the caller to call setOutputDevices() without conditions
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02007374 if ((filteredDevices.isEmpty() || filteredDevices == prevDevices) && !force && outputRouted) {
François Gaffie11d30102018-11-02 16:09:09 +01007375 ALOGV("%s setting same device %s or null device, force=%d, patch handle=%d", __func__,
7376 filteredDevices.toString().c_str(), force, outputDesc->getPatchHandle());
Francois Gaffie3523ab32021-06-22 13:24:34 +02007377 if (requiresVolumeCheck && !filteredDevices.isEmpty()) {
7378 ALOGV("%s setting same device on routed output, force apply volumes", __func__);
7379 applyStreamVolumes(outputDesc, filteredDevices.types(), delayMs, true /*force*/);
7380 }
Eric Laurente552edb2014-03-10 17:42:56 -07007381 return muteWaitMs;
7382 }
7383
François Gaffie11d30102018-11-02 16:09:09 +01007384 ALOGV("%s changing device to %s", __func__, filteredDevices.toString().c_str());
Eric Laurent1c333e22014-05-20 10:48:17 -07007385
Eric Laurente552edb2014-03-10 17:42:56 -07007386 // do the routing
Francois Gaffie3523ab32021-06-22 13:24:34 +02007387 if (filteredDevices.isEmpty() || mAvailableOutputDevices.filter(filteredDevices).empty()) {
Eric Laurentc75307b2015-03-17 15:29:32 -07007388 resetOutputDevice(outputDesc, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07007389 } else {
François Gaffie11d30102018-11-02 16:09:09 +01007390 PatchBuilder patchBuilder;
7391 patchBuilder.addSource(outputDesc);
7392 ALOG_ASSERT(filteredDevices.size() <= AUDIO_PATCH_PORTS_MAX, "Too many sink ports");
7393 for (const auto &filteredDevice : filteredDevices) {
7394 patchBuilder.addSink(filteredDevice);
Eric Laurentc40d9692016-04-13 19:14:13 -07007395 }
7396
Jasmine Cha7f82d1a2020-03-16 13:21:47 +08007397 // Add half reported latency to delayMs when muteWaitMs is null in order
7398 // to avoid disordered sequence of muting volume and changing devices.
7399 installPatch(__func__, patchHandle, outputDesc.get(), patchBuilder.patch(),
7400 muteWaitMs == 0 ? (delayMs + (outputDesc->latency() / 2)) : delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07007401 }
Eric Laurente552edb2014-03-10 17:42:56 -07007402
7403 // update stream volumes according to new device
François Gaffie11d30102018-11-02 16:09:09 +01007404 applyStreamVolumes(outputDesc, filteredDevices.types(), delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07007405
7406 return muteWaitMs;
7407}
7408
Eric Laurentc75307b2015-03-17 15:29:32 -07007409status_t AudioPolicyManager::resetOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurent6a94d692014-05-20 11:18:06 -07007410 int delayMs,
7411 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07007412{
Eric Laurent6a94d692014-05-20 11:18:06 -07007413 ssize_t index;
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02007414 if (patchHandle == nullptr && !outputDesc->isRouted()) {
7415 return INVALID_OPERATION;
7416 }
Eric Laurent6a94d692014-05-20 11:18:06 -07007417 if (patchHandle) {
7418 index = mAudioPatches.indexOfKey(*patchHandle);
7419 } else {
Jean-Michel Triviff155c62016-02-26 12:07:16 -08007420 index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007421 }
7422 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07007423 return INVALID_OPERATION;
7424 }
Eric Laurent6a94d692014-05-20 11:18:06 -07007425 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007426 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07007427 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07007428 outputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
François Gaffieafd4cea2019-11-18 15:50:22 +01007429 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007430 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07007431 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07007432 return status;
7433}
7434
7435status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
François Gaffie11d30102018-11-02 16:09:09 +01007436 const sp<DeviceDescriptor> &device,
Eric Laurent6a94d692014-05-20 11:18:06 -07007437 bool force,
7438 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07007439{
7440 status_t status = NO_ERROR;
7441
Eric Laurent1f2f2232014-06-02 12:01:23 -07007442 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
François Gaffie11d30102018-11-02 16:09:09 +01007443 if ((device != nullptr) && ((device != inputDesc->getDevice()) || force)) {
7444 inputDesc->setDevice(device);
Eric Laurent1c333e22014-05-20 10:48:17 -07007445
François Gaffie11d30102018-11-02 16:09:09 +01007446 if (mAvailableInputDevices.contains(device)) {
Mikhail Naganovdc769682018-05-04 15:34:08 -07007447 PatchBuilder patchBuilder;
7448 patchBuilder.addSink(inputDesc,
Eric Laurentdaf92cc2014-07-22 15:36:10 -07007449 // AUDIO_SOURCE_HOTWORD is for internal use only:
7450 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
Mikhail Naganovdc769682018-05-04 15:34:08 -07007451 [inputDesc](const PatchBuilder::mix_usecase_t& usecase) {
7452 auto result = usecase;
7453 if (result.source == AUDIO_SOURCE_HOTWORD && !inputDesc->isSoundTrigger()) {
7454 result.source = AUDIO_SOURCE_VOICE_RECOGNITION;
7455 }
7456 return result; }).
Eric Laurent1c333e22014-05-20 10:48:17 -07007457 //only one input device for now
François Gaffie11d30102018-11-02 16:09:09 +01007458 addSource(device);
Mikhail Naganovdc769682018-05-04 15:34:08 -07007459 status = installPatch(__func__, patchHandle, inputDesc.get(), patchBuilder.patch(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07007460 }
7461 }
7462 return status;
7463}
7464
Eric Laurent6a94d692014-05-20 11:18:06 -07007465status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
7466 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07007467{
Eric Laurent1f2f2232014-06-02 12:01:23 -07007468 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07007469 ssize_t index;
7470 if (patchHandle) {
7471 index = mAudioPatches.indexOfKey(*patchHandle);
7472 } else {
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08007473 index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007474 }
7475 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07007476 return INVALID_OPERATION;
7477 }
Eric Laurent6a94d692014-05-20 11:18:06 -07007478 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007479 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07007480 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07007481 inputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
François Gaffieafd4cea2019-11-18 15:50:22 +01007482 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007483 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07007484 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07007485 return status;
7486}
7487
François Gaffie11d30102018-11-02 16:09:09 +01007488sp<IOProfile> AudioPolicyManager::getInputProfile(const sp<DeviceDescriptor> &device,
François Gaffie53615e22015-03-19 09:24:12 +01007489 uint32_t& samplingRate,
Andy Hungf129b032015-04-07 13:45:50 -07007490 audio_format_t& format,
7491 audio_channel_mask_t& channelMask,
François Gaffie53615e22015-03-19 09:24:12 +01007492 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07007493{
7494 // Choose an input profile based on the requested capture parameters: select the first available
7495 // profile supporting all requested parameters.
jiabin2fd710d2022-05-02 23:20:22 +00007496 // The flags can be ignored if it doesn't contain a much match flag.
Andy Hungf129b032015-04-07 13:45:50 -07007497 //
7498 // TODO: perhaps isCompatibleProfile should return a "matching" score so we can return
7499 // the best matching profile, not the first one.
Eric Laurente552edb2014-03-10 17:42:56 -07007500
Atneya Nair0f0a8032022-12-12 16:20:12 -08007501 using underlying_input_flag_t = std::underlying_type_t<audio_input_flags_t>;
7502 const underlying_input_flag_t mustMatchFlag = AUDIO_INPUT_FLAG_MMAP_NOIRQ |
7503 AUDIO_INPUT_FLAG_HOTWORD_TAP | AUDIO_INPUT_FLAG_HW_LOOKBACK;
Glenn Kasten730b9262018-03-29 15:01:26 -07007504
Atneya Nair0f0a8032022-12-12 16:20:12 -08007505 const underlying_input_flag_t oriFlags = flags;
Eric Laurente552edb2014-03-10 17:42:56 -07007506
jiabin2fd710d2022-05-02 23:20:22 +00007507 for (;;) {
7508 sp<IOProfile> firstInexact = nullptr;
7509 uint32_t updatedSamplingRate = 0;
7510 audio_format_t updatedFormat = AUDIO_FORMAT_INVALID;
7511 audio_channel_mask_t updatedChannelMask = AUDIO_CHANNEL_INVALID;
7512 for (const auto& hwModule : mHwModules) {
7513 for (const auto& profile : hwModule->getInputProfiles()) {
7514 // profile->log();
7515 //updatedFormat = format;
7516 if (profile->isCompatibleProfile(DeviceVector(device), samplingRate,
7517 &samplingRate /*updatedSamplingRate*/,
7518 format,
7519 &format, /*updatedFormat*/
7520 channelMask,
7521 &channelMask /*updatedChannelMask*/,
7522 // FIXME ugly cast
7523 (audio_output_flags_t) flags,
7524 true /*exactMatchRequiredForInputFlags*/)) {
7525 return profile;
7526 }
7527 if (firstInexact == nullptr && profile->isCompatibleProfile(DeviceVector(device),
7528 samplingRate,
7529 &updatedSamplingRate,
7530 format,
7531 &updatedFormat,
7532 channelMask,
7533 &updatedChannelMask,
7534 // FIXME ugly cast
7535 (audio_output_flags_t) flags,
7536 false /*exactMatchRequiredForInputFlags*/)) {
7537 firstInexact = profile;
7538 }
7539 }
7540 }
7541
7542 if (firstInexact != nullptr) {
7543 samplingRate = updatedSamplingRate;
7544 format = updatedFormat;
7545 channelMask = updatedChannelMask;
7546 return firstInexact;
7547 } else if (flags & AUDIO_INPUT_FLAG_RAW) {
7548 flags = (audio_input_flags_t) (flags & ~AUDIO_INPUT_FLAG_RAW); // retry
7549 } else if ((flags & mustMatchFlag) == AUDIO_INPUT_FLAG_NONE &&
7550 flags != AUDIO_INPUT_FLAG_NONE && audio_is_linear_pcm(format)) {
7551 flags = AUDIO_INPUT_FLAG_NONE;
7552 } else { // fail
7553 ALOGW("%s could not find profile for device %s, sampling rate %u, format %#x, "
7554 "channel mask 0x%X, flags %#x", __func__, device->toString().c_str(),
7555 samplingRate, format, channelMask, oriFlags);
7556 break;
Eric Laurente552edb2014-03-10 17:42:56 -07007557 }
7558 }
jiabin2fd710d2022-05-02 23:20:22 +00007559
7560 return nullptr;
Eric Laurente552edb2014-03-10 17:42:56 -07007561}
7562
François Gaffieaaac0fd2018-11-22 17:56:39 +01007563float AudioPolicyManager::computeVolume(IVolumeCurves &curves,
7564 VolumeSource volumeSource,
François Gaffied1ab2bd2015-12-02 18:20:06 +01007565 int index,
jiabin9a3361e2019-10-01 09:38:30 -07007566 const DeviceTypeSet& deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07007567{
jiabin9a3361e2019-10-01 09:38:30 -07007568 float volumeDb = curves.volIndexToDb(Volume::getDeviceCategory(deviceTypes), index);
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07007569
7570 // handle the case of accessibility active while a ringtone is playing: if the ringtone is much
7571 // louder than the accessibility prompt, the prompt cannot be heard, thus masking the touch
7572 // exploration of the dialer UI. In this situation, bring the accessibility volume closer to
7573 // the ringtone volume
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007574 const auto callVolumeSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL, false);
7575 const auto ringVolumeSrc = toVolumeSource(AUDIO_STREAM_RING, false);
7576 const auto musicVolumeSrc = toVolumeSource(AUDIO_STREAM_MUSIC, false);
7577 const auto alarmVolumeSrc = toVolumeSource(AUDIO_STREAM_ALARM, false);
7578 const auto a11yVolumeSrc = toVolumeSource(AUDIO_STREAM_ACCESSIBILITY, false);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007579
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07007580 if (volumeSource == a11yVolumeSrc
François Gaffieaaac0fd2018-11-22 17:56:39 +01007581 && (AUDIO_MODE_RINGTONE == mEngine->getPhoneState()) &&
7582 mOutputs.isActive(ringVolumeSrc, 0)) {
7583 auto &ringCurves = getVolumeCurves(AUDIO_STREAM_RING);
jiabin9a3361e2019-10-01 09:38:30 -07007584 const float ringVolumeDb = computeVolume(ringCurves, ringVolumeSrc, index, deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007585 return ringVolumeDb - 4 > volumeDb ? ringVolumeDb - 4 : volumeDb;
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07007586 }
7587
Eric Laurentdcd4ab12018-06-29 17:45:13 -07007588 // in-call: always cap volume by voice volume + some low headroom
François Gaffieaaac0fd2018-11-22 17:56:39 +01007589 if ((volumeSource != callVolumeSrc && (isInCall() ||
7590 mOutputs.isActiveLocally(callVolumeSrc))) &&
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007591 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM, false) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01007592 volumeSource == ringVolumeSrc || volumeSource == musicVolumeSrc ||
7593 volumeSource == alarmVolumeSrc ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007594 volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION, false) ||
7595 volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false) ||
7596 volumeSource == toVolumeSource(AUDIO_STREAM_DTMF, false) ||
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07007597 volumeSource == a11yVolumeSrc)) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007598 auto &voiceCurves = getVolumeCurves(callVolumeSrc);
jiabin9a3361e2019-10-01 09:38:30 -07007599 int voiceVolumeIndex = voiceCurves.getVolumeIndex(deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007600 const float maxVoiceVolDb =
jiabin9a3361e2019-10-01 09:38:30 -07007601 computeVolume(voiceCurves, callVolumeSrc, voiceVolumeIndex, deviceTypes)
Eric Laurent7731b5a2018-04-06 15:47:22 -07007602 + IN_CALL_EARPIECE_HEADROOM_DB;
Abhijith Shastry329ddab2019-04-23 11:53:26 -07007603 // FIXME: Workaround for call screening applications until a proper audio mode is defined
7604 // to support this scenario : Exempt the RING stream from the audio cap if the audio was
7605 // programmatically muted.
7606 // VOICE_CALL stream has minVolumeIndex > 0 : Users cannot set the volume of voice calls to
7607 // 0. We don't want to cap volume when the system has programmatically muted the voice call
7608 // stream. See setVolumeCurveIndex() for more information.
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07007609 bool exemptFromCapping =
7610 ((volumeSource == ringVolumeSrc) || (volumeSource == a11yVolumeSrc))
7611 && (voiceVolumeIndex == 0);
Abhijith Shastry329ddab2019-04-23 11:53:26 -07007612 ALOGV_IF(exemptFromCapping, "%s volume source %d at vol=%f not capped", __func__,
7613 volumeSource, volumeDb);
7614 if ((volumeDb > maxVoiceVolDb) && !exemptFromCapping) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007615 ALOGV("%s volume source %d at vol=%f overriden by volume group %d at vol=%f", __func__,
7616 volumeSource, volumeDb, callVolumeSrc, maxVoiceVolDb);
7617 volumeDb = maxVoiceVolDb;
Jean-Michel Trivi719a9872017-08-05 13:51:35 -07007618 }
7619 }
Eric Laurente552edb2014-03-10 17:42:56 -07007620 // if a headset is connected, apply the following rules to ring tones and notifications
7621 // to avoid sound level bursts in user's ears:
Eric Laurent6af1c1d2016-04-14 11:20:44 -07007622 // - always attenuate notifications volume by 6dB
7623 // - attenuate ring tones volume by 6dB unless music is not playing and
7624 // speaker is part of the select devices
Eric Laurente552edb2014-03-10 17:42:56 -07007625 // - if music is playing, always limit the volume to current music volume,
7626 // with a minimum threshold at -36dB so that notification is always perceived.
jiabin9a3361e2019-10-01 09:38:30 -07007627 if (!Intersection(deviceTypes,
7628 {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP, AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES,
7629 AUDIO_DEVICE_OUT_WIRED_HEADSET, AUDIO_DEVICE_OUT_WIRED_HEADPHONE,
Eric Laurentc42df452020-08-07 10:51:53 -07007630 AUDIO_DEVICE_OUT_USB_HEADSET, AUDIO_DEVICE_OUT_HEARING_AID,
7631 AUDIO_DEVICE_OUT_BLE_HEADSET}).empty() &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01007632 ((volumeSource == alarmVolumeSrc ||
7633 volumeSource == ringVolumeSrc) ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007634 (volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION, false)) ||
7635 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM, false)) ||
7636 ((volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false)) &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01007637 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) &&
7638 curves.canBeMuted()) {
7639
Eric Laurente552edb2014-03-10 17:42:56 -07007640 // when the phone is ringing we must consider that music could have been paused just before
7641 // by the music application and behave as if music was active if the last music track was
7642 // just stopped
Eric Laurent3b73df72014-03-11 09:06:29 -07007643 if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY) ||
Eric Laurente552edb2014-03-10 17:42:56 -07007644 mLimitRingtoneVolume) {
François Gaffie43c73442018-11-08 08:21:55 +01007645 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
jiabin9a3361e2019-10-01 09:38:30 -07007646 DeviceTypeSet musicDevice =
François Gaffiec005e562018-11-06 15:04:49 +01007647 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
7648 nullptr, true /*fromCache*/).types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01007649 auto &musicCurves = getVolumeCurves(AUDIO_STREAM_MUSIC);
jiabin9a3361e2019-10-01 09:38:30 -07007650 float musicVolDb = computeVolume(musicCurves,
7651 musicVolumeSrc,
7652 musicCurves.getVolumeIndex(musicDevice),
7653 musicDevice);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007654 float minVolDb = (musicVolDb > SONIFICATION_HEADSET_VOLUME_MIN_DB) ?
7655 musicVolDb : SONIFICATION_HEADSET_VOLUME_MIN_DB;
7656 if (volumeDb > minVolDb) {
7657 volumeDb = minVolDb;
7658 ALOGV("computeVolume limiting volume to %f musicVol %f", minVolDb, musicVolDb);
Eric Laurente552edb2014-03-10 17:42:56 -07007659 }
Eric Laurent7b6385c2021-05-12 17:55:36 +02007660 if (Volume::getDeviceForVolume(deviceTypes) != AUDIO_DEVICE_OUT_SPEAKER
7661 && !Intersection(deviceTypes, {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP,
7662 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES}).empty()) {
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07007663 // on A2DP, also ensure notification volume is not too low compared to media when
7664 // intended to be played
François Gaffie43c73442018-11-08 08:21:55 +01007665 if ((volumeDb > -96.0f) &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01007666 (musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB > volumeDb)) {
jiabin9a3361e2019-10-01 09:38:30 -07007667 ALOGV("%s increasing volume for volume source=%d device=%s from %f to %f",
7668 __func__, volumeSource, dumpDeviceTypes(deviceTypes).c_str(), volumeDb,
François Gaffieaaac0fd2018-11-22 17:56:39 +01007669 musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB);
7670 volumeDb = musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB;
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07007671 }
7672 }
jiabin9a3361e2019-10-01 09:38:30 -07007673 } else if ((Volume::getDeviceForVolume(deviceTypes) != AUDIO_DEVICE_OUT_SPEAKER) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01007674 (!(volumeSource == alarmVolumeSrc || volumeSource == ringVolumeSrc))) {
François Gaffie43c73442018-11-08 08:21:55 +01007675 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07007676 }
7677 }
7678
François Gaffie43c73442018-11-08 08:21:55 +01007679 return volumeDb;
Eric Laurente552edb2014-03-10 17:42:56 -07007680}
7681
Eric Laurent3839bc02018-07-10 18:33:34 -07007682int AudioPolicyManager::rescaleVolumeIndex(int srcIndex,
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01007683 VolumeSource fromVolumeSource,
7684 VolumeSource toVolumeSource)
Eric Laurent3839bc02018-07-10 18:33:34 -07007685{
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01007686 if (fromVolumeSource == toVolumeSource) {
Eric Laurent3839bc02018-07-10 18:33:34 -07007687 return srcIndex;
7688 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01007689 auto &srcCurves = getVolumeCurves(fromVolumeSource);
7690 auto &dstCurves = getVolumeCurves(toVolumeSource);
Eric Laurentf5aa58d2019-02-22 18:20:11 -08007691 float minSrc = (float)srcCurves.getVolumeIndexMin();
7692 float maxSrc = (float)srcCurves.getVolumeIndexMax();
7693 float minDst = (float)dstCurves.getVolumeIndexMin();
7694 float maxDst = (float)dstCurves.getVolumeIndexMax();
Eric Laurent3839bc02018-07-10 18:33:34 -07007695
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08007696 // preserve mute request or correct range
7697 if (srcIndex < minSrc) {
7698 if (srcIndex == 0) {
7699 return 0;
7700 }
7701 srcIndex = minSrc;
7702 } else if (srcIndex > maxSrc) {
7703 srcIndex = maxSrc;
7704 }
Eric Laurent3839bc02018-07-10 18:33:34 -07007705 return (int)(minDst + ((srcIndex - minSrc) * (maxDst - minDst)) / (maxSrc - minSrc));
7706}
7707
François Gaffieaaac0fd2018-11-22 17:56:39 +01007708status_t AudioPolicyManager::checkAndSetVolume(IVolumeCurves &curves,
7709 VolumeSource volumeSource,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08007710 int index,
7711 const sp<AudioOutputDescriptor>& outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07007712 DeviceTypeSet deviceTypes,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08007713 int delayMs,
7714 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07007715{
François Gaffieaaac0fd2018-11-22 17:56:39 +01007716 // do not change actual attributes volume if the attributes is muted
7717 if (outputDesc->isMuted(volumeSource)) {
7718 ALOGVV("%s: volume source %d muted count %d active=%d", __func__, volumeSource,
7719 outputDesc->getMuteCount(volumeSource), outputDesc->isActive(volumeSource));
Eric Laurente552edb2014-03-10 17:42:56 -07007720 return NO_ERROR;
7721 }
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007722 VolumeSource callVolSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL, false);
7723 VolumeSource btScoVolSrc = toVolumeSource(AUDIO_STREAM_BLUETOOTH_SCO, false);
7724 bool isVoiceVolSrc = (volumeSource != VOLUME_SOURCE_NONE) && (callVolSrc == volumeSource);
7725 bool isBtScoVolSrc = (volumeSource != VOLUME_SOURCE_NONE) && (btScoVolSrc == volumeSource);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007726
Eric Laurent2517af32020-11-25 15:31:27 +01007727 bool isScoRequested = isScoRequestedForComm();
Eric Laurent1a8b45f2022-04-13 16:01:47 +02007728 bool isHAUsed = isHearingAidUsedForComm();
7729
Eric Laurente552edb2014-03-10 17:42:56 -07007730 // do not change in call volume if bluetooth is connected and vice versa
François Gaffieaaac0fd2018-11-22 17:56:39 +01007731 // if sco and call follow same curves, bypass forceUseForComm
7732 if ((callVolSrc != btScoVolSrc) &&
Eric Laurent2517af32020-11-25 15:31:27 +01007733 ((isVoiceVolSrc && isScoRequested) ||
Beibeif660a512023-02-28 17:00:34 +08007734 (isBtScoVolSrc && !(isScoRequested || isHAUsed))) &&
7735 !isSingleDeviceType(deviceTypes, AUDIO_DEVICE_OUT_TELEPHONY_TX)) {
Eric Laurent2517af32020-11-25 15:31:27 +01007736 ALOGV("%s cannot set volume group %d volume when is%srequested for comm", __func__,
Eric Laurent1a8b45f2022-04-13 16:01:47 +02007737 volumeSource, isScoRequested ? " " : " not ");
Eric Laurent571ef962020-07-24 11:43:48 -07007738 // Do not return an error here as AudioService will always set both voice call
7739 // and bluetooth SCO volumes due to stream aliasing.
7740 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07007741 }
jiabin9a3361e2019-10-01 09:38:30 -07007742 if (deviceTypes.empty()) {
7743 deviceTypes = outputDesc->devices().types();
chenxin2080986da2023-07-17 11:45:21 +08007744 index = curves.getVolumeIndex(deviceTypes);
7745 ALOGD("%s if deviceTypes is change from none to device %s, need get index %d",
7746 __func__, dumpDeviceTypes(deviceTypes).c_str(), index);
Eric Laurentc75307b2015-03-17 15:29:32 -07007747 }
Eric Laurent275e8e92014-11-30 15:14:47 -08007748
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00007749 if (curves.getVolumeIndexMin() < 0 || curves.getVolumeIndexMax() < 0) {
7750 ALOGE("invalid volume index range");
7751 return BAD_VALUE;
7752 }
7753
jiabin9a3361e2019-10-01 09:38:30 -07007754 float volumeDb = computeVolume(curves, volumeSource, index, deviceTypes);
7755 if (outputDesc->isFixedVolume(deviceTypes) ||
Eric Laurent9698a4c2020-10-12 17:10:23 -07007756 // Force VoIP volume to max for bluetooth SCO device except if muted
7757 (index != 0 && (isVoiceVolSrc || isBtScoVolSrc) &&
jiabin9a3361e2019-10-01 09:38:30 -07007758 isSingleDeviceType(deviceTypes, audio_is_bluetooth_out_sco_device))) {
Eric Laurentffbc80f2015-03-18 18:30:19 -07007759 volumeDb = 0.0f;
Eric Laurent275e8e92014-11-30 15:14:47 -08007760 }
Francois Gaffie593634d2021-06-22 13:31:31 +02007761 const bool muted = (index == 0) && (volumeDb != 0.0f);
jiabin9a3361e2019-10-01 09:38:30 -07007762 outputDesc->setVolume(
Francois Gaffie593634d2021-06-22 13:31:31 +02007763 volumeDb, muted, volumeSource, curves.getStreamTypes(), deviceTypes, delayMs, force);
Eric Laurentc75307b2015-03-17 15:29:32 -07007764
Eric Laurente8f2c0f2021-08-17 11:17:19 +02007765 if (outputDesc == mPrimaryOutput && (isVoiceVolSrc || isBtScoVolSrc)) {
Eric Laurente552edb2014-03-10 17:42:56 -07007766 float voiceVolume;
Eric Laurentfad001d2019-06-11 19:17:57 -07007767 // 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 +01007768 if (isVoiceVolSrc) {
7769 voiceVolume = (float)index/(float)curves.getVolumeIndexMax();
Eric Laurente552edb2014-03-10 17:42:56 -07007770 } else {
Eric Laurentfad001d2019-06-11 19:17:57 -07007771 voiceVolume = index == 0 ? 0.0 : 1.0;
Eric Laurente552edb2014-03-10 17:42:56 -07007772 }
Eric Laurent18fba842016-03-31 14:41:26 -07007773 if (voiceVolume != mLastVoiceVolume) {
Eric Laurente552edb2014-03-10 17:42:56 -07007774 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
7775 mLastVoiceVolume = voiceVolume;
7776 }
7777 }
Eric Laurente552edb2014-03-10 17:42:56 -07007778 return NO_ERROR;
7779}
7780
Eric Laurentc75307b2015-03-17 15:29:32 -07007781void AudioPolicyManager::applyStreamVolumes(const sp<AudioOutputDescriptor>& outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07007782 const DeviceTypeSet& deviceTypes,
7783 int delayMs,
7784 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07007785{
jiabincd510522020-01-22 09:40:55 -08007786 ALOGVV("applyStreamVolumes() for device %s", dumpDeviceTypes(deviceTypes).c_str());
François Gaffieaaac0fd2018-11-22 17:56:39 +01007787 for (const auto &volumeGroup : mEngine->getVolumeGroups()) {
7788 auto &curves = getVolumeCurves(toVolumeSource(volumeGroup));
7789 checkAndSetVolume(curves, toVolumeSource(volumeGroup),
jiabin9a3361e2019-10-01 09:38:30 -07007790 curves.getVolumeIndex(deviceTypes),
7791 outputDesc, deviceTypes, delayMs, force);
Eric Laurente552edb2014-03-10 17:42:56 -07007792 }
7793}
7794
François Gaffiec005e562018-11-06 15:04:49 +01007795void AudioPolicyManager::setStrategyMute(product_strategy_t strategy,
7796 bool on,
7797 const sp<AudioOutputDescriptor>& outputDesc,
7798 int delayMs,
jiabin9a3361e2019-10-01 09:38:30 -07007799 DeviceTypeSet deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07007800{
François Gaffieaaac0fd2018-11-22 17:56:39 +01007801 std::vector<VolumeSource> sourcesToMute;
7802 for (auto attributes: mEngine->getAllAttributesForProductStrategy(strategy)) {
7803 ALOGVV("%s() attributes %s, mute %d, output ID %d", __func__,
7804 toString(attributes).c_str(), on, outputDesc->getId());
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007805 VolumeSource source = toVolumeSource(attributes, false);
7806 if ((source != VOLUME_SOURCE_NONE) &&
7807 (std::find(begin(sourcesToMute), end(sourcesToMute), source)
7808 == end(sourcesToMute))) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007809 sourcesToMute.push_back(source);
7810 }
Eric Laurente552edb2014-03-10 17:42:56 -07007811 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01007812 for (auto source : sourcesToMute) {
jiabin9a3361e2019-10-01 09:38:30 -07007813 setVolumeSourceMute(source, on, outputDesc, delayMs, deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007814 }
7815
Eric Laurente552edb2014-03-10 17:42:56 -07007816}
7817
François Gaffieaaac0fd2018-11-22 17:56:39 +01007818void AudioPolicyManager::setVolumeSourceMute(VolumeSource volumeSource,
7819 bool on,
7820 const sp<AudioOutputDescriptor>& outputDesc,
7821 int delayMs,
jiabin9a3361e2019-10-01 09:38:30 -07007822 DeviceTypeSet deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07007823{
jiabin9a3361e2019-10-01 09:38:30 -07007824 if (deviceTypes.empty()) {
7825 deviceTypes = outputDesc->devices().types();
Eric Laurente552edb2014-03-10 17:42:56 -07007826 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01007827 auto &curves = getVolumeCurves(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07007828 if (on) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007829 if (!outputDesc->isMuted(volumeSource)) {
Eric Laurentf5aa58d2019-02-22 18:20:11 -08007830 if (curves.canBeMuted() &&
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007831 (volumeSource != toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01007832 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) ==
7833 AUDIO_POLICY_FORCE_NONE))) {
jiabin9a3361e2019-10-01 09:38:30 -07007834 checkAndSetVolume(curves, volumeSource, 0, outputDesc, deviceTypes, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07007835 }
7836 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01007837 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not
7838 // ignored
7839 outputDesc->incMuteCount(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07007840 } else {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007841 if (!outputDesc->isMuted(volumeSource)) {
7842 ALOGV("%s unmuting non muted attributes!", __func__);
Eric Laurente552edb2014-03-10 17:42:56 -07007843 return;
7844 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01007845 if (outputDesc->decMuteCount(volumeSource) == 0) {
7846 checkAndSetVolume(curves, volumeSource,
jiabin9a3361e2019-10-01 09:38:30 -07007847 curves.getVolumeIndex(deviceTypes),
Eric Laurentc75307b2015-03-17 15:29:32 -07007848 outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07007849 deviceTypes,
Eric Laurente552edb2014-03-10 17:42:56 -07007850 delayMs);
7851 }
7852 }
7853}
7854
François Gaffie53615e22015-03-19 09:24:12 +01007855bool AudioPolicyManager::isValidAttributes(const audio_attributes_t *paa)
7856{
François Gaffiec005e562018-11-06 15:04:49 +01007857 // has flags that map to a stream type?
Eric Laurente83b55d2014-11-14 10:06:21 -08007858 if ((paa->flags & (AUDIO_FLAG_AUDIBILITY_ENFORCED | AUDIO_FLAG_SCO | AUDIO_FLAG_BEACON)) != 0) {
7859 return true;
7860 }
7861
7862 // has known usage?
7863 switch (paa->usage) {
7864 case AUDIO_USAGE_UNKNOWN:
7865 case AUDIO_USAGE_MEDIA:
7866 case AUDIO_USAGE_VOICE_COMMUNICATION:
7867 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
7868 case AUDIO_USAGE_ALARM:
7869 case AUDIO_USAGE_NOTIFICATION:
7870 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
7871 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
7872 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
7873 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
7874 case AUDIO_USAGE_NOTIFICATION_EVENT:
7875 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
7876 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
7877 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
7878 case AUDIO_USAGE_GAME:
Eric Laurent275e8e92014-11-30 15:14:47 -08007879 case AUDIO_USAGE_VIRTUAL_SOURCE:
Jean-Michel Trivi36867762016-12-29 12:03:28 -08007880 case AUDIO_USAGE_ASSISTANT:
Eric Laurent21777f82019-12-06 18:12:06 -08007881 case AUDIO_USAGE_CALL_ASSISTANT:
Hayden Gomes524159d2019-12-23 14:41:47 -08007882 case AUDIO_USAGE_EMERGENCY:
7883 case AUDIO_USAGE_SAFETY:
7884 case AUDIO_USAGE_VEHICLE_STATUS:
7885 case AUDIO_USAGE_ANNOUNCEMENT:
Eric Laurente83b55d2014-11-14 10:06:21 -08007886 break;
7887 default:
7888 return false;
7889 }
7890 return true;
7891}
7892
François Gaffie2110e042015-03-24 08:41:51 +01007893audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
7894{
7895 return mEngine->getForceUse(usage);
7896}
7897
Eric Laurent96d1dda2022-03-14 17:14:19 +01007898bool AudioPolicyManager::isInCall() const {
François Gaffie2110e042015-03-24 08:41:51 +01007899 return isStateInCall(mEngine->getPhoneState());
7900}
7901
Eric Laurent96d1dda2022-03-14 17:14:19 +01007902bool AudioPolicyManager::isStateInCall(int state) const {
François Gaffie2110e042015-03-24 08:41:51 +01007903 return is_state_in_call(state);
7904}
7905
Eric Laurentf9cccec2022-11-16 19:12:00 +01007906bool AudioPolicyManager::isCallAudioAccessible() const {
Eric Laurent74b71512019-11-06 17:21:57 -08007907 audio_mode_t mode = mEngine->getPhoneState();
7908 return (mode == AUDIO_MODE_IN_CALL)
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01007909 || (mode == AUDIO_MODE_CALL_SCREEN)
7910 || (mode == AUDIO_MODE_CALL_REDIRECT);
Eric Laurent74b71512019-11-06 17:21:57 -08007911}
7912
Eric Laurentf9cccec2022-11-16 19:12:00 +01007913bool AudioPolicyManager::isInCallOrScreening() const {
7914 audio_mode_t mode = mEngine->getPhoneState();
7915 return isStateInCall(mode) || mode == AUDIO_MODE_CALL_SCREEN;
7916}
7917
Eric Laurentd60560a2015-04-10 11:31:20 -07007918void AudioPolicyManager::cleanUpForDevice(const sp<DeviceDescriptor>& deviceDesc)
7919{
7920 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07007921 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02007922 if (sourceDesc->isConnected() && (sourceDesc->srcDevice()->equals(deviceDesc) ||
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02007923 sourceDesc->sinkDevice()->equals(deviceDesc))
7924 && !isCallRxAudioSource(sourceDesc)) {
Francois Gaffiea0e5c992020-09-29 16:05:07 +02007925 disconnectAudioSource(sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07007926 }
7927 }
7928
7929 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
7930 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
7931 bool release = false;
7932 for (size_t j = 0; j < patchDesc->mPatch.num_sources && !release; j++) {
7933 const struct audio_port_config *source = &patchDesc->mPatch.sources[j];
7934 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
7935 source->ext.device.type == deviceDesc->type()) {
7936 release = true;
7937 }
7938 }
Francois Gaffiea0e5c992020-09-29 16:05:07 +02007939 const char *address = deviceDesc->address().c_str();
Eric Laurentd60560a2015-04-10 11:31:20 -07007940 for (size_t j = 0; j < patchDesc->mPatch.num_sinks && !release; j++) {
7941 const struct audio_port_config *sink = &patchDesc->mPatch.sinks[j];
7942 if (sink->type == AUDIO_PORT_TYPE_DEVICE &&
Francois Gaffiea0e5c992020-09-29 16:05:07 +02007943 sink->ext.device.type == deviceDesc->type() &&
7944 (strnlen(address, AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0
7945 || strncmp(sink->ext.device.address, address,
7946 AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0)) {
Eric Laurentd60560a2015-04-10 11:31:20 -07007947 release = true;
7948 }
7949 }
7950 if (release) {
François Gaffieafd4cea2019-11-18 15:50:22 +01007951 ALOGV("%s releasing patch %u", __FUNCTION__, patchDesc->getHandle());
7952 releaseAudioPatch(patchDesc->getHandle(), patchDesc->getUid());
Eric Laurentd60560a2015-04-10 11:31:20 -07007953 }
7954 }
Francois Gaffie716e1432019-01-14 16:58:59 +01007955
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01007956 mInputs.clearSessionRoutesForDevice(deviceDesc);
7957
Francois Gaffie716e1432019-01-14 16:58:59 +01007958 mHwModules.cleanUpForDevice(deviceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07007959}
7960
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007961void AudioPolicyManager::modifySurroundFormats(
7962 const sp<DeviceDescriptor>& devDesc, FormatVector *formatsPtr) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007963 std::unordered_set<audio_format_t> enforcedSurround(
7964 devDesc->encodedFormats().begin(), devDesc->encodedFormats().end());
Mikhail Naganov100f0122018-11-29 11:22:16 -08007965 std::unordered_set<audio_format_t> allSurround; // A flat set of all known surround formats
Mikhail Naganovb0fbc1b2023-04-28 13:06:32 -07007966 for (const auto& pair : mConfig->getSurroundFormats()) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08007967 allSurround.insert(pair.first);
7968 for (const auto& subformat : pair.second) allSurround.insert(subformat);
7969 }
Phil Burk09bc4612016-02-24 15:58:15 -08007970
7971 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
7972 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Phil Burk0709b0a2016-03-31 12:54:57 -07007973 ALOGD("%s: forced use = %d", __FUNCTION__, forceUse);
Mikhail Naganov100f0122018-11-29 11:22:16 -08007974 // This is the resulting set of formats depending on the surround mode:
7975 // 'all surround' = allSurround
7976 // 'enforced surround' = enforcedSurround [may include IEC69137 which isn't raw surround fmt]
7977 // 'non-surround' = not in 'all surround' and not in 'enforced surround'
7978 // 'manual surround' = mManualSurroundFormats
7979 // AUTO: formats v 'enforced surround'
7980 // ALWAYS: formats v 'all surround' v 'enforced surround'
7981 // NEVER: formats ^ 'non-surround'
7982 // MANUAL: formats ^ ('non-surround' v 'manual surround' v (IEC69137 ^ 'enforced surround'))
Phil Burk09bc4612016-02-24 15:58:15 -08007983
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007984 std::unordered_set<audio_format_t> formatSet;
7985 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL
7986 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08007987 // formatSet is (formats ^ 'non-surround')
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007988 for (auto formatIter = formatsPtr->begin(); formatIter != formatsPtr->end(); ++formatIter) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08007989 if (allSurround.count(*formatIter) == 0 && enforcedSurround.count(*formatIter) == 0) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007990 formatSet.insert(*formatIter);
7991 }
7992 }
7993 } else {
7994 formatSet.insert(formatsPtr->begin(), formatsPtr->end());
7995 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08007996 formatsPtr->clear(); // Re-filled from the formatSet at the end.
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007997
jiabin81772902018-04-02 17:52:27 -07007998 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08007999 formatSet.insert(mManualSurroundFormats.begin(), mManualSurroundFormats.end());
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008000 // Enable IEC61937 when in MANUAL mode if it's enforced for this device.
8001 if (enforcedSurround.count(AUDIO_FORMAT_IEC61937) != 0) {
8002 formatSet.insert(AUDIO_FORMAT_IEC61937);
Phil Burk09bc4612016-02-24 15:58:15 -08008003 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08008004 } else if (forceUse != AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) { // AUTO or ALWAYS
8005 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS) {
8006 formatSet.insert(allSurround.begin(), allSurround.end());
Phil Burk07ac1142016-03-25 13:39:29 -07008007 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08008008 formatSet.insert(enforcedSurround.begin(), enforcedSurround.end());
Phil Burk09bc4612016-02-24 15:58:15 -08008009 }
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008010 for (const auto& format : formatSet) {
jiabin06e4bab2019-07-29 10:13:34 -07008011 formatsPtr->push_back(format);
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008012 }
Phil Burk0709b0a2016-03-31 12:54:57 -07008013}
8014
jiabin06e4bab2019-07-29 10:13:34 -07008015void AudioPolicyManager::modifySurroundChannelMasks(ChannelMaskSet *channelMasksPtr) {
8016 ChannelMaskSet &channelMasks = *channelMasksPtr;
Phil Burk0709b0a2016-03-31 12:54:57 -07008017 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
8018 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
8019
8020 // If NEVER, then remove support for channelMasks > stereo.
8021 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
jiabin06e4bab2019-07-29 10:13:34 -07008022 for (auto it = channelMasks.begin(); it != channelMasks.end();) {
8023 audio_channel_mask_t channelMask = *it;
Phil Burk0709b0a2016-03-31 12:54:57 -07008024 if (channelMask & ~AUDIO_CHANNEL_OUT_STEREO) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01008025 ALOGV("%s: force NEVER, so remove channelMask 0x%08x", __FUNCTION__, channelMask);
jiabin06e4bab2019-07-29 10:13:34 -07008026 it = channelMasks.erase(it);
Phil Burk0709b0a2016-03-31 12:54:57 -07008027 } else {
jiabin06e4bab2019-07-29 10:13:34 -07008028 ++it;
Phil Burk0709b0a2016-03-31 12:54:57 -07008029 }
8030 }
jiabin81772902018-04-02 17:52:27 -07008031 // If ALWAYS or MANUAL, then make sure we at least support 5.1
8032 } else if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS
8033 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Phil Burk0709b0a2016-03-31 12:54:57 -07008034 bool supports5dot1 = false;
8035 // Are there any channel masks that can be considered "surround"?
Mikhail Naganovcf84e592017-12-07 11:25:11 -08008036 for (audio_channel_mask_t channelMask : channelMasks) {
Phil Burk0709b0a2016-03-31 12:54:57 -07008037 if ((channelMask & AUDIO_CHANNEL_OUT_5POINT1) == AUDIO_CHANNEL_OUT_5POINT1) {
8038 supports5dot1 = true;
8039 break;
8040 }
8041 }
8042 // If not then add 5.1 support.
8043 if (!supports5dot1) {
jiabin06e4bab2019-07-29 10:13:34 -07008044 channelMasks.insert(AUDIO_CHANNEL_OUT_5POINT1);
Eric Laurentfecbceb2021-02-09 14:46:43 +01008045 ALOGV("%s: force MANUAL or ALWAYS, so adding channelMask for 5.1 surround", __func__);
Phil Burk0709b0a2016-03-31 12:54:57 -07008046 }
Phil Burk09bc4612016-02-24 15:58:15 -08008047 }
8048}
8049
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008050void AudioPolicyManager::updateAudioProfiles(const sp<DeviceDescriptor>& devDesc,
Phil Burk00eeb322016-03-31 12:41:00 -07008051 audio_io_handle_t ioHandle,
François Gaffie112b0af2015-11-19 16:13:25 +01008052 AudioProfileVector &profiles)
8053{
8054 String8 reply;
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008055 audio_devices_t device = devDesc->type();
Phil Burk0709b0a2016-03-31 12:54:57 -07008056
François Gaffie112b0af2015-11-19 16:13:25 +01008057 // Format MUST be checked first to update the list of AudioProfile
8058 if (profiles.hasDynamicFormat()) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07008059 reply = mpClientInterface->getParameters(
8060 ioHandle, String8(AudioParameter::keyStreamSupportedFormats));
Tomasz Wasilczyk8f36f6e2023-08-15 20:59:35 +00008061 ALOGV("%s: supported formats %d, %s", __FUNCTION__, ioHandle, reply.c_str());
Eric Laurent62e4bc52016-02-02 18:37:28 -08008062 AudioParameter repliedParameters(reply);
jiabinf26596b2023-04-12 18:56:39 +00008063 FormatVector formats;
Eric Laurent62e4bc52016-02-02 18:37:28 -08008064 if (repliedParameters.get(
jiabinf26596b2023-04-12 18:56:39 +00008065 String8(AudioParameter::keyStreamSupportedFormats), reply) == NO_ERROR) {
Tomasz Wasilczyk8f36f6e2023-08-15 20:59:35 +00008066 formats = formatsFromString(reply.c_str());
jiabinf26596b2023-04-12 18:56:39 +00008067 } else if (devDesc->hasValidAudioProfile()) {
8068 ALOGD("%s: using the device profiles", __func__);
8069 formats = devDesc->getAudioProfiles().getSupportedFormats();
8070 } else {
8071 ALOGE("%s: failed to retrieve format, bailing out", __func__);
François Gaffie112b0af2015-11-19 16:13:25 +01008072 return;
8073 }
Kriti Dangef6be8f2020-11-05 11:58:19 +01008074 mReportedFormatsMap[devDesc] = formats;
Mikhail Naganov100f0122018-11-29 11:22:16 -08008075 if (device == AUDIO_DEVICE_OUT_HDMI
8076 || isDeviceOfModule(devDesc, AUDIO_HARDWARE_MODULE_ID_MSD)) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008077 modifySurroundFormats(devDesc, &formats);
Phil Burk00eeb322016-03-31 12:41:00 -07008078 }
jiabin3e277cc2019-09-10 14:27:34 -07008079 addProfilesForFormats(profiles, formats);
François Gaffie112b0af2015-11-19 16:13:25 +01008080 }
François Gaffie112b0af2015-11-19 16:13:25 +01008081
Mikhail Naganovcf84e592017-12-07 11:25:11 -08008082 for (audio_format_t format : profiles.getSupportedFormats()) {
jiabinf26596b2023-04-12 18:56:39 +00008083 std::optional<ChannelMaskSet> channelMasks;
jiabin06e4bab2019-07-29 10:13:34 -07008084 SampleRateSet samplingRates;
François Gaffie112b0af2015-11-19 16:13:25 +01008085 AudioParameter requestedParameters;
Mikhail Naganov388360c2016-10-17 17:09:41 -07008086 requestedParameters.addInt(String8(AudioParameter::keyFormat), format);
François Gaffie112b0af2015-11-19 16:13:25 +01008087
8088 if (profiles.hasDynamicRateFor(format)) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07008089 reply = mpClientInterface->getParameters(
8090 ioHandle,
8091 requestedParameters.toString() + ";" +
8092 AudioParameter::keyStreamSupportedSamplingRates);
Tomasz Wasilczyk8f36f6e2023-08-15 20:59:35 +00008093 ALOGV("%s: supported sampling rates %s", __FUNCTION__, reply.c_str());
Eric Laurent62e4bc52016-02-02 18:37:28 -08008094 AudioParameter repliedParameters(reply);
8095 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07008096 String8(AudioParameter::keyStreamSupportedSamplingRates), reply) == NO_ERROR) {
Tomasz Wasilczyk8f36f6e2023-08-15 20:59:35 +00008097 samplingRates = samplingRatesFromString(reply.c_str());
jiabinf26596b2023-04-12 18:56:39 +00008098 } else {
8099 samplingRates = devDesc->getAudioProfiles().getSampleRatesFor(format);
François Gaffie112b0af2015-11-19 16:13:25 +01008100 }
8101 }
8102 if (profiles.hasDynamicChannelsFor(format)) {
8103 reply = mpClientInterface->getParameters(ioHandle,
8104 requestedParameters.toString() + ";" +
Mikhail Naganov388360c2016-10-17 17:09:41 -07008105 AudioParameter::keyStreamSupportedChannels);
Tomasz Wasilczyk8f36f6e2023-08-15 20:59:35 +00008106 ALOGV("%s: supported channel masks %s", __FUNCTION__, reply.c_str());
Eric Laurent62e4bc52016-02-02 18:37:28 -08008107 AudioParameter repliedParameters(reply);
8108 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07008109 String8(AudioParameter::keyStreamSupportedChannels), reply) == NO_ERROR) {
Tomasz Wasilczyk8f36f6e2023-08-15 20:59:35 +00008110 channelMasks = channelMasksFromString(reply.c_str());
jiabinf26596b2023-04-12 18:56:39 +00008111 } else {
8112 channelMasks = devDesc->getAudioProfiles().getChannelMasksFor(format);
8113 }
8114 if (channelMasks.has_value() && (device == AUDIO_DEVICE_OUT_HDMI
8115 || isDeviceOfModule(devDesc, AUDIO_HARDWARE_MODULE_ID_MSD))) {
8116 modifySurroundChannelMasks(&channelMasks.value());
François Gaffie112b0af2015-11-19 16:13:25 +01008117 }
8118 }
jiabin3e277cc2019-09-10 14:27:34 -07008119 addDynamicAudioProfileAndSort(
jiabinf26596b2023-04-12 18:56:39 +00008120 profiles, new AudioProfile(
8121 format, channelMasks.value_or(ChannelMaskSet()), samplingRates));
François Gaffie112b0af2015-11-19 16:13:25 +01008122 }
8123}
Eric Laurentd60560a2015-04-10 11:31:20 -07008124
Mikhail Naganovdc769682018-05-04 15:34:08 -07008125status_t AudioPolicyManager::installPatch(const char *caller,
8126 audio_patch_handle_t *patchHandle,
8127 AudioIODescriptorInterface *ioDescriptor,
8128 const struct audio_patch *patch,
8129 int delayMs)
8130{
8131 ssize_t index = mAudioPatches.indexOfKey(
8132 patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE ?
8133 *patchHandle : ioDescriptor->getPatchHandle());
8134 sp<AudioPatch> patchDesc;
8135 status_t status = installPatch(
8136 caller, index, patchHandle, patch, delayMs, mUidCached, &patchDesc);
8137 if (status == NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01008138 ioDescriptor->setPatchHandle(patchDesc->getHandle());
Mikhail Naganovdc769682018-05-04 15:34:08 -07008139 }
8140 return status;
8141}
8142
8143status_t AudioPolicyManager::installPatch(const char *caller,
8144 ssize_t index,
8145 audio_patch_handle_t *patchHandle,
8146 const struct audio_patch *patch,
8147 int delayMs,
8148 uid_t uid,
8149 sp<AudioPatch> *patchDescPtr)
8150{
8151 sp<AudioPatch> patchDesc;
8152 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
8153 if (index >= 0) {
8154 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01008155 afPatchHandle = patchDesc->getAfHandle();
Mikhail Naganovdc769682018-05-04 15:34:08 -07008156 }
8157
8158 status_t status = mpClientInterface->createAudioPatch(patch, &afPatchHandle, delayMs);
8159 ALOGV("%s() AF::createAudioPatch returned %d patchHandle %d num_sources %d num_sinks %d",
8160 caller, status, afPatchHandle, patch->num_sources, patch->num_sinks);
8161 if (status == NO_ERROR) {
8162 if (index < 0) {
8163 patchDesc = new AudioPatch(patch, uid);
François Gaffieafd4cea2019-11-18 15:50:22 +01008164 addAudioPatch(patchDesc->getHandle(), patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07008165 } else {
8166 patchDesc->mPatch = *patch;
8167 }
François Gaffieafd4cea2019-11-18 15:50:22 +01008168 patchDesc->setAfHandle(afPatchHandle);
Mikhail Naganovdc769682018-05-04 15:34:08 -07008169 if (patchHandle) {
François Gaffieafd4cea2019-11-18 15:50:22 +01008170 *patchHandle = patchDesc->getHandle();
Mikhail Naganovdc769682018-05-04 15:34:08 -07008171 }
8172 nextAudioPortGeneration();
8173 mpClientInterface->onAudioPatchListUpdate();
8174 }
8175 if (patchDescPtr) *patchDescPtr = patchDesc;
8176 return status;
8177}
8178
jiabinbce0c1d2020-10-05 11:20:18 -07008179bool AudioPolicyManager::areAllActiveTracksRerouted(const sp<SwAudioOutputDescriptor>& output)
8180{
8181 const TrackClientVector activeClients = output->getActiveClients();
8182 if (activeClients.empty()) {
8183 return true;
8184 }
8185 ssize_t index = mAudioPatches.indexOfKey(output->getPatchHandle());
8186 if (index < 0) {
8187 ALOGE("%s, no audio patch found while there are active clients on output %d",
8188 __func__, output->getId());
8189 return false;
8190 }
8191 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
8192 DeviceVector routedDevices;
8193 for (int i = 0; i < patchDesc->mPatch.num_sinks; ++i) {
8194 sp<DeviceDescriptor> device = mAvailableOutputDevices.getDeviceFromId(
8195 patchDesc->mPatch.sinks[i].id);
8196 if (device == nullptr) {
8197 ALOGE("%s, no audio device found with id(%d)",
8198 __func__, patchDesc->mPatch.sinks[i].id);
8199 return false;
8200 }
8201 routedDevices.add(device);
8202 }
8203 for (const auto& client : activeClients) {
jiabin49256852022-03-09 11:21:35 -08008204 if (client->isInvalid()) {
8205 // No need to take care about invalidated clients.
8206 continue;
8207 }
jiabinbce0c1d2020-10-05 11:20:18 -07008208 sp<DeviceDescriptor> preferredDevice =
8209 mAvailableOutputDevices.getDeviceFromId(client->preferredDeviceId());
8210 if (mEngine->getOutputDevicesForAttributes(
8211 client->attributes(), preferredDevice, false) == routedDevices) {
8212 return false;
8213 }
8214 }
8215 return true;
8216}
8217
8218sp<SwAudioOutputDescriptor> AudioPolicyManager::openOutputWithProfileAndDevice(
Eric Laurentb4f42a92022-01-17 17:37:31 +01008219 const sp<IOProfile>& profile, const DeviceVector& devices,
jiabina84c3d32022-12-02 18:59:55 +00008220 const audio_config_base_t *mixerConfig, const audio_config_t *halConfig,
8221 audio_output_flags_t flags)
jiabinbce0c1d2020-10-05 11:20:18 -07008222{
8223 for (const auto& device : devices) {
8224 // TODO: This should be checking if the profile supports the device combo.
8225 if (!profile->supportsDevice(device)) {
jiabina84c3d32022-12-02 18:59:55 +00008226 ALOGE("%s profile(%s) doesn't support device %#x", __func__, profile->getName().c_str(),
8227 device->type());
jiabinbce0c1d2020-10-05 11:20:18 -07008228 return nullptr;
8229 }
8230 }
8231 sp<SwAudioOutputDescriptor> desc = new SwAudioOutputDescriptor(profile, mpClientInterface);
8232 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
jiabina84c3d32022-12-02 18:59:55 +00008233 status_t status = desc->open(halConfig, mixerConfig, devices,
8234 AUDIO_STREAM_DEFAULT, flags, &output);
jiabinbce0c1d2020-10-05 11:20:18 -07008235 if (status != NO_ERROR) {
jiabina84c3d32022-12-02 18:59:55 +00008236 ALOGE("%s failed to open output %d", __func__, status);
jiabinbce0c1d2020-10-05 11:20:18 -07008237 return nullptr;
8238 }
8239
8240 // Here is where the out_set_parameters() for card & device gets called
8241 sp<DeviceDescriptor> device = devices.getDeviceForOpening();
8242 const audio_devices_t deviceType = device->type();
8243 const String8 &address = String8(device->address().c_str());
Tomasz Wasilczykfd9ffd12023-08-14 17:56:22 +00008244 if (!address.empty()) {
jiabinbce0c1d2020-10-05 11:20:18 -07008245 char *param = audio_device_address_to_parameter(deviceType, address.c_str());
8246 mpClientInterface->setParameters(output, String8(param));
8247 free(param);
8248 }
8249 updateAudioProfiles(device, output, profile->getAudioProfiles());
8250 if (!profile->hasValidAudioProfile()) {
8251 ALOGW("%s() missing param", __func__);
8252 desc->close();
8253 return nullptr;
jiabina84c3d32022-12-02 18:59:55 +00008254 } else if (profile->hasDynamicAudioProfile() && halConfig == nullptr) {
8255 // Reopen the output with the best audio profile picked by APM when the profile supports
8256 // dynamic audio profile and the hal config is not specified.
jiabinbce0c1d2020-10-05 11:20:18 -07008257 desc->close();
8258 output = AUDIO_IO_HANDLE_NONE;
8259 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
8260 profile->pickAudioProfile(
8261 config.sample_rate, config.channel_mask, config.format);
8262 config.offload_info.sample_rate = config.sample_rate;
8263 config.offload_info.channel_mask = config.channel_mask;
8264 config.offload_info.format = config.format;
8265
jiabina84c3d32022-12-02 18:59:55 +00008266 status = desc->open(&config, mixerConfig, devices, AUDIO_STREAM_DEFAULT, flags, &output);
jiabinbce0c1d2020-10-05 11:20:18 -07008267 if (status != NO_ERROR) {
8268 return nullptr;
8269 }
8270 }
8271
8272 addOutput(output, desc);
Eric Laurentb4f42a92022-01-17 17:37:31 +01008273
baek.kim -61c20122022-07-27 10:05:32 +00008274 sp<DeviceDescriptor> speaker = mAvailableOutputDevices.getDevice(
8275 AUDIO_DEVICE_OUT_SPEAKER, String8(""), AUDIO_FORMAT_DEFAULT);
8276
jiabinbce0c1d2020-10-05 11:20:18 -07008277 if (audio_is_remote_submix_device(deviceType) && address != "0") {
8278 sp<AudioPolicyMix> policyMix;
8279 if (mPolicyMixes.getAudioPolicyMix(deviceType, address, policyMix) == NO_ERROR) {
8280 policyMix->setOutput(desc);
8281 desc->mPolicyMix = policyMix;
8282 } else {
8283 ALOGW("checkOutputsForDevice() cannot find policy for address %s",
Tomasz Wasilczyk8f36f6e2023-08-15 20:59:35 +00008284 address.c_str());
jiabinbce0c1d2020-10-05 11:20:18 -07008285 }
8286
baek.kim -61c20122022-07-27 10:05:32 +00008287 } else if (hasPrimaryOutput() && speaker != nullptr
8288 && mPrimaryOutput->supportsDevice(speaker) && !desc->supportsDevice(speaker)
Eric Laurentb4f42a92022-01-17 17:37:31 +01008289 && ((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0)) {
8290 // no duplicated output for:
8291 // - direct outputs
8292 // - outputs used by dynamic policy mixes
baek.kim -61c20122022-07-27 10:05:32 +00008293 // - outputs that supports SPEAKER while the primary output does not.
jiabinbce0c1d2020-10-05 11:20:18 -07008294 audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE;
8295
8296 //TODO: configure audio effect output stage here
8297
8298 // open a duplicating output thread for the new output and the primary output
8299 sp<SwAudioOutputDescriptor> dupOutputDesc =
8300 new SwAudioOutputDescriptor(nullptr, mpClientInterface);
8301 status = dupOutputDesc->openDuplicating(mPrimaryOutput, desc, &duplicatedOutput);
8302 if (status == NO_ERROR) {
8303 // add duplicated output descriptor
8304 addOutput(duplicatedOutput, dupOutputDesc);
8305 } else {
8306 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
8307 mPrimaryOutput->mIoHandle, output);
8308 desc->close();
8309 removeOutput(output);
8310 nextAudioPortGeneration();
8311 return nullptr;
8312 }
8313 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02008314 if (mPrimaryOutput == nullptr && profile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
8315 ALOGV("%s(): re-assigning mPrimaryOutput", __func__);
8316 mPrimaryOutput = desc;
8317 }
jiabinbce0c1d2020-10-05 11:20:18 -07008318 return desc;
8319}
8320
jiabinf1c73972022-04-14 16:28:52 -07008321status_t AudioPolicyManager::getDevicesForAttributes(
8322 const audio_attributes_t &attr, DeviceVector &devices, bool forVolume) {
8323 // Devices are determined in the following precedence:
8324 //
8325 // 1) Devices associated with a dynamic policy matching the attributes. This is often
8326 // a remote submix from MIX_ROUTE_FLAG_LOOP_BACK.
8327 //
8328 // If no such dynamic policy then
8329 // 2) Devices containing an active client using setPreferredDevice
8330 // with same strategy as the attributes.
8331 // (from the default Engine::getOutputDevicesForAttributes() implementation).
8332 //
8333 // If no corresponding active client with setPreferredDevice then
8334 // 3) Devices associated with the strategy determined by the attributes
8335 // (from the default Engine::getOutputDevicesForAttributes() implementation).
8336 //
8337 // See related getOutputForAttrInt().
8338
8339 // check dynamic policies but only for primary descriptors (secondary not used for audible
8340 // audio routing, only used for duplication for playback capture)
8341 sp<AudioPolicyMix> policyMix;
Oscar Azucena873d10f2023-01-12 18:34:42 -08008342 bool unneededUsePrimaryOutputFromPolicyMixes = false;
jiabinf1c73972022-04-14 16:28:52 -07008343 status_t status = mPolicyMixes.getOutputForAttr(attr, AUDIO_CONFIG_BASE_INITIALIZER,
Oscar Azucena873d10f2023-01-12 18:34:42 -08008344 0 /*uid unknown here*/, AUDIO_SESSION_NONE, AUDIO_OUTPUT_FLAG_NONE,
8345 mAvailableOutputDevices, nullptr /* requestedDevice */, policyMix,
8346 nullptr /* secondaryMixes */, unneededUsePrimaryOutputFromPolicyMixes);
jiabinf1c73972022-04-14 16:28:52 -07008347 if (status != OK) {
8348 return status;
8349 }
8350
8351 if (policyMix != nullptr && policyMix->getOutput() != nullptr &&
8352 // For volume control, skip LOOPBACK mixes which use AUDIO_DEVICE_OUT_REMOTE_SUBMIX
8353 // as they are unaffected by device/stream volume
8354 // (per SwAudioOutputDescriptor::isFixedVolume()).
8355 (!forVolume || policyMix->mDeviceType != AUDIO_DEVICE_OUT_REMOTE_SUBMIX)
8356 ) {
8357 sp<DeviceDescriptor> deviceDesc = mAvailableOutputDevices.getDevice(
8358 policyMix->mDeviceType, policyMix->mDeviceAddress, AUDIO_FORMAT_DEFAULT);
8359 devices.add(deviceDesc);
8360 } else {
8361 // The default Engine::getOutputDevicesForAttributes() uses findPreferredDevice()
8362 // which selects setPreferredDevice if active. This means forVolume call
8363 // will take an active setPreferredDevice, if such exists.
8364
8365 devices = mEngine->getOutputDevicesForAttributes(
8366 attr, nullptr /* preferredDevice */, false /* fromCache */);
8367 }
8368
8369 if (forVolume) {
8370 // We alias the device AUDIO_DEVICE_OUT_SPEAKER_SAFE to AUDIO_DEVICE_OUT_SPEAKER
8371 // for single volume control in AudioService (such relationship should exist if
8372 // SPEAKER_SAFE is present).
8373 //
8374 // (This is unrelated to a different device grouping as Volume::getDeviceCategory)
8375 DeviceVector speakerSafeDevices =
8376 devices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER_SAFE);
8377 if (!speakerSafeDevices.isEmpty()) {
8378 devices.merge(mAvailableOutputDevices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER));
8379 devices.remove(speakerSafeDevices);
8380 }
8381 }
8382
8383 return NO_ERROR;
8384}
8385
8386status_t AudioPolicyManager::getProfilesForDevices(const DeviceVector& devices,
8387 AudioProfileVector& audioProfiles,
8388 uint32_t flags,
8389 bool isInput) {
8390 for (const auto& hwModule : mHwModules) {
8391 // the MSD module checks for different conditions
8392 if (strcmp(hwModule->getName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0) {
8393 continue;
8394 }
8395 IOProfileCollection ioProfiles = isInput ? hwModule->getInputProfiles()
8396 : hwModule->getOutputProfiles();
8397 for (const auto& profile : ioProfiles) {
8398 if (!profile->areAllDevicesSupported(devices) ||
8399 !profile->isCompatibleProfileForFlags(
8400 flags, false /*exactMatchRequiredForInputFlags*/)) {
8401 continue;
8402 }
8403 audioProfiles.addAllValidProfiles(profile->asAudioPort()->getAudioProfiles());
8404 }
8405 }
8406
8407 if (!isInput) {
8408 // add the direct profiles from MSD if present and has audio patches to all the output(s)
8409 const auto &msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
8410 if (msdModule != nullptr) {
8411 if (msdHasPatchesToAllDevices(devices.toTypeAddrVector())) {
8412 ALOGV("%s: MSD audio patches set to all output devices.", __func__);
8413 for (const auto &profile: msdModule->getOutputProfiles()) {
8414 if (!profile->asAudioPort()->isDirectOutput()) {
8415 continue;
8416 }
8417 audioProfiles.addAllValidProfiles(profile->asAudioPort()->getAudioProfiles());
8418 }
8419 } else {
8420 ALOGV("%s: MSD audio patches NOT set to all output devices.", __func__);
8421 }
8422 }
8423 }
8424
8425 return NO_ERROR;
8426}
8427
jiabin3ff8d7d2022-12-13 06:27:44 +00008428sp<SwAudioOutputDescriptor> AudioPolicyManager::reopenOutput(sp<SwAudioOutputDescriptor> outputDesc,
8429 const audio_config_t *config,
8430 audio_output_flags_t flags,
8431 const char* caller) {
jiabina84c3d32022-12-02 18:59:55 +00008432 closeOutput(outputDesc->mIoHandle);
8433 sp<SwAudioOutputDescriptor> preferredOutput = openOutputWithProfileAndDevice(
8434 outputDesc->mProfile, outputDesc->devices(), nullptr /*mixerConfig*/, config, flags);
8435 if (preferredOutput == nullptr) {
8436 ALOGE("%s failed to reopen output device=%d, caller=%s",
8437 __func__, outputDesc->devices()[0]->getId(), caller);
jiabina84c3d32022-12-02 18:59:55 +00008438 }
jiabin3ff8d7d2022-12-13 06:27:44 +00008439 return preferredOutput;
8440}
8441
8442void AudioPolicyManager::reopenOutputsWithDevices(
8443 const std::map<audio_io_handle_t, DeviceVector> &outputsToReopen) {
8444 for (const auto& [output, devices] : outputsToReopen) {
8445 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
8446 closeOutput(output);
8447 openOutputWithProfileAndDevice(desc->mProfile, devices);
8448 }
jiabina84c3d32022-12-02 18:59:55 +00008449}
8450
jiabinc44b3462022-12-08 12:52:31 -08008451PortHandleVector AudioPolicyManager::getClientsForStream(
8452 audio_stream_type_t streamType) const {
8453 PortHandleVector clients;
8454 for (size_t i = 0; i < mOutputs.size(); ++i) {
8455 PortHandleVector clientsForStream = mOutputs.valueAt(i)->getClientsForStream(streamType);
8456 clients.insert(clients.end(), clientsForStream.begin(), clientsForStream.end());
8457 }
8458 return clients;
8459}
8460
8461void AudioPolicyManager::invalidateStreams(StreamTypeVector streams) const {
8462 PortHandleVector clients;
8463 for (auto stream : streams) {
8464 PortHandleVector clientsForStream = getClientsForStream(stream);
8465 clients.insert(clients.end(), clientsForStream.begin(), clientsForStream.end());
8466 }
8467 mpClientInterface->invalidateTracks(clients);
8468}
8469
Mikhail Naganov1b2a7942017-12-08 10:18:09 -08008470} // namespace android