blob: d4176c10254215ca08afd47477977091cdc820b5 [file] [log] [blame]
Eric Laurente552edb2014-03-10 17:42:56 -07001/*
2 * Copyright (C) 2009 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -070017#define LOG_TAG "APM_AudioPolicyManager"
Tomoharu Kasahara71c90912018-10-31 09:10:12 +090018
19// Need to keep the log statements even in production builds
20// to enable VERBOSE logging dynamically.
21// You can enable VERBOSE logging as follows:
22// adb shell setprop log.tag.APM_AudioPolicyManager V
23#define LOG_NDEBUG 0
Eric Laurente552edb2014-03-10 17:42:56 -070024
25//#define VERY_VERBOSE_LOGGING
26#ifdef VERY_VERBOSE_LOGGING
27#define ALOGVV ALOGV
28#else
29#define ALOGVV(a...) do { } while(0)
30#endif
31
Eric Laurent16c66dd2019-05-01 17:54:10 -070032#include <algorithm>
Eric Laurentd4692962014-05-05 18:13:44 -070033#include <inttypes.h>
jiabin10a03f12021-05-07 23:46:28 +000034#include <map>
Eric Laurente552edb2014-03-10 17:42:56 -070035#include <math.h>
Kevin Rocard153f92d2018-12-18 18:33:28 -080036#include <set>
Atneya Nair0f0a8032022-12-12 16:20:12 -080037#include <type_traits>
Mikhail Naganovd5e18052018-11-30 14:55:45 -080038#include <unordered_set>
Mikhail Naganov15be9d22017-11-08 14:18:13 +110039#include <vector>
Mikhail Naganov946c0032020-10-21 13:04:58 -070040
41#include <Serializer.h>
Nathalie Le Clair88fa2752021-11-23 13:03:41 +010042#include <android/media/audio/common/AudioPort.h>
Glenn Kasten76a13442020-07-01 12:10:59 -070043#include <cutils/bitops.h>
Eric Laurente552edb2014-03-10 17:42:56 -070044#include <cutils/properties.h>
Eric Laurent3b73df72014-03-11 09:06:29 -070045#include <media/AudioParameter.h>
Mikhail Naganov946c0032020-10-21 13:04:58 -070046#include <policy.h>
Andy Hung4ef19fa2018-05-15 19:35:29 -070047#include <private/android_filesystem_config.h>
Mikhail Naganovcbc8f612016-10-11 18:05:13 -070048#include <system/audio.h>
Mikhail Naganov27cf37c2020-04-14 14:47:01 -070049#include <system/audio_config.h>
jiabinebb6af42020-06-09 17:31:17 -070050#include <system/audio_effects/effect_hapticgenerator.h>
Mikhail Naganov946c0032020-10-21 13:04:58 -070051#include <utils/Log.h>
52
Eric Laurentd4692962014-05-05 18:13:44 -070053#include "AudioPolicyManager.h"
François Gaffiea8ecc2c2015-11-09 16:10:40 +010054#include "TypeConverter.h"
Eric Laurente552edb2014-03-10 17:42:56 -070055
Eric Laurent3b73df72014-03-11 09:06:29 -070056namespace android {
Eric Laurente552edb2014-03-10 17:42:56 -070057
Nathalie Le Clair88fa2752021-11-23 13:03:41 +010058using android::media::audio::common::AudioDevice;
59using android::media::audio::common::AudioDeviceAddress;
60using android::media::audio::common::AudioPortDeviceExt;
61using android::media::audio::common::AudioPortExt;
Svet Ganov3e5f14f2021-05-13 22:51:08 +000062using content::AttributionSourceState;
Philip P. Moltmannbda45752020-07-17 16:41:18 -070063
Eric Laurentdc462862016-07-19 12:29:53 -070064//FIXME: workaround for truncated touch sounds
65// to be removed when the problem is handled by system UI
66#define TOUCH_SOUND_FIXED_DELAY_MS 100
Jean-Michel Trivi719a9872017-08-05 13:51:35 -070067
68// Largest difference in dB on earpiece in call between the voice volume and another
69// media / notification / system volume.
70constexpr float IN_CALL_EARPIECE_HEADROOM_DB = 3.f;
71
jiabin06e4bab2019-07-29 10:13:34 -070072template <typename T>
73bool operator== (const SortedVector<T> &left, const SortedVector<T> &right)
74{
75 if (left.size() != right.size()) {
76 return false;
77 }
78 for (size_t index = 0; index < right.size(); index++) {
79 if (left[index] != right[index]) {
80 return false;
81 }
82 }
83 return true;
84}
85
86template <typename T>
87bool operator!= (const SortedVector<T> &left, const SortedVector<T> &right)
88{
89 return !(left == right);
90}
91
Eric Laurente552edb2014-03-10 17:42:56 -070092// ----------------------------------------------------------------------------
93// AudioPolicyInterface implementation
94// ----------------------------------------------------------------------------
95
Nathalie Le Clair88fa2752021-11-23 13:03:41 +010096status_t AudioPolicyManager::setDeviceConnectionState(audio_policy_dev_state_t state,
97 const android::media::audio::common::AudioPort& port, audio_format_t encodedFormat) {
98 status_t status = setDeviceConnectionStateInt(state, port, encodedFormat);
jiabina7b43792018-02-15 16:04:46 -080099 nextAudioPortGeneration();
100 return status;
Eric Laurentc73ca6e2014-12-12 14:34:22 -0800101}
102
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100103status_t AudioPolicyManager::setDeviceConnectionState(audio_devices_t device,
104 audio_policy_dev_state_t state,
105 const char* device_address,
106 const char* device_name,
107 audio_format_t encodedFormat) {
Atneya Nair638a6e42022-12-18 16:45:15 -0800108 media::AudioPortFw aidlPort;
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100109 if (status_t status = deviceToAudioPort(device, device_address, device_name, &aidlPort);
110 status == OK) {
111 return setDeviceConnectionState(state, aidlPort.hal, encodedFormat);
112 } else {
113 ALOGE("Failed to convert to AudioPort Parcelable: %s", statusToString(status).c_str());
114 return status;
115 }
116}
117
François Gaffie11d30102018-11-02 16:09:09 +0100118void AudioPolicyManager::broadcastDeviceConnectionState(const sp<DeviceDescriptor> &device,
jiabinc0048632023-04-27 22:04:31 +0000119 media::DeviceConnectedState state)
François Gaffie44481e72016-04-20 07:49:57 +0200120{
Mikhail Naganov516d3982022-02-01 23:53:59 +0000121 audio_port_v7 devicePort;
122 device->toAudioPort(&devicePort);
jiabinc0048632023-04-27 22:04:31 +0000123 if (status_t status = mpClientInterface->setDeviceConnectedState(&devicePort, state);
Mikhail Naganov516d3982022-02-01 23:53:59 +0000124 status != OK) {
jiabinc0048632023-04-27 22:04:31 +0000125 ALOGE("Error %d while setting connected state for device %s", state,
Mikhail Naganov516d3982022-02-01 23:53:59 +0000126 device->getDeviceTypeAddr().toString(false).c_str());
127 }
François Gaffie44481e72016-04-20 07:49:57 +0200128}
129
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100130status_t AudioPolicyManager::setDeviceConnectionStateInt(
131 audio_policy_dev_state_t state, const android::media::audio::common::AudioPort& port,
132 audio_format_t encodedFormat) {
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100133 if (port.ext.getTag() != AudioPortExt::device) {
134 return BAD_VALUE;
135 }
136 audio_devices_t device_type;
137 std::string device_address;
138 if (status_t status = aidl2legacy_AudioDevice_audio_device(
139 port.ext.get<AudioPortExt::device>().device, &device_type, &device_address);
140 status != OK) {
141 return status;
142 };
143 const char* device_name = port.name.c_str();
144 // connect/disconnect only 1 device at a time
145 if (!audio_is_output_device(device_type) && !audio_is_input_device(device_type))
146 return BAD_VALUE;
147
148 sp<DeviceDescriptor> device = mHwModules.getDeviceDescriptor(
149 device_type, device_address.c_str(), device_name, encodedFormat,
150 state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
Mikhail Naganovddc5f312022-06-11 00:47:52 +0000151 if (device == nullptr) {
152 return INVALID_OPERATION;
153 }
154 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
155 device->setExtraAudioDescriptors(port.extraAudioDescriptors);
156 }
157 return setDeviceConnectionStateInt(device, state);
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100158}
159
François Gaffie11d30102018-11-02 16:09:09 +0100160status_t AudioPolicyManager::setDeviceConnectionStateInt(audio_devices_t deviceType,
Eric Laurenta1d525f2015-01-29 13:36:45 -0800161 audio_policy_dev_state_t state,
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100162 const char* device_address,
163 const char* device_name,
164 audio_format_t encodedFormat) {
Atneya Nair638a6e42022-12-18 16:45:15 -0800165 media::AudioPortFw aidlPort;
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100166 if (status_t status = deviceToAudioPort(deviceType, device_address, device_name, &aidlPort);
167 status == OK) {
168 return setDeviceConnectionStateInt(state, aidlPort.hal, encodedFormat);
169 } else {
170 ALOGE("Failed to convert to AudioPort Parcelable: %s", statusToString(status).c_str());
171 return status;
172 }
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700173}
Paul McLeane743a472015-01-28 11:07:31 -0800174
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700175status_t AudioPolicyManager::setDeviceConnectionStateInt(const sp<DeviceDescriptor> &device,
176 audio_policy_dev_state_t state)
177{
Eric Laurente552edb2014-03-10 17:42:56 -0700178 // handle output devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700179 if (audio_is_output_device(device->type())) {
Eric Laurentd4692962014-05-05 18:13:44 -0700180 SortedVector <audio_io_handle_t> outputs;
181
François Gaffie11d30102018-11-02 16:09:09 +0100182 ssize_t index = mAvailableOutputDevices.indexOf(device);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700183
Eric Laurente552edb2014-03-10 17:42:56 -0700184 // save a copy of the opened output descriptors before any output is opened or closed
185 // by checkOutputsForDevice(). This will be needed by checkOutputForAllStrategies()
186 mPreviousOutputs = mOutputs;
Eric Laurent96d1dda2022-03-14 17:14:19 +0100187
188 bool wasLeUnicastActive = isLeUnicastActive();
189
Eric Laurente552edb2014-03-10 17:42:56 -0700190 switch (state)
191 {
192 // handle output device connection
Eric Laurent3ae5f312015-02-03 17:12:08 -0800193 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700194 if (index >= 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100195 ALOGW("%s() device already connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700196 return INVALID_OPERATION;
197 }
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800198 ALOGV("%s() connecting device %s format %x",
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700199 __func__, device->toString().c_str(), device->getEncodedFormat());
Eric Laurente552edb2014-03-10 17:42:56 -0700200
Eric Laurente552edb2014-03-10 17:42:56 -0700201 // register new device as available
Francois Gaffie993f3902019-04-10 15:39:27 +0200202 if (mAvailableOutputDevices.add(device) < 0) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700203 return NO_MEMORY;
Eric Laurente552edb2014-03-10 17:42:56 -0700204 }
205
François Gaffie44481e72016-04-20 07:49:57 +0200206 // Before checking outputs, broadcast connect event to allow HAL to retrieve dynamic
207 // parameters on newly connected devices (instead of opening the outputs...)
jiabinc0048632023-04-27 22:04:31 +0000208 broadcastDeviceConnectionState(device, media::DeviceConnectedState::CONNECTED);
François Gaffie44481e72016-04-20 07:49:57 +0200209
François Gaffie11d30102018-11-02 16:09:09 +0100210 if (checkOutputsForDevice(device, state, outputs) != NO_ERROR) {
211 mAvailableOutputDevices.remove(device);
François Gaffie44481e72016-04-20 07:49:57 +0200212
Francois Gaffie716e1432019-01-14 16:58:59 +0100213 mHwModules.cleanUpForDevice(device);
214
jiabinc0048632023-04-27 22:04:31 +0000215 broadcastDeviceConnectionState(device, media::DeviceConnectedState::DISCONNECTED);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700216 return INVALID_OPERATION;
217 }
François Gaffie2110e042015-03-24 08:41:51 +0100218
jiabin1c4794b2020-05-05 10:08:05 -0700219 // Populate encapsulation information when a output device is connected.
220 device->setEncapsulationInfoFromHal(mpClientInterface);
221
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700222 // outputs should never be empty here
223 ALOG_ASSERT(outputs.size() != 0, "setDeviceConnectionState():"
224 "checkOutputsForDevice() returned no outputs but status OK");
François Gaffie11d30102018-11-02 16:09:09 +0100225 ALOGV("%s() checkOutputsForDevice() returned %zu outputs", __func__, outputs.size());
Eric Laurent3ae5f312015-02-03 17:12:08 -0800226
Eric Laurent3ae5f312015-02-03 17:12:08 -0800227 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700228 // handle output device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700229 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700230 if (index < 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100231 ALOGW("%s() device not connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700232 return INVALID_OPERATION;
233 }
234
François Gaffie11d30102018-11-02 16:09:09 +0100235 ALOGV("%s() disconnecting output device %s", __func__, device->toString().c_str());
Paul McLean5c477aa2014-08-20 16:47:57 -0700236
jiabinc0048632023-04-27 22:04:31 +0000237 // Notify the HAL to prepare to disconnect device
238 broadcastDeviceConnectionState(
239 device, media::DeviceConnectedState::PREPARE_TO_DISCONNECT);
Paul McLean5c477aa2014-08-20 16:47:57 -0700240
Eric Laurente552edb2014-03-10 17:42:56 -0700241 // remove device from available output devices
François Gaffie11d30102018-11-02 16:09:09 +0100242 mAvailableOutputDevices.remove(device);
Eric Laurente552edb2014-03-10 17:42:56 -0700243
Francois Gaffieba2cf0f2018-12-12 16:40:25 +0100244 mOutputs.clearSessionRoutesForDevice(device);
245
François Gaffie11d30102018-11-02 16:09:09 +0100246 checkOutputsForDevice(device, state, outputs);
François Gaffie2110e042015-03-24 08:41:51 +0100247
jiabinc0048632023-04-27 22:04:31 +0000248 // Send Disconnect to HALs
249 broadcastDeviceConnectionState(device, media::DeviceConnectedState::DISCONNECTED);
250
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800251 // Reset active device codec
252 device->setEncodedFormat(AUDIO_FORMAT_DEFAULT);
253
Kriti Dangef6be8f2020-11-05 11:58:19 +0100254 // remove device from mReportedFormatsMap cache
255 mReportedFormatsMap.erase(device);
256
jiabina84c3d32022-12-02 18:59:55 +0000257 // remove preferred mixer configurations
258 mPreferredMixerAttrInfos.erase(device->getId());
259
Eric Laurente552edb2014-03-10 17:42:56 -0700260 } break;
261
262 default:
François Gaffie11d30102018-11-02 16:09:09 +0100263 ALOGE("%s() invalid state: %x", __func__, state);
Eric Laurente552edb2014-03-10 17:42:56 -0700264 return BAD_VALUE;
265 }
266
Eric Laurent736a1022019-03-27 18:28:46 -0700267 // Propagate device availability to Engine
268 setEngineDeviceConnectionState(device, state);
269
Eric Laurentae970022019-01-29 14:25:04 -0800270 // No need to evaluate playback routing when connecting a remote submix
271 // output device used by a dynamic policy of type recorder as no
272 // playback use case is affected.
273 bool doCheckForDeviceAndOutputChanges = true;
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700274 if (device->type() == AUDIO_DEVICE_OUT_REMOTE_SUBMIX && device->address() != "0") {
Eric Laurentae970022019-01-29 14:25:04 -0800275 for (audio_io_handle_t output : outputs) {
276 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
Mikhail Naganovbfac5832019-03-05 16:55:28 -0800277 sp<AudioPolicyMix> policyMix = desc->mPolicyMix.promote();
278 if (policyMix != nullptr
279 && policyMix->mMixType == MIX_TYPE_RECORDERS
Tomasz Wasilczyk5b054372023-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...)
jiabinc0048632023-04-27 22:04:31 +0000390 broadcastDeviceConnectionState(device, media::DeviceConnectedState::CONNECTED);
François Gaffie44481e72016-04-20 07:49:57 +0200391
Eric Laurent0dd51852019-04-19 18:18:58 -0700392 if (checkInputsForDevice(device, state) != NO_ERROR) {
393 mAvailableInputDevices.remove(device);
394
jiabinc0048632023-04-27 22:04:31 +0000395 broadcastDeviceConnectionState(device, media::DeviceConnectedState::DISCONNECTED);
Francois Gaffie716e1432019-01-14 16:58:59 +0100396
397 mHwModules.cleanUpForDevice(device);
398
Eric Laurentd4692962014-05-05 18:13:44 -0700399 return INVALID_OPERATION;
400 }
401
Eric Laurentd4692962014-05-05 18:13:44 -0700402 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700403
404 // handle input device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700405 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700406 if (index < 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100407 ALOGW("%s() device not connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700408 return INVALID_OPERATION;
409 }
Paul McLean5c477aa2014-08-20 16:47:57 -0700410
François Gaffie11d30102018-11-02 16:09:09 +0100411 ALOGV("%s() disconnecting input device %s", __func__, device->toString().c_str());
Paul McLean5c477aa2014-08-20 16:47:57 -0700412
jiabinc0048632023-04-27 22:04:31 +0000413 // Notify the HAL to prepare to disconnect device
414 broadcastDeviceConnectionState(
415 device, media::DeviceConnectedState::PREPARE_TO_DISCONNECT);
Paul McLean5c477aa2014-08-20 16:47:57 -0700416
François Gaffie11d30102018-11-02 16:09:09 +0100417 mAvailableInputDevices.remove(device);
Eric Laurent0dd51852019-04-19 18:18:58 -0700418
419 checkInputsForDevice(device, state);
Kriti Dangef6be8f2020-11-05 11:58:19 +0100420
jiabinc0048632023-04-27 22:04:31 +0000421 // Set Disconnect to HALs
422 broadcastDeviceConnectionState(device, media::DeviceConnectedState::DISCONNECTED);
423
Kriti Dangef6be8f2020-11-05 11:58:19 +0100424 // remove device from mReportedFormatsMap cache
425 mReportedFormatsMap.erase(device);
Eric Laurentd4692962014-05-05 18:13:44 -0700426 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700427
428 default:
François Gaffie11d30102018-11-02 16:09:09 +0100429 ALOGE("%s() invalid state: %x", __func__, state);
Eric Laurente552edb2014-03-10 17:42:56 -0700430 return BAD_VALUE;
431 }
432
Eric Laurent736a1022019-03-27 18:28:46 -0700433 // Propagate device availability to Engine
434 setEngineDeviceConnectionState(device, state);
435
Eric Laurent0dd51852019-04-19 18:18:58 -0700436 checkCloseInputs();
Eric Laurent5f5fca52016-08-04 11:48:57 -0700437 // As the input device list can impact the output device selection, update
438 // getDeviceForStrategy() cache
439 updateDevicesAndOutputs();
Eric Laurente552edb2014-03-10 17:42:56 -0700440
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100441 (void)updateCallRouting(false /*fromCache*/);
Francois Gaffiea0e5c992020-09-29 16:05:07 +0200442 // Reconnect Audio Source
443 for (const auto &strategy : mEngine->getOrderedProductStrategies()) {
444 auto attributes = mEngine->getAllAttributesForProductStrategy(strategy).front();
445 checkAudioSourceForAttributes(attributes);
446 }
Eric Laurentd60560a2015-04-10 11:31:20 -0700447 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
François Gaffie11d30102018-11-02 16:09:09 +0100448 cleanUpForDevice(device);
Eric Laurentd60560a2015-04-10 11:31:20 -0700449 }
450
Eric Laurentb52c1522014-05-20 11:27:36 -0700451 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -0700452 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700453 } // end if is input device
Eric Laurente552edb2014-03-10 17:42:56 -0700454
François Gaffie11d30102018-11-02 16:09:09 +0100455 ALOGW("%s() invalid device: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700456 return BAD_VALUE;
457}
458
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100459status_t AudioPolicyManager::deviceToAudioPort(audio_devices_t device, const char* device_address,
460 const char* device_name,
Atneya Nair638a6e42022-12-18 16:45:15 -0800461 media::AudioPortFw* aidlPort) {
Andy 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 Huang36028df2022-07-06 00:14:12 +0800613 audioDeviceSet = getAudioDeviceOutLeAudioUnicastSet();
614 break;
615 case AUDIO_DEVICE_OUT_BLE_BROADCAST:
616 audioDeviceSet = getAudioDeviceOutLeAudioBroadcastSet();
Pattydd807582021-11-04 21:01:03 +0800617 break;
618 default:
619 ALOGE("%s() device type 0x%08x not supported", __func__, device);
620 return BAD_VALUE;
621 }
622
jiabin9a3361e2019-10-01 09:38:30 -0700623 DeviceVector declaredDevices = primaryModule->getDeclaredDevices().getDevicesFromTypes(
Pattydd807582021-11-04 21:01:03 +0800624 audioDeviceSet);
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800625 for (const auto& device : declaredDevices) {
626 formatSet.insert(device->encodedFormats().begin(), device->encodedFormats().end());
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800627 }
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800628 formats->assign(formatSet.begin(), formatSet.end());
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800629 return status;
630}
631
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100632DeviceVector AudioPolicyManager::selectBestRxSinkDevicesForCall(bool fromCache)
633{
634 DeviceVector rxSinkdevices{};
635 rxSinkdevices = mEngine->getOutputDevicesForAttributes(
636 attributes_initializer(AUDIO_USAGE_VOICE_COMMUNICATION), nullptr, fromCache);
637 if (!rxSinkdevices.isEmpty() && mAvailableOutputDevices.contains(rxSinkdevices.itemAt(0))) {
638 auto rxSinkDevice = rxSinkdevices.itemAt(0);
639 auto telephonyRxModule = mHwModules.getModuleForDeviceType(
640 AUDIO_DEVICE_IN_TELEPHONY_RX, AUDIO_FORMAT_DEFAULT);
641 // retrieve Rx Source device descriptor
642 sp<DeviceDescriptor> rxSourceDevice = mAvailableInputDevices.getDevice(
643 AUDIO_DEVICE_IN_TELEPHONY_RX, String8(), AUDIO_FORMAT_DEFAULT);
644
645 // RX Telephony and Rx sink devices are declared by Primary Audio HAL
646 if (isPrimaryModule(telephonyRxModule) && (telephonyRxModule->getHalVersionMajor() >= 3) &&
647 telephonyRxModule->supportsPatch(rxSourceDevice, rxSinkDevice)) {
648 ALOGW("%s() device %s using HW Bridge", __func__, rxSinkDevice->toString().c_str());
649 return DeviceVector(rxSinkDevice);
650 }
651 }
652 // Note that despite the fact that getNewOutputDevices() is called on the primary output,
653 // the device returned is not necessarily reachable via this output
654 // (filter later by setOutputDevices())
655 return getNewOutputDevices(mPrimaryOutput, fromCache);
656}
657
658status_t AudioPolicyManager::updateCallRouting(bool fromCache, uint32_t delayMs, uint32_t *waitMs)
659{
660 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL && hasPrimaryOutput()) {
661 DeviceVector rxDevices = selectBestRxSinkDevicesForCall(fromCache);
662 return updateCallRoutingInternal(rxDevices, delayMs, waitMs);
663 }
664 return INVALID_OPERATION;
665}
666
667status_t AudioPolicyManager::updateCallRoutingInternal(
668 const DeviceVector &rxDevices, uint32_t delayMs, uint32_t *waitMs)
Eric Laurentc2730ba2014-07-20 15:47:07 -0700669{
670 bool createTxPatch = false;
François Gaffie9eb18552018-11-05 10:33:26 +0100671 bool createRxPatch = false;
Eric Laurentdc462862016-07-19 12:29:53 -0700672 uint32_t muteWaitMs = 0;
jiabin9a3361e2019-10-01 09:38:30 -0700673 if(!hasPrimaryOutput() ||
674 mPrimaryOutput->devices().onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_STUB)) {
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100675 return INVALID_OPERATION;
Eric Laurent87ffa392015-05-22 10:32:38 -0700676 }
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100677 ALOG_ASSERT(!rxDevices.isEmpty(), "%s() no selected output device", __func__);
François Gaffie11d30102018-11-02 16:09:09 +0100678
Francois Gaffie716e1432019-01-14 16:58:59 +0100679 audio_attributes_t attr = { .source = AUDIO_SOURCE_VOICE_COMMUNICATION };
François Gaffiec005e562018-11-06 15:04:49 +0100680 auto txSourceDevice = mEngine->getInputDeviceForAttributes(attr);
Eric Laurentcedd5b52023-03-22 00:03:31 +0000681 if (txSourceDevice == nullptr) {
682 ALOGE("%s() selected input device not available", __func__);
683 return INVALID_OPERATION;
684 }
François Gaffiec005e562018-11-06 15:04:49 +0100685
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100686 ALOGV("%s device rxDevice %s txDevice %s", __func__,
François Gaffie9eb18552018-11-05 10:33:26 +0100687 rxDevices.itemAt(0)->toString().c_str(), txSourceDevice->toString().c_str());
Eric Laurentc2730ba2014-07-20 15:47:07 -0700688
Francois Gaffie601801d2021-06-22 13:27:39 +0200689 disconnectTelephonyAudioSource(mCallRxSourceClient);
690 disconnectTelephonyAudioSource(mCallTxSourceClient);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700691
François Gaffie9eb18552018-11-05 10:33:26 +0100692 auto telephonyRxModule =
jiabin9a3361e2019-10-01 09:38:30 -0700693 mHwModules.getModuleForDeviceType(AUDIO_DEVICE_IN_TELEPHONY_RX, AUDIO_FORMAT_DEFAULT);
François Gaffie9eb18552018-11-05 10:33:26 +0100694 auto telephonyTxModule =
jiabin9a3361e2019-10-01 09:38:30 -0700695 mHwModules.getModuleForDeviceType(AUDIO_DEVICE_OUT_TELEPHONY_TX, AUDIO_FORMAT_DEFAULT);
François Gaffie9eb18552018-11-05 10:33:26 +0100696 // retrieve Rx Source and Tx Sink device descriptors
697 sp<DeviceDescriptor> rxSourceDevice =
698 mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_TELEPHONY_RX,
699 String8(),
700 AUDIO_FORMAT_DEFAULT);
701 sp<DeviceDescriptor> txSinkDevice =
702 mAvailableOutputDevices.getDevice(AUDIO_DEVICE_OUT_TELEPHONY_TX,
703 String8(),
704 AUDIO_FORMAT_DEFAULT);
705
706 // RX and TX Telephony device are declared by Primary Audio HAL
707 if (isPrimaryModule(telephonyRxModule) && isPrimaryModule(telephonyTxModule) &&
708 (telephonyRxModule->getHalVersionMajor() >= 3)) {
709 if (rxSourceDevice == 0 || txSinkDevice == 0) {
710 // RX / TX Telephony device(s) is(are) not currently available
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100711 ALOGE("%s() no telephony Tx and/or RX device", __func__);
712 return INVALID_OPERATION;
François Gaffie9eb18552018-11-05 10:33:26 +0100713 }
François Gaffieafd4cea2019-11-18 15:50:22 +0100714 // createAudioPatchInternal now supports both HW / SW bridging
715 createRxPatch = true;
716 createTxPatch = true;
François Gaffie9eb18552018-11-05 10:33:26 +0100717 } else {
718 // If the RX device is on the primary HW module, then use legacy routing method for
719 // voice calls via setOutputDevice() on primary output.
720 // Otherwise, create two audio patches for TX and RX path.
721 createRxPatch = !(availablePrimaryOutputDevices().contains(rxDevices.itemAt(0))) &&
722 (rxSourceDevice != 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700723 // If the TX device is also on the primary HW module, setOutputDevice() will take care
724 // of it due to legacy implementation. If not, create a patch.
François Gaffie9eb18552018-11-05 10:33:26 +0100725 createTxPatch = !(availablePrimaryModuleInputDevices().contains(txSourceDevice)) &&
726 (txSinkDevice != 0);
727 }
728 // Use legacy routing method for voice calls via setOutputDevice() on primary output.
729 // Otherwise, create two audio patches for TX and RX path.
730 if (!createRxPatch) {
731 muteWaitMs = setOutputDevices(mPrimaryOutput, rxDevices, true, delayMs);
Eric Laurent8ae73122016-04-12 10:13:29 -0700732 } else { // create RX path audio patch
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200733 connectTelephonyRxAudioSource();
juyuchen2224c5a2019-01-21 12:00:58 +0800734 // If the TX device is on the primary HW module but RX device is
735 // on other HW module, SinkMetaData of telephony input should handle it
736 // assuming the device uses audio HAL V5.0 and above
Eric Laurentc2730ba2014-07-20 15:47:07 -0700737 }
Eric Laurent8ae73122016-04-12 10:13:29 -0700738 if (createTxPatch) { // create TX path audio patch
François Gaffieafd4cea2019-11-18 15:50:22 +0100739 // terminate active capture if on the same HW module as the call TX source device
740 // FIXME: would be better to refine to only inputs whose profile connects to the
741 // call TX device but this information is not in the audio patch and logic here must be
742 // symmetric to the one in startInput()
743 for (const auto& activeDesc : mInputs.getActiveInputs()) {
744 if (activeDesc->hasSameHwModuleAs(txSourceDevice)) {
745 closeActiveClients(activeDesc);
746 }
747 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200748 connectTelephonyTxAudioSource(txSourceDevice, txSinkDevice, delayMs);
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800749 }
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100750 if (waitMs != nullptr) {
751 *waitMs = muteWaitMs;
752 }
753 return NO_ERROR;
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800754}
Eric Laurentc2730ba2014-07-20 15:47:07 -0700755
Mikhail Naganov100f0122018-11-29 11:22:16 -0800756bool AudioPolicyManager::isDeviceOfModule(
757 const sp<DeviceDescriptor>& devDesc, const char *moduleId) const {
758 sp<HwModule> module = mHwModules.getModuleFromName(moduleId);
759 if (module != 0) {
760 return mAvailableOutputDevices.getDevicesFromHwModule(module->getHandle())
761 .indexOf(devDesc) != NAME_NOT_FOUND
762 || mAvailableInputDevices.getDevicesFromHwModule(module->getHandle())
763 .indexOf(devDesc) != NAME_NOT_FOUND;
764 }
765 return false;
766}
767
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200768void AudioPolicyManager::connectTelephonyRxAudioSource()
769{
Francois Gaffie601801d2021-06-22 13:27:39 +0200770 disconnectTelephonyAudioSource(mCallRxSourceClient);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200771 const struct audio_port_config source = {
772 .role = AUDIO_PORT_ROLE_SOURCE, .type = AUDIO_PORT_TYPE_DEVICE,
773 .ext.device.type = AUDIO_DEVICE_IN_TELEPHONY_RX, .ext.device.address = ""
774 };
775 const auto aa = mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL);
Francois Gaffie601801d2021-06-22 13:27:39 +0200776 mCallRxSourceClient = startAudioSourceInternal(&source, &aa, 0/*uid*/);
777 ALOGE_IF(mCallRxSourceClient == nullptr,
778 "%s failed to start Telephony Rx AudioSource", __func__);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200779}
780
Francois Gaffie601801d2021-06-22 13:27:39 +0200781void AudioPolicyManager::disconnectTelephonyAudioSource(sp<SourceClientDescriptor> &clientDesc)
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200782{
Francois Gaffie601801d2021-06-22 13:27:39 +0200783 if (clientDesc == nullptr) {
784 return;
785 }
786 ALOGW_IF(stopAudioSource(clientDesc->portId()) != NO_ERROR,
787 "%s error stopping audio source", __func__);
788 clientDesc.clear();
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200789}
790
791void AudioPolicyManager::connectTelephonyTxAudioSource(
792 const sp<DeviceDescriptor> &srcDevice, const sp<DeviceDescriptor> &sinkDevice,
793 uint32_t delayMs)
794{
Francois Gaffie601801d2021-06-22 13:27:39 +0200795 disconnectTelephonyAudioSource(mCallTxSourceClient);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200796 if (srcDevice == nullptr || sinkDevice == nullptr) {
797 ALOGW("%s could not create patch, invalid sink and/or source device(s)", __func__);
798 return;
799 }
800 PatchBuilder patchBuilder;
801 patchBuilder.addSource(srcDevice).addSink(sinkDevice);
802 ALOGV("%s between source %s and sink %s", __func__,
803 srcDevice->toString().c_str(), sinkDevice->toString().c_str());
Francois Gaffie601801d2021-06-22 13:27:39 +0200804 auto callTxSourceClientPortId = PolicyAudioPort::getNextUniqueId();
Eric Laurent78b07302022-10-07 16:20:34 +0200805 const auto aa = mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL);
806
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200807 struct audio_port_config source = {};
808 srcDevice->toAudioPortConfig(&source);
Francois Gaffie601801d2021-06-22 13:27:39 +0200809 mCallTxSourceClient = new InternalSourceClientDescriptor(
810 callTxSourceClientPortId, mUidCached, aa, source, srcDevice, sinkDevice,
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200811 mCommunnicationStrategy, toVolumeSource(aa));
812 audio_patch_handle_t patchHandle = AUDIO_PATCH_HANDLE_NONE;
813 status_t status = connectAudioSourceToSink(
Francois Gaffie601801d2021-06-22 13:27:39 +0200814 mCallTxSourceClient, sinkDevice, patchBuilder.patch(), patchHandle, mUidCached,
815 delayMs);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200816 ALOGE_IF(status != NO_ERROR, "%s() error %d creating TX audio patch", __func__, status);
817 if (status == NO_ERROR) {
Francois Gaffie601801d2021-06-22 13:27:39 +0200818 mAudioSources.add(callTxSourceClientPortId, mCallTxSourceClient);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200819 }
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200820}
821
Eric Laurente0720872014-03-11 09:30:41 -0700822void AudioPolicyManager::setPhoneState(audio_mode_t state)
Eric Laurente552edb2014-03-10 17:42:56 -0700823{
824 ALOGV("setPhoneState() state %d", state);
François Gaffie2110e042015-03-24 08:41:51 +0100825 // store previous phone state for management of sonification strategy below
826 int oldState = mEngine->getPhoneState();
Eric Laurent96d1dda2022-03-14 17:14:19 +0100827 bool wasLeUnicastActive = isLeUnicastActive();
François Gaffie2110e042015-03-24 08:41:51 +0100828
829 if (mEngine->setPhoneState(state) != NO_ERROR) {
830 ALOGW("setPhoneState() invalid or same state %d", state);
Eric Laurente552edb2014-03-10 17:42:56 -0700831 return;
832 }
François Gaffie2110e042015-03-24 08:41:51 +0100833 /// Opens: can these line be executed after the switch of volume curves???
Eric Laurent63dea1d2015-07-02 17:10:28 -0700834 if (isStateInCall(oldState)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700835 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent63dea1d2015-07-02 17:10:28 -0700836 // force reevaluating accessibility routing when call stops
jiabinc44b3462022-12-08 12:52:31 -0800837 invalidateStreams({AUDIO_STREAM_ACCESSIBILITY});
Eric Laurente552edb2014-03-10 17:42:56 -0700838 }
839
François Gaffie2110e042015-03-24 08:41:51 +0100840 /**
841 * Switching to or from incall state or switching between telephony and VoIP lead to force
842 * routing command.
843 */
Eric Laurent74b71512019-11-06 17:21:57 -0800844 bool force = ((isStateInCall(oldState) != isStateInCall(state))
845 || (isStateInCall(state) && (state != oldState)));
Eric Laurente552edb2014-03-10 17:42:56 -0700846
847 // check for device and output changes triggered by new phone state
Mikhail Naganov37977152018-07-11 15:54:44 -0700848 checkForDeviceAndOutputChanges();
Eric Laurente552edb2014-03-10 17:42:56 -0700849
Eric Laurente552edb2014-03-10 17:42:56 -0700850 int delayMs = 0;
851 if (isStateInCall(state)) {
852 nsecs_t sysTime = systemTime();
François Gaffiec005e562018-11-06 15:04:49 +0100853 auto musicStrategy = streamToStrategy(AUDIO_STREAM_MUSIC);
854 auto sonificationStrategy = streamToStrategy(AUDIO_STREAM_ALARM);
Eric Laurente552edb2014-03-10 17:42:56 -0700855 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700856 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700857 // mute media and sonification strategies and delay device switch by the largest
858 // latency of any output where either strategy is active.
859 // This avoid sending the ring tone or music tail into the earpiece or headset.
François Gaffiec005e562018-11-06 15:04:49 +0100860 if ((desc->isStrategyActive(musicStrategy, SONIFICATION_HEADSET_MUSIC_DELAY, sysTime) ||
861 desc->isStrategyActive(sonificationStrategy, SONIFICATION_HEADSET_MUSIC_DELAY,
862 sysTime)) &&
Eric Laurentc75307b2015-03-17 15:29:32 -0700863 (delayMs < (int)desc->latency()*2)) {
864 delayMs = desc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -0700865 }
François Gaffiec005e562018-11-06 15:04:49 +0100866 setStrategyMute(musicStrategy, true, desc);
867 setStrategyMute(musicStrategy, false, desc, MUTE_TIME_MS,
868 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
869 nullptr, true /*fromCache*/).types());
870 setStrategyMute(sonificationStrategy, true, desc);
871 setStrategyMute(sonificationStrategy, false, desc, MUTE_TIME_MS,
872 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_ALARM),
873 nullptr, true /*fromCache*/).types());
Eric Laurente552edb2014-03-10 17:42:56 -0700874 }
875 }
876
Eric Laurent87ffa392015-05-22 10:32:38 -0700877 if (hasPrimaryOutput()) {
Eric Laurent87ffa392015-05-22 10:32:38 -0700878 if (state == AUDIO_MODE_IN_CALL) {
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100879 (void)updateCallRouting(false /*fromCache*/, delayMs);
Eric Laurent87ffa392015-05-22 10:32:38 -0700880 } else {
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100881 DeviceVector rxDevices = getNewOutputDevices(mPrimaryOutput, false /*fromCache*/);
882 // force routing command to audio hardware when ending call
883 // even if no device change is needed
884 if (isStateInCall(oldState) && rxDevices.isEmpty()) {
885 rxDevices = mPrimaryOutput->devices();
886 }
887 if (oldState == AUDIO_MODE_IN_CALL) {
Francois Gaffie601801d2021-06-22 13:27:39 +0200888 disconnectTelephonyAudioSource(mCallRxSourceClient);
889 disconnectTelephonyAudioSource(mCallTxSourceClient);
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100890 }
François Gaffie11d30102018-11-02 16:09:09 +0100891 setOutputDevices(mPrimaryOutput, rxDevices, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700892 }
Eric Laurentc2730ba2014-07-20 15:47:07 -0700893 }
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700894
jiabin3ff8d7d2022-12-13 06:27:44 +0000895 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700896 // reevaluate routing on all outputs in case tracks have been started during the call
897 for (size_t i = 0; i < mOutputs.size(); i++) {
898 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
François Gaffie11d30102018-11-02 16:09:09 +0100899 DeviceVector newDevices = getNewOutputDevices(desc, true /*fromCache*/);
Francois Gaffie601801d2021-06-22 13:27:39 +0200900 if (state != AUDIO_MODE_IN_CALL || (desc != mPrimaryOutput && !isTelephonyRxOrTx(desc))) {
901 bool forceRouting = !newDevices.isEmpty();
jiabin3ff8d7d2022-12-13 06:27:44 +0000902 if (desc->mUsePreferredMixerAttributes && newDevices != desc->devices()) {
903 // If the device is using preferred mixer attributes, the output need to reopen
904 // with default configuration when the new selected devices are different from
905 // current routing devices.
906 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices);
907 continue;
908 }
Francois Gaffie601801d2021-06-22 13:27:39 +0200909 setOutputDevices(desc, newDevices, forceRouting, 0 /*delayMs*/, nullptr,
910 true /*requiresMuteCheck*/, !forceRouting /*requiresVolumeCheck*/);
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700911 }
912 }
jiabin3ff8d7d2022-12-13 06:27:44 +0000913 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700914
Eric Laurent96d1dda2022-03-14 17:14:19 +0100915 checkLeBroadcastRoutes(wasLeUnicastActive, nullptr, delayMs);
916
Eric Laurente552edb2014-03-10 17:42:56 -0700917 if (isStateInCall(state)) {
918 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent63dea1d2015-07-02 17:10:28 -0700919 // force reevaluating accessibility routing when call starts
jiabinc44b3462022-12-08 12:52:31 -0800920 invalidateStreams({AUDIO_STREAM_ACCESSIBILITY});
Eric Laurente552edb2014-03-10 17:42:56 -0700921 }
922
923 // Flag that ringtone volume must be limited to music volume until we exit MODE_RINGTONE
François Gaffiec005e562018-11-06 15:04:49 +0100924 mLimitRingtoneVolume = (state == AUDIO_MODE_RINGTONE &&
925 isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY));
Eric Laurente552edb2014-03-10 17:42:56 -0700926}
927
Jean-Michel Trivi887a9ed2015-03-31 18:02:24 -0700928audio_mode_t AudioPolicyManager::getPhoneState() {
929 return mEngine->getPhoneState();
930}
931
Eric Laurente0720872014-03-11 09:30:41 -0700932void AudioPolicyManager::setForceUse(audio_policy_force_use_t usage,
François Gaffie11d30102018-11-02 16:09:09 +0100933 audio_policy_forced_cfg_t config)
Eric Laurente552edb2014-03-10 17:42:56 -0700934{
François Gaffie2110e042015-03-24 08:41:51 +0100935 ALOGV("setForceUse() usage %d, config %d, mPhoneState %d", usage, config, mEngine->getPhoneState());
Eric Laurent8dc87a62017-05-16 19:00:40 -0700936 if (config == mEngine->getForceUse(usage)) {
937 return;
938 }
Eric Laurente552edb2014-03-10 17:42:56 -0700939
François Gaffie2110e042015-03-24 08:41:51 +0100940 if (mEngine->setForceUse(usage, config) != NO_ERROR) {
941 ALOGW("setForceUse() could not set force cfg %d for usage %d", config, usage);
942 return;
Eric Laurente552edb2014-03-10 17:42:56 -0700943 }
François Gaffie2110e042015-03-24 08:41:51 +0100944 bool forceVolumeReeval = (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) ||
945 (usage == AUDIO_POLICY_FORCE_FOR_DOCK) ||
946 (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM);
Eric Laurente552edb2014-03-10 17:42:56 -0700947
948 // check for device and output changes triggered by new force usage
Mikhail Naganov37977152018-07-11 15:54:44 -0700949 checkForDeviceAndOutputChanges();
Phil Burk09bc4612016-02-24 15:58:15 -0800950
Eric Laurent22fcda22019-05-17 16:28:47 -0700951 // force client reconnection to reevaluate flag AUDIO_FLAG_AUDIBILITY_ENFORCED
952 if (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM) {
jiabinc44b3462022-12-08 12:52:31 -0800953 invalidateStreams({AUDIO_STREAM_SYSTEM, AUDIO_STREAM_ENFORCED_AUDIBLE});
Eric Laurent22fcda22019-05-17 16:28:47 -0700954 }
955
Eric Laurentdc462862016-07-19 12:29:53 -0700956 //FIXME: workaround for truncated touch sounds
957 // to be removed when the problem is handled by system UI
958 uint32_t delayMs = 0;
Eric Laurentdc462862016-07-19 12:29:53 -0700959 if (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) {
960 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
961 }
Jean-Michel Trivi30857152019-11-01 11:04:15 -0700962
963 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Eric Laurent2517af32020-11-25 15:31:27 +0100964 updateInputRouting();
Eric Laurente552edb2014-03-10 17:42:56 -0700965}
966
Eric Laurente0720872014-03-11 09:30:41 -0700967void AudioPolicyManager::setSystemProperty(const char* property, const char* value)
Eric Laurente552edb2014-03-10 17:42:56 -0700968{
969 ALOGV("setSystemProperty() property %s, value %s", property, value);
970}
971
Dorin Drimusecc9f422022-03-09 17:57:40 +0100972// Find an MSD output profile compatible with the parameters passed.
973// When "directOnly" is set, restrict search to profiles for direct outputs.
974sp<IOProfile> AudioPolicyManager::getMsdProfileForOutput(
975 const DeviceVector& devices,
976 uint32_t samplingRate,
977 audio_format_t format,
978 audio_channel_mask_t channelMask,
979 audio_output_flags_t flags,
980 bool directOnly)
981{
982 flags = getRelevantFlags(flags, directOnly);
983
984 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
985 if (msdModule != nullptr) {
986 // for the msd module check if there are patches to the output devices
987 if (msdHasPatchesToAllDevices(devices.toTypeAddrVector())) {
988 HwModuleCollection modules;
989 modules.add(msdModule);
990 return searchCompatibleProfileHwModules(
991 modules, getMsdAudioOutDevices(), samplingRate, format, channelMask,
992 flags, directOnly);
993 }
994 }
995 return nullptr;
996}
997
Michael Chana94fbb22018-04-24 14:31:19 +1000998// Find an output profile compatible with the parameters passed. When "directOnly" is set, restrict
999// search to profiles for direct outputs.
1000sp<IOProfile> AudioPolicyManager::getProfileForOutput(
François Gaffie11d30102018-11-02 16:09:09 +01001001 const DeviceVector& devices,
Michael Chana94fbb22018-04-24 14:31:19 +10001002 uint32_t samplingRate,
1003 audio_format_t format,
1004 audio_channel_mask_t channelMask,
1005 audio_output_flags_t flags,
1006 bool directOnly)
Eric Laurente552edb2014-03-10 17:42:56 -07001007{
Dorin Drimusecc9f422022-03-09 17:57:40 +01001008 flags = getRelevantFlags(flags, directOnly);
1009
1010 return searchCompatibleProfileHwModules(
1011 mHwModules, devices, samplingRate, format, channelMask, flags, directOnly);
1012}
1013
1014audio_output_flags_t AudioPolicyManager::getRelevantFlags (
1015 audio_output_flags_t flags, bool directOnly) {
Michael Chana94fbb22018-04-24 14:31:19 +10001016 if (directOnly) {
Dorin Drimusecc9f422022-03-09 17:57:40 +01001017 // only retain flags that will drive the direct output profile selection
1018 // if explicitly requested
1019 static const uint32_t kRelevantFlags =
Michael Chana94fbb22018-04-24 14:31:19 +10001020 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD |
Dorin Drimusecc9f422022-03-09 17:57:40 +01001021 AUDIO_OUTPUT_FLAG_VOIP_RX | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ);
1022 flags = (audio_output_flags_t)((flags & kRelevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
Michael Chana94fbb22018-04-24 14:31:19 +10001023 }
Dorin Drimusecc9f422022-03-09 17:57:40 +01001024 return flags;
1025}
Eric Laurent861a6282015-05-18 15:40:16 -07001026
Dorin Drimusecc9f422022-03-09 17:57:40 +01001027sp<IOProfile> AudioPolicyManager::searchCompatibleProfileHwModules (
1028 const HwModuleCollection& hwModules,
1029 const DeviceVector& devices,
1030 uint32_t samplingRate,
1031 audio_format_t format,
1032 audio_channel_mask_t channelMask,
1033 audio_output_flags_t flags,
1034 bool directOnly) {
Eric Laurent861a6282015-05-18 15:40:16 -07001035 sp<IOProfile> profile;
Dorin Drimusecc9f422022-03-09 17:57:40 +01001036 for (const auto& hwModule : hwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08001037 for (const auto& curProfile : hwModule->getOutputProfiles()) {
Dorin Drimusecc9f422022-03-09 17:57:40 +01001038 if (!curProfile->isCompatibleProfile(devices,
1039 samplingRate, NULL /*updatedSamplingRate*/,
1040 format, NULL /*updatedFormat*/,
1041 channelMask, NULL /*updatedChannelMask*/,
1042 flags)) {
1043 continue;
1044 }
1045 // reject profiles not corresponding to a device currently available
1046 if (!mAvailableOutputDevices.containsAtLeastOne(curProfile->getSupportedDevices())) {
1047 continue;
1048 }
1049 // reject profiles if connected device does not support codec
1050 if (!curProfile->devicesSupportEncodedFormats(devices.types())) {
1051 continue;
1052 }
1053 if (!directOnly) {
1054 return curProfile;
1055 }
1056
1057 // when searching for direct outputs, if several profiles are compatible, give priority
1058 // to one with offload capability
Patty Huang36028df2022-07-06 00:14:12 +08001059 if (profile != 0 &&
Dorin Drimusecc9f422022-03-09 17:57:40 +01001060 ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0)) {
Eric Laurent861a6282015-05-18 15:40:16 -07001061 continue;
Dorin Drimusecc9f422022-03-09 17:57:40 +01001062 }
1063 profile = curProfile;
1064 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1065 break;
1066 }
Eric Laurente552edb2014-03-10 17:42:56 -07001067 }
1068 }
Eric Laurent861a6282015-05-18 15:40:16 -07001069 return profile;
Eric Laurente552edb2014-03-10 17:42:56 -07001070}
1071
Eric Laurentfa0f6742021-08-17 18:39:44 +02001072sp<IOProfile> AudioPolicyManager::getSpatializerOutputProfile(
Eric Laurent39095982021-08-24 18:29:27 +02001073 const audio_config_t *config __unused, const AudioDeviceTypeAddrVector &devices) const
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001074{
1075 for (const auto& hwModule : mHwModules) {
1076 for (const auto& curProfile : hwModule->getOutputProfiles()) {
Eric Laurent1c5e2e32021-08-18 18:50:28 +02001077 if (curProfile->getFlags() != AUDIO_OUTPUT_FLAG_SPATIALIZER) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001078 continue;
1079 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001080 if (!devices.empty()) {
Eric Laurent0c8f7cc2022-06-24 14:32:36 +02001081 // reject profiles not corresponding to a device currently available
1082 DeviceVector supportedDevices = curProfile->getSupportedDevices();
1083 if (!mAvailableOutputDevices.containsAtLeastOne(supportedDevices)) {
1084 continue;
1085 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001086 if (supportedDevices.getDevicesFromDeviceTypeAddrVec(devices).size()
1087 != devices.size()) {
1088 continue;
1089 }
1090 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001091 ALOGV("%s found profile %s", __func__, curProfile->getName().c_str());
1092 return curProfile;
1093 }
1094 }
1095 return nullptr;
1096}
1097
Eric Laurentf4e63452017-11-06 19:31:46 +00001098audio_io_handle_t AudioPolicyManager::getOutput(audio_stream_type_t stream)
Eric Laurente552edb2014-03-10 17:42:56 -07001099{
François Gaffiec005e562018-11-06 15:04:49 +01001100 DeviceVector devices = mEngine->getOutputDevicesForStream(stream, false /*fromCache*/);
Andy Hungc9901522017-11-10 20:07:54 -08001101
1102 // Note that related method getOutputForAttr() uses getOutputForDevice() not selectOutput().
1103 // We use selectOutput() here since we don't have the desired AudioTrack sample rate,
1104 // format, flags, etc. This may result in some discrepancy for functions that utilize
1105 // getOutput() solely on audio_stream_type such as AudioSystem::getOutputFrameCount()
1106 // and AudioSystem::getOutputSamplingRate().
1107
François Gaffie11d30102018-11-02 16:09:09 +01001108 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Mingyu Shih75563d32023-05-24 04:47:40 +08001109 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
1110 if (stream == AUDIO_STREAM_MUSIC &&
1111 property_get_bool("audio.deep_buffer.media", false /* default_value */)) {
1112 flags = AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
1113 }
1114 const audio_io_handle_t output = selectOutput(outputs, flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001115
François Gaffie11d30102018-11-02 16:09:09 +01001116 ALOGV("getOutput() stream %d selected devices %s, output %d", stream,
1117 devices.toString().c_str(), output);
Eric Laurentf4e63452017-11-06 19:31:46 +00001118 return output;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001119}
1120
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001121status_t AudioPolicyManager::getAudioAttributes(audio_attributes_t *dstAttr,
1122 const audio_attributes_t *srcAttr,
1123 audio_stream_type_t srcStream)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001124{
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001125 if (srcAttr != NULL) {
1126 if (!isValidAttributes(srcAttr)) {
1127 ALOGE("%s invalid attributes: usage=%d content=%d flags=0x%x tags=[%s]",
1128 __func__,
1129 srcAttr->usage, srcAttr->content_type, srcAttr->flags,
1130 srcAttr->tags);
1131 return BAD_VALUE;
1132 }
1133 *dstAttr = *srcAttr;
1134 } else {
1135 if (srcStream < AUDIO_STREAM_MIN || srcStream >= AUDIO_STREAM_PUBLIC_CNT) {
1136 ALOGE("%s: invalid stream type", __func__);
1137 return BAD_VALUE;
1138 }
François Gaffiec005e562018-11-06 15:04:49 +01001139 *dstAttr = mEngine->getAttributesForStreamType(srcStream);
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001140 }
Eric Laurent22fcda22019-05-17 16:28:47 -07001141
1142 // Only honor audibility enforced when required. The client will be
1143 // forced to reconnect if the forced usage changes.
1144 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Mikhail Naganov55773032020-10-01 15:08:13 -07001145 dstAttr->flags = static_cast<audio_flags_mask_t>(
1146 dstAttr->flags & ~AUDIO_FLAG_AUDIBILITY_ENFORCED);
Eric Laurent22fcda22019-05-17 16:28:47 -07001147 }
1148
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001149 return NO_ERROR;
1150}
1151
Kevin Rocard153f92d2018-12-18 18:33:28 -08001152status_t AudioPolicyManager::getOutputForAttrInt(
1153 audio_attributes_t *resultAttr,
1154 audio_io_handle_t *output,
1155 audio_session_t session,
1156 const audio_attributes_t *attr,
1157 audio_stream_type_t *stream,
1158 uid_t uid,
jiabinf1c73972022-04-14 16:28:52 -07001159 audio_config_t *config,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001160 audio_output_flags_t *flags,
1161 audio_port_handle_t *selectedDeviceId,
1162 bool *isRequestedDeviceForExclusiveUse,
Eric Laurentc529cf62020-04-17 18:19:10 -07001163 std::vector<sp<AudioPolicyMix>> *secondaryMixes,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001164 output_type_t *outputType,
jiabinc658e452022-10-21 20:52:21 +00001165 bool *isSpatialized,
1166 bool *isBitPerfect)
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001167{
François Gaffiec005e562018-11-06 15:04:49 +01001168 DeviceVector outputDevices;
Francois Gaffie716e1432019-01-14 16:58:59 +01001169 const audio_port_handle_t requestedPortId = *selectedDeviceId;
François Gaffie11d30102018-11-02 16:09:09 +01001170 DeviceVector msdDevices = getMsdAudioOutDevices();
François Gaffiec005e562018-11-06 15:04:49 +01001171 const sp<DeviceDescriptor> requestedDevice =
1172 mAvailableOutputDevices.getDeviceFromId(requestedPortId);
1173
Eric Laurent8a1095a2019-11-08 14:44:16 -08001174 *outputType = API_OUTPUT_INVALID;
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001175 *isSpatialized = false;
1176
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001177 status_t status = getAudioAttributes(resultAttr, attr, *stream);
1178 if (status != NO_ERROR) {
1179 return status;
Eric Laurent8f42ea12018-08-08 09:08:25 -07001180 }
Kevin Rocardb99cc752019-03-21 20:52:24 -07001181 if (auto it = mAllowedCapturePolicies.find(uid); it != end(mAllowedCapturePolicies)) {
Mikhail Naganov55773032020-10-01 15:08:13 -07001182 resultAttr->flags = static_cast<audio_flags_mask_t>(resultAttr->flags | it->second);
Kevin Rocardb99cc752019-03-21 20:52:24 -07001183 }
François Gaffiec005e562018-11-06 15:04:49 +01001184 *stream = mEngine->getStreamTypeForAttributes(*resultAttr);
Eric Laurent8f42ea12018-08-08 09:08:25 -07001185
François Gaffiec005e562018-11-06 15:04:49 +01001186 ALOGV("%s() attributes=%s stream=%s session %d selectedDeviceId %d", __func__,
1187 toString(*resultAttr).c_str(), toString(*stream).c_str(), session, requestedPortId);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001188
Oscar Azucena873d10f2023-01-12 18:34:42 -08001189 bool usePrimaryOutputFromPolicyMixes = false;
1190
Kevin Rocard153f92d2018-12-18 18:33:28 -08001191 // The primary output is the explicit routing (eg. setPreferredDevice) if specified,
1192 // otherwise, fallback to the dynamic policies, if none match, query the engine.
1193 // Secondary outputs are always found by dynamic policies as the engine do not support them
Eric Laurentc529cf62020-04-17 18:19:10 -07001194 sp<AudioPolicyMix> primaryMix;
Dean Wheatleyd082f472022-02-04 11:10:48 +11001195 const audio_config_base_t clientConfig = {.sample_rate = config->sample_rate,
1196 .channel_mask = config->channel_mask,
1197 .format = config->format,
1198 };
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02001199 status = mPolicyMixes.getOutputForAttr(*resultAttr, clientConfig, uid, session, *flags,
Oscar Azucena873d10f2023-01-12 18:34:42 -08001200 mAvailableOutputDevices, requestedDevice, primaryMix,
1201 secondaryMixes, usePrimaryOutputFromPolicyMixes);
Kevin Rocard94114a22019-04-01 19:38:23 -07001202 if (status != OK) {
1203 return status;
Kevin Rocard153f92d2018-12-18 18:33:28 -08001204 }
Kevin Rocard94114a22019-04-01 19:38:23 -07001205
Kevin Rocard153f92d2018-12-18 18:33:28 -08001206 // FIXME: in case of RENDER policy, the output capabilities should be checked
Dean Wheatleyd082f472022-02-04 11:10:48 +11001207 if ((secondaryMixes != nullptr && !secondaryMixes->empty())
1208 && !audio_is_linear_pcm(config->format)) {
1209 ALOGD("%s: rejecting request as secondary mixes only support pcm", __func__);
Kevin Rocard153f92d2018-12-18 18:33:28 -08001210 return BAD_VALUE;
1211 }
1212 if (usePrimaryOutputFromPolicyMixes) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001213 sp<DeviceDescriptor> deviceDesc =
1214 mAvailableOutputDevices.getDevice(primaryMix->mDeviceType,
1215 primaryMix->mDeviceAddress,
1216 AUDIO_FORMAT_DEFAULT);
1217 sp<SwAudioOutputDescriptor> policyDesc = primaryMix->getOutput();
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001218 bool tryDirectForFlags = policyDesc == nullptr ||
1219 (policyDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT);
1220 // if a direct output can be opened to deliver the track's multi-channel content to the
1221 // output rather than being downmixed by the primary output, then use this direct
1222 // output by by-passing the primary mix if possible, otherwise fall-through to primary
1223 // mix.
1224 bool tryDirectForChannelMask = policyDesc != nullptr
1225 && (audio_channel_count_from_out_mask(policyDesc->getConfig().channel_mask) <
1226 audio_channel_count_from_out_mask(config->channel_mask));
1227 if (deviceDesc != nullptr && (tryDirectForFlags || tryDirectForChannelMask)) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001228 audio_io_handle_t newOutput;
1229 status = openDirectOutput(
1230 *stream, session, config,
1231 (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT),
1232 DeviceVector(deviceDesc), &newOutput);
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001233 if (status == NO_ERROR) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001234 policyDesc = mOutputs.valueFor(newOutput);
1235 primaryMix->setOutput(policyDesc);
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001236 } else if (tryDirectForFlags) {
1237 policyDesc = nullptr;
1238 } // otherwise use primary if available.
Eric Laurentc529cf62020-04-17 18:19:10 -07001239 }
1240 if (policyDesc != nullptr) {
1241 policyDesc->mPolicyMix = primaryMix;
1242 *output = policyDesc->mIoHandle;
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08001243 *selectedDeviceId = deviceDesc != 0 ? deviceDesc->getId() : AUDIO_PORT_HANDLE_NONE;
Eric Laurent8a1095a2019-11-08 14:44:16 -08001244
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08001245 ALOGV("getOutputForAttr() returns output %d", *output);
1246 if (resultAttr->usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
1247 *outputType = API_OUT_MIX_PLAYBACK;
1248 } else {
1249 *outputType = API_OUTPUT_LEGACY;
1250 }
1251 return NO_ERROR;
Eric Laurent8a1095a2019-11-08 14:44:16 -08001252 }
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001253 }
François Gaffiec005e562018-11-06 15:04:49 +01001254 // Virtual sources must always be dynamicaly or explicitly routed
1255 if (resultAttr->usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
1256 ALOGW("getOutputForAttr() no policy mix found for usage AUDIO_USAGE_VIRTUAL_SOURCE");
1257 return BAD_VALUE;
1258 }
1259 // explicit routing managed by getDeviceForStrategy in APM is now handled by engine
1260 // in order to let the choice of the order to future vendor engine
1261 outputDevices = mEngine->getOutputDevicesForAttributes(*resultAttr, requestedDevice, false);
Scott Randolph7b1fd232018-06-18 15:33:03 -07001262
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001263 if ((resultAttr->flags & AUDIO_FLAG_HW_AV_SYNC) != 0) {
Nadav Bar766fb022018-01-07 12:18:03 +02001264 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
Eric Laurent93c3d412014-08-01 14:48:35 -07001265 }
1266
Nadav Barb2f18162018-07-18 13:01:53 +03001267 // Set incall music only if device was explicitly set, and fallback to the device which is
1268 // chosen by the engine if not.
1269 // FIXME: provide a more generic approach which is not device specific and move this back
1270 // to getOutputForDevice.
Nadav Bar20919492018-11-20 10:20:51 +02001271 // TODO: Remove check of AUDIO_STREAM_MUSIC once migration is completed on the app side.
jiabin9a3361e2019-10-01 09:38:30 -07001272 if (outputDevices.onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_TELEPHONY_TX) &&
François Gaffiec005e562018-11-06 15:04:49 +01001273 (*stream == AUDIO_STREAM_MUSIC || resultAttr->usage == AUDIO_USAGE_VOICE_COMMUNICATION) &&
Nadav Barb2f18162018-07-18 13:01:53 +03001274 audio_is_linear_pcm(config->format) &&
Eric Laurent74b71512019-11-06 17:21:57 -08001275 isCallAudioAccessible()) {
Francois Gaffie716e1432019-01-14 16:58:59 +01001276 if (requestedPortId != AUDIO_PORT_HANDLE_NONE) {
Nadav Barb2f18162018-07-18 13:01:53 +03001277 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_INCALL_MUSIC;
François Gaffief579db52018-11-13 11:25:16 +01001278 *isRequestedDeviceForExclusiveUse = true;
Nadav Barb2f18162018-07-18 13:01:53 +03001279 }
1280 }
1281
François Gaffiec005e562018-11-06 15:04:49 +01001282 ALOGV("%s() device %s, sampling rate %d, format %#x, channel mask %#x, flags %#x stream %s",
1283 __func__, outputDevices.toString().c_str(), config->sample_rate, config->format,
1284 config->channel_mask, *flags, toString(*stream).c_str());
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001285
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001286 *output = AUDIO_IO_HANDLE_NONE;
François Gaffie11d30102018-11-02 16:09:09 +01001287 if (!msdDevices.isEmpty()) {
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001288 *output = getOutputForDevices(msdDevices, session, resultAttr, config, flags, isSpatialized);
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001289 if (*output != AUDIO_IO_HANDLE_NONE && setMsdOutputPatches(&outputDevices) == NO_ERROR) {
François Gaffiec005e562018-11-06 15:04:49 +01001290 ALOGV("%s() Using MSD devices %s instead of devices %s",
1291 __func__, msdDevices.toString().c_str(), outputDevices.toString().c_str());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001292 } else {
1293 *output = AUDIO_IO_HANDLE_NONE;
1294 }
1295 }
1296 if (*output == AUDIO_IO_HANDLE_NONE) {
jiabina84c3d32022-12-02 18:59:55 +00001297 sp<PreferredMixerAttributesInfo> info = nullptr;
1298 if (outputDevices.size() == 1) {
1299 info = getPreferredMixerAttributesInfo(
1300 outputDevices.itemAt(0)->getId(),
jiabind9a58d32023-06-01 17:57:30 +00001301 mEngine->getProductStrategyForAttributes(*resultAttr),
1302 true /*activeBitPerfectPreferred*/);
jiabin5eaf0962022-12-20 20:11:38 +00001303 // Only use preferred mixer if the uid matches or the preferred mixer is bit-perfect
1304 // and it is currently active.
1305 if (info != nullptr && info->getUid() != uid &&
1306 ((info->getFlags() & AUDIO_OUTPUT_FLAG_BIT_PERFECT) == AUDIO_OUTPUT_FLAG_NONE ||
1307 info->getActiveClientCount() == 0)) {
jiabina84c3d32022-12-02 18:59:55 +00001308 info = nullptr;
1309 }
1310 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001311 *output = getOutputForDevices(outputDevices, session, resultAttr, config,
jiabina84c3d32022-12-02 18:59:55 +00001312 flags, isSpatialized, info, resultAttr->flags & AUDIO_FLAG_MUTE_HAPTIC);
jiabin5eaf0962022-12-20 20:11:38 +00001313 // The client will be active if the client is currently preferred mixer owner and the
1314 // requested configuration matches the preferred mixer configuration.
jiabinc658e452022-10-21 20:52:21 +00001315 *isBitPerfect = (info != nullptr
1316 && (info->getFlags() & AUDIO_OUTPUT_FLAG_BIT_PERFECT) != AUDIO_OUTPUT_FLAG_NONE
jiabin5eaf0962022-12-20 20:11:38 +00001317 && info->getUid() == uid
1318 && *output != AUDIO_IO_HANDLE_NONE
1319 // When bit-perfect output is selected for the preferred mixer attributes owner,
1320 // only need to consider the config matches.
1321 && mOutputs.valueFor(*output)->isConfigurationMatched(
1322 clientConfig, AUDIO_OUTPUT_FLAG_NONE));
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001323 }
Eric Laurente83b55d2014-11-14 10:06:21 -08001324 if (*output == AUDIO_IO_HANDLE_NONE) {
jiabinf1c73972022-04-14 16:28:52 -07001325 AudioProfileVector profiles;
1326 status_t ret = getProfilesForDevices(outputDevices, profiles, *flags, false /*isInput*/);
1327 if (ret == NO_ERROR && !profiles.empty()) {
1328 config->channel_mask = profiles[0]->getChannels().empty() ? config->channel_mask
1329 : *profiles[0]->getChannels().begin();
1330 config->sample_rate = profiles[0]->getSampleRates().empty() ? config->sample_rate
1331 : *profiles[0]->getSampleRates().begin();
1332 config->format = profiles[0]->getFormat();
1333 }
Eric Laurente83b55d2014-11-14 10:06:21 -08001334 return INVALID_OPERATION;
1335 }
Paul McLeanaa981192015-03-21 09:55:15 -07001336
François Gaffiec005e562018-11-06 15:04:49 +01001337 *selectedDeviceId = getFirstDeviceId(outputDevices);
Michael Chan6fb34492020-12-08 15:44:49 +11001338 for (auto &outputDevice : outputDevices) {
Mikhail Naganov68e3f642023-04-28 13:06:32 -07001339 if (outputDevice->getId() == mConfig->getDefaultOutputDevice()->getId()) {
Michael Chan6fb34492020-12-08 15:44:49 +11001340 *selectedDeviceId = outputDevice->getId();
1341 break;
1342 }
1343 }
Eric Laurent2ac76942017-06-22 17:17:09 -07001344
Eric Laurent8a1095a2019-11-08 14:44:16 -08001345 if (outputDevices.onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_TELEPHONY_TX)) {
1346 *outputType = API_OUTPUT_TELEPHONY_TX;
1347 } else {
1348 *outputType = API_OUTPUT_LEGACY;
1349 }
1350
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001351 ALOGV("%s returns output %d selectedDeviceId %d", __func__, *output, *selectedDeviceId);
1352
1353 return NO_ERROR;
1354}
1355
1356status_t AudioPolicyManager::getOutputForAttr(const audio_attributes_t *attr,
1357 audio_io_handle_t *output,
1358 audio_session_t session,
1359 audio_stream_type_t *stream,
Svet Ganov3e5f14f2021-05-13 22:51:08 +00001360 const AttributionSourceState& attributionSource,
jiabinf1c73972022-04-14 16:28:52 -07001361 audio_config_t *config,
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001362 audio_output_flags_t *flags,
1363 audio_port_handle_t *selectedDeviceId,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001364 audio_port_handle_t *portId,
Eric Laurent8a1095a2019-11-08 14:44:16 -08001365 std::vector<audio_io_handle_t> *secondaryOutputs,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001366 output_type_t *outputType,
jiabinc658e452022-10-21 20:52:21 +00001367 bool *isSpatialized,
1368 bool *isBitPerfect)
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001369{
1370 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
1371 if (*portId != AUDIO_PORT_HANDLE_NONE) {
1372 return INVALID_OPERATION;
1373 }
Philip P. Moltmannbda45752020-07-17 16:41:18 -07001374 const uid_t uid = VALUE_OR_RETURN_STATUS(
Svet Ganov3e5f14f2021-05-13 22:51:08 +00001375 aidl2legacy_int32_t_uid_t(attributionSource.uid));
Francois Gaffie716e1432019-01-14 16:58:59 +01001376 const audio_port_handle_t requestedPortId = *selectedDeviceId;
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001377 audio_attributes_t resultAttr;
François Gaffief579db52018-11-13 11:25:16 +01001378 bool isRequestedDeviceForExclusiveUse = false;
Eric Laurentc529cf62020-04-17 18:19:10 -07001379 std::vector<sp<AudioPolicyMix>> secondaryMixes;
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001380 const sp<DeviceDescriptor> requestedDevice =
1381 mAvailableOutputDevices.getDeviceFromId(requestedPortId);
1382
1383 // Prevent from storing invalid requested device id in clients
1384 const audio_port_handle_t sanitizedRequestedPortId =
1385 requestedDevice != nullptr ? requestedPortId : AUDIO_PORT_HANDLE_NONE;
1386 *selectedDeviceId = sanitizedRequestedPortId;
1387
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001388 status_t status = getOutputForAttrInt(&resultAttr, output, session, attr, stream, uid,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001389 config, flags, selectedDeviceId, &isRequestedDeviceForExclusiveUse,
jiabinc658e452022-10-21 20:52:21 +00001390 secondaryOutputs != nullptr ? &secondaryMixes : nullptr, outputType, isSpatialized,
1391 isBitPerfect);
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001392 if (status != NO_ERROR) {
1393 return status;
1394 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001395 std::vector<wp<SwAudioOutputDescriptor>> weakSecondaryOutputDescs;
Eric Laurentc529cf62020-04-17 18:19:10 -07001396 if (secondaryOutputs != nullptr) {
1397 for (auto &secondaryMix : secondaryMixes) {
1398 sp<SwAudioOutputDescriptor> outputDesc = secondaryMix->getOutput();
1399 if (outputDesc != nullptr &&
1400 outputDesc->mIoHandle != AUDIO_IO_HANDLE_NONE) {
1401 secondaryOutputs->push_back(outputDesc->mIoHandle);
1402 weakSecondaryOutputDescs.push_back(outputDesc);
1403 }
1404 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001405 }
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001406
Eric Laurent8fc147b2018-07-22 19:13:55 -07001407 audio_config_base_t clientConfig = {.sample_rate = config->sample_rate,
Nick Desaulniersa30e3202019-10-18 13:38:23 -07001408 .channel_mask = config->channel_mask,
Eric Laurent8fc147b2018-07-22 19:13:55 -07001409 .format = config->format,
Nick Desaulniersa30e3202019-10-18 13:38:23 -07001410 };
jiabin4ef93452019-09-10 14:29:54 -07001411 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurent8f42ea12018-08-08 09:08:25 -07001412
Eric Laurentc209fe42020-06-05 18:11:23 -07001413 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(*output);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001414 sp<TrackClientDescriptor> clientDesc =
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001415 new TrackClientDescriptor(*portId, uid, session, resultAttr, clientConfig,
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001416 sanitizedRequestedPortId, *stream,
François Gaffiec005e562018-11-06 15:04:49 +01001417 mEngine->getProductStrategyForAttributes(resultAttr),
François Gaffieaaac0fd2018-11-22 17:56:39 +01001418 toVolumeSource(resultAttr),
Kevin Rocard153f92d2018-12-18 18:33:28 -08001419 *flags, isRequestedDeviceForExclusiveUse,
Eric Laurentc209fe42020-06-05 18:11:23 -07001420 std::move(weakSecondaryOutputDescs),
1421 outputDesc->mPolicyMix);
Andy Hung39efb7a2018-09-26 15:39:28 -07001422 outputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001423
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001424 ALOGV("%s() returns output %d requestedPortId %d selectedDeviceId %d for port ID %d", __func__,
1425 *output, requestedPortId, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07001426
Eric Laurente83b55d2014-11-14 10:06:21 -08001427 return NO_ERROR;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001428}
1429
Eric Laurentc529cf62020-04-17 18:19:10 -07001430status_t AudioPolicyManager::openDirectOutput(audio_stream_type_t stream,
1431 audio_session_t session,
1432 const audio_config_t *config,
1433 audio_output_flags_t flags,
1434 const DeviceVector &devices,
1435 audio_io_handle_t *output) {
1436
1437 *output = AUDIO_IO_HANDLE_NONE;
1438
1439 // skip direct output selection if the request can obviously be attached to a mixed output
1440 // and not explicitly requested
1441 if (((flags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
1442 audio_is_linear_pcm(config->format) && config->sample_rate <= SAMPLE_RATE_HZ_MAX &&
1443 audio_channel_count_from_out_mask(config->channel_mask) <= 2) {
1444 return NAME_NOT_FOUND;
1445 }
1446
1447 // Do not allow offloading if one non offloadable effect is enabled or MasterMono is enabled.
1448 // This prevents creating an offloaded track and tearing it down immediately after start
1449 // when audioflinger detects there is an active non offloadable effect.
1450 // FIXME: We should check the audio session here but we do not have it in this context.
1451 // This may prevent offloading in rare situations where effects are left active by apps
1452 // in the background.
1453 sp<IOProfile> profile;
1454 if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) ||
1455 !(mEffects.isNonOffloadableEffectEnabled() || mMasterMono)) {
1456 profile = getProfileForOutput(
1457 devices, config->sample_rate, config->format, config->channel_mask,
1458 flags, true /* directOnly */);
1459 }
1460
1461 if (profile == nullptr) {
1462 return NAME_NOT_FOUND;
1463 }
1464
1465 // exclusive outputs for MMAP and Offload are enforced by different session ids.
1466 for (size_t i = 0; i < mOutputs.size(); i++) {
1467 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
1468 if (!desc->isDuplicated() && (profile == desc->mProfile)) {
1469 // reuse direct output if currently open by the same client
1470 // and configured with same parameters
1471 if ((config->sample_rate == desc->getSamplingRate()) &&
1472 (config->format == desc->getFormat()) &&
1473 (config->channel_mask == desc->getChannelMask()) &&
1474 (session == desc->mDirectClientSession)) {
1475 desc->mDirectOpenCount++;
Eric Laurentfecbceb2021-02-09 14:46:43 +01001476 ALOGV("%s reusing direct output %d for session %d", __func__,
Eric Laurentc529cf62020-04-17 18:19:10 -07001477 mOutputs.keyAt(i), session);
1478 *output = mOutputs.keyAt(i);
1479 return NO_ERROR;
1480 }
1481 }
1482 }
1483
1484 if (!profile->canOpenNewIo()) {
1485 return NAME_NOT_FOUND;
1486 }
1487
1488 sp<SwAudioOutputDescriptor> outputDesc =
1489 new SwAudioOutputDescriptor(profile, mpClientInterface);
1490
Michael Chan6fb34492020-12-08 15:44:49 +11001491 // An MSD patch may be using the only output stream that can service this request. Release
1492 // all MSD patches to prioritize this request over any active output on MSD.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001493 releaseMsdOutputPatches(devices);
Eric Laurentc529cf62020-04-17 18:19:10 -07001494
Eric Laurentf1f22e72021-07-13 14:04:14 +02001495 status_t status =
1496 outputDesc->open(config, nullptr /* mixerConfig */, devices, stream, flags, output);
Eric Laurentc529cf62020-04-17 18:19:10 -07001497
1498 // only accept an output with the requested parameters
1499 if (status != NO_ERROR ||
1500 (config->sample_rate != 0 && config->sample_rate != outputDesc->getSamplingRate()) ||
1501 (config->format != AUDIO_FORMAT_DEFAULT && config->format != outputDesc->getFormat()) ||
1502 (config->channel_mask != 0 && config->channel_mask != outputDesc->getChannelMask())) {
1503 ALOGV("%s failed opening direct output: output %d sample rate %d %d,"
1504 "format %d %d, channel mask %04x %04x", __func__, *output, config->sample_rate,
1505 outputDesc->getSamplingRate(), config->format, outputDesc->getFormat(),
1506 config->channel_mask, outputDesc->getChannelMask());
1507 if (*output != AUDIO_IO_HANDLE_NONE) {
1508 outputDesc->close();
1509 }
1510 // fall back to mixer output if possible when the direct output could not be open
1511 if (audio_is_linear_pcm(config->format) &&
1512 config->sample_rate <= SAMPLE_RATE_HZ_MAX) {
1513 return NAME_NOT_FOUND;
1514 }
1515 *output = AUDIO_IO_HANDLE_NONE;
1516 return BAD_VALUE;
1517 }
1518 outputDesc->mDirectOpenCount = 1;
1519 outputDesc->mDirectClientSession = session;
1520
1521 addOutput(*output, outputDesc);
1522 mPreviousOutputs = mOutputs;
1523 ALOGV("%s returns new direct output %d", __func__, *output);
1524 mpClientInterface->onAudioPortListUpdate();
1525 return NO_ERROR;
1526}
1527
François Gaffie11d30102018-11-02 16:09:09 +01001528audio_io_handle_t AudioPolicyManager::getOutputForDevices(
1529 const DeviceVector &devices,
Kevin Rocard169753c2017-03-06 14:18:23 -08001530 audio_session_t session,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001531 const audio_attributes_t *attr,
Eric Laurentfe231122017-11-17 17:48:06 -08001532 const audio_config_t *config,
jiabine375d412019-02-26 12:54:53 -08001533 audio_output_flags_t *flags,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001534 bool *isSpatialized,
jiabina84c3d32022-12-02 18:59:55 +00001535 sp<PreferredMixerAttributesInfo> prefMixerConfigInfo,
jiabine375d412019-02-26 12:54:53 -08001536 bool forceMutingHaptic)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001537{
Andy Hungc88b0642018-04-27 15:42:35 -07001538 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001539
jiabine375d412019-02-26 12:54:53 -08001540 // Discard haptic channel mask when forcing muting haptic channels.
1541 audio_channel_mask_t channelMask = forceMutingHaptic
Mikhail Naganov55773032020-10-01 15:08:13 -07001542 ? static_cast<audio_channel_mask_t>(config->channel_mask & ~AUDIO_CHANNEL_HAPTIC_ALL)
1543 : config->channel_mask;
jiabine375d412019-02-26 12:54:53 -08001544
Eric Laurente552edb2014-03-10 17:42:56 -07001545 // open a direct output if required by specified parameters
1546 //force direct flag if offload flag is set: offloading implies a direct output stream
1547 // and all common behaviors are driven by checking only the direct flag
1548 // this should normally be set appropriately in the policy configuration file
Nadav Bar766fb022018-01-07 12:18:03 +02001549 if ((*flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1550 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurente552edb2014-03-10 17:42:56 -07001551 }
Nadav Bar766fb022018-01-07 12:18:03 +02001552 if ((*flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
1553 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent93c3d412014-08-01 14:48:35 -07001554 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001555
1556 audio_stream_type_t stream = mEngine->getStreamTypeForAttributes(*attr);
1557
Eric Laurente83b55d2014-11-14 10:06:21 -08001558 // only allow deep buffering for music stream type
1559 if (stream != AUDIO_STREAM_MUSIC) {
Nadav Bar766fb022018-01-07 12:18:03 +02001560 *flags = (audio_output_flags_t)(*flags &~AUDIO_OUTPUT_FLAG_DEEP_BUFFER);
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -07001561 } else if (/* stream == AUDIO_STREAM_MUSIC && */
Nadav Bar766fb022018-01-07 12:18:03 +02001562 *flags == AUDIO_OUTPUT_FLAG_NONE &&
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -07001563 property_get_bool("audio.deep_buffer.media", false /* default_value */)) {
1564 // use DEEP_BUFFER as default output for music stream type
Nadav Bar766fb022018-01-07 12:18:03 +02001565 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
Eric Laurente83b55d2014-11-14 10:06:21 -08001566 }
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -07001567 if (stream == AUDIO_STREAM_TTS) {
Nadav Bar766fb022018-01-07 12:18:03 +02001568 *flags = AUDIO_OUTPUT_FLAG_TTS;
Haynes Mathew George84c621e2017-04-25 11:41:50 -07001569 } else if (stream == AUDIO_STREAM_VOICE_CALL &&
Nadav Bar20919492018-11-20 10:20:51 +02001570 audio_is_linear_pcm(config->format) &&
1571 (*flags & AUDIO_OUTPUT_FLAG_INCALL_MUSIC) == 0) {
Nadav Bar766fb022018-01-07 12:18:03 +02001572 *flags = (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_VOIP_RX |
Haynes Mathew George84c621e2017-04-25 11:41:50 -07001573 AUDIO_OUTPUT_FLAG_DIRECT);
1574 ALOGV("Set VoIP and Direct output flags for PCM format");
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -07001575 }
Eric Laurente552edb2014-03-10 17:42:56 -07001576
Carter Hsua3abb402021-10-26 11:11:20 +08001577 // Attach the Ultrasound flag for the AUDIO_CONTENT_TYPE_ULTRASOUND
1578 if (attr->content_type == AUDIO_CONTENT_TYPE_ULTRASOUND) {
1579 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_ULTRASOUND);
1580 }
1581
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001582 *isSpatialized = false;
Eric Laurentfa0f6742021-08-17 18:39:44 +02001583 if (mSpatializerOutput != nullptr
Andy Hung9dd1a5b2022-05-10 15:39:39 -07001584 && canBeSpatializedInt(attr, config, devices.toTypeAddrVector())) {
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001585 *isSpatialized = true;
Eric Laurentfa0f6742021-08-17 18:39:44 +02001586 return mSpatializerOutput->mIoHandle;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001587 }
1588
Eric Laurentc529cf62020-04-17 18:19:10 -07001589 audio_config_t directConfig = *config;
1590 directConfig.channel_mask = channelMask;
1591 status_t status = openDirectOutput(stream, session, &directConfig, *flags, devices, &output);
1592 if (status != NAME_NOT_FOUND) {
Eric Laurente552edb2014-03-10 17:42:56 -07001593 return output;
1594 }
1595
Eric Laurent14cbfca2016-03-17 09:42:16 -07001596 // A request for HW A/V sync cannot fallback to a mixed output because time
1597 // stamps are embedded in audio data
Phil Burk2d059932018-02-15 15:55:11 -08001598 if ((*flags & (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ)) != 0) {
Eric Laurent14cbfca2016-03-17 09:42:16 -07001599 return AUDIO_IO_HANDLE_NONE;
1600 }
Pierre Couillaude73496b2023-03-06 16:19:05 +00001601 // A request for Tuner cannot fallback to a mixed output
1602 if ((directConfig.offload_info.content_id || directConfig.offload_info.sync_id)) {
1603 return AUDIO_IO_HANDLE_NONE;
1604 }
Eric Laurent14cbfca2016-03-17 09:42:16 -07001605
Eric Laurente552edb2014-03-10 17:42:56 -07001606 // ignoring channel mask due to downmix capability in mixer
1607
1608 // open a non direct output
1609
1610 // for non direct outputs, only PCM is supported
Eric Laurentfe231122017-11-17 17:48:06 -08001611 if (audio_is_linear_pcm(config->format)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001612 // get which output is suitable for the specified stream. The actual
1613 // routing change will happen when startOutput() will be called
François Gaffie11d30102018-11-02 16:09:09 +01001614 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
jiabina84c3d32022-12-02 18:59:55 +00001615 if (prefMixerConfigInfo != nullptr) {
1616 for (audio_io_handle_t outputHandle : outputs) {
1617 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(outputHandle);
1618 if (outputDesc->mProfile == prefMixerConfigInfo->getProfile()) {
1619 output = outputHandle;
1620 break;
1621 }
1622 }
1623 if (output == AUDIO_IO_HANDLE_NONE) {
1624 // No output open with the preferred profile. Open a new one.
1625 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
1626 config.channel_mask = prefMixerConfigInfo->getConfigBase().channel_mask;
1627 config.sample_rate = prefMixerConfigInfo->getConfigBase().sample_rate;
1628 config.format = prefMixerConfigInfo->getConfigBase().format;
1629 sp<SwAudioOutputDescriptor> preferredOutput = openOutputWithProfileAndDevice(
1630 prefMixerConfigInfo->getProfile(), devices, nullptr /*mixerConfig*/,
1631 &config, prefMixerConfigInfo->getFlags());
1632 if (preferredOutput == nullptr) {
1633 ALOGE("%s failed to open output with preferred mixer config", __func__);
1634 } else {
1635 output = preferredOutput->mIoHandle;
1636 }
1637 }
1638 } else {
1639 // at this stage we should ignore the DIRECT flag as no direct output could be
1640 // found earlier
1641 *flags = (audio_output_flags_t) (*flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
1642 output = selectOutput(
1643 outputs, *flags, config->format, channelMask, config->sample_rate, session);
1644 }
Eric Laurente552edb2014-03-10 17:42:56 -07001645 }
François Gaffie11d30102018-11-02 16:09:09 +01001646 ALOGW_IF((output == 0), "getOutputForDevices() could not find output for stream %d, "
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001647 "sampling rate %d, format %#x, channels %#x, flags %#x",
jiabine375d412019-02-26 12:54:53 -08001648 stream, config->sample_rate, config->format, channelMask, *flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001649
Eric Laurente552edb2014-03-10 17:42:56 -07001650 return output;
1651}
1652
Mikhail Naganovf02f3672018-11-09 12:44:16 -08001653sp<DeviceDescriptor> AudioPolicyManager::getMsdAudioInDevice() const {
François Gaffie11d30102018-11-02 16:09:09 +01001654 auto msdInDevices = mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1655 mAvailableInputDevices);
1656 return msdInDevices.isEmpty()? nullptr : msdInDevices.itemAt(0);
1657}
1658
1659DeviceVector AudioPolicyManager::getMsdAudioOutDevices() const {
1660 return mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1661 mAvailableOutputDevices);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001662}
1663
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001664const AudioPatchCollection AudioPolicyManager::getMsdOutputPatches() const {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001665 AudioPatchCollection msdPatches;
Mikhail Naganov86112352018-10-04 09:02:49 -07001666 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1667 if (msdModule != 0) {
1668 for (size_t i = 0; i < mAudioPatches.size(); ++i) {
1669 sp<AudioPatch> patch = mAudioPatches.valueAt(i);
1670 for (size_t j = 0; j < patch->mPatch.num_sources; ++j) {
1671 const struct audio_port_config *source = &patch->mPatch.sources[j];
1672 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
1673 source->ext.device.hw_module == msdModule->getHandle()) {
François Gaffieafd4cea2019-11-18 15:50:22 +01001674 msdPatches.addAudioPatch(patch->getHandle(), patch);
Mikhail Naganov86112352018-10-04 09:02:49 -07001675 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001676 }
1677 }
1678 }
1679 return msdPatches;
1680}
1681
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02001682bool AudioPolicyManager::isMsdPatch(const audio_patch_handle_t &handle) const {
1683 ssize_t index = mAudioPatches.indexOfKey(handle);
1684 if (index < 0) {
1685 return false;
1686 }
1687 const sp<AudioPatch> patch = mAudioPatches.valueAt(index);
1688 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1689 if (msdModule == nullptr) {
1690 return false;
1691 }
1692 const struct audio_port_config *sink = &patch->mPatch.sinks[0];
1693 if (getMsdAudioOutDevices().contains(mAvailableOutputDevices.getDeviceFromId(sink->id))) {
1694 return true;
1695 }
1696 index = getMsdOutputPatches().indexOfKey(handle);
1697 if (index < 0) {
1698 return false;
1699 }
1700 return true;
1701}
1702
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001703status_t AudioPolicyManager::getMsdProfiles(bool hwAvSync,
1704 const InputProfileCollection &inputProfiles,
1705 const OutputProfileCollection &outputProfiles,
1706 const sp<DeviceDescriptor> &sourceDevice,
1707 const sp<DeviceDescriptor> &sinkDevice,
1708 AudioProfileVector& sourceProfiles,
1709 AudioProfileVector& sinkProfiles) const {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001710 if (inputProfiles.isEmpty()) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001711 ALOGE("%s() no input profiles for source module", __func__);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001712 return NO_INIT;
1713 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001714 if (outputProfiles.isEmpty()) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001715 ALOGE("%s() no output profiles for sink module", __func__);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001716 return NO_INIT;
1717 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001718 for (const auto &inProfile : inputProfiles) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001719 if (hwAvSync == ((inProfile->getFlags() & AUDIO_INPUT_FLAG_HW_AV_SYNC) != 0) &&
1720 inProfile->supportsDevice(sourceDevice)) {
1721 appendAudioProfiles(sourceProfiles, inProfile->getAudioProfiles());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001722 }
1723 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001724 for (const auto &outProfile : outputProfiles) {
Michael Chan6fb34492020-12-08 15:44:49 +11001725 if (hwAvSync == ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) &&
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001726 outProfile->supportsDevice(sinkDevice)) {
1727 appendAudioProfiles(sinkProfiles, outProfile->getAudioProfiles());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001728 }
1729 }
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001730 return NO_ERROR;
1731}
1732
1733status_t AudioPolicyManager::getBestMsdConfig(bool hwAvSync,
1734 const AudioProfileVector &sourceProfiles, const AudioProfileVector &sinkProfiles,
1735 audio_port_config *sourceConfig, audio_port_config *sinkConfig) const
1736{
Dean Wheatley16809da2022-12-09 14:55:46 +11001737 // Compressed formats for MSD module, ordered from most preferred to least preferred.
1738 static const std::vector<audio_format_t> formatsOrder = {{
1739 AUDIO_FORMAT_IEC60958, AUDIO_FORMAT_MAT_2_1, AUDIO_FORMAT_MAT_2_0, AUDIO_FORMAT_E_AC3,
Dean Wheatley0f27c602023-08-23 13:57:21 +10001740 AUDIO_FORMAT_AC3, AUDIO_FORMAT_PCM_FLOAT, AUDIO_FORMAT_PCM_32_BIT,
1741 AUDIO_FORMAT_PCM_8_24_BIT, AUDIO_FORMAT_PCM_24_BIT_PACKED, AUDIO_FORMAT_PCM_16_BIT }};
Dean Wheatley16809da2022-12-09 14:55:46 +11001742 static const std::vector<audio_channel_mask_t> channelMasksOrder = [](){
1743 // Channel position masks for MSD module, 3D > 2D > 1D ordering (most preferred to least
1744 // preferred).
1745 std::vector<audio_channel_mask_t> masks = {{
1746 AUDIO_CHANNEL_OUT_3POINT1POINT2, AUDIO_CHANNEL_OUT_3POINT0POINT2,
1747 AUDIO_CHANNEL_OUT_2POINT1POINT2, AUDIO_CHANNEL_OUT_2POINT0POINT2,
1748 AUDIO_CHANNEL_OUT_5POINT1, AUDIO_CHANNEL_OUT_STEREO }};
1749 // insert index masks (higher counts most preferred) as preferred over position masks
1750 for (int i = 1; i <= AUDIO_CHANNEL_COUNT_MAX; i++) {
1751 masks.insert(
1752 masks.begin(), audio_channel_mask_for_index_assignment_from_count(i));
1753 }
1754 return masks;
1755 }();
1756
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001757 struct audio_config_base bestSinkConfig;
Dean Wheatley16809da2022-12-09 14:55:46 +11001758 status_t result = findBestMatchingOutputConfig(sourceProfiles, sinkProfiles, formatsOrder,
1759 channelMasksOrder, true /*preferHigherSamplingRates*/, bestSinkConfig);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001760 if (result != NO_ERROR) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001761 ALOGD("%s() no matching config found for sink, hwAvSync: %d",
1762 __func__, hwAvSync);
Greg Kaiser83289652018-07-30 06:13:57 -07001763 return result;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001764 }
1765 sinkConfig->sample_rate = bestSinkConfig.sample_rate;
1766 sinkConfig->channel_mask = bestSinkConfig.channel_mask;
1767 sinkConfig->format = bestSinkConfig.format;
1768 // For encoded streams force direct flag to prevent downstream mixing.
1769 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1770 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_DIRECT);
Dean Wheatley5c9f0832019-11-21 13:39:31 +11001771 if (audio_is_iec61937_compatible(sinkConfig->format)) {
1772 // For formats compatible with IEC61937 encapsulation, assume that
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001773 // the input is IEC61937 framed (for proportional buffer sizing).
Dean Wheatley5c9f0832019-11-21 13:39:31 +11001774 // Add the AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO flag so downstream HAL can distinguish between
1775 // raw and IEC61937 framed streams.
1776 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1777 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO);
1778 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001779 sourceConfig->sample_rate = bestSinkConfig.sample_rate;
1780 // Specify exact channel mask to prevent guessing by bit count in PatchPanel.
Dean Wheatley16809da2022-12-09 14:55:46 +11001781 sourceConfig->channel_mask =
1782 audio_channel_mask_get_representation(bestSinkConfig.channel_mask)
1783 == AUDIO_CHANNEL_REPRESENTATION_INDEX ?
1784 bestSinkConfig.channel_mask : audio_channel_mask_out_to_in(bestSinkConfig.channel_mask);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001785 sourceConfig->format = bestSinkConfig.format;
1786 // Copy input stream directly without any processing (e.g. resampling).
1787 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1788 sourceConfig->flags.input | AUDIO_INPUT_FLAG_DIRECT);
1789 if (hwAvSync) {
1790 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1791 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
1792 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1793 sourceConfig->flags.input | AUDIO_INPUT_FLAG_HW_AV_SYNC);
1794 }
1795 const unsigned int config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE |
1796 AUDIO_PORT_CONFIG_CHANNEL_MASK | AUDIO_PORT_CONFIG_FORMAT | AUDIO_PORT_CONFIG_FLAGS;
1797 sinkConfig->config_mask |= config_mask;
1798 sourceConfig->config_mask |= config_mask;
1799 return NO_ERROR;
1800}
1801
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001802PatchBuilder AudioPolicyManager::buildMsdPatch(bool msdIsSource,
1803 const sp<DeviceDescriptor> &device) const
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001804{
1805 PatchBuilder patchBuilder;
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001806 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1807 ALOG_ASSERT(msdModule != nullptr, "MSD module not available");
1808 sp<HwModule> deviceModule = mHwModules.getModuleForDevice(device, AUDIO_FORMAT_DEFAULT);
1809 if (deviceModule == nullptr) {
1810 ALOGE("%s() unable to get module for %s", __func__, device->toString().c_str());
1811 return patchBuilder;
1812 }
1813 const InputProfileCollection inputProfiles = msdIsSource ?
1814 msdModule->getInputProfiles() : deviceModule->getInputProfiles();
1815 const OutputProfileCollection outputProfiles = msdIsSource ?
1816 deviceModule->getOutputProfiles() : msdModule->getOutputProfiles();
1817
1818 const sp<DeviceDescriptor> sourceDevice = msdIsSource ? getMsdAudioInDevice() : device;
1819 const sp<DeviceDescriptor> sinkDevice = msdIsSource ?
1820 device : getMsdAudioOutDevices().itemAt(0);
1821 patchBuilder.addSource(sourceDevice).addSink(sinkDevice);
1822
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001823 audio_port_config sourceConfig = patchBuilder.patch()->sources[0];
1824 audio_port_config sinkConfig = patchBuilder.patch()->sinks[0];
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001825 AudioProfileVector sourceProfiles;
1826 AudioProfileVector sinkProfiles;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001827 // TODO: Figure out whether MSD module has HW_AV_SYNC flag set in the AP config file.
1828 // For now, we just forcefully try with HwAvSync first.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001829 for (auto hwAvSync : { true, false }) {
1830 if (getMsdProfiles(hwAvSync, inputProfiles, outputProfiles, sourceDevice, sinkDevice,
1831 sourceProfiles, sinkProfiles) != NO_ERROR) {
1832 continue;
1833 }
1834 if (getBestMsdConfig(hwAvSync, sourceProfiles, sinkProfiles, &sourceConfig,
1835 &sinkConfig) == NO_ERROR) {
1836 // Found a matching config. Re-create PatchBuilder with this config.
1837 return (PatchBuilder()).addSource(sourceConfig).addSink(sinkConfig);
1838 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001839 }
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001840 ALOGV("%s() no matching config found. Fall through to default PCM patch"
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001841 " supporting PCM format conversion.", __func__);
1842 return patchBuilder;
1843}
1844
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001845status_t AudioPolicyManager::setMsdOutputPatches(const DeviceVector *outputDevices) {
Michael Chan6fb34492020-12-08 15:44:49 +11001846 DeviceVector devices;
1847 if (outputDevices != nullptr && outputDevices->size() > 0) {
1848 devices.add(*outputDevices);
1849 } else {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001850 // Use media strategy for unspecified output device. This should only
1851 // occur on checkForDeviceAndOutputChanges(). Device connection events may
1852 // therefore invalidate explicit routing requests.
Michael Chan6fb34492020-12-08 15:44:49 +11001853 devices = mEngine->getOutputDevicesForAttributes(
François Gaffiec005e562018-11-06 15:04:49 +01001854 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
Michael Chan6fb34492020-12-08 15:44:49 +11001855 LOG_ALWAYS_FATAL_IF(devices.isEmpty(), "no output device to set MSD patch");
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001856 }
Michael Chan6fb34492020-12-08 15:44:49 +11001857 std::vector<PatchBuilder> patchesToCreate;
1858 for (auto i = 0u; i < devices.size(); ++i) {
1859 ALOGV("%s() for device %s", __func__, devices[i]->toString().c_str());
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001860 patchesToCreate.push_back(buildMsdPatch(true /*msdIsSource*/, devices[i]));
Michael Chan6fb34492020-12-08 15:44:49 +11001861 }
1862 // Retain only the MSD patches associated with outputDevices request.
1863 // Tear down the others, and create new ones as needed.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001864 AudioPatchCollection patchesToRemove = getMsdOutputPatches();
Michael Chan6fb34492020-12-08 15:44:49 +11001865 for (auto it = patchesToCreate.begin(); it != patchesToCreate.end(); ) {
1866 auto retainedPatch = false;
1867 for (auto i = 0u; i < patchesToRemove.size(); ++i) {
1868 if (audio_patches_are_equal(it->patch(), &patchesToRemove[i]->mPatch)) {
1869 patchesToRemove.removeItemsAt(i);
1870 retainedPatch = true;
1871 break;
1872 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001873 }
Michael Chan6fb34492020-12-08 15:44:49 +11001874 if (retainedPatch) {
1875 it = patchesToCreate.erase(it);
1876 continue;
1877 }
1878 ++it;
1879 }
1880 if (patchesToCreate.size() == 0 && patchesToRemove.size() == 0) {
1881 return NO_ERROR;
1882 }
1883 for (auto i = 0u; i < patchesToRemove.size(); ++i) {
1884 auto &currentPatch = patchesToRemove.valueAt(i);
François Gaffieafd4cea2019-11-18 15:50:22 +01001885 releaseAudioPatch(currentPatch->getHandle(), mUidCached);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001886 }
Michael Chan6fb34492020-12-08 15:44:49 +11001887 status_t status = NO_ERROR;
1888 for (const auto &p : patchesToCreate) {
1889 auto currStatus = installPatch(__func__, -1 /*index*/, nullptr /*patchHandle*/,
1890 p.patch(), 0 /*delayMs*/, mUidCached, nullptr /*patchDescPtr*/);
1891 char message[256];
1892 snprintf(message, sizeof(message), "%s() %s: creating MSD patch from device:IN_BUS to "
1893 "device:%#x (format:%#x channels:%#x samplerate:%d)", __func__,
1894 currStatus == NO_ERROR ? "Success" : "Error",
1895 p.patch()->sinks[0].ext.device.type, p.patch()->sources[0].format,
1896 p.patch()->sources[0].channel_mask, p.patch()->sources[0].sample_rate);
1897 if (currStatus == NO_ERROR) {
1898 ALOGD("%s", message);
1899 } else {
1900 ALOGE("%s", message);
1901 if (status == NO_ERROR) {
1902 status = currStatus;
1903 }
1904 }
1905 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001906 return status;
1907}
1908
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001909void AudioPolicyManager::releaseMsdOutputPatches(const DeviceVector& devices) {
1910 AudioPatchCollection msdPatches = getMsdOutputPatches();
Michael Chan6fb34492020-12-08 15:44:49 +11001911 for (size_t i = 0; i < msdPatches.size(); i++) {
1912 const auto& patch = msdPatches[i];
1913 for (size_t j = 0; j < patch->mPatch.num_sinks; ++j) {
1914 const struct audio_port_config *sink = &patch->mPatch.sinks[j];
1915 if (sink->type == AUDIO_PORT_TYPE_DEVICE && devices.getDevice(sink->ext.device.type,
1916 String8(sink->ext.device.address), AUDIO_FORMAT_DEFAULT) != nullptr) {
1917 releaseAudioPatch(patch->getHandle(), mUidCached);
1918 break;
1919 }
1920 }
1921 }
1922}
1923
Dorin Drimus94d94412022-02-02 09:05:02 +01001924bool AudioPolicyManager::msdHasPatchesToAllDevices(const AudioDeviceTypeAddrVector& devices) {
Mikhail Naganov68e3f642023-04-28 13:06:32 -07001925 DeviceVector devicesToCheck =
1926 mConfig->getOutputDevices().getDevicesFromDeviceTypeAddrVec(devices);
Dorin Drimus94d94412022-02-02 09:05:02 +01001927 AudioPatchCollection msdPatches = getMsdOutputPatches();
1928 for (size_t i = 0; i < msdPatches.size(); i++) {
1929 const auto& patch = msdPatches[i];
1930 for (size_t j = 0; j < patch->mPatch.num_sinks; ++j) {
1931 const struct audio_port_config *sink = &patch->mPatch.sinks[j];
1932 if (sink->type == AUDIO_PORT_TYPE_DEVICE) {
1933 const auto& foundDevice = devicesToCheck.getDevice(
1934 sink->ext.device.type, String8(sink->ext.device.address), AUDIO_FORMAT_DEFAULT);
1935 if (foundDevice != nullptr) {
1936 devicesToCheck.remove(foundDevice);
1937 if (devicesToCheck.isEmpty()) {
1938 return true;
1939 }
1940 }
1941 }
1942 }
1943 }
1944 return false;
1945}
1946
Eric Laurente0720872014-03-11 09:30:41 -07001947audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
jiabinebb6af42020-06-09 17:31:17 -07001948 audio_output_flags_t flags,
1949 audio_format_t format,
1950 audio_channel_mask_t channelMask,
1951 uint32_t samplingRate,
1952 audio_session_t sessionId)
Eric Laurente552edb2014-03-10 17:42:56 -07001953{
Eric Laurent16c66dd2019-05-01 17:54:10 -07001954 LOG_ALWAYS_FATAL_IF(!(format == AUDIO_FORMAT_INVALID || audio_is_linear_pcm(format)),
1955 "%s called with format %#x", __func__, format);
1956
jiabinebb6af42020-06-09 17:31:17 -07001957 // Return the output that haptic-generating attached to when 1) session id is specified,
1958 // 2) haptic-generating effect exists for given session id and 3) the output that
1959 // haptic-generating effect attached to is in given outputs.
1960 if (sessionId != AUDIO_SESSION_NONE) {
1961 audio_io_handle_t hapticGeneratingOutput = mEffects.getIoForSession(
1962 sessionId, FX_IID_HAPTICGENERATOR);
1963 if (outputs.indexOf(hapticGeneratingOutput) >= 0) {
1964 return hapticGeneratingOutput;
1965 }
1966 }
1967
Eric Laurent16c66dd2019-05-01 17:54:10 -07001968 // Flags disqualifying an output: the match must happen before calling selectOutput()
1969 static const audio_output_flags_t kExcludedFlags = (audio_output_flags_t)
1970 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ | AUDIO_OUTPUT_FLAG_DIRECT);
1971
1972 // Flags expressing a functional request: must be honored in priority over
1973 // other criteria
1974 static const audio_output_flags_t kFunctionalFlags = (audio_output_flags_t)
1975 (AUDIO_OUTPUT_FLAG_VOIP_RX | AUDIO_OUTPUT_FLAG_INCALL_MUSIC |
Eric Laurente28c66d2022-01-21 13:40:41 +01001976 AUDIO_OUTPUT_FLAG_TTS | AUDIO_OUTPUT_FLAG_DIRECT_PCM | AUDIO_OUTPUT_FLAG_ULTRASOUND |
1977 AUDIO_OUTPUT_FLAG_SPATIALIZER);
Eric Laurent16c66dd2019-05-01 17:54:10 -07001978 // Flags expressing a performance request: have lower priority than serving
1979 // requested sampling rate or channel mask
1980 static const audio_output_flags_t kPerformanceFlags = (audio_output_flags_t)
1981 (AUDIO_OUTPUT_FLAG_FAST | AUDIO_OUTPUT_FLAG_DEEP_BUFFER |
1982 AUDIO_OUTPUT_FLAG_RAW | AUDIO_OUTPUT_FLAG_SYNC);
1983
1984 const audio_output_flags_t functionalFlags =
1985 (audio_output_flags_t)(flags & kFunctionalFlags);
1986 const audio_output_flags_t performanceFlags =
1987 (audio_output_flags_t)(flags & kPerformanceFlags);
1988
1989 audio_io_handle_t bestOutput = (outputs.size() == 0) ? AUDIO_IO_HANDLE_NONE : outputs[0];
1990
Eric Laurente552edb2014-03-10 17:42:56 -07001991 // select one output among several that provide a path to a particular device or set of
François Gaffie11d30102018-11-02 16:09:09 +01001992 // devices (the list was previously build by getOutputsForDevices()).
Eric Laurente552edb2014-03-10 17:42:56 -07001993 // The priority is as follows:
jiabin40573322018-11-08 12:08:02 -08001994 // 1: the output supporting haptic playback when requesting haptic playback
Eric Laurent16c66dd2019-05-01 17:54:10 -07001995 // 2: the output with the highest number of requested functional flags
Carter Hsu199f1892021-10-15 15:47:29 +08001996 // with tiebreak preferring the minimum number of extra functional flags
1997 // (see b/200293124, the incorrect selection of AUDIO_OUTPUT_FLAG_VOIP_RX).
Eric Laurent16c66dd2019-05-01 17:54:10 -07001998 // 3: the output supporting the exact channel mask
1999 // 4: the output with a higher channel count than requested
jiabinb12a6da2022-06-03 20:48:18 +00002000 // 5: the output with the highest sampling rate if the requested sample rate is
2001 // greater than default sampling rate
Eric Laurent16c66dd2019-05-01 17:54:10 -07002002 // 6: the output with the highest number of requested performance flags
2003 // 7: the output with the bit depth the closest to the requested one
2004 // 8: the primary output
2005 // 9: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07002006
Eric Laurent16c66dd2019-05-01 17:54:10 -07002007 // matching criteria values in priority order for best matching output so far
2008 std::vector<uint32_t> bestMatchCriteria(8, 0);
Eric Laurente552edb2014-03-10 17:42:56 -07002009
Eric Laurent16c66dd2019-05-01 17:54:10 -07002010 const uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
2011 const uint32_t hapticChannelCount = audio_channel_count_from_out_mask(
2012 channelMask & AUDIO_CHANNEL_HAPTIC_ALL);
Eric Laurente78b6762018-12-19 16:29:01 -08002013
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002014 for (audio_io_handle_t output : outputs) {
2015 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent16c66dd2019-05-01 17:54:10 -07002016 // matching criteria values in priority order for current output
2017 std::vector<uint32_t> currentMatchCriteria(8, 0);
jiabin40573322018-11-08 12:08:02 -08002018
Eric Laurent16c66dd2019-05-01 17:54:10 -07002019 if (outputDesc->isDuplicated()) {
2020 continue;
2021 }
2022 if ((kExcludedFlags & outputDesc->mFlags) != 0) {
2023 continue;
2024 }
Eric Laurent8838a382014-09-08 16:44:28 -07002025
Eric Laurent16c66dd2019-05-01 17:54:10 -07002026 // If haptic channel is specified, use the haptic output if present.
2027 // When using haptic output, same audio format and sample rate are required.
2028 const uint32_t outputHapticChannelCount = audio_channel_count_from_out_mask(
jiabin5740f082019-08-19 15:08:30 -07002029 outputDesc->getChannelMask() & AUDIO_CHANNEL_HAPTIC_ALL);
Eric Laurent16c66dd2019-05-01 17:54:10 -07002030 if ((hapticChannelCount == 0) != (outputHapticChannelCount == 0)) {
2031 continue;
2032 }
2033 if (outputHapticChannelCount >= hapticChannelCount
jiabin5740f082019-08-19 15:08:30 -07002034 && format == outputDesc->getFormat()
2035 && samplingRate == outputDesc->getSamplingRate()) {
Eric Laurent16c66dd2019-05-01 17:54:10 -07002036 currentMatchCriteria[0] = outputHapticChannelCount;
2037 }
2038
2039 // functional flags match
Carter Hsu199f1892021-10-15 15:47:29 +08002040 const int matchingFunctionalFlags =
2041 __builtin_popcount(outputDesc->mFlags & functionalFlags);
2042 const int totalFunctionalFlags =
2043 __builtin_popcount(outputDesc->mFlags & kFunctionalFlags);
2044 // Prefer matching functional flags, but subtract unnecessary functional flags.
2045 currentMatchCriteria[1] = 100 * (matchingFunctionalFlags + 1) - totalFunctionalFlags;
Eric Laurent16c66dd2019-05-01 17:54:10 -07002046
2047 // channel mask and channel count match
jiabin5740f082019-08-19 15:08:30 -07002048 uint32_t outputChannelCount = audio_channel_count_from_out_mask(
2049 outputDesc->getChannelMask());
Eric Laurent16c66dd2019-05-01 17:54:10 -07002050 if (channelMask != AUDIO_CHANNEL_NONE && channelCount > 2 &&
2051 channelCount <= outputChannelCount) {
2052 if ((audio_channel_mask_get_representation(channelMask) ==
jiabin5740f082019-08-19 15:08:30 -07002053 audio_channel_mask_get_representation(outputDesc->getChannelMask())) &&
2054 ((channelMask & outputDesc->getChannelMask()) == channelMask)) {
Eric Laurent16c66dd2019-05-01 17:54:10 -07002055 currentMatchCriteria[2] = outputChannelCount;
Eric Laurente552edb2014-03-10 17:42:56 -07002056 }
Eric Laurent16c66dd2019-05-01 17:54:10 -07002057 currentMatchCriteria[3] = outputChannelCount;
2058 }
2059
2060 // sampling rate match
jiabinb12a6da2022-06-03 20:48:18 +00002061 if (samplingRate > SAMPLE_RATE_HZ_DEFAULT) {
jiabin5740f082019-08-19 15:08:30 -07002062 currentMatchCriteria[4] = outputDesc->getSamplingRate();
Eric Laurent16c66dd2019-05-01 17:54:10 -07002063 }
2064
2065 // performance flags match
2066 currentMatchCriteria[5] = popcount(outputDesc->mFlags & performanceFlags);
2067
2068 // format match
2069 if (format != AUDIO_FORMAT_INVALID) {
2070 currentMatchCriteria[6] =
jiabin4ef93452019-09-10 14:29:54 -07002071 PolicyAudioPort::kFormatDistanceMax -
2072 PolicyAudioPort::formatDistance(format, outputDesc->getFormat());
Eric Laurent16c66dd2019-05-01 17:54:10 -07002073 }
2074
2075 // primary output match
2076 currentMatchCriteria[7] = outputDesc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY;
2077
2078 // compare match criteria by priority then value
2079 if (std::lexicographical_compare(bestMatchCriteria.begin(), bestMatchCriteria.end(),
2080 currentMatchCriteria.begin(), currentMatchCriteria.end())) {
2081 bestMatchCriteria = currentMatchCriteria;
2082 bestOutput = output;
2083
2084 std::stringstream result;
2085 std::copy(bestMatchCriteria.begin(), bestMatchCriteria.end(),
2086 std::ostream_iterator<int>(result, " "));
2087 ALOGV("%s new bestOutput %d criteria %s",
2088 __func__, bestOutput, result.str().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07002089 }
2090 }
2091
Eric Laurent16c66dd2019-05-01 17:54:10 -07002092 return bestOutput;
Eric Laurente552edb2014-03-10 17:42:56 -07002093}
2094
Eric Laurent8fc147b2018-07-22 19:13:55 -07002095status_t AudioPolicyManager::startOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002096{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002097 ALOGV("%s portId %d", __FUNCTION__, portId);
2098
2099 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2100 if (outputDesc == 0) {
2101 ALOGW("startOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002102 return BAD_VALUE;
2103 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002104 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002105
Eric Laurent8fc147b2018-07-22 19:13:55 -07002106 ALOGV("startOutput() output %d, stream %d, session %d",
Eric Laurent97ac8712018-07-27 18:59:02 -07002107 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurentc75307b2015-03-17 15:29:32 -07002108
Eric Laurent733ce942017-12-07 12:18:25 -08002109 status_t status = outputDesc->start();
2110 if (status != NO_ERROR) {
2111 return status;
Eric Laurent3974e3b2017-12-07 17:58:43 -08002112 }
2113
Eric Laurent97ac8712018-07-27 18:59:02 -07002114 uint32_t delayMs;
2115 status = startSource(outputDesc, client, &delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07002116
2117 if (status != NO_ERROR) {
Eric Laurent733ce942017-12-07 12:18:25 -08002118 outputDesc->stop();
jiabin3ff8d7d2022-12-13 06:27:44 +00002119 if (status == DEAD_OBJECT) {
2120 sp<SwAudioOutputDescriptor> desc =
2121 reopenOutput(outputDesc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
2122 if (desc == nullptr) {
2123 // This is not common, it may indicate something wrong with the HAL.
2124 ALOGE("%s unable to open output with default config", __func__);
2125 return status;
2126 }
2127 desc->mUsePreferredMixerAttributes = true;
2128 }
Eric Laurent8c7e6da2015-04-21 17:37:00 -07002129 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07002130 }
jiabina84c3d32022-12-02 18:59:55 +00002131
2132 // If the client is the first one active on preferred mixer parameters, reopen the output
2133 // if the current mixer parameters doesn't match the preferred one.
2134 if (outputDesc->devices().size() == 1) {
2135 sp<PreferredMixerAttributesInfo> info = getPreferredMixerAttributesInfo(
2136 outputDesc->devices()[0]->getId(), client->strategy());
2137 if (info != nullptr && info->getUid() == client->uid()) {
2138 if (info->getActiveClientCount() == 0 && !outputDesc->isConfigurationMatched(
2139 info->getConfigBase(), info->getFlags())) {
2140 stopSource(outputDesc, client);
2141 outputDesc->stop();
2142 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
2143 config.channel_mask = info->getConfigBase().channel_mask;
2144 config.sample_rate = info->getConfigBase().sample_rate;
2145 config.format = info->getConfigBase().format;
jiabin3ff8d7d2022-12-13 06:27:44 +00002146 sp<SwAudioOutputDescriptor> desc =
2147 reopenOutput(outputDesc, &config, info->getFlags(), __func__);
2148 if (desc == nullptr) {
2149 return BAD_VALUE;
jiabina84c3d32022-12-02 18:59:55 +00002150 }
jiabin3ff8d7d2022-12-13 06:27:44 +00002151 desc->mUsePreferredMixerAttributes = true;
jiabina84c3d32022-12-02 18:59:55 +00002152 // Intentionally return error to let the client side resending request for
2153 // creating and starting.
2154 return DEAD_OBJECT;
2155 }
2156 info->increaseActiveClient();
jiabine3d1f552023-06-14 17:42:17 +00002157 if (info->getActiveClientCount() == 1 &&
2158 (info->getFlags() & AUDIO_OUTPUT_FLAG_BIT_PERFECT) != AUDIO_OUTPUT_FLAG_NONE) {
2159 // If it is first bit-perfect client, reroute all clients that will be routed to
2160 // the bit-perfect sink so that it is guaranteed only bit-perfect stream is active.
2161 PortHandleVector clientsToInvalidate;
2162 for (size_t i = 0; i < mOutputs.size(); i++) {
2163 if (mOutputs[i] == outputDesc ||
jiabin98c519c2023-07-05 17:34:21 +00002164 mOutputs[i]->devices().filter(outputDesc->devices()).isEmpty()) {
jiabine3d1f552023-06-14 17:42:17 +00002165 continue;
2166 }
2167 for (const auto& c : mOutputs[i]->getClientIterable()) {
2168 clientsToInvalidate.push_back(c->portId());
2169 }
2170 }
2171 if (!clientsToInvalidate.empty()) {
2172 ALOGD("%s Invalidate clients due to first bit-perfect client started",
2173 __func__);
2174 mpClientInterface->invalidateTracks(clientsToInvalidate);
2175 }
2176 }
jiabina84c3d32022-12-02 18:59:55 +00002177 }
2178 }
2179
Jean-Michel Trivib1f6e642023-02-07 20:49:04 +00002180 if (client->hasPreferredDevice()) {
2181 // playback activity with preferred device impacts routing occurred, inform upper layers
2182 mpClientInterface->onRoutingUpdated();
2183 }
Eric Laurentc75307b2015-03-17 15:29:32 -07002184 if (delayMs != 0) {
2185 usleep(delayMs * 1000);
2186 }
2187
2188 return status;
2189}
2190
Eric Laurent96d1dda2022-03-14 17:14:19 +01002191bool AudioPolicyManager::isLeUnicastActive() const {
2192 if (isInCall()) {
2193 return true;
2194 }
2195 return isAnyDeviceTypeActive(getAudioDeviceOutLeAudioUnicastSet());
2196}
2197
2198bool AudioPolicyManager::isAnyDeviceTypeActive(const DeviceTypeSet& deviceTypes) const {
2199 if (mAvailableOutputDevices.getDevicesFromTypes(deviceTypes).isEmpty()) {
2200 return false;
2201 }
2202 bool active = mOutputs.isAnyDeviceTypeActive(deviceTypes);
2203 ALOGV("%s active %d", __func__, active);
2204 return active;
2205}
2206
Eric Laurent97ac8712018-07-27 18:59:02 -07002207status_t AudioPolicyManager::startSource(const sp<SwAudioOutputDescriptor>& outputDesc,
2208 const sp<TrackClientDescriptor>& client,
2209 uint32_t *delayMs)
Eric Laurentc75307b2015-03-17 15:29:32 -07002210{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002211 // cannot start playback of STREAM_TTS if any other output is being used
2212 uint32_t beaconMuteLatency = 0;
Eric Laurentc75307b2015-03-17 15:29:32 -07002213
2214 *delayMs = 0;
Eric Laurent97ac8712018-07-27 18:59:02 -07002215 audio_stream_type_t stream = client->stream();
François Gaffie1c878552018-11-22 16:53:21 +01002216 auto clientVolSrc = client->volumeSource();
François Gaffiec005e562018-11-06 15:04:49 +01002217 auto clientStrategy = client->strategy();
2218 auto clientAttr = client->attributes();
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002219 if (stream == AUDIO_STREAM_TTS) {
2220 ALOGV("\t found BEACON stream");
François Gaffie1c878552018-11-22 16:53:21 +01002221 if (!mTtsOutputAvailable && mOutputs.isAnyOutputActive(
Francois Gaffie4404ddb2021-02-04 17:03:38 +01002222 toVolumeSource(AUDIO_STREAM_TTS, false) /*sourceToIgnore*/)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002223 return INVALID_OPERATION;
2224 } else {
2225 beaconMuteLatency = handleEventForBeacon(STARTING_BEACON);
2226 }
2227 } else {
2228 // some playback other than beacon starts
2229 beaconMuteLatency = handleEventForBeacon(STARTING_OUTPUT);
2230 }
2231
Eric Laurent77305a62016-07-25 16:39:22 -07002232 // force device change if the output is inactive and no audio patch is already present.
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002233 // check active before incrementing usage count
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02002234 bool force = !outputDesc->isActive() && !outputDesc->isRouted();
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002235
François Gaffie11d30102018-11-02 16:09:09 +01002236 DeviceVector devices;
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002237 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
Eric Laurent97ac8712018-07-27 18:59:02 -07002238 const char *address = NULL;
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002239 if (policyMix != nullptr) {
François Gaffie11d30102018-11-02 16:09:09 +01002240 audio_devices_t newDeviceType;
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00002241 address = policyMix->mDeviceAddress.c_str();
Kevin Rocard153f92d2018-12-18 18:33:28 -08002242 if ((policyMix->mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie11d30102018-11-02 16:09:09 +01002243 newDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Kevin Rocard153f92d2018-12-18 18:33:28 -08002244 } else {
2245 newDeviceType = policyMix->mDeviceType;
Eric Laurent97ac8712018-07-27 18:59:02 -07002246 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08002247 sp device = mAvailableOutputDevices.getDevice(newDeviceType, String8(address),
2248 AUDIO_FORMAT_DEFAULT);
2249 ALOG_ASSERT(device, "%s: no device found t=%u, a=%s", __func__, newDeviceType, address);
2250 devices.add(device);
Eric Laurent97ac8712018-07-27 18:59:02 -07002251 }
2252
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002253 // requiresMuteCheck is false when we can bypass mute strategy.
2254 // It covers a common case when there is no materially active audio
2255 // and muting would result in unnecessary delay and dropped audio.
2256 const uint32_t outputLatencyMs = outputDesc->latency();
2257 bool requiresMuteCheck = outputDesc->isActive(outputLatencyMs * 2); // account for drain
Eric Laurent96d1dda2022-03-14 17:14:19 +01002258 bool wasLeUnicastActive = isLeUnicastActive();
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002259
Eric Laurente552edb2014-03-10 17:42:56 -07002260 // increment usage count for this stream on the requested output:
2261 // NOTE that the usage count is the same for duplicated output and hardware output which is
2262 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
Eric Laurent592dd7b2018-08-05 18:58:48 -07002263 outputDesc->setClientActive(client, true);
Eric Laurent97ac8712018-07-27 18:59:02 -07002264
2265 if (client->hasPreferredDevice(true)) {
Eric Laurent72af8012023-03-15 17:36:22 +01002266 if (outputDesc->sameExclusivePreferredDevicesCount() > 0) {
François Gaffief96e5432019-04-09 17:13:56 +02002267 // Preferred device may be exclusive, use only if no other active clients on this output
2268 devices = DeviceVector(
2269 mAvailableOutputDevices.getDeviceFromId(client->preferredDeviceId()));
2270 } else {
2271 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
2272 }
François Gaffie11d30102018-11-02 16:09:09 +01002273 if (devices != outputDesc->devices()) {
François Gaffiec005e562018-11-06 15:04:49 +01002274 checkStrategyRoute(clientStrategy, outputDesc->mIoHandle);
Eric Laurent97ac8712018-07-27 18:59:02 -07002275 }
2276 }
Eric Laurente552edb2014-03-10 17:42:56 -07002277
François Gaffiec005e562018-11-06 15:04:49 +01002278 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07002279 selectOutputForMusicEffects();
2280 }
2281
François Gaffie1c878552018-11-22 16:53:21 +01002282 if (outputDesc->getActivityCount(clientVolSrc) == 1 || !devices.isEmpty()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08002283 // starting an output being rerouted?
François Gaffie11d30102018-11-02 16:09:09 +01002284 if (devices.isEmpty()) {
2285 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Eric Laurent275e8e92014-11-30 15:14:47 -08002286 }
François Gaffiec005e562018-11-06 15:04:49 +01002287 bool shouldWait =
2288 (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM)) ||
2289 followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_NOTIFICATION)) ||
2290 (beaconMuteLatency > 0));
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002291 uint32_t waitMs = beaconMuteLatency;
Eric Laurente552edb2014-03-10 17:42:56 -07002292 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01002293 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07002294 if (desc != outputDesc) {
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002295 // An output has a shared device if
2296 // - managed by the same hw module
2297 // - supports the currently selected device
2298 const bool sharedDevice = outputDesc->sharesHwModuleWith(desc)
François Gaffie11d30102018-11-02 16:09:09 +01002299 && (!desc->filterSupportedDevices(devices).isEmpty());
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002300
Eric Laurent77305a62016-07-25 16:39:22 -07002301 // force a device change if any other output is:
2302 // - managed by the same hw module
Jean-Michel Trivi4a5b4812018-02-08 17:22:32 +00002303 // - supports currently selected device
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002304 // - has a current device selection that differs from selected device.
Eric Laurent77305a62016-07-25 16:39:22 -07002305 // - has an active audio patch
Eric Laurente552edb2014-03-10 17:42:56 -07002306 // In this case, the audio HAL must receive the new device selection so that it can
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002307 // change the device currently selected by the other output.
2308 if (sharedDevice &&
François Gaffie11d30102018-11-02 16:09:09 +01002309 desc->devices() != devices &&
Eric Laurent77305a62016-07-25 16:39:22 -07002310 desc->getPatchHandle() != AUDIO_PATCH_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07002311 force = true;
2312 }
2313 // wait for audio on other active outputs to be presented when starting
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002314 // a notification so that audio focus effect can propagate, or that a mute/unmute
2315 // event occurred for beacon
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002316 const uint32_t latencyMs = desc->latency();
2317 const bool isActive = desc->isActive(latencyMs * 2); // account for drain
2318
2319 if (shouldWait && isActive && (waitMs < latencyMs)) {
2320 waitMs = latencyMs;
Eric Laurente552edb2014-03-10 17:42:56 -07002321 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002322
2323 // Require mute check if another output is on a shared device
2324 // and currently active to have proper drain and avoid pops.
2325 // Note restoring AudioTracks onto this output needs to invoke
2326 // a volume ramp if there is no mute.
2327 requiresMuteCheck |= sharedDevice && isActive;
Eric Laurente552edb2014-03-10 17:42:56 -07002328 }
2329 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002330
jiabin3ff8d7d2022-12-13 06:27:44 +00002331 if (outputDesc->mUsePreferredMixerAttributes && devices != outputDesc->devices()) {
2332 // If the output is open with preferred mixer attributes, but the routed device is
2333 // changed when calling this function, returning DEAD_OBJECT to indicate routing
2334 // changed.
2335 return DEAD_OBJECT;
2336 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002337 const uint32_t muteWaitMs =
jiabin3ff8d7d2022-12-13 06:27:44 +00002338 setOutputDevices(outputDesc, devices, force, 0, nullptr, requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07002339
Eric Laurente552edb2014-03-10 17:42:56 -07002340 // apply volume rules for current stream and device if necessary
François Gaffieaaac0fd2018-11-22 17:56:39 +01002341 auto &curves = getVolumeCurves(client->attributes());
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00002342 if (NO_ERROR != checkAndSetVolume(curves, client->volumeSource(),
François Gaffieaaac0fd2018-11-22 17:56:39 +01002343 curves.getVolumeIndex(outputDesc->devices().types()),
Eric Laurentc75307b2015-03-17 15:29:32 -07002344 outputDesc,
Francois Gaffied11442b2020-04-27 11:51:09 +02002345 outputDesc->devices().types(), 0 /*delay*/,
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00002346 outputDesc->useHwGain() /*force*/)) {
2347 // request AudioService to reinitialize the volume curves asynchronously
2348 ALOGE("checkAndSetVolume failed, requesting volume range init");
2349 mpClientInterface->onVolumeRangeInitRequest();
2350 };
Eric Laurente552edb2014-03-10 17:42:56 -07002351
2352 // update the outputs if starting an output with a stream that can affect notification
2353 // routing
2354 handleNotificationRoutingForStream(stream);
Eric Laurentc722f302014-12-10 11:21:49 -08002355
Eric Laurent2cbe89a2014-12-19 11:49:08 -08002356 // force reevaluating accessibility routing when ringtone or alarm starts
François Gaffiec005e562018-11-06 15:04:49 +01002357 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM))) {
jiabinc44b3462022-12-08 12:52:31 -08002358 invalidateStreams({AUDIO_STREAM_ACCESSIBILITY});
Eric Laurent2cbe89a2014-12-19 11:49:08 -08002359 }
Eric Laurentdc462862016-07-19 12:29:53 -07002360
2361 if (waitMs > muteWaitMs) {
2362 *delayMs = waitMs - muteWaitMs;
2363 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002364
2365 // FIXME: A device change (muteWaitMs > 0) likely introduces a volume change.
2366 // A volume change enacted by APM with 0 delay is not synchronous, as it goes
2367 // via AudioCommandThread to AudioFlinger. Hence it is possible that the volume
2368 // change occurs after the MixerThread starts and causes a stream volume
2369 // glitch.
2370 //
2371 // We do not introduce additional delay here.
Eric Laurente552edb2014-03-10 17:42:56 -07002372 }
Eric Laurentdc462862016-07-19 12:29:53 -07002373
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002374 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
jiabin9a3361e2019-10-01 09:38:30 -07002375 mEngine->getForceUse(
2376 AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
François Gaffiec005e562018-11-06 15:04:49 +01002377 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), true, outputDesc);
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002378 }
2379
Eric Laurent97ac8712018-07-27 18:59:02 -07002380 // Automatically enable the remote submix input when output is started on a re routing mix
2381 // of type MIX_TYPE_RECORDERS
jiabin9a3361e2019-10-01 09:38:30 -07002382 if (isSingleDeviceType(devices.types(), &audio_is_remote_submix_device) &&
2383 policyMix != NULL && policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002384 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2385 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2386 address,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002387 "remote-submix",
2388 AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07002389 }
2390
Eric Laurent96d1dda2022-03-14 17:14:19 +01002391 checkLeBroadcastRoutes(wasLeUnicastActive, outputDesc, *delayMs);
2392
Eric Laurente552edb2014-03-10 17:42:56 -07002393 return NO_ERROR;
2394}
2395
Eric Laurent96d1dda2022-03-14 17:14:19 +01002396void AudioPolicyManager::checkLeBroadcastRoutes(bool wasUnicastActive,
2397 sp<SwAudioOutputDescriptor> ignoredOutput, uint32_t delayMs) {
2398 bool isUnicastActive = isLeUnicastActive();
2399
2400 if (wasUnicastActive != isUnicastActive) {
jiabin3ff8d7d2022-12-13 06:27:44 +00002401 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent96d1dda2022-03-14 17:14:19 +01002402 //reroute all outputs routed to LE broadcast if LE unicast activy changed on any output
2403 for (size_t i = 0; i < mOutputs.size(); i++) {
2404 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
2405 if (desc != ignoredOutput && desc->isActive()
2406 && ((isUnicastActive &&
2407 !desc->devices().
2408 getDevicesFromType(AUDIO_DEVICE_OUT_BLE_BROADCAST).isEmpty())
2409 || (wasUnicastActive &&
2410 !desc->devices().getDevicesFromTypes(
2411 getAudioDeviceOutLeAudioUnicastSet()).isEmpty()))) {
2412 DeviceVector newDevices = getNewOutputDevices(desc, false /*fromCache*/);
2413 bool force = desc->devices() != newDevices;
jiabin3ff8d7d2022-12-13 06:27:44 +00002414 if (desc->mUsePreferredMixerAttributes && force) {
2415 // If the device is using preferred mixer attributes, the output need to reopen
2416 // with default configuration when the new selected devices are different from
2417 // current routing devices.
2418 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices);
2419 continue;
2420 }
Eric Laurent96d1dda2022-03-14 17:14:19 +01002421 setOutputDevices(desc, newDevices, force, delayMs);
2422 // re-apply device specific volume if not done by setOutputDevice()
2423 if (!force) {
2424 applyStreamVolumes(desc, newDevices.types(), delayMs);
2425 }
2426 }
2427 }
jiabin3ff8d7d2022-12-13 06:27:44 +00002428 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent96d1dda2022-03-14 17:14:19 +01002429 }
2430}
2431
Eric Laurent8fc147b2018-07-22 19:13:55 -07002432status_t AudioPolicyManager::stopOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002433{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002434 ALOGV("%s portId %d", __FUNCTION__, portId);
2435
2436 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2437 if (outputDesc == 0) {
2438 ALOGW("stopOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002439 return BAD_VALUE;
2440 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002441 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002442
Jean-Michel Trivib1f6e642023-02-07 20:49:04 +00002443 if (client->hasPreferredDevice(true)) {
2444 // playback activity with preferred device impacts routing occurred, inform upper layers
2445 mpClientInterface->onRoutingUpdated();
2446 }
2447
Eric Laurent97ac8712018-07-27 18:59:02 -07002448 ALOGV("stopOutput() output %d, stream %d, session %d",
2449 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurente552edb2014-03-10 17:42:56 -07002450
Eric Laurent97ac8712018-07-27 18:59:02 -07002451 status_t status = stopSource(outputDesc, client);
Eric Laurent3974e3b2017-12-07 17:58:43 -08002452
Eric Laurent733ce942017-12-07 12:18:25 -08002453 if (status == NO_ERROR ) {
2454 outputDesc->stop();
jiabina84c3d32022-12-02 18:59:55 +00002455 } else {
2456 return status;
2457 }
2458
2459 if (outputDesc->devices().size() == 1) {
2460 sp<PreferredMixerAttributesInfo> info = getPreferredMixerAttributesInfo(
2461 outputDesc->devices()[0]->getId(), client->strategy());
2462 if (info != nullptr && info->getUid() == client->uid()) {
2463 info->decreaseActiveClient();
2464 if (info->getActiveClientCount() == 0) {
2465 reopenOutput(outputDesc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
2466 }
2467 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002468 }
2469 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07002470}
2471
Eric Laurent97ac8712018-07-27 18:59:02 -07002472status_t AudioPolicyManager::stopSource(const sp<SwAudioOutputDescriptor>& outputDesc,
2473 const sp<TrackClientDescriptor>& client)
Eric Laurentc75307b2015-03-17 15:29:32 -07002474{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002475 // always handle stream stop, check which stream type is stopping
Eric Laurent97ac8712018-07-27 18:59:02 -07002476 audio_stream_type_t stream = client->stream();
François Gaffie1c878552018-11-22 16:53:21 +01002477 auto clientVolSrc = client->volumeSource();
Eric Laurent96d1dda2022-03-14 17:14:19 +01002478 bool wasLeUnicastActive = isLeUnicastActive();
Eric Laurent97ac8712018-07-27 18:59:02 -07002479
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002480 handleEventForBeacon(stream == AUDIO_STREAM_TTS ? STOPPING_BEACON : STOPPING_OUTPUT);
2481
François Gaffie1c878552018-11-22 16:53:21 +01002482 if (outputDesc->getActivityCount(clientVolSrc) > 0) {
2483 if (outputDesc->getActivityCount(clientVolSrc) == 1) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002484 // Automatically disable the remote submix input when output is stopped on a
2485 // re routing mix of type MIX_TYPE_RECORDERS
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002486 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
jiabin9a3361e2019-10-01 09:38:30 -07002487 if (isSingleDeviceType(
2488 outputDesc->devices().types(), &audio_is_remote_submix_device) &&
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002489 policyMix != nullptr &&
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002490 policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002491 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2492 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002493 policyMix->mDeviceAddress,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002494 "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07002495 }
2496 }
2497 bool forceDeviceUpdate = false;
Eric Laurent72af8012023-03-15 17:36:22 +01002498 if (client->hasPreferredDevice(true) &&
2499 outputDesc->sameExclusivePreferredDevicesCount() < 2) {
François Gaffiec005e562018-11-06 15:04:49 +01002500 checkStrategyRoute(client->strategy(), AUDIO_IO_HANDLE_NONE);
Eric Laurent97ac8712018-07-27 18:59:02 -07002501 forceDeviceUpdate = true;
2502 }
2503
Eric Laurente552edb2014-03-10 17:42:56 -07002504 // decrement usage count of this stream on the output
Eric Laurent592dd7b2018-08-05 18:58:48 -07002505 outputDesc->setClientActive(client, false);
Paul McLeanaa981192015-03-21 09:55:15 -07002506
Eric Laurente552edb2014-03-10 17:42:56 -07002507 // store time at which the stream was stopped - see isStreamActive()
François Gaffie1c878552018-11-22 16:53:21 +01002508 if (outputDesc->getActivityCount(clientVolSrc) == 0 || forceDeviceUpdate) {
François Gaffiec005e562018-11-06 15:04:49 +01002509 outputDesc->setStopTime(client, systemTime());
François Gaffie11d30102018-11-02 16:09:09 +01002510 DeviceVector newDevices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Francois Gaffie3523ab32021-06-22 13:24:34 +02002511
2512 // If the routing does not change, if an output is routed on a device using HwGain
2513 // (aka setAudioPortConfig) and there are still active clients following different
2514 // volume group(s), force reapply volume
2515 bool requiresVolumeCheck = outputDesc->getActivityCount(clientVolSrc) == 0 &&
2516 outputDesc->useHwGain() && outputDesc->isAnyActive(VOLUME_SOURCE_NONE);
2517
Eric Laurente552edb2014-03-10 17:42:56 -07002518 // delay the device switch by twice the latency because stopOutput() is executed when
2519 // the track stop() command is received and at that time the audio track buffer can
2520 // still contain data that needs to be drained. The latency only covers the audio HAL
2521 // and kernel buffers. Also the latency does not always include additional delay in the
2522 // audio path (audio DSP, CODEC ...)
Francois Gaffie3523ab32021-06-22 13:24:34 +02002523 setOutputDevices(outputDesc, newDevices, false, outputDesc->latency()*2,
2524 nullptr, true /*requiresMuteCheck*/, requiresVolumeCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07002525
2526 // force restoring the device selection on other active outputs if it differs from the
2527 // one being selected for this output
jiabin3ff8d7d2022-12-13 06:27:44 +00002528 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent57de36c2016-09-28 16:59:11 -07002529 uint32_t delayMs = outputDesc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -07002530 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01002531 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07002532 if (desc != outputDesc &&
Eric Laurente552edb2014-03-10 17:42:56 -07002533 desc->isActive() &&
2534 outputDesc->sharesHwModuleWith(desc) &&
François Gaffie11d30102018-11-02 16:09:09 +01002535 (newDevices != desc->devices())) {
2536 DeviceVector newDevices2 = getNewOutputDevices(desc, false /*fromCache*/);
2537 bool force = desc->devices() != newDevices2;
Eric Laurentf3a5a602018-05-22 18:42:55 -07002538
jiabin3ff8d7d2022-12-13 06:27:44 +00002539 if (desc->mUsePreferredMixerAttributes && force) {
2540 // If the device is using preferred mixer attributes, the output need to
2541 // reopen with default configuration when the new selected devices are
2542 // different from current routing devices.
2543 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices2);
2544 continue;
2545 }
François Gaffie11d30102018-11-02 16:09:09 +01002546 setOutputDevices(desc, newDevices2, force, delayMs);
2547
Eric Laurent57de36c2016-09-28 16:59:11 -07002548 // re-apply device specific volume if not done by setOutputDevice()
2549 if (!force) {
François Gaffie11d30102018-11-02 16:09:09 +01002550 applyStreamVolumes(desc, newDevices2.types(), delayMs);
Eric Laurent57de36c2016-09-28 16:59:11 -07002551 }
Eric Laurente552edb2014-03-10 17:42:56 -07002552 }
2553 }
jiabin3ff8d7d2022-12-13 06:27:44 +00002554 reopenOutputsWithDevices(outputsToReopen);
Eric Laurente552edb2014-03-10 17:42:56 -07002555 // update the outputs if stopping one with a stream that can affect notification routing
2556 handleNotificationRoutingForStream(stream);
2557 }
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002558
2559 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
2560 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Jean-Michel Trivi74e01fa2019-02-25 12:18:09 -08002561 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), false, outputDesc);
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002562 }
2563
François Gaffiec005e562018-11-06 15:04:49 +01002564 if (followsSameRouting(client->attributes(), attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07002565 selectOutputForMusicEffects();
2566 }
Eric Laurent96d1dda2022-03-14 17:14:19 +01002567
2568 checkLeBroadcastRoutes(wasLeUnicastActive, outputDesc, outputDesc->latency()*2);
2569
Eric Laurente552edb2014-03-10 17:42:56 -07002570 return NO_ERROR;
2571 } else {
Eric Laurentc75307b2015-03-17 15:29:32 -07002572 ALOGW("stopOutput() refcount is already 0");
Eric Laurente552edb2014-03-10 17:42:56 -07002573 return INVALID_OPERATION;
2574 }
2575}
2576
jiabinbce0c1d2020-10-05 11:20:18 -07002577bool AudioPolicyManager::releaseOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002578{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002579 ALOGV("%s portId %d", __FUNCTION__, portId);
2580
2581 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2582 if (outputDesc == 0) {
Andy Hung39efb7a2018-09-26 15:39:28 -07002583 // If an output descriptor is closed due to a device routing change,
2584 // then there are race conditions with releaseOutput from tracks
2585 // that may be destroyed (with no PlaybackThread) or a PlaybackThread
2586 // destroyed shortly thereafter.
2587 //
2588 // Here we just log a warning, instead of a fatal error.
Eric Laurent8fc147b2018-07-22 19:13:55 -07002589 ALOGW("releaseOutput() no output for client %d", portId);
jiabinbce0c1d2020-10-05 11:20:18 -07002590 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002591 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002592
2593 ALOGV("releaseOutput() %d", outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -07002594
Jaideep Sharma7bf382e2020-11-26 17:07:29 +05302595 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
2596 if (outputDesc->isClientActive(client)) {
2597 ALOGW("releaseOutput() inactivates portId %d in good faith", portId);
2598 stopOutput(portId);
2599 }
2600
Eric Laurent8fc147b2018-07-22 19:13:55 -07002601 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
2602 if (outputDesc->mDirectOpenCount <= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07002603 ALOGW("releaseOutput() invalid open count %d for output %d",
Eric Laurent8fc147b2018-07-22 19:13:55 -07002604 outputDesc->mDirectOpenCount, outputDesc->mIoHandle);
jiabinbce0c1d2020-10-05 11:20:18 -07002605 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002606 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002607 if (--outputDesc->mDirectOpenCount == 0) {
2608 closeOutput(outputDesc->mIoHandle);
Eric Laurentb52c1522014-05-20 11:27:36 -07002609 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07002610 }
2611 }
Jaideep Sharma7bf382e2020-11-26 17:07:29 +05302612
Andy Hung39efb7a2018-09-26 15:39:28 -07002613 outputDesc->removeClient(portId);
jiabinbce0c1d2020-10-05 11:20:18 -07002614 if (outputDesc->mPendingReopenToQueryProfiles && outputDesc->getClientCount() == 0) {
2615 // The output is pending reopened to query dynamic profiles and
2616 // there is no active clients
2617 closeOutput(outputDesc->mIoHandle);
2618 sp<SwAudioOutputDescriptor> newOutputDesc = openOutputWithProfileAndDevice(
2619 outputDesc->mProfile, mEngine->getActiveMediaDevices(mAvailableOutputDevices));
2620 if (newOutputDesc == nullptr) {
2621 ALOGE("%s failed to open output", __func__);
2622 }
2623 return true;
2624 }
2625 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002626}
2627
Eric Laurentcaf7f482014-11-25 17:50:47 -08002628status_t AudioPolicyManager::getInputForAttr(const audio_attributes_t *attr,
2629 audio_io_handle_t *input,
Mikhail Naganov2996f672019-04-18 12:29:59 -07002630 audio_unique_id_t riid,
Eric Laurentcaf7f482014-11-25 17:50:47 -08002631 audio_session_t session,
Svet Ganov3e5f14f2021-05-13 22:51:08 +00002632 const AttributionSourceState& attributionSource,
jiabinf1c73972022-04-14 16:28:52 -07002633 audio_config_base_t *config,
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002634 audio_input_flags_t flags,
Eric Laurent2ac76942017-06-22 17:17:09 -07002635 audio_port_handle_t *selectedDeviceId,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002636 input_type_t *inputType,
2637 audio_port_handle_t *portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002638{
François Gaffiec005e562018-11-06 15:04:49 +01002639 ALOGV("%s() source %d, sampling rate %d, format %#x, channel mask %#x, session %d, "
Eric Laurent2f2c1982021-06-02 14:03:11 +02002640 "flags %#x attributes=%s requested device ID %d",
2641 __func__, attr->source, config->sample_rate, config->format, config->channel_mask,
2642 session, flags, toString(*attr).c_str(), *selectedDeviceId);
Eric Laurente552edb2014-03-10 17:42:56 -07002643
Eric Laurentad2e7b92017-09-14 20:06:42 -07002644 status_t status = NO_ERROR;
Francois Gaffie716e1432019-01-14 16:58:59 +01002645 audio_attributes_t attributes = *attr;
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002646 sp<AudioPolicyMix> policyMix;
François Gaffie11d30102018-11-02 16:09:09 +01002647 sp<DeviceDescriptor> device;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002648 sp<AudioInputDescriptor> inputDesc;
2649 sp<RecordClientDescriptor> clientDesc;
2650 audio_port_handle_t requestedDeviceId = *selectedDeviceId;
Svet Ganov3e5f14f2021-05-13 22:51:08 +00002651 uid_t uid = VALUE_OR_RETURN_STATUS(aidl2legacy_int32_t_uid_t(attributionSource.uid));
Eric Laurent8f42ea12018-08-08 09:08:25 -07002652 bool isSoundTrigger;
Eric Laurent8f42ea12018-08-08 09:08:25 -07002653
2654 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
2655 if (*portId != AUDIO_PORT_HANDLE_NONE) {
2656 return INVALID_OPERATION;
2657 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08002658
Francois Gaffie716e1432019-01-14 16:58:59 +01002659 if (attr->source == AUDIO_SOURCE_DEFAULT) {
2660 attributes.source = AUDIO_SOURCE_MIC;
Eric Laurentfe231122017-11-17 17:48:06 -08002661 }
2662
Paul McLean466dc8e2015-04-17 13:15:36 -06002663 // Explicit routing?
Pattydd807582021-11-04 21:01:03 +08002664 sp<DeviceDescriptor> explicitRoutingDevice =
François Gaffie11d30102018-11-02 16:09:09 +01002665 mAvailableInputDevices.getDeviceFromId(*selectedDeviceId);
Paul McLean466dc8e2015-04-17 13:15:36 -06002666
Eric Laurentad2e7b92017-09-14 20:06:42 -07002667 // special case for mmap capture: if an input IO handle is specified, we reuse this input if
2668 // possible
2669 if ((flags & AUDIO_INPUT_FLAG_MMAP_NOIRQ) == AUDIO_INPUT_FLAG_MMAP_NOIRQ &&
2670 *input != AUDIO_IO_HANDLE_NONE) {
2671 ssize_t index = mInputs.indexOfKey(*input);
2672 if (index < 0) {
2673 ALOGW("getInputForAttr() unknown MMAP input %d", *input);
2674 status = BAD_VALUE;
2675 goto error;
2676 }
2677 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002678 RecordClientVector clients = inputDesc->getClientsForSession(session);
2679 if (clients.size() == 0) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07002680 ALOGW("getInputForAttr() unknown session %d on input %d", session, *input);
2681 status = BAD_VALUE;
2682 goto error;
2683 }
2684 // For MMAP mode, the first call to getInputForAttr() is made on behalf of audioflinger.
2685 // The second call is for the first active client and sets the UID. Any further call
Eric Laurent331679c2018-04-16 17:03:16 -07002686 // corresponds to a new client and is only permitted from the same UID.
2687 // If the first UID is silenced, allow a new UID connection and replace with new UID
Eric Laurent8f42ea12018-08-08 09:08:25 -07002688 if (clients.size() > 1) {
2689 for (const auto& client : clients) {
2690 // The client map is ordered by key values (portId) and portIds are allocated
2691 // incrementaly. So the first client in this list is the one opened by audio flinger
2692 // when the mmap stream is created and should be ignored as it does not correspond
2693 // to an actual client
2694 if (client == *clients.cbegin()) {
2695 continue;
2696 }
2697 if (uid != client->uid() && !client->isSilenced()) {
2698 ALOGW("getInputForAttr() bad uid %d for client %d uid %d",
2699 uid, client->portId(), client->uid());
2700 status = INVALID_OPERATION;
2701 goto error;
2702 }
Eric Laurent331679c2018-04-16 17:03:16 -07002703 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002704 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002705 *inputType = API_INPUT_LEGACY;
François Gaffie11d30102018-11-02 16:09:09 +01002706 device = inputDesc->getDevice();
Eric Laurentad2e7b92017-09-14 20:06:42 -07002707
Eric Laurentfecbceb2021-02-09 14:46:43 +01002708 ALOGV("%s reusing MMAP input %d for session %d", __FUNCTION__, *input, session);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002709 goto exit;
Eric Laurentad2e7b92017-09-14 20:06:42 -07002710 }
2711
2712 *input = AUDIO_IO_HANDLE_NONE;
2713 *inputType = API_INPUT_INVALID;
2714
Francois Gaffie716e1432019-01-14 16:58:59 +01002715 if (attributes.source == AUDIO_SOURCE_REMOTE_SUBMIX &&
Jan Sebechlebskybc56bcd2022-09-26 13:15:19 +02002716 extractAddressFromAudioAttributes(attributes).has_value()) {
Francois Gaffie716e1432019-01-14 16:58:59 +01002717 status = mPolicyMixes.getInputMixForAttr(attributes, &policyMix);
Eric Laurentad2e7b92017-09-14 20:06:42 -07002718 if (status != NO_ERROR) {
jiabinc1de2df2019-05-07 14:26:40 -07002719 ALOGW("%s could not find input mix for attr %s",
2720 __func__, toString(attributes).c_str());
Eric Laurentad2e7b92017-09-14 20:06:42 -07002721 goto error;
François Gaffie036e1e92015-03-19 10:16:24 +01002722 }
jiabinc1de2df2019-05-07 14:26:40 -07002723 device = mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2724 String8(attr->tags + strlen("addr=")),
2725 AUDIO_FORMAT_DEFAULT);
2726 if (device == nullptr) {
Kevin Rocard04ed0462019-05-02 17:53:24 -07002727 ALOGW("%s could not find in Remote Submix device for source %d, tags %s",
jiabinc1de2df2019-05-07 14:26:40 -07002728 __func__, attributes.source, attributes.tags);
2729 status = BAD_VALUE;
2730 goto error;
2731 }
2732
Kevin Rocard25f9b052019-02-27 15:08:54 -08002733 if (is_mix_loopback_render(policyMix->mRouteFlags)) {
2734 *inputType = API_INPUT_MIX_PUBLIC_CAPTURE_PLAYBACK;
2735 } else {
2736 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
2737 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002738 } else {
François Gaffie11d30102018-11-02 16:09:09 +01002739 if (explicitRoutingDevice != nullptr) {
2740 device = explicitRoutingDevice;
Eric Laurent97ac8712018-07-27 18:59:02 -07002741 } else {
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01002742 // Prevent from storing invalid requested device id in clients
2743 requestedDeviceId = AUDIO_PORT_HANDLE_NONE;
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02002744 device = mEngine->getInputDeviceForAttributes(attributes, uid, session, &policyMix);
yuanjiahsu4069d5d2021-04-19 07:54:27 +08002745 ALOGV_IF(device != nullptr, "%s found device type is 0x%X",
2746 __FUNCTION__, device->type());
Eric Laurent97ac8712018-07-27 18:59:02 -07002747 }
François Gaffie11d30102018-11-02 16:09:09 +01002748 if (device == nullptr) {
Francois Gaffie716e1432019-01-14 16:58:59 +01002749 ALOGW("getInputForAttr() could not find device for source %d", attributes.source);
Eric Laurentad2e7b92017-09-14 20:06:42 -07002750 status = BAD_VALUE;
2751 goto error;
Eric Laurent275e8e92014-11-30 15:14:47 -08002752 }
Alden DSouzab7d20782021-02-08 08:51:42 -08002753 if (device->type() == AUDIO_DEVICE_IN_ECHO_REFERENCE) {
2754 *inputType = API_INPUT_MIX_CAPTURE;
2755 } else if (policyMix) {
François Gaffie11d30102018-11-02 16:09:09 +01002756 ALOG_ASSERT(policyMix->mMixType == MIX_TYPE_RECORDERS, "Invalid Mix Type");
2757 // there is an external policy, but this input is attached to a mix of recorders,
2758 // meaning it receives audio injected into the framework, so the recorder doesn't
2759 // know about it and is therefore considered "legacy"
2760 *inputType = API_INPUT_LEGACY;
2761 } else if (audio_is_remote_submix_device(device->type())) {
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002762 *inputType = API_INPUT_MIX_CAPTURE;
François Gaffie11d30102018-11-02 16:09:09 +01002763 } else if (device->type() == AUDIO_DEVICE_IN_TELEPHONY_RX) {
Eric Laurent82db2692015-08-07 13:59:42 -07002764 *inputType = API_INPUT_TELEPHONY_RX;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002765 } else {
2766 *inputType = API_INPUT_LEGACY;
Eric Laurentc722f302014-12-10 11:21:49 -08002767 }
Ravi Kumar Alamandab367f5b2015-08-25 08:21:37 -07002768
Eric Laurent599c7582015-12-07 18:05:55 -08002769 }
2770
François Gaffiec005e562018-11-06 15:04:49 +01002771 *input = getInputForDevice(device, session, attributes, config, flags, policyMix);
Eric Laurent599c7582015-12-07 18:05:55 -08002772 if (*input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07002773 status = INVALID_OPERATION;
jiabinf1c73972022-04-14 16:28:52 -07002774 AudioProfileVector profiles;
2775 status_t ret = getProfilesForDevices(
2776 DeviceVector(device), profiles, flags, true /*isInput*/);
2777 if (ret == NO_ERROR && !profiles.empty()) {
2778 config->channel_mask = profiles[0]->getChannels().empty() ? config->channel_mask
2779 : *profiles[0]->getChannels().begin();
2780 config->sample_rate = profiles[0]->getSampleRates().empty() ? config->sample_rate
2781 : *profiles[0]->getSampleRates().begin();
2782 config->format = profiles[0]->getFormat();
2783 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002784 goto error;
Eric Laurent599c7582015-12-07 18:05:55 -08002785 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08002786
Eric Laurent8f42ea12018-08-08 09:08:25 -07002787exit:
2788
François Gaffiec005e562018-11-06 15:04:49 +01002789 *selectedDeviceId = mAvailableInputDevices.contains(device) ?
2790 device->getId() : AUDIO_PORT_HANDLE_NONE;
Eric Laurent2ac76942017-06-22 17:17:09 -07002791
Francois Gaffie716e1432019-01-14 16:58:59 +01002792 isSoundTrigger = attributes.source == AUDIO_SOURCE_HOTWORD &&
Carter Hsud0cce2e2019-05-03 17:36:28 +08002793 mSoundTriggerSessions.indexOfKey(session) >= 0;
jiabin4ef93452019-09-10 14:29:54 -07002794 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002795
Mikhail Naganov2996f672019-04-18 12:29:59 -07002796 clientDesc = new RecordClientDescriptor(*portId, riid, uid, session, attributes, *config,
Francois Gaffie716e1432019-01-14 16:58:59 +01002797 requestedDeviceId, attributes.source, flags,
2798 isSoundTrigger);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002799 inputDesc = mInputs.valueFor(*input);
Andy Hung39efb7a2018-09-26 15:39:28 -07002800 inputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002801
2802 ALOGV("getInputForAttr() returns input %d type %d selectedDeviceId %d for port ID %d",
2803 *input, *inputType, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07002804
Eric Laurent599c7582015-12-07 18:05:55 -08002805 return NO_ERROR;
Eric Laurentad2e7b92017-09-14 20:06:42 -07002806
2807error:
Eric Laurentad2e7b92017-09-14 20:06:42 -07002808 return status;
Eric Laurent599c7582015-12-07 18:05:55 -08002809}
2810
2811
François Gaffie11d30102018-11-02 16:09:09 +01002812audio_io_handle_t AudioPolicyManager::getInputForDevice(const sp<DeviceDescriptor> &device,
Eric Laurent599c7582015-12-07 18:05:55 -08002813 audio_session_t session,
François Gaffiec005e562018-11-06 15:04:49 +01002814 const audio_attributes_t &attributes,
jiabinf1c73972022-04-14 16:28:52 -07002815 audio_config_base_t *config,
Eric Laurent599c7582015-12-07 18:05:55 -08002816 audio_input_flags_t flags,
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002817 const sp<AudioPolicyMix> &policyMix)
Eric Laurent599c7582015-12-07 18:05:55 -08002818{
2819 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
François Gaffiec005e562018-11-06 15:04:49 +01002820 audio_source_t halInputSource = attributes.source;
Eric Laurent599c7582015-12-07 18:05:55 -08002821 bool isSoundTrigger = false;
2822
François Gaffiec005e562018-11-06 15:04:49 +01002823 if (attributes.source == AUDIO_SOURCE_HOTWORD) {
Eric Laurent599c7582015-12-07 18:05:55 -08002824 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
2825 if (index >= 0) {
2826 input = mSoundTriggerSessions.valueFor(session);
2827 isSoundTrigger = true;
2828 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_HW_HOTWORD);
2829 ALOGV("SoundTrigger capture on session %d input %d", session, input);
2830 } else {
2831 halInputSource = AUDIO_SOURCE_VOICE_RECOGNITION;
Eric Laurent5dbe4712014-09-19 19:04:57 -07002832 }
François Gaffiec005e562018-11-06 15:04:49 +01002833 } else if (attributes.source == AUDIO_SOURCE_VOICE_COMMUNICATION &&
Eric Laurentfe231122017-11-17 17:48:06 -08002834 audio_is_linear_pcm(config->format)) {
Haynes Mathew George851d3ff2017-06-19 20:01:57 -07002835 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_VOIP_TX);
Eric Laurent5dbe4712014-09-19 19:04:57 -07002836 }
2837
Carter Hsua3abb402021-10-26 11:11:20 +08002838 if (attributes.source == AUDIO_SOURCE_ULTRASOUND) {
2839 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_ULTRASOUND);
2840 }
2841
Eric Laurentfe231122017-11-17 17:48:06 -08002842 // sampling rate and flags may be updated by getInputProfile
2843 uint32_t profileSamplingRate = (config->sample_rate == 0) ?
2844 SAMPLE_RATE_HZ_DEFAULT : config->sample_rate;
jiabin2fd710d2022-05-02 23:20:22 +00002845 audio_format_t profileFormat = config->format;
Eric Laurentfe231122017-11-17 17:48:06 -08002846 audio_channel_mask_t profileChannelMask = config->channel_mask;
Andy Hungf129b032015-04-07 13:45:50 -07002847 audio_input_flags_t profileFlags = flags;
jiabin2fd710d2022-05-02 23:20:22 +00002848 // find a compatible input profile (not necessarily identical in parameters)
2849 sp<IOProfile> profile = getInputProfile(
2850 device, profileSamplingRate, profileFormat, profileChannelMask, profileFlags);
2851 if (profile == nullptr) {
2852 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07002853 }
jiabin2fd710d2022-05-02 23:20:22 +00002854
Glenn Kasten05ddca52016-02-11 08:17:12 -08002855 // Pick input sampling rate if not specified by client
Eric Laurentfe231122017-11-17 17:48:06 -08002856 uint32_t samplingRate = config->sample_rate;
Glenn Kasten05ddca52016-02-11 08:17:12 -08002857 if (samplingRate == 0) {
2858 samplingRate = profileSamplingRate;
2859 }
Eric Laurente552edb2014-03-10 17:42:56 -07002860
Eric Laurent322b4d22015-04-03 15:57:54 -07002861 if (profile->getModuleHandle() == 0) {
2862 ALOGE("getInputForAttr(): HW module %s not opened", profile->getModuleName());
Eric Laurent599c7582015-12-07 18:05:55 -08002863 return input;
Eric Laurentcf2c0212014-07-25 16:20:43 -07002864 }
2865
Eric Laurentec376dc2021-04-08 20:41:22 +02002866 // Reuse an already opened input if a client with the same session ID already exists
2867 // on that input
2868 for (size_t i = 0; i < mInputs.size(); i++) {
2869 sp <AudioInputDescriptor> desc = mInputs.valueAt(i);
2870 if (desc->mProfile != profile) {
2871 continue;
2872 }
2873 RecordClientVector clients = desc->clientsList();
2874 for (const auto &client : clients) {
2875 if (session == client->session()) {
2876 return desc->mIoHandle;
2877 }
2878 }
2879 }
2880
Eric Laurent3974e3b2017-12-07 17:58:43 -08002881 if (!profile->canOpenNewIo()) {
Eric Laurent4eb58f12018-12-07 16:41:02 -08002882 for (size_t i = 0; i < mInputs.size(); ) {
Eric Laurentc529cf62020-04-17 18:19:10 -07002883 sp<AudioInputDescriptor> desc = mInputs.valueAt(i);
Eric Laurent4eb58f12018-12-07 16:41:02 -08002884 if (desc->mProfile != profile) {
Carter Hsu9a645a92019-05-15 12:15:32 +08002885 i++;
Eric Laurent4eb58f12018-12-07 16:41:02 -08002886 continue;
2887 }
2888 // if sound trigger, reuse input if used by other sound trigger on same session
2889 // else
2890 // reuse input if active client app is not in IDLE state
2891 //
2892 RecordClientVector clients = desc->clientsList();
2893 bool doClose = false;
2894 for (const auto& client : clients) {
2895 if (isSoundTrigger != client->isSoundTrigger()) {
2896 continue;
2897 }
2898 if (client->isSoundTrigger()) {
2899 if (session == client->session()) {
2900 return desc->mIoHandle;
2901 }
2902 continue;
2903 }
2904 if (client->active() && client->appState() != APP_STATE_IDLE) {
2905 return desc->mIoHandle;
2906 }
2907 doClose = true;
2908 }
2909 if (doClose) {
2910 closeInput(desc->mIoHandle);
2911 } else {
2912 i++;
2913 }
2914 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002915 }
2916
Eric Laurentfe231122017-11-17 17:48:06 -08002917 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07002918
Eric Laurentfe231122017-11-17 17:48:06 -08002919 audio_config_t lConfig = AUDIO_CONFIG_INITIALIZER;
2920 lConfig.sample_rate = profileSamplingRate;
2921 lConfig.channel_mask = profileChannelMask;
2922 lConfig.format = profileFormat;
Eric Laurente3014102017-05-03 11:15:43 -07002923
François Gaffie11d30102018-11-02 16:09:09 +01002924 status_t status = inputDesc->open(&lConfig, device, halInputSource, profileFlags, &input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07002925
2926 // only accept input with the exact requested set of parameters
Eric Laurent599c7582015-12-07 18:05:55 -08002927 if (status != NO_ERROR || input == AUDIO_IO_HANDLE_NONE ||
Eric Laurentfe231122017-11-17 17:48:06 -08002928 (profileSamplingRate != lConfig.sample_rate) ||
2929 !audio_formats_match(profileFormat, lConfig.format) ||
2930 (profileChannelMask != lConfig.channel_mask)) {
2931 ALOGW("getInputForAttr() failed opening input: sampling rate %d"
Glenn Kasten49f36ba2017-12-06 13:02:02 -08002932 ", format %#x, channel mask %#x",
Eric Laurentfe231122017-11-17 17:48:06 -08002933 profileSamplingRate, profileFormat, profileChannelMask);
Eric Laurent599c7582015-12-07 18:05:55 -08002934 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfe231122017-11-17 17:48:06 -08002935 inputDesc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07002936 }
Eric Laurent599c7582015-12-07 18:05:55 -08002937 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07002938 }
2939
Eric Laurentc722f302014-12-10 11:21:49 -08002940 inputDesc->mPolicyMix = policyMix;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002941
Eric Laurent599c7582015-12-07 18:05:55 -08002942 addInput(input, inputDesc);
Eric Laurentb52c1522014-05-20 11:27:36 -07002943 mpClientInterface->onAudioPortListUpdate();
Paul McLean466dc8e2015-04-17 13:15:36 -06002944
Eric Laurent599c7582015-12-07 18:05:55 -08002945 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07002946}
2947
Eric Laurent4eb58f12018-12-07 16:41:02 -08002948status_t AudioPolicyManager::startInput(audio_port_handle_t portId)
Eric Laurentbb948092017-01-23 18:33:30 -08002949{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002950 ALOGV("%s portId %d", __FUNCTION__, portId);
2951
2952 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2953 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002954 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurentd52a28c2020-08-21 17:10:39 -07002955 return DEAD_OBJECT;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002956 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002957 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07002958 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002959 if (client->active()) {
2960 ALOGW("%s input %d client %d already started", __FUNCTION__, input, client->portId());
2961 return INVALID_OPERATION;
Eric Laurent4dc68062014-07-28 17:26:49 -07002962 }
2963
Eric Laurent8f42ea12018-08-08 09:08:25 -07002964 audio_session_t session = client->session();
2965
Eric Laurent4eb58f12018-12-07 16:41:02 -08002966 ALOGV("%s input:%d, session:%d)", __FUNCTION__, input, session);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002967
Eric Laurent4eb58f12018-12-07 16:41:02 -08002968 Vector<sp<AudioInputDescriptor>> activeInputs = mInputs.getActiveInputs();
Eric Laurent74708e72017-04-07 17:13:42 -07002969
Eric Laurent4eb58f12018-12-07 16:41:02 -08002970 status_t status = inputDesc->start();
2971 if (status != NO_ERROR) {
2972 return status;
Eric Laurent74708e72017-04-07 17:13:42 -07002973 }
Eric Laurente552edb2014-03-10 17:42:56 -07002974
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002975 // increment activity count before calling getNewInputDevice() below as only active sessions
Eric Laurent313d1e72016-01-29 09:56:57 -08002976 // are considered for device selection
Eric Laurent8f42ea12018-08-08 09:08:25 -07002977 inputDesc->setClientActive(client, true);
Eric Laurent313d1e72016-01-29 09:56:57 -08002978
Eric Laurent8f42ea12018-08-08 09:08:25 -07002979 // indicate active capture to sound trigger service if starting capture from a mic on
2980 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01002981 sp<DeviceDescriptor> device = getNewInputDevice(inputDesc);
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002982 if (device != nullptr) {
2983 status = setInputDevice(input, device, true /* force */);
2984 } else {
2985 ALOGW("%s no new input device can be found for descriptor %d",
2986 __FUNCTION__, inputDesc->getId());
2987 status = BAD_VALUE;
2988 }
Eric Laurente552edb2014-03-10 17:42:56 -07002989
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002990 if (status == NO_ERROR && inputDesc->activeCount() == 1) {
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002991 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002992 // if input maps to a dynamic policy with an activity listener, notify of state change
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002993 if ((policyMix != nullptr)
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002994 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
2995 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
Eric Laurent8f42ea12018-08-08 09:08:25 -07002996 MIX_STATE_MIXING);
Eric Laurent733ce942017-12-07 12:18:25 -08002997 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002998
François Gaffie11d30102018-11-02 16:09:09 +01002999 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
3000 if (primaryInputDevices.contains(device) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07003001 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 1) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07003002 mpClientInterface->setSoundTriggerCaptureState(true);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003003 }
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07003004
Eric Laurent8f42ea12018-08-08 09:08:25 -07003005 // automatically enable the remote submix output when input is started if not
3006 // used by a policy mix of type MIX_TYPE_RECORDERS
3007 // For remote submix (a virtual device), we open only one input per capture request.
François Gaffie11d30102018-11-02 16:09:09 +01003008 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003009 String8 address = String8("");
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003010 if (policyMix == nullptr) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003011 address = String8("0");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003012 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
3013 address = policyMix->mDeviceAddress;
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07003014 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07003015 if (address != "") {
3016 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
3017 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08003018 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurentc722f302014-12-10 11:21:49 -08003019 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07003020 }
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003021 } else if (status != NO_ERROR) {
3022 // Restore client activity state.
3023 inputDesc->setClientActive(client, false);
3024 inputDesc->stop();
Eric Laurente552edb2014-03-10 17:42:56 -07003025 }
3026
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003027 ALOGV("%s input %d source = %d status = %d exit",
3028 __FUNCTION__, input, client->source(), status);
Eric Laurente552edb2014-03-10 17:42:56 -07003029
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003030 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07003031}
3032
Eric Laurent8fc147b2018-07-22 19:13:55 -07003033status_t AudioPolicyManager::stopInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07003034{
Eric Laurent8fc147b2018-07-22 19:13:55 -07003035 ALOGV("%s portId %d", __FUNCTION__, portId);
3036
3037 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
3038 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003039 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07003040 return BAD_VALUE;
3041 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07003042 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07003043 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003044 if (!client->active()) {
3045 ALOGW("%s input %d client %d already stopped", __FUNCTION__, input, client->portId());
Eric Laurente552edb2014-03-10 17:42:56 -07003046 return INVALID_OPERATION;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003047 }
Carter Hsue6139d52021-07-08 10:30:20 +08003048 auto old_source = inputDesc->source();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003049 inputDesc->setClientActive(client, false);
Paul McLean466dc8e2015-04-17 13:15:36 -06003050
Eric Laurent8f42ea12018-08-08 09:08:25 -07003051 inputDesc->stop();
3052 if (inputDesc->isActive()) {
Carter Hsue6139d52021-07-08 10:30:20 +08003053 auto current_source = inputDesc->source();
3054 setInputDevice(input, getNewInputDevice(inputDesc),
3055 old_source != current_source /* force */);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003056 } else {
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003057 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003058 // if input maps to a dynamic policy with an activity listener, notify of state change
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003059 if ((policyMix != nullptr)
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003060 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
3061 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
Eric Laurent8f42ea12018-08-08 09:08:25 -07003062 MIX_STATE_IDLE);
Eric Laurent84332aa2016-01-28 22:19:18 +00003063 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07003064
3065 // automatically disable the remote submix output when input is stopped if not
3066 // used by a policy mix of type MIX_TYPE_RECORDERS
François Gaffie11d30102018-11-02 16:09:09 +01003067 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003068 String8 address = String8("");
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003069 if (policyMix == nullptr) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003070 address = String8("0");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003071 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
3072 address = policyMix->mDeviceAddress;
Eric Laurent8f42ea12018-08-08 09:08:25 -07003073 }
3074 if (address != "") {
3075 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
3076 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08003077 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003078 }
3079 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07003080 resetInputDevice(input);
3081
3082 // indicate inactive capture to sound trigger service if stopping capture from a mic on
3083 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01003084 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
3085 if (primaryInputDevices.contains(inputDesc->getDevice()) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07003086 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07003087 mpClientInterface->setSoundTriggerCaptureState(false);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003088 }
3089 inputDesc->clearPreemptedSessions();
Eric Laurente552edb2014-03-10 17:42:56 -07003090 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003091 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07003092}
3093
Eric Laurent8fc147b2018-07-22 19:13:55 -07003094void AudioPolicyManager::releaseInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07003095{
Eric Laurent8fc147b2018-07-22 19:13:55 -07003096 ALOGV("%s portId %d", __FUNCTION__, portId);
3097
3098 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
3099 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003100 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07003101 return;
3102 }
Andy Hung39efb7a2018-09-26 15:39:28 -07003103 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8fc147b2018-07-22 19:13:55 -07003104 audio_io_handle_t input = inputDesc->mIoHandle;
3105
Eric Laurent8f42ea12018-08-08 09:08:25 -07003106 ALOGV("%s %d", __FUNCTION__, input);
Paul McLean466dc8e2015-04-17 13:15:36 -06003107
Andy Hung39efb7a2018-09-26 15:39:28 -07003108 inputDesc->removeClient(portId);
Eric Laurent599c7582015-12-07 18:05:55 -08003109
Andy Hung39efb7a2018-09-26 15:39:28 -07003110 if (inputDesc->getClientCount() > 0) {
3111 ALOGV("%s(%d) %zu clients remaining", __func__, portId, inputDesc->getClientCount());
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003112 return;
3113 }
3114
Eric Laurent05b90f82014-08-27 15:32:29 -07003115 closeInput(input);
Eric Laurentb52c1522014-05-20 11:27:36 -07003116 mpClientInterface->onAudioPortListUpdate();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003117 ALOGV("%s exit", __FUNCTION__);
Eric Laurente552edb2014-03-10 17:42:56 -07003118}
3119
Eric Laurent8f42ea12018-08-08 09:08:25 -07003120void AudioPolicyManager::closeActiveClients(const sp<AudioInputDescriptor>& input)
Eric Laurent8fc147b2018-07-22 19:13:55 -07003121{
Eric Laurent8f42ea12018-08-08 09:08:25 -07003122 RecordClientVector clients = input->clientsList(true);
Eric Laurent8fc147b2018-07-22 19:13:55 -07003123
3124 for (const auto& client : clients) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003125 closeClient(client->portId());
Eric Laurent8fc147b2018-07-22 19:13:55 -07003126 }
3127}
3128
Eric Laurent8f42ea12018-08-08 09:08:25 -07003129void AudioPolicyManager::closeClient(audio_port_handle_t portId)
3130{
3131 stopInput(portId);
3132 releaseInput(portId);
3133}
Eric Laurent8fc147b2018-07-22 19:13:55 -07003134
Eric Laurent0dd51852019-04-19 18:18:58 -07003135void AudioPolicyManager::checkCloseInputs() {
3136 // After connecting or disconnecting an input device, close input if:
3137 // - it has no client (was just opened to check profile) OR
3138 // - none of its supported devices are connected anymore OR
3139 // - one of its clients cannot be routed to one of its supported
3140 // devices anymore. Otherwise update device selection
3141 std::vector<audio_io_handle_t> inputsToClose;
3142 for (size_t i = 0; i < mInputs.size(); i++) {
3143 const sp<AudioInputDescriptor> input = mInputs.valueAt(i);
3144 if (input->clientsList().size() == 0
Eric Laurent85732f42020-03-19 11:31:10 -07003145 || !mAvailableInputDevices.containsAtLeastOne(input->supportedDevices())) {
Eric Laurent0dd51852019-04-19 18:18:58 -07003146 inputsToClose.push_back(mInputs.keyAt(i));
3147 } else {
3148 bool close = false;
3149 for (const auto& client : input->clientsList()) {
3150 sp<DeviceDescriptor> device =
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02003151 mEngine->getInputDeviceForAttributes(client->attributes(), client->uid(),
3152 client->session());
Eric Laurent0dd51852019-04-19 18:18:58 -07003153 if (!input->supportedDevices().contains(device)) {
3154 close = true;
3155 break;
3156 }
3157 }
3158 if (close) {
3159 inputsToClose.push_back(mInputs.keyAt(i));
3160 } else {
3161 setInputDevice(input->mIoHandle, getNewInputDevice(input));
3162 }
3163 }
3164 }
3165
3166 for (const audio_io_handle_t handle : inputsToClose) {
3167 ALOGV("%s closing input %d", __func__, handle);
3168 closeInput(handle);
Eric Laurent05b90f82014-08-27 15:32:29 -07003169 }
Eric Laurentd4692962014-05-05 18:13:44 -07003170}
3171
François Gaffie251c7f02018-11-07 10:41:08 +01003172void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream, int indexMin, int indexMax)
Eric Laurente552edb2014-03-10 17:42:56 -07003173{
3174 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08003175 if (indexMin < 0 || indexMax < 0) {
3176 ALOGE("%s for stream %d: invalid min %d or max %d", __func__, stream , indexMin, indexMax);
3177 return;
3178 }
Eric Laurentf5aa58d2019-02-22 18:20:11 -08003179 getVolumeCurves(stream).initVolume(indexMin, indexMax);
Eric Laurent28d09f02016-03-08 10:43:05 -08003180
3181 // initialize other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08003182 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
3183 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08003184 continue;
3185 }
Eric Laurentf5aa58d2019-02-22 18:20:11 -08003186 getVolumeCurves((audio_stream_type_t)curStream).initVolume(indexMin, indexMax);
Eric Laurent223fd5c2014-11-11 13:43:36 -08003187 }
Eric Laurente552edb2014-03-10 17:42:56 -07003188}
3189
Eric Laurente0720872014-03-11 09:30:41 -07003190status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
François Gaffie53615e22015-03-19 09:24:12 +01003191 int index,
3192 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07003193{
François Gaffieaaac0fd2018-11-22 17:56:39 +01003194 auto attributes = mEngine->getAttributesForStreamType(stream);
Eric Laurent242a9f82020-03-23 15:57:04 -07003195 if (attributes == AUDIO_ATTRIBUTES_INITIALIZER) {
3196 ALOGW("%s: no group for stream %s, bailing out", __func__, toString(stream).c_str());
3197 return NO_ERROR;
3198 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01003199 ALOGV("%s: stream %s attributes=%s", __func__,
3200 toString(stream).c_str(), toString(attributes).c_str());
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003201 return setVolumeIndexForAttributes(attributes, index, device);
Eric Laurente552edb2014-03-10 17:42:56 -07003202}
3203
Eric Laurente0720872014-03-11 09:30:41 -07003204status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
François Gaffieaaac0fd2018-11-22 17:56:39 +01003205 int *index,
3206 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07003207{
François Gaffiec005e562018-11-06 15:04:49 +01003208 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
3209 // stream by the engine.
jiabin9a3361e2019-10-01 09:38:30 -07003210 DeviceTypeSet deviceTypes = {device};
Eric Laurent5a2b6292016-04-14 18:05:57 -07003211 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
jiabin9a3361e2019-10-01 09:38:30 -07003212 deviceTypes = mEngine->getOutputDevicesForStream(
3213 stream, true /*fromCache*/).types();
Eric Laurente552edb2014-03-10 17:42:56 -07003214 }
jiabin9a3361e2019-10-01 09:38:30 -07003215 return getVolumeIndex(getVolumeCurves(stream), *index, deviceTypes);
Eric Laurente552edb2014-03-10 17:42:56 -07003216}
3217
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003218status_t AudioPolicyManager::setVolumeIndexForAttributes(const audio_attributes_t &attributes,
François Gaffiecfe17322018-11-07 13:41:29 +01003219 int index,
3220 audio_devices_t device)
3221{
3222 // Get Volume group matching the Audio Attributes
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003223 auto group = mEngine->getVolumeGroupForAttributes(attributes);
3224 if (group == VOLUME_GROUP_NONE) {
3225 ALOGD("%s: no group matching with %s", __FUNCTION__, toString(attributes).c_str());
François Gaffiecfe17322018-11-07 13:41:29 +01003226 return BAD_VALUE;
3227 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003228 ALOGV("%s: group %d matching with %s", __FUNCTION__, group, toString(attributes).c_str());
François Gaffiecfe17322018-11-07 13:41:29 +01003229 status_t status = NO_ERROR;
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003230 IVolumeCurves &curves = getVolumeCurves(attributes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01003231 VolumeSource vs = toVolumeSource(group);
Eric Laurentf9cccec2022-11-16 19:12:00 +01003232 // AUDIO_STREAM_BLUETOOTH_SCO is only used for volume control so we remap
3233 // to AUDIO_STREAM_VOICE_CALL to match with relevant playback activity
3234 VolumeSource activityVs = (vs == toVolumeSource(AUDIO_STREAM_BLUETOOTH_SCO, false)) ?
3235 toVolumeSource(AUDIO_STREAM_VOICE_CALL, false) : vs;
François Gaffieaaac0fd2018-11-22 17:56:39 +01003236 product_strategy_t strategy = mEngine->getProductStrategyForAttributes(attributes);
3237
3238 status = setVolumeCurveIndex(index, device, curves);
3239 if (status != NO_ERROR) {
3240 ALOGE("%s failed to set curve index for group %d device 0x%X", __func__, group, device);
3241 return status;
3242 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003243
jiabin9a3361e2019-10-01 09:38:30 -07003244 DeviceTypeSet curSrcDevices;
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003245 auto curCurvAttrs = curves.getAttributes();
3246 if (!curCurvAttrs.empty() && curCurvAttrs.front() != defaultAttr) {
3247 auto attr = curCurvAttrs.front();
jiabin9a3361e2019-10-01 09:38:30 -07003248 curSrcDevices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false).types();
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003249 } else if (!curves.getStreamTypes().empty()) {
3250 auto stream = curves.getStreamTypes().front();
jiabin9a3361e2019-10-01 09:38:30 -07003251 curSrcDevices = mEngine->getOutputDevicesForStream(stream, false).types();
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003252 } else {
3253 ALOGE("%s: Invalid src %d: no valid attributes nor stream",__func__, vs);
3254 return BAD_VALUE;
3255 }
jiabin9a3361e2019-10-01 09:38:30 -07003256 audio_devices_t curSrcDevice = Volume::getDeviceForVolume(curSrcDevices);
3257 resetDeviceTypes(curSrcDevices, curSrcDevice);
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003258
François Gaffiecfe17322018-11-07 13:41:29 +01003259 // update volume on all outputs and streams matching the following:
3260 // - The requested stream (or a stream matching for volume control) is active on the output
3261 // - The device (or devices) selected by the engine for this stream includes
3262 // the requested device
3263 // - For non default requested device, currently selected device on the output is either the
3264 // requested device or one of the devices selected by the engine for this stream
3265 // - For default requested device (AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME), apply volume only if
3266 // no specific device volume value exists for currently selected device.
François Gaffieaaac0fd2018-11-22 17:56:39 +01003267 for (size_t i = 0; i < mOutputs.size(); i++) {
3268 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
jiabin9a3361e2019-10-01 09:38:30 -07003269 DeviceTypeSet curDevices = desc->devices().types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01003270
jiabin9a3361e2019-10-01 09:38:30 -07003271 if (curDevices.erase(AUDIO_DEVICE_OUT_SPEAKER_SAFE)) {
3272 curDevices.insert(AUDIO_DEVICE_OUT_SPEAKER);
Robert Lee5e66e792019-04-03 18:37:15 +08003273 }
Eric Laurentf9cccec2022-11-16 19:12:00 +01003274
3275 if (!(desc->isActive(activityVs) || isInCallOrScreening())) {
François Gaffieed91f582020-01-31 10:35:37 +01003276 continue;
3277 }
3278 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME &&
3279 curDevices.find(device) == curDevices.end()) {
3280 continue;
3281 }
3282 bool applyVolume = false;
3283 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
3284 curSrcDevices.insert(device);
3285 applyVolume = (curSrcDevices.find(
3286 Volume::getDeviceForVolume(curDevices)) != curSrcDevices.end());
3287 } else {
3288 applyVolume = !curves.hasVolumeIndexForDevice(curSrcDevice);
3289 }
3290 if (!applyVolume) {
3291 continue; // next output
3292 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01003293 // Inter / intra volume group priority management: Loop on strategies arranged by priority
3294 // If a higher priority strategy is active, and the output is routed to a device with a
3295 // HW Gain management, do not change the volume
François Gaffieaaac0fd2018-11-22 17:56:39 +01003296 if (desc->useHwGain()) {
François Gaffieed91f582020-01-31 10:35:37 +01003297 applyVolume = false;
Francois Gaffie593634d2021-06-22 13:31:31 +02003298 // If the volume source is active with higher priority source, ensure at least Sw Muted
3299 desc->setSwMute((index == 0), vs, curves.getStreamTypes(), curDevices, 0 /*delayMs*/);
François Gaffieaaac0fd2018-11-22 17:56:39 +01003300 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
3301 auto activeClients = desc->clientsList(true /*activeOnly*/, productStrategy,
3302 false /*preferredDevice*/);
3303 if (activeClients.empty()) {
3304 continue;
3305 }
3306 bool isPreempted = false;
3307 bool isHigherPriority = productStrategy < strategy;
3308 for (const auto &client : activeClients) {
Eric Laurentf9cccec2022-11-16 19:12:00 +01003309 if (isHigherPriority && (client->volumeSource() != activityVs)) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01003310 ALOGV("%s: Strategy=%d (\nrequester:\n"
3311 " group %d, volumeGroup=%d attributes=%s)\n"
3312 " higher priority source active:\n"
3313 " volumeGroup=%d attributes=%s) \n"
3314 " on output %zu, bailing out", __func__, productStrategy,
3315 group, group, toString(attributes).c_str(),
3316 client->volumeSource(), toString(client->attributes()).c_str(), i);
3317 applyVolume = false;
3318 isPreempted = true;
3319 break;
3320 }
3321 // However, continue for loop to ensure no higher prio clients running on output
Eric Laurentf9cccec2022-11-16 19:12:00 +01003322 if (client->volumeSource() == activityVs) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01003323 applyVolume = true;
3324 }
3325 }
3326 if (isPreempted || applyVolume) {
3327 break;
3328 }
3329 }
3330 if (!applyVolume) {
3331 continue; // next output
3332 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01003333 }
François Gaffieed91f582020-01-31 10:35:37 +01003334 //FIXME: workaround for truncated touch sounds
3335 // delayed volume change for system stream to be removed when the problem is
3336 // handled by system UI
3337 status_t volStatus = checkAndSetVolume(
3338 curves, vs, index, desc, curDevices,
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003339 ((vs == toVolumeSource(AUDIO_STREAM_SYSTEM, false))?
François Gaffieed91f582020-01-31 10:35:37 +01003340 TOUCH_SOUND_FIXED_DELAY_MS : 0));
3341 if (volStatus != NO_ERROR) {
3342 status = volStatus;
François Gaffieaaac0fd2018-11-22 17:56:39 +01003343 }
3344 }
François Gaffiecfe17322018-11-07 13:41:29 +01003345 mpClientInterface->onAudioVolumeGroupChanged(group, 0 /*flags*/);
3346 return status;
3347}
3348
François Gaffieaaac0fd2018-11-22 17:56:39 +01003349status_t AudioPolicyManager::setVolumeCurveIndex(int index,
François Gaffiecfe17322018-11-07 13:41:29 +01003350 audio_devices_t device,
3351 IVolumeCurves &volumeCurves)
3352{
3353 // VOICE_CALL stream has minVolumeIndex > 0 but can be muted directly by an
3354 // app that has MODIFY_PHONE_STATE permission.
François Gaffieaaac0fd2018-11-22 17:56:39 +01003355 bool hasVoice = hasVoiceStream(volumeCurves.getStreamTypes());
3356 if (((index < volumeCurves.getVolumeIndexMin()) && !(hasVoice && index == 0)) ||
François Gaffiecfe17322018-11-07 13:41:29 +01003357 (index > volumeCurves.getVolumeIndexMax())) {
3358 ALOGD("%s: wrong index %d min=%d max=%d", __FUNCTION__, index,
3359 volumeCurves.getVolumeIndexMin(), volumeCurves.getVolumeIndexMax());
3360 return BAD_VALUE;
3361 }
3362 if (!audio_is_output_device(device)) {
3363 return BAD_VALUE;
3364 }
3365
3366 // Force max volume if stream cannot be muted
3367 if (!volumeCurves.canBeMuted()) index = volumeCurves.getVolumeIndexMax();
3368
François Gaffieaaac0fd2018-11-22 17:56:39 +01003369 ALOGV("%s device %08x, index %d", __FUNCTION__ , device, index);
François Gaffiecfe17322018-11-07 13:41:29 +01003370 volumeCurves.addCurrentVolumeIndex(device, index);
3371 return NO_ERROR;
3372}
3373
3374status_t AudioPolicyManager::getVolumeIndexForAttributes(const audio_attributes_t &attr,
3375 int &index,
3376 audio_devices_t device)
3377{
3378 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
3379 // stream by the engine.
jiabin9a3361e2019-10-01 09:38:30 -07003380 DeviceTypeSet deviceTypes = {device};
François Gaffiecfe17322018-11-07 13:41:29 +01003381 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
Mikhail Naganovbb990f22022-06-15 00:46:43 +00003382 deviceTypes = mEngine->getOutputDevicesForAttributes(
jiabin9a3361e2019-10-01 09:38:30 -07003383 attr, nullptr, true /*fromCache*/).types();
François Gaffiecfe17322018-11-07 13:41:29 +01003384 }
jiabin9a3361e2019-10-01 09:38:30 -07003385 return getVolumeIndex(getVolumeCurves(attr), index, deviceTypes);
François Gaffiecfe17322018-11-07 13:41:29 +01003386}
3387
3388status_t AudioPolicyManager::getVolumeIndex(const IVolumeCurves &curves,
3389 int &index,
jiabin9a3361e2019-10-01 09:38:30 -07003390 const DeviceTypeSet& deviceTypes) const
François Gaffiecfe17322018-11-07 13:41:29 +01003391{
Mikhail Naganovbb990f22022-06-15 00:46:43 +00003392 if (!isSingleDeviceType(deviceTypes, audio_is_output_device)) {
François Gaffiecfe17322018-11-07 13:41:29 +01003393 return BAD_VALUE;
3394 }
jiabin9a3361e2019-10-01 09:38:30 -07003395 index = curves.getVolumeIndex(deviceTypes);
3396 ALOGV("%s: device %s index %d", __FUNCTION__, dumpDeviceTypes(deviceTypes).c_str(), index);
François Gaffiecfe17322018-11-07 13:41:29 +01003397 return NO_ERROR;
3398}
3399
3400status_t AudioPolicyManager::getMinVolumeIndexForAttributes(const audio_attributes_t &attr,
3401 int &index)
3402{
3403 index = getVolumeCurves(attr).getVolumeIndexMin();
3404 return NO_ERROR;
3405}
3406
3407status_t AudioPolicyManager::getMaxVolumeIndexForAttributes(const audio_attributes_t &attr,
3408 int &index)
3409{
3410 index = getVolumeCurves(attr).getVolumeIndexMax();
3411 return NO_ERROR;
3412}
3413
Eric Laurent36829f92017-04-07 19:04:42 -07003414audio_io_handle_t AudioPolicyManager::selectOutputForMusicEffects()
Eric Laurente552edb2014-03-10 17:42:56 -07003415{
3416 // select one output among several suitable for global effects.
3417 // The priority is as follows:
3418 // 1: An offloaded output. If the effect ends up not being offloadable,
3419 // AudioFlinger will invalidate the track and the offloaded output
3420 // will be closed causing the effect to be moved to a PCM output.
3421 // 2: A deep buffer output
Eric Laurent36829f92017-04-07 19:04:42 -07003422 // 3: The primary output
3423 // 4: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07003424
François Gaffiec005e562018-11-06 15:04:49 +01003425 DeviceVector devices = mEngine->getOutputDevicesForAttributes(
3426 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
François Gaffie11d30102018-11-02 16:09:09 +01003427 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07003428
Eric Laurent36829f92017-04-07 19:04:42 -07003429 if (outputs.size() == 0) {
3430 return AUDIO_IO_HANDLE_NONE;
3431 }
Eric Laurente552edb2014-03-10 17:42:56 -07003432
Eric Laurent36829f92017-04-07 19:04:42 -07003433 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
3434 bool activeOnly = true;
3435
3436 while (output == AUDIO_IO_HANDLE_NONE) {
3437 audio_io_handle_t outputOffloaded = AUDIO_IO_HANDLE_NONE;
3438 audio_io_handle_t outputDeepBuffer = AUDIO_IO_HANDLE_NONE;
3439 audio_io_handle_t outputPrimary = AUDIO_IO_HANDLE_NONE;
3440
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003441 for (audio_io_handle_t output : outputs) {
3442 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
Eric Laurent83d17c22019-04-02 17:10:01 -07003443 if (activeOnly && !desc->isActive(toVolumeSource(AUDIO_STREAM_MUSIC))) {
Eric Laurent36829f92017-04-07 19:04:42 -07003444 continue;
3445 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003446 ALOGV("selectOutputForMusicEffects activeOnly %d output %d flags 0x%08x",
3447 activeOnly, output, desc->mFlags);
Eric Laurent36829f92017-04-07 19:04:42 -07003448 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003449 outputOffloaded = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003450 }
3451 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003452 outputDeepBuffer = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003453 }
3454 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003455 outputPrimary = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003456 }
3457 }
3458 if (outputOffloaded != AUDIO_IO_HANDLE_NONE) {
3459 output = outputOffloaded;
3460 } else if (outputDeepBuffer != AUDIO_IO_HANDLE_NONE) {
3461 output = outputDeepBuffer;
3462 } else if (outputPrimary != AUDIO_IO_HANDLE_NONE) {
3463 output = outputPrimary;
3464 } else {
3465 output = outputs[0];
3466 }
3467 activeOnly = false;
3468 }
3469
3470 if (output != mMusicEffectOutput) {
Eric Laurent6c796322019-04-09 14:13:17 -07003471 mEffects.moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output);
Eric Laurent36829f92017-04-07 19:04:42 -07003472 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output);
3473 mMusicEffectOutput = output;
3474 }
3475
3476 ALOGV("selectOutputForMusicEffects selected output %d", output);
Eric Laurente552edb2014-03-10 17:42:56 -07003477 return output;
3478}
3479
Eric Laurent36829f92017-04-07 19:04:42 -07003480audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc __unused)
3481{
3482 return selectOutputForMusicEffects();
3483}
3484
Eric Laurente0720872014-03-11 09:30:41 -07003485status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07003486 audio_io_handle_t io,
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08003487 product_strategy_t strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07003488 int session,
3489 int id)
3490{
Eric Laurentb82e6b72019-11-22 17:25:04 -08003491 if (session != AUDIO_SESSION_DEVICE) {
3492 ssize_t index = mOutputs.indexOfKey(io);
Eric Laurente552edb2014-03-10 17:42:56 -07003493 if (index < 0) {
Eric Laurentb82e6b72019-11-22 17:25:04 -08003494 index = mInputs.indexOfKey(io);
3495 if (index < 0) {
3496 ALOGW("registerEffect() unknown io %d", io);
3497 return INVALID_OPERATION;
3498 }
Eric Laurente552edb2014-03-10 17:42:56 -07003499 }
3500 }
Eric Laurentbf8f69f2022-03-25 17:48:38 +01003501 bool isMusicEffect = (session != AUDIO_SESSION_OUTPUT_STAGE)
3502 && ((strategy == streamToStrategy(AUDIO_STREAM_MUSIC)
3503 || strategy == PRODUCT_STRATEGY_NONE));
3504 return mEffects.registerEffect(desc, io, session, id, isMusicEffect);
Eric Laurente552edb2014-03-10 17:42:56 -07003505}
3506
Eric Laurentc241b0d2018-11-28 09:08:49 -08003507status_t AudioPolicyManager::unregisterEffect(int id)
3508{
3509 if (mEffects.getEffect(id) == nullptr) {
3510 return INVALID_OPERATION;
3511 }
Eric Laurentc241b0d2018-11-28 09:08:49 -08003512 if (mEffects.isEffectEnabled(id)) {
3513 ALOGW("%s effect %d enabled", __FUNCTION__, id);
3514 setEffectEnabled(id, false);
3515 }
3516 return mEffects.unregisterEffect(id);
3517}
3518
3519status_t AudioPolicyManager::setEffectEnabled(int id, bool enabled)
3520{
3521 sp<EffectDescriptor> effect = mEffects.getEffect(id);
3522 if (effect == nullptr) {
3523 return INVALID_OPERATION;
3524 }
3525
3526 status_t status = mEffects.setEffectEnabled(id, enabled);
3527 if (status == NO_ERROR) {
3528 mInputs.trackEffectEnabled(effect, enabled);
3529 }
3530 return status;
3531}
3532
Eric Laurent6c796322019-04-09 14:13:17 -07003533
3534status_t AudioPolicyManager::moveEffectsToIo(const std::vector<int>& ids, audio_io_handle_t io)
3535{
3536 mEffects.moveEffects(ids, io);
3537 return NO_ERROR;
3538}
3539
Eric Laurentc75307b2015-03-17 15:29:32 -07003540bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
3541{
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003542 auto vs = toVolumeSource(stream, false);
3543 return vs != VOLUME_SOURCE_NONE ? mOutputs.isActive(vs, inPastMs) : false;
Eric Laurentc75307b2015-03-17 15:29:32 -07003544}
3545
3546bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream, uint32_t inPastMs) const
3547{
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003548 auto vs = toVolumeSource(stream, false);
3549 return vs != VOLUME_SOURCE_NONE ? mOutputs.isActiveRemotely(vs, inPastMs) : false;
Eric Laurentc75307b2015-03-17 15:29:32 -07003550}
3551
Eric Laurente0720872014-03-11 09:30:41 -07003552bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07003553{
3554 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003555 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08003556 if (inputDescriptor->isSourceActive(source)) {
Eric Laurente552edb2014-03-10 17:42:56 -07003557 return true;
3558 }
3559 }
3560 return false;
3561}
3562
Eric Laurent275e8e92014-11-30 15:14:47 -08003563// Register a list of custom mixes with their attributes and format.
3564// When a mix is registered, corresponding input and output profiles are
3565// added to the remote submix hw module. The profile contains only the
3566// parameters (sampling rate, format...) specified by the mix.
3567// The corresponding input remote submix device is also connected.
3568//
3569// When a remote submix device is connected, the address is checked to select the
3570// appropriate profile and the corresponding input or output stream is opened.
3571//
3572// When capture starts, getInputForAttr() will:
3573// - 1 look for a mix matching the address passed in attribtutes tags if any
3574// - 2 if none found, getDeviceForInputSource() will:
3575// - 2.1 look for a mix matching the attributes source
3576// - 2.2 if none found, default to device selection by policy rules
3577// At this time, the corresponding output remote submix device is also connected
3578// and active playback use cases can be transferred to this mix if needed when reconnecting
3579// after AudioTracks are invalidated
3580//
3581// When playback starts, getOutputForAttr() will:
3582// - 1 look for a mix matching the address passed in attribtutes tags if any
3583// - 2 if none found, look for a mix matching the attributes usage
3584// - 3 if none found, default to device and output selection by policy rules.
3585
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003586status_t AudioPolicyManager::registerPolicyMixes(const Vector<AudioMix>& mixes)
Eric Laurent275e8e92014-11-30 15:14:47 -08003587{
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003588 ALOGV("registerPolicyMixes() %zu mix(es)", mixes.size());
3589 status_t res = NO_ERROR;
Eric Laurentc209fe42020-06-05 18:11:23 -07003590 bool checkOutputs = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003591 sp<HwModule> rSubmixModule;
3592 // examine each mix's route type
3593 for (size_t i = 0; i < mixes.size(); i++) {
Eric Laurent97ac8712018-07-27 18:59:02 -07003594 AudioMix mix = mixes[i];
Kevin Rocard153f92d2018-12-18 18:33:28 -08003595 // Only capture of playback is allowed in LOOP_BACK & RENDER mode
3596 if (is_mix_loopback_render(mix.mRouteFlags) && mix.mMixType != MIX_TYPE_PLAYERS) {
3597 ALOGE("Unsupported Policy Mix %zu of %zu: "
3598 "Only capture of playback is allowed in LOOP_BACK & RENDER mode",
3599 i, mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003600 res = INVALID_OPERATION;
Eric Laurent275e8e92014-11-30 15:14:47 -08003601 break;
3602 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08003603 // LOOP_BACK and LOOP_BACK | RENDER have the same remote submix backend and are handled
3604 // in the same way.
Eric Laurent97ac8712018-07-27 18:59:02 -07003605 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003606 ALOGV("registerPolicyMixes() mix %zu of %zu is LOOP_BACK %d", i, mixes.size(),
3607 mix.mRouteFlags);
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003608 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003609 rSubmixModule = mHwModules.getModuleFromName(
3610 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
3611 if (rSubmixModule == 0) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003612 ALOGE("Unable to find audio module for submix, aborting mix %zu registration",
Mikhail Naganovd4120142017-12-06 15:49:22 -08003613 i);
3614 res = INVALID_OPERATION;
3615 break;
3616 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003617 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003618
Eric Laurent97ac8712018-07-27 18:59:02 -07003619 String8 address = mix.mDeviceAddress;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003620 audio_devices_t deviceTypeToMakeAvailable;
Eric Laurent97ac8712018-07-27 18:59:02 -07003621 if (mix.mMixType == MIX_TYPE_PLAYERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07003622 mix.mDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003623 deviceTypeToMakeAvailable = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
3624 } else {
3625 mix.mDeviceType = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
3626 deviceTypeToMakeAvailable = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Eric Laurent97ac8712018-07-27 18:59:02 -07003627 }
François Gaffie036e1e92015-03-19 10:16:24 +01003628
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003629 if (mPolicyMixes.registerMix(mix, 0 /*output desc*/) != NO_ERROR) {
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00003630 ALOGE("Error registering mix %zu for address %s", i, address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003631 res = INVALID_OPERATION;
3632 break;
3633 }
Eric Laurent97ac8712018-07-27 18:59:02 -07003634 audio_config_t outputConfig = mix.mFormat;
3635 audio_config_t inputConfig = mix.mFormat;
Eric Laurentc529cf62020-04-17 18:19:10 -07003636 // NOTE: audio flinger mixer does not support mono output: configure remote submix HAL
3637 // in stereo and let audio flinger do the channel conversion if needed.
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003638 outputConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
3639 inputConfig.channel_mask = AUDIO_CHANNEL_IN_STEREO;
jiabin5740f082019-08-19 15:08:30 -07003640 rSubmixModule->addOutputProfile(address.c_str(), &outputConfig,
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003641 AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address);
jiabin5740f082019-08-19 15:08:30 -07003642 rSubmixModule->addInputProfile(address.c_str(), &inputConfig,
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003643 AUDIO_DEVICE_IN_REMOTE_SUBMIX, address);
François Gaffie036e1e92015-03-19 10:16:24 +01003644
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003645 if ((res = setDeviceConnectionStateInt(deviceTypeToMakeAvailable,
jiabinc1de2df2019-05-07 14:26:40 -07003646 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00003647 address.c_str(), "remote-submix", AUDIO_FORMAT_DEFAULT)) != NO_ERROR) {
jiabinc1de2df2019-05-07 14:26:40 -07003648 ALOGE("Failed to set remote submix device available, type %u, address %s",
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00003649 mix.mDeviceType, address.c_str());
jiabinc1de2df2019-05-07 14:26:40 -07003650 break;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003651 }
Eric Laurent97ac8712018-07-27 18:59:02 -07003652 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
3653 String8 address = mix.mDeviceAddress;
Eric Laurent2c80be02019-01-23 18:06:37 -08003654 audio_devices_t type = mix.mDeviceType;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003655 ALOGV(" registerPolicyMixes() mix %zu of %zu is RENDER, dev=0x%X addr=%s",
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00003656 i, mixes.size(), type, address.c_str());
Eric Laurent2c80be02019-01-23 18:06:37 -08003657
3658 sp<DeviceDescriptor> device = mHwModules.getDeviceDescriptor(
3659 mix.mDeviceType, mix.mDeviceAddress,
3660 String8(), AUDIO_FORMAT_DEFAULT);
3661 if (device == nullptr) {
3662 res = INVALID_OPERATION;
3663 break;
3664 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003665
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003666 bool foundOutput = false;
Eric Laurentc529cf62020-04-17 18:19:10 -07003667 // First try to find an already opened output supporting the device
3668 for (size_t j = 0 ; j < mOutputs.size() && !foundOutput && res == NO_ERROR; j++) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003669 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurent2c80be02019-01-23 18:06:37 -08003670
Eric Laurentc529cf62020-04-17 18:19:10 -07003671 if (!desc->isDuplicated() && desc->supportedDevices().contains(device)) {
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003672 if (mPolicyMixes.registerMix(mix, desc) != NO_ERROR) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003673 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00003674 address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003675 res = INVALID_OPERATION;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003676 } else {
3677 foundOutput = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003678 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003679 }
3680 }
Eric Laurentc529cf62020-04-17 18:19:10 -07003681 // If no output found, try to find a direct output profile supporting the device
3682 for (size_t i = 0; i < mHwModules.size() && !foundOutput && res == NO_ERROR; i++) {
3683 sp<HwModule> module = mHwModules[i];
3684 for (size_t j = 0;
3685 j < module->getOutputProfiles().size() && !foundOutput && res == NO_ERROR;
3686 j++) {
3687 sp<IOProfile> profile = module->getOutputProfiles()[j];
3688 if (profile->isDirectOutput() && profile->supportsDevice(device)) {
3689 if (mPolicyMixes.registerMix(mix, nullptr) != NO_ERROR) {
3690 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00003691 address.c_str());
Eric Laurentc529cf62020-04-17 18:19:10 -07003692 res = INVALID_OPERATION;
3693 } else {
3694 foundOutput = true;
3695 }
3696 }
3697 }
3698 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003699 if (res != NO_ERROR) {
3700 ALOGE(" Error registering mix %zu for device 0x%X addr %s",
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00003701 i, type, address.c_str());
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003702 res = INVALID_OPERATION;
3703 break;
3704 } else if (!foundOutput) {
3705 ALOGE(" Output not found for mix %zu for device 0x%X addr %s",
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00003706 i, type, address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003707 res = INVALID_OPERATION;
3708 break;
Eric Laurentc209fe42020-06-05 18:11:23 -07003709 } else {
3710 checkOutputs = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003711 }
Eric Laurentc722f302014-12-10 11:21:49 -08003712 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003713 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003714 if (res != NO_ERROR) {
3715 unregisterPolicyMixes(mixes);
Eric Laurentc209fe42020-06-05 18:11:23 -07003716 } else if (checkOutputs) {
3717 checkForDeviceAndOutputChanges();
3718 updateCallAndOutputRouting();
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003719 }
3720 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08003721}
3722
3723status_t AudioPolicyManager::unregisterPolicyMixes(Vector<AudioMix> mixes)
3724{
Eric Laurent7b279bb2015-12-14 10:18:23 -08003725 ALOGV("unregisterPolicyMixes() num mixes %zu", mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003726 status_t res = NO_ERROR;
Eric Laurentc209fe42020-06-05 18:11:23 -07003727 bool checkOutputs = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003728 sp<HwModule> rSubmixModule;
3729 // examine each mix's route type
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003730 for (const auto& mix : mixes) {
3731 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie036e1e92015-03-19 10:16:24 +01003732
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003733 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003734 rSubmixModule = mHwModules.getModuleFromName(
3735 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
3736 if (rSubmixModule == 0) {
3737 res = INVALID_OPERATION;
3738 continue;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003739 }
3740 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003741
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003742 String8 address = mix.mDeviceAddress;
Eric Laurent275e8e92014-11-30 15:14:47 -08003743
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003744 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003745 res = INVALID_OPERATION;
3746 continue;
3747 }
3748
Kevin Rocard04ed0462019-05-02 17:53:24 -07003749 for (auto device : {AUDIO_DEVICE_IN_REMOTE_SUBMIX, AUDIO_DEVICE_OUT_REMOTE_SUBMIX}) {
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00003750 if (getDeviceConnectionState(device, address.c_str()) ==
Kevin Rocard04ed0462019-05-02 17:53:24 -07003751 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
3752 res = setDeviceConnectionStateInt(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00003753 address.c_str(), "remote-submix",
Kevin Rocard04ed0462019-05-02 17:53:24 -07003754 AUDIO_FORMAT_DEFAULT);
3755 if (res != OK) {
3756 ALOGE("Error making RemoteSubmix device unavailable for mix "
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00003757 "with type %d, address %s", device, address.c_str());
Kevin Rocard04ed0462019-05-02 17:53:24 -07003758 }
3759 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003760 }
jiabin5740f082019-08-19 15:08:30 -07003761 rSubmixModule->removeOutputProfile(address.c_str());
3762 rSubmixModule->removeInputProfile(address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003763
Kevin Rocard153f92d2018-12-18 18:33:28 -08003764 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003765 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003766 res = INVALID_OPERATION;
3767 continue;
Eric Laurentc209fe42020-06-05 18:11:23 -07003768 } else {
3769 checkOutputs = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003770 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003771 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003772 }
Eric Laurentc209fe42020-06-05 18:11:23 -07003773 if (res == NO_ERROR && checkOutputs) {
3774 checkForDeviceAndOutputChanges();
3775 updateCallAndOutputRouting();
3776 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003777 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08003778}
3779
Mikhail Naganov100f0122018-11-29 11:22:16 -08003780void AudioPolicyManager::dumpManualSurroundFormats(String8 *dst) const
3781{
3782 size_t i = 0;
3783 constexpr size_t audioFormatPrefixLen = sizeof("AUDIO_FORMAT_");
3784 for (const auto& fmt : mManualSurroundFormats) {
3785 if (i++ != 0) dst->append(", ");
3786 std::string sfmt;
3787 FormatConverter::toString(fmt, sfmt);
3788 dst->append(sfmt.size() >= audioFormatPrefixLen ?
3789 sfmt.c_str() + audioFormatPrefixLen - 1 : sfmt.c_str());
3790 }
3791}
3792
Eric Laurentc529cf62020-04-17 18:19:10 -07003793// Returns true if all devices types match the predicate and are supported by one HW module
3794bool AudioPolicyManager::areAllDevicesSupported(
jiabin6a02d532020-08-07 11:56:38 -07003795 const AudioDeviceTypeAddrVector& devices,
Eric Laurentc529cf62020-04-17 18:19:10 -07003796 std::function<bool(audio_devices_t)> predicate,
Eric Laurent78fedbf2023-03-09 14:40:44 +01003797 const char *context,
3798 bool matchAddress) {
Eric Laurentc529cf62020-04-17 18:19:10 -07003799 for (size_t i = 0; i < devices.size(); i++) {
3800 sp<DeviceDescriptor> devDesc = mHwModules.getDeviceDescriptor(
jiabin0a488932020-08-07 17:32:40 -07003801 devices[i].mType, devices[i].getAddress(), String8(),
Eric Laurent78fedbf2023-03-09 14:40:44 +01003802 AUDIO_FORMAT_DEFAULT, false /*allowToCreate*/, matchAddress);
Eric Laurentc529cf62020-04-17 18:19:10 -07003803 if (devDesc == nullptr || (predicate != nullptr && !predicate(devices[i].mType))) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003804 ALOGE("%s: device type %#x address %s not supported or not match predicate",
jiabin0a488932020-08-07 17:32:40 -07003805 context, devices[i].mType, devices[i].getAddress());
Eric Laurentc529cf62020-04-17 18:19:10 -07003806 return false;
3807 }
3808 }
3809 return true;
3810}
3811
Oscar Azucena6acf34b2023-04-27 16:32:09 -07003812void AudioPolicyManager::changeOutputDevicesMuteState(
3813 const AudioDeviceTypeAddrVector& devices) {
3814 ALOGVV("%s() num devices %zu", __func__, devices.size());
3815
3816 std::vector<sp<SwAudioOutputDescriptor>> outputs =
3817 getSoftwareOutputsForDevices(devices);
3818
3819 for (size_t i = 0; i < outputs.size(); i++) {
3820 sp<SwAudioOutputDescriptor> outputDesc = outputs[i];
3821 DeviceVector prevDevices = outputDesc->devices();
3822 checkDeviceMuteStrategies(outputDesc, prevDevices, 0 /* delayMs */);
3823 }
3824}
3825
3826std::vector<sp<SwAudioOutputDescriptor>> AudioPolicyManager::getSoftwareOutputsForDevices(
3827 const AudioDeviceTypeAddrVector& devices) const
3828{
3829 std::vector<sp<SwAudioOutputDescriptor>> outputs;
3830 DeviceVector deviceDescriptors;
3831 for (size_t j = 0; j < devices.size(); j++) {
3832 sp<DeviceDescriptor> desc = mHwModules.getDeviceDescriptor(
3833 devices[j].mType, devices[j].getAddress(), String8(), AUDIO_FORMAT_DEFAULT);
3834 if (desc == nullptr || !audio_is_output_device(devices[j].mType)) {
3835 ALOGE("%s: device type %#x address %s not supported or not an output device",
3836 __func__, devices[j].mType, devices[j].getAddress());
3837 continue;
3838 }
3839 deviceDescriptors.add(desc);
3840 }
3841 for (size_t i = 0; i < mOutputs.size(); i++) {
3842 if (!mOutputs.valueAt(i)->supportsAtLeastOne(deviceDescriptors)) {
3843 continue;
3844 }
3845 outputs.push_back(mOutputs.valueAt(i));
3846 }
3847 return outputs;
3848}
3849
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003850status_t AudioPolicyManager::setUidDeviceAffinities(uid_t uid,
jiabin6a02d532020-08-07 11:56:38 -07003851 const AudioDeviceTypeAddrVector& devices) {
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003852 ALOGV("%s() uid=%d num devices %zu", __FUNCTION__, uid, devices.size());
Eric Laurentc529cf62020-04-17 18:19:10 -07003853 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
3854 return BAD_VALUE;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003855 }
3856 status_t res = mPolicyMixes.setUidDeviceAffinities(uid, devices);
Eric Laurentc529cf62020-04-17 18:19:10 -07003857 if (res != NO_ERROR) {
3858 ALOGE("%s() Could not set all device affinities for uid = %d", __FUNCTION__, uid);
3859 return res;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003860 }
Eric Laurentc529cf62020-04-17 18:19:10 -07003861
3862 checkForDeviceAndOutputChanges();
3863 updateCallAndOutputRouting();
3864
3865 return NO_ERROR;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003866}
3867
3868status_t AudioPolicyManager::removeUidDeviceAffinities(uid_t uid) {
3869 ALOGV("%s() uid=%d", __FUNCTION__, uid);
Oscar Azucena4b2a8212019-04-26 23:48:59 -07003870 status_t res = mPolicyMixes.removeUidDeviceAffinities(uid);
3871 if (res != NO_ERROR) {
Eric Laurentc529cf62020-04-17 18:19:10 -07003872 ALOGE("%s() Could not remove all device affinities for uid = %d",
Oscar Azucena4b2a8212019-04-26 23:48:59 -07003873 __FUNCTION__, uid);
3874 return INVALID_OPERATION;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003875 }
3876
Eric Laurentc529cf62020-04-17 18:19:10 -07003877 checkForDeviceAndOutputChanges();
3878 updateCallAndOutputRouting();
3879
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003880 return res;
3881}
3882
Eric Laurent2517af32020-11-25 15:31:27 +01003883
jiabin0a488932020-08-07 17:32:40 -07003884status_t AudioPolicyManager::setDevicesRoleForStrategy(product_strategy_t strategy,
3885 device_role_t role,
3886 const AudioDeviceTypeAddrVector &devices) {
3887 ALOGV("%s() strategy=%d role=%d %s", __func__, strategy, role,
3888 dumpAudioDeviceTypeAddrVector(devices).c_str());
Eric Laurentc529cf62020-04-17 18:19:10 -07003889
Eric Laurentc529cf62020-04-17 18:19:10 -07003890 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003891 return BAD_VALUE;
3892 }
jiabin0a488932020-08-07 17:32:40 -07003893 status_t status = mEngine->setDevicesRoleForStrategy(strategy, role, devices);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003894 if (status != NO_ERROR) {
jiabin0a488932020-08-07 17:32:40 -07003895 ALOGW("Engine could not set preferred devices %s for strategy %d role %d",
3896 dumpAudioDeviceTypeAddrVector(devices).c_str(), strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003897 return status;
3898 }
3899
3900 checkForDeviceAndOutputChanges();
Eric Laurent2517af32020-11-25 15:31:27 +01003901
3902 bool forceVolumeReeval = false;
3903 // FIXME: workaround for truncated touch sounds
3904 // to be removed when the problem is handled by system UI
3905 uint32_t delayMs = 0;
3906 if (strategy == mCommunnicationStrategy) {
3907 forceVolumeReeval = true;
3908 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
3909 updateInputRouting();
3910 }
3911 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003912
3913 return NO_ERROR;
3914}
3915
Oscar Azucena6acf34b2023-04-27 16:32:09 -07003916void AudioPolicyManager::updateCallAndOutputRouting(bool forceVolumeReeval, uint32_t delayMs,
3917 bool skipDelays)
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003918{
3919 uint32_t waitMs = 0;
Eric Laurent96d1dda2022-03-14 17:14:19 +01003920 bool wasLeUnicastActive = isLeUnicastActive();
Francois Gaffie19fd6c52021-02-04 17:02:59 +01003921 if (updateCallRouting(true /*fromCache*/, delayMs, &waitMs) == NO_ERROR) {
Eric Laurentb36b4ac2020-08-21 12:50:41 -07003922 // Only apply special touch sound delay once
3923 delayMs = 0;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003924 }
jiabin3ff8d7d2022-12-13 06:27:44 +00003925 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003926 for (size_t i = 0; i < mOutputs.size(); i++) {
3927 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
3928 DeviceVector newDevices = getNewOutputDevices(outputDesc, true /*fromCache*/);
Francois Gaffie601801d2021-06-22 13:27:39 +02003929 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) ||
3930 (outputDesc != mPrimaryOutput && !isTelephonyRxOrTx(outputDesc))) {
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003931 // As done in setDeviceConnectionState, we could also fix default device issue by
3932 // preventing the force re-routing in case of default dev that distinguishes on address.
3933 // Let's give back to engine full device choice decision however.
Francois Gaffie601801d2021-06-22 13:27:39 +02003934 bool forceRouting = !newDevices.isEmpty();
jiabin3ff8d7d2022-12-13 06:27:44 +00003935 if (outputDesc->mUsePreferredMixerAttributes && newDevices != outputDesc->devices()) {
3936 // If the device is using preferred mixer attributes, the output need to reopen
3937 // with default configuration when the new selected devices are different from
3938 // current routing devices.
3939 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices);
3940 continue;
3941 }
Francois Gaffie601801d2021-06-22 13:27:39 +02003942 waitMs = setOutputDevices(outputDesc, newDevices, forceRouting, delayMs, nullptr,
Oscar Azucena6acf34b2023-04-27 16:32:09 -07003943 !skipDelays /*requiresMuteCheck*/,
3944 !forceRouting /*requiresVolumeCheck*/, skipDelays);
Eric Laurentb36b4ac2020-08-21 12:50:41 -07003945 // Only apply special touch sound delay once
3946 delayMs = 0;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003947 }
3948 if (forceVolumeReeval && !newDevices.isEmpty()) {
3949 applyStreamVolumes(outputDesc, newDevices.types(), waitMs, true);
3950 }
3951 }
jiabin3ff8d7d2022-12-13 06:27:44 +00003952 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent96d1dda2022-03-14 17:14:19 +01003953 checkLeBroadcastRoutes(wasLeUnicastActive, nullptr, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003954}
3955
Eric Laurent2517af32020-11-25 15:31:27 +01003956void AudioPolicyManager::updateInputRouting() {
3957 for (const auto& activeDesc : mInputs.getActiveInputs()) {
Jaideep Sharma408349a2020-11-27 14:47:17 +05303958 // Skip for hotword recording as the input device switch
3959 // is handled within sound trigger HAL
3960 if (activeDesc->isSoundTrigger() && activeDesc->source() == AUDIO_SOURCE_HOTWORD) {
3961 continue;
3962 }
Eric Laurent2517af32020-11-25 15:31:27 +01003963 auto newDevice = getNewInputDevice(activeDesc);
3964 // Force new input selection if the new device can not be reached via current input
3965 if (activeDesc->mProfile->getSupportedDevices().contains(newDevice)) {
3966 setInputDevice(activeDesc->mIoHandle, newDevice);
3967 } else {
3968 closeInput(activeDesc->mIoHandle);
3969 }
3970 }
3971}
3972
Paul Wang5d7cdb52022-11-22 09:45:06 +00003973status_t
3974AudioPolicyManager::removeDevicesRoleForStrategy(product_strategy_t strategy,
3975 device_role_t role,
3976 const AudioDeviceTypeAddrVector &devices) {
3977 ALOGV("%s() strategy=%d role=%d %s", __func__, strategy, role,
3978 dumpAudioDeviceTypeAddrVector(devices).c_str());
3979
Eric Laurent78fedbf2023-03-09 14:40:44 +01003980 if (!areAllDevicesSupported(
3981 devices, audio_is_output_device, __func__, /*matchAddress*/false)) {
Paul Wang5d7cdb52022-11-22 09:45:06 +00003982 return BAD_VALUE;
3983 }
3984 status_t status = mEngine->removeDevicesRoleForStrategy(strategy, role, devices);
3985 if (status != NO_ERROR) {
3986 ALOGW("Engine could not remove devices %s for strategy %d role %d",
3987 dumpAudioDeviceTypeAddrVector(devices).c_str(), strategy, role);
3988 return status;
3989 }
3990
3991 checkForDeviceAndOutputChanges();
3992
3993 bool forceVolumeReeval = false;
3994 // TODO(b/263479999): workaround for truncated touch sounds
3995 // to be removed when the problem is handled by system UI
3996 uint32_t delayMs = 0;
3997 if (strategy == mCommunnicationStrategy) {
3998 forceVolumeReeval = true;
3999 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
4000 updateInputRouting();
4001 }
4002 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
4003
4004 return NO_ERROR;
4005}
4006
4007status_t AudioPolicyManager::clearDevicesRoleForStrategy(product_strategy_t strategy,
4008 device_role_t role)
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004009{
Eric Laurentfecbceb2021-02-09 14:46:43 +01004010 ALOGV("%s() strategy=%d role=%d", __func__, strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004011
Paul Wang5d7cdb52022-11-22 09:45:06 +00004012 status_t status = mEngine->clearDevicesRoleForStrategy(strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004013 if (status != NO_ERROR) {
Eric Laurent9ae44f32022-12-14 16:17:02 +01004014 ALOGW_IF(status != NAME_NOT_FOUND,
4015 "Engine could not remove device role for strategy %d status %d",
Eric Laurent2517af32020-11-25 15:31:27 +01004016 strategy, status);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004017 return status;
4018 }
4019
4020 checkForDeviceAndOutputChanges();
Eric Laurent2517af32020-11-25 15:31:27 +01004021
4022 bool forceVolumeReeval = false;
4023 // FIXME: workaround for truncated touch sounds
4024 // to be removed when the problem is handled by system UI
4025 uint32_t delayMs = 0;
4026 if (strategy == mCommunnicationStrategy) {
4027 forceVolumeReeval = true;
4028 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
4029 updateInputRouting();
4030 }
4031 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004032
4033 return NO_ERROR;
4034}
4035
jiabin0a488932020-08-07 17:32:40 -07004036status_t AudioPolicyManager::getDevicesForRoleAndStrategy(product_strategy_t strategy,
4037 device_role_t role,
4038 AudioDeviceTypeAddrVector &devices) {
4039 return mEngine->getDevicesForRoleAndStrategy(strategy, role, devices);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004040}
4041
Jiabin Huang3b98d322020-09-03 17:54:16 +00004042status_t AudioPolicyManager::setDevicesRoleForCapturePreset(
4043 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices) {
4044 ALOGV("%s() audioSource=%d role=%d %s", __func__, audioSource, role,
4045 dumpAudioDeviceTypeAddrVector(devices).c_str());
4046
Mikhail Naganov55773032020-10-01 15:08:13 -07004047 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00004048 return BAD_VALUE;
4049 }
4050 status_t status = mEngine->setDevicesRoleForCapturePreset(audioSource, role, devices);
4051 ALOGW_IF(status != NO_ERROR,
4052 "Engine could not set preferred devices %s for audio source %d role %d",
4053 dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
4054
4055 return status;
4056}
4057
4058status_t AudioPolicyManager::addDevicesRoleForCapturePreset(
4059 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices) {
4060 ALOGV("%s() audioSource=%d role=%d %s", __func__, audioSource, role,
4061 dumpAudioDeviceTypeAddrVector(devices).c_str());
4062
Mikhail Naganov55773032020-10-01 15:08:13 -07004063 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00004064 return BAD_VALUE;
4065 }
4066 status_t status = mEngine->addDevicesRoleForCapturePreset(audioSource, role, devices);
4067 ALOGW_IF(status != NO_ERROR,
4068 "Engine could not add preferred devices %s for audio source %d role %d",
4069 dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
4070
Eric Laurent2517af32020-11-25 15:31:27 +01004071 updateInputRouting();
Jiabin Huang3b98d322020-09-03 17:54:16 +00004072 return status;
4073}
4074
4075status_t AudioPolicyManager::removeDevicesRoleForCapturePreset(
4076 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector& devices)
4077{
4078 ALOGV("%s() audioSource=%d role=%d devices=%s", __func__, audioSource, role,
4079 dumpAudioDeviceTypeAddrVector(devices).c_str());
4080
Eric Laurent78fedbf2023-03-09 14:40:44 +01004081 if (!areAllDevicesSupported(
4082 devices, audio_call_is_input_device, __func__, /*matchAddress*/false)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00004083 return BAD_VALUE;
4084 }
4085
4086 status_t status = mEngine->removeDevicesRoleForCapturePreset(
4087 audioSource, role, devices);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004088 ALOGW_IF(status != NO_ERROR && status != NAME_NOT_FOUND,
Jiabin Huang3b98d322020-09-03 17:54:16 +00004089 "Engine could not remove devices role (%d) for capture preset %d", role, audioSource);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004090 if (status == NO_ERROR) {
4091 updateInputRouting();
4092 }
Jiabin Huang3b98d322020-09-03 17:54:16 +00004093 return status;
4094}
4095
4096status_t AudioPolicyManager::clearDevicesRoleForCapturePreset(audio_source_t audioSource,
4097 device_role_t role) {
4098 ALOGV("%s() audioSource=%d role=%d", __func__, audioSource, role);
4099
4100 status_t status = mEngine->clearDevicesRoleForCapturePreset(audioSource, role);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004101 ALOGW_IF(status != NO_ERROR && status != NAME_NOT_FOUND,
Jiabin Huang3b98d322020-09-03 17:54:16 +00004102 "Engine could not clear devices role (%d) for capture preset %d", role, audioSource);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004103 if (status == NO_ERROR) {
4104 updateInputRouting();
4105 }
Jiabin Huang3b98d322020-09-03 17:54:16 +00004106 return status;
4107}
4108
4109status_t AudioPolicyManager::getDevicesForRoleAndCapturePreset(
4110 audio_source_t audioSource, device_role_t role, AudioDeviceTypeAddrVector &devices) {
4111 return mEngine->getDevicesForRoleAndCapturePreset(audioSource, role, devices);
4112}
4113
Oscar Azucena90e77632019-11-27 17:12:28 -08004114status_t AudioPolicyManager::setUserIdDeviceAffinities(int userId,
jiabin6a02d532020-08-07 11:56:38 -07004115 const AudioDeviceTypeAddrVector& devices) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01004116 ALOGV("%s() userId=%d num devices %zu", __func__, userId, devices.size());
Eric Laurentc529cf62020-04-17 18:19:10 -07004117 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
4118 return BAD_VALUE;
Oscar Azucena90e77632019-11-27 17:12:28 -08004119 }
Oscar Azucena90e77632019-11-27 17:12:28 -08004120 status_t status = mPolicyMixes.setUserIdDeviceAffinities(userId, devices);
4121 if (status != NO_ERROR) {
4122 ALOGE("%s() could not set device affinity for userId %d",
4123 __FUNCTION__, userId);
4124 return status;
4125 }
4126
4127 // reevaluate outputs for all devices
4128 checkForDeviceAndOutputChanges();
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004129 changeOutputDevicesMuteState(devices);
4130 updateCallAndOutputRouting(false /* forceVolumeReeval */, 0 /* delayMs */,
4131 true /* skipDelays */);
4132 changeOutputDevicesMuteState(devices);
Oscar Azucena90e77632019-11-27 17:12:28 -08004133
4134 return NO_ERROR;
4135}
4136
4137status_t AudioPolicyManager::removeUserIdDeviceAffinities(int userId) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01004138 ALOGV("%s() userId=%d", __FUNCTION__, userId);
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004139 AudioDeviceTypeAddrVector devices;
4140 mPolicyMixes.getDevicesForUserId(userId, devices);
Oscar Azucena90e77632019-11-27 17:12:28 -08004141 status_t status = mPolicyMixes.removeUserIdDeviceAffinities(userId);
4142 if (status != NO_ERROR) {
4143 ALOGE("%s() Could not remove all device affinities fo userId = %d",
4144 __FUNCTION__, userId);
4145 return status;
4146 }
4147
4148 // reevaluate outputs for all devices
4149 checkForDeviceAndOutputChanges();
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004150 changeOutputDevicesMuteState(devices);
4151 updateCallAndOutputRouting(false /* forceVolumeReeval */, 0 /* delayMs */,
4152 true /* skipDelays */);
4153 changeOutputDevicesMuteState(devices);
Oscar Azucena90e77632019-11-27 17:12:28 -08004154
4155 return NO_ERROR;
4156}
4157
Andy Hungc29d82b2018-10-05 12:23:17 -07004158void AudioPolicyManager::dump(String8 *dst) const
Eric Laurente552edb2014-03-10 17:42:56 -07004159{
Andy Hungc29d82b2018-10-05 12:23:17 -07004160 dst->appendFormat("\nAudioPolicyManager Dump: %p\n", this);
Mikhail Naganov0dbe87b2021-12-01 02:03:31 +00004161 dst->appendFormat(" Primary Output I/O handle: %d\n",
Eric Laurent87ffa392015-05-22 10:32:38 -07004162 hasPrimaryOutput() ? mPrimaryOutput->mIoHandle : AUDIO_IO_HANDLE_NONE);
Mikhail Naganov0d6a0332016-04-19 17:12:38 -07004163 std::string stateLiteral;
4164 AudioModeConverter::toString(mEngine->getPhoneState(), stateLiteral);
Andy Hungc29d82b2018-10-05 12:23:17 -07004165 dst->appendFormat(" Phone state: %s\n", stateLiteral.c_str());
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07004166 const char* forceUses[AUDIO_POLICY_FORCE_USE_CNT] = {
4167 "communications", "media", "record", "dock", "system",
4168 "HDMI system audio", "encoded surround output", "vibrate ringing" };
4169 for (audio_policy_force_use_t i = AUDIO_POLICY_FORCE_FOR_COMMUNICATION;
4170 i < AUDIO_POLICY_FORCE_USE_CNT; i = (audio_policy_force_use_t)((int)i + 1)) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08004171 audio_policy_forced_cfg_t forceUseValue = mEngine->getForceUse(i);
4172 dst->appendFormat(" Force use for %s: %d", forceUses[i], forceUseValue);
4173 if (i == AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND &&
4174 forceUseValue == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
4175 dst->append(" (MANUAL: ");
4176 dumpManualSurroundFormats(dst);
4177 dst->append(")");
4178 }
4179 dst->append("\n");
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07004180 }
Andy Hungc29d82b2018-10-05 12:23:17 -07004181 dst->appendFormat(" TTS output %savailable\n", mTtsOutputAvailable ? "" : "not ");
4182 dst->appendFormat(" Master mono: %s\n", mMasterMono ? "on" : "off");
Mikhail Naganovb3bcb4f2022-02-23 23:46:56 +00004183 dst->appendFormat(" Communication Strategy id: %d\n", mCommunnicationStrategy);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07004184 dst->appendFormat(" Config source: %s\n", mConfig->getSource().c_str());
Eric Laurent2517af32020-11-25 15:31:27 +01004185
Mikhail Naganov0f413b22021-12-02 05:29:27 +00004186 dst->append("\n");
4187 mAvailableOutputDevices.dump(dst, String8("Available output"), 1);
4188 dst->append("\n");
4189 mAvailableInputDevices.dump(dst, String8("Available input"), 1);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07004190 mHwModules.dump(dst);
Andy Hungc29d82b2018-10-05 12:23:17 -07004191 mOutputs.dump(dst);
4192 mInputs.dump(dst);
Mikhail Naganov0f413b22021-12-02 05:29:27 +00004193 mEffects.dump(dst, 1);
Andy Hungc29d82b2018-10-05 12:23:17 -07004194 mAudioPatches.dump(dst);
4195 mPolicyMixes.dump(dst);
4196 mAudioSources.dump(dst);
François Gaffiec005e562018-11-06 15:04:49 +01004197
Kevin Rocardb99cc752019-03-21 20:52:24 -07004198 dst->appendFormat(" AllowedCapturePolicies:\n");
4199 for (auto& policy : mAllowedCapturePolicies) {
4200 dst->appendFormat(" - uid=%d flag_mask=%#x\n", policy.first, policy.second);
4201 }
4202
jiabina84c3d32022-12-02 18:59:55 +00004203 dst->appendFormat(" Preferred mixer audio configuration:\n");
4204 for (const auto it : mPreferredMixerAttrInfos) {
4205 dst->appendFormat(" - device port id: %d\n", it.first);
4206 for (const auto preferredMixerInfoIt : it.second) {
4207 dst->appendFormat(" - strategy: %d; ", preferredMixerInfoIt.first);
4208 preferredMixerInfoIt.second->dump(dst);
4209 }
4210 }
4211
François Gaffiec005e562018-11-06 15:04:49 +01004212 dst->appendFormat("\nPolicy Engine dump:\n");
4213 mEngine->dump(dst);
Andy Hungc29d82b2018-10-05 12:23:17 -07004214}
4215
4216status_t AudioPolicyManager::dump(int fd)
4217{
4218 String8 result;
4219 dump(&result);
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00004220 write(fd, result.c_str(), result.size());
Eric Laurente552edb2014-03-10 17:42:56 -07004221 return NO_ERROR;
4222}
4223
Kevin Rocardb99cc752019-03-21 20:52:24 -07004224status_t AudioPolicyManager::setAllowedCapturePolicy(uid_t uid, audio_flags_mask_t capturePolicy)
4225{
4226 mAllowedCapturePolicies[uid] = capturePolicy;
4227 return NO_ERROR;
4228}
4229
Eric Laurente552edb2014-03-10 17:42:56 -07004230// This function checks for the parameters which can be offloaded.
4231// This can be enhanced depending on the capability of the DSP and policy
4232// of the system.
Eric Laurent90fe31c2020-11-26 20:06:35 +01004233audio_offload_mode_t AudioPolicyManager::getOffloadSupport(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07004234{
Eric Laurent90fe31c2020-11-26 20:06:35 +01004235 ALOGV("%s: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07004236 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurent90fe31c2020-11-26 20:06:35 +01004237 __func__, offloadInfo.sample_rate, offloadInfo.channel_mask,
Eric Laurente552edb2014-03-10 17:42:56 -07004238 offloadInfo.format,
4239 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
4240 offloadInfo.has_video);
4241
jiabin2b9d5a12021-12-10 01:06:29 +00004242 if (!isOffloadPossible(offloadInfo)) {
Eric Laurent90fe31c2020-11-26 20:06:35 +01004243 return AUDIO_OFFLOAD_NOT_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07004244 }
4245
4246 // See if there is a profile to support this.
4247 // AUDIO_DEVICE_NONE
François Gaffie11d30102018-11-02 16:09:09 +01004248 sp<IOProfile> profile = getProfileForOutput(DeviceVector() /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07004249 offloadInfo.sample_rate,
4250 offloadInfo.format,
4251 offloadInfo.channel_mask,
Michael Chana94fbb22018-04-24 14:31:19 +10004252 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD,
4253 true /* directOnly */);
Eric Laurent94365442021-01-08 18:36:05 +01004254 ALOGV("%s: profile %sfound%s", __func__, profile != nullptr ? "" : "NOT ",
4255 (profile != nullptr && (profile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD) != 0)
4256 ? ", supports gapless" : "");
Eric Laurent90fe31c2020-11-26 20:06:35 +01004257 if (profile == nullptr) {
4258 return AUDIO_OFFLOAD_NOT_SUPPORTED;
4259 }
4260 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD) != 0) {
4261 return AUDIO_OFFLOAD_GAPLESS_SUPPORTED;
4262 }
4263 return AUDIO_OFFLOAD_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07004264}
4265
Michael Chana94fbb22018-04-24 14:31:19 +10004266bool AudioPolicyManager::isDirectOutputSupported(const audio_config_base_t& config,
4267 const audio_attributes_t& attributes) {
4268 audio_output_flags_t output_flags = AUDIO_OUTPUT_FLAG_NONE;
François Gaffie58d4be52018-11-06 15:30:12 +01004269 audio_flags_to_audio_output_flags(attributes.flags, &output_flags);
Dorin Drimus9901eb02022-01-14 11:36:51 +00004270 DeviceVector outputDevices = mEngine->getOutputDevicesForAttributes(attributes);
4271 sp<IOProfile> profile = getProfileForOutput(outputDevices,
Michael Chana94fbb22018-04-24 14:31:19 +10004272 config.sample_rate,
4273 config.format,
4274 config.channel_mask,
4275 output_flags,
4276 true /* directOnly */);
4277 ALOGV("%s() profile %sfound with name: %s, "
4278 "sample rate: %u, format: 0x%x, channel_mask: 0x%x, output flags: 0x%x",
4279 __FUNCTION__, profile != 0 ? "" : "NOT ",
jiabin5740f082019-08-19 15:08:30 -07004280 (profile != 0 ? profile->getTagName().c_str() : "null"),
Michael Chana94fbb22018-04-24 14:31:19 +10004281 config.sample_rate, config.format, config.channel_mask, output_flags);
Dorin Drimusecc9f422022-03-09 17:57:40 +01004282
4283 // also try the MSD module if compatible profile not found
4284 if (profile == nullptr) {
4285 profile = getMsdProfileForOutput(outputDevices,
4286 config.sample_rate,
4287 config.format,
4288 config.channel_mask,
4289 output_flags,
4290 true /* directOnly */);
4291 ALOGV("%s() MSD profile %sfound with name: %s, "
4292 "sample rate: %u, format: 0x%x, channel_mask: 0x%x, output flags: 0x%x",
4293 __FUNCTION__, profile != 0 ? "" : "NOT ",
4294 (profile != 0 ? profile->getTagName().c_str() : "null"),
4295 config.sample_rate, config.format, config.channel_mask, output_flags);
4296 }
4297 return (profile != nullptr);
Michael Chana94fbb22018-04-24 14:31:19 +10004298}
4299
jiabin2b9d5a12021-12-10 01:06:29 +00004300bool AudioPolicyManager::isOffloadPossible(const audio_offload_info_t &offloadInfo,
4301 bool durationIgnored) {
4302 if (mMasterMono) {
4303 return false; // no offloading if mono is set.
4304 }
4305
4306 // Check if offload has been disabled
4307 if (property_get_bool("audio.offload.disable", false /* default_value */)) {
4308 ALOGV("%s: offload disabled by audio.offload.disable", __func__);
4309 return false;
4310 }
4311
4312 // Check if stream type is music, then only allow offload as of now.
4313 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
4314 {
4315 ALOGV("%s: stream_type != MUSIC, returning false", __func__);
4316 return false;
4317 }
4318
4319 //TODO: enable audio offloading with video when ready
4320 const bool allowOffloadWithVideo =
4321 property_get_bool("audio.offload.video", false /* default_value */);
4322 if (offloadInfo.has_video && !allowOffloadWithVideo) {
4323 ALOGV("%s: has_video == true, returning false", __func__);
4324 return false;
4325 }
4326
4327 //If duration is less than minimum value defined in property, return false
4328 const int min_duration_secs = property_get_int32(
4329 "audio.offload.min.duration.secs", -1 /* default_value */);
4330 if (!durationIgnored) {
4331 if (min_duration_secs >= 0) {
4332 if (offloadInfo.duration_us < min_duration_secs * 1000000LL) {
4333 ALOGV("%s: Offload denied by duration < audio.offload.min.duration.secs(=%d)",
4334 __func__, min_duration_secs);
4335 return false;
4336 }
4337 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
4338 ALOGV("%s: Offload denied by duration < default min(=%u)",
4339 __func__, OFFLOAD_DEFAULT_MIN_DURATION_SECS);
4340 return false;
4341 }
4342 }
4343
4344 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
4345 // creating an offloaded track and tearing it down immediately after start when audioflinger
4346 // detects there is an active non offloadable effect.
4347 // FIXME: We should check the audio session here but we do not have it in this context.
4348 // This may prevent offloading in rare situations where effects are left active by apps
4349 // in the background.
4350 if (mEffects.isNonOffloadableEffectEnabled()) {
4351 return false;
4352 }
4353
4354 return true;
4355}
4356
4357audio_direct_mode_t AudioPolicyManager::getDirectPlaybackSupport(const audio_attributes_t *attr,
4358 const audio_config_t *config) {
4359 audio_offload_info_t offloadInfo = AUDIO_INFO_INITIALIZER;
4360 offloadInfo.format = config->format;
4361 offloadInfo.sample_rate = config->sample_rate;
4362 offloadInfo.channel_mask = config->channel_mask;
4363 offloadInfo.stream_type = mEngine->getStreamTypeForAttributes(*attr);
4364 offloadInfo.has_video = false;
4365 offloadInfo.is_streaming = false;
4366 const bool offloadPossible = isOffloadPossible(offloadInfo, true /*durationIgnored*/);
4367
4368 audio_direct_mode_t directMode = AUDIO_DIRECT_NOT_SUPPORTED;
4369 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
4370 audio_flags_to_audio_output_flags(attr->flags, &flags);
4371 // only retain flags that will drive compressed offload or passthrough
4372 uint32_t relevantFlags = AUDIO_OUTPUT_FLAG_HW_AV_SYNC;
4373 if (offloadPossible) {
4374 relevantFlags |= AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD;
4375 }
4376 flags = (audio_output_flags_t)((flags & relevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
4377
Dorin Drimusfae3c642022-03-17 18:36:30 +01004378 DeviceVector engineOutputDevices = mEngine->getOutputDevicesForAttributes(*attr);
jiabin2b9d5a12021-12-10 01:06:29 +00004379 for (const auto& hwModule : mHwModules) {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004380 DeviceVector outputDevices = engineOutputDevices;
4381 // the MSD module checks for different conditions and output devices
4382 if (strcmp(hwModule->getName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0) {
4383 if (!msdHasPatchesToAllDevices(engineOutputDevices.toTypeAddrVector())) {
4384 continue;
4385 }
4386 outputDevices = getMsdAudioOutDevices();
4387 }
jiabin2b9d5a12021-12-10 01:06:29 +00004388 for (const auto& curProfile : hwModule->getOutputProfiles()) {
jiabinc8f7dfc2022-01-06 18:42:08 +00004389 if (!curProfile->isCompatibleProfile(outputDevices,
jiabin2b9d5a12021-12-10 01:06:29 +00004390 config->sample_rate, nullptr /*updatedSamplingRate*/,
4391 config->format, nullptr /*updatedFormat*/,
4392 config->channel_mask, nullptr /*updatedChannelMask*/,
4393 flags)) {
4394 continue;
4395 }
4396 // reject profiles not corresponding to a device currently available
4397 if (!mAvailableOutputDevices.containsAtLeastOne(curProfile->getSupportedDevices())) {
4398 continue;
4399 }
4400 if ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)
4401 != AUDIO_OUTPUT_FLAG_NONE) {
jiabinc6132d62022-01-01 07:36:31 +00004402 if ((directMode & AUDIO_DIRECT_OFFLOAD_GAPLESS_SUPPORTED)
jiabin2b9d5a12021-12-10 01:06:29 +00004403 != AUDIO_DIRECT_NOT_SUPPORTED) {
4404 // Already reports offload gapless supported. No need to report offload support.
4405 continue;
4406 }
4407 if ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD)
4408 != AUDIO_OUTPUT_FLAG_NONE) {
4409 // If offload gapless is reported, no need to report offload support.
4410 directMode = (audio_direct_mode_t) ((directMode &
4411 ~AUDIO_DIRECT_OFFLOAD_SUPPORTED) |
4412 AUDIO_DIRECT_OFFLOAD_GAPLESS_SUPPORTED);
4413 } else {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004414 directMode = (audio_direct_mode_t)(directMode | AUDIO_DIRECT_OFFLOAD_SUPPORTED);
jiabin2b9d5a12021-12-10 01:06:29 +00004415 }
4416 } else {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004417 directMode = (audio_direct_mode_t) (directMode | AUDIO_DIRECT_BITSTREAM_SUPPORTED);
jiabin2b9d5a12021-12-10 01:06:29 +00004418 }
4419 }
4420 }
4421 return directMode;
4422}
4423
Dorin Drimusf2196d82022-01-03 12:11:18 +01004424status_t AudioPolicyManager::getDirectProfilesForAttributes(const audio_attributes_t* attr,
4425 AudioProfileVector& audioProfilesVector) {
Dorin Drimus17112632022-09-23 15:28:51 +00004426 if (mEffects.isNonOffloadableEffectEnabled()) {
4427 return OK;
4428 }
jiabinf1c73972022-04-14 16:28:52 -07004429 DeviceVector devices;
4430 status_t status = getDevicesForAttributes(*attr, devices, false /* forVolume */);
Dorin Drimusf2196d82022-01-03 12:11:18 +01004431 if (status != OK) {
4432 return status;
4433 }
4434 ALOGV("%s: found %zu output devices for attributes.", __func__, devices.size());
4435 if (devices.empty()) {
4436 return OK; // no output devices for the attributes
4437 }
jiabinf1c73972022-04-14 16:28:52 -07004438 return getProfilesForDevices(devices, audioProfilesVector,
4439 AUDIO_OUTPUT_FLAG_DIRECT /*flags*/, false /*isInput*/);
Dorin Drimusf2196d82022-01-03 12:11:18 +01004440}
4441
jiabina84c3d32022-12-02 18:59:55 +00004442status_t AudioPolicyManager::getSupportedMixerAttributes(
4443 audio_port_handle_t portId, std::vector<audio_mixer_attributes_t> &mixerAttrs) {
4444 ALOGV("%s, portId=%d", __func__, portId);
4445 sp<DeviceDescriptor> deviceDescriptor = mAvailableOutputDevices.getDeviceFromId(portId);
4446 if (deviceDescriptor == nullptr) {
4447 ALOGE("%s the requested device is currently unavailable", __func__);
4448 return BAD_VALUE;
4449 }
jiabin96daffc2023-05-11 17:51:55 +00004450 if (!audio_is_usb_out_device(deviceDescriptor->type())) {
4451 ALOGE("%s the requested device(type=%#x) is not usb device", __func__,
4452 deviceDescriptor->type());
4453 return BAD_VALUE;
4454 }
jiabina84c3d32022-12-02 18:59:55 +00004455 for (const auto& hwModule : mHwModules) {
4456 for (const auto& curProfile : hwModule->getOutputProfiles()) {
4457 if (curProfile->supportsDevice(deviceDescriptor)) {
4458 curProfile->toSupportedMixerAttributes(&mixerAttrs);
4459 }
4460 }
4461 }
4462 return NO_ERROR;
4463}
4464
4465status_t AudioPolicyManager::setPreferredMixerAttributes(
4466 const audio_attributes_t *attr,
4467 audio_port_handle_t portId,
4468 uid_t uid,
4469 const audio_mixer_attributes_t *mixerAttributes) {
4470 ALOGV("%s, attr=%s, mixerAttributes={format=%#x, channelMask=%#x, samplingRate=%u, "
4471 "mixerBehavior=%d}, uid=%d, portId=%u",
4472 __func__, toString(*attr).c_str(), mixerAttributes->config.format,
4473 mixerAttributes->config.channel_mask, mixerAttributes->config.sample_rate,
4474 mixerAttributes->mixer_behavior, uid, portId);
4475 if (attr->usage != AUDIO_USAGE_MEDIA) {
4476 ALOGE("%s failed, only media is allowed, the given usage is %d", __func__, attr->usage);
4477 return BAD_VALUE;
4478 }
4479 sp<DeviceDescriptor> deviceDescriptor = mAvailableOutputDevices.getDeviceFromId(portId);
4480 if (deviceDescriptor == nullptr) {
4481 ALOGE("%s the requested device is currently unavailable", __func__);
4482 return BAD_VALUE;
4483 }
4484 if (!audio_is_usb_out_device(deviceDescriptor->type())) {
4485 ALOGE("%s(%d), type=%d, is not a usb output device",
4486 __func__, portId, deviceDescriptor->type());
4487 return BAD_VALUE;
4488 }
4489
4490 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
4491 audio_flags_to_audio_output_flags(attr->flags, &flags);
4492 flags = (audio_output_flags_t) (flags |
4493 audio_output_flags_from_mixer_behavior(mixerAttributes->mixer_behavior));
4494 sp<IOProfile> profile = nullptr;
4495 DeviceVector devices(deviceDescriptor);
4496 for (const auto& hwModule : mHwModules) {
4497 for (const auto& curProfile : hwModule->getOutputProfiles()) {
4498 if (curProfile->hasDynamicAudioProfile()
4499 && curProfile->isCompatibleProfile(devices,
4500 mixerAttributes->config.sample_rate,
4501 nullptr /*updatedSamplingRate*/,
4502 mixerAttributes->config.format,
4503 nullptr /*updatedFormat*/,
4504 mixerAttributes->config.channel_mask,
4505 nullptr /*updatedChannelMask*/,
4506 flags,
4507 false /*exactMatchRequiredForInputFlags*/)) {
4508 profile = curProfile;
4509 break;
4510 }
4511 }
4512 }
4513 if (profile == nullptr) {
4514 ALOGE("%s, there is no compatible profile found", __func__);
4515 return BAD_VALUE;
4516 }
4517
4518 sp<PreferredMixerAttributesInfo> mixerAttrInfo =
4519 sp<PreferredMixerAttributesInfo>::make(
4520 uid, portId, profile, flags, *mixerAttributes);
4521 const product_strategy_t strategy = mEngine->getProductStrategyForAttributes(*attr);
4522 mPreferredMixerAttrInfos[portId][strategy] = mixerAttrInfo;
4523
4524 // If 1) there is any client from the preferred mixer configuration owner that is currently
4525 // active and matches the strategy and 2) current output is on the preferred device and the
4526 // mixer configuration doesn't match the preferred one, reopen output with preferred mixer
4527 // configuration.
4528 std::vector<audio_io_handle_t> outputsToReopen;
4529 for (size_t i = 0; i < mOutputs.size(); i++) {
4530 const auto output = mOutputs.valueAt(i);
jiabin3ff8d7d2022-12-13 06:27:44 +00004531 if (output->mProfile == profile && output->devices().onlyContainsDevice(deviceDescriptor)) {
4532 if (output->isConfigurationMatched(mixerAttributes->config, flags)) {
4533 output->mUsePreferredMixerAttributes = true;
4534 } else {
4535 for (const auto &client: output->getActiveClients()) {
4536 if (client->uid() == uid && client->strategy() == strategy) {
4537 client->setIsInvalid();
4538 outputsToReopen.push_back(output->mIoHandle);
4539 }
jiabina84c3d32022-12-02 18:59:55 +00004540 }
4541 }
4542 }
4543 }
4544 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
4545 config.sample_rate = mixerAttributes->config.sample_rate;
4546 config.channel_mask = mixerAttributes->config.channel_mask;
4547 config.format = mixerAttributes->config.format;
4548 for (const auto output : outputsToReopen) {
jiabin3ff8d7d2022-12-13 06:27:44 +00004549 sp<SwAudioOutputDescriptor> desc =
4550 reopenOutput(mOutputs.valueFor(output), &config, flags, __func__);
4551 if (desc == nullptr) {
4552 ALOGE("%s, failed to reopen output with preferred mixer attributes", __func__);
4553 continue;
4554 }
4555 desc->mUsePreferredMixerAttributes = true;
jiabina84c3d32022-12-02 18:59:55 +00004556 }
4557
4558 return NO_ERROR;
4559}
4560
4561sp<PreferredMixerAttributesInfo> AudioPolicyManager::getPreferredMixerAttributesInfo(
jiabind9a58d32023-06-01 17:57:30 +00004562 audio_port_handle_t devicePortId,
4563 product_strategy_t strategy,
4564 bool activeBitPerfectPreferred) {
jiabina84c3d32022-12-02 18:59:55 +00004565 auto it = mPreferredMixerAttrInfos.find(devicePortId);
4566 if (it == mPreferredMixerAttrInfos.end()) {
4567 return nullptr;
4568 }
jiabind9a58d32023-06-01 17:57:30 +00004569 if (activeBitPerfectPreferred) {
4570 for (auto [strategy, info] : it->second) {
4571 if ((info->getFlags() & AUDIO_OUTPUT_FLAG_BIT_PERFECT) != AUDIO_OUTPUT_FLAG_NONE
4572 && info->getActiveClientCount() != 0) {
4573 return info;
4574 }
4575 }
jiabina84c3d32022-12-02 18:59:55 +00004576 }
jiabind9a58d32023-06-01 17:57:30 +00004577 auto strategyMatchedMixerAttrInfoIt = it->second.find(strategy);
4578 return strategyMatchedMixerAttrInfoIt == it->second.end()
4579 ? nullptr : strategyMatchedMixerAttrInfoIt->second;
jiabina84c3d32022-12-02 18:59:55 +00004580}
4581
4582status_t AudioPolicyManager::getPreferredMixerAttributes(
4583 const audio_attributes_t *attr,
4584 audio_port_handle_t portId,
4585 audio_mixer_attributes_t* mixerAttributes) {
4586 sp<PreferredMixerAttributesInfo> info = getPreferredMixerAttributesInfo(
4587 portId, mEngine->getProductStrategyForAttributes(*attr));
4588 if (info == nullptr) {
4589 return NAME_NOT_FOUND;
4590 }
4591 *mixerAttributes = info->getMixerAttributes();
4592 return NO_ERROR;
4593}
4594
4595status_t AudioPolicyManager::clearPreferredMixerAttributes(const audio_attributes_t *attr,
4596 audio_port_handle_t portId,
4597 uid_t uid) {
4598 const product_strategy_t strategy = mEngine->getProductStrategyForAttributes(*attr);
4599 const auto preferredMixerAttrInfo = getPreferredMixerAttributesInfo(portId, strategy);
4600 if (preferredMixerAttrInfo == nullptr) {
4601 return NAME_NOT_FOUND;
4602 }
4603 if (preferredMixerAttrInfo->getUid() != uid) {
4604 ALOGE("%s, requested uid=%d, owned uid=%d",
4605 __func__, uid, preferredMixerAttrInfo->getUid());
4606 return PERMISSION_DENIED;
4607 }
4608 mPreferredMixerAttrInfos[portId].erase(strategy);
4609 if (mPreferredMixerAttrInfos[portId].empty()) {
4610 mPreferredMixerAttrInfos.erase(portId);
4611 }
4612
4613 // Reconfig existing output
4614 std::vector<audio_io_handle_t> potentialOutputsToReopen;
4615 for (size_t i = 0; i < mOutputs.size(); i++) {
4616 if (mOutputs.valueAt(i)->mProfile == preferredMixerAttrInfo->getProfile()) {
4617 potentialOutputsToReopen.push_back(mOutputs.keyAt(i));
4618 }
4619 }
4620 for (const auto output : potentialOutputsToReopen) {
4621 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
4622 if (desc->isConfigurationMatched(preferredMixerAttrInfo->getConfigBase(),
4623 preferredMixerAttrInfo->getFlags())) {
4624 reopenOutput(desc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
4625 }
4626 }
4627 return NO_ERROR;
4628}
4629
Eric Laurent6a94d692014-05-20 11:18:06 -07004630status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
4631 audio_port_type_t type,
4632 unsigned int *num_ports,
jiabin19cdba52020-11-24 11:28:58 -08004633 struct audio_port_v7 *ports,
Eric Laurent6a94d692014-05-20 11:18:06 -07004634 unsigned int *generation)
4635{
jiabin19cdba52020-11-24 11:28:58 -08004636 if (num_ports == nullptr || (*num_ports != 0 && ports == nullptr) ||
4637 generation == nullptr) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004638 return BAD_VALUE;
4639 }
4640 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
jiabin19cdba52020-11-24 11:28:58 -08004641 if (ports == nullptr) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004642 *num_ports = 0;
4643 }
4644
4645 size_t portsWritten = 0;
4646 size_t portsMax = *num_ports;
4647 *num_ports = 0;
4648 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07004649 // do not report devices with type AUDIO_DEVICE_IN_STUB or AUDIO_DEVICE_OUT_STUB
4650 // as they are used by stub HALs by convention
Eric Laurent6a94d692014-05-20 11:18:06 -07004651 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004652 for (const auto& dev : mAvailableOutputDevices) {
4653 if (dev->type() == AUDIO_DEVICE_OUT_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07004654 continue;
4655 }
4656 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004657 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07004658 }
4659 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07004660 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004661 }
4662 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004663 for (const auto& dev : mAvailableInputDevices) {
4664 if (dev->type() == AUDIO_DEVICE_IN_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07004665 continue;
4666 }
4667 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004668 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07004669 }
4670 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07004671 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004672 }
4673 }
4674 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
4675 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
4676 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
4677 mInputs[i]->toAudioPort(&ports[portsWritten++]);
4678 }
4679 *num_ports += mInputs.size();
4680 }
4681 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent84c70242014-06-23 08:46:27 -07004682 size_t numOutputs = 0;
4683 for (size_t i = 0; i < mOutputs.size(); i++) {
4684 if (!mOutputs[i]->isDuplicated()) {
4685 numOutputs++;
4686 if (portsWritten < portsMax) {
4687 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
4688 }
4689 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004690 }
Eric Laurent84c70242014-06-23 08:46:27 -07004691 *num_ports += numOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07004692 }
4693 }
jiabina84c3d32022-12-02 18:59:55 +00004694
Eric Laurent6a94d692014-05-20 11:18:06 -07004695 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07004696 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
Eric Laurent6a94d692014-05-20 11:18:06 -07004697 return NO_ERROR;
4698}
4699
Mikhail Naganov5edc5ed2023-03-23 14:52:15 -07004700status_t AudioPolicyManager::listDeclaredDevicePorts(media::AudioPortRole role,
4701 std::vector<media::AudioPortFw>* _aidl_return) {
4702 auto pushPort = [&](const sp<DeviceDescriptor>& dev) -> status_t {
4703 audio_port_v7 port;
4704 dev->toAudioPort(&port);
4705 auto aidlPort = VALUE_OR_RETURN_STATUS(legacy2aidl_audio_port_v7_AudioPortFw(port));
4706 _aidl_return->push_back(std::move(aidlPort));
4707 return OK;
4708 };
4709
Mikhail Naganov68e3f642023-04-28 13:06:32 -07004710 for (const auto& module : mHwModules) {
Mikhail Naganov5edc5ed2023-03-23 14:52:15 -07004711 for (const auto& dev : module->getDeclaredDevices()) {
4712 if (role == media::AudioPortRole::NONE ||
4713 ((role == media::AudioPortRole::SOURCE)
4714 == audio_is_input_device(dev->type()))) {
4715 RETURN_STATUS_IF_ERROR(pushPort(dev));
4716 }
4717 }
4718 }
4719 return OK;
4720}
4721
jiabin19cdba52020-11-24 11:28:58 -08004722status_t AudioPolicyManager::getAudioPort(struct audio_port_v7 *port)
Eric Laurent6a94d692014-05-20 11:18:06 -07004723{
Eric Laurent99fcae42018-05-17 16:59:18 -07004724 if (port == nullptr || port->id == AUDIO_PORT_HANDLE_NONE) {
4725 return BAD_VALUE;
4726 }
4727 sp<DeviceDescriptor> dev = mAvailableOutputDevices.getDeviceFromId(port->id);
4728 if (dev != 0) {
4729 dev->toAudioPort(port);
4730 return NO_ERROR;
4731 }
4732 dev = mAvailableInputDevices.getDeviceFromId(port->id);
4733 if (dev != 0) {
4734 dev->toAudioPort(port);
4735 return NO_ERROR;
4736 }
4737 sp<SwAudioOutputDescriptor> out = mOutputs.getOutputFromId(port->id);
4738 if (out != 0) {
4739 out->toAudioPort(port);
4740 return NO_ERROR;
4741 }
4742 sp<AudioInputDescriptor> in = mInputs.getInputFromId(port->id);
4743 if (in != 0) {
4744 in->toAudioPort(port);
4745 return NO_ERROR;
4746 }
4747 return BAD_VALUE;
Eric Laurent6a94d692014-05-20 11:18:06 -07004748}
4749
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004750status_t AudioPolicyManager::createAudioPatch(const struct audio_patch *patch,
4751 audio_patch_handle_t *handle,
4752 uid_t uid)
Eric Laurent6a94d692014-05-20 11:18:06 -07004753{
François Gaffieafd4cea2019-11-18 15:50:22 +01004754 ALOGV("%s", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004755 if (handle == NULL || patch == NULL) {
4756 return BAD_VALUE;
4757 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004758 ALOGV("%s num sources %d num sinks %d", __func__, patch->num_sources, patch->num_sinks);
Mikhail Naganovac9858b2018-06-15 13:12:37 -07004759 if (!audio_patch_is_valid(patch)) {
Eric Laurent874c42872014-08-08 15:13:39 -07004760 return BAD_VALUE;
4761 }
4762 // only one source per audio patch supported for now
4763 if (patch->num_sources > 1) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004764 return INVALID_OPERATION;
4765 }
Eric Laurent874c42872014-08-08 15:13:39 -07004766 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004767 return INVALID_OPERATION;
4768 }
Eric Laurent874c42872014-08-08 15:13:39 -07004769 for (size_t i = 0; i < patch->num_sinks; i++) {
4770 if (patch->sinks[i].role != AUDIO_PORT_ROLE_SINK) {
4771 return INVALID_OPERATION;
4772 }
4773 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004774
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004775 sp<DeviceDescriptor> srcDevice = mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
4776 sp<DeviceDescriptor> sinkDevice = mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id);
4777 if (srcDevice == nullptr || sinkDevice == nullptr) {
4778 ALOGW("%s could not create patch, invalid sink and/or source device(s)", __func__);
4779 return BAD_VALUE;
4780 }
4781 ALOGV("%s between source %s and sink %s", __func__,
4782 srcDevice->toString().c_str(), sinkDevice->toString().c_str());
4783 audio_port_handle_t portId = PolicyAudioPort::getNextUniqueId();
4784 // Default attributes, default volume priority, not to infer with non raw audio patches.
4785 audio_attributes_t attributes = attributes_initializer(AUDIO_USAGE_MEDIA);
4786 const struct audio_port_config *source = &patch->sources[0];
4787 sp<SourceClientDescriptor> sourceDesc =
4788 new InternalSourceClientDescriptor(
4789 portId, uid, attributes, *source, srcDevice, sinkDevice,
4790 mEngine->getProductStrategyForAttributes(attributes), toVolumeSource(attributes));
4791
4792 status_t status =
4793 connectAudioSourceToSink(sourceDesc, sinkDevice, patch, *handle, uid, 0 /* delayMs */);
4794
4795 if (status != NO_ERROR) {
4796 return INVALID_OPERATION;
4797 }
4798 mAudioSources.add(portId, sourceDesc);
4799 return NO_ERROR;
4800}
4801
4802status_t AudioPolicyManager::connectAudioSourceToSink(
4803 const sp<SourceClientDescriptor>& sourceDesc, const sp<DeviceDescriptor> &sinkDevice,
4804 const struct audio_patch *patch,
4805 audio_patch_handle_t &handle,
4806 uid_t uid, uint32_t delayMs)
4807{
4808 status_t status = createAudioPatchInternal(patch, &handle, uid, delayMs, sourceDesc);
4809 if (status != NO_ERROR || mAudioPatches.indexOfKey(handle) < 0) {
4810 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
4811 return INVALID_OPERATION;
4812 }
4813 sourceDesc->connect(handle, sinkDevice);
4814 if (isMsdPatch(handle)) {
4815 return NO_ERROR;
4816 }
4817 // SW Bridge? (@todo: HW bridge, keep track of HwOutput for device selection "reconsideration")
4818 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
4819 ALOG_ASSERT(swOutput != nullptr, "%s: a swOutput shall always be associated", __func__);
4820 if (swOutput->getClient(sourceDesc->portId()) != nullptr) {
4821 ALOGW("%s source portId has already been attached to outputDesc", __func__);
4822 goto FailurePatchAdded;
4823 }
4824 status = swOutput->start();
4825 if (status != NO_ERROR) {
4826 goto FailureSourceAdded;
4827 }
4828 swOutput->addClient(sourceDesc);
4829 status = startSource(swOutput, sourceDesc, &delayMs);
4830 if (status != NO_ERROR) {
4831 ALOGW("%s failed to start source, error %d", __FUNCTION__, status);
4832 goto FailureSourceActive;
4833 }
4834 if (delayMs != 0) {
4835 usleep(delayMs * 1000);
4836 }
4837 return NO_ERROR;
4838
4839FailureSourceActive:
4840 swOutput->stop();
4841 releaseOutput(sourceDesc->portId());
4842FailureSourceAdded:
4843 sourceDesc->setSwOutput(nullptr);
4844FailurePatchAdded:
4845 releaseAudioPatchInternal(handle);
4846 return INVALID_OPERATION;
4847}
4848
4849status_t AudioPolicyManager::createAudioPatchInternal(const struct audio_patch *patch,
4850 audio_patch_handle_t *handle,
4851 uid_t uid, uint32_t delayMs,
4852 const sp<SourceClientDescriptor>& sourceDesc)
4853{
4854 ALOGV("%s num sources %d num sinks %d", __func__, patch->num_sources, patch->num_sinks);
Eric Laurent6a94d692014-05-20 11:18:06 -07004855 sp<AudioPatch> patchDesc;
4856 ssize_t index = mAudioPatches.indexOfKey(*handle);
4857
François Gaffieafd4cea2019-11-18 15:50:22 +01004858 ALOGV("%s source id %d role %d type %d", __func__, patch->sources[0].id,
4859 patch->sources[0].role,
4860 patch->sources[0].type);
Eric Laurent874c42872014-08-08 15:13:39 -07004861#if LOG_NDEBUG == 0
4862 for (size_t i = 0; i < patch->num_sinks; i++) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004863 ALOGV("%s sink %zu: id %d role %d type %d", __func__ ,i, patch->sinks[i].id,
4864 patch->sinks[i].role,
4865 patch->sinks[i].type);
Eric Laurent874c42872014-08-08 15:13:39 -07004866 }
4867#endif
Eric Laurent6a94d692014-05-20 11:18:06 -07004868
4869 if (index >= 0) {
4870 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01004871 ALOGV("%s mUidCached %d patchDesc->mUid %d uid %d",
4872 __func__, mUidCached, patchDesc->getUid(), uid);
4873 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004874 return INVALID_OPERATION;
4875 }
4876 } else {
Glenn Kastena13cde92016-03-28 15:26:02 -07004877 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07004878 }
4879
4880 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004881 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004882 if (outputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004883 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004884 return BAD_VALUE;
4885 }
Eric Laurent84c70242014-06-23 08:46:27 -07004886 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
4887 outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004888 if (patchDesc != 0) {
4889 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004890 ALOGV("%s source id differs for patch current id %d new id %d",
4891 __func__, patchDesc->mPatch.sources[0].id, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004892 return BAD_VALUE;
4893 }
4894 }
Eric Laurent874c42872014-08-08 15:13:39 -07004895 DeviceVector devices;
4896 for (size_t i = 0; i < patch->num_sinks; i++) {
4897 // Only support mix to devices connection
4898 // TODO add support for mix to mix connection
4899 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004900 ALOGV("%s source mix but sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07004901 return INVALID_OPERATION;
4902 }
4903 sp<DeviceDescriptor> devDesc =
4904 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
4905 if (devDesc == 0) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004906 ALOGV("%s out device not found for id %d", __func__, patch->sinks[i].id);
Eric Laurent874c42872014-08-08 15:13:39 -07004907 return BAD_VALUE;
4908 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004909
François Gaffie11d30102018-11-02 16:09:09 +01004910 if (!outputDesc->mProfile->isCompatibleProfile(DeviceVector(devDesc),
Eric Laurent874c42872014-08-08 15:13:39 -07004911 patch->sources[0].sample_rate,
François Gaffie53615e22015-03-19 09:24:12 +01004912 NULL, // updatedSamplingRate
4913 patch->sources[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07004914 NULL, // updatedFormat
François Gaffie53615e22015-03-19 09:24:12 +01004915 patch->sources[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07004916 NULL, // updatedChannelMask
François Gaffie53615e22015-03-19 09:24:12 +01004917 AUDIO_OUTPUT_FLAG_NONE /*FIXME*/)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004918 ALOGV("%s profile not supported for device %08x", __func__, devDesc->type());
Eric Laurent874c42872014-08-08 15:13:39 -07004919 return INVALID_OPERATION;
4920 }
4921 devices.add(devDesc);
4922 }
4923 if (devices.size() == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004924 return INVALID_OPERATION;
4925 }
Eric Laurent874c42872014-08-08 15:13:39 -07004926
Eric Laurent6a94d692014-05-20 11:18:06 -07004927 // TODO: reconfigure output format and channels here
François Gaffieafd4cea2019-11-18 15:50:22 +01004928 ALOGV("%s setting device %s on output %d",
4929 __func__, dumpDeviceTypes(devices.types()).c_str(), outputDesc->mIoHandle);
François Gaffie11d30102018-11-02 16:09:09 +01004930 setOutputDevices(outputDesc, devices, true, 0, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004931 index = mAudioPatches.indexOfKey(*handle);
4932 if (index >= 0) {
4933 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004934 ALOGW("%s setOutputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004935 }
4936 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01004937 patchDesc->setUid(uid);
4938 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004939 } else {
François Gaffieafd4cea2019-11-18 15:50:22 +01004940 ALOGW("%s setOutputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004941 return INVALID_OPERATION;
4942 }
4943 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
4944 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
4945 // input device to input mix connection
Eric Laurent874c42872014-08-08 15:13:39 -07004946 // only one sink supported when connecting an input device to a mix
4947 if (patch->num_sinks > 1) {
4948 return INVALID_OPERATION;
4949 }
François Gaffie53615e22015-03-19 09:24:12 +01004950 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004951 if (inputDesc == NULL) {
4952 return BAD_VALUE;
4953 }
4954 if (patchDesc != 0) {
4955 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
4956 return BAD_VALUE;
4957 }
4958 }
François Gaffie11d30102018-11-02 16:09:09 +01004959 sp<DeviceDescriptor> device =
Eric Laurent6a94d692014-05-20 11:18:06 -07004960 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01004961 if (device == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004962 return BAD_VALUE;
4963 }
4964
François Gaffie11d30102018-11-02 16:09:09 +01004965 if (!inputDesc->mProfile->isCompatibleProfile(DeviceVector(device),
Eric Laurent275e8e92014-11-30 15:14:47 -08004966 patch->sinks[0].sample_rate,
4967 NULL, /*updatedSampleRate*/
4968 patch->sinks[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07004969 NULL, /*updatedFormat*/
Eric Laurent275e8e92014-11-30 15:14:47 -08004970 patch->sinks[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07004971 NULL, /*updatedChannelMask*/
Eric Laurent275e8e92014-11-30 15:14:47 -08004972 // FIXME for the parameter type,
4973 // and the NONE
4974 (audio_output_flags_t)
Glenn Kasten6a8ab052014-07-24 14:08:35 -07004975 AUDIO_INPUT_FLAG_NONE)) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004976 return INVALID_OPERATION;
4977 }
4978 // TODO: reconfigure output format and channels here
François Gaffieafd4cea2019-11-18 15:50:22 +01004979 ALOGV("%s setting device %s on output %d", __func__,
François Gaffie11d30102018-11-02 16:09:09 +01004980 device->toString().c_str(), inputDesc->mIoHandle);
4981 setInputDevice(inputDesc->mIoHandle, device, true, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004982 index = mAudioPatches.indexOfKey(*handle);
4983 if (index >= 0) {
4984 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004985 ALOGW("%s setInputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004986 }
4987 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01004988 patchDesc->setUid(uid);
4989 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004990 } else {
François Gaffieafd4cea2019-11-18 15:50:22 +01004991 ALOGW("%s setInputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004992 return INVALID_OPERATION;
4993 }
4994 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
4995 // device to device connection
4996 if (patchDesc != 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07004997 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004998 return BAD_VALUE;
4999 }
5000 }
François Gaffie11d30102018-11-02 16:09:09 +01005001 sp<DeviceDescriptor> srcDevice =
Eric Laurent6a94d692014-05-20 11:18:06 -07005002 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01005003 if (srcDevice == 0) {
Eric Laurent58f8eb72014-09-12 16:19:41 -07005004 return BAD_VALUE;
5005 }
Eric Laurent874c42872014-08-08 15:13:39 -07005006
Eric Laurent6a94d692014-05-20 11:18:06 -07005007 //update source and sink with our own data as the data passed in the patch may
5008 // be incomplete.
François Gaffieafd4cea2019-11-18 15:50:22 +01005009 PatchBuilder patchBuilder;
5010 audio_port_config sourcePortConfig = {};
Dean Wheatley8bee85a2021-02-10 16:02:23 +11005011
5012 // if first sink is to MSD, establish single MSD patch
5013 if (getMsdAudioOutDevices().contains(
5014 mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id))) {
5015 ALOGV("%s patching to MSD", __FUNCTION__);
5016 patchBuilder = buildMsdPatch(false /*msdIsSource*/, srcDevice);
5017 goto installPatch;
5018 }
5019
François Gaffieafd4cea2019-11-18 15:50:22 +01005020 srcDevice->toAudioPortConfig(&sourcePortConfig, &patch->sources[0]);
5021 patchBuilder.addSource(sourcePortConfig);
Eric Laurent6a94d692014-05-20 11:18:06 -07005022
Eric Laurent874c42872014-08-08 15:13:39 -07005023 for (size_t i = 0; i < patch->num_sinks; i++) {
5024 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005025 ALOGV("%s source device but one sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07005026 return INVALID_OPERATION;
5027 }
François Gaffie11d30102018-11-02 16:09:09 +01005028 sp<DeviceDescriptor> sinkDevice =
Eric Laurent874c42872014-08-08 15:13:39 -07005029 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
François Gaffie11d30102018-11-02 16:09:09 +01005030 if (sinkDevice == 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07005031 return BAD_VALUE;
5032 }
François Gaffieafd4cea2019-11-18 15:50:22 +01005033 audio_port_config sinkPortConfig = {};
5034 sinkDevice->toAudioPortConfig(&sinkPortConfig, &patch->sinks[i]);
5035 patchBuilder.addSink(sinkPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07005036
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005037 // Whatever Sw or Hw bridge, we do attach an SwOutput to an Audio Source for
5038 // volume management purpose (tracking activity)
5039 // In case of Hw bridge, it is a Work Around. The mixPort used is the one declared
5040 // in config XML to reach the sink so that is can be declared as available.
5041 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurent78b07302022-10-07 16:20:34 +02005042 sp<SwAudioOutputDescriptor> outputDesc;
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005043 if (!sourceDesc->isInternal()) {
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005044 // take care of dynamic routing for SwOutput selection,
5045 audio_attributes_t attributes = sourceDesc->attributes();
5046 audio_stream_type_t stream = sourceDesc->stream();
5047 audio_attributes_t resultAttr;
5048 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
5049 config.sample_rate = sourceDesc->config().sample_rate;
François Gaffie2a24db42022-04-04 16:45:02 +02005050 audio_channel_mask_t sourceMask = sourceDesc->config().channel_mask;
5051 config.channel_mask =
5052 (audio_channel_mask_get_representation(sourceMask)
5053 == AUDIO_CHANNEL_REPRESENTATION_INDEX) ? sourceMask
5054 : audio_channel_mask_in_to_out(sourceMask);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005055 config.format = sourceDesc->config().format;
5056 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
5057 audio_port_handle_t selectedDeviceId = AUDIO_PORT_HANDLE_NONE;
5058 bool isRequestedDeviceForExclusiveUse = false;
5059 output_type_t outputType;
Eric Laurentb0a7bc92022-04-05 15:06:08 +02005060 bool isSpatialized;
jiabinc658e452022-10-21 20:52:21 +00005061 bool isBitPerfect;
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005062 getOutputForAttrInt(&resultAttr, &output, AUDIO_SESSION_NONE, &attributes,
5063 &stream, sourceDesc->uid(), &config, &flags,
5064 &selectedDeviceId, &isRequestedDeviceForExclusiveUse,
jiabinc658e452022-10-21 20:52:21 +00005065 nullptr, &outputType, &isSpatialized, &isBitPerfect);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005066 if (output == AUDIO_IO_HANDLE_NONE) {
5067 ALOGV("%s no output for device %s",
5068 __FUNCTION__, sinkDevice->toString().c_str());
5069 return INVALID_OPERATION;
5070 }
5071 outputDesc = mOutputs.valueFor(output);
5072 if (outputDesc->isDuplicated()) {
5073 ALOGE("%s output is duplicated", __func__);
5074 return INVALID_OPERATION;
5075 }
François Gaffie7e39df22022-04-26 12:48:49 +02005076 bool closeOutput = outputDesc->mDirectOpenCount != 0;
5077 sourceDesc->setSwOutput(outputDesc, closeOutput);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005078 } else {
5079 // Same for "raw patches" aka created from createAudioPatch API
5080 SortedVector<audio_io_handle_t> outputs =
5081 getOutputsForDevices(DeviceVector(sinkDevice), mOutputs);
5082 // if the sink device is reachable via an opened output stream, request to
5083 // go via this output stream by adding a second source to the patch
5084 // description
5085 output = selectOutput(outputs);
5086 if (output == AUDIO_IO_HANDLE_NONE) {
5087 ALOGE("%s no output available for internal patch sink", __func__);
5088 return INVALID_OPERATION;
5089 }
5090 outputDesc = mOutputs.valueFor(output);
5091 if (outputDesc->isDuplicated()) {
5092 ALOGV("%s output for device %s is duplicated",
5093 __func__, sinkDevice->toString().c_str());
5094 return INVALID_OPERATION;
5095 }
François Gaffie7e39df22022-04-26 12:48:49 +02005096 sourceDesc->setSwOutput(outputDesc, /* closeOutput= */ false);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005097 }
Eric Laurent3bcf8592015-04-03 12:13:24 -07005098 // create a software bridge in PatchPanel if:
Scott Randolphf3172402018-01-23 17:06:53 -08005099 // - source and sink devices are on different HW modules OR
Eric Laurent3bcf8592015-04-03 12:13:24 -07005100 // - audio HAL version is < 3.0
Francois Gaffie99896da2018-04-09 11:05:33 +02005101 // - audio HAL version is >= 3.0 but no route has been declared between devices
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005102 // - called from startAudioSource (aka sourceDesc is not internal) and source device
5103 // does not have a gain controller
François Gaffie11d30102018-11-02 16:09:09 +01005104 if (!srcDevice->hasSameHwModuleAs(sinkDevice) ||
5105 (srcDevice->getModuleVersionMajor() < 3) ||
François Gaffieafd4cea2019-11-18 15:50:22 +01005106 !srcDevice->getModule()->supportsPatch(srcDevice, sinkDevice) ||
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005107 (!sourceDesc->isInternal() &&
François Gaffieafd4cea2019-11-18 15:50:22 +01005108 srcDevice->getAudioPort()->getGains().size() == 0)) {
Eric Laurent3bcf8592015-04-03 12:13:24 -07005109 // support only one sink device for now to simplify output selection logic
Eric Laurent874c42872014-08-08 15:13:39 -07005110 if (patch->num_sinks > 1) {
Eric Laurent83b88082014-06-20 18:31:16 -07005111 return INVALID_OPERATION;
5112 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005113 sourceDesc->setUseSwBridge();
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005114 if (outputDesc != nullptr) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005115 audio_port_config srcMixPortConfig = {};
Ytai Ben-Tsvic9d2a912021-11-22 16:43:09 -08005116 outputDesc->toAudioPortConfig(&srcMixPortConfig, nullptr);
François Gaffieafd4cea2019-11-18 15:50:22 +01005117 // for volume control, we may need a valid stream
Eric Laurent78b07302022-10-07 16:20:34 +02005118 srcMixPortConfig.ext.mix.usecase.stream =
5119 (!sourceDesc->isInternal() || isCallTxAudioSource(sourceDesc)) ?
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005120 mEngine->getStreamTypeForAttributes(sourceDesc->attributes()) :
5121 AUDIO_STREAM_PATCH;
François Gaffieafd4cea2019-11-18 15:50:22 +01005122 patchBuilder.addSource(srcMixPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07005123 }
Eric Laurent83b88082014-06-20 18:31:16 -07005124 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005125 }
5126 // TODO: check from routing capabilities in config file and other conflicting patches
5127
Dean Wheatley8bee85a2021-02-10 16:02:23 +11005128installPatch:
François Gaffieafd4cea2019-11-18 15:50:22 +01005129 status_t status = installPatch(
5130 __func__, index, handle, patchBuilder.patch(), delayMs, uid, &patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07005131 if (status != NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005132 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
Eric Laurent6a94d692014-05-20 11:18:06 -07005133 return INVALID_OPERATION;
5134 }
5135 } else {
5136 return BAD_VALUE;
5137 }
5138 } else {
5139 return BAD_VALUE;
5140 }
5141 return NO_ERROR;
5142}
5143
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005144status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle, uid_t uid)
Eric Laurent6a94d692014-05-20 11:18:06 -07005145{
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005146 ALOGV("%s patch %d", __func__, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005147 ssize_t index = mAudioPatches.indexOfKey(handle);
5148
5149 if (index < 0) {
5150 return BAD_VALUE;
5151 }
5152 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005153 ALOGV("%s() mUidCached %d patchDesc->mUid %d uid %d",
5154 __func__, mUidCached, patchDesc->getUid(), uid);
5155 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005156 return INVALID_OPERATION;
5157 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005158 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
5159 for (size_t i = 0; i < mAudioSources.size(); i++) {
5160 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
5161 if (sourceDesc != nullptr && sourceDesc->getPatchHandle() == handle) {
5162 portId = sourceDesc->portId();
5163 break;
5164 }
5165 }
5166 return portId != AUDIO_PORT_HANDLE_NONE ?
5167 stopAudioSource(portId) : releaseAudioPatchInternal(handle);
François Gaffieafd4cea2019-11-18 15:50:22 +01005168}
Eric Laurent6a94d692014-05-20 11:18:06 -07005169
François Gaffieafd4cea2019-11-18 15:50:22 +01005170status_t AudioPolicyManager::releaseAudioPatchInternal(audio_patch_handle_t handle,
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005171 uint32_t delayMs,
5172 const sp<SourceClientDescriptor>& sourceDesc)
François Gaffieafd4cea2019-11-18 15:50:22 +01005173{
5174 ALOGV("%s patch %d", __func__, handle);
5175 if (mAudioPatches.indexOfKey(handle) < 0) {
5176 ALOGE("%s: no patch found with handle=%d", __func__, handle);
5177 return BAD_VALUE;
5178 }
5179 sp<AudioPatch> patchDesc = mAudioPatches.valueFor(handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005180 struct audio_patch *patch = &patchDesc->mPatch;
François Gaffieafd4cea2019-11-18 15:50:22 +01005181 patchDesc->setUid(mUidCached);
Eric Laurent6a94d692014-05-20 11:18:06 -07005182 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005183 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005184 if (outputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005185 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005186 return BAD_VALUE;
5187 }
5188
François Gaffie11d30102018-11-02 16:09:09 +01005189 setOutputDevices(outputDesc,
5190 getNewOutputDevices(outputDesc, true /*fromCache*/),
5191 true,
5192 0,
5193 NULL);
Eric Laurent6a94d692014-05-20 11:18:06 -07005194 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
5195 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
François Gaffie53615e22015-03-19 09:24:12 +01005196 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005197 if (inputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005198 ALOGV("%s input not found for id %d", __func__, patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005199 return BAD_VALUE;
5200 }
5201 setInputDevice(inputDesc->mIoHandle,
Eric Laurentfb66dd92016-01-28 18:32:03 -08005202 getNewInputDevice(inputDesc),
Eric Laurent6a94d692014-05-20 11:18:06 -07005203 true,
5204 NULL);
5205 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005206 status_t status =
5207 mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
5208 ALOGV("%s patch panel returned %d patchHandle %d",
5209 __func__, status, patchDesc->getAfHandle());
5210 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005211 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005212 mpClientInterface->onAudioPatchListUpdate();
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005213 // SW or HW Bridge
5214 sp<SwAudioOutputDescriptor> outputDesc = nullptr;
5215 audio_patch_handle_t patchHandle = AUDIO_PATCH_HANDLE_NONE;
Francois Gaffie7feb8542020-04-06 17:39:47 +02005216 if (patch->num_sources > 1 && patch->sources[1].type == AUDIO_PORT_TYPE_MIX) {
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005217 outputDesc = mOutputs.getOutputFromId(patch->sources[1].id);
5218 } else if (patch->num_sources == 1 && sourceDesc != nullptr) {
5219 outputDesc = sourceDesc->swOutput().promote();
5220 }
5221 if (outputDesc == nullptr) {
5222 ALOGW("%s no output for id %d", __func__, patch->sources[0].id);
5223 // releaseOutput has already called closeOutput in case of direct output
5224 return NO_ERROR;
5225 }
François Gaffie7e39df22022-04-26 12:48:49 +02005226 patchHandle = outputDesc->getPatchHandle();
5227 // When a Sw bridge is released, the mixer used by this bridge will release its
5228 // patch at AudioFlinger side. Hence, the mixer audio patch must be recreated
5229 // Reuse patch handle to force audio flinger removing initial mixer patch removal
5230 // updating hal patch handle (prevent leaks).
5231 // While using a HwBridge, force reconsidering device only if not reusing an existing
5232 // output and no more activity on output (will force to close).
5233 bool force = sourceDesc->useSwBridge() ||
5234 (sourceDesc->canCloseOutput() && !outputDesc->isActive());
5235 // APM pattern is to have always outputs opened / patch realized for reachable devices.
5236 // Update device may result to NONE (empty), coupled with force, it releases the patch.
5237 // Reconsider device only for cases:
5238 // 1 / Active Output
5239 // 2 / Inactive Output previously hosting HwBridge
5240 // 3 / Inactive Output previously hosting SwBridge that can be closed.
5241 bool updateDevice = outputDesc->isActive() || !sourceDesc->useSwBridge() ||
5242 sourceDesc->canCloseOutput();
5243 setOutputDevices(outputDesc,
5244 updateDevice ? getNewOutputDevices(outputDesc, true /*fromCache*/) :
5245 outputDesc->devices(),
5246 force,
5247 0,
5248 patchHandle == AUDIO_PATCH_HANDLE_NONE ? nullptr : &patchHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005249 } else {
5250 return BAD_VALUE;
5251 }
5252 } else {
5253 return BAD_VALUE;
5254 }
5255 return NO_ERROR;
5256}
5257
5258status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
5259 struct audio_patch *patches,
5260 unsigned int *generation)
5261{
François Gaffie53615e22015-03-19 09:24:12 +01005262 if (generation == NULL) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005263 return BAD_VALUE;
5264 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005265 *generation = curAudioPortGeneration();
François Gaffie53615e22015-03-19 09:24:12 +01005266 return mAudioPatches.listAudioPatches(num_patches, patches);
Eric Laurent6a94d692014-05-20 11:18:06 -07005267}
5268
Eric Laurente1715a42014-05-20 11:30:42 -07005269status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07005270{
Eric Laurente1715a42014-05-20 11:30:42 -07005271 ALOGV("setAudioPortConfig()");
5272
5273 if (config == NULL) {
5274 return BAD_VALUE;
5275 }
5276 ALOGV("setAudioPortConfig() on port handle %d", config->id);
5277 // Only support gain configuration for now
Eric Laurenta121f902014-06-03 13:32:54 -07005278 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
5279 return INVALID_OPERATION;
Eric Laurente1715a42014-05-20 11:30:42 -07005280 }
5281
Eric Laurenta121f902014-06-03 13:32:54 -07005282 sp<AudioPortConfig> audioPortConfig;
Eric Laurente1715a42014-05-20 11:30:42 -07005283 if (config->type == AUDIO_PORT_TYPE_MIX) {
5284 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005285 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07005286 if (outputDesc == NULL) {
5287 return BAD_VALUE;
5288 }
Eric Laurent84c70242014-06-23 08:46:27 -07005289 ALOG_ASSERT(!outputDesc->isDuplicated(),
5290 "setAudioPortConfig() called on duplicated output %d",
5291 outputDesc->mIoHandle);
Eric Laurenta121f902014-06-03 13:32:54 -07005292 audioPortConfig = outputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07005293 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
François Gaffie53615e22015-03-19 09:24:12 +01005294 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07005295 if (inputDesc == NULL) {
5296 return BAD_VALUE;
5297 }
Eric Laurenta121f902014-06-03 13:32:54 -07005298 audioPortConfig = inputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07005299 } else {
5300 return BAD_VALUE;
5301 }
5302 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
5303 sp<DeviceDescriptor> deviceDesc;
5304 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
5305 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
5306 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
5307 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
5308 } else {
5309 return BAD_VALUE;
5310 }
5311 if (deviceDesc == NULL) {
5312 return BAD_VALUE;
5313 }
Eric Laurenta121f902014-06-03 13:32:54 -07005314 audioPortConfig = deviceDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07005315 } else {
5316 return BAD_VALUE;
5317 }
5318
Mikhail Naganov7be71d22018-05-23 16:51:46 -07005319 struct audio_port_config backupConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07005320 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
5321 if (status == NO_ERROR) {
Mikhail Naganov7be71d22018-05-23 16:51:46 -07005322 struct audio_port_config newConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07005323 audioPortConfig->toAudioPortConfig(&newConfig, config);
5324 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
Eric Laurente1715a42014-05-20 11:30:42 -07005325 }
Eric Laurenta121f902014-06-03 13:32:54 -07005326 if (status != NO_ERROR) {
5327 audioPortConfig->applyAudioPortConfig(&backupConfig);
Eric Laurente1715a42014-05-20 11:30:42 -07005328 }
Eric Laurente1715a42014-05-20 11:30:42 -07005329
5330 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07005331}
5332
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005333void AudioPolicyManager::releaseResourcesForUid(uid_t uid)
5334{
Eric Laurentd60560a2015-04-10 11:31:20 -07005335 clearAudioSources(uid);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005336 clearAudioPatches(uid);
5337 clearSessionRoutes(uid);
5338}
5339
Eric Laurent6a94d692014-05-20 11:18:06 -07005340void AudioPolicyManager::clearAudioPatches(uid_t uid)
5341{
Eric Laurent0add0fd2014-12-04 18:58:14 -08005342 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005343 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
François Gaffieafd4cea2019-11-18 15:50:22 +01005344 if (patchDesc->getUid() == uid) {
Eric Laurent0add0fd2014-12-04 18:58:14 -08005345 releaseAudioPatch(mAudioPatches.keyAt(i), uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07005346 }
5347 }
5348}
5349
François Gaffiec005e562018-11-06 15:04:49 +01005350void AudioPolicyManager::checkStrategyRoute(product_strategy_t ps, audio_io_handle_t ouptutToSkip)
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005351{
François Gaffiec005e562018-11-06 15:04:49 +01005352 // Take the first attributes following the product strategy as it is used to retrieve the routed
5353 // device. All attributes wihin a strategy follows the same "routing strategy"
5354 auto attributes = mEngine->getAllAttributesForProductStrategy(ps).front();
5355 DeviceVector devices = mEngine->getOutputDevicesForAttributes(attributes, nullptr, false);
François Gaffie11d30102018-11-02 16:09:09 +01005356 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
jiabin3ff8d7d2022-12-13 06:27:44 +00005357 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005358 for (size_t j = 0; j < mOutputs.size(); j++) {
5359 if (mOutputs.keyAt(j) == ouptutToSkip) {
5360 continue;
5361 }
5362 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(j);
François Gaffiec005e562018-11-06 15:04:49 +01005363 if (!outputDesc->isStrategyActive(ps)) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005364 continue;
5365 }
5366 // If the default device for this strategy is on another output mix,
5367 // invalidate all tracks in this strategy to force re connection.
5368 // Otherwise select new device on the output mix.
5369 if (outputs.indexOf(mOutputs.keyAt(j)) < 0) {
jiabinc44b3462022-12-08 12:52:31 -08005370 invalidateStreams(mEngine->getStreamTypesForProductStrategy(ps));
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005371 } else {
jiabin3ff8d7d2022-12-13 06:27:44 +00005372 DeviceVector newDevices = getNewOutputDevices(outputDesc, false /*fromCache*/);
5373 if (outputDesc->mUsePreferredMixerAttributes && outputDesc->devices() != newDevices) {
5374 // If the device is using preferred mixer attributes, the output need to reopen
5375 // with default configuration when the new selected devices are different from
5376 // current routing devices.
5377 outputsToReopen.emplace(mOutputs.keyAt(j), newDevices);
5378 continue;
5379 }
5380 setOutputDevices(outputDesc, newDevices, false);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005381 }
5382 }
jiabin3ff8d7d2022-12-13 06:27:44 +00005383 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005384}
5385
5386void AudioPolicyManager::clearSessionRoutes(uid_t uid)
5387{
5388 // remove output routes associated with this uid
François Gaffiec005e562018-11-06 15:04:49 +01005389 std::vector<product_strategy_t> affectedStrategies;
Eric Laurent97ac8712018-07-27 18:59:02 -07005390 for (size_t i = 0; i < mOutputs.size(); i++) {
5391 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07005392 for (const auto& client : outputDesc->getClientIterable()) {
5393 if (client->hasPreferredDevice() && client->uid() == uid) {
5394 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
François Gaffiec005e562018-11-06 15:04:49 +01005395 auto clientStrategy = client->strategy();
5396 if (std::find(begin(affectedStrategies), end(affectedStrategies), clientStrategy) !=
5397 end(affectedStrategies)) {
5398 continue;
5399 }
5400 affectedStrategies.push_back(client->strategy());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005401 }
5402 }
5403 }
5404 // reroute outputs if necessary
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005405 for (const auto& strategy : affectedStrategies) {
5406 checkStrategyRoute(strategy, AUDIO_IO_HANDLE_NONE);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005407 }
5408
5409 // remove input routes associated with this uid
5410 SortedVector<audio_source_t> affectedSources;
Eric Laurent97ac8712018-07-27 18:59:02 -07005411 for (size_t i = 0; i < mInputs.size(); i++) {
5412 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07005413 for (const auto& client : inputDesc->getClientIterable()) {
5414 if (client->hasPreferredDevice() && client->uid() == uid) {
5415 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
5416 affectedSources.add(client->source());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005417 }
5418 }
5419 }
5420 // reroute inputs if necessary
5421 SortedVector<audio_io_handle_t> inputsToClose;
5422 for (size_t i = 0; i < mInputs.size(); i++) {
5423 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Eric Laurent4eb58f12018-12-07 16:41:02 -08005424 if (affectedSources.indexOf(inputDesc->source()) >= 0) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005425 inputsToClose.add(inputDesc->mIoHandle);
5426 }
5427 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005428 for (const auto& input : inputsToClose) {
5429 closeInput(input);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005430 }
5431}
5432
Eric Laurentd60560a2015-04-10 11:31:20 -07005433void AudioPolicyManager::clearAudioSources(uid_t uid)
5434{
5435 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005436 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
5437 if (sourceDesc->uid() == uid) {
Eric Laurentd60560a2015-04-10 11:31:20 -07005438 stopAudioSource(mAudioSources.keyAt(i));
5439 }
5440 }
5441}
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005442
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005443status_t AudioPolicyManager::acquireSoundTriggerSession(audio_session_t *session,
5444 audio_io_handle_t *ioHandle,
5445 audio_devices_t *device)
5446{
Glenn Kastenf0c6d7d2016-02-26 10:44:04 -08005447 *session = (audio_session_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
5448 *ioHandle = (audio_io_handle_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
Francois Gaffie716e1432019-01-14 16:58:59 +01005449 audio_attributes_t attr = { .source = AUDIO_SOURCE_HOTWORD };
Eric Laurentcedd5b52023-03-22 00:03:31 +00005450 sp<DeviceDescriptor> deviceDesc = mEngine->getInputDeviceForAttributes(attr);
5451 if (deviceDesc == nullptr) {
5452 return INVALID_OPERATION;
5453 }
5454 *device = deviceDesc->type();
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005455
François Gaffiedf372692015-03-19 10:43:27 +01005456 return mSoundTriggerSessions.acquireSession(*session, *ioHandle);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005457}
5458
Eric Laurentd60560a2015-04-10 11:31:20 -07005459status_t AudioPolicyManager::startAudioSource(const struct audio_port_config *source,
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005460 const audio_attributes_t *attributes,
5461 audio_port_handle_t *portId,
5462 uid_t uid)
Eric Laurent554a2772015-04-10 11:29:24 -07005463{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005464 ALOGV("%s", __FUNCTION__);
5465 *portId = AUDIO_PORT_HANDLE_NONE;
5466
5467 if (source == NULL || attributes == NULL || portId == NULL) {
5468 ALOGW("%s invalid argument: source %p attributes %p handle %p",
5469 __FUNCTION__, source, attributes, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005470 return BAD_VALUE;
5471 }
5472
Eric Laurentd60560a2015-04-10 11:31:20 -07005473 if (source->role != AUDIO_PORT_ROLE_SOURCE ||
5474 source->type != AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005475 ALOGW("%s INVALID_OPERATION source->role %d source->type %d",
5476 __FUNCTION__, source->role, source->type);
Eric Laurentd60560a2015-04-10 11:31:20 -07005477 return INVALID_OPERATION;
5478 }
5479
François Gaffie11d30102018-11-02 16:09:09 +01005480 sp<DeviceDescriptor> srcDevice =
Eric Laurentd60560a2015-04-10 11:31:20 -07005481 mAvailableInputDevices.getDevice(source->ext.device.type,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005482 String8(source->ext.device.address),
5483 AUDIO_FORMAT_DEFAULT);
François Gaffie11d30102018-11-02 16:09:09 +01005484 if (srcDevice == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005485 ALOGW("%s source->ext.device.type %08x not found", __FUNCTION__, source->ext.device.type);
Eric Laurentd60560a2015-04-10 11:31:20 -07005486 return BAD_VALUE;
5487 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005488
jiabin4ef93452019-09-10 14:29:54 -07005489 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurentd60560a2015-04-10 11:31:20 -07005490
François Gaffieaaac0fd2018-11-22 17:56:39 +01005491 sp<SourceClientDescriptor> sourceDesc =
François Gaffieafd4cea2019-11-18 15:50:22 +01005492 new SourceClientDescriptor(*portId, uid, *attributes, *source, srcDevice,
François Gaffieaaac0fd2018-11-22 17:56:39 +01005493 mEngine->getStreamTypeForAttributes(*attributes),
5494 mEngine->getProductStrategyForAttributes(*attributes),
5495 toVolumeSource(*attributes));
Eric Laurentd60560a2015-04-10 11:31:20 -07005496
5497 status_t status = connectAudioSource(sourceDesc);
5498 if (status == NO_ERROR) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005499 mAudioSources.add(*portId, sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07005500 }
5501 return status;
5502}
5503
Francois Gaffie601801d2021-06-22 13:27:39 +02005504sp<SourceClientDescriptor> AudioPolicyManager::startAudioSourceInternal(
5505 const struct audio_port_config *source, const audio_attributes_t *attributes, uid_t uid)
5506{
5507 ALOGV("%s", __FUNCTION__);
5508 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
5509
5510 status_t status = startAudioSource(source, attributes, &portId, uid);
5511 ALOGE_IF(status != OK, "%s: failed to start audio source (%d)", __func__, status);
5512 return mAudioSources.valueFor(portId);
5513}
5514
5515
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005516status_t AudioPolicyManager::connectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07005517{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005518 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->portId());
Eric Laurentd60560a2015-04-10 11:31:20 -07005519
5520 // make sure we only have one patch per source.
5521 disconnectAudioSource(sourceDesc);
5522
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005523 audio_attributes_t attributes = sourceDesc->attributes();
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005524 // May the device (dynamic) have been disconnected/reconnected, id has changed.
5525 sp<DeviceDescriptor> srcDevice = mAvailableInputDevices.getDevice(
5526 sourceDesc->srcDevice()->type(),
5527 String8(sourceDesc->srcDevice()->address().c_str()),
5528 AUDIO_FORMAT_DEFAULT);
François Gaffiec005e562018-11-06 15:04:49 +01005529 DeviceVector sinkDevices =
Francois Gaffieff1eb522020-05-06 18:37:04 +02005530 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false /*fromCache*/);
François Gaffiec005e562018-11-06 15:04:49 +01005531 ALOG_ASSERT(!sinkDevices.isEmpty(), "connectAudioSource(): no device found for attributes");
François Gaffie11d30102018-11-02 16:09:09 +01005532 sp<DeviceDescriptor> sinkDevice = sinkDevices.itemAt(0);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005533 if (!mAvailableOutputDevices.contains(sinkDevice)) {
5534 ALOGE("%s Device %s not available", __func__, sinkDevice->toString().c_str());
5535 return INVALID_OPERATION;
5536 }
François Gaffieafd4cea2019-11-18 15:50:22 +01005537 PatchBuilder patchBuilder;
5538 patchBuilder.addSink(sinkDevice).addSource(srcDevice);
5539 audio_patch_handle_t handle = AUDIO_PATCH_HANDLE_NONE;
François Gaffieafd4cea2019-11-18 15:50:22 +01005540
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005541 return connectAudioSourceToSink(
5542 sourceDesc, sinkDevice, patchBuilder.patch(), handle, mUidCached, 0 /*delayMs*/);
Eric Laurent554a2772015-04-10 11:29:24 -07005543}
5544
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005545status_t AudioPolicyManager::stopAudioSource(audio_port_handle_t portId)
Eric Laurent554a2772015-04-10 11:29:24 -07005546{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005547 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueFor(portId);
5548 ALOGV("%s port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005549 if (sourceDesc == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005550 ALOGW("%s unknown source for port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005551 return BAD_VALUE;
5552 }
5553 status_t status = disconnectAudioSource(sourceDesc);
5554
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005555 mAudioSources.removeItem(portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005556 return status;
5557}
5558
Andy Hung2ddee192015-12-18 17:34:44 -08005559status_t AudioPolicyManager::setMasterMono(bool mono)
5560{
5561 if (mMasterMono == mono) {
5562 return NO_ERROR;
5563 }
5564 mMasterMono = mono;
5565 // if enabling mono we close all offloaded devices, which will invalidate the
5566 // corresponding AudioTrack. The AudioTrack client/MediaPlayer is responsible
5567 // for recreating the new AudioTrack as non-offloaded PCM.
5568 //
5569 // If disabling mono, we leave all tracks as is: we don't know which clients
5570 // and tracks are able to be recreated as offloaded. The next "song" should
5571 // play back offloaded.
5572 if (mMasterMono) {
5573 Vector<audio_io_handle_t> offloaded;
5574 for (size_t i = 0; i < mOutputs.size(); ++i) {
5575 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
5576 if (desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
5577 offloaded.push(desc->mIoHandle);
5578 }
5579 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005580 for (const auto& handle : offloaded) {
5581 closeOutput(handle);
Andy Hung2ddee192015-12-18 17:34:44 -08005582 }
5583 }
5584 // update master mono for all remaining outputs
5585 for (size_t i = 0; i < mOutputs.size(); ++i) {
5586 updateMono(mOutputs.keyAt(i));
5587 }
5588 return NO_ERROR;
5589}
5590
5591status_t AudioPolicyManager::getMasterMono(bool *mono)
5592{
5593 *mono = mMasterMono;
5594 return NO_ERROR;
5595}
5596
Eric Laurentac9cef52017-06-09 15:46:26 -07005597float AudioPolicyManager::getStreamVolumeDB(
5598 audio_stream_type_t stream, int index, audio_devices_t device)
5599{
jiabin9a3361e2019-10-01 09:38:30 -07005600 return computeVolume(getVolumeCurves(stream), toVolumeSource(stream), index, {device});
Eric Laurentac9cef52017-06-09 15:46:26 -07005601}
5602
jiabin81772902018-04-02 17:52:27 -07005603status_t AudioPolicyManager::getSurroundFormats(unsigned int *numSurroundFormats,
5604 audio_format_t *surroundFormats,
Kriti Dang6537def2021-03-02 13:46:59 +01005605 bool *surroundFormatsEnabled)
jiabin81772902018-04-02 17:52:27 -07005606{
Kriti Dang6537def2021-03-02 13:46:59 +01005607 if (numSurroundFormats == nullptr || (*numSurroundFormats != 0 &&
5608 (surroundFormats == nullptr || surroundFormatsEnabled == nullptr))) {
jiabin81772902018-04-02 17:52:27 -07005609 return BAD_VALUE;
5610 }
Kriti Dang6537def2021-03-02 13:46:59 +01005611 ALOGV("%s() numSurroundFormats %d surroundFormats %p surroundFormatsEnabled %p",
5612 __func__, *numSurroundFormats, surroundFormats, surroundFormatsEnabled);
jiabin81772902018-04-02 17:52:27 -07005613
5614 size_t formatsWritten = 0;
5615 size_t formatsMax = *numSurroundFormats;
Kriti Dangef6be8f2020-11-05 11:58:19 +01005616
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005617 *numSurroundFormats = mConfig->getSurroundFormats().size();
Mikhail Naganov100f0122018-11-29 11:22:16 -08005618 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
5619 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005620 for (const auto& format: mConfig->getSurroundFormats()) {
jiabin81772902018-04-02 17:52:27 -07005621 if (formatsWritten < formatsMax) {
Kriti Dang6537def2021-03-02 13:46:59 +01005622 surroundFormats[formatsWritten] = format.first;
Mikhail Naganov100f0122018-11-29 11:22:16 -08005623 bool formatEnabled = true;
5624 switch (forceUse) {
5625 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL:
Kriti Dang6537def2021-03-02 13:46:59 +01005626 formatEnabled = mManualSurroundFormats.count(format.first) != 0;
Mikhail Naganov100f0122018-11-29 11:22:16 -08005627 break;
5628 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER:
5629 formatEnabled = false;
5630 break;
5631 default: // AUTO or ALWAYS => true
5632 break;
jiabin81772902018-04-02 17:52:27 -07005633 }
5634 surroundFormatsEnabled[formatsWritten++] = formatEnabled;
5635 }
jiabin81772902018-04-02 17:52:27 -07005636 }
5637 return NO_ERROR;
5638}
5639
Kriti Dang6537def2021-03-02 13:46:59 +01005640status_t AudioPolicyManager::getReportedSurroundFormats(unsigned int *numSurroundFormats,
5641 audio_format_t *surroundFormats) {
5642 if (numSurroundFormats == nullptr || (*numSurroundFormats != 0 && surroundFormats == nullptr)) {
5643 return BAD_VALUE;
5644 }
5645 ALOGV("%s() numSurroundFormats %d surroundFormats %p",
5646 __func__, *numSurroundFormats, surroundFormats);
5647
5648 size_t formatsWritten = 0;
5649 size_t formatsMax = *numSurroundFormats;
5650 std::unordered_set<audio_format_t> formats; // Uses primary surround formats only
5651
5652 // Return formats from all device profiles that have already been resolved by
5653 // checkOutputsForDevice().
5654 for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
5655 sp<DeviceDescriptor> device = mAvailableOutputDevices[i];
5656 audio_devices_t deviceType = device->type();
5657 // Enabling/disabling formats are applied to only HDMI devices. So, this function
5658 // returns formats reported by HDMI devices.
5659 if (deviceType != AUDIO_DEVICE_OUT_HDMI) {
5660 continue;
5661 }
5662 // Formats reported by sink devices
5663 std::unordered_set<audio_format_t> formatset;
5664 if (auto it = mReportedFormatsMap.find(device); it != mReportedFormatsMap.end()) {
5665 formatset.insert(it->second.begin(), it->second.end());
5666 }
5667
5668 // Formats hard-coded in the in policy configuration file (if any).
5669 FormatVector encodedFormats = device->encodedFormats();
5670 formatset.insert(encodedFormats.begin(), encodedFormats.end());
5671 // Filter the formats which are supported by the vendor hardware.
5672 for (auto it = formatset.begin(); it != formatset.end(); ++it) {
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005673 if (mConfig->getSurroundFormats().count(*it) != 0) {
Kriti Dang6537def2021-03-02 13:46:59 +01005674 formats.insert(*it);
5675 } else {
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005676 for (const auto& pair : mConfig->getSurroundFormats()) {
Kriti Dang6537def2021-03-02 13:46:59 +01005677 if (pair.second.count(*it) != 0) {
5678 formats.insert(pair.first);
5679 break;
5680 }
5681 }
5682 }
5683 }
5684 }
5685 *numSurroundFormats = formats.size();
5686 for (const auto& format: formats) {
5687 if (formatsWritten < formatsMax) {
5688 surroundFormats[formatsWritten++] = format;
5689 }
5690 }
5691 return NO_ERROR;
5692}
5693
jiabin81772902018-04-02 17:52:27 -07005694status_t AudioPolicyManager::setSurroundFormatEnabled(audio_format_t audioFormat, bool enabled)
5695{
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005696 ALOGV("%s() format 0x%X enabled %d", __func__, audioFormat, enabled);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005697 const auto& formatIter = mConfig->getSurroundFormats().find(audioFormat);
5698 if (formatIter == mConfig->getSurroundFormats().end()) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005699 ALOGW("%s() format 0x%X is not a known surround format", __func__, audioFormat);
jiabin81772902018-04-02 17:52:27 -07005700 return BAD_VALUE;
5701 }
5702
Mikhail Naganov100f0122018-11-29 11:22:16 -08005703 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND) !=
5704 AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005705 ALOGW("%s() not in manual mode for surround sound format selection", __func__);
jiabin81772902018-04-02 17:52:27 -07005706 return INVALID_OPERATION;
5707 }
5708
Mikhail Naganov100f0122018-11-29 11:22:16 -08005709 if ((mManualSurroundFormats.count(audioFormat) != 0) == enabled) {
jiabin81772902018-04-02 17:52:27 -07005710 return NO_ERROR;
5711 }
5712
Mikhail Naganov100f0122018-11-29 11:22:16 -08005713 std::unordered_set<audio_format_t> surroundFormatsBackup(mManualSurroundFormats);
jiabin81772902018-04-02 17:52:27 -07005714 if (enabled) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005715 mManualSurroundFormats.insert(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07005716 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005717 mManualSurroundFormats.insert(subFormat);
jiabin81772902018-04-02 17:52:27 -07005718 }
5719 } else {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005720 mManualSurroundFormats.erase(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07005721 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005722 mManualSurroundFormats.erase(subFormat);
jiabin81772902018-04-02 17:52:27 -07005723 }
5724 }
5725
5726 sp<SwAudioOutputDescriptor> outputDesc;
5727 bool profileUpdated = false;
jiabin9a3361e2019-10-01 09:38:30 -07005728 DeviceVector hdmiOutputDevices = mAvailableOutputDevices.getDevicesFromType(
5729 AUDIO_DEVICE_OUT_HDMI);
jiabin81772902018-04-02 17:52:27 -07005730 for (size_t i = 0; i < hdmiOutputDevices.size(); i++) {
5731 // Simulate reconnection to update enabled surround sound formats.
jiabince9f20e2019-09-12 16:29:15 -07005732 String8 address = String8(hdmiOutputDevices[i]->address().c_str());
jiabin5740f082019-08-19 15:08:30 -07005733 std::string name = hdmiOutputDevices[i]->getName();
jiabin81772902018-04-02 17:52:27 -07005734 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
5735 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
5736 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005737 name.c_str(),
5738 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005739 if (status != NO_ERROR) {
5740 continue;
5741 }
5742 status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
5743 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
5744 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005745 name.c_str(),
5746 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005747 profileUpdated |= (status == NO_ERROR);
5748 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08005749 // FIXME: Why doing this for input HDMI devices if we don't augment their reported formats?
jiabin9a3361e2019-10-01 09:38:30 -07005750 DeviceVector hdmiInputDevices = mAvailableInputDevices.getDevicesFromType(
jiabin81772902018-04-02 17:52:27 -07005751 AUDIO_DEVICE_IN_HDMI);
5752 for (size_t i = 0; i < hdmiInputDevices.size(); i++) {
5753 // Simulate reconnection to update enabled surround sound formats.
jiabince9f20e2019-09-12 16:29:15 -07005754 String8 address = String8(hdmiInputDevices[i]->address().c_str());
jiabin5740f082019-08-19 15:08:30 -07005755 std::string name = hdmiInputDevices[i]->getName();
jiabin81772902018-04-02 17:52:27 -07005756 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
5757 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
5758 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005759 name.c_str(),
5760 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005761 if (status != NO_ERROR) {
5762 continue;
5763 }
5764 status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
5765 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
5766 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005767 name.c_str(),
5768 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005769 profileUpdated |= (status == NO_ERROR);
5770 }
5771
jiabin81772902018-04-02 17:52:27 -07005772 if (!profileUpdated) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005773 ALOGW("%s() no audio profiles updated, undoing surround formats change", __func__);
Mikhail Naganov100f0122018-11-29 11:22:16 -08005774 mManualSurroundFormats = std::move(surroundFormatsBackup);
jiabin81772902018-04-02 17:52:27 -07005775 }
5776
5777 return profileUpdated ? NO_ERROR : INVALID_OPERATION;
5778}
5779
Eric Laurent5ada82e2019-08-29 17:53:54 -07005780void AudioPolicyManager::setAppState(audio_port_handle_t portId, app_state_t state)
Svet Ganovf4ddfef2018-01-16 07:37:58 -08005781{
Eric Laurent5ada82e2019-08-29 17:53:54 -07005782 ALOGV("%s(portId:%d, state:%d)", __func__, portId, state);
Eric Laurenta9f86652018-11-28 17:23:11 -08005783 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent5ada82e2019-08-29 17:53:54 -07005784 mInputs.valueAt(i)->setAppState(portId, state);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08005785 }
5786}
5787
jiabin6012f912018-11-02 17:06:30 -07005788bool AudioPolicyManager::isHapticPlaybackSupported()
5789{
5790 for (const auto& hwModule : mHwModules) {
5791 const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
5792 for (const auto &outProfile : outputProfiles) {
5793 struct audio_port audioPort;
5794 outProfile->toAudioPort(&audioPort);
5795 for (size_t i = 0; i < audioPort.num_channel_masks; i++) {
5796 if (audioPort.channel_masks[i] & AUDIO_CHANNEL_HAPTIC_ALL) {
5797 return true;
5798 }
5799 }
5800 }
5801 }
5802 return false;
5803}
5804
Carter Hsu325a8eb2022-01-19 19:56:51 +08005805bool AudioPolicyManager::isUltrasoundSupported()
5806{
5807 bool hasUltrasoundOutput = false;
5808 bool hasUltrasoundInput = false;
5809 for (const auto& hwModule : mHwModules) {
5810 const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
5811 if (!hasUltrasoundOutput) {
5812 for (const auto &outProfile : outputProfiles) {
5813 if (outProfile->getFlags() & AUDIO_OUTPUT_FLAG_ULTRASOUND) {
5814 hasUltrasoundOutput = true;
5815 break;
5816 }
5817 }
5818 }
5819
5820 const InputProfileCollection &inputProfiles = hwModule->getInputProfiles();
5821 if (!hasUltrasoundInput) {
5822 for (const auto &inputProfile : inputProfiles) {
5823 if (inputProfile->getFlags() & AUDIO_INPUT_FLAG_ULTRASOUND) {
5824 hasUltrasoundInput = true;
5825 break;
5826 }
5827 }
5828 }
5829
5830 if (hasUltrasoundOutput && hasUltrasoundInput)
5831 return true;
5832 }
5833 return false;
5834}
5835
Atneya Nair698f5ef2022-12-15 16:15:09 -08005836bool AudioPolicyManager::isHotwordStreamSupported(bool lookbackAudio)
5837{
5838 const auto mask = AUDIO_INPUT_FLAG_HOTWORD_TAP |
5839 (lookbackAudio ? AUDIO_INPUT_FLAG_HW_LOOKBACK : 0);
5840 for (const auto& hwModule : mHwModules) {
5841 const InputProfileCollection &inputProfiles = hwModule->getInputProfiles();
5842 for (const auto &inputProfile : inputProfiles) {
5843 if ((inputProfile->getFlags() & mask) == mask) {
5844 return true;
5845 }
5846 }
5847 }
5848 return false;
5849}
5850
Eric Laurent8340e672019-11-06 11:01:08 -08005851bool AudioPolicyManager::isCallScreenModeSupported()
5852{
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005853 return mConfig->isCallScreenModeSupported();
Eric Laurent8340e672019-11-06 11:01:08 -08005854}
5855
5856
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005857status_t AudioPolicyManager::disconnectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07005858{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005859 ALOGV("%s port Id %d", __FUNCTION__, sourceDesc->portId());
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005860 if (!sourceDesc->isConnected()) {
5861 ALOGV("%s port Id %d already disconnected", __FUNCTION__, sourceDesc->portId());
5862 return NO_ERROR;
5863 }
François Gaffieafd4cea2019-11-18 15:50:22 +01005864 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
5865 if (swOutput != 0) {
5866 status_t status = stopSource(swOutput, sourceDesc);
Eric Laurent733ce942017-12-07 12:18:25 -08005867 if (status == NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005868 swOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08005869 }
jiabinbce0c1d2020-10-05 11:20:18 -07005870 if (releaseOutput(sourceDesc->portId())) {
5871 // The output descriptor is reopened to query dynamic profiles. In that case, there is
5872 // no need to release audio patch here but just return NO_ERROR.
5873 return NO_ERROR;
5874 }
Eric Laurentd60560a2015-04-10 11:31:20 -07005875 } else {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005876 sp<HwAudioOutputDescriptor> hwOutputDesc = sourceDesc->hwOutput().promote();
Eric Laurentd60560a2015-04-10 11:31:20 -07005877 if (hwOutputDesc != 0) {
Eric Laurentd60560a2015-04-10 11:31:20 -07005878 // close Hwoutput and remove from mHwOutputs
5879 } else {
5880 ALOGW("%s source has neither SW nor HW output", __FUNCTION__);
5881 }
5882 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005883 status_t status = releaseAudioPatchInternal(sourceDesc->getPatchHandle(), 0, sourceDesc);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005884 sourceDesc->disconnect();
5885 return status;
Eric Laurentd60560a2015-04-10 11:31:20 -07005886}
5887
François Gaffiec005e562018-11-06 15:04:49 +01005888sp<SourceClientDescriptor> AudioPolicyManager::getSourceForAttributesOnOutput(
5889 audio_io_handle_t output, const audio_attributes_t &attr)
Eric Laurentd60560a2015-04-10 11:31:20 -07005890{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005891 sp<SourceClientDescriptor> source;
Eric Laurentd60560a2015-04-10 11:31:20 -07005892 for (size_t i = 0; i < mAudioSources.size(); i++) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005893 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005894 sp<SwAudioOutputDescriptor> outputDesc = sourceDesc->swOutput().promote();
François Gaffiec005e562018-11-06 15:04:49 +01005895 if (followsSameRouting(attr, sourceDesc->attributes()) &&
5896 outputDesc != 0 && outputDesc->mIoHandle == output) {
Eric Laurentd60560a2015-04-10 11:31:20 -07005897 source = sourceDesc;
5898 break;
5899 }
5900 }
5901 return source;
Eric Laurent554a2772015-04-10 11:29:24 -07005902}
5903
Eric Laurentb4f42a92022-01-17 17:37:31 +01005904bool AudioPolicyManager::canBeSpatializedInt(const audio_attributes_t *attr,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005905 const audio_config_t *config,
Andy Hung9dd1a5b2022-05-10 15:39:39 -07005906 const AudioDeviceTypeAddrVector &devices) const
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005907{
5908 // The caller can have the audio attributes criteria ignored by either passing a null ptr or
5909 // the AUDIO_ATTRIBUTES_INITIALIZER value.
Eric Laurentfa0f6742021-08-17 18:39:44 +02005910 // If attributes are specified, current policy is to only allow spatialization for media
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005911 // and game usages.
Eric Laurent39095982021-08-24 18:29:27 +02005912 if (attr != nullptr && *attr != AUDIO_ATTRIBUTES_INITIALIZER) {
5913 if (attr->usage != AUDIO_USAGE_MEDIA && attr->usage != AUDIO_USAGE_GAME) {
5914 return false;
5915 }
5916 if ((attr->flags & (AUDIO_FLAG_CONTENT_SPATIALIZED | AUDIO_FLAG_NEVER_SPATIALIZE)) != 0) {
5917 return false;
5918 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005919 }
5920
Eric Laurentd332bc82023-08-04 11:45:23 +02005921 // The caller can have the audio config criteria ignored by either passing a null ptr or
5922 // the AUDIO_CONFIG_INITIALIZER value.
5923 // If an audio config is specified, current policy is to only allow spatialization for
5924 // some positional channel masks and PCM format
5925
5926 if (config != nullptr && *config != AUDIO_CONFIG_INITIALIZER) {
5927 if (!audio_is_channel_mask_spatialized(config->channel_mask)) {
5928 return false;
5929 }
5930 if (!audio_is_linear_pcm(config->format)) {
5931 return false;
5932 }
5933 }
5934
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005935 sp<IOProfile> profile =
Eric Laurent39095982021-08-24 18:29:27 +02005936 getSpatializerOutputProfile(config, devices);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005937 if (profile == nullptr) {
5938 return false;
5939 }
5940
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005941 return true;
5942}
5943
5944void AudioPolicyManager::checkVirtualizerClientRoutes() {
5945 std::set<audio_stream_type_t> streamsToInvalidate;
5946 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent39095982021-08-24 18:29:27 +02005947 const sp<SwAudioOutputDescriptor>& desc = mOutputs[i];
5948 for (const sp<TrackClientDescriptor>& client : desc->getClientIterable()) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005949 audio_attributes_t attr = client->attributes();
5950 DeviceVector devices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false);
5951 AudioDeviceTypeAddrVector devicesTypeAddress = devices.toTypeAddrVector();
5952 audio_config_base_t clientConfig = client->config();
5953 audio_config_t config = audio_config_initializer(&clientConfig);
Eric Laurent39095982021-08-24 18:29:27 +02005954 if (desc != mSpatializerOutput
Andy Hung9dd1a5b2022-05-10 15:39:39 -07005955 && canBeSpatializedInt(&attr, &config, devicesTypeAddress)) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005956 streamsToInvalidate.insert(client->stream());
5957 }
5958 }
5959 }
5960
jiabinc44b3462022-12-08 12:52:31 -08005961 invalidateStreams(StreamTypeVector(streamsToInvalidate.begin(), streamsToInvalidate.end()));
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005962}
5963
Eric Laurente191d1b2022-04-15 11:59:25 +02005964
5965bool AudioPolicyManager::isOutputOnlyAvailableRouteToSomeDevice(
5966 const sp<SwAudioOutputDescriptor>& outputDesc) {
5967 if (outputDesc->isDuplicated()) {
5968 return false;
5969 }
5970 DeviceVector devices = outputDesc->supportedDevices();
5971 for (size_t i = 0; i < mOutputs.size(); i++) {
5972 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
5973 if (desc == outputDesc || desc->isDuplicated()) {
5974 continue;
5975 }
5976 DeviceVector sharedDevices = desc->filterSupportedDevices(devices);
5977 if (!sharedDevices.isEmpty()
5978 && (desc->devicesSupportEncodedFormats(sharedDevices.types())
5979 == outputDesc->devicesSupportEncodedFormats(sharedDevices.types()))) {
5980 return false;
5981 }
5982 }
5983 return true;
5984}
5985
5986
Eric Laurentfa0f6742021-08-17 18:39:44 +02005987status_t AudioPolicyManager::getSpatializerOutput(const audio_config_base_t *mixerConfig,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005988 const audio_attributes_t *attr,
5989 audio_io_handle_t *output) {
5990 *output = AUDIO_IO_HANDLE_NONE;
5991
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005992 DeviceVector devices = mEngine->getOutputDevicesForAttributes(*attr, nullptr, false);
5993 AudioDeviceTypeAddrVector devicesTypeAddress = devices.toTypeAddrVector();
5994 audio_config_t *configPtr = nullptr;
5995 audio_config_t config;
5996 if (mixerConfig != nullptr) {
5997 config = audio_config_initializer(mixerConfig);
5998 configPtr = &config;
5999 }
Andy Hung9dd1a5b2022-05-10 15:39:39 -07006000 if (!canBeSpatializedInt(attr, configPtr, devicesTypeAddress)) {
Eric Laurente191d1b2022-04-15 11:59:25 +02006001 ALOGV("%s provided attributes or mixer config cannot be spatialized", __func__);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006002 return BAD_VALUE;
6003 }
6004
6005 sp<IOProfile> profile =
Eric Laurent39095982021-08-24 18:29:27 +02006006 getSpatializerOutputProfile(configPtr, devicesTypeAddress);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006007 if (profile == nullptr) {
Eric Laurente191d1b2022-04-15 11:59:25 +02006008 ALOGV("%s no suitable output profile for provided attributes or mixer config", __func__);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006009 return BAD_VALUE;
6010 }
6011
Eric Laurente191d1b2022-04-15 11:59:25 +02006012 std::vector<sp<SwAudioOutputDescriptor>> spatializerOutputs;
Eric Laurent39095982021-08-24 18:29:27 +02006013 for (size_t i = 0; i < mOutputs.size(); i++) {
6014 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente191d1b2022-04-15 11:59:25 +02006015 if (!desc->isDuplicated()
6016 && (desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0) {
6017 spatializerOutputs.push_back(desc);
6018 ALOGV("%s adding opened spatializer Output %d", __func__, desc->mIoHandle);
Eric Laurent39095982021-08-24 18:29:27 +02006019 }
6020 }
Eric Laurente191d1b2022-04-15 11:59:25 +02006021 mSpatializerOutput.clear();
6022 bool outputsChanged = false;
6023 for (const auto& desc : spatializerOutputs) {
6024 if (desc->mProfile == profile
6025 && (configPtr == nullptr
6026 || configPtr->channel_mask == desc->mMixerChannelMask)) {
6027 mSpatializerOutput = desc;
6028 ALOGV("%s reusing current spatializer output %d", __func__, desc->mIoHandle);
6029 } else {
6030 ALOGV("%s closing spatializerOutput output %d to match channel mask %#x"
6031 " and devices %s", __func__, desc->mIoHandle,
6032 configPtr != nullptr ? configPtr->channel_mask : 0,
6033 devices.toString().c_str());
6034 closeOutput(desc->mIoHandle);
6035 outputsChanged = true;
6036 }
Eric Laurent39095982021-08-24 18:29:27 +02006037 }
6038
Eric Laurente191d1b2022-04-15 11:59:25 +02006039 if (mSpatializerOutput == nullptr) {
Eric Laurentb4f42a92022-01-17 17:37:31 +01006040 sp<SwAudioOutputDescriptor> desc =
6041 openOutputWithProfileAndDevice(profile, devices, mixerConfig);
Eric Laurente191d1b2022-04-15 11:59:25 +02006042 if (desc != nullptr) {
6043 mSpatializerOutput = desc;
6044 outputsChanged = true;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006045 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006046 }
6047
6048 checkVirtualizerClientRoutes();
6049
Eric Laurente191d1b2022-04-15 11:59:25 +02006050 if (outputsChanged) {
6051 mPreviousOutputs = mOutputs;
6052 mpClientInterface->onAudioPortListUpdate();
6053 }
6054
6055 if (mSpatializerOutput == nullptr) {
6056 ALOGV("%s could not open spatializer output with requested config", __func__);
6057 return BAD_VALUE;
6058 }
Eric Laurent39095982021-08-24 18:29:27 +02006059 *output = mSpatializerOutput->mIoHandle;
Eric Laurente191d1b2022-04-15 11:59:25 +02006060 ALOGV("%s returning new spatializer output %d", __func__, *output);
6061 return OK;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006062}
6063
Eric Laurentfa0f6742021-08-17 18:39:44 +02006064status_t AudioPolicyManager::releaseSpatializerOutput(audio_io_handle_t output) {
6065 if (mSpatializerOutput == nullptr) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006066 return INVALID_OPERATION;
6067 }
Eric Laurentfa0f6742021-08-17 18:39:44 +02006068 if (mSpatializerOutput->mIoHandle != output) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006069 return BAD_VALUE;
6070 }
Eric Laurent39095982021-08-24 18:29:27 +02006071
Eric Laurente191d1b2022-04-15 11:59:25 +02006072 if (!isOutputOnlyAvailableRouteToSomeDevice(mSpatializerOutput)) {
6073 ALOGV("%s closing spatializer output %d", __func__, mSpatializerOutput->mIoHandle);
6074 closeOutput(mSpatializerOutput->mIoHandle);
6075 //from now on mSpatializerOutput is null
6076 checkVirtualizerClientRoutes();
6077 }
Eric Laurent39095982021-08-24 18:29:27 +02006078
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006079 return NO_ERROR;
6080}
6081
Eric Laurente552edb2014-03-10 17:42:56 -07006082// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07006083// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07006084// ----------------------------------------------------------------------------
Eric Laurent6a94d692014-05-20 11:18:06 -07006085uint32_t AudioPolicyManager::nextAudioPortGeneration()
6086{
Mikhail Naganov2773dd72017-12-08 10:12:11 -08006087 return mAudioPortGeneration++;
Eric Laurent6a94d692014-05-20 11:18:06 -07006088}
6089
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006090AudioPolicyManager::AudioPolicyManager(const sp<const AudioPolicyConfig>& config,
Mikhail Naganovf1b6d972023-05-02 13:56:01 -07006091 EngineInstance&& engine,
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006092 AudioPolicyClientInterface *clientInterface)
Eric Laurente552edb2014-03-10 17:42:56 -07006093 :
Andy Hung4ef19fa2018-05-15 19:35:29 -07006094 mUidCached(AID_AUDIOSERVER), // no need to call getuid(), there's only one of us running.
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006095 mConfig(config),
Mikhail Naganovf1b6d972023-05-02 13:56:01 -07006096 mEngine(std::move(engine)),
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006097 mpClientInterface(clientInterface),
Eric Laurente552edb2014-03-10 17:42:56 -07006098 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
Eric Laurent3a4311c2014-03-17 12:00:47 -07006099 mA2dpSuspended(false),
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006100 mAudioPortGeneration(1),
6101 mBeaconMuteRefCount(0),
6102 mBeaconPlayingRefCount(0),
Eric Laurent9459fb02015-08-12 18:36:32 -07006103 mBeaconMuted(false),
Andy Hung2ddee192015-12-18 17:34:44 -08006104 mTtsOutputAvailable(false),
Eric Laurent36829f92017-04-07 19:04:42 -07006105 mMasterMono(false),
Eric Laurent4eb58f12018-12-07 16:41:02 -08006106 mMusicEffectOutput(AUDIO_IO_HANDLE_NONE)
Eric Laurente552edb2014-03-10 17:42:56 -07006107{
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006108}
François Gaffied1ab2bd2015-12-02 18:20:06 +01006109
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006110status_t AudioPolicyManager::initialize() {
Mikhail Naganovf1b6d972023-05-02 13:56:01 -07006111 if (mEngine == nullptr) {
6112 return NO_INIT;
François Gaffie2110e042015-03-24 08:41:51 +01006113 }
6114 mEngine->setObserver(this);
6115 status_t status = mEngine->initCheck();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006116 if (status != NO_ERROR) {
6117 LOG_FATAL("Policy engine not initialized(err=%d)", status);
6118 return status;
6119 }
François Gaffie2110e042015-03-24 08:41:51 +01006120
jiabin29230182023-04-04 21:02:36 +00006121 // The actual device selection cache will be updated when calling `updateDevicesAndOutputs`
6122 // at the end of this function.
6123 mEngine->initializeDeviceSelectionCache();
Eric Laurent1d69c872021-01-11 18:53:01 +01006124 mCommunnicationStrategy = mEngine->getProductStrategyForAttributes(
6125 mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL));
6126
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006127 // after parsing the config, mConfig contain all known devices;
Eric Laurente552edb2014-03-10 17:42:56 -07006128 // open all output streams needed to access attached devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006129 onNewAudioModulesAvailableInt(nullptr /*newDevices*/);
François Gaffie11d30102018-11-02 16:09:09 +01006130
Eric Laurent3a4311c2014-03-17 12:00:47 -07006131 // make sure default device is reachable
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006132 if (const auto defaultOutputDevice = mConfig->getDefaultOutputDevice();
6133 defaultOutputDevice == nullptr ||
6134 !mAvailableOutputDevices.contains(defaultOutputDevice)) {
6135 ALOGE_IF(defaultOutputDevice != nullptr, "Default device %s is unreachable",
6136 defaultOutputDevice->toString().c_str());
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006137 status = NO_INIT;
Eric Laurent3a4311c2014-03-17 12:00:47 -07006138 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02006139 ALOGW_IF(mPrimaryOutput == nullptr, "The policy configuration does not declare a primary output");
Eric Laurente552edb2014-03-10 17:42:56 -07006140
Tomoharu Kasahara71c90912018-10-31 09:10:12 +09006141 // Silence ALOGV statements
6142 property_set("log.tag." LOG_TAG, "D");
6143
Eric Laurente552edb2014-03-10 17:42:56 -07006144 updateDevicesAndOutputs();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006145 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07006146}
6147
Eric Laurente0720872014-03-11 09:30:41 -07006148AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07006149{
Eric Laurente552edb2014-03-10 17:42:56 -07006150 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08006151 mOutputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07006152 }
6153 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08006154 mInputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07006155 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07006156 mAvailableOutputDevices.clear();
6157 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07006158 mOutputs.clear();
6159 mInputs.clear();
6160 mHwModules.clear();
Mikhail Naganov100f0122018-11-29 11:22:16 -08006161 mManualSurroundFormats.clear();
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006162 mConfig.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07006163}
6164
Eric Laurente0720872014-03-11 09:30:41 -07006165status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07006166{
Eric Laurent87ffa392015-05-22 10:32:38 -07006167 return hasPrimaryOutput() ? NO_ERROR : NO_INIT;
Eric Laurente552edb2014-03-10 17:42:56 -07006168}
6169
Eric Laurente552edb2014-03-10 17:42:56 -07006170// ---
6171
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006172void AudioPolicyManager::onNewAudioModulesAvailable()
6173{
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006174 DeviceVector newDevices;
6175 onNewAudioModulesAvailableInt(&newDevices);
6176 if (!newDevices.empty()) {
6177 nextAudioPortGeneration();
6178 mpClientInterface->onAudioPortListUpdate();
6179 }
6180}
6181
6182void AudioPolicyManager::onNewAudioModulesAvailableInt(DeviceVector *newDevices)
6183{
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006184 for (const auto& hwModule : mConfig->getHwModules()) {
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006185 if (std::find(mHwModules.begin(), mHwModules.end(), hwModule) != mHwModules.end()) {
6186 continue;
6187 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006188 if (hwModule->getHandle() == AUDIO_MODULE_HANDLE_NONE) {
Mikhail Naganovffd97712023-05-03 17:45:36 -07006189 if (audio_module_handle_t handle = mpClientInterface->loadHwModule(hwModule->getName());
6190 handle != AUDIO_MODULE_HANDLE_NONE) {
6191 hwModule->setHandle(handle);
6192 } else {
6193 ALOGW("could not load HW module %s", hwModule->getName());
6194 continue;
6195 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006196 }
6197 mHwModules.push_back(hwModule);
Dean Wheatley12a87132021-04-16 10:08:49 +10006198 // open all output streams needed to access attached devices.
6199 // direct outputs are closed immediately after checking the availability of attached devices
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006200 // This also validates mAvailableOutputDevices list
6201 for (const auto& outProfile : hwModule->getOutputProfiles()) {
6202 if (!outProfile->canOpenNewIo()) {
6203 ALOGE("Invalid Output profile max open count %u for profile %s",
6204 outProfile->maxOpenCount, outProfile->getTagName().c_str());
6205 continue;
6206 }
6207 if (!outProfile->hasSupportedDevices()) {
6208 ALOGW("Output profile contains no device on module %s", hwModule->getName());
6209 continue;
6210 }
Carter Hsu1a3364a2022-01-21 15:32:56 +08006211 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_TTS) != 0 ||
6212 (outProfile->getFlags() & AUDIO_OUTPUT_FLAG_ULTRASOUND) != 0) {
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006213 mTtsOutputAvailable = true;
6214 }
6215
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006216 const DeviceVector &supportedDevices = outProfile->getSupportedDevices();
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006217 DeviceVector availProfileDevices = supportedDevices.filter(mConfig->getOutputDevices());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006218 sp<DeviceDescriptor> supportedDevice = 0;
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006219 if (supportedDevices.contains(mConfig->getDefaultOutputDevice())) {
6220 supportedDevice = mConfig->getDefaultOutputDevice();
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006221 } else {
6222 // choose first device present in profile's SupportedDevices also part of
6223 // mAvailableOutputDevices.
6224 if (availProfileDevices.isEmpty()) {
6225 continue;
6226 }
6227 supportedDevice = availProfileDevices.itemAt(0);
6228 }
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006229 if (!mConfig->getOutputDevices().contains(supportedDevice)) {
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006230 continue;
6231 }
6232 sp<SwAudioOutputDescriptor> outputDesc = new SwAudioOutputDescriptor(outProfile,
6233 mpClientInterface);
6234 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentf1f22e72021-07-13 14:04:14 +02006235 status_t status = outputDesc->open(nullptr /* halConfig */, nullptr /* mixerConfig */,
6236 DeviceVector(supportedDevice),
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006237 AUDIO_STREAM_DEFAULT,
6238 AUDIO_OUTPUT_FLAG_NONE, &output);
6239 if (status != NO_ERROR) {
6240 ALOGW("Cannot open output stream for devices %s on hw module %s",
6241 supportedDevice->toString().c_str(), hwModule->getName());
6242 continue;
6243 }
6244 for (const auto &device : availProfileDevices) {
6245 // give a valid ID to an attached device once confirmed it is reachable
6246 if (!device->isAttached()) {
6247 device->attach(hwModule);
6248 mAvailableOutputDevices.add(device);
jiabin1c4794b2020-05-05 10:08:05 -07006249 device->setEncapsulationInfoFromHal(mpClientInterface);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006250 if (newDevices) newDevices->add(device);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006251 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
6252 }
6253 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02006254 if (mPrimaryOutput == nullptr &&
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006255 outProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
6256 mPrimaryOutput = outputDesc;
6257 }
Eric Laurent39095982021-08-24 18:29:27 +02006258 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
Eric Laurentc529cf62020-04-17 18:19:10 -07006259 outputDesc->close();
6260 } else {
6261 addOutput(output, outputDesc);
6262 setOutputDevices(outputDesc,
6263 DeviceVector(supportedDevice),
6264 true,
6265 0,
6266 NULL);
6267 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006268 }
6269 // open input streams needed to access attached devices to validate
6270 // mAvailableInputDevices list
6271 for (const auto& inProfile : hwModule->getInputProfiles()) {
6272 if (!inProfile->canOpenNewIo()) {
6273 ALOGE("Invalid Input profile max open count %u for profile %s",
6274 inProfile->maxOpenCount, inProfile->getTagName().c_str());
6275 continue;
6276 }
6277 if (!inProfile->hasSupportedDevices()) {
6278 ALOGW("Input profile contains no device on module %s", hwModule->getName());
6279 continue;
6280 }
6281 // chose first device present in profile's SupportedDevices also part of
6282 // available input devices
6283 const DeviceVector &supportedDevices = inProfile->getSupportedDevices();
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006284 DeviceVector availProfileDevices = supportedDevices.filter(mConfig->getInputDevices());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006285 if (availProfileDevices.isEmpty()) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01006286 ALOGV("%s: Input device list is empty! for profile %s",
6287 __func__, inProfile->getTagName().c_str());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006288 continue;
6289 }
6290 sp<AudioInputDescriptor> inputDesc =
6291 new AudioInputDescriptor(inProfile, mpClientInterface);
6292
6293 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
6294 status_t status = inputDesc->open(nullptr,
6295 availProfileDevices.itemAt(0),
6296 AUDIO_SOURCE_MIC,
6297 AUDIO_INPUT_FLAG_NONE,
6298 &input);
6299 if (status != NO_ERROR) {
6300 ALOGW("Cannot open input stream for device %s on hw module %s",
6301 availProfileDevices.toString().c_str(),
6302 hwModule->getName());
6303 continue;
6304 }
6305 for (const auto &device : availProfileDevices) {
6306 // give a valid ID to an attached device once confirmed it is reachable
6307 if (!device->isAttached()) {
6308 device->attach(hwModule);
6309 device->importAudioPortAndPickAudioProfile(inProfile, true);
6310 mAvailableInputDevices.add(device);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006311 if (newDevices) newDevices->add(device);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006312 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
6313 }
6314 }
6315 inputDesc->close();
6316 }
6317 }
Eric Laurente191d1b2022-04-15 11:59:25 +02006318
6319 // Check if spatializer outputs can be closed until used.
6320 // mOutputs vector never contains duplicated outputs at this point.
6321 std::vector<audio_io_handle_t> outputsClosed;
6322 for (size_t i = 0; i < mOutputs.size(); i++) {
6323 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
6324 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0
6325 && !isOutputOnlyAvailableRouteToSomeDevice(desc)) {
6326 outputsClosed.push_back(desc->mIoHandle);
6327 desc->close();
6328 }
6329 }
6330 for (auto output : outputsClosed) {
6331 removeOutput(output);
6332 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006333}
6334
Eric Laurent98e38192018-02-15 18:31:53 -08006335void AudioPolicyManager::addOutput(audio_io_handle_t output,
6336 const sp<SwAudioOutputDescriptor>& outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07006337{
Eric Laurent1c333e22014-05-20 10:48:17 -07006338 mOutputs.add(output, outputDesc);
jiabin9a3361e2019-10-01 09:38:30 -07006339 applyStreamVolumes(outputDesc, DeviceTypeSet(), 0 /* delayMs */, true /* force */);
Andy Hung2ddee192015-12-18 17:34:44 -08006340 updateMono(output); // update mono status when adding to output list
Eric Laurent36829f92017-04-07 19:04:42 -07006341 selectOutputForMusicEffects();
Eric Laurent6a94d692014-05-20 11:18:06 -07006342 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07006343}
6344
François Gaffie53615e22015-03-19 09:24:12 +01006345void AudioPolicyManager::removeOutput(audio_io_handle_t output)
6346{
Francois Gaffiebce7cd42020-10-14 16:13:20 +02006347 if (mPrimaryOutput != 0 && mPrimaryOutput == mOutputs.valueFor(output)) {
6348 ALOGV("%s: removing primary output", __func__);
6349 mPrimaryOutput = nullptr;
6350 }
François Gaffie53615e22015-03-19 09:24:12 +01006351 mOutputs.removeItem(output);
Eric Laurent36829f92017-04-07 19:04:42 -07006352 selectOutputForMusicEffects();
François Gaffie53615e22015-03-19 09:24:12 +01006353}
6354
Eric Laurent98e38192018-02-15 18:31:53 -08006355void AudioPolicyManager::addInput(audio_io_handle_t input,
6356 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07006357{
Eric Laurent1c333e22014-05-20 10:48:17 -07006358 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07006359 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07006360}
Eric Laurente552edb2014-03-10 17:42:56 -07006361
François Gaffie11d30102018-11-02 16:09:09 +01006362status_t AudioPolicyManager::checkOutputsForDevice(const sp<DeviceDescriptor>& device,
François Gaffie53615e22015-03-19 09:24:12 +01006363 audio_policy_dev_state_t state,
François Gaffie11d30102018-11-02 16:09:09 +01006364 SortedVector<audio_io_handle_t>& outputs)
Eric Laurente552edb2014-03-10 17:42:56 -07006365{
François Gaffie11d30102018-11-02 16:09:09 +01006366 audio_devices_t deviceType = device->type();
jiabince9f20e2019-09-12 16:29:15 -07006367 const String8 &address = String8(device->address().c_str());
Eric Laurentc75307b2015-03-17 15:29:32 -07006368 sp<SwAudioOutputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07006369
François Gaffie11d30102018-11-02 16:09:09 +01006370 if (audio_device_is_digital(deviceType)) {
Eric Laurentcc750d32015-06-25 11:48:20 -07006371 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01006372 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07006373 }
Eric Laurente552edb2014-03-10 17:42:56 -07006374
Eric Laurent3b73df72014-03-11 09:06:29 -07006375 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
jiabinb4fed192020-09-22 14:45:40 -07006376 // first call getAudioPort to get the supported attributes from the HAL
6377 struct audio_port_v7 port = {};
6378 device->toAudioPort(&port);
6379 status_t status = mpClientInterface->getAudioPort(&port);
6380 if (status == NO_ERROR) {
6381 device->importAudioPort(port);
6382 }
6383
6384 // then list already open outputs that can be routed to this device
Eric Laurente552edb2014-03-10 17:42:56 -07006385 for (size_t i = 0; i < mOutputs.size(); i++) {
6386 desc = mOutputs.valueAt(i);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006387 if (!desc->isDuplicated() && desc->supportsDevice(device)
jiabin9a3361e2019-10-01 09:38:30 -07006388 && desc->devicesSupportEncodedFormats({deviceType})) {
François Gaffie11d30102018-11-02 16:09:09 +01006389 ALOGV("checkOutputsForDevice(): adding opened output %d on device %s",
6390 mOutputs.keyAt(i), device->toString().c_str());
6391 outputs.add(mOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07006392 }
6393 }
6394 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07006395 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006396 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006397 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
6398 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
François Gaffie11d30102018-11-02 16:09:09 +01006399 if (profile->supportsDevice(device)) {
6400 profiles.add(profile);
6401 ALOGV("checkOutputsForDevice(): adding profile %zu from module %s",
6402 j, hwModule->getName());
Eric Laurente552edb2014-03-10 17:42:56 -07006403 }
6404 }
6405 }
6406
Eric Laurent7b279bb2015-12-14 10:18:23 -08006407 ALOGV(" found %zu profiles, %zu outputs", profiles.size(), outputs.size());
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006408
Eric Laurente552edb2014-03-10 17:42:56 -07006409 if (profiles.isEmpty() && outputs.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006410 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07006411 return BAD_VALUE;
6412 }
6413
6414 // open outputs for matching profiles if needed. Direct outputs are also opened to
6415 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
6416 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07006417 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07006418
6419 // nothing to do if one output is already opened for this profile
6420 size_t j;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006421 for (j = 0; j < outputs.size(); j++) {
6422 desc = mOutputs.valueFor(outputs.itemAt(j));
Eric Laurente552edb2014-03-10 17:42:56 -07006423 if (!desc->isDuplicated() && desc->mProfile == profile) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07006424 // matching profile: save the sample rates, format and channel masks supported
6425 // by the profile in our device descriptor
François Gaffie11d30102018-11-02 16:09:09 +01006426 if (audio_device_is_digital(deviceType)) {
jiabin4ef93452019-09-10 14:29:54 -07006427 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006428 }
Eric Laurente552edb2014-03-10 17:42:56 -07006429 break;
6430 }
6431 }
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006432 if (j != outputs.size()) {
Eric Laurente552edb2014-03-10 17:42:56 -07006433 continue;
6434 }
6435
Eric Laurent3974e3b2017-12-07 17:58:43 -08006436 if (!profile->canOpenNewIo()) {
6437 ALOGW("Max Output number %u already opened for this profile %s",
6438 profile->maxOpenCount, profile->getTagName().c_str());
6439 continue;
6440 }
6441
Eric Laurent83efe1c2017-07-09 16:51:08 -07006442 ALOGV("opening output for device %08x with params %s profile %p name %s",
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00006443 deviceType, address.c_str(), profile.get(), profile->getName().c_str());
jiabinbce0c1d2020-10-05 11:20:18 -07006444 desc = openOutputWithProfileAndDevice(profile, DeviceVector(device));
6445 audio_io_handle_t output = desc == nullptr ? AUDIO_IO_HANDLE_NONE : desc->mIoHandle;
Eric Laurentcf2c0212014-07-25 16:20:43 -07006446 if (output == AUDIO_IO_HANDLE_NONE) {
François Gaffie11d30102018-11-02 16:09:09 +01006447 ALOGW("checkOutputsForDevice() could not open output for device %x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07006448 profiles.removeAt(profile_index);
6449 profile_index--;
6450 } else {
6451 outputs.add(output);
Paul McLean9080a4c2015-06-18 08:24:02 -07006452 // Load digital format info only for digital devices
François Gaffie11d30102018-11-02 16:09:09 +01006453 if (audio_device_is_digital(deviceType)) {
jiabinbce0c1d2020-10-05 11:20:18 -07006454 // TODO: when getAudioPort is ready, it may not be needed to import the audio
6455 // port but just pick audio profile
jiabin4ef93452019-09-10 14:29:54 -07006456 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006457 }
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07006458
François Gaffie11d30102018-11-02 16:09:09 +01006459 if (device_distinguishes_on_address(deviceType)) {
6460 ALOGV("checkOutputsForDevice(): setOutputDevices %s",
6461 device->toString().c_str());
6462 setOutputDevices(desc, DeviceVector(device), true/*force*/, 0/*delay*/,
6463 NULL/*patch handle*/);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006464 }
Eric Laurente552edb2014-03-10 17:42:56 -07006465 ALOGV("checkOutputsForDevice(): adding output %d", output);
6466 }
6467 }
6468
6469 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006470 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07006471 return BAD_VALUE;
6472 }
Eric Laurentd4692962014-05-05 18:13:44 -07006473 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07006474 // check if one opened output is not needed any more after disconnecting one device
6475 for (size_t i = 0; i < mOutputs.size(); i++) {
6476 desc = mOutputs.valueAt(i);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006477 if (!desc->isDuplicated()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08006478 // exact match on device
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006479 if (device_distinguishes_on_address(deviceType) && desc->supportsDevice(device)
Francois Gaffiec7d4c222021-12-02 11:12:52 +01006480 && desc->containsSingleDeviceSupportingEncodedFormats(device)) {
François Gaffie11d30102018-11-02 16:09:09 +01006481 outputs.add(mOutputs.keyAt(i));
Francois Gaffie716e1432019-01-14 16:58:59 +01006482 } else if (!mAvailableOutputDevices.containsAtLeastOne(desc->supportedDevices())) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006483 ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
6484 mOutputs.keyAt(i));
6485 outputs.add(mOutputs.keyAt(i));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006486 }
Eric Laurente552edb2014-03-10 17:42:56 -07006487 }
6488 }
Eric Laurentd4692962014-05-05 18:13:44 -07006489 // Clear any profiles associated with the disconnected device.
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006490 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006491 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
6492 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
jiabinbce0c1d2020-10-05 11:20:18 -07006493 if (!profile->supportsDevice(device)) {
6494 continue;
6495 }
6496 ALOGV("checkOutputsForDevice(): "
6497 "clearing direct output profile %zu on module %s",
6498 j, hwModule->getName());
6499 profile->clearAudioProfiles();
6500 if (!profile->hasDynamicAudioProfile()) {
6501 continue;
6502 }
6503 // When a device is disconnected, if there is an IOProfile that contains dynamic
6504 // profiles and supports the disconnected device, call getAudioPort to repopulate
6505 // the capabilities of the devices that is supported by the IOProfile.
6506 for (const auto& supportedDevice : profile->getSupportedDevices()) {
6507 if (supportedDevice == device ||
6508 !mAvailableOutputDevices.contains(supportedDevice)) {
6509 continue;
6510 }
6511 struct audio_port_v7 port;
6512 supportedDevice->toAudioPort(&port);
6513 status_t status = mpClientInterface->getAudioPort(&port);
6514 if (status == NO_ERROR) {
6515 supportedDevice->importAudioPort(port);
6516 }
Eric Laurente552edb2014-03-10 17:42:56 -07006517 }
6518 }
6519 }
6520 }
6521 return NO_ERROR;
6522}
6523
François Gaffie11d30102018-11-02 16:09:09 +01006524status_t AudioPolicyManager::checkInputsForDevice(const sp<DeviceDescriptor>& device,
Eric Laurent0dd51852019-04-19 18:18:58 -07006525 audio_policy_dev_state_t state)
Eric Laurentd4692962014-05-05 18:13:44 -07006526{
Eric Laurent1f2f2232014-06-02 12:01:23 -07006527 sp<AudioInputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07006528
François Gaffie11d30102018-11-02 16:09:09 +01006529 if (audio_device_is_digital(device->type())) {
Eric Laurentcc750d32015-06-25 11:48:20 -07006530 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01006531 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07006532 }
6533
Eric Laurentd4692962014-05-05 18:13:44 -07006534 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
jiabinbf5f4262023-04-12 21:48:34 +00006535 // first call getAudioPort to get the supported attributes from the HAL
6536 struct audio_port_v7 port = {};
6537 device->toAudioPort(&port);
6538 status_t status = mpClientInterface->getAudioPort(&port);
6539 if (status == NO_ERROR) {
6540 device->importAudioPort(port);
6541 }
6542
Eric Laurent0dd51852019-04-19 18:18:58 -07006543 // look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07006544 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006545 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07006546 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006547 profile_index < hwModule->getInputProfiles().size();
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006548 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006549 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Eric Laurent275e8e92014-11-30 15:14:47 -08006550
François Gaffie11d30102018-11-02 16:09:09 +01006551 if (profile->supportsDevice(device)) {
6552 profiles.add(profile);
6553 ALOGV("checkInputsForDevice(): adding profile %zu from module %s",
6554 profile_index, hwModule->getName());
Eric Laurentd4692962014-05-05 18:13:44 -07006555 }
6556 }
6557 }
6558
Eric Laurent0dd51852019-04-19 18:18:58 -07006559 if (profiles.isEmpty()) {
6560 ALOGW("%s: No input profile available for device %s",
6561 __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07006562 return BAD_VALUE;
6563 }
6564
6565 // open inputs for matching profiles if needed. Direct inputs are also opened to
6566 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
6567 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
6568
Eric Laurent1c333e22014-05-20 10:48:17 -07006569 sp<IOProfile> profile = profiles[profile_index];
Eric Laurent3974e3b2017-12-07 17:58:43 -08006570
Eric Laurentd4692962014-05-05 18:13:44 -07006571 // nothing to do if one input is already opened for this profile
6572 size_t input_index;
6573 for (input_index = 0; input_index < mInputs.size(); input_index++) {
6574 desc = mInputs.valueAt(input_index);
6575 if (desc->mProfile == profile) {
François Gaffie11d30102018-11-02 16:09:09 +01006576 if (audio_device_is_digital(device->type())) {
jiabin4ef93452019-09-10 14:29:54 -07006577 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006578 }
Eric Laurentd4692962014-05-05 18:13:44 -07006579 break;
6580 }
6581 }
6582 if (input_index != mInputs.size()) {
6583 continue;
6584 }
6585
Eric Laurent3974e3b2017-12-07 17:58:43 -08006586 if (!profile->canOpenNewIo()) {
6587 ALOGW("Max Input number %u already opened for this profile %s",
6588 profile->maxOpenCount, profile->getTagName().c_str());
6589 continue;
6590 }
6591
Eric Laurentfe231122017-11-17 17:48:06 -08006592 desc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentcf2c0212014-07-25 16:20:43 -07006593 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
jiabinbf5f4262023-04-12 21:48:34 +00006594 status = desc->open(nullptr, device, AUDIO_SOURCE_MIC, AUDIO_INPUT_FLAG_NONE, &input);
Eric Laurentd4692962014-05-05 18:13:44 -07006595
Eric Laurentcf2c0212014-07-25 16:20:43 -07006596 if (status == NO_ERROR) {
jiabince9f20e2019-09-12 16:29:15 -07006597 const String8& address = String8(device->address().c_str());
Tomasz Wasilczykfd9ffd12023-08-14 17:56:22 +00006598 if (!address.empty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006599 char *param = audio_device_address_to_parameter(device->type(), address);
Eric Laurentcf2c0212014-07-25 16:20:43 -07006600 mpClientInterface->setParameters(input, String8(param));
6601 free(param);
Eric Laurentd4692962014-05-05 18:13:44 -07006602 }
jiabin12537fc2023-10-12 17:56:08 +00006603 updateAudioProfiles(device, input, profile);
François Gaffie112b0af2015-11-19 16:13:25 +01006604 if (!profile->hasValidAudioProfile()) {
Eric Laurentd4692962014-05-05 18:13:44 -07006605 ALOGW("checkInputsForDevice() direct input missing param");
Eric Laurentfe231122017-11-17 17:48:06 -08006606 desc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07006607 input = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07006608 }
6609
Eric Laurent0dd51852019-04-19 18:18:58 -07006610 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07006611 addInput(input, desc);
6612 }
6613 } // endif input != 0
6614
Eric Laurentcf2c0212014-07-25 16:20:43 -07006615 if (input == AUDIO_IO_HANDLE_NONE) {
Pattydd807582021-11-04 21:01:03 +08006616 ALOGW("%s could not open input for device %s", __func__,
François Gaffie11d30102018-11-02 16:09:09 +01006617 device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07006618 profiles.removeAt(profile_index);
6619 profile_index--;
6620 } else {
François Gaffie11d30102018-11-02 16:09:09 +01006621 if (audio_device_is_digital(device->type())) {
jiabin4ef93452019-09-10 14:29:54 -07006622 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006623 }
Eric Laurentd4692962014-05-05 18:13:44 -07006624 ALOGV("checkInputsForDevice(): adding input %d", input);
6625 }
6626 } // end scan profiles
6627
6628 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006629 ALOGW("%s: No input available for device %s", __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07006630 return BAD_VALUE;
6631 }
6632 } else {
6633 // Disconnect
Eric Laurentd4692962014-05-05 18:13:44 -07006634 // Clear any profiles associated with the disconnected device.
Mikhail Naganovd4120142017-12-06 15:49:22 -08006635 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07006636 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006637 profile_index < hwModule->getInputProfiles().size();
Eric Laurentd4692962014-05-05 18:13:44 -07006638 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006639 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Francois Gaffie716e1432019-01-14 16:58:59 +01006640 if (profile->supportsDevice(device)) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08006641 ALOGV("checkInputsForDevice(): clearing direct input profile %zu on module %s",
6642 profile_index, hwModule->getName());
François Gaffie112b0af2015-11-19 16:13:25 +01006643 profile->clearAudioProfiles();
Eric Laurentd4692962014-05-05 18:13:44 -07006644 }
6645 }
6646 }
6647 } // end disconnect
6648
6649 return NO_ERROR;
6650}
6651
6652
Eric Laurente0720872014-03-11 09:30:41 -07006653void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07006654{
6655 ALOGV("closeOutput(%d)", output);
6656
François Gaffie1c878552018-11-22 16:53:21 +01006657 sp<SwAudioOutputDescriptor> closingOutput = mOutputs.valueFor(output);
6658 if (closingOutput == NULL) {
Eric Laurente552edb2014-03-10 17:42:56 -07006659 ALOGW("closeOutput() unknown output %d", output);
6660 return;
6661 }
Mikhail Naganov32ebca32019-03-22 15:42:52 -07006662 const bool closingOutputWasActive = closingOutput->isActive();
François Gaffie1c878552018-11-22 16:53:21 +01006663 mPolicyMixes.closeOutput(closingOutput);
Eric Laurent275e8e92014-11-30 15:14:47 -08006664
Eric Laurente552edb2014-03-10 17:42:56 -07006665 // look for duplicated outputs connected to the output being removed.
6666 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie1c878552018-11-22 16:53:21 +01006667 sp<SwAudioOutputDescriptor> dupOutput = mOutputs.valueAt(i);
6668 if (dupOutput->isDuplicated() &&
6669 (dupOutput->mOutput1 == closingOutput || dupOutput->mOutput2 == closingOutput)) {
6670 sp<SwAudioOutputDescriptor> remainingOutput =
6671 dupOutput->mOutput1 == closingOutput ? dupOutput->mOutput2 : dupOutput->mOutput1;
Eric Laurente552edb2014-03-10 17:42:56 -07006672 // As all active tracks on duplicated output will be deleted,
6673 // and as they were also referenced on the other output, the reference
6674 // count for their stream type must be adjusted accordingly on
6675 // the other output.
François Gaffie1c878552018-11-22 16:53:21 +01006676 const bool wasActive = remainingOutput->isActive();
6677 // Note: no-op on the closing output where all clients has already been set inactive
6678 dupOutput->setAllClientsInactive();
Eric Laurent733ce942017-12-07 12:18:25 -08006679 // stop() will be a no op if the output is still active but is needed in case all
6680 // active streams refcounts where cleared above
6681 if (wasActive) {
François Gaffie1c878552018-11-22 16:53:21 +01006682 remainingOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08006683 }
Eric Laurente552edb2014-03-10 17:42:56 -07006684 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
6685 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
6686
6687 mpClientInterface->closeOutput(duplicatedOutput);
François Gaffie53615e22015-03-19 09:24:12 +01006688 removeOutput(duplicatedOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07006689 }
6690 }
6691
Eric Laurent05b90f82014-08-27 15:32:29 -07006692 nextAudioPortGeneration();
6693
François Gaffie1c878552018-11-22 16:53:21 +01006694 ssize_t index = mAudioPatches.indexOfKey(closingOutput->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07006695 if (index >= 0) {
6696 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006697 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
6698 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07006699 mAudioPatches.removeItemsAt(index);
6700 mpClientInterface->onAudioPatchListUpdate();
6701 }
6702
Mikhail Naganov32ebca32019-03-22 15:42:52 -07006703 if (closingOutputWasActive) {
6704 closingOutput->stop();
6705 }
François Gaffie1c878552018-11-22 16:53:21 +01006706 closingOutput->close();
Eric Laurente552edb2014-03-10 17:42:56 -07006707
François Gaffie53615e22015-03-19 09:24:12 +01006708 removeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07006709 mPreviousOutputs = mOutputs;
Eric Laurentb4f42a92022-01-17 17:37:31 +01006710 if (closingOutput == mSpatializerOutput) {
6711 mSpatializerOutput.clear();
6712 }
Dean Wheatley3023b382018-08-09 07:42:40 +10006713
6714 // MSD patches may have been released to support a non-MSD direct output. Reset MSD patch if
6715 // no direct outputs are open.
François Gaffie11d30102018-11-02 16:09:09 +01006716 if (!getMsdAudioOutDevices().isEmpty()) {
Dean Wheatley3023b382018-08-09 07:42:40 +10006717 bool directOutputOpen = false;
6718 for (size_t i = 0; i < mOutputs.size(); i++) {
6719 if (mOutputs[i]->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
6720 directOutputOpen = true;
6721 break;
6722 }
6723 }
6724 if (!directOutputOpen) {
Michael Chan6fb34492020-12-08 15:44:49 +11006725 ALOGV("no direct outputs open, reset MSD patches");
6726 // TODO: The MSD patches to be established here may differ to current MSD patches due to
6727 // how output devices for patching are resolved. Avoid by caching and reusing the
6728 // arguments to mEngine->getOutputDevicesForAttributes() when resolving which output
6729 // devices to patch to. This may be complicated by the fact that devices may become
6730 // unavailable.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11006731 setMsdOutputPatches();
Dean Wheatley3023b382018-08-09 07:42:40 +10006732 }
6733 }
Eric Laurent05b90f82014-08-27 15:32:29 -07006734}
6735
6736void AudioPolicyManager::closeInput(audio_io_handle_t input)
6737{
6738 ALOGV("closeInput(%d)", input);
6739
6740 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
6741 if (inputDesc == NULL) {
6742 ALOGW("closeInput() unknown input %d", input);
6743 return;
6744 }
6745
Eric Laurent6a94d692014-05-20 11:18:06 -07006746 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07006747
François Gaffie11d30102018-11-02 16:09:09 +01006748 sp<DeviceDescriptor> device = inputDesc->getDevice();
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08006749 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07006750 if (index >= 0) {
6751 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006752 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
6753 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07006754 mAudioPatches.removeItemsAt(index);
6755 mpClientInterface->onAudioPatchListUpdate();
6756 }
6757
Eric Laurentfe231122017-11-17 17:48:06 -08006758 inputDesc->close();
Eric Laurent05b90f82014-08-27 15:32:29 -07006759 mInputs.removeItem(input);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07006760
François Gaffie11d30102018-11-02 16:09:09 +01006761 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
6762 if (primaryInputDevices.contains(device) &&
Haynes Mathew George1d539d92018-03-16 11:40:49 -07006763 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07006764 mpClientInterface->setSoundTriggerCaptureState(false);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07006765 }
Eric Laurente552edb2014-03-10 17:42:56 -07006766}
6767
François Gaffie11d30102018-11-02 16:09:09 +01006768SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevices(
6769 const DeviceVector &devices,
6770 const SwAudioOutputCollection& openOutputs)
Eric Laurente552edb2014-03-10 17:42:56 -07006771{
6772 SortedVector<audio_io_handle_t> outputs;
6773
François Gaffie11d30102018-11-02 16:09:09 +01006774 ALOGVV("%s() devices %s", __func__, devices.toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07006775 for (size_t i = 0; i < openOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01006776 ALOGVV("output %zu isDuplicated=%d device=%s",
Eric Laurent8c7e6da2015-04-21 17:37:00 -07006777 i, openOutputs.valueAt(i)->isDuplicated(),
François Gaffie11d30102018-11-02 16:09:09 +01006778 openOutputs.valueAt(i)->supportedDevices().toString().c_str());
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006779 if (openOutputs.valueAt(i)->supportsAllDevices(devices)
jiabin9a3361e2019-10-01 09:38:30 -07006780 && openOutputs.valueAt(i)->devicesSupportEncodedFormats(devices.types())) {
François Gaffie11d30102018-11-02 16:09:09 +01006781 ALOGVV("%s() found output %d", __func__, openOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07006782 outputs.add(openOutputs.keyAt(i));
6783 }
6784 }
6785 return outputs;
6786}
6787
Mikhail Naganov37977152018-07-11 15:54:44 -07006788void AudioPolicyManager::checkForDeviceAndOutputChanges(std::function<bool()> onOutputsChecked)
6789{
6790 // checkA2dpSuspend must run before checkOutputForAllStrategies so that A2DP
6791 // output is suspended before any tracks are moved to it
6792 checkA2dpSuspend();
6793 checkOutputForAllStrategies();
Kevin Rocard153f92d2018-12-18 18:33:28 -08006794 checkSecondaryOutputs();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11006795 if (onOutputsChecked != nullptr && onOutputsChecked()) checkA2dpSuspend();
Mikhail Naganov37977152018-07-11 15:54:44 -07006796 updateDevicesAndOutputs();
Mikhail Naganov7bd9b8d2018-11-15 02:09:03 +00006797 if (mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD) != 0) {
Michael Chan6fb34492020-12-08 15:44:49 +11006798 // TODO: The MSD patches to be established here may differ to current MSD patches due to how
6799 // output devices for patching are resolved. Nevertheless, AudioTracks affected by device
6800 // configuration changes will ultimately be rerouted correctly. We can still avoid
6801 // unnecessary rerouting by caching and reusing the arguments to
6802 // mEngine->getOutputDevicesForAttributes() when resolving which output devices to patch to.
6803 // This may be complicated by the fact that devices may become unavailable.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11006804 setMsdOutputPatches();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11006805 }
Jean-Michel Trivi9a6b9ad2020-10-22 16:46:43 -07006806 // an event that changed routing likely occurred, inform upper layers
6807 mpClientInterface->onRoutingUpdated();
Mikhail Naganov37977152018-07-11 15:54:44 -07006808}
6809
François Gaffiec005e562018-11-06 15:04:49 +01006810bool AudioPolicyManager::followsSameRouting(const audio_attributes_t &lAttr,
6811 const audio_attributes_t &rAttr) const
Eric Laurente552edb2014-03-10 17:42:56 -07006812{
François Gaffiec005e562018-11-06 15:04:49 +01006813 return mEngine->getProductStrategyForAttributes(lAttr) ==
6814 mEngine->getProductStrategyForAttributes(rAttr);
6815}
6816
Francois Gaffieff1eb522020-05-06 18:37:04 +02006817void AudioPolicyManager::checkAudioSourceForAttributes(const audio_attributes_t &attr)
6818{
6819 for (size_t i = 0; i < mAudioSources.size(); i++) {
6820 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
6821 if (sourceDesc != nullptr && followsSameRouting(attr, sourceDesc->attributes())
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02006822 && sourceDesc->getPatchHandle() == AUDIO_PATCH_HANDLE_NONE
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02006823 && !isCallRxAudioSource(sourceDesc) && !sourceDesc->isInternal()) {
Francois Gaffieff1eb522020-05-06 18:37:04 +02006824 connectAudioSource(sourceDesc);
6825 }
6826 }
6827}
6828
6829void AudioPolicyManager::clearAudioSourcesForOutput(audio_io_handle_t output)
6830{
6831 for (size_t i = 0; i < mAudioSources.size(); i++) {
6832 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
6833 if (sourceDesc != nullptr && sourceDesc->swOutput().promote() != nullptr
6834 && sourceDesc->swOutput().promote()->mIoHandle == output) {
6835 disconnectAudioSource(sourceDesc);
6836 }
6837 }
6838}
6839
François Gaffiec005e562018-11-06 15:04:49 +01006840void AudioPolicyManager::checkOutputForAttributes(const audio_attributes_t &attr)
6841{
6842 auto psId = mEngine->getProductStrategyForAttributes(attr);
6843
6844 DeviceVector oldDevices = mEngine->getOutputDevicesForAttributes(attr, 0, true /*fromCache*/);
6845 DeviceVector newDevices = mEngine->getOutputDevicesForAttributes(attr, 0, false /*fromCache*/);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07006846
François Gaffie11d30102018-11-02 16:09:09 +01006847 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevices(oldDevices, mPreviousOutputs);
6848 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevices(newDevices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07006849
Eric Laurentc209fe42020-06-05 18:11:23 -07006850 uint32_t maxLatency = 0;
Oscar Azucena873d10f2023-01-12 18:34:42 -08006851 bool unneededUsePrimaryOutputFromPolicyMixes = false;
Eric Laurent56ed8842022-11-15 16:04:41 +01006852 std::vector<sp<SwAudioOutputDescriptor>> invalidatedOutputs;
Eric Laurentc209fe42020-06-05 18:11:23 -07006853 // take into account dynamic audio policies related changes: if a client is now associated
6854 // to a different policy mix than at creation time, invalidate corresponding stream
Eric Laurent56ed8842022-11-15 16:04:41 +01006855 for (size_t i = 0; i < mPreviousOutputs.size(); i++) {
Eric Laurentc209fe42020-06-05 18:11:23 -07006856 const sp<SwAudioOutputDescriptor>& desc = mPreviousOutputs.valueAt(i);
6857 if (desc->isDuplicated()) {
6858 continue;
Jean-Michel Trivife472e22014-12-16 14:23:13 -08006859 }
Eric Laurentc209fe42020-06-05 18:11:23 -07006860 for (const sp<TrackClientDescriptor>& client : desc->getClientIterable()) {
6861 if (mEngine->getProductStrategyForAttributes(client->attributes()) != psId) {
6862 continue;
6863 }
6864 sp<AudioPolicyMix> primaryMix;
Dean Wheatleyd082f472022-02-04 11:10:48 +11006865 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->config(),
Oscar Azucena873d10f2023-01-12 18:34:42 -08006866 client->uid(), client->session(), client->flags(), mAvailableOutputDevices,
6867 nullptr /* requestedDevice */, primaryMix, nullptr /* secondaryMixes */,
6868 unneededUsePrimaryOutputFromPolicyMixes);
Eric Laurentc209fe42020-06-05 18:11:23 -07006869 if (status != OK) {
6870 continue;
6871 }
yucliuf4de36d2020-09-14 14:57:56 -07006872 if (client->getPrimaryMix() != primaryMix || client->hasLostPrimaryMix()) {
Eric Laurent56ed8842022-11-15 16:04:41 +01006873 if (desc->isStrategyActive(psId) && maxLatency < desc->latency()) {
Eric Laurentc209fe42020-06-05 18:11:23 -07006874 maxLatency = desc->latency();
6875 }
Eric Laurent56ed8842022-11-15 16:04:41 +01006876 invalidatedOutputs.push_back(desc);
Eric Laurentc209fe42020-06-05 18:11:23 -07006877 }
Jean-Michel Trivife472e22014-12-16 14:23:13 -08006878 }
6879 }
6880
Eric Laurent56ed8842022-11-15 16:04:41 +01006881 if (srcOutputs != dstOutputs || !invalidatedOutputs.empty()) {
Eric Laurentac3a6902018-05-11 16:39:10 -07006882 // get maximum latency of all source outputs to determine the minimum mute time guaranteeing
6883 // audio from invalidated tracks will be rendered when unmuting
Eric Laurentac3a6902018-05-11 16:39:10 -07006884 for (audio_io_handle_t srcOut : srcOutputs) {
6885 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
Eric Laurentaa02db82019-09-05 17:31:49 -07006886 if (desc == nullptr) continue;
6887
6888 if (desc->isStrategyActive(psId) && maxLatency < desc->latency()) {
Eric Laurentac3a6902018-05-11 16:39:10 -07006889 maxLatency = desc->latency();
6890 }
Eric Laurentaa02db82019-09-05 17:31:49 -07006891
Eric Laurent56ed8842022-11-15 16:04:41 +01006892 bool invalidate = false;
Eric Laurentaa02db82019-09-05 17:31:49 -07006893 for (auto client : desc->clientsList(false /*activeOnly*/)) {
Eric Laurent78aade82019-09-13 18:55:08 -07006894 if (desc->isDuplicated() || !desc->mProfile->isDirectOutput()) {
Eric Laurentaa02db82019-09-05 17:31:49 -07006895 // a client on a non direct outputs has necessarily a linear PCM format
6896 // so we can call selectOutput() safely
6897 const audio_io_handle_t newOutput = selectOutput(dstOutputs,
6898 client->flags(),
6899 client->config().format,
6900 client->config().channel_mask,
jiabinebb6af42020-06-09 17:31:17 -07006901 client->config().sample_rate,
6902 client->session());
Eric Laurentaa02db82019-09-05 17:31:49 -07006903 if (newOutput != srcOut) {
6904 invalidate = true;
6905 break;
6906 }
6907 } else {
6908 sp<IOProfile> profile = getProfileForOutput(newDevices,
6909 client->config().sample_rate,
6910 client->config().format,
6911 client->config().channel_mask,
6912 client->flags(),
6913 true /* directOnly */);
6914 if (profile != desc->mProfile) {
6915 invalidate = true;
6916 break;
6917 }
6918 }
6919 }
Eric Laurent56ed8842022-11-15 16:04:41 +01006920 // mute strategy while moving tracks from one output to another
6921 if (invalidate) {
6922 invalidatedOutputs.push_back(desc);
6923 if (desc->isStrategyActive(psId)) {
6924 setStrategyMute(psId, true, desc);
6925 setStrategyMute(psId, false, desc, maxLatency * LATENCY_MUTE_FACTOR,
6926 newDevices.types());
6927 }
Eric Laurente552edb2014-03-10 17:42:56 -07006928 }
François Gaffiec005e562018-11-06 15:04:49 +01006929 sp<SourceClientDescriptor> source = getSourceForAttributesOnOutput(srcOut, attr);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02006930 if (source != nullptr && !isCallRxAudioSource(source) && !source->isInternal()) {
Eric Laurentd60560a2015-04-10 11:31:20 -07006931 connectAudioSource(source);
6932 }
Eric Laurente552edb2014-03-10 17:42:56 -07006933 }
6934
Eric Laurent56ed8842022-11-15 16:04:41 +01006935 ALOGV_IF(!(srcOutputs.isEmpty() || dstOutputs.isEmpty()),
6936 "%s: strategy %d, moving from output %s to output %s", __func__, psId,
6937 std::to_string(srcOutputs[0]).c_str(),
6938 std::to_string(dstOutputs[0]).c_str());
6939
François Gaffiec005e562018-11-06 15:04:49 +01006940 // Move effects associated to this stream from previous output to new output
6941 if (followsSameRouting(attr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07006942 selectOutputForMusicEffects();
Eric Laurente552edb2014-03-10 17:42:56 -07006943 }
François Gaffiec005e562018-11-06 15:04:49 +01006944 // Move tracks associated to this stream (and linked) from previous output to new output
Eric Laurent56ed8842022-11-15 16:04:41 +01006945 if (!invalidatedOutputs.empty()) {
jiabinc44b3462022-12-08 12:52:31 -08006946 invalidateStreams(mEngine->getStreamTypesForProductStrategy(psId));
Eric Laurent56ed8842022-11-15 16:04:41 +01006947 for (sp<SwAudioOutputDescriptor> desc : invalidatedOutputs) {
jiabin49256852022-03-09 11:21:35 -08006948 desc->setTracksInvalidatedStatusByStrategy(psId);
6949 }
Eric Laurente552edb2014-03-10 17:42:56 -07006950 }
6951 }
6952}
6953
Eric Laurente0720872014-03-11 09:30:41 -07006954void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07006955{
François Gaffiec005e562018-11-06 15:04:49 +01006956 for (const auto &strategy : mEngine->getOrderedProductStrategies()) {
6957 auto attributes = mEngine->getAllAttributesForProductStrategy(strategy).front();
6958 checkOutputForAttributes(attributes);
Francois Gaffieff1eb522020-05-06 18:37:04 +02006959 checkAudioSourceForAttributes(attributes);
François Gaffiec005e562018-11-06 15:04:49 +01006960 }
Eric Laurente552edb2014-03-10 17:42:56 -07006961}
6962
Kevin Rocard153f92d2018-12-18 18:33:28 -08006963void AudioPolicyManager::checkSecondaryOutputs() {
jiabinc44b3462022-12-08 12:52:31 -08006964 PortHandleVector clientsToInvalidate;
jiabin10a03f12021-05-07 23:46:28 +00006965 TrackSecondaryOutputsMap trackSecondaryOutputs;
Oscar Azucena873d10f2023-01-12 18:34:42 -08006966 bool unneededUsePrimaryOutputFromPolicyMixes = false;
Kevin Rocard153f92d2018-12-18 18:33:28 -08006967 for (size_t i = 0; i < mOutputs.size(); i++) {
6968 const sp<SwAudioOutputDescriptor>& outputDescriptor = mOutputs[i];
6969 for (const sp<TrackClientDescriptor>& client : outputDescriptor->getClientIterable()) {
Eric Laurentc529cf62020-04-17 18:19:10 -07006970 sp<AudioPolicyMix> primaryMix;
6971 std::vector<sp<AudioPolicyMix>> secondaryMixes;
Dean Wheatleyd082f472022-02-04 11:10:48 +11006972 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->config(),
Oscar Azucena873d10f2023-01-12 18:34:42 -08006973 client->uid(), client->session(), client->flags(), mAvailableOutputDevices,
6974 nullptr /* requestedDevice */, primaryMix, &secondaryMixes,
6975 unneededUsePrimaryOutputFromPolicyMixes);
Eric Laurentc529cf62020-04-17 18:19:10 -07006976 std::vector<sp<SwAudioOutputDescriptor>> secondaryDescs;
6977 for (auto &secondaryMix : secondaryMixes) {
6978 sp<SwAudioOutputDescriptor> outputDesc = secondaryMix->getOutput();
6979 if (outputDesc != nullptr &&
6980 outputDesc->mIoHandle != AUDIO_IO_HANDLE_NONE) {
6981 secondaryDescs.push_back(outputDesc);
6982 }
6983 }
6984
jiabinc44b3462022-12-08 12:52:31 -08006985 if (status != OK &&
6986 (client->flags() & AUDIO_OUTPUT_FLAG_MMAP_NOIRQ) == AUDIO_OUTPUT_FLAG_NONE) {
6987 // When it failed to query secondary output, only invalidate the client that is not
6988 // MMAP. The reason is that MMAP stream will not support secondary output.
6989 clientsToInvalidate.push_back(client->portId());
jiabin10a03f12021-05-07 23:46:28 +00006990 } else if (!std::equal(
6991 client->getSecondaryOutputs().begin(),
6992 client->getSecondaryOutputs().end(),
6993 secondaryDescs.begin(), secondaryDescs.end())) {
jiabina5281062021-11-23 00:10:23 +00006994 if (!audio_is_linear_pcm(client->config().format)) {
6995 // If the format is not PCM, the tracks should be invalidated to get correct
6996 // behavior when the secondary output is changed.
jiabinc44b3462022-12-08 12:52:31 -08006997 clientsToInvalidate.push_back(client->portId());
jiabina5281062021-11-23 00:10:23 +00006998 } else {
6999 std::vector<wp<SwAudioOutputDescriptor>> weakSecondaryDescs;
7000 std::vector<audio_io_handle_t> secondaryOutputIds;
7001 for (const auto &secondaryDesc: secondaryDescs) {
7002 secondaryOutputIds.push_back(secondaryDesc->mIoHandle);
7003 weakSecondaryDescs.push_back(secondaryDesc);
7004 }
7005 trackSecondaryOutputs.emplace(client->portId(), secondaryOutputIds);
7006 client->setSecondaryOutputs(std::move(weakSecondaryDescs));
jiabin10a03f12021-05-07 23:46:28 +00007007 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08007008 }
7009 }
7010 }
jiabin10a03f12021-05-07 23:46:28 +00007011 if (!trackSecondaryOutputs.empty()) {
7012 mpClientInterface->updateSecondaryOutputs(trackSecondaryOutputs);
7013 }
jiabinc44b3462022-12-08 12:52:31 -08007014 if (!clientsToInvalidate.empty()) {
7015 ALOGD("%s Invalidate clients due to fail getting output for attr", __func__);
7016 mpClientInterface->invalidateTracks(clientsToInvalidate);
Kevin Rocard153f92d2018-12-18 18:33:28 -08007017 }
7018}
7019
Eric Laurent2517af32020-11-25 15:31:27 +01007020bool AudioPolicyManager::isScoRequestedForComm() const {
7021 AudioDeviceTypeAddrVector devices;
7022 mEngine->getDevicesForRoleAndStrategy(mCommunnicationStrategy, DEVICE_ROLE_PREFERRED, devices);
7023 for (const auto &device : devices) {
7024 if (audio_is_bluetooth_out_sco_device(device.mType)) {
7025 return true;
7026 }
7027 }
7028 return false;
7029}
7030
Eric Laurent1a8b45f2022-04-13 16:01:47 +02007031bool AudioPolicyManager::isHearingAidUsedForComm() const {
7032 DeviceVector devices = mEngine->getOutputDevicesForStream(AUDIO_STREAM_VOICE_CALL,
7033 true /*fromCache*/);
7034 for (const auto &device : devices) {
7035 if (device->type() == AUDIO_DEVICE_OUT_HEARING_AID) {
7036 return true;
7037 }
7038 }
7039 return false;
7040}
7041
7042
Eric Laurente0720872014-03-11 09:30:41 -07007043void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07007044{
François Gaffie53615e22015-03-19 09:24:12 +01007045 audio_io_handle_t a2dpOutput = mOutputs.getA2dpOutput();
Aniket Kumar Lataa8ee9962018-01-31 20:24:23 -08007046 if (a2dpOutput == 0 || mOutputs.isA2dpOffloadedOnPrimary()) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07007047 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07007048 return;
7049 }
7050
Eric Laurent3a4311c2014-03-17 12:00:47 -07007051 bool isScoConnected =
jiabin9a3361e2019-10-01 09:38:30 -07007052 (mAvailableInputDevices.types().count(AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) != 0 ||
7053 !Intersection(mAvailableOutputDevices.types(), getAudioDeviceOutAllScoSet()).empty());
Eric Laurent2517af32020-11-25 15:31:27 +01007054 bool isScoRequested = isScoRequestedForComm();
Eric Laurentf732e072016-08-03 19:30:28 -07007055
7056 // if suspended, restore A2DP output if:
7057 // ((SCO device is NOT connected) ||
Eric Laurent2517af32020-11-25 15:31:27 +01007058 // ((SCO is not requested) &&
Eric Laurentf732e072016-08-03 19:30:28 -07007059 // (phone state is NOT in call) && (phone state is NOT ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07007060 //
Eric Laurentf732e072016-08-03 19:30:28 -07007061 // if not suspended, suspend A2DP output if:
7062 // (SCO device is connected) &&
Eric Laurent2517af32020-11-25 15:31:27 +01007063 // ((SCO is requested) ||
Eric Laurentf732e072016-08-03 19:30:28 -07007064 // ((phone state is in call) || (phone state is ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07007065 //
7066 if (mA2dpSuspended) {
Eric Laurentf732e072016-08-03 19:30:28 -07007067 if (!isScoConnected ||
Eric Laurent2517af32020-11-25 15:31:27 +01007068 (!isScoRequested &&
Eric Laurentf732e072016-08-03 19:30:28 -07007069 (mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) &&
François Gaffie2110e042015-03-24 08:41:51 +01007070 (mEngine->getPhoneState() != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07007071
7072 mpClientInterface->restoreOutput(a2dpOutput);
7073 mA2dpSuspended = false;
7074 }
7075 } else {
Eric Laurentf732e072016-08-03 19:30:28 -07007076 if (isScoConnected &&
Eric Laurent2517af32020-11-25 15:31:27 +01007077 (isScoRequested ||
Eric Laurentf732e072016-08-03 19:30:28 -07007078 (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) ||
François Gaffie2110e042015-03-24 08:41:51 +01007079 (mEngine->getPhoneState() == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07007080
7081 mpClientInterface->suspendOutput(a2dpOutput);
7082 mA2dpSuspended = true;
7083 }
7084 }
7085}
7086
François Gaffie11d30102018-11-02 16:09:09 +01007087DeviceVector AudioPolicyManager::getNewOutputDevices(const sp<SwAudioOutputDescriptor>& outputDesc,
7088 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07007089{
François Gaffie11d30102018-11-02 16:09:09 +01007090 DeviceVector devices;
7091
Jean-Michel Triviff155c62016-02-26 12:07:16 -08007092 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007093 if (index >= 0) {
7094 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007095 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01007096 ALOGV("%s device %s forced by patch %d", __func__,
7097 outputDesc->devices().toString().c_str(), outputDesc->getPatchHandle());
7098 return outputDesc->devices();
Eric Laurent6a94d692014-05-20 11:18:06 -07007099 }
7100 }
7101
Dean Wheatley514b4312020-06-17 21:45:00 +10007102 // Do not retrieve engine device for outputs through MSD
7103 // TODO: support explicit routing requests by resetting MSD patch to engine device.
7104 if (outputDesc->devices() == getMsdAudioOutDevices()) {
7105 return outputDesc->devices();
7106 }
7107
Eric Laurent97ac8712018-07-27 18:59:02 -07007108 // Honor explicit routing requests only if no client using default routing is active on this
7109 // input: a specific app can not force routing for other apps by setting a preferred device.
7110 bool active; // unused
François Gaffie11d30102018-11-02 16:09:09 +01007111 sp<DeviceDescriptor> device =
François Gaffiec005e562018-11-06 15:04:49 +01007112 findPreferredDevice(outputDesc, PRODUCT_STRATEGY_NONE, active, mAvailableOutputDevices);
François Gaffie11d30102018-11-02 16:09:09 +01007113 if (device != nullptr) {
7114 return DeviceVector(device);
Eric Laurentf3a5a602018-05-22 18:42:55 -07007115 }
7116
François Gaffiea807ef92018-11-05 10:44:33 +01007117 // Legacy Engine cannot take care of bus devices and mix, so we need to handle the conflict
7118 // of setForceUse / Default Bus device here
7119 device = mPolicyMixes.getDeviceAndMixForOutput(outputDesc, mAvailableOutputDevices);
7120 if (device != nullptr) {
7121 return DeviceVector(device);
7122 }
7123
François Gaffiec005e562018-11-06 15:04:49 +01007124 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
7125 StreamTypeVector streams = mEngine->getStreamTypesForProductStrategy(productStrategy);
7126 auto attr = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307127 auto hasStreamActive = [&](auto stream) {
7128 return hasStream(streams, stream) && isStreamActive(stream, 0);
7129 };
Eric Laurent484e9272018-06-07 17:29:23 -07007130
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307131 auto doGetOutputDevicesForVoice = [&]() {
7132 return hasVoiceStream(streams) && (outputDesc == mPrimaryOutput ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007133 outputDesc->isActive(toVolumeSource(AUDIO_STREAM_VOICE_CALL, false))) &&
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307134 (isInCall() ||
Henrik Backlund07c654a2021-10-14 15:57:10 +02007135 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc)) &&
7136 !isStreamActive(AUDIO_STREAM_ENFORCED_AUDIBLE, 0);
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307137 };
7138
7139 // With low-latency playing on speaker, music on WFD, when the first low-latency
7140 // output is stopped, getNewOutputDevices checks for a product strategy
7141 // from the list, as STRATEGY_SONIFICATION comes prior to STRATEGY_MEDIA.
Carter Hsucc58a6b2021-07-20 08:44:50 +00007142 // If an ALARM or ENFORCED_AUDIBLE stream is supported by the product strategy,
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307143 // devices are returned for STRATEGY_SONIFICATION without checking whether the
7144 // stream is associated to the output descriptor.
7145 if (doGetOutputDevicesForVoice() || outputDesc->isStrategyActive(productStrategy) ||
7146 ((hasStreamActive(AUDIO_STREAM_ALARM) ||
7147 hasStreamActive(AUDIO_STREAM_ENFORCED_AUDIBLE)) &&
7148 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc))) {
François Gaffiec005e562018-11-06 15:04:49 +01007149 // Retrieval of devices for voice DL is done on primary output profile, cannot
7150 // check the route (would force modifying configuration file for this profile)
7151 devices = mEngine->getOutputDevicesForAttributes(attr, nullptr, fromCache);
7152 break;
7153 }
Eric Laurente552edb2014-03-10 17:42:56 -07007154 }
François Gaffiec005e562018-11-06 15:04:49 +01007155 ALOGV("%s selected devices %s", __func__, devices.toString().c_str());
François Gaffie11d30102018-11-02 16:09:09 +01007156 return devices;
Eric Laurent1c333e22014-05-20 10:48:17 -07007157}
7158
François Gaffie11d30102018-11-02 16:09:09 +01007159sp<DeviceDescriptor> AudioPolicyManager::getNewInputDevice(
7160 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurent1c333e22014-05-20 10:48:17 -07007161{
François Gaffie11d30102018-11-02 16:09:09 +01007162 sp<DeviceDescriptor> device;
Eric Laurent6a94d692014-05-20 11:18:06 -07007163
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08007164 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007165 if (index >= 0) {
7166 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007167 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01007168 ALOGV("getNewInputDevice() device %s forced by patch %d",
7169 inputDesc->getDevice()->toString().c_str(), inputDesc->getPatchHandle());
7170 return inputDesc->getDevice();
Eric Laurent6a94d692014-05-20 11:18:06 -07007171 }
7172 }
7173
Eric Laurent97ac8712018-07-27 18:59:02 -07007174 // Honor explicit routing requests only if no client using default routing is active on this
7175 // input: a specific app can not force routing for other apps by setting a preferred device.
7176 bool active;
François Gaffie11d30102018-11-02 16:09:09 +01007177 device = findPreferredDevice(inputDesc, AUDIO_SOURCE_DEFAULT, active, mAvailableInputDevices);
7178 if (device != nullptr) {
7179 return device;
Eric Laurent97ac8712018-07-27 18:59:02 -07007180 }
7181
Eric Laurentdc95a252018-04-12 12:46:56 -07007182 // If we are not in call and no client is active on this input, this methods returns
Andy Hungf024a9e2019-01-30 16:01:02 -08007183 // a null sp<>, causing the patch on the input stream to be released.
yuanjiahsu0735bf32021-03-18 08:12:54 +08007184 audio_attributes_t attributes;
7185 uid_t uid;
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007186 audio_session_t session;
yuanjiahsu0735bf32021-03-18 08:12:54 +08007187 sp<RecordClientDescriptor> topClient = inputDesc->getHighestPriorityClient();
7188 if (topClient != nullptr) {
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01007189 attributes = topClient->attributes();
7190 uid = topClient->uid();
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007191 session = topClient->session();
yuanjiahsu0735bf32021-03-18 08:12:54 +08007192 } else {
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01007193 attributes = { .source = AUDIO_SOURCE_DEFAULT };
7194 uid = 0;
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007195 session = AUDIO_SESSION_NONE;
yuanjiahsu0735bf32021-03-18 08:12:54 +08007196 }
7197
Francois Gaffie716e1432019-01-14 16:58:59 +01007198 if (attributes.source == AUDIO_SOURCE_DEFAULT && isInCall()) {
7199 attributes.source = AUDIO_SOURCE_VOICE_COMMUNICATION;
Eric Laurentdc95a252018-04-12 12:46:56 -07007200 }
Francois Gaffie716e1432019-01-14 16:58:59 +01007201 if (attributes.source != AUDIO_SOURCE_DEFAULT) {
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007202 device = mEngine->getInputDeviceForAttributes(attributes, uid, session);
Eric Laurentfb66dd92016-01-28 18:32:03 -08007203 }
Eric Laurent1c333e22014-05-20 10:48:17 -07007204
Eric Laurente552edb2014-03-10 17:42:56 -07007205 return device;
7206}
7207
Eric Laurent794fde22016-03-11 09:50:45 -08007208bool AudioPolicyManager::streamsMatchForvolume(audio_stream_type_t stream1,
7209 audio_stream_type_t stream2) {
Jean-Michel Trivi99bb2f92016-11-23 15:52:07 -08007210 return (stream1 == stream2);
Eric Laurent28d09f02016-03-08 10:43:05 -08007211}
7212
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08007213status_t AudioPolicyManager::getDevicesForAttributes(
Andy Hung6d23c0f2022-02-16 09:37:15 -08007214 const audio_attributes_t &attr, AudioDeviceTypeAddrVector *devices, bool forVolume) {
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08007215 if (devices == nullptr) {
7216 return BAD_VALUE;
7217 }
Andy Hung6d23c0f2022-02-16 09:37:15 -08007218
Andy Hung6d23c0f2022-02-16 09:37:15 -08007219 DeviceVector curDevices;
jiabinf1c73972022-04-14 16:28:52 -07007220 if (status_t status = getDevicesForAttributes(attr, curDevices, forVolume); status != OK) {
7221 return status;
Andy Hung6d23c0f2022-02-16 09:37:15 -08007222 }
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08007223 for (const auto& device : curDevices) {
7224 devices->push_back(device->getDeviceTypeAddr());
7225 }
7226 return NO_ERROR;
7227}
7228
Eric Laurente0720872014-03-11 09:30:41 -07007229void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07007230 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07007231 case AUDIO_STREAM_MUSIC:
François Gaffiec005e562018-11-06 15:04:49 +01007232 checkOutputForAttributes(attributes_initializer(AUDIO_USAGE_NOTIFICATION));
Eric Laurente552edb2014-03-10 17:42:56 -07007233 updateDevicesAndOutputs();
7234 break;
7235 default:
7236 break;
7237 }
7238}
7239
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007240uint32_t AudioPolicyManager::handleEventForBeacon(int event) {
Eric Laurent9459fb02015-08-12 18:36:32 -07007241
7242 // skip beacon mute management if a dedicated TTS output is available
7243 if (mTtsOutputAvailable) {
7244 return 0;
7245 }
7246
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007247 switch(event) {
7248 case STARTING_OUTPUT:
7249 mBeaconMuteRefCount++;
7250 break;
7251 case STOPPING_OUTPUT:
7252 if (mBeaconMuteRefCount > 0) {
7253 mBeaconMuteRefCount--;
7254 }
7255 break;
7256 case STARTING_BEACON:
7257 mBeaconPlayingRefCount++;
7258 break;
7259 case STOPPING_BEACON:
7260 if (mBeaconPlayingRefCount > 0) {
7261 mBeaconPlayingRefCount--;
7262 }
7263 break;
7264 }
7265
7266 if (mBeaconMuteRefCount > 0) {
7267 // any playback causes beacon to be muted
7268 return setBeaconMute(true);
7269 } else {
7270 // no other playback: unmute when beacon starts playing, mute when it stops
7271 return setBeaconMute(mBeaconPlayingRefCount == 0);
7272 }
7273}
7274
7275uint32_t AudioPolicyManager::setBeaconMute(bool mute) {
7276 ALOGV("setBeaconMute(%d) mBeaconMuteRefCount=%d mBeaconPlayingRefCount=%d",
7277 mute, mBeaconMuteRefCount, mBeaconPlayingRefCount);
7278 // keep track of muted state to avoid repeating mute/unmute operations
7279 if (mBeaconMuted != mute) {
7280 // mute/unmute AUDIO_STREAM_TTS on all outputs
7281 ALOGV("\t muting %d", mute);
7282 uint32_t maxLatency = 0;
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007283 auto ttsVolumeSource = toVolumeSource(AUDIO_STREAM_TTS, false);
7284 if (ttsVolumeSource == VOLUME_SOURCE_NONE) {
7285 ALOGV("\t no tts volume source available");
7286 return 0;
7287 }
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007288 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07007289 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
jiabin9a3361e2019-10-01 09:38:30 -07007290 setVolumeSourceMute(ttsVolumeSource, mute/*on*/, desc, 0 /*delay*/, DeviceTypeSet());
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007291 const uint32_t latency = desc->latency() * 2;
Eric Laurentcdb2b352020-07-23 10:57:02 -07007292 if (desc->isActive(latency * 2) && latency > maxLatency) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007293 maxLatency = latency;
7294 }
7295 }
7296 mBeaconMuted = mute;
7297 return maxLatency;
7298 }
7299 return 0;
7300}
7301
Eric Laurente0720872014-03-11 09:30:41 -07007302void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07007303{
François Gaffiec005e562018-11-06 15:04:49 +01007304 mEngine->updateDeviceSelectionCache();
Eric Laurente552edb2014-03-10 17:42:56 -07007305 mPreviousOutputs = mOutputs;
7306}
7307
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07007308uint32_t AudioPolicyManager::checkDeviceMuteStrategies(const sp<AudioOutputDescriptor>& outputDesc,
François Gaffiec005e562018-11-06 15:04:49 +01007309 const DeviceVector &prevDevices,
Eric Laurente552edb2014-03-10 17:42:56 -07007310 uint32_t delayMs)
7311{
7312 // mute/unmute strategies using an incompatible device combination
7313 // if muting, wait for the audio in pcm buffer to be drained before proceeding
7314 // if unmuting, unmute only after the specified delay
7315 if (outputDesc->isDuplicated()) {
7316 return 0;
7317 }
7318
7319 uint32_t muteWaitMs = 0;
François Gaffiec005e562018-11-06 15:04:49 +01007320 DeviceVector devices = outputDesc->devices();
7321 bool shouldMute = outputDesc->isActive() && (devices.size() >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07007322
François Gaffiec005e562018-11-06 15:04:49 +01007323 auto productStrategies = mEngine->getOrderedProductStrategies();
7324 for (const auto &productStrategy : productStrategies) {
7325 auto attributes = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
7326 DeviceVector curDevices =
7327 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false/*fromCache*/);
7328 curDevices = curDevices.filter(outputDesc->supportedDevices());
7329 bool mute = shouldMute && curDevices.containsAtLeastOne(devices) && curDevices != devices;
Eric Laurente552edb2014-03-10 17:42:56 -07007330 bool doMute = false;
7331
François Gaffiec005e562018-11-06 15:04:49 +01007332 if (mute && !outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07007333 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01007334 outputDesc->setStrategyMutedByDevice(productStrategy, true);
7335 } else if (!mute && outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07007336 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01007337 outputDesc->setStrategyMutedByDevice(productStrategy, false);
Eric Laurente552edb2014-03-10 17:42:56 -07007338 }
Eric Laurent99401132014-05-07 19:48:15 -07007339 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07007340 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07007341 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07007342 // skip output if it does not share any device with current output
François Gaffie11d30102018-11-02 16:09:09 +01007343 if (!desc->supportedDevices().containsAtLeastOne(outputDesc->supportedDevices())) {
Eric Laurente552edb2014-03-10 17:42:56 -07007344 continue;
7345 }
François Gaffiec005e562018-11-06 15:04:49 +01007346 ALOGVV("%s() %s (curDevice %s)", __func__,
7347 mute ? "muting" : "unmuting", curDevices.toString().c_str());
7348 setStrategyMute(productStrategy, mute, desc, mute ? 0 : delayMs);
7349 if (desc->isStrategyActive(productStrategy)) {
Eric Laurent99401132014-05-07 19:48:15 -07007350 if (mute) {
7351 // FIXME: should not need to double latency if volume could be applied
7352 // immediately by the audioflinger mixer. We must account for the delay
7353 // between now and the next time the audioflinger thread for this output
7354 // will process a buffer (which corresponds to one buffer size,
7355 // usually 1/2 or 1/4 of the latency).
7356 if (muteWaitMs < desc->latency() * 2) {
7357 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07007358 }
7359 }
7360 }
7361 }
7362 }
7363 }
7364
Eric Laurent99401132014-05-07 19:48:15 -07007365 // temporary mute output if device selection changes to avoid volume bursts due to
7366 // different per device volumes
François Gaffiec005e562018-11-06 15:04:49 +01007367 if (outputDesc->isActive() && (devices != prevDevices)) {
Eric Laurentdc462862016-07-19 12:29:53 -07007368 uint32_t tempMuteWaitMs = outputDesc->latency() * 2;
Jasmine Chaf6074fe2021-08-17 13:44:31 +08007369
Eric Laurentdc462862016-07-19 12:29:53 -07007370 if (muteWaitMs < tempMuteWaitMs) {
7371 muteWaitMs = tempMuteWaitMs;
Eric Laurent99401132014-05-07 19:48:15 -07007372 }
Jasmine Chaf6074fe2021-08-17 13:44:31 +08007373
7374 // If recommended duration is defined, replace temporary mute duration to avoid
7375 // truncated notifications at beginning, which depends on duration of changing path in HAL.
7376 // Otherwise, temporary mute duration is conservatively set to 4 times the reported latency.
7377 uint32_t tempRecommendedMuteDuration = outputDesc->getRecommendedMuteDurationMs();
7378 uint32_t tempMuteDurationMs = tempRecommendedMuteDuration > 0 ?
7379 tempRecommendedMuteDuration : outputDesc->latency() * 4;
7380
François Gaffieaaac0fd2018-11-22 17:56:39 +01007381 for (const auto &activeVs : outputDesc->getActiveVolumeSources()) {
7382 // make sure that we do not start the temporary mute period too early in case of
7383 // delayed device change
7384 setVolumeSourceMute(activeVs, true, outputDesc, delayMs);
7385 setVolumeSourceMute(activeVs, false, outputDesc, delayMs + tempMuteDurationMs,
François Gaffiec005e562018-11-06 15:04:49 +01007386 devices.types());
Eric Laurent99401132014-05-07 19:48:15 -07007387 }
7388 }
7389
Eric Laurente552edb2014-03-10 17:42:56 -07007390 // wait for the PCM output buffers to empty before proceeding with the rest of the command
7391 if (muteWaitMs > delayMs) {
7392 muteWaitMs -= delayMs;
7393 usleep(muteWaitMs * 1000);
7394 return muteWaitMs;
7395 }
7396 return 0;
7397}
7398
François Gaffie11d30102018-11-02 16:09:09 +01007399uint32_t AudioPolicyManager::setOutputDevices(const sp<SwAudioOutputDescriptor>& outputDesc,
7400 const DeviceVector &devices,
7401 bool force,
7402 int delayMs,
7403 audio_patch_handle_t *patchHandle,
Oscar Azucena6acf34b2023-04-27 16:32:09 -07007404 bool requiresMuteCheck, bool requiresVolumeCheck,
7405 bool skipMuteDelay)
Eric Laurente552edb2014-03-10 17:42:56 -07007406{
jiabin3ff8d7d2022-12-13 06:27:44 +00007407 // TODO(b/262404095): Consider if the output need to be reopened.
François Gaffie11d30102018-11-02 16:09:09 +01007408 ALOGV("%s device %s delayMs %d", __func__, devices.toString().c_str(), delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07007409 uint32_t muteWaitMs;
7410
7411 if (outputDesc->isDuplicated()) {
François Gaffie11d30102018-11-02 16:09:09 +01007412 muteWaitMs = setOutputDevices(outputDesc->subOutput1(), devices, force, delayMs,
Oscar Azucena6acf34b2023-04-27 16:32:09 -07007413 nullptr /* patchHandle */, requiresMuteCheck, skipMuteDelay);
François Gaffie11d30102018-11-02 16:09:09 +01007414 muteWaitMs += setOutputDevices(outputDesc->subOutput2(), devices, force, delayMs,
Oscar Azucena6acf34b2023-04-27 16:32:09 -07007415 nullptr /* patchHandle */, requiresMuteCheck, skipMuteDelay);
Eric Laurente552edb2014-03-10 17:42:56 -07007416 return muteWaitMs;
7417 }
Eric Laurente552edb2014-03-10 17:42:56 -07007418
7419 // filter devices according to output selected
Francois Gaffie716e1432019-01-14 16:58:59 +01007420 DeviceVector filteredDevices = outputDesc->filterSupportedDevices(devices);
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01007421 DeviceVector prevDevices = outputDesc->devices();
Francois Gaffie3523ab32021-06-22 13:24:34 +02007422 DeviceVector availPrevDevices = mAvailableOutputDevices.filter(prevDevices);
Eric Laurente552edb2014-03-10 17:42:56 -07007423
François Gaffie11d30102018-11-02 16:09:09 +01007424 ALOGV("setOutputDevices() prevDevice %s", prevDevices.toString().c_str());
7425
7426 if (!filteredDevices.isEmpty()) {
7427 outputDesc->setDevices(filteredDevices);
Eric Laurente552edb2014-03-10 17:42:56 -07007428 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00007429
7430 // if the outputs are not materially active, there is no need to mute.
7431 if (requiresMuteCheck) {
François Gaffiec005e562018-11-06 15:04:49 +01007432 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevices, delayMs);
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00007433 } else {
7434 ALOGV("%s: suppressing checkDeviceMuteStrategies", __func__);
7435 muteWaitMs = 0;
7436 }
Eric Laurente552edb2014-03-10 17:42:56 -07007437
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02007438 bool outputRouted = outputDesc->isRouted();
7439
Eric Laurent79ea9582020-06-11 18:49:24 -07007440 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
7441 // output profile or if new device is not supported AND previous device(s) is(are) still
7442 // available (otherwise reset device must be done on the output)
Francois Gaffie3523ab32021-06-22 13:24:34 +02007443 if (!devices.isEmpty() && filteredDevices.isEmpty() && !availPrevDevices.empty()) {
Eric Laurent79ea9582020-06-11 18:49:24 -07007444 ALOGV("%s: unsupported device %s for output", __func__, devices.toString().c_str());
7445 // restore previous device after evaluating strategy mute state
7446 outputDesc->setDevices(prevDevices);
7447 return muteWaitMs;
7448 }
7449
Eric Laurente552edb2014-03-10 17:42:56 -07007450 // Do not change the routing if:
Eric Laurentb80a2a82014-10-27 16:07:59 -07007451 // the requested device is AUDIO_DEVICE_NONE
7452 // OR the requested device is the same as current device
7453 // AND force is not specified
7454 // AND the output is connected by a valid audio patch.
François Gaffie11d30102018-11-02 16:09:09 +01007455 // Doing this check here allows the caller to call setOutputDevices() without conditions
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02007456 if ((filteredDevices.isEmpty() || filteredDevices == prevDevices) && !force && outputRouted) {
François Gaffie11d30102018-11-02 16:09:09 +01007457 ALOGV("%s setting same device %s or null device, force=%d, patch handle=%d", __func__,
7458 filteredDevices.toString().c_str(), force, outputDesc->getPatchHandle());
Francois Gaffie3523ab32021-06-22 13:24:34 +02007459 if (requiresVolumeCheck && !filteredDevices.isEmpty()) {
7460 ALOGV("%s setting same device on routed output, force apply volumes", __func__);
7461 applyStreamVolumes(outputDesc, filteredDevices.types(), delayMs, true /*force*/);
7462 }
Eric Laurente552edb2014-03-10 17:42:56 -07007463 return muteWaitMs;
7464 }
7465
François Gaffie11d30102018-11-02 16:09:09 +01007466 ALOGV("%s changing device to %s", __func__, filteredDevices.toString().c_str());
Eric Laurent1c333e22014-05-20 10:48:17 -07007467
Eric Laurente552edb2014-03-10 17:42:56 -07007468 // do the routing
Francois Gaffie3523ab32021-06-22 13:24:34 +02007469 if (filteredDevices.isEmpty() || mAvailableOutputDevices.filter(filteredDevices).empty()) {
Eric Laurentc75307b2015-03-17 15:29:32 -07007470 resetOutputDevice(outputDesc, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07007471 } else {
François Gaffie11d30102018-11-02 16:09:09 +01007472 PatchBuilder patchBuilder;
7473 patchBuilder.addSource(outputDesc);
7474 ALOG_ASSERT(filteredDevices.size() <= AUDIO_PATCH_PORTS_MAX, "Too many sink ports");
7475 for (const auto &filteredDevice : filteredDevices) {
7476 patchBuilder.addSink(filteredDevice);
Eric Laurentc40d9692016-04-13 19:14:13 -07007477 }
7478
Jasmine Cha7f82d1a2020-03-16 13:21:47 +08007479 // Add half reported latency to delayMs when muteWaitMs is null in order
7480 // to avoid disordered sequence of muting volume and changing devices.
Oscar Azucena6acf34b2023-04-27 16:32:09 -07007481 int actualDelayMs = !skipMuteDelay && muteWaitMs == 0
7482 ? (delayMs + (outputDesc->latency() / 2)) : delayMs;
7483 installPatch(__func__, patchHandle, outputDesc.get(), patchBuilder.patch(), actualDelayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07007484 }
Eric Laurente552edb2014-03-10 17:42:56 -07007485
Oscar Azucena6acf34b2023-04-27 16:32:09 -07007486 // Since the mute is skip, also skip the apply stream volume as that will be applied externally
7487 if (!skipMuteDelay) {
7488 // update stream volumes according to new device
7489 applyStreamVolumes(outputDesc, filteredDevices.types(), delayMs);
7490 }
Eric Laurente552edb2014-03-10 17:42:56 -07007491
7492 return muteWaitMs;
7493}
7494
Eric Laurentc75307b2015-03-17 15:29:32 -07007495status_t AudioPolicyManager::resetOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurent6a94d692014-05-20 11:18:06 -07007496 int delayMs,
7497 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07007498{
Eric Laurent6a94d692014-05-20 11:18:06 -07007499 ssize_t index;
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02007500 if (patchHandle == nullptr && !outputDesc->isRouted()) {
7501 return INVALID_OPERATION;
7502 }
Eric Laurent6a94d692014-05-20 11:18:06 -07007503 if (patchHandle) {
7504 index = mAudioPatches.indexOfKey(*patchHandle);
7505 } else {
Jean-Michel Triviff155c62016-02-26 12:07:16 -08007506 index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007507 }
7508 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07007509 return INVALID_OPERATION;
7510 }
Eric Laurent6a94d692014-05-20 11:18:06 -07007511 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007512 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07007513 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07007514 outputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
François Gaffieafd4cea2019-11-18 15:50:22 +01007515 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007516 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07007517 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07007518 return status;
7519}
7520
7521status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
François Gaffie11d30102018-11-02 16:09:09 +01007522 const sp<DeviceDescriptor> &device,
Eric Laurent6a94d692014-05-20 11:18:06 -07007523 bool force,
7524 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07007525{
7526 status_t status = NO_ERROR;
7527
Eric Laurent1f2f2232014-06-02 12:01:23 -07007528 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
François Gaffie11d30102018-11-02 16:09:09 +01007529 if ((device != nullptr) && ((device != inputDesc->getDevice()) || force)) {
7530 inputDesc->setDevice(device);
Eric Laurent1c333e22014-05-20 10:48:17 -07007531
François Gaffie11d30102018-11-02 16:09:09 +01007532 if (mAvailableInputDevices.contains(device)) {
Mikhail Naganovdc769682018-05-04 15:34:08 -07007533 PatchBuilder patchBuilder;
7534 patchBuilder.addSink(inputDesc,
Eric Laurentdaf92cc2014-07-22 15:36:10 -07007535 // AUDIO_SOURCE_HOTWORD is for internal use only:
7536 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
Mikhail Naganovdc769682018-05-04 15:34:08 -07007537 [inputDesc](const PatchBuilder::mix_usecase_t& usecase) {
7538 auto result = usecase;
7539 if (result.source == AUDIO_SOURCE_HOTWORD && !inputDesc->isSoundTrigger()) {
7540 result.source = AUDIO_SOURCE_VOICE_RECOGNITION;
7541 }
7542 return result; }).
Eric Laurent1c333e22014-05-20 10:48:17 -07007543 //only one input device for now
François Gaffie11d30102018-11-02 16:09:09 +01007544 addSource(device);
Mikhail Naganovdc769682018-05-04 15:34:08 -07007545 status = installPatch(__func__, patchHandle, inputDesc.get(), patchBuilder.patch(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07007546 }
7547 }
7548 return status;
7549}
7550
Eric Laurent6a94d692014-05-20 11:18:06 -07007551status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
7552 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07007553{
Eric Laurent1f2f2232014-06-02 12:01:23 -07007554 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07007555 ssize_t index;
7556 if (patchHandle) {
7557 index = mAudioPatches.indexOfKey(*patchHandle);
7558 } else {
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08007559 index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007560 }
7561 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07007562 return INVALID_OPERATION;
7563 }
Eric Laurent6a94d692014-05-20 11:18:06 -07007564 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007565 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07007566 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07007567 inputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
François Gaffieafd4cea2019-11-18 15:50:22 +01007568 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007569 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07007570 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07007571 return status;
7572}
7573
François Gaffie11d30102018-11-02 16:09:09 +01007574sp<IOProfile> AudioPolicyManager::getInputProfile(const sp<DeviceDescriptor> &device,
François Gaffie53615e22015-03-19 09:24:12 +01007575 uint32_t& samplingRate,
Andy Hungf129b032015-04-07 13:45:50 -07007576 audio_format_t& format,
7577 audio_channel_mask_t& channelMask,
François Gaffie53615e22015-03-19 09:24:12 +01007578 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07007579{
7580 // Choose an input profile based on the requested capture parameters: select the first available
7581 // profile supporting all requested parameters.
jiabin2fd710d2022-05-02 23:20:22 +00007582 // The flags can be ignored if it doesn't contain a much match flag.
Andy Hungf129b032015-04-07 13:45:50 -07007583 //
7584 // TODO: perhaps isCompatibleProfile should return a "matching" score so we can return
7585 // the best matching profile, not the first one.
Eric Laurente552edb2014-03-10 17:42:56 -07007586
Atneya Nair0f0a8032022-12-12 16:20:12 -08007587 using underlying_input_flag_t = std::underlying_type_t<audio_input_flags_t>;
7588 const underlying_input_flag_t mustMatchFlag = AUDIO_INPUT_FLAG_MMAP_NOIRQ |
7589 AUDIO_INPUT_FLAG_HOTWORD_TAP | AUDIO_INPUT_FLAG_HW_LOOKBACK;
7590
7591 const underlying_input_flag_t oriFlags = flags;
Glenn Kasten730b9262018-03-29 15:01:26 -07007592
jiabin2fd710d2022-05-02 23:20:22 +00007593 for (;;) {
7594 sp<IOProfile> firstInexact = nullptr;
7595 uint32_t updatedSamplingRate = 0;
7596 audio_format_t updatedFormat = AUDIO_FORMAT_INVALID;
7597 audio_channel_mask_t updatedChannelMask = AUDIO_CHANNEL_INVALID;
7598 for (const auto& hwModule : mHwModules) {
7599 for (const auto& profile : hwModule->getInputProfiles()) {
7600 // profile->log();
7601 //updatedFormat = format;
7602 if (profile->isCompatibleProfile(DeviceVector(device), samplingRate,
7603 &samplingRate /*updatedSamplingRate*/,
7604 format,
7605 &format, /*updatedFormat*/
7606 channelMask,
7607 &channelMask /*updatedChannelMask*/,
7608 // FIXME ugly cast
7609 (audio_output_flags_t) flags,
7610 true /*exactMatchRequiredForInputFlags*/)) {
7611 return profile;
7612 }
7613 if (firstInexact == nullptr && profile->isCompatibleProfile(DeviceVector(device),
7614 samplingRate,
7615 &updatedSamplingRate,
7616 format,
7617 &updatedFormat,
7618 channelMask,
7619 &updatedChannelMask,
7620 // FIXME ugly cast
7621 (audio_output_flags_t) flags,
7622 false /*exactMatchRequiredForInputFlags*/)) {
7623 firstInexact = profile;
7624 }
7625 }
7626 }
7627
7628 if (firstInexact != nullptr) {
7629 samplingRate = updatedSamplingRate;
7630 format = updatedFormat;
7631 channelMask = updatedChannelMask;
7632 return firstInexact;
7633 } else if (flags & AUDIO_INPUT_FLAG_RAW) {
7634 flags = (audio_input_flags_t) (flags & ~AUDIO_INPUT_FLAG_RAW); // retry
7635 } else if ((flags & mustMatchFlag) == AUDIO_INPUT_FLAG_NONE &&
7636 flags != AUDIO_INPUT_FLAG_NONE && audio_is_linear_pcm(format)) {
7637 flags = AUDIO_INPUT_FLAG_NONE;
7638 } else { // fail
7639 ALOGW("%s could not find profile for device %s, sampling rate %u, format %#x, "
7640 "channel mask 0x%X, flags %#x", __func__, device->toString().c_str(),
7641 samplingRate, format, channelMask, oriFlags);
7642 break;
Eric Laurente552edb2014-03-10 17:42:56 -07007643 }
7644 }
jiabin2fd710d2022-05-02 23:20:22 +00007645
7646 return nullptr;
Eric Laurente552edb2014-03-10 17:42:56 -07007647}
7648
François Gaffieaaac0fd2018-11-22 17:56:39 +01007649float AudioPolicyManager::computeVolume(IVolumeCurves &curves,
7650 VolumeSource volumeSource,
François Gaffied1ab2bd2015-12-02 18:20:06 +01007651 int index,
jiabin9a3361e2019-10-01 09:38:30 -07007652 const DeviceTypeSet& deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07007653{
jiabin9a3361e2019-10-01 09:38:30 -07007654 float volumeDb = curves.volIndexToDb(Volume::getDeviceCategory(deviceTypes), index);
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07007655
7656 // handle the case of accessibility active while a ringtone is playing: if the ringtone is much
7657 // louder than the accessibility prompt, the prompt cannot be heard, thus masking the touch
7658 // exploration of the dialer UI. In this situation, bring the accessibility volume closer to
7659 // the ringtone volume
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007660 const auto callVolumeSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL, false);
7661 const auto ringVolumeSrc = toVolumeSource(AUDIO_STREAM_RING, false);
7662 const auto musicVolumeSrc = toVolumeSource(AUDIO_STREAM_MUSIC, false);
7663 const auto alarmVolumeSrc = toVolumeSource(AUDIO_STREAM_ALARM, false);
7664 const auto a11yVolumeSrc = toVolumeSource(AUDIO_STREAM_ACCESSIBILITY, false);
Oscar Azucena5300db62023-08-30 18:45:18 -07007665 // Verify that the current volume source is not the ringer volume to prevent recursively
7666 // calling to compute volume. This could happen in cases where a11y and ringer sounds belong
7667 // to the same volume group.
7668 if (volumeSource != ringVolumeSrc && volumeSource == a11yVolumeSrc
François Gaffieaaac0fd2018-11-22 17:56:39 +01007669 && (AUDIO_MODE_RINGTONE == mEngine->getPhoneState()) &&
7670 mOutputs.isActive(ringVolumeSrc, 0)) {
7671 auto &ringCurves = getVolumeCurves(AUDIO_STREAM_RING);
jiabin9a3361e2019-10-01 09:38:30 -07007672 const float ringVolumeDb = computeVolume(ringCurves, ringVolumeSrc, index, deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007673 return ringVolumeDb - 4 > volumeDb ? ringVolumeDb - 4 : volumeDb;
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07007674 }
7675
Eric Laurentdcd4ab12018-06-29 17:45:13 -07007676 // in-call: always cap volume by voice volume + some low headroom
François Gaffieaaac0fd2018-11-22 17:56:39 +01007677 if ((volumeSource != callVolumeSrc && (isInCall() ||
7678 mOutputs.isActiveLocally(callVolumeSrc))) &&
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007679 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM, false) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01007680 volumeSource == ringVolumeSrc || volumeSource == musicVolumeSrc ||
7681 volumeSource == alarmVolumeSrc ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007682 volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION, false) ||
7683 volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false) ||
7684 volumeSource == toVolumeSource(AUDIO_STREAM_DTMF, false) ||
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07007685 volumeSource == a11yVolumeSrc)) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007686 auto &voiceCurves = getVolumeCurves(callVolumeSrc);
jiabin9a3361e2019-10-01 09:38:30 -07007687 int voiceVolumeIndex = voiceCurves.getVolumeIndex(deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007688 const float maxVoiceVolDb =
jiabin9a3361e2019-10-01 09:38:30 -07007689 computeVolume(voiceCurves, callVolumeSrc, voiceVolumeIndex, deviceTypes)
Eric Laurent7731b5a2018-04-06 15:47:22 -07007690 + IN_CALL_EARPIECE_HEADROOM_DB;
Abhijith Shastry329ddab2019-04-23 11:53:26 -07007691 // FIXME: Workaround for call screening applications until a proper audio mode is defined
7692 // to support this scenario : Exempt the RING stream from the audio cap if the audio was
7693 // programmatically muted.
7694 // VOICE_CALL stream has minVolumeIndex > 0 : Users cannot set the volume of voice calls to
7695 // 0. We don't want to cap volume when the system has programmatically muted the voice call
7696 // stream. See setVolumeCurveIndex() for more information.
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07007697 bool exemptFromCapping =
7698 ((volumeSource == ringVolumeSrc) || (volumeSource == a11yVolumeSrc))
7699 && (voiceVolumeIndex == 0);
Abhijith Shastry329ddab2019-04-23 11:53:26 -07007700 ALOGV_IF(exemptFromCapping, "%s volume source %d at vol=%f not capped", __func__,
7701 volumeSource, volumeDb);
7702 if ((volumeDb > maxVoiceVolDb) && !exemptFromCapping) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007703 ALOGV("%s volume source %d at vol=%f overriden by volume group %d at vol=%f", __func__,
7704 volumeSource, volumeDb, callVolumeSrc, maxVoiceVolDb);
7705 volumeDb = maxVoiceVolDb;
Jean-Michel Trivi719a9872017-08-05 13:51:35 -07007706 }
7707 }
Eric Laurente552edb2014-03-10 17:42:56 -07007708 // if a headset is connected, apply the following rules to ring tones and notifications
7709 // to avoid sound level bursts in user's ears:
Eric Laurent6af1c1d2016-04-14 11:20:44 -07007710 // - always attenuate notifications volume by 6dB
7711 // - attenuate ring tones volume by 6dB unless music is not playing and
7712 // speaker is part of the select devices
Eric Laurente552edb2014-03-10 17:42:56 -07007713 // - if music is playing, always limit the volume to current music volume,
7714 // with a minimum threshold at -36dB so that notification is always perceived.
jiabin9a3361e2019-10-01 09:38:30 -07007715 if (!Intersection(deviceTypes,
7716 {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP, AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES,
7717 AUDIO_DEVICE_OUT_WIRED_HEADSET, AUDIO_DEVICE_OUT_WIRED_HEADPHONE,
Eric Laurentc42df452020-08-07 10:51:53 -07007718 AUDIO_DEVICE_OUT_USB_HEADSET, AUDIO_DEVICE_OUT_HEARING_AID,
7719 AUDIO_DEVICE_OUT_BLE_HEADSET}).empty() &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01007720 ((volumeSource == alarmVolumeSrc ||
7721 volumeSource == ringVolumeSrc) ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007722 (volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION, false)) ||
7723 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM, false)) ||
7724 ((volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false)) &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01007725 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) &&
7726 curves.canBeMuted()) {
7727
Eric Laurente552edb2014-03-10 17:42:56 -07007728 // when the phone is ringing we must consider that music could have been paused just before
7729 // by the music application and behave as if music was active if the last music track was
7730 // just stopped
Oscar Azucena5300db62023-08-30 18:45:18 -07007731 // Verify that the current volume source is not the music volume to prevent recursively
7732 // calling to compute volume. This could happen in cases where music and
7733 // (alarm, ring, notification, system, etc.) sounds belong to the same volume group.
7734 if (volumeSource != musicVolumeSrc &&
7735 (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY)
7736 || mLimitRingtoneVolume)) {
François Gaffie43c73442018-11-08 08:21:55 +01007737 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
jiabin9a3361e2019-10-01 09:38:30 -07007738 DeviceTypeSet musicDevice =
François Gaffiec005e562018-11-06 15:04:49 +01007739 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
7740 nullptr, true /*fromCache*/).types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01007741 auto &musicCurves = getVolumeCurves(AUDIO_STREAM_MUSIC);
jiabin9a3361e2019-10-01 09:38:30 -07007742 float musicVolDb = computeVolume(musicCurves,
7743 musicVolumeSrc,
7744 musicCurves.getVolumeIndex(musicDevice),
7745 musicDevice);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007746 float minVolDb = (musicVolDb > SONIFICATION_HEADSET_VOLUME_MIN_DB) ?
7747 musicVolDb : SONIFICATION_HEADSET_VOLUME_MIN_DB;
7748 if (volumeDb > minVolDb) {
7749 volumeDb = minVolDb;
7750 ALOGV("computeVolume limiting volume to %f musicVol %f", minVolDb, musicVolDb);
Eric Laurente552edb2014-03-10 17:42:56 -07007751 }
Eric Laurent7b6385c2021-05-12 17:55:36 +02007752 if (Volume::getDeviceForVolume(deviceTypes) != AUDIO_DEVICE_OUT_SPEAKER
7753 && !Intersection(deviceTypes, {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP,
7754 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES}).empty()) {
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07007755 // on A2DP, also ensure notification volume is not too low compared to media when
7756 // intended to be played
François Gaffie43c73442018-11-08 08:21:55 +01007757 if ((volumeDb > -96.0f) &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01007758 (musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB > volumeDb)) {
jiabin9a3361e2019-10-01 09:38:30 -07007759 ALOGV("%s increasing volume for volume source=%d device=%s from %f to %f",
7760 __func__, volumeSource, dumpDeviceTypes(deviceTypes).c_str(), volumeDb,
François Gaffieaaac0fd2018-11-22 17:56:39 +01007761 musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB);
7762 volumeDb = musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB;
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07007763 }
7764 }
jiabin9a3361e2019-10-01 09:38:30 -07007765 } else if ((Volume::getDeviceForVolume(deviceTypes) != AUDIO_DEVICE_OUT_SPEAKER) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01007766 (!(volumeSource == alarmVolumeSrc || volumeSource == ringVolumeSrc))) {
François Gaffie43c73442018-11-08 08:21:55 +01007767 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07007768 }
7769 }
7770
François Gaffie43c73442018-11-08 08:21:55 +01007771 return volumeDb;
Eric Laurente552edb2014-03-10 17:42:56 -07007772}
7773
Eric Laurent3839bc02018-07-10 18:33:34 -07007774int AudioPolicyManager::rescaleVolumeIndex(int srcIndex,
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01007775 VolumeSource fromVolumeSource,
7776 VolumeSource toVolumeSource)
Eric Laurent3839bc02018-07-10 18:33:34 -07007777{
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01007778 if (fromVolumeSource == toVolumeSource) {
Eric Laurent3839bc02018-07-10 18:33:34 -07007779 return srcIndex;
7780 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01007781 auto &srcCurves = getVolumeCurves(fromVolumeSource);
7782 auto &dstCurves = getVolumeCurves(toVolumeSource);
Eric Laurentf5aa58d2019-02-22 18:20:11 -08007783 float minSrc = (float)srcCurves.getVolumeIndexMin();
7784 float maxSrc = (float)srcCurves.getVolumeIndexMax();
7785 float minDst = (float)dstCurves.getVolumeIndexMin();
7786 float maxDst = (float)dstCurves.getVolumeIndexMax();
Eric Laurent3839bc02018-07-10 18:33:34 -07007787
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08007788 // preserve mute request or correct range
7789 if (srcIndex < minSrc) {
7790 if (srcIndex == 0) {
7791 return 0;
7792 }
7793 srcIndex = minSrc;
7794 } else if (srcIndex > maxSrc) {
7795 srcIndex = maxSrc;
7796 }
Eric Laurent3839bc02018-07-10 18:33:34 -07007797 return (int)(minDst + ((srcIndex - minSrc) * (maxDst - minDst)) / (maxSrc - minSrc));
7798}
7799
François Gaffieaaac0fd2018-11-22 17:56:39 +01007800status_t AudioPolicyManager::checkAndSetVolume(IVolumeCurves &curves,
7801 VolumeSource volumeSource,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08007802 int index,
7803 const sp<AudioOutputDescriptor>& outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07007804 DeviceTypeSet deviceTypes,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08007805 int delayMs,
7806 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07007807{
François Gaffieaaac0fd2018-11-22 17:56:39 +01007808 // do not change actual attributes volume if the attributes is muted
7809 if (outputDesc->isMuted(volumeSource)) {
7810 ALOGVV("%s: volume source %d muted count %d active=%d", __func__, volumeSource,
7811 outputDesc->getMuteCount(volumeSource), outputDesc->isActive(volumeSource));
Eric Laurente552edb2014-03-10 17:42:56 -07007812 return NO_ERROR;
7813 }
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007814 VolumeSource callVolSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL, false);
7815 VolumeSource btScoVolSrc = toVolumeSource(AUDIO_STREAM_BLUETOOTH_SCO, false);
7816 bool isVoiceVolSrc = (volumeSource != VOLUME_SOURCE_NONE) && (callVolSrc == volumeSource);
7817 bool isBtScoVolSrc = (volumeSource != VOLUME_SOURCE_NONE) && (btScoVolSrc == volumeSource);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007818
Eric Laurent2517af32020-11-25 15:31:27 +01007819 bool isScoRequested = isScoRequestedForComm();
Eric Laurent1a8b45f2022-04-13 16:01:47 +02007820 bool isHAUsed = isHearingAidUsedForComm();
7821
Eric Laurente552edb2014-03-10 17:42:56 -07007822 // do not change in call volume if bluetooth is connected and vice versa
François Gaffieaaac0fd2018-11-22 17:56:39 +01007823 // if sco and call follow same curves, bypass forceUseForComm
7824 if ((callVolSrc != btScoVolSrc) &&
Eric Laurent2517af32020-11-25 15:31:27 +01007825 ((isVoiceVolSrc && isScoRequested) ||
Beibeif660a512023-02-28 17:00:34 +08007826 (isBtScoVolSrc && !(isScoRequested || isHAUsed))) &&
7827 !isSingleDeviceType(deviceTypes, AUDIO_DEVICE_OUT_TELEPHONY_TX)) {
Eric Laurent2517af32020-11-25 15:31:27 +01007828 ALOGV("%s cannot set volume group %d volume when is%srequested for comm", __func__,
Eric Laurent1a8b45f2022-04-13 16:01:47 +02007829 volumeSource, isScoRequested ? " " : " not ");
Eric Laurent571ef962020-07-24 11:43:48 -07007830 // Do not return an error here as AudioService will always set both voice call
7831 // and bluetooth SCO volumes due to stream aliasing.
7832 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07007833 }
jiabin9a3361e2019-10-01 09:38:30 -07007834 if (deviceTypes.empty()) {
7835 deviceTypes = outputDesc->devices().types();
chenxin2080986da2023-07-17 11:45:21 +08007836 index = curves.getVolumeIndex(deviceTypes);
7837 ALOGD("%s if deviceTypes is change from none to device %s, need get index %d",
7838 __func__, dumpDeviceTypes(deviceTypes).c_str(), index);
Eric Laurentc75307b2015-03-17 15:29:32 -07007839 }
Eric Laurent275e8e92014-11-30 15:14:47 -08007840
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00007841 if (curves.getVolumeIndexMin() < 0 || curves.getVolumeIndexMax() < 0) {
7842 ALOGE("invalid volume index range");
7843 return BAD_VALUE;
7844 }
7845
jiabin9a3361e2019-10-01 09:38:30 -07007846 float volumeDb = computeVolume(curves, volumeSource, index, deviceTypes);
7847 if (outputDesc->isFixedVolume(deviceTypes) ||
Eric Laurent9698a4c2020-10-12 17:10:23 -07007848 // Force VoIP volume to max for bluetooth SCO device except if muted
7849 (index != 0 && (isVoiceVolSrc || isBtScoVolSrc) &&
jiabin9a3361e2019-10-01 09:38:30 -07007850 isSingleDeviceType(deviceTypes, audio_is_bluetooth_out_sco_device))) {
Eric Laurentffbc80f2015-03-18 18:30:19 -07007851 volumeDb = 0.0f;
Eric Laurent275e8e92014-11-30 15:14:47 -08007852 }
Francois Gaffie593634d2021-06-22 13:31:31 +02007853 const bool muted = (index == 0) && (volumeDb != 0.0f);
Eric Laurent31a428a2023-08-11 12:16:28 +02007854 outputDesc->setVolume(volumeDb, muted, volumeSource, curves.getStreamTypes(),
7855 deviceTypes, delayMs, force, isVoiceVolSrc);
Eric Laurentc75307b2015-03-17 15:29:32 -07007856
Eric Laurente8f2c0f2021-08-17 11:17:19 +02007857 if (outputDesc == mPrimaryOutput && (isVoiceVolSrc || isBtScoVolSrc)) {
Eric Laurente552edb2014-03-10 17:42:56 -07007858 float voiceVolume;
Eric Laurentfad001d2019-06-11 19:17:57 -07007859 // 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 +01007860 if (isVoiceVolSrc) {
7861 voiceVolume = (float)index/(float)curves.getVolumeIndexMax();
Eric Laurente552edb2014-03-10 17:42:56 -07007862 } else {
Eric Laurentfad001d2019-06-11 19:17:57 -07007863 voiceVolume = index == 0 ? 0.0 : 1.0;
Eric Laurente552edb2014-03-10 17:42:56 -07007864 }
Eric Laurent18fba842016-03-31 14:41:26 -07007865 if (voiceVolume != mLastVoiceVolume) {
Eric Laurente552edb2014-03-10 17:42:56 -07007866 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
7867 mLastVoiceVolume = voiceVolume;
7868 }
7869 }
Eric Laurente552edb2014-03-10 17:42:56 -07007870 return NO_ERROR;
7871}
7872
Eric Laurentc75307b2015-03-17 15:29:32 -07007873void AudioPolicyManager::applyStreamVolumes(const sp<AudioOutputDescriptor>& outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07007874 const DeviceTypeSet& deviceTypes,
7875 int delayMs,
7876 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07007877{
jiabincd510522020-01-22 09:40:55 -08007878 ALOGVV("applyStreamVolumes() for device %s", dumpDeviceTypes(deviceTypes).c_str());
François Gaffieaaac0fd2018-11-22 17:56:39 +01007879 for (const auto &volumeGroup : mEngine->getVolumeGroups()) {
7880 auto &curves = getVolumeCurves(toVolumeSource(volumeGroup));
7881 checkAndSetVolume(curves, toVolumeSource(volumeGroup),
jiabin9a3361e2019-10-01 09:38:30 -07007882 curves.getVolumeIndex(deviceTypes),
7883 outputDesc, deviceTypes, delayMs, force);
Eric Laurente552edb2014-03-10 17:42:56 -07007884 }
7885}
7886
François Gaffiec005e562018-11-06 15:04:49 +01007887void AudioPolicyManager::setStrategyMute(product_strategy_t strategy,
7888 bool on,
7889 const sp<AudioOutputDescriptor>& outputDesc,
7890 int delayMs,
jiabin9a3361e2019-10-01 09:38:30 -07007891 DeviceTypeSet deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07007892{
François Gaffieaaac0fd2018-11-22 17:56:39 +01007893 std::vector<VolumeSource> sourcesToMute;
7894 for (auto attributes: mEngine->getAllAttributesForProductStrategy(strategy)) {
7895 ALOGVV("%s() attributes %s, mute %d, output ID %d", __func__,
7896 toString(attributes).c_str(), on, outputDesc->getId());
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007897 VolumeSource source = toVolumeSource(attributes, false);
7898 if ((source != VOLUME_SOURCE_NONE) &&
7899 (std::find(begin(sourcesToMute), end(sourcesToMute), source)
7900 == end(sourcesToMute))) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007901 sourcesToMute.push_back(source);
7902 }
Eric Laurente552edb2014-03-10 17:42:56 -07007903 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01007904 for (auto source : sourcesToMute) {
jiabin9a3361e2019-10-01 09:38:30 -07007905 setVolumeSourceMute(source, on, outputDesc, delayMs, deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007906 }
7907
Eric Laurente552edb2014-03-10 17:42:56 -07007908}
7909
François Gaffieaaac0fd2018-11-22 17:56:39 +01007910void AudioPolicyManager::setVolumeSourceMute(VolumeSource volumeSource,
7911 bool on,
7912 const sp<AudioOutputDescriptor>& outputDesc,
7913 int delayMs,
jiabin9a3361e2019-10-01 09:38:30 -07007914 DeviceTypeSet deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07007915{
jiabin9a3361e2019-10-01 09:38:30 -07007916 if (deviceTypes.empty()) {
7917 deviceTypes = outputDesc->devices().types();
Eric Laurente552edb2014-03-10 17:42:56 -07007918 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01007919 auto &curves = getVolumeCurves(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07007920 if (on) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007921 if (!outputDesc->isMuted(volumeSource)) {
Eric Laurentf5aa58d2019-02-22 18:20:11 -08007922 if (curves.canBeMuted() &&
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007923 (volumeSource != toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01007924 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) ==
7925 AUDIO_POLICY_FORCE_NONE))) {
jiabin9a3361e2019-10-01 09:38:30 -07007926 checkAndSetVolume(curves, volumeSource, 0, outputDesc, deviceTypes, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07007927 }
7928 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01007929 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not
7930 // ignored
7931 outputDesc->incMuteCount(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07007932 } else {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007933 if (!outputDesc->isMuted(volumeSource)) {
7934 ALOGV("%s unmuting non muted attributes!", __func__);
Eric Laurente552edb2014-03-10 17:42:56 -07007935 return;
7936 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01007937 if (outputDesc->decMuteCount(volumeSource) == 0) {
7938 checkAndSetVolume(curves, volumeSource,
jiabin9a3361e2019-10-01 09:38:30 -07007939 curves.getVolumeIndex(deviceTypes),
Eric Laurentc75307b2015-03-17 15:29:32 -07007940 outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07007941 deviceTypes,
Eric Laurente552edb2014-03-10 17:42:56 -07007942 delayMs);
7943 }
7944 }
7945}
7946
François Gaffie53615e22015-03-19 09:24:12 +01007947bool AudioPolicyManager::isValidAttributes(const audio_attributes_t *paa)
7948{
François Gaffiec005e562018-11-06 15:04:49 +01007949 // has flags that map to a stream type?
Eric Laurente83b55d2014-11-14 10:06:21 -08007950 if ((paa->flags & (AUDIO_FLAG_AUDIBILITY_ENFORCED | AUDIO_FLAG_SCO | AUDIO_FLAG_BEACON)) != 0) {
7951 return true;
7952 }
7953
7954 // has known usage?
7955 switch (paa->usage) {
7956 case AUDIO_USAGE_UNKNOWN:
7957 case AUDIO_USAGE_MEDIA:
7958 case AUDIO_USAGE_VOICE_COMMUNICATION:
7959 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
7960 case AUDIO_USAGE_ALARM:
7961 case AUDIO_USAGE_NOTIFICATION:
7962 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
7963 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
7964 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
7965 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
7966 case AUDIO_USAGE_NOTIFICATION_EVENT:
7967 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
7968 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
7969 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
7970 case AUDIO_USAGE_GAME:
Eric Laurent275e8e92014-11-30 15:14:47 -08007971 case AUDIO_USAGE_VIRTUAL_SOURCE:
Jean-Michel Trivi36867762016-12-29 12:03:28 -08007972 case AUDIO_USAGE_ASSISTANT:
Eric Laurent21777f82019-12-06 18:12:06 -08007973 case AUDIO_USAGE_CALL_ASSISTANT:
Hayden Gomes524159d2019-12-23 14:41:47 -08007974 case AUDIO_USAGE_EMERGENCY:
7975 case AUDIO_USAGE_SAFETY:
7976 case AUDIO_USAGE_VEHICLE_STATUS:
7977 case AUDIO_USAGE_ANNOUNCEMENT:
Eric Laurente83b55d2014-11-14 10:06:21 -08007978 break;
7979 default:
7980 return false;
7981 }
7982 return true;
7983}
7984
François Gaffie2110e042015-03-24 08:41:51 +01007985audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
7986{
7987 return mEngine->getForceUse(usage);
7988}
7989
Eric Laurent96d1dda2022-03-14 17:14:19 +01007990bool AudioPolicyManager::isInCall() const {
François Gaffie2110e042015-03-24 08:41:51 +01007991 return isStateInCall(mEngine->getPhoneState());
7992}
7993
Eric Laurent96d1dda2022-03-14 17:14:19 +01007994bool AudioPolicyManager::isStateInCall(int state) const {
François Gaffie2110e042015-03-24 08:41:51 +01007995 return is_state_in_call(state);
7996}
7997
Eric Laurentf9cccec2022-11-16 19:12:00 +01007998bool AudioPolicyManager::isCallAudioAccessible() const {
Eric Laurent74b71512019-11-06 17:21:57 -08007999 audio_mode_t mode = mEngine->getPhoneState();
8000 return (mode == AUDIO_MODE_IN_CALL)
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01008001 || (mode == AUDIO_MODE_CALL_SCREEN)
8002 || (mode == AUDIO_MODE_CALL_REDIRECT);
Eric Laurent74b71512019-11-06 17:21:57 -08008003}
8004
Eric Laurentf9cccec2022-11-16 19:12:00 +01008005bool AudioPolicyManager::isInCallOrScreening() const {
8006 audio_mode_t mode = mEngine->getPhoneState();
8007 return isStateInCall(mode) || mode == AUDIO_MODE_CALL_SCREEN;
8008}
8009
Eric Laurentd60560a2015-04-10 11:31:20 -07008010void AudioPolicyManager::cleanUpForDevice(const sp<DeviceDescriptor>& deviceDesc)
8011{
8012 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07008013 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008014 if (sourceDesc->isConnected() && (sourceDesc->srcDevice()->equals(deviceDesc) ||
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02008015 sourceDesc->sinkDevice()->equals(deviceDesc))
8016 && !isCallRxAudioSource(sourceDesc)) {
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008017 disconnectAudioSource(sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07008018 }
8019 }
8020
8021 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
8022 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
8023 bool release = false;
8024 for (size_t j = 0; j < patchDesc->mPatch.num_sources && !release; j++) {
8025 const struct audio_port_config *source = &patchDesc->mPatch.sources[j];
8026 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
8027 source->ext.device.type == deviceDesc->type()) {
8028 release = true;
8029 }
8030 }
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008031 const char *address = deviceDesc->address().c_str();
Eric Laurentd60560a2015-04-10 11:31:20 -07008032 for (size_t j = 0; j < patchDesc->mPatch.num_sinks && !release; j++) {
8033 const struct audio_port_config *sink = &patchDesc->mPatch.sinks[j];
8034 if (sink->type == AUDIO_PORT_TYPE_DEVICE &&
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008035 sink->ext.device.type == deviceDesc->type() &&
8036 (strnlen(address, AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0
8037 || strncmp(sink->ext.device.address, address,
8038 AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0)) {
Eric Laurentd60560a2015-04-10 11:31:20 -07008039 release = true;
8040 }
8041 }
8042 if (release) {
François Gaffieafd4cea2019-11-18 15:50:22 +01008043 ALOGV("%s releasing patch %u", __FUNCTION__, patchDesc->getHandle());
8044 releaseAudioPatch(patchDesc->getHandle(), patchDesc->getUid());
Eric Laurentd60560a2015-04-10 11:31:20 -07008045 }
8046 }
Francois Gaffie716e1432019-01-14 16:58:59 +01008047
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01008048 mInputs.clearSessionRoutesForDevice(deviceDesc);
8049
Francois Gaffie716e1432019-01-14 16:58:59 +01008050 mHwModules.cleanUpForDevice(deviceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07008051}
8052
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008053void AudioPolicyManager::modifySurroundFormats(
8054 const sp<DeviceDescriptor>& devDesc, FormatVector *formatsPtr) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008055 std::unordered_set<audio_format_t> enforcedSurround(
8056 devDesc->encodedFormats().begin(), devDesc->encodedFormats().end());
Mikhail Naganov100f0122018-11-29 11:22:16 -08008057 std::unordered_set<audio_format_t> allSurround; // A flat set of all known surround formats
Mikhail Naganov68e3f642023-04-28 13:06:32 -07008058 for (const auto& pair : mConfig->getSurroundFormats()) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008059 allSurround.insert(pair.first);
8060 for (const auto& subformat : pair.second) allSurround.insert(subformat);
8061 }
Phil Burk09bc4612016-02-24 15:58:15 -08008062
8063 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
8064 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Phil Burk0709b0a2016-03-31 12:54:57 -07008065 ALOGD("%s: forced use = %d", __FUNCTION__, forceUse);
Mikhail Naganov100f0122018-11-29 11:22:16 -08008066 // This is the resulting set of formats depending on the surround mode:
8067 // 'all surround' = allSurround
8068 // 'enforced surround' = enforcedSurround [may include IEC69137 which isn't raw surround fmt]
8069 // 'non-surround' = not in 'all surround' and not in 'enforced surround'
8070 // 'manual surround' = mManualSurroundFormats
8071 // AUTO: formats v 'enforced surround'
8072 // ALWAYS: formats v 'all surround' v 'enforced surround'
8073 // NEVER: formats ^ 'non-surround'
8074 // MANUAL: formats ^ ('non-surround' v 'manual surround' v (IEC69137 ^ 'enforced surround'))
Phil Burk09bc4612016-02-24 15:58:15 -08008075
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008076 std::unordered_set<audio_format_t> formatSet;
8077 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL
8078 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008079 // formatSet is (formats ^ 'non-surround')
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008080 for (auto formatIter = formatsPtr->begin(); formatIter != formatsPtr->end(); ++formatIter) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008081 if (allSurround.count(*formatIter) == 0 && enforcedSurround.count(*formatIter) == 0) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008082 formatSet.insert(*formatIter);
8083 }
8084 }
8085 } else {
8086 formatSet.insert(formatsPtr->begin(), formatsPtr->end());
8087 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08008088 formatsPtr->clear(); // Re-filled from the formatSet at the end.
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008089
jiabin81772902018-04-02 17:52:27 -07008090 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008091 formatSet.insert(mManualSurroundFormats.begin(), mManualSurroundFormats.end());
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008092 // Enable IEC61937 when in MANUAL mode if it's enforced for this device.
8093 if (enforcedSurround.count(AUDIO_FORMAT_IEC61937) != 0) {
8094 formatSet.insert(AUDIO_FORMAT_IEC61937);
Phil Burk09bc4612016-02-24 15:58:15 -08008095 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08008096 } else if (forceUse != AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) { // AUTO or ALWAYS
8097 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS) {
8098 formatSet.insert(allSurround.begin(), allSurround.end());
Phil Burk07ac1142016-03-25 13:39:29 -07008099 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08008100 formatSet.insert(enforcedSurround.begin(), enforcedSurround.end());
Phil Burk09bc4612016-02-24 15:58:15 -08008101 }
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008102 for (const auto& format : formatSet) {
jiabin06e4bab2019-07-29 10:13:34 -07008103 formatsPtr->push_back(format);
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008104 }
Phil Burk0709b0a2016-03-31 12:54:57 -07008105}
8106
jiabin06e4bab2019-07-29 10:13:34 -07008107void AudioPolicyManager::modifySurroundChannelMasks(ChannelMaskSet *channelMasksPtr) {
8108 ChannelMaskSet &channelMasks = *channelMasksPtr;
Phil Burk0709b0a2016-03-31 12:54:57 -07008109 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
8110 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
8111
8112 // If NEVER, then remove support for channelMasks > stereo.
8113 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
jiabin06e4bab2019-07-29 10:13:34 -07008114 for (auto it = channelMasks.begin(); it != channelMasks.end();) {
8115 audio_channel_mask_t channelMask = *it;
Phil Burk0709b0a2016-03-31 12:54:57 -07008116 if (channelMask & ~AUDIO_CHANNEL_OUT_STEREO) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01008117 ALOGV("%s: force NEVER, so remove channelMask 0x%08x", __FUNCTION__, channelMask);
jiabin06e4bab2019-07-29 10:13:34 -07008118 it = channelMasks.erase(it);
Phil Burk0709b0a2016-03-31 12:54:57 -07008119 } else {
jiabin06e4bab2019-07-29 10:13:34 -07008120 ++it;
Phil Burk0709b0a2016-03-31 12:54:57 -07008121 }
8122 }
jiabin81772902018-04-02 17:52:27 -07008123 // If ALWAYS or MANUAL, then make sure we at least support 5.1
8124 } else if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS
8125 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Phil Burk0709b0a2016-03-31 12:54:57 -07008126 bool supports5dot1 = false;
8127 // Are there any channel masks that can be considered "surround"?
Mikhail Naganovcf84e592017-12-07 11:25:11 -08008128 for (audio_channel_mask_t channelMask : channelMasks) {
Phil Burk0709b0a2016-03-31 12:54:57 -07008129 if ((channelMask & AUDIO_CHANNEL_OUT_5POINT1) == AUDIO_CHANNEL_OUT_5POINT1) {
8130 supports5dot1 = true;
8131 break;
8132 }
8133 }
8134 // If not then add 5.1 support.
8135 if (!supports5dot1) {
jiabin06e4bab2019-07-29 10:13:34 -07008136 channelMasks.insert(AUDIO_CHANNEL_OUT_5POINT1);
Eric Laurentfecbceb2021-02-09 14:46:43 +01008137 ALOGV("%s: force MANUAL or ALWAYS, so adding channelMask for 5.1 surround", __func__);
Phil Burk0709b0a2016-03-31 12:54:57 -07008138 }
Phil Burk09bc4612016-02-24 15:58:15 -08008139 }
8140}
8141
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008142void AudioPolicyManager::updateAudioProfiles(const sp<DeviceDescriptor>& devDesc,
Phil Burk00eeb322016-03-31 12:41:00 -07008143 audio_io_handle_t ioHandle,
jiabin12537fc2023-10-12 17:56:08 +00008144 const sp<IOProfile>& profile) {
8145 if (!profile->hasDynamicAudioProfile()) {
8146 return;
François Gaffie112b0af2015-11-19 16:13:25 +01008147 }
François Gaffie112b0af2015-11-19 16:13:25 +01008148
jiabin12537fc2023-10-12 17:56:08 +00008149 audio_port_v7 devicePort;
8150 devDesc->toAudioPort(&devicePort);
François Gaffie112b0af2015-11-19 16:13:25 +01008151
jiabin12537fc2023-10-12 17:56:08 +00008152 audio_port_v7 mixPort;
8153 profile->toAudioPort(&mixPort);
8154 mixPort.ext.mix.handle = ioHandle;
8155
8156 status_t status = mpClientInterface->getAudioMixPort(&devicePort, &mixPort);
8157 if (status != NO_ERROR) {
8158 ALOGE("%s failed to query the attributes of the mix port", __func__);
8159 return;
François Gaffie112b0af2015-11-19 16:13:25 +01008160 }
jiabin12537fc2023-10-12 17:56:08 +00008161
8162 std::set<audio_format_t> supportedFormats;
8163 for (size_t i = 0; i < mixPort.num_audio_profiles; ++i) {
8164 supportedFormats.insert(mixPort.audio_profiles[i].format);
8165 }
8166 FormatVector formats(supportedFormats.begin(), supportedFormats.end());
8167 mReportedFormatsMap[devDesc] = formats;
8168
8169 if (devDesc->type() == AUDIO_DEVICE_OUT_HDMI ||
8170 isDeviceOfModule(devDesc,AUDIO_HARDWARE_MODULE_ID_MSD)) {
8171 modifySurroundFormats(devDesc, &formats);
8172 size_t modifiedNumProfiles = 0;
8173 for (size_t i = 0; i < mixPort.num_audio_profiles; ++i) {
8174 if (std::find(formats.begin(), formats.end(), mixPort.audio_profiles[i].format) ==
8175 formats.end()) {
8176 // Skip the format that is not present after modifying surround formats.
8177 continue;
8178 }
8179 memcpy(&mixPort.audio_profiles[modifiedNumProfiles], &mixPort.audio_profiles[i],
8180 sizeof(struct audio_profile));
8181 ChannelMaskSet channels(mixPort.audio_profiles[modifiedNumProfiles].channel_masks,
8182 mixPort.audio_profiles[modifiedNumProfiles].channel_masks +
8183 mixPort.audio_profiles[modifiedNumProfiles].num_channel_masks);
8184 modifySurroundChannelMasks(&channels);
8185 std::copy(channels.begin(), channels.end(),
8186 std::begin(mixPort.audio_profiles[modifiedNumProfiles].channel_masks));
8187 mixPort.audio_profiles[modifiedNumProfiles++].num_channel_masks = channels.size();
8188 }
8189 mixPort.num_audio_profiles = modifiedNumProfiles;
8190 }
8191 profile->importAudioPort(mixPort);
François Gaffie112b0af2015-11-19 16:13:25 +01008192}
Eric Laurentd60560a2015-04-10 11:31:20 -07008193
Mikhail Naganovdc769682018-05-04 15:34:08 -07008194status_t AudioPolicyManager::installPatch(const char *caller,
8195 audio_patch_handle_t *patchHandle,
8196 AudioIODescriptorInterface *ioDescriptor,
8197 const struct audio_patch *patch,
8198 int delayMs)
8199{
8200 ssize_t index = mAudioPatches.indexOfKey(
8201 patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE ?
8202 *patchHandle : ioDescriptor->getPatchHandle());
8203 sp<AudioPatch> patchDesc;
8204 status_t status = installPatch(
8205 caller, index, patchHandle, patch, delayMs, mUidCached, &patchDesc);
8206 if (status == NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01008207 ioDescriptor->setPatchHandle(patchDesc->getHandle());
Mikhail Naganovdc769682018-05-04 15:34:08 -07008208 }
8209 return status;
8210}
8211
8212status_t AudioPolicyManager::installPatch(const char *caller,
8213 ssize_t index,
8214 audio_patch_handle_t *patchHandle,
8215 const struct audio_patch *patch,
8216 int delayMs,
8217 uid_t uid,
8218 sp<AudioPatch> *patchDescPtr)
8219{
8220 sp<AudioPatch> patchDesc;
8221 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
8222 if (index >= 0) {
8223 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01008224 afPatchHandle = patchDesc->getAfHandle();
Mikhail Naganovdc769682018-05-04 15:34:08 -07008225 }
8226
8227 status_t status = mpClientInterface->createAudioPatch(patch, &afPatchHandle, delayMs);
8228 ALOGV("%s() AF::createAudioPatch returned %d patchHandle %d num_sources %d num_sinks %d",
8229 caller, status, afPatchHandle, patch->num_sources, patch->num_sinks);
8230 if (status == NO_ERROR) {
8231 if (index < 0) {
8232 patchDesc = new AudioPatch(patch, uid);
François Gaffieafd4cea2019-11-18 15:50:22 +01008233 addAudioPatch(patchDesc->getHandle(), patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07008234 } else {
8235 patchDesc->mPatch = *patch;
8236 }
François Gaffieafd4cea2019-11-18 15:50:22 +01008237 patchDesc->setAfHandle(afPatchHandle);
Mikhail Naganovdc769682018-05-04 15:34:08 -07008238 if (patchHandle) {
François Gaffieafd4cea2019-11-18 15:50:22 +01008239 *patchHandle = patchDesc->getHandle();
Mikhail Naganovdc769682018-05-04 15:34:08 -07008240 }
8241 nextAudioPortGeneration();
8242 mpClientInterface->onAudioPatchListUpdate();
8243 }
8244 if (patchDescPtr) *patchDescPtr = patchDesc;
8245 return status;
8246}
8247
jiabinbce0c1d2020-10-05 11:20:18 -07008248bool AudioPolicyManager::areAllActiveTracksRerouted(const sp<SwAudioOutputDescriptor>& output)
8249{
8250 const TrackClientVector activeClients = output->getActiveClients();
8251 if (activeClients.empty()) {
8252 return true;
8253 }
8254 ssize_t index = mAudioPatches.indexOfKey(output->getPatchHandle());
8255 if (index < 0) {
8256 ALOGE("%s, no audio patch found while there are active clients on output %d",
8257 __func__, output->getId());
8258 return false;
8259 }
8260 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
8261 DeviceVector routedDevices;
8262 for (int i = 0; i < patchDesc->mPatch.num_sinks; ++i) {
8263 sp<DeviceDescriptor> device = mAvailableOutputDevices.getDeviceFromId(
8264 patchDesc->mPatch.sinks[i].id);
8265 if (device == nullptr) {
8266 ALOGE("%s, no audio device found with id(%d)",
8267 __func__, patchDesc->mPatch.sinks[i].id);
8268 return false;
8269 }
8270 routedDevices.add(device);
8271 }
8272 for (const auto& client : activeClients) {
jiabin49256852022-03-09 11:21:35 -08008273 if (client->isInvalid()) {
8274 // No need to take care about invalidated clients.
8275 continue;
8276 }
jiabinbce0c1d2020-10-05 11:20:18 -07008277 sp<DeviceDescriptor> preferredDevice =
8278 mAvailableOutputDevices.getDeviceFromId(client->preferredDeviceId());
8279 if (mEngine->getOutputDevicesForAttributes(
8280 client->attributes(), preferredDevice, false) == routedDevices) {
8281 return false;
8282 }
8283 }
8284 return true;
8285}
8286
8287sp<SwAudioOutputDescriptor> AudioPolicyManager::openOutputWithProfileAndDevice(
Eric Laurentb4f42a92022-01-17 17:37:31 +01008288 const sp<IOProfile>& profile, const DeviceVector& devices,
jiabina84c3d32022-12-02 18:59:55 +00008289 const audio_config_base_t *mixerConfig, const audio_config_t *halConfig,
8290 audio_output_flags_t flags)
jiabinbce0c1d2020-10-05 11:20:18 -07008291{
8292 for (const auto& device : devices) {
8293 // TODO: This should be checking if the profile supports the device combo.
8294 if (!profile->supportsDevice(device)) {
jiabina84c3d32022-12-02 18:59:55 +00008295 ALOGE("%s profile(%s) doesn't support device %#x", __func__, profile->getName().c_str(),
8296 device->type());
jiabinbce0c1d2020-10-05 11:20:18 -07008297 return nullptr;
8298 }
8299 }
8300 sp<SwAudioOutputDescriptor> desc = new SwAudioOutputDescriptor(profile, mpClientInterface);
8301 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
jiabina84c3d32022-12-02 18:59:55 +00008302 status_t status = desc->open(halConfig, mixerConfig, devices,
8303 AUDIO_STREAM_DEFAULT, flags, &output);
jiabinbce0c1d2020-10-05 11:20:18 -07008304 if (status != NO_ERROR) {
jiabina84c3d32022-12-02 18:59:55 +00008305 ALOGE("%s failed to open output %d", __func__, status);
jiabinbce0c1d2020-10-05 11:20:18 -07008306 return nullptr;
8307 }
8308
8309 // Here is where the out_set_parameters() for card & device gets called
8310 sp<DeviceDescriptor> device = devices.getDeviceForOpening();
8311 const audio_devices_t deviceType = device->type();
8312 const String8 &address = String8(device->address().c_str());
Tomasz Wasilczykfd9ffd12023-08-14 17:56:22 +00008313 if (!address.empty()) {
jiabinbce0c1d2020-10-05 11:20:18 -07008314 char *param = audio_device_address_to_parameter(deviceType, address.c_str());
8315 mpClientInterface->setParameters(output, String8(param));
8316 free(param);
8317 }
jiabin12537fc2023-10-12 17:56:08 +00008318 updateAudioProfiles(device, output, profile);
jiabinbce0c1d2020-10-05 11:20:18 -07008319 if (!profile->hasValidAudioProfile()) {
8320 ALOGW("%s() missing param", __func__);
8321 desc->close();
8322 return nullptr;
jiabina84c3d32022-12-02 18:59:55 +00008323 } else if (profile->hasDynamicAudioProfile() && halConfig == nullptr) {
8324 // Reopen the output with the best audio profile picked by APM when the profile supports
8325 // dynamic audio profile and the hal config is not specified.
jiabinbce0c1d2020-10-05 11:20:18 -07008326 desc->close();
8327 output = AUDIO_IO_HANDLE_NONE;
8328 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
8329 profile->pickAudioProfile(
8330 config.sample_rate, config.channel_mask, config.format);
8331 config.offload_info.sample_rate = config.sample_rate;
8332 config.offload_info.channel_mask = config.channel_mask;
8333 config.offload_info.format = config.format;
8334
jiabina84c3d32022-12-02 18:59:55 +00008335 status = desc->open(&config, mixerConfig, devices, AUDIO_STREAM_DEFAULT, flags, &output);
jiabinbce0c1d2020-10-05 11:20:18 -07008336 if (status != NO_ERROR) {
8337 return nullptr;
8338 }
8339 }
8340
8341 addOutput(output, desc);
Eric Laurentb4f42a92022-01-17 17:37:31 +01008342
baek.kim -61c20122022-07-27 10:05:32 +00008343 sp<DeviceDescriptor> speaker = mAvailableOutputDevices.getDevice(
8344 AUDIO_DEVICE_OUT_SPEAKER, String8(""), AUDIO_FORMAT_DEFAULT);
8345
jiabinbce0c1d2020-10-05 11:20:18 -07008346 if (audio_is_remote_submix_device(deviceType) && address != "0") {
8347 sp<AudioPolicyMix> policyMix;
8348 if (mPolicyMixes.getAudioPolicyMix(deviceType, address, policyMix) == NO_ERROR) {
8349 policyMix->setOutput(desc);
8350 desc->mPolicyMix = policyMix;
8351 } else {
8352 ALOGW("checkOutputsForDevice() cannot find policy for address %s",
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00008353 address.c_str());
jiabinbce0c1d2020-10-05 11:20:18 -07008354 }
8355
baek.kim -61c20122022-07-27 10:05:32 +00008356 } else if (hasPrimaryOutput() && speaker != nullptr
8357 && mPrimaryOutput->supportsDevice(speaker) && !desc->supportsDevice(speaker)
Eric Laurentb4f42a92022-01-17 17:37:31 +01008358 && ((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0)) {
8359 // no duplicated output for:
8360 // - direct outputs
8361 // - outputs used by dynamic policy mixes
baek.kim -61c20122022-07-27 10:05:32 +00008362 // - outputs that supports SPEAKER while the primary output does not.
jiabinbce0c1d2020-10-05 11:20:18 -07008363 audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE;
8364
8365 //TODO: configure audio effect output stage here
8366
8367 // open a duplicating output thread for the new output and the primary output
8368 sp<SwAudioOutputDescriptor> dupOutputDesc =
8369 new SwAudioOutputDescriptor(nullptr, mpClientInterface);
8370 status = dupOutputDesc->openDuplicating(mPrimaryOutput, desc, &duplicatedOutput);
8371 if (status == NO_ERROR) {
8372 // add duplicated output descriptor
8373 addOutput(duplicatedOutput, dupOutputDesc);
8374 } else {
8375 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
8376 mPrimaryOutput->mIoHandle, output);
8377 desc->close();
8378 removeOutput(output);
8379 nextAudioPortGeneration();
8380 return nullptr;
8381 }
8382 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02008383 if (mPrimaryOutput == nullptr && profile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
8384 ALOGV("%s(): re-assigning mPrimaryOutput", __func__);
8385 mPrimaryOutput = desc;
8386 }
jiabinbce0c1d2020-10-05 11:20:18 -07008387 return desc;
8388}
8389
jiabinf1c73972022-04-14 16:28:52 -07008390status_t AudioPolicyManager::getDevicesForAttributes(
8391 const audio_attributes_t &attr, DeviceVector &devices, bool forVolume) {
8392 // Devices are determined in the following precedence:
8393 //
8394 // 1) Devices associated with a dynamic policy matching the attributes. This is often
8395 // a remote submix from MIX_ROUTE_FLAG_LOOP_BACK.
8396 //
8397 // If no such dynamic policy then
8398 // 2) Devices containing an active client using setPreferredDevice
8399 // with same strategy as the attributes.
8400 // (from the default Engine::getOutputDevicesForAttributes() implementation).
8401 //
8402 // If no corresponding active client with setPreferredDevice then
8403 // 3) Devices associated with the strategy determined by the attributes
8404 // (from the default Engine::getOutputDevicesForAttributes() implementation).
8405 //
8406 // See related getOutputForAttrInt().
8407
8408 // check dynamic policies but only for primary descriptors (secondary not used for audible
8409 // audio routing, only used for duplication for playback capture)
8410 sp<AudioPolicyMix> policyMix;
Oscar Azucena873d10f2023-01-12 18:34:42 -08008411 bool unneededUsePrimaryOutputFromPolicyMixes = false;
jiabinf1c73972022-04-14 16:28:52 -07008412 status_t status = mPolicyMixes.getOutputForAttr(attr, AUDIO_CONFIG_BASE_INITIALIZER,
Oscar Azucena873d10f2023-01-12 18:34:42 -08008413 0 /*uid unknown here*/, AUDIO_SESSION_NONE, AUDIO_OUTPUT_FLAG_NONE,
8414 mAvailableOutputDevices, nullptr /* requestedDevice */, policyMix,
8415 nullptr /* secondaryMixes */, unneededUsePrimaryOutputFromPolicyMixes);
jiabinf1c73972022-04-14 16:28:52 -07008416 if (status != OK) {
8417 return status;
8418 }
8419
8420 if (policyMix != nullptr && policyMix->getOutput() != nullptr &&
8421 // For volume control, skip LOOPBACK mixes which use AUDIO_DEVICE_OUT_REMOTE_SUBMIX
8422 // as they are unaffected by device/stream volume
8423 // (per SwAudioOutputDescriptor::isFixedVolume()).
8424 (!forVolume || policyMix->mDeviceType != AUDIO_DEVICE_OUT_REMOTE_SUBMIX)
8425 ) {
8426 sp<DeviceDescriptor> deviceDesc = mAvailableOutputDevices.getDevice(
8427 policyMix->mDeviceType, policyMix->mDeviceAddress, AUDIO_FORMAT_DEFAULT);
8428 devices.add(deviceDesc);
8429 } else {
8430 // The default Engine::getOutputDevicesForAttributes() uses findPreferredDevice()
8431 // which selects setPreferredDevice if active. This means forVolume call
8432 // will take an active setPreferredDevice, if such exists.
8433
8434 devices = mEngine->getOutputDevicesForAttributes(
8435 attr, nullptr /* preferredDevice */, false /* fromCache */);
8436 }
8437
8438 if (forVolume) {
8439 // We alias the device AUDIO_DEVICE_OUT_SPEAKER_SAFE to AUDIO_DEVICE_OUT_SPEAKER
8440 // for single volume control in AudioService (such relationship should exist if
8441 // SPEAKER_SAFE is present).
8442 //
8443 // (This is unrelated to a different device grouping as Volume::getDeviceCategory)
8444 DeviceVector speakerSafeDevices =
8445 devices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER_SAFE);
8446 if (!speakerSafeDevices.isEmpty()) {
8447 devices.merge(mAvailableOutputDevices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER));
8448 devices.remove(speakerSafeDevices);
8449 }
8450 }
8451
8452 return NO_ERROR;
8453}
8454
8455status_t AudioPolicyManager::getProfilesForDevices(const DeviceVector& devices,
8456 AudioProfileVector& audioProfiles,
8457 uint32_t flags,
8458 bool isInput) {
8459 for (const auto& hwModule : mHwModules) {
8460 // the MSD module checks for different conditions
8461 if (strcmp(hwModule->getName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0) {
8462 continue;
8463 }
8464 IOProfileCollection ioProfiles = isInput ? hwModule->getInputProfiles()
8465 : hwModule->getOutputProfiles();
8466 for (const auto& profile : ioProfiles) {
8467 if (!profile->areAllDevicesSupported(devices) ||
8468 !profile->isCompatibleProfileForFlags(
8469 flags, false /*exactMatchRequiredForInputFlags*/)) {
8470 continue;
8471 }
8472 audioProfiles.addAllValidProfiles(profile->asAudioPort()->getAudioProfiles());
8473 }
8474 }
8475
8476 if (!isInput) {
8477 // add the direct profiles from MSD if present and has audio patches to all the output(s)
8478 const auto &msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
8479 if (msdModule != nullptr) {
8480 if (msdHasPatchesToAllDevices(devices.toTypeAddrVector())) {
8481 ALOGV("%s: MSD audio patches set to all output devices.", __func__);
8482 for (const auto &profile: msdModule->getOutputProfiles()) {
8483 if (!profile->asAudioPort()->isDirectOutput()) {
8484 continue;
8485 }
8486 audioProfiles.addAllValidProfiles(profile->asAudioPort()->getAudioProfiles());
8487 }
8488 } else {
8489 ALOGV("%s: MSD audio patches NOT set to all output devices.", __func__);
8490 }
8491 }
8492 }
8493
8494 return NO_ERROR;
8495}
8496
jiabin3ff8d7d2022-12-13 06:27:44 +00008497sp<SwAudioOutputDescriptor> AudioPolicyManager::reopenOutput(sp<SwAudioOutputDescriptor> outputDesc,
8498 const audio_config_t *config,
8499 audio_output_flags_t flags,
8500 const char* caller) {
jiabina84c3d32022-12-02 18:59:55 +00008501 closeOutput(outputDesc->mIoHandle);
8502 sp<SwAudioOutputDescriptor> preferredOutput = openOutputWithProfileAndDevice(
8503 outputDesc->mProfile, outputDesc->devices(), nullptr /*mixerConfig*/, config, flags);
8504 if (preferredOutput == nullptr) {
8505 ALOGE("%s failed to reopen output device=%d, caller=%s",
8506 __func__, outputDesc->devices()[0]->getId(), caller);
jiabina84c3d32022-12-02 18:59:55 +00008507 }
jiabin3ff8d7d2022-12-13 06:27:44 +00008508 return preferredOutput;
8509}
8510
8511void AudioPolicyManager::reopenOutputsWithDevices(
8512 const std::map<audio_io_handle_t, DeviceVector> &outputsToReopen) {
8513 for (const auto& [output, devices] : outputsToReopen) {
8514 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
8515 closeOutput(output);
8516 openOutputWithProfileAndDevice(desc->mProfile, devices);
8517 }
jiabina84c3d32022-12-02 18:59:55 +00008518}
8519
jiabinc44b3462022-12-08 12:52:31 -08008520PortHandleVector AudioPolicyManager::getClientsForStream(
8521 audio_stream_type_t streamType) const {
8522 PortHandleVector clients;
8523 for (size_t i = 0; i < mOutputs.size(); ++i) {
8524 PortHandleVector clientsForStream = mOutputs.valueAt(i)->getClientsForStream(streamType);
8525 clients.insert(clients.end(), clientsForStream.begin(), clientsForStream.end());
8526 }
8527 return clients;
8528}
8529
8530void AudioPolicyManager::invalidateStreams(StreamTypeVector streams) const {
8531 PortHandleVector clients;
8532 for (auto stream : streams) {
8533 PortHandleVector clientsForStream = getClientsForStream(stream);
8534 clients.insert(clients.end(), clientsForStream.begin(), clientsForStream.end());
8535 }
8536 mpClientInterface->invalidateTracks(clients);
8537}
8538
Mikhail Naganov1b2a7942017-12-08 10:18:09 -08008539} // namespace android