blob: 1328b78355d49424edfddaa7161c2b478a254b73 [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) {
Andy Hung48940382024-02-08 21:19:47 -0800125 ALOGE("Error %d while setting connected state for device %s",
126 static_cast<int>(state),
Mikhail Naganov516d3982022-02-01 23:53:59 +0000127 device->getDeviceTypeAddr().toString(false).c_str());
128 }
François Gaffie44481e72016-04-20 07:49:57 +0200129}
130
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100131status_t AudioPolicyManager::setDeviceConnectionStateInt(
132 audio_policy_dev_state_t state, const android::media::audio::common::AudioPort& port,
133 audio_format_t encodedFormat) {
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100134 if (port.ext.getTag() != AudioPortExt::device) {
135 return BAD_VALUE;
136 }
137 audio_devices_t device_type;
138 std::string device_address;
139 if (status_t status = aidl2legacy_AudioDevice_audio_device(
140 port.ext.get<AudioPortExt::device>().device, &device_type, &device_address);
141 status != OK) {
142 return status;
143 };
144 const char* device_name = port.name.c_str();
145 // connect/disconnect only 1 device at a time
146 if (!audio_is_output_device(device_type) && !audio_is_input_device(device_type))
147 return BAD_VALUE;
148
149 sp<DeviceDescriptor> device = mHwModules.getDeviceDescriptor(
150 device_type, device_address.c_str(), device_name, encodedFormat,
151 state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
Mikhail Naganovddc5f312022-06-11 00:47:52 +0000152 if (device == nullptr) {
153 return INVALID_OPERATION;
154 }
155 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
156 device->setExtraAudioDescriptors(port.extraAudioDescriptors);
157 }
158 return setDeviceConnectionStateInt(device, state);
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100159}
160
François Gaffie11d30102018-11-02 16:09:09 +0100161status_t AudioPolicyManager::setDeviceConnectionStateInt(audio_devices_t deviceType,
Eric Laurenta1d525f2015-01-29 13:36:45 -0800162 audio_policy_dev_state_t state,
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100163 const char* device_address,
164 const char* device_name,
165 audio_format_t encodedFormat) {
Atneya Nair638a6e42022-12-18 16:45:15 -0800166 media::AudioPortFw aidlPort;
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100167 if (status_t status = deviceToAudioPort(deviceType, device_address, device_name, &aidlPort);
168 status == OK) {
169 return setDeviceConnectionStateInt(state, aidlPort.hal, encodedFormat);
170 } else {
171 ALOGE("Failed to convert to AudioPort Parcelable: %s", statusToString(status).c_str());
172 return status;
173 }
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700174}
Paul McLeane743a472015-01-28 11:07:31 -0800175
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700176status_t AudioPolicyManager::setDeviceConnectionStateInt(const sp<DeviceDescriptor> &device,
177 audio_policy_dev_state_t state)
178{
Eric Laurente552edb2014-03-10 17:42:56 -0700179 // handle output devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700180 if (audio_is_output_device(device->type())) {
Eric Laurentd4692962014-05-05 18:13:44 -0700181 SortedVector <audio_io_handle_t> outputs;
182
François Gaffie11d30102018-11-02 16:09:09 +0100183 ssize_t index = mAvailableOutputDevices.indexOf(device);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700184
Eric Laurente552edb2014-03-10 17:42:56 -0700185 // save a copy of the opened output descriptors before any output is opened or closed
186 // by checkOutputsForDevice(). This will be needed by checkOutputForAllStrategies()
187 mPreviousOutputs = mOutputs;
Eric Laurent96d1dda2022-03-14 17:14:19 +0100188
189 bool wasLeUnicastActive = isLeUnicastActive();
190
Eric Laurente552edb2014-03-10 17:42:56 -0700191 switch (state)
192 {
193 // handle output device connection
Eric Laurent3ae5f312015-02-03 17:12:08 -0800194 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700195 if (index >= 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100196 ALOGW("%s() device already connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700197 return INVALID_OPERATION;
198 }
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800199 ALOGV("%s() connecting device %s format %x",
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700200 __func__, device->toString().c_str(), device->getEncodedFormat());
Eric Laurente552edb2014-03-10 17:42:56 -0700201
Eric Laurente552edb2014-03-10 17:42:56 -0700202 // register new device as available
Francois Gaffie993f3902019-04-10 15:39:27 +0200203 if (mAvailableOutputDevices.add(device) < 0) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700204 return NO_MEMORY;
Eric Laurente552edb2014-03-10 17:42:56 -0700205 }
206
François Gaffie44481e72016-04-20 07:49:57 +0200207 // Before checking outputs, broadcast connect event to allow HAL to retrieve dynamic
208 // parameters on newly connected devices (instead of opening the outputs...)
jiabinc0048632023-04-27 22:04:31 +0000209 broadcastDeviceConnectionState(device, media::DeviceConnectedState::CONNECTED);
François Gaffie44481e72016-04-20 07:49:57 +0200210
François Gaffie11d30102018-11-02 16:09:09 +0100211 if (checkOutputsForDevice(device, state, outputs) != NO_ERROR) {
212 mAvailableOutputDevices.remove(device);
François Gaffie44481e72016-04-20 07:49:57 +0200213
Francois Gaffie716e1432019-01-14 16:58:59 +0100214 mHwModules.cleanUpForDevice(device);
215
jiabinc0048632023-04-27 22:04:31 +0000216 broadcastDeviceConnectionState(device, media::DeviceConnectedState::DISCONNECTED);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700217 return INVALID_OPERATION;
218 }
François Gaffie2110e042015-03-24 08:41:51 +0100219
jiabin1c4794b2020-05-05 10:08:05 -0700220 // Populate encapsulation information when a output device is connected.
221 device->setEncapsulationInfoFromHal(mpClientInterface);
222
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700223 // outputs should never be empty here
224 ALOG_ASSERT(outputs.size() != 0, "setDeviceConnectionState():"
225 "checkOutputsForDevice() returned no outputs but status OK");
François Gaffie11d30102018-11-02 16:09:09 +0100226 ALOGV("%s() checkOutputsForDevice() returned %zu outputs", __func__, outputs.size());
Eric Laurent3ae5f312015-02-03 17:12:08 -0800227
Eric Laurent3ae5f312015-02-03 17:12:08 -0800228 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700229 // handle output device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700230 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700231 if (index < 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100232 ALOGW("%s() device not connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700233 return INVALID_OPERATION;
234 }
235
François Gaffie11d30102018-11-02 16:09:09 +0100236 ALOGV("%s() disconnecting output device %s", __func__, device->toString().c_str());
Paul McLean5c477aa2014-08-20 16:47:57 -0700237
jiabinc0048632023-04-27 22:04:31 +0000238 // Notify the HAL to prepare to disconnect device
239 broadcastDeviceConnectionState(
240 device, media::DeviceConnectedState::PREPARE_TO_DISCONNECT);
Paul McLean5c477aa2014-08-20 16:47:57 -0700241
Eric Laurente552edb2014-03-10 17:42:56 -0700242 // remove device from available output devices
François Gaffie11d30102018-11-02 16:09:09 +0100243 mAvailableOutputDevices.remove(device);
Eric Laurente552edb2014-03-10 17:42:56 -0700244
Francois Gaffieba2cf0f2018-12-12 16:40:25 +0100245 mOutputs.clearSessionRoutesForDevice(device);
246
François Gaffie11d30102018-11-02 16:09:09 +0100247 checkOutputsForDevice(device, state, outputs);
François Gaffie2110e042015-03-24 08:41:51 +0100248
jiabinc0048632023-04-27 22:04:31 +0000249 // Send Disconnect to HALs
250 broadcastDeviceConnectionState(device, media::DeviceConnectedState::DISCONNECTED);
251
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800252 // Reset active device codec
253 device->setEncodedFormat(AUDIO_FORMAT_DEFAULT);
254
Kriti Dangef6be8f2020-11-05 11:58:19 +0100255 // remove device from mReportedFormatsMap cache
256 mReportedFormatsMap.erase(device);
257
jiabina84c3d32022-12-02 18:59:55 +0000258 // remove preferred mixer configurations
259 mPreferredMixerAttrInfos.erase(device->getId());
260
Eric Laurente552edb2014-03-10 17:42:56 -0700261 } break;
262
263 default:
François Gaffie11d30102018-11-02 16:09:09 +0100264 ALOGE("%s() invalid state: %x", __func__, state);
Eric Laurente552edb2014-03-10 17:42:56 -0700265 return BAD_VALUE;
266 }
267
Eric Laurent736a1022019-03-27 18:28:46 -0700268 // Propagate device availability to Engine
269 setEngineDeviceConnectionState(device, state);
270
Eric Laurentae970022019-01-29 14:25:04 -0800271 // No need to evaluate playback routing when connecting a remote submix
272 // output device used by a dynamic policy of type recorder as no
273 // playback use case is affected.
274 bool doCheckForDeviceAndOutputChanges = true;
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700275 if (device->type() == AUDIO_DEVICE_OUT_REMOTE_SUBMIX && device->address() != "0") {
Eric Laurentae970022019-01-29 14:25:04 -0800276 for (audio_io_handle_t output : outputs) {
277 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
Mikhail Naganovbfac5832019-03-05 16:55:28 -0800278 sp<AudioPolicyMix> policyMix = desc->mPolicyMix.promote();
279 if (policyMix != nullptr
280 && policyMix->mMixType == MIX_TYPE_RECORDERS
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +0000281 && device->address() == policyMix->mDeviceAddress.c_str()) {
Eric Laurentae970022019-01-29 14:25:04 -0800282 doCheckForDeviceAndOutputChanges = false;
283 break;
284 }
285 }
286 }
287
288 auto checkCloseOutputs = [&]() {
Mikhail Naganov37977152018-07-11 15:54:44 -0700289 // outputs must be closed after checkOutputForAllStrategies() is executed
290 if (!outputs.isEmpty()) {
291 for (audio_io_handle_t output : outputs) {
292 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
François Gaffie11d30102018-11-02 16:09:09 +0100293 // close unused outputs after device disconnection or direct outputs that have
294 // been opened by checkOutputsForDevice() to query dynamic parameters
Eric Laurente191d1b2022-04-15 11:59:25 +0200295 // "outputs" vector never contains duplicated outputs
Eric Laurentcad6c0d2021-07-13 15:12:39 +0200296 if ((state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE)
297 || (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != 0) &&
Eric Laurente191d1b2022-04-15 11:59:25 +0200298 (desc->mDirectOpenCount == 0))
299 || (((desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0) &&
300 !isOutputOnlyAvailableRouteToSomeDevice(desc))) {
Francois Gaffieff1eb522020-05-06 18:37:04 +0200301 clearAudioSourcesForOutput(output);
Mikhail Naganov37977152018-07-11 15:54:44 -0700302 closeOutput(output);
303 }
Eric Laurente552edb2014-03-10 17:42:56 -0700304 }
Mikhail Naganov37977152018-07-11 15:54:44 -0700305 // check A2DP again after closing A2DP output to reset mA2dpSuspended if needed
306 return true;
Eric Laurente552edb2014-03-10 17:42:56 -0700307 }
Mikhail Naganov37977152018-07-11 15:54:44 -0700308 return false;
Eric Laurentae970022019-01-29 14:25:04 -0800309 };
310
311 if (doCheckForDeviceAndOutputChanges) {
312 checkForDeviceAndOutputChanges(checkCloseOutputs);
313 } else {
314 checkCloseOutputs();
315 }
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100316 (void)updateCallRouting(false /*fromCache*/);
François Gaffie11d30102018-11-02 16:09:09 +0100317 const DeviceVector msdOutDevices = getMsdAudioOutDevices();
jiabinbce0c1d2020-10-05 11:20:18 -0700318 const DeviceVector activeMediaDevices =
319 mEngine->getActiveMediaDevices(mAvailableOutputDevices);
jiabin3ff8d7d2022-12-13 06:27:44 +0000320 std::map<audio_io_handle_t, DeviceVector> outputsToReopenWithDevices;
Eric Laurente552edb2014-03-10 17:42:56 -0700321 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700322 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Jaideep Sharma89b5b852020-11-23 16:41:33 +0530323 if (desc->isActive() && ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) ||
324 (desc != mPrimaryOutput))) {
François Gaffie11d30102018-11-02 16:09:09 +0100325 DeviceVector newDevices = getNewOutputDevices(desc, true /*fromCache*/);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700326 // do not force device change on duplicated output because if device is 0, it will
327 // also force a device 0 for the two outputs it is duplicated to which may override
328 // a valid device selection on those outputs.
François Gaffie11d30102018-11-02 16:09:09 +0100329 bool force = (msdOutDevices.isEmpty() || msdOutDevices != desc->devices())
Mikhail Naganov15be9d22017-11-08 14:18:13 +1100330 && !desc->isDuplicated()
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700331 && (!device_distinguishes_on_address(device->type())
Eric Laurentc2730ba2014-07-20 15:47:07 -0700332 // always force when disconnecting (a non-duplicated device)
333 || (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE));
jiabin3ff8d7d2022-12-13 06:27:44 +0000334 if (desc->mUsePreferredMixerAttributes && newDevices != desc->devices()) {
335 // If the device is using preferred mixer attributes, the output need to reopen
336 // with default configuration when the new selected devices are different from
337 // current routing devices
338 outputsToReopenWithDevices.emplace(mOutputs.keyAt(i), newDevices);
339 continue;
340 }
François Gaffie11d30102018-11-02 16:09:09 +0100341 setOutputDevices(desc, newDevices, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700342 }
jiabinbce0c1d2020-10-05 11:20:18 -0700343 if (!desc->isDuplicated() && desc->mProfile->hasDynamicAudioProfile() &&
jiabin498d2152021-04-02 00:26:46 +0000344 !activeMediaDevices.empty() && desc->devices() != activeMediaDevices &&
jiabinbce0c1d2020-10-05 11:20:18 -0700345 desc->supportsDevicesForPlayback(activeMediaDevices)) {
346 // Reopen the output to query the dynamic profiles when there is not active
347 // clients or all active clients will be rerouted. Otherwise, set the flag
348 // `mPendingReopenToQueryProfiles` in the SwOutputDescriptor so that the output
349 // can be reopened to query dynamic profiles when all clients are inactive.
350 if (areAllActiveTracksRerouted(desc)) {
jiabin3ff8d7d2022-12-13 06:27:44 +0000351 outputsToReopenWithDevices.emplace(mOutputs.keyAt(i), activeMediaDevices);
jiabinbce0c1d2020-10-05 11:20:18 -0700352 } else {
353 desc->mPendingReopenToQueryProfiles = true;
354 }
355 }
356 if (!desc->supportsDevicesForPlayback(activeMediaDevices)) {
357 // Clear the flag that previously set for re-querying profiles.
358 desc->mPendingReopenToQueryProfiles = false;
359 }
360 }
jiabin3ff8d7d2022-12-13 06:27:44 +0000361 reopenOutputsWithDevices(outputsToReopenWithDevices);
Eric Laurente552edb2014-03-10 17:42:56 -0700362
Eric Laurentd60560a2015-04-10 11:31:20 -0700363 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
François Gaffie11d30102018-11-02 16:09:09 +0100364 cleanUpForDevice(device);
Eric Laurentd60560a2015-04-10 11:31:20 -0700365 }
366
Eric Laurent96d1dda2022-03-14 17:14:19 +0100367 checkLeBroadcastRoutes(wasLeUnicastActive, nullptr, 0);
368
Eric Laurent72aa32f2014-05-30 18:51:48 -0700369 mpClientInterface->onAudioPortListUpdate();
Eric Laurentb71e58b2014-05-29 16:08:11 -0700370 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700371 } // end if is output device
372
Eric Laurente552edb2014-03-10 17:42:56 -0700373 // handle input devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700374 if (audio_is_input_device(device->type())) {
François Gaffie11d30102018-11-02 16:09:09 +0100375 ssize_t index = mAvailableInputDevices.indexOf(device);
Eric Laurente552edb2014-03-10 17:42:56 -0700376 switch (state)
377 {
378 // handle input device connection
Eric Laurent3b73df72014-03-11 09:06:29 -0700379 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700380 if (index >= 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100381 ALOGW("%s() device already connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700382 return INVALID_OPERATION;
383 }
Eric Laurent0dd51852019-04-19 18:18:58 -0700384
385 if (mAvailableInputDevices.add(device) < 0) {
386 return NO_MEMORY;
387 }
388
François Gaffie44481e72016-04-20 07:49:57 +0200389 // Before checking intputs, broadcast connect event to allow HAL to retrieve dynamic
390 // parameters on newly connected devices (instead of opening the inputs...)
jiabinc0048632023-04-27 22:04:31 +0000391 broadcastDeviceConnectionState(device, media::DeviceConnectedState::CONNECTED);
François Gaffie44481e72016-04-20 07:49:57 +0200392
Eric Laurent0dd51852019-04-19 18:18:58 -0700393 if (checkInputsForDevice(device, state) != NO_ERROR) {
394 mAvailableInputDevices.remove(device);
395
jiabinc0048632023-04-27 22:04:31 +0000396 broadcastDeviceConnectionState(device, media::DeviceConnectedState::DISCONNECTED);
Francois Gaffie716e1432019-01-14 16:58:59 +0100397
398 mHwModules.cleanUpForDevice(device);
399
Eric Laurentd4692962014-05-05 18:13:44 -0700400 return INVALID_OPERATION;
401 }
402
Eric Laurentd4692962014-05-05 18:13:44 -0700403 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700404
405 // handle input device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700406 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700407 if (index < 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100408 ALOGW("%s() device not connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700409 return INVALID_OPERATION;
410 }
Paul McLean5c477aa2014-08-20 16:47:57 -0700411
François Gaffie11d30102018-11-02 16:09:09 +0100412 ALOGV("%s() disconnecting input device %s", __func__, device->toString().c_str());
Paul McLean5c477aa2014-08-20 16:47:57 -0700413
jiabinc0048632023-04-27 22:04:31 +0000414 // Notify the HAL to prepare to disconnect device
415 broadcastDeviceConnectionState(
416 device, media::DeviceConnectedState::PREPARE_TO_DISCONNECT);
Paul McLean5c477aa2014-08-20 16:47:57 -0700417
François Gaffie11d30102018-11-02 16:09:09 +0100418 mAvailableInputDevices.remove(device);
Eric Laurent0dd51852019-04-19 18:18:58 -0700419
420 checkInputsForDevice(device, state);
Kriti Dangef6be8f2020-11-05 11:58:19 +0100421
jiabinc0048632023-04-27 22:04:31 +0000422 // Set Disconnect to HALs
423 broadcastDeviceConnectionState(device, media::DeviceConnectedState::DISCONNECTED);
424
Kriti Dangef6be8f2020-11-05 11:58:19 +0100425 // remove device from mReportedFormatsMap cache
426 mReportedFormatsMap.erase(device);
Eric Laurentd4692962014-05-05 18:13:44 -0700427 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700428
429 default:
François Gaffie11d30102018-11-02 16:09:09 +0100430 ALOGE("%s() invalid state: %x", __func__, state);
Eric Laurente552edb2014-03-10 17:42:56 -0700431 return BAD_VALUE;
432 }
433
Eric Laurent736a1022019-03-27 18:28:46 -0700434 // Propagate device availability to Engine
435 setEngineDeviceConnectionState(device, state);
436
Eric Laurent0dd51852019-04-19 18:18:58 -0700437 checkCloseInputs();
Eric Laurent5f5fca52016-08-04 11:48:57 -0700438 // As the input device list can impact the output device selection, update
439 // getDeviceForStrategy() cache
440 updateDevicesAndOutputs();
Eric Laurente552edb2014-03-10 17:42:56 -0700441
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100442 (void)updateCallRouting(false /*fromCache*/);
Francois Gaffiea0e5c992020-09-29 16:05:07 +0200443 // Reconnect Audio Source
444 for (const auto &strategy : mEngine->getOrderedProductStrategies()) {
445 auto attributes = mEngine->getAllAttributesForProductStrategy(strategy).front();
446 checkAudioSourceForAttributes(attributes);
447 }
Eric Laurentd60560a2015-04-10 11:31:20 -0700448 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
François Gaffie11d30102018-11-02 16:09:09 +0100449 cleanUpForDevice(device);
Eric Laurentd60560a2015-04-10 11:31:20 -0700450 }
451
Eric Laurentb52c1522014-05-20 11:27:36 -0700452 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -0700453 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700454 } // end if is input device
Eric Laurente552edb2014-03-10 17:42:56 -0700455
François Gaffie11d30102018-11-02 16:09:09 +0100456 ALOGW("%s() invalid device: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700457 return BAD_VALUE;
458}
459
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100460status_t AudioPolicyManager::deviceToAudioPort(audio_devices_t device, const char* device_address,
461 const char* device_name,
Atneya Nair638a6e42022-12-18 16:45:15 -0800462 media::AudioPortFw* aidlPort) {
Andy Hunged722372023-09-18 22:00:21 +0000463 const auto devDescr = sp<DeviceDescriptorBase>::make(device, device_address);
464 devDescr->setName(device_name);
465 return devDescr->writeToParcelable(aidlPort);
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100466}
467
Eric Laurent736a1022019-03-27 18:28:46 -0700468void AudioPolicyManager::setEngineDeviceConnectionState(const sp<DeviceDescriptor> device,
469 audio_policy_dev_state_t state) {
470
471 // the Engine does not have to know about remote submix devices used by dynamic audio policies
472 if (audio_is_remote_submix_device(device->type()) && device->address() != "0") {
473 return;
474 }
475 mEngine->setDeviceConnectionState(device, state);
476}
477
478
Eric Laurente0720872014-03-11 09:30:41 -0700479audio_policy_dev_state_t AudioPolicyManager::getDeviceConnectionState(audio_devices_t device,
François Gaffie53615e22015-03-19 09:24:12 +0100480 const char *device_address)
Eric Laurente552edb2014-03-10 17:42:56 -0700481{
Eric Laurent634b7142016-04-20 13:48:02 -0700482 sp<DeviceDescriptor> devDesc =
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800483 mHwModules.getDeviceDescriptor(device, device_address, "", AUDIO_FORMAT_DEFAULT,
484 false /* allowToCreate */,
Eric Laurent634b7142016-04-20 13:48:02 -0700485 (strlen(device_address) != 0)/*matchAddress*/);
486
487 if (devDesc == 0) {
François Gaffie251c7f02018-11-07 10:41:08 +0100488 ALOGV("getDeviceConnectionState() undeclared device, type %08x, address: %s",
Eric Laurent634b7142016-04-20 13:48:02 -0700489 device, device_address);
490 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
491 }
François Gaffie53615e22015-03-19 09:24:12 +0100492
Eric Laurent3a4311c2014-03-17 12:00:47 -0700493 DeviceVector *deviceVector;
494
Eric Laurente552edb2014-03-10 17:42:56 -0700495 if (audio_is_output_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700496 deviceVector = &mAvailableOutputDevices;
Eric Laurente552edb2014-03-10 17:42:56 -0700497 } else if (audio_is_input_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700498 deviceVector = &mAvailableInputDevices;
499 } else {
François Gaffie11d30102018-11-02 16:09:09 +0100500 ALOGW("%s() invalid device type %08x", __func__, device);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700501 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurente552edb2014-03-10 17:42:56 -0700502 }
Eric Laurent634b7142016-04-20 13:48:02 -0700503
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800504 return (deviceVector->getDevice(
505 device, String8(device_address), AUDIO_FORMAT_DEFAULT) != 0) ?
Eric Laurent634b7142016-04-20 13:48:02 -0700506 AUDIO_POLICY_DEVICE_STATE_AVAILABLE : AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurenta1d525f2015-01-29 13:36:45 -0800507}
508
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800509status_t AudioPolicyManager::handleDeviceConfigChange(audio_devices_t device,
510 const char *device_address,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800511 const char *device_name,
512 audio_format_t encodedFormat)
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800513{
514 status_t status;
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700515 String8 reply;
516 AudioParameter param;
517 int isReconfigA2dpSupported = 0;
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800518
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800519 ALOGV("handleDeviceConfigChange(() device: 0x%X, address %s name %s encodedFormat: 0x%X",
520 device, device_address, device_name, encodedFormat);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800521
Pavlin Radoslavovc694ff42017-01-09 23:27:29 -0800522 // connect/disconnect only 1 device at a time
523 if (!audio_is_output_device(device) && !audio_is_input_device(device)) return BAD_VALUE;
524
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800525 // Check if the device is currently connected
jiabin9a3361e2019-10-01 09:38:30 -0700526 DeviceVector deviceList = mAvailableOutputDevices.getDevicesFromType(device);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800527 if (deviceList.empty()) {
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800528 // Nothing to do: device is not connected
529 return NO_ERROR;
530 }
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800531 sp<DeviceDescriptor> devDesc = deviceList.itemAt(0);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800532
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700533 // For offloaded A2DP, Hw modules may have the capability to
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800534 // configure codecs.
535 // Handle two specific cases by sending a set parameter to
536 // configure A2DP codecs. No need to toggle device state.
537 // Case 1: A2DP active device switches from primary to primary
538 // module
539 // Case 2: A2DP device config changes on primary module.
Francois Gaffiebce7cd42020-10-14 16:13:20 +0200540 if (audio_is_a2dp_out_device(device) && hasPrimaryOutput()) {
jiabin9a3361e2019-10-01 09:38:30 -0700541 sp<HwModule> module = mHwModules.getModuleForDeviceType(device, encodedFormat);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800542 audio_module_handle_t primaryHandle = mPrimaryOutput->getModuleHandle();
543 if (availablePrimaryOutputDevices().contains(devDesc) &&
544 (module != 0 && module->getHandle() == primaryHandle)) {
545 reply = mpClientInterface->getParameters(
546 AUDIO_IO_HANDLE_NONE,
547 String8(AudioParameter::keyReconfigA2dpSupported));
548 AudioParameter repliedParameters(reply);
549 repliedParameters.getInt(
550 String8(AudioParameter::keyReconfigA2dpSupported), isReconfigA2dpSupported);
551 if (isReconfigA2dpSupported) {
552 const String8 key(AudioParameter::keyReconfigA2dp);
553 param.add(key, String8("true"));
554 mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString());
555 devDesc->setEncodedFormat(encodedFormat);
556 return NO_ERROR;
557 }
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700558 }
559 }
cnx421bd2dcc42020-07-11 14:58:44 +0800560 auto musicStrategy = streamToStrategy(AUDIO_STREAM_MUSIC);
561 for (size_t i = 0; i < mOutputs.size(); i++) {
562 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
563 // mute media strategies and delay device switch by the largest
564 // This avoid sending the music tail into the earpiece or headset.
565 setStrategyMute(musicStrategy, true, desc);
566 setStrategyMute(musicStrategy, false, desc, MUTE_TIME_MS,
567 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
568 nullptr, true /*fromCache*/).types());
569 }
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800570 // Toggle the device state: UNAVAILABLE -> AVAILABLE
571 // This will force reading again the device configuration
572 status = setDeviceConnectionState(device,
573 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800574 device_address, device_name,
575 devDesc->getEncodedFormat());
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800576 if (status != NO_ERROR) {
577 ALOGW("handleDeviceConfigChange() error disabling connection state: %d",
578 status);
579 return status;
580 }
581
582 status = setDeviceConnectionState(device,
583 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800584 device_address, device_name, encodedFormat);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800585 if (status != NO_ERROR) {
586 ALOGW("handleDeviceConfigChange() error enabling connection state: %d",
587 status);
588 return status;
589 }
590
591 return NO_ERROR;
592}
593
Pattydd807582021-11-04 21:01:03 +0800594status_t AudioPolicyManager::getHwOffloadFormatsSupportedForBluetoothMedia(
595 audio_devices_t device, std::vector<audio_format_t> *formats)
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800596{
Pattydd807582021-11-04 21:01:03 +0800597 ALOGV("getHwOffloadFormatsSupportedForBluetoothMedia()");
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800598 status_t status = NO_ERROR;
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800599 std::unordered_set<audio_format_t> formatSet;
600 sp<HwModule> primaryModule =
601 mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_PRIMARY);
Aniket Kumar Latafedb5982019-07-03 11:20:36 -0700602 if (primaryModule == nullptr) {
603 ALOGE("%s() unable to get primary module", __func__);
604 return NO_INIT;
605 }
Pattydd807582021-11-04 21:01:03 +0800606
607 DeviceTypeSet audioDeviceSet;
608
609 switch(device) {
610 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP:
611 audioDeviceSet = getAudioDeviceOutAllA2dpSet();
612 break;
613 case AUDIO_DEVICE_OUT_BLE_HEADSET:
Patty Huang36028df2022-07-06 00:14:12 +0800614 audioDeviceSet = getAudioDeviceOutLeAudioUnicastSet();
615 break;
616 case AUDIO_DEVICE_OUT_BLE_BROADCAST:
617 audioDeviceSet = getAudioDeviceOutLeAudioBroadcastSet();
Pattydd807582021-11-04 21:01:03 +0800618 break;
619 default:
620 ALOGE("%s() device type 0x%08x not supported", __func__, device);
621 return BAD_VALUE;
622 }
623
jiabin9a3361e2019-10-01 09:38:30 -0700624 DeviceVector declaredDevices = primaryModule->getDeclaredDevices().getDevicesFromTypes(
Pattydd807582021-11-04 21:01:03 +0800625 audioDeviceSet);
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800626 for (const auto& device : declaredDevices) {
627 formatSet.insert(device->encodedFormats().begin(), device->encodedFormats().end());
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800628 }
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800629 formats->assign(formatSet.begin(), formatSet.end());
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800630 return status;
631}
632
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100633DeviceVector AudioPolicyManager::selectBestRxSinkDevicesForCall(bool fromCache)
634{
635 DeviceVector rxSinkdevices{};
636 rxSinkdevices = mEngine->getOutputDevicesForAttributes(
637 attributes_initializer(AUDIO_USAGE_VOICE_COMMUNICATION), nullptr, fromCache);
638 if (!rxSinkdevices.isEmpty() && mAvailableOutputDevices.contains(rxSinkdevices.itemAt(0))) {
639 auto rxSinkDevice = rxSinkdevices.itemAt(0);
640 auto telephonyRxModule = mHwModules.getModuleForDeviceType(
641 AUDIO_DEVICE_IN_TELEPHONY_RX, AUDIO_FORMAT_DEFAULT);
642 // retrieve Rx Source device descriptor
643 sp<DeviceDescriptor> rxSourceDevice = mAvailableInputDevices.getDevice(
644 AUDIO_DEVICE_IN_TELEPHONY_RX, String8(), AUDIO_FORMAT_DEFAULT);
645
646 // RX Telephony and Rx sink devices are declared by Primary Audio HAL
647 if (isPrimaryModule(telephonyRxModule) && (telephonyRxModule->getHalVersionMajor() >= 3) &&
648 telephonyRxModule->supportsPatch(rxSourceDevice, rxSinkDevice)) {
649 ALOGW("%s() device %s using HW Bridge", __func__, rxSinkDevice->toString().c_str());
650 return DeviceVector(rxSinkDevice);
651 }
652 }
653 // Note that despite the fact that getNewOutputDevices() is called on the primary output,
654 // the device returned is not necessarily reachable via this output
655 // (filter later by setOutputDevices())
656 return getNewOutputDevices(mPrimaryOutput, fromCache);
657}
658
659status_t AudioPolicyManager::updateCallRouting(bool fromCache, uint32_t delayMs, uint32_t *waitMs)
660{
661 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL && hasPrimaryOutput()) {
662 DeviceVector rxDevices = selectBestRxSinkDevicesForCall(fromCache);
663 return updateCallRoutingInternal(rxDevices, delayMs, waitMs);
664 }
665 return INVALID_OPERATION;
666}
667
668status_t AudioPolicyManager::updateCallRoutingInternal(
669 const DeviceVector &rxDevices, uint32_t delayMs, uint32_t *waitMs)
Eric Laurentc2730ba2014-07-20 15:47:07 -0700670{
671 bool createTxPatch = false;
François Gaffie9eb18552018-11-05 10:33:26 +0100672 bool createRxPatch = false;
Eric Laurentdc462862016-07-19 12:29:53 -0700673 uint32_t muteWaitMs = 0;
jiabin9a3361e2019-10-01 09:38:30 -0700674 if(!hasPrimaryOutput() ||
675 mPrimaryOutput->devices().onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_STUB)) {
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100676 return INVALID_OPERATION;
Eric Laurent87ffa392015-05-22 10:32:38 -0700677 }
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100678 ALOG_ASSERT(!rxDevices.isEmpty(), "%s() no selected output device", __func__);
François Gaffie11d30102018-11-02 16:09:09 +0100679
Francois Gaffie716e1432019-01-14 16:58:59 +0100680 audio_attributes_t attr = { .source = AUDIO_SOURCE_VOICE_COMMUNICATION };
François Gaffiec005e562018-11-06 15:04:49 +0100681 auto txSourceDevice = mEngine->getInputDeviceForAttributes(attr);
Eric Laurentcedd5b52023-03-22 00:03:31 +0000682 if (txSourceDevice == nullptr) {
683 ALOGE("%s() selected input device not available", __func__);
684 return INVALID_OPERATION;
685 }
François Gaffiec005e562018-11-06 15:04:49 +0100686
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100687 ALOGV("%s device rxDevice %s txDevice %s", __func__,
François Gaffie9eb18552018-11-05 10:33:26 +0100688 rxDevices.itemAt(0)->toString().c_str(), txSourceDevice->toString().c_str());
Eric Laurentc2730ba2014-07-20 15:47:07 -0700689
Francois Gaffie601801d2021-06-22 13:27:39 +0200690 disconnectTelephonyAudioSource(mCallRxSourceClient);
691 disconnectTelephonyAudioSource(mCallTxSourceClient);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700692
François Gaffie9eb18552018-11-05 10:33:26 +0100693 auto telephonyRxModule =
jiabin9a3361e2019-10-01 09:38:30 -0700694 mHwModules.getModuleForDeviceType(AUDIO_DEVICE_IN_TELEPHONY_RX, AUDIO_FORMAT_DEFAULT);
François Gaffie9eb18552018-11-05 10:33:26 +0100695 auto telephonyTxModule =
jiabin9a3361e2019-10-01 09:38:30 -0700696 mHwModules.getModuleForDeviceType(AUDIO_DEVICE_OUT_TELEPHONY_TX, AUDIO_FORMAT_DEFAULT);
François Gaffie9eb18552018-11-05 10:33:26 +0100697 // retrieve Rx Source and Tx Sink device descriptors
698 sp<DeviceDescriptor> rxSourceDevice =
699 mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_TELEPHONY_RX,
700 String8(),
701 AUDIO_FORMAT_DEFAULT);
702 sp<DeviceDescriptor> txSinkDevice =
703 mAvailableOutputDevices.getDevice(AUDIO_DEVICE_OUT_TELEPHONY_TX,
704 String8(),
705 AUDIO_FORMAT_DEFAULT);
706
707 // RX and TX Telephony device are declared by Primary Audio HAL
708 if (isPrimaryModule(telephonyRxModule) && isPrimaryModule(telephonyTxModule) &&
709 (telephonyRxModule->getHalVersionMajor() >= 3)) {
710 if (rxSourceDevice == 0 || txSinkDevice == 0) {
711 // RX / TX Telephony device(s) is(are) not currently available
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100712 ALOGE("%s() no telephony Tx and/or RX device", __func__);
713 return INVALID_OPERATION;
François Gaffie9eb18552018-11-05 10:33:26 +0100714 }
François Gaffieafd4cea2019-11-18 15:50:22 +0100715 // createAudioPatchInternal now supports both HW / SW bridging
716 createRxPatch = true;
717 createTxPatch = true;
François Gaffie9eb18552018-11-05 10:33:26 +0100718 } else {
719 // If the RX device is on the primary HW module, then use legacy routing method for
720 // voice calls via setOutputDevice() on primary output.
721 // Otherwise, create two audio patches for TX and RX path.
722 createRxPatch = !(availablePrimaryOutputDevices().contains(rxDevices.itemAt(0))) &&
723 (rxSourceDevice != 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700724 // If the TX device is also on the primary HW module, setOutputDevice() will take care
725 // of it due to legacy implementation. If not, create a patch.
François Gaffie9eb18552018-11-05 10:33:26 +0100726 createTxPatch = !(availablePrimaryModuleInputDevices().contains(txSourceDevice)) &&
727 (txSinkDevice != 0);
728 }
729 // Use legacy routing method for voice calls via setOutputDevice() on primary output.
730 // Otherwise, create two audio patches for TX and RX path.
731 if (!createRxPatch) {
732 muteWaitMs = setOutputDevices(mPrimaryOutput, rxDevices, true, delayMs);
Eric Laurent8ae73122016-04-12 10:13:29 -0700733 } else { // create RX path audio patch
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200734 connectTelephonyRxAudioSource();
juyuchen2224c5a2019-01-21 12:00:58 +0800735 // If the TX device is on the primary HW module but RX device is
736 // on other HW module, SinkMetaData of telephony input should handle it
737 // assuming the device uses audio HAL V5.0 and above
Eric Laurentc2730ba2014-07-20 15:47:07 -0700738 }
Eric Laurent8ae73122016-04-12 10:13:29 -0700739 if (createTxPatch) { // create TX path audio patch
François Gaffieafd4cea2019-11-18 15:50:22 +0100740 // terminate active capture if on the same HW module as the call TX source device
741 // FIXME: would be better to refine to only inputs whose profile connects to the
742 // call TX device but this information is not in the audio patch and logic here must be
743 // symmetric to the one in startInput()
744 for (const auto& activeDesc : mInputs.getActiveInputs()) {
745 if (activeDesc->hasSameHwModuleAs(txSourceDevice)) {
746 closeActiveClients(activeDesc);
747 }
748 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200749 connectTelephonyTxAudioSource(txSourceDevice, txSinkDevice, delayMs);
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800750 }
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100751 if (waitMs != nullptr) {
752 *waitMs = muteWaitMs;
753 }
754 return NO_ERROR;
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800755}
Eric Laurentc2730ba2014-07-20 15:47:07 -0700756
Mikhail Naganov100f0122018-11-29 11:22:16 -0800757bool AudioPolicyManager::isDeviceOfModule(
758 const sp<DeviceDescriptor>& devDesc, const char *moduleId) const {
759 sp<HwModule> module = mHwModules.getModuleFromName(moduleId);
760 if (module != 0) {
761 return mAvailableOutputDevices.getDevicesFromHwModule(module->getHandle())
762 .indexOf(devDesc) != NAME_NOT_FOUND
763 || mAvailableInputDevices.getDevicesFromHwModule(module->getHandle())
764 .indexOf(devDesc) != NAME_NOT_FOUND;
765 }
766 return false;
767}
768
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200769void AudioPolicyManager::connectTelephonyRxAudioSource()
770{
Francois Gaffie601801d2021-06-22 13:27:39 +0200771 disconnectTelephonyAudioSource(mCallRxSourceClient);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200772 const struct audio_port_config source = {
773 .role = AUDIO_PORT_ROLE_SOURCE, .type = AUDIO_PORT_TYPE_DEVICE,
774 .ext.device.type = AUDIO_DEVICE_IN_TELEPHONY_RX, .ext.device.address = ""
775 };
776 const auto aa = mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL);
Francois Gaffie601801d2021-06-22 13:27:39 +0200777 mCallRxSourceClient = startAudioSourceInternal(&source, &aa, 0/*uid*/);
778 ALOGE_IF(mCallRxSourceClient == nullptr,
779 "%s failed to start Telephony Rx AudioSource", __func__);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200780}
781
Francois Gaffie601801d2021-06-22 13:27:39 +0200782void AudioPolicyManager::disconnectTelephonyAudioSource(sp<SourceClientDescriptor> &clientDesc)
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200783{
Francois Gaffie601801d2021-06-22 13:27:39 +0200784 if (clientDesc == nullptr) {
785 return;
786 }
787 ALOGW_IF(stopAudioSource(clientDesc->portId()) != NO_ERROR,
788 "%s error stopping audio source", __func__);
789 clientDesc.clear();
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200790}
791
792void AudioPolicyManager::connectTelephonyTxAudioSource(
793 const sp<DeviceDescriptor> &srcDevice, const sp<DeviceDescriptor> &sinkDevice,
794 uint32_t delayMs)
795{
Francois Gaffie601801d2021-06-22 13:27:39 +0200796 disconnectTelephonyAudioSource(mCallTxSourceClient);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200797 if (srcDevice == nullptr || sinkDevice == nullptr) {
798 ALOGW("%s could not create patch, invalid sink and/or source device(s)", __func__);
799 return;
800 }
801 PatchBuilder patchBuilder;
802 patchBuilder.addSource(srcDevice).addSink(sinkDevice);
803 ALOGV("%s between source %s and sink %s", __func__,
804 srcDevice->toString().c_str(), sinkDevice->toString().c_str());
Francois Gaffie601801d2021-06-22 13:27:39 +0200805 auto callTxSourceClientPortId = PolicyAudioPort::getNextUniqueId();
Eric Laurent78b07302022-10-07 16:20:34 +0200806 const auto aa = mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL);
807
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200808 struct audio_port_config source = {};
809 srcDevice->toAudioPortConfig(&source);
Francois Gaffie601801d2021-06-22 13:27:39 +0200810 mCallTxSourceClient = new InternalSourceClientDescriptor(
811 callTxSourceClientPortId, mUidCached, aa, source, srcDevice, sinkDevice,
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200812 mCommunnicationStrategy, toVolumeSource(aa));
813 audio_patch_handle_t patchHandle = AUDIO_PATCH_HANDLE_NONE;
814 status_t status = connectAudioSourceToSink(
Francois Gaffie601801d2021-06-22 13:27:39 +0200815 mCallTxSourceClient, sinkDevice, patchBuilder.patch(), patchHandle, mUidCached,
816 delayMs);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200817 ALOGE_IF(status != NO_ERROR, "%s() error %d creating TX audio patch", __func__, status);
818 if (status == NO_ERROR) {
Francois Gaffie601801d2021-06-22 13:27:39 +0200819 mAudioSources.add(callTxSourceClientPortId, mCallTxSourceClient);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200820 }
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200821}
822
Eric Laurente0720872014-03-11 09:30:41 -0700823void AudioPolicyManager::setPhoneState(audio_mode_t state)
Eric Laurente552edb2014-03-10 17:42:56 -0700824{
825 ALOGV("setPhoneState() state %d", state);
François Gaffie2110e042015-03-24 08:41:51 +0100826 // store previous phone state for management of sonification strategy below
827 int oldState = mEngine->getPhoneState();
Eric Laurent96d1dda2022-03-14 17:14:19 +0100828 bool wasLeUnicastActive = isLeUnicastActive();
François Gaffie2110e042015-03-24 08:41:51 +0100829
830 if (mEngine->setPhoneState(state) != NO_ERROR) {
831 ALOGW("setPhoneState() invalid or same state %d", state);
Eric Laurente552edb2014-03-10 17:42:56 -0700832 return;
833 }
François Gaffie2110e042015-03-24 08:41:51 +0100834 /// Opens: can these line be executed after the switch of volume curves???
Eric Laurent63dea1d2015-07-02 17:10:28 -0700835 if (isStateInCall(oldState)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700836 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent63dea1d2015-07-02 17:10:28 -0700837 // force reevaluating accessibility routing when call stops
jiabinc44b3462022-12-08 12:52:31 -0800838 invalidateStreams({AUDIO_STREAM_ACCESSIBILITY});
Eric Laurente552edb2014-03-10 17:42:56 -0700839 }
840
François Gaffie2110e042015-03-24 08:41:51 +0100841 /**
842 * Switching to or from incall state or switching between telephony and VoIP lead to force
843 * routing command.
844 */
Eric Laurent74b71512019-11-06 17:21:57 -0800845 bool force = ((isStateInCall(oldState) != isStateInCall(state))
846 || (isStateInCall(state) && (state != oldState)));
Eric Laurente552edb2014-03-10 17:42:56 -0700847
848 // check for device and output changes triggered by new phone state
Mikhail Naganov37977152018-07-11 15:54:44 -0700849 checkForDeviceAndOutputChanges();
Eric Laurente552edb2014-03-10 17:42:56 -0700850
Eric Laurente552edb2014-03-10 17:42:56 -0700851 int delayMs = 0;
852 if (isStateInCall(state)) {
853 nsecs_t sysTime = systemTime();
François Gaffiec005e562018-11-06 15:04:49 +0100854 auto musicStrategy = streamToStrategy(AUDIO_STREAM_MUSIC);
855 auto sonificationStrategy = streamToStrategy(AUDIO_STREAM_ALARM);
Eric Laurente552edb2014-03-10 17:42:56 -0700856 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700857 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700858 // mute media and sonification strategies and delay device switch by the largest
859 // latency of any output where either strategy is active.
860 // This avoid sending the ring tone or music tail into the earpiece or headset.
François Gaffiec005e562018-11-06 15:04:49 +0100861 if ((desc->isStrategyActive(musicStrategy, SONIFICATION_HEADSET_MUSIC_DELAY, sysTime) ||
862 desc->isStrategyActive(sonificationStrategy, SONIFICATION_HEADSET_MUSIC_DELAY,
863 sysTime)) &&
Eric Laurentc75307b2015-03-17 15:29:32 -0700864 (delayMs < (int)desc->latency()*2)) {
865 delayMs = desc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -0700866 }
François Gaffiec005e562018-11-06 15:04:49 +0100867 setStrategyMute(musicStrategy, true, desc);
868 setStrategyMute(musicStrategy, false, desc, MUTE_TIME_MS,
869 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
870 nullptr, true /*fromCache*/).types());
871 setStrategyMute(sonificationStrategy, true, desc);
872 setStrategyMute(sonificationStrategy, false, desc, MUTE_TIME_MS,
873 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_ALARM),
874 nullptr, true /*fromCache*/).types());
Eric Laurente552edb2014-03-10 17:42:56 -0700875 }
876 }
877
Eric Laurent87ffa392015-05-22 10:32:38 -0700878 if (hasPrimaryOutput()) {
Eric Laurent87ffa392015-05-22 10:32:38 -0700879 if (state == AUDIO_MODE_IN_CALL) {
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100880 (void)updateCallRouting(false /*fromCache*/, delayMs);
Eric Laurent87ffa392015-05-22 10:32:38 -0700881 } else {
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100882 DeviceVector rxDevices = getNewOutputDevices(mPrimaryOutput, false /*fromCache*/);
883 // force routing command to audio hardware when ending call
884 // even if no device change is needed
885 if (isStateInCall(oldState) && rxDevices.isEmpty()) {
886 rxDevices = mPrimaryOutput->devices();
887 }
888 if (oldState == AUDIO_MODE_IN_CALL) {
Francois Gaffie601801d2021-06-22 13:27:39 +0200889 disconnectTelephonyAudioSource(mCallRxSourceClient);
890 disconnectTelephonyAudioSource(mCallTxSourceClient);
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100891 }
François Gaffie11d30102018-11-02 16:09:09 +0100892 setOutputDevices(mPrimaryOutput, rxDevices, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700893 }
Eric Laurentc2730ba2014-07-20 15:47:07 -0700894 }
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700895
jiabin3ff8d7d2022-12-13 06:27:44 +0000896 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700897 // reevaluate routing on all outputs in case tracks have been started during the call
898 for (size_t i = 0; i < mOutputs.size(); i++) {
899 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
François Gaffie11d30102018-11-02 16:09:09 +0100900 DeviceVector newDevices = getNewOutputDevices(desc, true /*fromCache*/);
Francois Gaffie601801d2021-06-22 13:27:39 +0200901 if (state != AUDIO_MODE_IN_CALL || (desc != mPrimaryOutput && !isTelephonyRxOrTx(desc))) {
902 bool forceRouting = !newDevices.isEmpty();
jiabin3ff8d7d2022-12-13 06:27:44 +0000903 if (desc->mUsePreferredMixerAttributes && newDevices != desc->devices()) {
904 // If the device is using preferred mixer attributes, the output need to reopen
905 // with default configuration when the new selected devices are different from
906 // current routing devices.
907 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices);
908 continue;
909 }
Francois Gaffie601801d2021-06-22 13:27:39 +0200910 setOutputDevices(desc, newDevices, forceRouting, 0 /*delayMs*/, nullptr,
911 true /*requiresMuteCheck*/, !forceRouting /*requiresVolumeCheck*/);
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700912 }
913 }
jiabin3ff8d7d2022-12-13 06:27:44 +0000914 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700915
Eric Laurent96d1dda2022-03-14 17:14:19 +0100916 checkLeBroadcastRoutes(wasLeUnicastActive, nullptr, delayMs);
917
Eric Laurente552edb2014-03-10 17:42:56 -0700918 if (isStateInCall(state)) {
919 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent63dea1d2015-07-02 17:10:28 -0700920 // force reevaluating accessibility routing when call starts
jiabinc44b3462022-12-08 12:52:31 -0800921 invalidateStreams({AUDIO_STREAM_ACCESSIBILITY});
Eric Laurente552edb2014-03-10 17:42:56 -0700922 }
923
924 // Flag that ringtone volume must be limited to music volume until we exit MODE_RINGTONE
François Gaffiec005e562018-11-06 15:04:49 +0100925 mLimitRingtoneVolume = (state == AUDIO_MODE_RINGTONE &&
926 isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY));
Eric Laurente552edb2014-03-10 17:42:56 -0700927}
928
Jean-Michel Trivi887a9ed2015-03-31 18:02:24 -0700929audio_mode_t AudioPolicyManager::getPhoneState() {
930 return mEngine->getPhoneState();
931}
932
Eric Laurente0720872014-03-11 09:30:41 -0700933void AudioPolicyManager::setForceUse(audio_policy_force_use_t usage,
François Gaffie11d30102018-11-02 16:09:09 +0100934 audio_policy_forced_cfg_t config)
Eric Laurente552edb2014-03-10 17:42:56 -0700935{
François Gaffie2110e042015-03-24 08:41:51 +0100936 ALOGV("setForceUse() usage %d, config %d, mPhoneState %d", usage, config, mEngine->getPhoneState());
Eric Laurent8dc87a62017-05-16 19:00:40 -0700937 if (config == mEngine->getForceUse(usage)) {
938 return;
939 }
Eric Laurente552edb2014-03-10 17:42:56 -0700940
François Gaffie2110e042015-03-24 08:41:51 +0100941 if (mEngine->setForceUse(usage, config) != NO_ERROR) {
942 ALOGW("setForceUse() could not set force cfg %d for usage %d", config, usage);
943 return;
Eric Laurente552edb2014-03-10 17:42:56 -0700944 }
François Gaffie2110e042015-03-24 08:41:51 +0100945 bool forceVolumeReeval = (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) ||
946 (usage == AUDIO_POLICY_FORCE_FOR_DOCK) ||
947 (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM);
Eric Laurente552edb2014-03-10 17:42:56 -0700948
949 // check for device and output changes triggered by new force usage
Mikhail Naganov37977152018-07-11 15:54:44 -0700950 checkForDeviceAndOutputChanges();
Phil Burk09bc4612016-02-24 15:58:15 -0800951
Eric Laurent22fcda22019-05-17 16:28:47 -0700952 // force client reconnection to reevaluate flag AUDIO_FLAG_AUDIBILITY_ENFORCED
953 if (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM) {
jiabinc44b3462022-12-08 12:52:31 -0800954 invalidateStreams({AUDIO_STREAM_SYSTEM, AUDIO_STREAM_ENFORCED_AUDIBLE});
Eric Laurent22fcda22019-05-17 16:28:47 -0700955 }
956
Eric Laurentdc462862016-07-19 12:29:53 -0700957 //FIXME: workaround for truncated touch sounds
958 // to be removed when the problem is handled by system UI
959 uint32_t delayMs = 0;
Eric Laurentdc462862016-07-19 12:29:53 -0700960 if (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) {
961 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
962 }
Jean-Michel Trivi30857152019-11-01 11:04:15 -0700963
964 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Eric Laurent2517af32020-11-25 15:31:27 +0100965 updateInputRouting();
Eric Laurente552edb2014-03-10 17:42:56 -0700966}
967
Eric Laurente0720872014-03-11 09:30:41 -0700968void AudioPolicyManager::setSystemProperty(const char* property, const char* value)
Eric Laurente552edb2014-03-10 17:42:56 -0700969{
970 ALOGV("setSystemProperty() property %s, value %s", property, value);
971}
972
Dorin Drimusecc9f422022-03-09 17:57:40 +0100973// Find an MSD output profile compatible with the parameters passed.
974// When "directOnly" is set, restrict search to profiles for direct outputs.
975sp<IOProfile> AudioPolicyManager::getMsdProfileForOutput(
976 const DeviceVector& devices,
977 uint32_t samplingRate,
978 audio_format_t format,
979 audio_channel_mask_t channelMask,
980 audio_output_flags_t flags,
981 bool directOnly)
982{
983 flags = getRelevantFlags(flags, directOnly);
984
985 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
986 if (msdModule != nullptr) {
987 // for the msd module check if there are patches to the output devices
988 if (msdHasPatchesToAllDevices(devices.toTypeAddrVector())) {
989 HwModuleCollection modules;
990 modules.add(msdModule);
991 return searchCompatibleProfileHwModules(
992 modules, getMsdAudioOutDevices(), samplingRate, format, channelMask,
993 flags, directOnly);
994 }
995 }
996 return nullptr;
997}
998
Michael Chana94fbb22018-04-24 14:31:19 +1000999// Find an output profile compatible with the parameters passed. When "directOnly" is set, restrict
1000// search to profiles for direct outputs.
1001sp<IOProfile> AudioPolicyManager::getProfileForOutput(
François Gaffie11d30102018-11-02 16:09:09 +01001002 const DeviceVector& devices,
Michael Chana94fbb22018-04-24 14:31:19 +10001003 uint32_t samplingRate,
1004 audio_format_t format,
1005 audio_channel_mask_t channelMask,
1006 audio_output_flags_t flags,
1007 bool directOnly)
Eric Laurente552edb2014-03-10 17:42:56 -07001008{
Dorin Drimusecc9f422022-03-09 17:57:40 +01001009 flags = getRelevantFlags(flags, directOnly);
1010
1011 return searchCompatibleProfileHwModules(
1012 mHwModules, devices, samplingRate, format, channelMask, flags, directOnly);
1013}
1014
1015audio_output_flags_t AudioPolicyManager::getRelevantFlags (
1016 audio_output_flags_t flags, bool directOnly) {
Michael Chana94fbb22018-04-24 14:31:19 +10001017 if (directOnly) {
Dorin Drimusecc9f422022-03-09 17:57:40 +01001018 // only retain flags that will drive the direct output profile selection
1019 // if explicitly requested
1020 static const uint32_t kRelevantFlags =
Michael Chana94fbb22018-04-24 14:31:19 +10001021 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD |
Dorin Drimusecc9f422022-03-09 17:57:40 +01001022 AUDIO_OUTPUT_FLAG_VOIP_RX | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ);
1023 flags = (audio_output_flags_t)((flags & kRelevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
Michael Chana94fbb22018-04-24 14:31:19 +10001024 }
Dorin Drimusecc9f422022-03-09 17:57:40 +01001025 return flags;
1026}
Eric Laurent861a6282015-05-18 15:40:16 -07001027
Dorin Drimusecc9f422022-03-09 17:57:40 +01001028sp<IOProfile> AudioPolicyManager::searchCompatibleProfileHwModules (
1029 const HwModuleCollection& hwModules,
1030 const DeviceVector& devices,
1031 uint32_t samplingRate,
1032 audio_format_t format,
1033 audio_channel_mask_t channelMask,
1034 audio_output_flags_t flags,
1035 bool directOnly) {
Eric Laurent861a6282015-05-18 15:40:16 -07001036 sp<IOProfile> profile;
Dorin Drimusecc9f422022-03-09 17:57:40 +01001037 for (const auto& hwModule : hwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08001038 for (const auto& curProfile : hwModule->getOutputProfiles()) {
Dorin Drimusecc9f422022-03-09 17:57:40 +01001039 if (!curProfile->isCompatibleProfile(devices,
1040 samplingRate, NULL /*updatedSamplingRate*/,
1041 format, NULL /*updatedFormat*/,
1042 channelMask, NULL /*updatedChannelMask*/,
1043 flags)) {
1044 continue;
1045 }
1046 // reject profiles not corresponding to a device currently available
1047 if (!mAvailableOutputDevices.containsAtLeastOne(curProfile->getSupportedDevices())) {
1048 continue;
1049 }
1050 // reject profiles if connected device does not support codec
1051 if (!curProfile->devicesSupportEncodedFormats(devices.types())) {
1052 continue;
1053 }
1054 if (!directOnly) {
1055 return curProfile;
1056 }
1057
1058 // when searching for direct outputs, if several profiles are compatible, give priority
1059 // to one with offload capability
Patty Huang36028df2022-07-06 00:14:12 +08001060 if (profile != 0 &&
Dorin Drimusecc9f422022-03-09 17:57:40 +01001061 ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0)) {
Eric Laurent861a6282015-05-18 15:40:16 -07001062 continue;
Dorin Drimusecc9f422022-03-09 17:57:40 +01001063 }
1064 profile = curProfile;
1065 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1066 break;
1067 }
Eric Laurente552edb2014-03-10 17:42:56 -07001068 }
1069 }
Eric Laurent861a6282015-05-18 15:40:16 -07001070 return profile;
Eric Laurente552edb2014-03-10 17:42:56 -07001071}
1072
Eric Laurentfa0f6742021-08-17 18:39:44 +02001073sp<IOProfile> AudioPolicyManager::getSpatializerOutputProfile(
Eric Laurent39095982021-08-24 18:29:27 +02001074 const audio_config_t *config __unused, const AudioDeviceTypeAddrVector &devices) const
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001075{
1076 for (const auto& hwModule : mHwModules) {
1077 for (const auto& curProfile : hwModule->getOutputProfiles()) {
Eric Laurent1c5e2e32021-08-18 18:50:28 +02001078 if (curProfile->getFlags() != AUDIO_OUTPUT_FLAG_SPATIALIZER) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001079 continue;
1080 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001081 if (!devices.empty()) {
Eric Laurent0c8f7cc2022-06-24 14:32:36 +02001082 // reject profiles not corresponding to a device currently available
1083 DeviceVector supportedDevices = curProfile->getSupportedDevices();
1084 if (!mAvailableOutputDevices.containsAtLeastOne(supportedDevices)) {
1085 continue;
1086 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001087 if (supportedDevices.getDevicesFromDeviceTypeAddrVec(devices).size()
1088 != devices.size()) {
1089 continue;
1090 }
1091 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001092 ALOGV("%s found profile %s", __func__, curProfile->getName().c_str());
1093 return curProfile;
1094 }
1095 }
1096 return nullptr;
1097}
1098
Eric Laurentf4e63452017-11-06 19:31:46 +00001099audio_io_handle_t AudioPolicyManager::getOutput(audio_stream_type_t stream)
Eric Laurente552edb2014-03-10 17:42:56 -07001100{
François Gaffiec005e562018-11-06 15:04:49 +01001101 DeviceVector devices = mEngine->getOutputDevicesForStream(stream, false /*fromCache*/);
Andy Hungc9901522017-11-10 20:07:54 -08001102
1103 // Note that related method getOutputForAttr() uses getOutputForDevice() not selectOutput().
1104 // We use selectOutput() here since we don't have the desired AudioTrack sample rate,
1105 // format, flags, etc. This may result in some discrepancy for functions that utilize
1106 // getOutput() solely on audio_stream_type such as AudioSystem::getOutputFrameCount()
1107 // and AudioSystem::getOutputSamplingRate().
1108
François Gaffie11d30102018-11-02 16:09:09 +01001109 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Mingyu Shih75563d32023-05-24 04:47:40 +08001110 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
1111 if (stream == AUDIO_STREAM_MUSIC &&
1112 property_get_bool("audio.deep_buffer.media", false /* default_value */)) {
1113 flags = AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
1114 }
1115 const audio_io_handle_t output = selectOutput(outputs, flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001116
François Gaffie11d30102018-11-02 16:09:09 +01001117 ALOGV("getOutput() stream %d selected devices %s, output %d", stream,
1118 devices.toString().c_str(), output);
Eric Laurentf4e63452017-11-06 19:31:46 +00001119 return output;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001120}
1121
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001122status_t AudioPolicyManager::getAudioAttributes(audio_attributes_t *dstAttr,
1123 const audio_attributes_t *srcAttr,
1124 audio_stream_type_t srcStream)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001125{
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001126 if (srcAttr != NULL) {
1127 if (!isValidAttributes(srcAttr)) {
1128 ALOGE("%s invalid attributes: usage=%d content=%d flags=0x%x tags=[%s]",
1129 __func__,
1130 srcAttr->usage, srcAttr->content_type, srcAttr->flags,
1131 srcAttr->tags);
1132 return BAD_VALUE;
1133 }
1134 *dstAttr = *srcAttr;
1135 } else {
1136 if (srcStream < AUDIO_STREAM_MIN || srcStream >= AUDIO_STREAM_PUBLIC_CNT) {
1137 ALOGE("%s: invalid stream type", __func__);
1138 return BAD_VALUE;
1139 }
François Gaffiec005e562018-11-06 15:04:49 +01001140 *dstAttr = mEngine->getAttributesForStreamType(srcStream);
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001141 }
Eric Laurent22fcda22019-05-17 16:28:47 -07001142
1143 // Only honor audibility enforced when required. The client will be
1144 // forced to reconnect if the forced usage changes.
1145 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Mikhail Naganov55773032020-10-01 15:08:13 -07001146 dstAttr->flags = static_cast<audio_flags_mask_t>(
1147 dstAttr->flags & ~AUDIO_FLAG_AUDIBILITY_ENFORCED);
Eric Laurent22fcda22019-05-17 16:28:47 -07001148 }
1149
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001150 return NO_ERROR;
1151}
1152
Kevin Rocard153f92d2018-12-18 18:33:28 -08001153status_t AudioPolicyManager::getOutputForAttrInt(
1154 audio_attributes_t *resultAttr,
1155 audio_io_handle_t *output,
1156 audio_session_t session,
1157 const audio_attributes_t *attr,
1158 audio_stream_type_t *stream,
1159 uid_t uid,
jiabinf1c73972022-04-14 16:28:52 -07001160 audio_config_t *config,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001161 audio_output_flags_t *flags,
1162 audio_port_handle_t *selectedDeviceId,
1163 bool *isRequestedDeviceForExclusiveUse,
Eric Laurentc529cf62020-04-17 18:19:10 -07001164 std::vector<sp<AudioPolicyMix>> *secondaryMixes,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001165 output_type_t *outputType,
jiabinc658e452022-10-21 20:52:21 +00001166 bool *isSpatialized,
1167 bool *isBitPerfect)
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001168{
François Gaffiec005e562018-11-06 15:04:49 +01001169 DeviceVector outputDevices;
Francois Gaffie716e1432019-01-14 16:58:59 +01001170 const audio_port_handle_t requestedPortId = *selectedDeviceId;
François Gaffie11d30102018-11-02 16:09:09 +01001171 DeviceVector msdDevices = getMsdAudioOutDevices();
François Gaffiec005e562018-11-06 15:04:49 +01001172 const sp<DeviceDescriptor> requestedDevice =
1173 mAvailableOutputDevices.getDeviceFromId(requestedPortId);
1174
Eric Laurent8a1095a2019-11-08 14:44:16 -08001175 *outputType = API_OUTPUT_INVALID;
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001176 *isSpatialized = false;
1177
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001178 status_t status = getAudioAttributes(resultAttr, attr, *stream);
1179 if (status != NO_ERROR) {
1180 return status;
Eric Laurent8f42ea12018-08-08 09:08:25 -07001181 }
Kevin Rocardb99cc752019-03-21 20:52:24 -07001182 if (auto it = mAllowedCapturePolicies.find(uid); it != end(mAllowedCapturePolicies)) {
Mikhail Naganov55773032020-10-01 15:08:13 -07001183 resultAttr->flags = static_cast<audio_flags_mask_t>(resultAttr->flags | it->second);
Kevin Rocardb99cc752019-03-21 20:52:24 -07001184 }
François Gaffiec005e562018-11-06 15:04:49 +01001185 *stream = mEngine->getStreamTypeForAttributes(*resultAttr);
Eric Laurent8f42ea12018-08-08 09:08:25 -07001186
François Gaffiec005e562018-11-06 15:04:49 +01001187 ALOGV("%s() attributes=%s stream=%s session %d selectedDeviceId %d", __func__,
1188 toString(*resultAttr).c_str(), toString(*stream).c_str(), session, requestedPortId);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001189
Oscar Azucena873d10f2023-01-12 18:34:42 -08001190 bool usePrimaryOutputFromPolicyMixes = false;
1191
Kevin Rocard153f92d2018-12-18 18:33:28 -08001192 // The primary output is the explicit routing (eg. setPreferredDevice) if specified,
1193 // otherwise, fallback to the dynamic policies, if none match, query the engine.
1194 // Secondary outputs are always found by dynamic policies as the engine do not support them
Eric Laurentc529cf62020-04-17 18:19:10 -07001195 sp<AudioPolicyMix> primaryMix;
Dean Wheatleyd082f472022-02-04 11:10:48 +11001196 const audio_config_base_t clientConfig = {.sample_rate = config->sample_rate,
1197 .channel_mask = config->channel_mask,
1198 .format = config->format,
1199 };
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02001200 status = mPolicyMixes.getOutputForAttr(*resultAttr, clientConfig, uid, session, *flags,
Oscar Azucena873d10f2023-01-12 18:34:42 -08001201 mAvailableOutputDevices, requestedDevice, primaryMix,
1202 secondaryMixes, usePrimaryOutputFromPolicyMixes);
Kevin Rocard94114a22019-04-01 19:38:23 -07001203 if (status != OK) {
1204 return status;
Kevin Rocard153f92d2018-12-18 18:33:28 -08001205 }
Kevin Rocard94114a22019-04-01 19:38:23 -07001206
Kevin Rocard153f92d2018-12-18 18:33:28 -08001207 // FIXME: in case of RENDER policy, the output capabilities should be checked
Dean Wheatleyd082f472022-02-04 11:10:48 +11001208 if ((secondaryMixes != nullptr && !secondaryMixes->empty())
1209 && !audio_is_linear_pcm(config->format)) {
1210 ALOGD("%s: rejecting request as secondary mixes only support pcm", __func__);
Kevin Rocard153f92d2018-12-18 18:33:28 -08001211 return BAD_VALUE;
1212 }
1213 if (usePrimaryOutputFromPolicyMixes) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001214 sp<DeviceDescriptor> deviceDesc =
1215 mAvailableOutputDevices.getDevice(primaryMix->mDeviceType,
1216 primaryMix->mDeviceAddress,
1217 AUDIO_FORMAT_DEFAULT);
1218 sp<SwAudioOutputDescriptor> policyDesc = primaryMix->getOutput();
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001219 bool tryDirectForFlags = policyDesc == nullptr ||
1220 (policyDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT);
1221 // if a direct output can be opened to deliver the track's multi-channel content to the
1222 // output rather than being downmixed by the primary output, then use this direct
1223 // output by by-passing the primary mix if possible, otherwise fall-through to primary
1224 // mix.
1225 bool tryDirectForChannelMask = policyDesc != nullptr
1226 && (audio_channel_count_from_out_mask(policyDesc->getConfig().channel_mask) <
1227 audio_channel_count_from_out_mask(config->channel_mask));
1228 if (deviceDesc != nullptr && (tryDirectForFlags || tryDirectForChannelMask)) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001229 audio_io_handle_t newOutput;
1230 status = openDirectOutput(
1231 *stream, session, config,
1232 (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT),
1233 DeviceVector(deviceDesc), &newOutput);
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001234 if (status == NO_ERROR) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001235 policyDesc = mOutputs.valueFor(newOutput);
1236 primaryMix->setOutput(policyDesc);
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001237 } else if (tryDirectForFlags) {
1238 policyDesc = nullptr;
1239 } // otherwise use primary if available.
Eric Laurentc529cf62020-04-17 18:19:10 -07001240 }
1241 if (policyDesc != nullptr) {
1242 policyDesc->mPolicyMix = primaryMix;
1243 *output = policyDesc->mIoHandle;
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08001244 *selectedDeviceId = deviceDesc != 0 ? deviceDesc->getId() : AUDIO_PORT_HANDLE_NONE;
Eric Laurent8a1095a2019-11-08 14:44:16 -08001245
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08001246 ALOGV("getOutputForAttr() returns output %d", *output);
1247 if (resultAttr->usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
1248 *outputType = API_OUT_MIX_PLAYBACK;
1249 } else {
1250 *outputType = API_OUTPUT_LEGACY;
1251 }
1252 return NO_ERROR;
Eric Laurent8a1095a2019-11-08 14:44:16 -08001253 }
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001254 }
François Gaffiec005e562018-11-06 15:04:49 +01001255 // Virtual sources must always be dynamicaly or explicitly routed
1256 if (resultAttr->usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
1257 ALOGW("getOutputForAttr() no policy mix found for usage AUDIO_USAGE_VIRTUAL_SOURCE");
1258 return BAD_VALUE;
1259 }
1260 // explicit routing managed by getDeviceForStrategy in APM is now handled by engine
1261 // in order to let the choice of the order to future vendor engine
1262 outputDevices = mEngine->getOutputDevicesForAttributes(*resultAttr, requestedDevice, false);
Scott Randolph7b1fd232018-06-18 15:33:03 -07001263
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001264 if ((resultAttr->flags & AUDIO_FLAG_HW_AV_SYNC) != 0) {
Nadav Bar766fb022018-01-07 12:18:03 +02001265 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
Eric Laurent93c3d412014-08-01 14:48:35 -07001266 }
1267
Nadav Barb2f18162018-07-18 13:01:53 +03001268 // Set incall music only if device was explicitly set, and fallback to the device which is
1269 // chosen by the engine if not.
1270 // FIXME: provide a more generic approach which is not device specific and move this back
1271 // to getOutputForDevice.
Nadav Bar20919492018-11-20 10:20:51 +02001272 // TODO: Remove check of AUDIO_STREAM_MUSIC once migration is completed on the app side.
jiabin9a3361e2019-10-01 09:38:30 -07001273 if (outputDevices.onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_TELEPHONY_TX) &&
François Gaffiec005e562018-11-06 15:04:49 +01001274 (*stream == AUDIO_STREAM_MUSIC || resultAttr->usage == AUDIO_USAGE_VOICE_COMMUNICATION) &&
Nadav Barb2f18162018-07-18 13:01:53 +03001275 audio_is_linear_pcm(config->format) &&
Eric Laurent74b71512019-11-06 17:21:57 -08001276 isCallAudioAccessible()) {
Francois Gaffie716e1432019-01-14 16:58:59 +01001277 if (requestedPortId != AUDIO_PORT_HANDLE_NONE) {
Nadav Barb2f18162018-07-18 13:01:53 +03001278 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_INCALL_MUSIC;
François Gaffief579db52018-11-13 11:25:16 +01001279 *isRequestedDeviceForExclusiveUse = true;
Nadav Barb2f18162018-07-18 13:01:53 +03001280 }
1281 }
1282
François Gaffiec005e562018-11-06 15:04:49 +01001283 ALOGV("%s() device %s, sampling rate %d, format %#x, channel mask %#x, flags %#x stream %s",
1284 __func__, outputDevices.toString().c_str(), config->sample_rate, config->format,
1285 config->channel_mask, *flags, toString(*stream).c_str());
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001286
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001287 *output = AUDIO_IO_HANDLE_NONE;
François Gaffie11d30102018-11-02 16:09:09 +01001288 if (!msdDevices.isEmpty()) {
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001289 *output = getOutputForDevices(msdDevices, session, resultAttr, config, flags, isSpatialized);
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001290 if (*output != AUDIO_IO_HANDLE_NONE && setMsdOutputPatches(&outputDevices) == NO_ERROR) {
François Gaffiec005e562018-11-06 15:04:49 +01001291 ALOGV("%s() Using MSD devices %s instead of devices %s",
1292 __func__, msdDevices.toString().c_str(), outputDevices.toString().c_str());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001293 } else {
1294 *output = AUDIO_IO_HANDLE_NONE;
1295 }
1296 }
1297 if (*output == AUDIO_IO_HANDLE_NONE) {
jiabina84c3d32022-12-02 18:59:55 +00001298 sp<PreferredMixerAttributesInfo> info = nullptr;
1299 if (outputDevices.size() == 1) {
1300 info = getPreferredMixerAttributesInfo(
1301 outputDevices.itemAt(0)->getId(),
jiabind9a58d32023-06-01 17:57:30 +00001302 mEngine->getProductStrategyForAttributes(*resultAttr),
1303 true /*activeBitPerfectPreferred*/);
jiabin5eaf0962022-12-20 20:11:38 +00001304 // Only use preferred mixer if the uid matches or the preferred mixer is bit-perfect
1305 // and it is currently active.
1306 if (info != nullptr && info->getUid() != uid &&
1307 ((info->getFlags() & AUDIO_OUTPUT_FLAG_BIT_PERFECT) == AUDIO_OUTPUT_FLAG_NONE ||
1308 info->getActiveClientCount() == 0)) {
jiabina84c3d32022-12-02 18:59:55 +00001309 info = nullptr;
1310 }
1311 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001312 *output = getOutputForDevices(outputDevices, session, resultAttr, config,
jiabina84c3d32022-12-02 18:59:55 +00001313 flags, isSpatialized, info, resultAttr->flags & AUDIO_FLAG_MUTE_HAPTIC);
jiabin5eaf0962022-12-20 20:11:38 +00001314 // The client will be active if the client is currently preferred mixer owner and the
1315 // requested configuration matches the preferred mixer configuration.
jiabinc658e452022-10-21 20:52:21 +00001316 *isBitPerfect = (info != nullptr
1317 && (info->getFlags() & AUDIO_OUTPUT_FLAG_BIT_PERFECT) != AUDIO_OUTPUT_FLAG_NONE
jiabin5eaf0962022-12-20 20:11:38 +00001318 && info->getUid() == uid
1319 && *output != AUDIO_IO_HANDLE_NONE
1320 // When bit-perfect output is selected for the preferred mixer attributes owner,
1321 // only need to consider the config matches.
1322 && mOutputs.valueFor(*output)->isConfigurationMatched(
1323 clientConfig, AUDIO_OUTPUT_FLAG_NONE));
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001324 }
Eric Laurente83b55d2014-11-14 10:06:21 -08001325 if (*output == AUDIO_IO_HANDLE_NONE) {
jiabinf1c73972022-04-14 16:28:52 -07001326 AudioProfileVector profiles;
1327 status_t ret = getProfilesForDevices(outputDevices, profiles, *flags, false /*isInput*/);
1328 if (ret == NO_ERROR && !profiles.empty()) {
1329 config->channel_mask = profiles[0]->getChannels().empty() ? config->channel_mask
1330 : *profiles[0]->getChannels().begin();
1331 config->sample_rate = profiles[0]->getSampleRates().empty() ? config->sample_rate
1332 : *profiles[0]->getSampleRates().begin();
1333 config->format = profiles[0]->getFormat();
1334 }
Eric Laurente83b55d2014-11-14 10:06:21 -08001335 return INVALID_OPERATION;
1336 }
Paul McLeanaa981192015-03-21 09:55:15 -07001337
François Gaffiec005e562018-11-06 15:04:49 +01001338 *selectedDeviceId = getFirstDeviceId(outputDevices);
Michael Chan6fb34492020-12-08 15:44:49 +11001339 for (auto &outputDevice : outputDevices) {
Mikhail Naganov68e3f642023-04-28 13:06:32 -07001340 if (outputDevice->getId() == mConfig->getDefaultOutputDevice()->getId()) {
Michael Chan6fb34492020-12-08 15:44:49 +11001341 *selectedDeviceId = outputDevice->getId();
1342 break;
1343 }
1344 }
Eric Laurent2ac76942017-06-22 17:17:09 -07001345
Eric Laurent8a1095a2019-11-08 14:44:16 -08001346 if (outputDevices.onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_TELEPHONY_TX)) {
1347 *outputType = API_OUTPUT_TELEPHONY_TX;
1348 } else {
1349 *outputType = API_OUTPUT_LEGACY;
1350 }
1351
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001352 ALOGV("%s returns output %d selectedDeviceId %d", __func__, *output, *selectedDeviceId);
1353
1354 return NO_ERROR;
1355}
1356
1357status_t AudioPolicyManager::getOutputForAttr(const audio_attributes_t *attr,
1358 audio_io_handle_t *output,
1359 audio_session_t session,
1360 audio_stream_type_t *stream,
Svet Ganov3e5f14f2021-05-13 22:51:08 +00001361 const AttributionSourceState& attributionSource,
jiabinf1c73972022-04-14 16:28:52 -07001362 audio_config_t *config,
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001363 audio_output_flags_t *flags,
1364 audio_port_handle_t *selectedDeviceId,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001365 audio_port_handle_t *portId,
Eric Laurent8a1095a2019-11-08 14:44:16 -08001366 std::vector<audio_io_handle_t> *secondaryOutputs,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001367 output_type_t *outputType,
jiabinc658e452022-10-21 20:52:21 +00001368 bool *isSpatialized,
1369 bool *isBitPerfect)
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001370{
1371 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
1372 if (*portId != AUDIO_PORT_HANDLE_NONE) {
1373 return INVALID_OPERATION;
1374 }
Philip P. Moltmannbda45752020-07-17 16:41:18 -07001375 const uid_t uid = VALUE_OR_RETURN_STATUS(
Svet Ganov3e5f14f2021-05-13 22:51:08 +00001376 aidl2legacy_int32_t_uid_t(attributionSource.uid));
Francois Gaffie716e1432019-01-14 16:58:59 +01001377 const audio_port_handle_t requestedPortId = *selectedDeviceId;
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001378 audio_attributes_t resultAttr;
François Gaffief579db52018-11-13 11:25:16 +01001379 bool isRequestedDeviceForExclusiveUse = false;
Eric Laurentc529cf62020-04-17 18:19:10 -07001380 std::vector<sp<AudioPolicyMix>> secondaryMixes;
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001381 const sp<DeviceDescriptor> requestedDevice =
1382 mAvailableOutputDevices.getDeviceFromId(requestedPortId);
1383
1384 // Prevent from storing invalid requested device id in clients
1385 const audio_port_handle_t sanitizedRequestedPortId =
1386 requestedDevice != nullptr ? requestedPortId : AUDIO_PORT_HANDLE_NONE;
1387 *selectedDeviceId = sanitizedRequestedPortId;
1388
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001389 status_t status = getOutputForAttrInt(&resultAttr, output, session, attr, stream, uid,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001390 config, flags, selectedDeviceId, &isRequestedDeviceForExclusiveUse,
jiabinc658e452022-10-21 20:52:21 +00001391 secondaryOutputs != nullptr ? &secondaryMixes : nullptr, outputType, isSpatialized,
1392 isBitPerfect);
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001393 if (status != NO_ERROR) {
1394 return status;
1395 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001396 std::vector<wp<SwAudioOutputDescriptor>> weakSecondaryOutputDescs;
Eric Laurentc529cf62020-04-17 18:19:10 -07001397 if (secondaryOutputs != nullptr) {
1398 for (auto &secondaryMix : secondaryMixes) {
1399 sp<SwAudioOutputDescriptor> outputDesc = secondaryMix->getOutput();
1400 if (outputDesc != nullptr &&
1401 outputDesc->mIoHandle != AUDIO_IO_HANDLE_NONE) {
1402 secondaryOutputs->push_back(outputDesc->mIoHandle);
1403 weakSecondaryOutputDescs.push_back(outputDesc);
1404 }
1405 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001406 }
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001407
Eric Laurent8fc147b2018-07-22 19:13:55 -07001408 audio_config_base_t clientConfig = {.sample_rate = config->sample_rate,
Nick Desaulniersa30e3202019-10-18 13:38:23 -07001409 .channel_mask = config->channel_mask,
Eric Laurent8fc147b2018-07-22 19:13:55 -07001410 .format = config->format,
Nick Desaulniersa30e3202019-10-18 13:38:23 -07001411 };
jiabin4ef93452019-09-10 14:29:54 -07001412 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurent8f42ea12018-08-08 09:08:25 -07001413
Eric Laurentc209fe42020-06-05 18:11:23 -07001414 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(*output);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001415 sp<TrackClientDescriptor> clientDesc =
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001416 new TrackClientDescriptor(*portId, uid, session, resultAttr, clientConfig,
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001417 sanitizedRequestedPortId, *stream,
François Gaffiec005e562018-11-06 15:04:49 +01001418 mEngine->getProductStrategyForAttributes(resultAttr),
François Gaffieaaac0fd2018-11-22 17:56:39 +01001419 toVolumeSource(resultAttr),
Kevin Rocard153f92d2018-12-18 18:33:28 -08001420 *flags, isRequestedDeviceForExclusiveUse,
Eric Laurentc209fe42020-06-05 18:11:23 -07001421 std::move(weakSecondaryOutputDescs),
1422 outputDesc->mPolicyMix);
Andy Hung39efb7a2018-09-26 15:39:28 -07001423 outputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001424
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001425 ALOGV("%s() returns output %d requestedPortId %d selectedDeviceId %d for port ID %d", __func__,
1426 *output, requestedPortId, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07001427
Eric Laurente83b55d2014-11-14 10:06:21 -08001428 return NO_ERROR;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001429}
1430
Eric Laurentc529cf62020-04-17 18:19:10 -07001431status_t AudioPolicyManager::openDirectOutput(audio_stream_type_t stream,
1432 audio_session_t session,
1433 const audio_config_t *config,
1434 audio_output_flags_t flags,
1435 const DeviceVector &devices,
1436 audio_io_handle_t *output) {
1437
1438 *output = AUDIO_IO_HANDLE_NONE;
1439
1440 // skip direct output selection if the request can obviously be attached to a mixed output
1441 // and not explicitly requested
1442 if (((flags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
1443 audio_is_linear_pcm(config->format) && config->sample_rate <= SAMPLE_RATE_HZ_MAX &&
1444 audio_channel_count_from_out_mask(config->channel_mask) <= 2) {
1445 return NAME_NOT_FOUND;
1446 }
1447
1448 // Do not allow offloading if one non offloadable effect is enabled or MasterMono is enabled.
1449 // This prevents creating an offloaded track and tearing it down immediately after start
1450 // when audioflinger detects there is an active non offloadable effect.
1451 // FIXME: We should check the audio session here but we do not have it in this context.
1452 // This may prevent offloading in rare situations where effects are left active by apps
1453 // in the background.
1454 sp<IOProfile> profile;
1455 if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) ||
1456 !(mEffects.isNonOffloadableEffectEnabled() || mMasterMono)) {
1457 profile = getProfileForOutput(
1458 devices, config->sample_rate, config->format, config->channel_mask,
1459 flags, true /* directOnly */);
1460 }
1461
1462 if (profile == nullptr) {
1463 return NAME_NOT_FOUND;
1464 }
1465
1466 // exclusive outputs for MMAP and Offload are enforced by different session ids.
1467 for (size_t i = 0; i < mOutputs.size(); i++) {
1468 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
1469 if (!desc->isDuplicated() && (profile == desc->mProfile)) {
1470 // reuse direct output if currently open by the same client
1471 // and configured with same parameters
1472 if ((config->sample_rate == desc->getSamplingRate()) &&
1473 (config->format == desc->getFormat()) &&
1474 (config->channel_mask == desc->getChannelMask()) &&
1475 (session == desc->mDirectClientSession)) {
1476 desc->mDirectOpenCount++;
Eric Laurentfecbceb2021-02-09 14:46:43 +01001477 ALOGV("%s reusing direct output %d for session %d", __func__,
Eric Laurentc529cf62020-04-17 18:19:10 -07001478 mOutputs.keyAt(i), session);
1479 *output = mOutputs.keyAt(i);
1480 return NO_ERROR;
1481 }
1482 }
1483 }
1484
1485 if (!profile->canOpenNewIo()) {
1486 return NAME_NOT_FOUND;
1487 }
1488
1489 sp<SwAudioOutputDescriptor> outputDesc =
1490 new SwAudioOutputDescriptor(profile, mpClientInterface);
1491
Michael Chan6fb34492020-12-08 15:44:49 +11001492 // An MSD patch may be using the only output stream that can service this request. Release
1493 // all MSD patches to prioritize this request over any active output on MSD.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001494 releaseMsdOutputPatches(devices);
Eric Laurentc529cf62020-04-17 18:19:10 -07001495
Eric Laurentf1f22e72021-07-13 14:04:14 +02001496 status_t status =
1497 outputDesc->open(config, nullptr /* mixerConfig */, devices, stream, flags, output);
Eric Laurentc529cf62020-04-17 18:19:10 -07001498
1499 // only accept an output with the requested parameters
1500 if (status != NO_ERROR ||
1501 (config->sample_rate != 0 && config->sample_rate != outputDesc->getSamplingRate()) ||
1502 (config->format != AUDIO_FORMAT_DEFAULT && config->format != outputDesc->getFormat()) ||
1503 (config->channel_mask != 0 && config->channel_mask != outputDesc->getChannelMask())) {
1504 ALOGV("%s failed opening direct output: output %d sample rate %d %d,"
1505 "format %d %d, channel mask %04x %04x", __func__, *output, config->sample_rate,
1506 outputDesc->getSamplingRate(), config->format, outputDesc->getFormat(),
1507 config->channel_mask, outputDesc->getChannelMask());
1508 if (*output != AUDIO_IO_HANDLE_NONE) {
1509 outputDesc->close();
1510 }
1511 // fall back to mixer output if possible when the direct output could not be open
1512 if (audio_is_linear_pcm(config->format) &&
1513 config->sample_rate <= SAMPLE_RATE_HZ_MAX) {
1514 return NAME_NOT_FOUND;
1515 }
1516 *output = AUDIO_IO_HANDLE_NONE;
1517 return BAD_VALUE;
1518 }
1519 outputDesc->mDirectOpenCount = 1;
1520 outputDesc->mDirectClientSession = session;
1521
1522 addOutput(*output, outputDesc);
1523 mPreviousOutputs = mOutputs;
1524 ALOGV("%s returns new direct output %d", __func__, *output);
1525 mpClientInterface->onAudioPortListUpdate();
1526 return NO_ERROR;
1527}
1528
François Gaffie11d30102018-11-02 16:09:09 +01001529audio_io_handle_t AudioPolicyManager::getOutputForDevices(
1530 const DeviceVector &devices,
Kevin Rocard169753c2017-03-06 14:18:23 -08001531 audio_session_t session,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001532 const audio_attributes_t *attr,
Eric Laurentfe231122017-11-17 17:48:06 -08001533 const audio_config_t *config,
jiabine375d412019-02-26 12:54:53 -08001534 audio_output_flags_t *flags,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001535 bool *isSpatialized,
jiabina84c3d32022-12-02 18:59:55 +00001536 sp<PreferredMixerAttributesInfo> prefMixerConfigInfo,
jiabine375d412019-02-26 12:54:53 -08001537 bool forceMutingHaptic)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001538{
Andy Hungc88b0642018-04-27 15:42:35 -07001539 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001540
jiabine375d412019-02-26 12:54:53 -08001541 // Discard haptic channel mask when forcing muting haptic channels.
1542 audio_channel_mask_t channelMask = forceMutingHaptic
Mikhail Naganov55773032020-10-01 15:08:13 -07001543 ? static_cast<audio_channel_mask_t>(config->channel_mask & ~AUDIO_CHANNEL_HAPTIC_ALL)
1544 : config->channel_mask;
jiabine375d412019-02-26 12:54:53 -08001545
Eric Laurente552edb2014-03-10 17:42:56 -07001546 // open a direct output if required by specified parameters
1547 //force direct flag if offload flag is set: offloading implies a direct output stream
1548 // and all common behaviors are driven by checking only the direct flag
1549 // this should normally be set appropriately in the policy configuration file
Nadav Bar766fb022018-01-07 12:18:03 +02001550 if ((*flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1551 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurente552edb2014-03-10 17:42:56 -07001552 }
Nadav Bar766fb022018-01-07 12:18:03 +02001553 if ((*flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
1554 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent93c3d412014-08-01 14:48:35 -07001555 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001556
1557 audio_stream_type_t stream = mEngine->getStreamTypeForAttributes(*attr);
1558
Eric Laurente83b55d2014-11-14 10:06:21 -08001559 // only allow deep buffering for music stream type
1560 if (stream != AUDIO_STREAM_MUSIC) {
Nadav Bar766fb022018-01-07 12:18:03 +02001561 *flags = (audio_output_flags_t)(*flags &~AUDIO_OUTPUT_FLAG_DEEP_BUFFER);
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -07001562 } else if (/* stream == AUDIO_STREAM_MUSIC && */
Nadav Bar766fb022018-01-07 12:18:03 +02001563 *flags == AUDIO_OUTPUT_FLAG_NONE &&
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -07001564 property_get_bool("audio.deep_buffer.media", false /* default_value */)) {
1565 // use DEEP_BUFFER as default output for music stream type
Nadav Bar766fb022018-01-07 12:18:03 +02001566 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
Eric Laurente83b55d2014-11-14 10:06:21 -08001567 }
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -07001568 if (stream == AUDIO_STREAM_TTS) {
Nadav Bar766fb022018-01-07 12:18:03 +02001569 *flags = AUDIO_OUTPUT_FLAG_TTS;
Haynes Mathew George84c621e2017-04-25 11:41:50 -07001570 } else if (stream == AUDIO_STREAM_VOICE_CALL &&
Nadav Bar20919492018-11-20 10:20:51 +02001571 audio_is_linear_pcm(config->format) &&
1572 (*flags & AUDIO_OUTPUT_FLAG_INCALL_MUSIC) == 0) {
Nadav Bar766fb022018-01-07 12:18:03 +02001573 *flags = (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_VOIP_RX |
Haynes Mathew George84c621e2017-04-25 11:41:50 -07001574 AUDIO_OUTPUT_FLAG_DIRECT);
1575 ALOGV("Set VoIP and Direct output flags for PCM format");
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -07001576 }
Eric Laurente552edb2014-03-10 17:42:56 -07001577
Carter Hsua3abb402021-10-26 11:11:20 +08001578 // Attach the Ultrasound flag for the AUDIO_CONTENT_TYPE_ULTRASOUND
1579 if (attr->content_type == AUDIO_CONTENT_TYPE_ULTRASOUND) {
1580 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_ULTRASOUND);
1581 }
1582
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001583 *isSpatialized = false;
Eric Laurentfa0f6742021-08-17 18:39:44 +02001584 if (mSpatializerOutput != nullptr
Andy Hung9dd1a5b2022-05-10 15:39:39 -07001585 && canBeSpatializedInt(attr, config, devices.toTypeAddrVector())) {
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001586 *isSpatialized = true;
Eric Laurentfa0f6742021-08-17 18:39:44 +02001587 return mSpatializerOutput->mIoHandle;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001588 }
1589
Eric Laurentc529cf62020-04-17 18:19:10 -07001590 audio_config_t directConfig = *config;
1591 directConfig.channel_mask = channelMask;
1592 status_t status = openDirectOutput(stream, session, &directConfig, *flags, devices, &output);
1593 if (status != NAME_NOT_FOUND) {
Eric Laurente552edb2014-03-10 17:42:56 -07001594 return output;
1595 }
1596
Eric Laurent14cbfca2016-03-17 09:42:16 -07001597 // A request for HW A/V sync cannot fallback to a mixed output because time
1598 // stamps are embedded in audio data
Phil Burk2d059932018-02-15 15:55:11 -08001599 if ((*flags & (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ)) != 0) {
Eric Laurent14cbfca2016-03-17 09:42:16 -07001600 return AUDIO_IO_HANDLE_NONE;
1601 }
Pierre Couillaude73496b2023-03-06 16:19:05 +00001602 // A request for Tuner cannot fallback to a mixed output
1603 if ((directConfig.offload_info.content_id || directConfig.offload_info.sync_id)) {
1604 return AUDIO_IO_HANDLE_NONE;
1605 }
Eric Laurent14cbfca2016-03-17 09:42:16 -07001606
Eric Laurente552edb2014-03-10 17:42:56 -07001607 // ignoring channel mask due to downmix capability in mixer
1608
1609 // open a non direct output
1610
1611 // for non direct outputs, only PCM is supported
Eric Laurentfe231122017-11-17 17:48:06 -08001612 if (audio_is_linear_pcm(config->format)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001613 // get which output is suitable for the specified stream. The actual
1614 // routing change will happen when startOutput() will be called
François Gaffie11d30102018-11-02 16:09:09 +01001615 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
jiabina84c3d32022-12-02 18:59:55 +00001616 if (prefMixerConfigInfo != nullptr) {
1617 for (audio_io_handle_t outputHandle : outputs) {
1618 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(outputHandle);
1619 if (outputDesc->mProfile == prefMixerConfigInfo->getProfile()) {
1620 output = outputHandle;
1621 break;
1622 }
1623 }
1624 if (output == AUDIO_IO_HANDLE_NONE) {
1625 // No output open with the preferred profile. Open a new one.
1626 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
1627 config.channel_mask = prefMixerConfigInfo->getConfigBase().channel_mask;
1628 config.sample_rate = prefMixerConfigInfo->getConfigBase().sample_rate;
1629 config.format = prefMixerConfigInfo->getConfigBase().format;
1630 sp<SwAudioOutputDescriptor> preferredOutput = openOutputWithProfileAndDevice(
1631 prefMixerConfigInfo->getProfile(), devices, nullptr /*mixerConfig*/,
1632 &config, prefMixerConfigInfo->getFlags());
1633 if (preferredOutput == nullptr) {
1634 ALOGE("%s failed to open output with preferred mixer config", __func__);
1635 } else {
1636 output = preferredOutput->mIoHandle;
1637 }
1638 }
1639 } else {
1640 // at this stage we should ignore the DIRECT flag as no direct output could be
1641 // found earlier
1642 *flags = (audio_output_flags_t) (*flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
1643 output = selectOutput(
1644 outputs, *flags, config->format, channelMask, config->sample_rate, session);
1645 }
Eric Laurente552edb2014-03-10 17:42:56 -07001646 }
François Gaffie11d30102018-11-02 16:09:09 +01001647 ALOGW_IF((output == 0), "getOutputForDevices() could not find output for stream %d, "
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001648 "sampling rate %d, format %#x, channels %#x, flags %#x",
jiabine375d412019-02-26 12:54:53 -08001649 stream, config->sample_rate, config->format, channelMask, *flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001650
Eric Laurente552edb2014-03-10 17:42:56 -07001651 return output;
1652}
1653
Mikhail Naganovf02f3672018-11-09 12:44:16 -08001654sp<DeviceDescriptor> AudioPolicyManager::getMsdAudioInDevice() const {
François Gaffie11d30102018-11-02 16:09:09 +01001655 auto msdInDevices = mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1656 mAvailableInputDevices);
1657 return msdInDevices.isEmpty()? nullptr : msdInDevices.itemAt(0);
1658}
1659
1660DeviceVector AudioPolicyManager::getMsdAudioOutDevices() const {
1661 return mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1662 mAvailableOutputDevices);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001663}
1664
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001665const AudioPatchCollection AudioPolicyManager::getMsdOutputPatches() const {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001666 AudioPatchCollection msdPatches;
Mikhail Naganov86112352018-10-04 09:02:49 -07001667 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1668 if (msdModule != 0) {
1669 for (size_t i = 0; i < mAudioPatches.size(); ++i) {
1670 sp<AudioPatch> patch = mAudioPatches.valueAt(i);
1671 for (size_t j = 0; j < patch->mPatch.num_sources; ++j) {
1672 const struct audio_port_config *source = &patch->mPatch.sources[j];
1673 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
1674 source->ext.device.hw_module == msdModule->getHandle()) {
François Gaffieafd4cea2019-11-18 15:50:22 +01001675 msdPatches.addAudioPatch(patch->getHandle(), patch);
Mikhail Naganov86112352018-10-04 09:02:49 -07001676 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001677 }
1678 }
1679 }
1680 return msdPatches;
1681}
1682
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02001683bool AudioPolicyManager::isMsdPatch(const audio_patch_handle_t &handle) const {
1684 ssize_t index = mAudioPatches.indexOfKey(handle);
1685 if (index < 0) {
1686 return false;
1687 }
1688 const sp<AudioPatch> patch = mAudioPatches.valueAt(index);
1689 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1690 if (msdModule == nullptr) {
1691 return false;
1692 }
1693 const struct audio_port_config *sink = &patch->mPatch.sinks[0];
1694 if (getMsdAudioOutDevices().contains(mAvailableOutputDevices.getDeviceFromId(sink->id))) {
1695 return true;
1696 }
1697 index = getMsdOutputPatches().indexOfKey(handle);
1698 if (index < 0) {
1699 return false;
1700 }
1701 return true;
1702}
1703
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001704status_t AudioPolicyManager::getMsdProfiles(bool hwAvSync,
1705 const InputProfileCollection &inputProfiles,
1706 const OutputProfileCollection &outputProfiles,
1707 const sp<DeviceDescriptor> &sourceDevice,
1708 const sp<DeviceDescriptor> &sinkDevice,
1709 AudioProfileVector& sourceProfiles,
1710 AudioProfileVector& sinkProfiles) const {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001711 if (inputProfiles.isEmpty()) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001712 ALOGE("%s() no input profiles for source module", __func__);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001713 return NO_INIT;
1714 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001715 if (outputProfiles.isEmpty()) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001716 ALOGE("%s() no output profiles for sink module", __func__);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001717 return NO_INIT;
1718 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001719 for (const auto &inProfile : inputProfiles) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001720 if (hwAvSync == ((inProfile->getFlags() & AUDIO_INPUT_FLAG_HW_AV_SYNC) != 0) &&
1721 inProfile->supportsDevice(sourceDevice)) {
1722 appendAudioProfiles(sourceProfiles, inProfile->getAudioProfiles());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001723 }
1724 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001725 for (const auto &outProfile : outputProfiles) {
Michael Chan6fb34492020-12-08 15:44:49 +11001726 if (hwAvSync == ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) &&
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001727 outProfile->supportsDevice(sinkDevice)) {
1728 appendAudioProfiles(sinkProfiles, outProfile->getAudioProfiles());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001729 }
1730 }
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001731 return NO_ERROR;
1732}
1733
1734status_t AudioPolicyManager::getBestMsdConfig(bool hwAvSync,
1735 const AudioProfileVector &sourceProfiles, const AudioProfileVector &sinkProfiles,
1736 audio_port_config *sourceConfig, audio_port_config *sinkConfig) const
1737{
Dean Wheatley16809da2022-12-09 14:55:46 +11001738 // Compressed formats for MSD module, ordered from most preferred to least preferred.
1739 static const std::vector<audio_format_t> formatsOrder = {{
1740 AUDIO_FORMAT_IEC60958, AUDIO_FORMAT_MAT_2_1, AUDIO_FORMAT_MAT_2_0, AUDIO_FORMAT_E_AC3,
Dean Wheatley0f27c602023-08-23 13:57:21 +10001741 AUDIO_FORMAT_AC3, AUDIO_FORMAT_PCM_FLOAT, AUDIO_FORMAT_PCM_32_BIT,
1742 AUDIO_FORMAT_PCM_8_24_BIT, AUDIO_FORMAT_PCM_24_BIT_PACKED, AUDIO_FORMAT_PCM_16_BIT }};
Dean Wheatley16809da2022-12-09 14:55:46 +11001743 static const std::vector<audio_channel_mask_t> channelMasksOrder = [](){
1744 // Channel position masks for MSD module, 3D > 2D > 1D ordering (most preferred to least
1745 // preferred).
1746 std::vector<audio_channel_mask_t> masks = {{
1747 AUDIO_CHANNEL_OUT_3POINT1POINT2, AUDIO_CHANNEL_OUT_3POINT0POINT2,
1748 AUDIO_CHANNEL_OUT_2POINT1POINT2, AUDIO_CHANNEL_OUT_2POINT0POINT2,
1749 AUDIO_CHANNEL_OUT_5POINT1, AUDIO_CHANNEL_OUT_STEREO }};
1750 // insert index masks (higher counts most preferred) as preferred over position masks
1751 for (int i = 1; i <= AUDIO_CHANNEL_COUNT_MAX; i++) {
1752 masks.insert(
1753 masks.begin(), audio_channel_mask_for_index_assignment_from_count(i));
1754 }
1755 return masks;
1756 }();
1757
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001758 struct audio_config_base bestSinkConfig;
Dean Wheatley16809da2022-12-09 14:55:46 +11001759 status_t result = findBestMatchingOutputConfig(sourceProfiles, sinkProfiles, formatsOrder,
1760 channelMasksOrder, true /*preferHigherSamplingRates*/, bestSinkConfig);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001761 if (result != NO_ERROR) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001762 ALOGD("%s() no matching config found for sink, hwAvSync: %d",
1763 __func__, hwAvSync);
Greg Kaiser83289652018-07-30 06:13:57 -07001764 return result;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001765 }
1766 sinkConfig->sample_rate = bestSinkConfig.sample_rate;
1767 sinkConfig->channel_mask = bestSinkConfig.channel_mask;
1768 sinkConfig->format = bestSinkConfig.format;
1769 // For encoded streams force direct flag to prevent downstream mixing.
1770 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1771 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_DIRECT);
Dean Wheatley5c9f0832019-11-21 13:39:31 +11001772 if (audio_is_iec61937_compatible(sinkConfig->format)) {
1773 // For formats compatible with IEC61937 encapsulation, assume that
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001774 // the input is IEC61937 framed (for proportional buffer sizing).
Dean Wheatley5c9f0832019-11-21 13:39:31 +11001775 // Add the AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO flag so downstream HAL can distinguish between
1776 // raw and IEC61937 framed streams.
1777 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1778 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO);
1779 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001780 sourceConfig->sample_rate = bestSinkConfig.sample_rate;
1781 // Specify exact channel mask to prevent guessing by bit count in PatchPanel.
Dean Wheatley16809da2022-12-09 14:55:46 +11001782 sourceConfig->channel_mask =
1783 audio_channel_mask_get_representation(bestSinkConfig.channel_mask)
1784 == AUDIO_CHANNEL_REPRESENTATION_INDEX ?
1785 bestSinkConfig.channel_mask : audio_channel_mask_out_to_in(bestSinkConfig.channel_mask);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001786 sourceConfig->format = bestSinkConfig.format;
1787 // Copy input stream directly without any processing (e.g. resampling).
1788 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1789 sourceConfig->flags.input | AUDIO_INPUT_FLAG_DIRECT);
1790 if (hwAvSync) {
1791 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1792 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
1793 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1794 sourceConfig->flags.input | AUDIO_INPUT_FLAG_HW_AV_SYNC);
1795 }
1796 const unsigned int config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE |
1797 AUDIO_PORT_CONFIG_CHANNEL_MASK | AUDIO_PORT_CONFIG_FORMAT | AUDIO_PORT_CONFIG_FLAGS;
1798 sinkConfig->config_mask |= config_mask;
1799 sourceConfig->config_mask |= config_mask;
1800 return NO_ERROR;
1801}
1802
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001803PatchBuilder AudioPolicyManager::buildMsdPatch(bool msdIsSource,
1804 const sp<DeviceDescriptor> &device) const
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001805{
1806 PatchBuilder patchBuilder;
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001807 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1808 ALOG_ASSERT(msdModule != nullptr, "MSD module not available");
1809 sp<HwModule> deviceModule = mHwModules.getModuleForDevice(device, AUDIO_FORMAT_DEFAULT);
1810 if (deviceModule == nullptr) {
1811 ALOGE("%s() unable to get module for %s", __func__, device->toString().c_str());
1812 return patchBuilder;
1813 }
1814 const InputProfileCollection inputProfiles = msdIsSource ?
1815 msdModule->getInputProfiles() : deviceModule->getInputProfiles();
1816 const OutputProfileCollection outputProfiles = msdIsSource ?
1817 deviceModule->getOutputProfiles() : msdModule->getOutputProfiles();
1818
1819 const sp<DeviceDescriptor> sourceDevice = msdIsSource ? getMsdAudioInDevice() : device;
1820 const sp<DeviceDescriptor> sinkDevice = msdIsSource ?
1821 device : getMsdAudioOutDevices().itemAt(0);
1822 patchBuilder.addSource(sourceDevice).addSink(sinkDevice);
1823
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001824 audio_port_config sourceConfig = patchBuilder.patch()->sources[0];
1825 audio_port_config sinkConfig = patchBuilder.patch()->sinks[0];
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001826 AudioProfileVector sourceProfiles;
1827 AudioProfileVector sinkProfiles;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001828 // TODO: Figure out whether MSD module has HW_AV_SYNC flag set in the AP config file.
1829 // For now, we just forcefully try with HwAvSync first.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001830 for (auto hwAvSync : { true, false }) {
1831 if (getMsdProfiles(hwAvSync, inputProfiles, outputProfiles, sourceDevice, sinkDevice,
1832 sourceProfiles, sinkProfiles) != NO_ERROR) {
1833 continue;
1834 }
1835 if (getBestMsdConfig(hwAvSync, sourceProfiles, sinkProfiles, &sourceConfig,
1836 &sinkConfig) == NO_ERROR) {
1837 // Found a matching config. Re-create PatchBuilder with this config.
1838 return (PatchBuilder()).addSource(sourceConfig).addSink(sinkConfig);
1839 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001840 }
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001841 ALOGV("%s() no matching config found. Fall through to default PCM patch"
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001842 " supporting PCM format conversion.", __func__);
1843 return patchBuilder;
1844}
1845
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001846status_t AudioPolicyManager::setMsdOutputPatches(const DeviceVector *outputDevices) {
Michael Chan6fb34492020-12-08 15:44:49 +11001847 DeviceVector devices;
1848 if (outputDevices != nullptr && outputDevices->size() > 0) {
1849 devices.add(*outputDevices);
1850 } else {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001851 // Use media strategy for unspecified output device. This should only
1852 // occur on checkForDeviceAndOutputChanges(). Device connection events may
1853 // therefore invalidate explicit routing requests.
Michael Chan6fb34492020-12-08 15:44:49 +11001854 devices = mEngine->getOutputDevicesForAttributes(
François Gaffiec005e562018-11-06 15:04:49 +01001855 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
Michael Chan6fb34492020-12-08 15:44:49 +11001856 LOG_ALWAYS_FATAL_IF(devices.isEmpty(), "no output device to set MSD patch");
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001857 }
Michael Chan6fb34492020-12-08 15:44:49 +11001858 std::vector<PatchBuilder> patchesToCreate;
1859 for (auto i = 0u; i < devices.size(); ++i) {
1860 ALOGV("%s() for device %s", __func__, devices[i]->toString().c_str());
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001861 patchesToCreate.push_back(buildMsdPatch(true /*msdIsSource*/, devices[i]));
Michael Chan6fb34492020-12-08 15:44:49 +11001862 }
1863 // Retain only the MSD patches associated with outputDevices request.
1864 // Tear down the others, and create new ones as needed.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001865 AudioPatchCollection patchesToRemove = getMsdOutputPatches();
Michael Chan6fb34492020-12-08 15:44:49 +11001866 for (auto it = patchesToCreate.begin(); it != patchesToCreate.end(); ) {
1867 auto retainedPatch = false;
1868 for (auto i = 0u; i < patchesToRemove.size(); ++i) {
1869 if (audio_patches_are_equal(it->patch(), &patchesToRemove[i]->mPatch)) {
1870 patchesToRemove.removeItemsAt(i);
1871 retainedPatch = true;
1872 break;
1873 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001874 }
Michael Chan6fb34492020-12-08 15:44:49 +11001875 if (retainedPatch) {
1876 it = patchesToCreate.erase(it);
1877 continue;
1878 }
1879 ++it;
1880 }
1881 if (patchesToCreate.size() == 0 && patchesToRemove.size() == 0) {
1882 return NO_ERROR;
1883 }
1884 for (auto i = 0u; i < patchesToRemove.size(); ++i) {
1885 auto &currentPatch = patchesToRemove.valueAt(i);
François Gaffieafd4cea2019-11-18 15:50:22 +01001886 releaseAudioPatch(currentPatch->getHandle(), mUidCached);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001887 }
Michael Chan6fb34492020-12-08 15:44:49 +11001888 status_t status = NO_ERROR;
1889 for (const auto &p : patchesToCreate) {
1890 auto currStatus = installPatch(__func__, -1 /*index*/, nullptr /*patchHandle*/,
1891 p.patch(), 0 /*delayMs*/, mUidCached, nullptr /*patchDescPtr*/);
1892 char message[256];
1893 snprintf(message, sizeof(message), "%s() %s: creating MSD patch from device:IN_BUS to "
1894 "device:%#x (format:%#x channels:%#x samplerate:%d)", __func__,
1895 currStatus == NO_ERROR ? "Success" : "Error",
1896 p.patch()->sinks[0].ext.device.type, p.patch()->sources[0].format,
1897 p.patch()->sources[0].channel_mask, p.patch()->sources[0].sample_rate);
1898 if (currStatus == NO_ERROR) {
1899 ALOGD("%s", message);
1900 } else {
1901 ALOGE("%s", message);
1902 if (status == NO_ERROR) {
1903 status = currStatus;
1904 }
1905 }
1906 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001907 return status;
1908}
1909
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001910void AudioPolicyManager::releaseMsdOutputPatches(const DeviceVector& devices) {
1911 AudioPatchCollection msdPatches = getMsdOutputPatches();
Michael Chan6fb34492020-12-08 15:44:49 +11001912 for (size_t i = 0; i < msdPatches.size(); i++) {
1913 const auto& patch = msdPatches[i];
1914 for (size_t j = 0; j < patch->mPatch.num_sinks; ++j) {
1915 const struct audio_port_config *sink = &patch->mPatch.sinks[j];
1916 if (sink->type == AUDIO_PORT_TYPE_DEVICE && devices.getDevice(sink->ext.device.type,
1917 String8(sink->ext.device.address), AUDIO_FORMAT_DEFAULT) != nullptr) {
1918 releaseAudioPatch(patch->getHandle(), mUidCached);
1919 break;
1920 }
1921 }
1922 }
1923}
1924
Dorin Drimus94d94412022-02-02 09:05:02 +01001925bool AudioPolicyManager::msdHasPatchesToAllDevices(const AudioDeviceTypeAddrVector& devices) {
Mikhail Naganov68e3f642023-04-28 13:06:32 -07001926 DeviceVector devicesToCheck =
1927 mConfig->getOutputDevices().getDevicesFromDeviceTypeAddrVec(devices);
Dorin Drimus94d94412022-02-02 09:05:02 +01001928 AudioPatchCollection msdPatches = getMsdOutputPatches();
1929 for (size_t i = 0; i < msdPatches.size(); i++) {
1930 const auto& patch = msdPatches[i];
1931 for (size_t j = 0; j < patch->mPatch.num_sinks; ++j) {
1932 const struct audio_port_config *sink = &patch->mPatch.sinks[j];
1933 if (sink->type == AUDIO_PORT_TYPE_DEVICE) {
1934 const auto& foundDevice = devicesToCheck.getDevice(
1935 sink->ext.device.type, String8(sink->ext.device.address), AUDIO_FORMAT_DEFAULT);
1936 if (foundDevice != nullptr) {
1937 devicesToCheck.remove(foundDevice);
1938 if (devicesToCheck.isEmpty()) {
1939 return true;
1940 }
1941 }
1942 }
1943 }
1944 }
1945 return false;
1946}
1947
Eric Laurente0720872014-03-11 09:30:41 -07001948audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
jiabinebb6af42020-06-09 17:31:17 -07001949 audio_output_flags_t flags,
1950 audio_format_t format,
1951 audio_channel_mask_t channelMask,
1952 uint32_t samplingRate,
1953 audio_session_t sessionId)
Eric Laurente552edb2014-03-10 17:42:56 -07001954{
Eric Laurent16c66dd2019-05-01 17:54:10 -07001955 LOG_ALWAYS_FATAL_IF(!(format == AUDIO_FORMAT_INVALID || audio_is_linear_pcm(format)),
1956 "%s called with format %#x", __func__, format);
1957
jiabinebb6af42020-06-09 17:31:17 -07001958 // Return the output that haptic-generating attached to when 1) session id is specified,
1959 // 2) haptic-generating effect exists for given session id and 3) the output that
1960 // haptic-generating effect attached to is in given outputs.
1961 if (sessionId != AUDIO_SESSION_NONE) {
1962 audio_io_handle_t hapticGeneratingOutput = mEffects.getIoForSession(
1963 sessionId, FX_IID_HAPTICGENERATOR);
1964 if (outputs.indexOf(hapticGeneratingOutput) >= 0) {
1965 return hapticGeneratingOutput;
1966 }
1967 }
1968
Eric Laurent16c66dd2019-05-01 17:54:10 -07001969 // Flags disqualifying an output: the match must happen before calling selectOutput()
1970 static const audio_output_flags_t kExcludedFlags = (audio_output_flags_t)
1971 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ | AUDIO_OUTPUT_FLAG_DIRECT);
1972
1973 // Flags expressing a functional request: must be honored in priority over
1974 // other criteria
1975 static const audio_output_flags_t kFunctionalFlags = (audio_output_flags_t)
1976 (AUDIO_OUTPUT_FLAG_VOIP_RX | AUDIO_OUTPUT_FLAG_INCALL_MUSIC |
Eric Laurente28c66d2022-01-21 13:40:41 +01001977 AUDIO_OUTPUT_FLAG_TTS | AUDIO_OUTPUT_FLAG_DIRECT_PCM | AUDIO_OUTPUT_FLAG_ULTRASOUND |
1978 AUDIO_OUTPUT_FLAG_SPATIALIZER);
Eric Laurent16c66dd2019-05-01 17:54:10 -07001979 // Flags expressing a performance request: have lower priority than serving
1980 // requested sampling rate or channel mask
1981 static const audio_output_flags_t kPerformanceFlags = (audio_output_flags_t)
1982 (AUDIO_OUTPUT_FLAG_FAST | AUDIO_OUTPUT_FLAG_DEEP_BUFFER |
1983 AUDIO_OUTPUT_FLAG_RAW | AUDIO_OUTPUT_FLAG_SYNC);
1984
1985 const audio_output_flags_t functionalFlags =
1986 (audio_output_flags_t)(flags & kFunctionalFlags);
1987 const audio_output_flags_t performanceFlags =
1988 (audio_output_flags_t)(flags & kPerformanceFlags);
1989
1990 audio_io_handle_t bestOutput = (outputs.size() == 0) ? AUDIO_IO_HANDLE_NONE : outputs[0];
1991
Eric Laurente552edb2014-03-10 17:42:56 -07001992 // select one output among several that provide a path to a particular device or set of
François Gaffie11d30102018-11-02 16:09:09 +01001993 // devices (the list was previously build by getOutputsForDevices()).
Eric Laurente552edb2014-03-10 17:42:56 -07001994 // The priority is as follows:
jiabin40573322018-11-08 12:08:02 -08001995 // 1: the output supporting haptic playback when requesting haptic playback
Eric Laurent16c66dd2019-05-01 17:54:10 -07001996 // 2: the output with the highest number of requested functional flags
Carter Hsu199f1892021-10-15 15:47:29 +08001997 // with tiebreak preferring the minimum number of extra functional flags
1998 // (see b/200293124, the incorrect selection of AUDIO_OUTPUT_FLAG_VOIP_RX).
Eric Laurent16c66dd2019-05-01 17:54:10 -07001999 // 3: the output supporting the exact channel mask
2000 // 4: the output with a higher channel count than requested
jiabinb12a6da2022-06-03 20:48:18 +00002001 // 5: the output with the highest sampling rate if the requested sample rate is
2002 // greater than default sampling rate
Eric Laurent16c66dd2019-05-01 17:54:10 -07002003 // 6: the output with the highest number of requested performance flags
2004 // 7: the output with the bit depth the closest to the requested one
2005 // 8: the primary output
2006 // 9: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07002007
Eric Laurent16c66dd2019-05-01 17:54:10 -07002008 // matching criteria values in priority order for best matching output so far
2009 std::vector<uint32_t> bestMatchCriteria(8, 0);
Eric Laurente552edb2014-03-10 17:42:56 -07002010
Eric Laurent16c66dd2019-05-01 17:54:10 -07002011 const uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
2012 const uint32_t hapticChannelCount = audio_channel_count_from_out_mask(
2013 channelMask & AUDIO_CHANNEL_HAPTIC_ALL);
Eric Laurente78b6762018-12-19 16:29:01 -08002014
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002015 for (audio_io_handle_t output : outputs) {
2016 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent16c66dd2019-05-01 17:54:10 -07002017 // matching criteria values in priority order for current output
2018 std::vector<uint32_t> currentMatchCriteria(8, 0);
jiabin40573322018-11-08 12:08:02 -08002019
Eric Laurent16c66dd2019-05-01 17:54:10 -07002020 if (outputDesc->isDuplicated()) {
2021 continue;
2022 }
2023 if ((kExcludedFlags & outputDesc->mFlags) != 0) {
2024 continue;
2025 }
Eric Laurent8838a382014-09-08 16:44:28 -07002026
Eric Laurent16c66dd2019-05-01 17:54:10 -07002027 // If haptic channel is specified, use the haptic output if present.
2028 // When using haptic output, same audio format and sample rate are required.
2029 const uint32_t outputHapticChannelCount = audio_channel_count_from_out_mask(
jiabin5740f082019-08-19 15:08:30 -07002030 outputDesc->getChannelMask() & AUDIO_CHANNEL_HAPTIC_ALL);
Eric Laurent16c66dd2019-05-01 17:54:10 -07002031 if ((hapticChannelCount == 0) != (outputHapticChannelCount == 0)) {
2032 continue;
2033 }
2034 if (outputHapticChannelCount >= hapticChannelCount
jiabin5740f082019-08-19 15:08:30 -07002035 && format == outputDesc->getFormat()
2036 && samplingRate == outputDesc->getSamplingRate()) {
Eric Laurent16c66dd2019-05-01 17:54:10 -07002037 currentMatchCriteria[0] = outputHapticChannelCount;
2038 }
2039
2040 // functional flags match
Carter Hsu199f1892021-10-15 15:47:29 +08002041 const int matchingFunctionalFlags =
2042 __builtin_popcount(outputDesc->mFlags & functionalFlags);
2043 const int totalFunctionalFlags =
2044 __builtin_popcount(outputDesc->mFlags & kFunctionalFlags);
2045 // Prefer matching functional flags, but subtract unnecessary functional flags.
2046 currentMatchCriteria[1] = 100 * (matchingFunctionalFlags + 1) - totalFunctionalFlags;
Eric Laurent16c66dd2019-05-01 17:54:10 -07002047
2048 // channel mask and channel count match
jiabin5740f082019-08-19 15:08:30 -07002049 uint32_t outputChannelCount = audio_channel_count_from_out_mask(
2050 outputDesc->getChannelMask());
Eric Laurent16c66dd2019-05-01 17:54:10 -07002051 if (channelMask != AUDIO_CHANNEL_NONE && channelCount > 2 &&
2052 channelCount <= outputChannelCount) {
2053 if ((audio_channel_mask_get_representation(channelMask) ==
jiabin5740f082019-08-19 15:08:30 -07002054 audio_channel_mask_get_representation(outputDesc->getChannelMask())) &&
2055 ((channelMask & outputDesc->getChannelMask()) == channelMask)) {
Eric Laurent16c66dd2019-05-01 17:54:10 -07002056 currentMatchCriteria[2] = outputChannelCount;
Eric Laurente552edb2014-03-10 17:42:56 -07002057 }
Eric Laurent16c66dd2019-05-01 17:54:10 -07002058 currentMatchCriteria[3] = outputChannelCount;
2059 }
2060
2061 // sampling rate match
jiabinb12a6da2022-06-03 20:48:18 +00002062 if (samplingRate > SAMPLE_RATE_HZ_DEFAULT) {
jiabin5740f082019-08-19 15:08:30 -07002063 currentMatchCriteria[4] = outputDesc->getSamplingRate();
Eric Laurent16c66dd2019-05-01 17:54:10 -07002064 }
2065
2066 // performance flags match
2067 currentMatchCriteria[5] = popcount(outputDesc->mFlags & performanceFlags);
2068
2069 // format match
2070 if (format != AUDIO_FORMAT_INVALID) {
2071 currentMatchCriteria[6] =
jiabin4ef93452019-09-10 14:29:54 -07002072 PolicyAudioPort::kFormatDistanceMax -
2073 PolicyAudioPort::formatDistance(format, outputDesc->getFormat());
Eric Laurent16c66dd2019-05-01 17:54:10 -07002074 }
2075
2076 // primary output match
2077 currentMatchCriteria[7] = outputDesc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY;
2078
2079 // compare match criteria by priority then value
2080 if (std::lexicographical_compare(bestMatchCriteria.begin(), bestMatchCriteria.end(),
2081 currentMatchCriteria.begin(), currentMatchCriteria.end())) {
2082 bestMatchCriteria = currentMatchCriteria;
2083 bestOutput = output;
2084
2085 std::stringstream result;
2086 std::copy(bestMatchCriteria.begin(), bestMatchCriteria.end(),
2087 std::ostream_iterator<int>(result, " "));
2088 ALOGV("%s new bestOutput %d criteria %s",
2089 __func__, bestOutput, result.str().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07002090 }
2091 }
2092
Eric Laurent16c66dd2019-05-01 17:54:10 -07002093 return bestOutput;
Eric Laurente552edb2014-03-10 17:42:56 -07002094}
2095
Eric Laurent8fc147b2018-07-22 19:13:55 -07002096status_t AudioPolicyManager::startOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002097{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002098 ALOGV("%s portId %d", __FUNCTION__, portId);
2099
2100 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2101 if (outputDesc == 0) {
2102 ALOGW("startOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002103 return BAD_VALUE;
2104 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002105 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002106
Eric Laurent8fc147b2018-07-22 19:13:55 -07002107 ALOGV("startOutput() output %d, stream %d, session %d",
Eric Laurent97ac8712018-07-27 18:59:02 -07002108 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurentc75307b2015-03-17 15:29:32 -07002109
Eric Laurent733ce942017-12-07 12:18:25 -08002110 status_t status = outputDesc->start();
2111 if (status != NO_ERROR) {
2112 return status;
Eric Laurent3974e3b2017-12-07 17:58:43 -08002113 }
2114
Eric Laurent97ac8712018-07-27 18:59:02 -07002115 uint32_t delayMs;
2116 status = startSource(outputDesc, client, &delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07002117
2118 if (status != NO_ERROR) {
Eric Laurent733ce942017-12-07 12:18:25 -08002119 outputDesc->stop();
jiabin3ff8d7d2022-12-13 06:27:44 +00002120 if (status == DEAD_OBJECT) {
2121 sp<SwAudioOutputDescriptor> desc =
2122 reopenOutput(outputDesc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
2123 if (desc == nullptr) {
2124 // This is not common, it may indicate something wrong with the HAL.
2125 ALOGE("%s unable to open output with default config", __func__);
2126 return status;
2127 }
2128 desc->mUsePreferredMixerAttributes = true;
2129 }
Eric Laurent8c7e6da2015-04-21 17:37:00 -07002130 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07002131 }
jiabina84c3d32022-12-02 18:59:55 +00002132
2133 // If the client is the first one active on preferred mixer parameters, reopen the output
2134 // if the current mixer parameters doesn't match the preferred one.
2135 if (outputDesc->devices().size() == 1) {
2136 sp<PreferredMixerAttributesInfo> info = getPreferredMixerAttributesInfo(
2137 outputDesc->devices()[0]->getId(), client->strategy());
2138 if (info != nullptr && info->getUid() == client->uid()) {
2139 if (info->getActiveClientCount() == 0 && !outputDesc->isConfigurationMatched(
2140 info->getConfigBase(), info->getFlags())) {
2141 stopSource(outputDesc, client);
2142 outputDesc->stop();
2143 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
2144 config.channel_mask = info->getConfigBase().channel_mask;
2145 config.sample_rate = info->getConfigBase().sample_rate;
2146 config.format = info->getConfigBase().format;
jiabin3ff8d7d2022-12-13 06:27:44 +00002147 sp<SwAudioOutputDescriptor> desc =
2148 reopenOutput(outputDesc, &config, info->getFlags(), __func__);
2149 if (desc == nullptr) {
2150 return BAD_VALUE;
jiabina84c3d32022-12-02 18:59:55 +00002151 }
jiabin3ff8d7d2022-12-13 06:27:44 +00002152 desc->mUsePreferredMixerAttributes = true;
jiabina84c3d32022-12-02 18:59:55 +00002153 // Intentionally return error to let the client side resending request for
2154 // creating and starting.
2155 return DEAD_OBJECT;
2156 }
2157 info->increaseActiveClient();
jiabine3d1f552023-06-14 17:42:17 +00002158 if (info->getActiveClientCount() == 1 &&
2159 (info->getFlags() & AUDIO_OUTPUT_FLAG_BIT_PERFECT) != AUDIO_OUTPUT_FLAG_NONE) {
2160 // If it is first bit-perfect client, reroute all clients that will be routed to
2161 // the bit-perfect sink so that it is guaranteed only bit-perfect stream is active.
2162 PortHandleVector clientsToInvalidate;
2163 for (size_t i = 0; i < mOutputs.size(); i++) {
2164 if (mOutputs[i] == outputDesc ||
jiabin98c519c2023-07-05 17:34:21 +00002165 mOutputs[i]->devices().filter(outputDesc->devices()).isEmpty()) {
jiabine3d1f552023-06-14 17:42:17 +00002166 continue;
2167 }
2168 for (const auto& c : mOutputs[i]->getClientIterable()) {
2169 clientsToInvalidate.push_back(c->portId());
2170 }
2171 }
2172 if (!clientsToInvalidate.empty()) {
2173 ALOGD("%s Invalidate clients due to first bit-perfect client started",
2174 __func__);
2175 mpClientInterface->invalidateTracks(clientsToInvalidate);
2176 }
2177 }
jiabina84c3d32022-12-02 18:59:55 +00002178 }
2179 }
2180
Jean-Michel Trivib1f6e642023-02-07 20:49:04 +00002181 if (client->hasPreferredDevice()) {
2182 // playback activity with preferred device impacts routing occurred, inform upper layers
2183 mpClientInterface->onRoutingUpdated();
2184 }
Eric Laurentc75307b2015-03-17 15:29:32 -07002185 if (delayMs != 0) {
2186 usleep(delayMs * 1000);
2187 }
2188
2189 return status;
2190}
2191
Eric Laurent96d1dda2022-03-14 17:14:19 +01002192bool AudioPolicyManager::isLeUnicastActive() const {
2193 if (isInCall()) {
2194 return true;
2195 }
2196 return isAnyDeviceTypeActive(getAudioDeviceOutLeAudioUnicastSet());
2197}
2198
2199bool AudioPolicyManager::isAnyDeviceTypeActive(const DeviceTypeSet& deviceTypes) const {
2200 if (mAvailableOutputDevices.getDevicesFromTypes(deviceTypes).isEmpty()) {
2201 return false;
2202 }
2203 bool active = mOutputs.isAnyDeviceTypeActive(deviceTypes);
2204 ALOGV("%s active %d", __func__, active);
2205 return active;
2206}
2207
Eric Laurent97ac8712018-07-27 18:59:02 -07002208status_t AudioPolicyManager::startSource(const sp<SwAudioOutputDescriptor>& outputDesc,
2209 const sp<TrackClientDescriptor>& client,
2210 uint32_t *delayMs)
Eric Laurentc75307b2015-03-17 15:29:32 -07002211{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002212 // cannot start playback of STREAM_TTS if any other output is being used
2213 uint32_t beaconMuteLatency = 0;
Eric Laurentc75307b2015-03-17 15:29:32 -07002214
2215 *delayMs = 0;
Eric Laurent97ac8712018-07-27 18:59:02 -07002216 audio_stream_type_t stream = client->stream();
François Gaffie1c878552018-11-22 16:53:21 +01002217 auto clientVolSrc = client->volumeSource();
François Gaffiec005e562018-11-06 15:04:49 +01002218 auto clientStrategy = client->strategy();
2219 auto clientAttr = client->attributes();
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002220 if (stream == AUDIO_STREAM_TTS) {
2221 ALOGV("\t found BEACON stream");
François Gaffie1c878552018-11-22 16:53:21 +01002222 if (!mTtsOutputAvailable && mOutputs.isAnyOutputActive(
Francois Gaffie4404ddb2021-02-04 17:03:38 +01002223 toVolumeSource(AUDIO_STREAM_TTS, false) /*sourceToIgnore*/)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002224 return INVALID_OPERATION;
2225 } else {
2226 beaconMuteLatency = handleEventForBeacon(STARTING_BEACON);
2227 }
2228 } else {
2229 // some playback other than beacon starts
2230 beaconMuteLatency = handleEventForBeacon(STARTING_OUTPUT);
2231 }
2232
Eric Laurent77305a62016-07-25 16:39:22 -07002233 // force device change if the output is inactive and no audio patch is already present.
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002234 // check active before incrementing usage count
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02002235 bool force = !outputDesc->isActive() && !outputDesc->isRouted();
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002236
François Gaffie11d30102018-11-02 16:09:09 +01002237 DeviceVector devices;
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002238 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
Eric Laurent97ac8712018-07-27 18:59:02 -07002239 const char *address = NULL;
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002240 if (policyMix != nullptr) {
François Gaffie11d30102018-11-02 16:09:09 +01002241 audio_devices_t newDeviceType;
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00002242 address = policyMix->mDeviceAddress.c_str();
Kevin Rocard153f92d2018-12-18 18:33:28 -08002243 if ((policyMix->mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie11d30102018-11-02 16:09:09 +01002244 newDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Kevin Rocard153f92d2018-12-18 18:33:28 -08002245 } else {
2246 newDeviceType = policyMix->mDeviceType;
Eric Laurent97ac8712018-07-27 18:59:02 -07002247 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08002248 sp device = mAvailableOutputDevices.getDevice(newDeviceType, String8(address),
2249 AUDIO_FORMAT_DEFAULT);
2250 ALOG_ASSERT(device, "%s: no device found t=%u, a=%s", __func__, newDeviceType, address);
2251 devices.add(device);
Eric Laurent97ac8712018-07-27 18:59:02 -07002252 }
2253
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002254 // requiresMuteCheck is false when we can bypass mute strategy.
2255 // It covers a common case when there is no materially active audio
2256 // and muting would result in unnecessary delay and dropped audio.
2257 const uint32_t outputLatencyMs = outputDesc->latency();
2258 bool requiresMuteCheck = outputDesc->isActive(outputLatencyMs * 2); // account for drain
Eric Laurent96d1dda2022-03-14 17:14:19 +01002259 bool wasLeUnicastActive = isLeUnicastActive();
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002260
Eric Laurente552edb2014-03-10 17:42:56 -07002261 // increment usage count for this stream on the requested output:
2262 // NOTE that the usage count is the same for duplicated output and hardware output which is
2263 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
Eric Laurent592dd7b2018-08-05 18:58:48 -07002264 outputDesc->setClientActive(client, true);
Eric Laurent97ac8712018-07-27 18:59:02 -07002265
2266 if (client->hasPreferredDevice(true)) {
Eric Laurent72af8012023-03-15 17:36:22 +01002267 if (outputDesc->sameExclusivePreferredDevicesCount() > 0) {
François Gaffief96e5432019-04-09 17:13:56 +02002268 // Preferred device may be exclusive, use only if no other active clients on this output
2269 devices = DeviceVector(
2270 mAvailableOutputDevices.getDeviceFromId(client->preferredDeviceId()));
2271 } else {
2272 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
2273 }
François Gaffie11d30102018-11-02 16:09:09 +01002274 if (devices != outputDesc->devices()) {
François Gaffiec005e562018-11-06 15:04:49 +01002275 checkStrategyRoute(clientStrategy, outputDesc->mIoHandle);
Eric Laurent97ac8712018-07-27 18:59:02 -07002276 }
2277 }
Eric Laurente552edb2014-03-10 17:42:56 -07002278
François Gaffiec005e562018-11-06 15:04:49 +01002279 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07002280 selectOutputForMusicEffects();
2281 }
2282
François Gaffie1c878552018-11-22 16:53:21 +01002283 if (outputDesc->getActivityCount(clientVolSrc) == 1 || !devices.isEmpty()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08002284 // starting an output being rerouted?
François Gaffie11d30102018-11-02 16:09:09 +01002285 if (devices.isEmpty()) {
2286 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Eric Laurent275e8e92014-11-30 15:14:47 -08002287 }
François Gaffiec005e562018-11-06 15:04:49 +01002288 bool shouldWait =
2289 (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM)) ||
2290 followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_NOTIFICATION)) ||
2291 (beaconMuteLatency > 0));
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002292 uint32_t waitMs = beaconMuteLatency;
Eric Laurente552edb2014-03-10 17:42:56 -07002293 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01002294 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07002295 if (desc != outputDesc) {
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002296 // An output has a shared device if
2297 // - managed by the same hw module
2298 // - supports the currently selected device
2299 const bool sharedDevice = outputDesc->sharesHwModuleWith(desc)
François Gaffie11d30102018-11-02 16:09:09 +01002300 && (!desc->filterSupportedDevices(devices).isEmpty());
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002301
Eric Laurent77305a62016-07-25 16:39:22 -07002302 // force a device change if any other output is:
2303 // - managed by the same hw module
Jean-Michel Trivi4a5b4812018-02-08 17:22:32 +00002304 // - supports currently selected device
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002305 // - has a current device selection that differs from selected device.
Eric Laurent77305a62016-07-25 16:39:22 -07002306 // - has an active audio patch
Eric Laurente552edb2014-03-10 17:42:56 -07002307 // In this case, the audio HAL must receive the new device selection so that it can
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002308 // change the device currently selected by the other output.
2309 if (sharedDevice &&
François Gaffie11d30102018-11-02 16:09:09 +01002310 desc->devices() != devices &&
Eric Laurent77305a62016-07-25 16:39:22 -07002311 desc->getPatchHandle() != AUDIO_PATCH_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07002312 force = true;
2313 }
2314 // wait for audio on other active outputs to be presented when starting
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002315 // a notification so that audio focus effect can propagate, or that a mute/unmute
2316 // event occurred for beacon
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002317 const uint32_t latencyMs = desc->latency();
2318 const bool isActive = desc->isActive(latencyMs * 2); // account for drain
2319
2320 if (shouldWait && isActive && (waitMs < latencyMs)) {
2321 waitMs = latencyMs;
Eric Laurente552edb2014-03-10 17:42:56 -07002322 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002323
2324 // Require mute check if another output is on a shared device
2325 // and currently active to have proper drain and avoid pops.
2326 // Note restoring AudioTracks onto this output needs to invoke
2327 // a volume ramp if there is no mute.
2328 requiresMuteCheck |= sharedDevice && isActive;
Eric Laurente552edb2014-03-10 17:42:56 -07002329 }
2330 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002331
jiabin3ff8d7d2022-12-13 06:27:44 +00002332 if (outputDesc->mUsePreferredMixerAttributes && devices != outputDesc->devices()) {
2333 // If the output is open with preferred mixer attributes, but the routed device is
2334 // changed when calling this function, returning DEAD_OBJECT to indicate routing
2335 // changed.
2336 return DEAD_OBJECT;
2337 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002338 const uint32_t muteWaitMs =
jiabin3ff8d7d2022-12-13 06:27:44 +00002339 setOutputDevices(outputDesc, devices, force, 0, nullptr, requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07002340
Eric Laurente552edb2014-03-10 17:42:56 -07002341 // apply volume rules for current stream and device if necessary
François Gaffieaaac0fd2018-11-22 17:56:39 +01002342 auto &curves = getVolumeCurves(client->attributes());
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00002343 if (NO_ERROR != checkAndSetVolume(curves, client->volumeSource(),
François Gaffieaaac0fd2018-11-22 17:56:39 +01002344 curves.getVolumeIndex(outputDesc->devices().types()),
Eric Laurentc75307b2015-03-17 15:29:32 -07002345 outputDesc,
Francois Gaffied11442b2020-04-27 11:51:09 +02002346 outputDesc->devices().types(), 0 /*delay*/,
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00002347 outputDesc->useHwGain() /*force*/)) {
2348 // request AudioService to reinitialize the volume curves asynchronously
2349 ALOGE("checkAndSetVolume failed, requesting volume range init");
2350 mpClientInterface->onVolumeRangeInitRequest();
2351 };
Eric Laurente552edb2014-03-10 17:42:56 -07002352
2353 // update the outputs if starting an output with a stream that can affect notification
2354 // routing
2355 handleNotificationRoutingForStream(stream);
Eric Laurentc722f302014-12-10 11:21:49 -08002356
Eric Laurent2cbe89a2014-12-19 11:49:08 -08002357 // force reevaluating accessibility routing when ringtone or alarm starts
François Gaffiec005e562018-11-06 15:04:49 +01002358 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM))) {
jiabinc44b3462022-12-08 12:52:31 -08002359 invalidateStreams({AUDIO_STREAM_ACCESSIBILITY});
Eric Laurent2cbe89a2014-12-19 11:49:08 -08002360 }
Eric Laurentdc462862016-07-19 12:29:53 -07002361
2362 if (waitMs > muteWaitMs) {
2363 *delayMs = waitMs - muteWaitMs;
2364 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002365
2366 // FIXME: A device change (muteWaitMs > 0) likely introduces a volume change.
2367 // A volume change enacted by APM with 0 delay is not synchronous, as it goes
2368 // via AudioCommandThread to AudioFlinger. Hence it is possible that the volume
2369 // change occurs after the MixerThread starts and causes a stream volume
2370 // glitch.
2371 //
2372 // We do not introduce additional delay here.
Eric Laurente552edb2014-03-10 17:42:56 -07002373 }
Eric Laurentdc462862016-07-19 12:29:53 -07002374
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002375 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
jiabin9a3361e2019-10-01 09:38:30 -07002376 mEngine->getForceUse(
2377 AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
François Gaffiec005e562018-11-06 15:04:49 +01002378 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), true, outputDesc);
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002379 }
2380
Eric Laurent97ac8712018-07-27 18:59:02 -07002381 // Automatically enable the remote submix input when output is started on a re routing mix
2382 // of type MIX_TYPE_RECORDERS
jiabin9a3361e2019-10-01 09:38:30 -07002383 if (isSingleDeviceType(devices.types(), &audio_is_remote_submix_device) &&
2384 policyMix != NULL && policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002385 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2386 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2387 address,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002388 "remote-submix",
2389 AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07002390 }
2391
Eric Laurent96d1dda2022-03-14 17:14:19 +01002392 checkLeBroadcastRoutes(wasLeUnicastActive, outputDesc, *delayMs);
2393
Eric Laurente552edb2014-03-10 17:42:56 -07002394 return NO_ERROR;
2395}
2396
Eric Laurent96d1dda2022-03-14 17:14:19 +01002397void AudioPolicyManager::checkLeBroadcastRoutes(bool wasUnicastActive,
2398 sp<SwAudioOutputDescriptor> ignoredOutput, uint32_t delayMs) {
2399 bool isUnicastActive = isLeUnicastActive();
2400
2401 if (wasUnicastActive != isUnicastActive) {
jiabin3ff8d7d2022-12-13 06:27:44 +00002402 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent96d1dda2022-03-14 17:14:19 +01002403 //reroute all outputs routed to LE broadcast if LE unicast activy changed on any output
2404 for (size_t i = 0; i < mOutputs.size(); i++) {
2405 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
2406 if (desc != ignoredOutput && desc->isActive()
2407 && ((isUnicastActive &&
2408 !desc->devices().
2409 getDevicesFromType(AUDIO_DEVICE_OUT_BLE_BROADCAST).isEmpty())
2410 || (wasUnicastActive &&
2411 !desc->devices().getDevicesFromTypes(
2412 getAudioDeviceOutLeAudioUnicastSet()).isEmpty()))) {
2413 DeviceVector newDevices = getNewOutputDevices(desc, false /*fromCache*/);
2414 bool force = desc->devices() != newDevices;
jiabin3ff8d7d2022-12-13 06:27:44 +00002415 if (desc->mUsePreferredMixerAttributes && force) {
2416 // If the device is using preferred mixer attributes, the output need to reopen
2417 // with default configuration when the new selected devices are different from
2418 // current routing devices.
2419 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices);
2420 continue;
2421 }
Eric Laurent96d1dda2022-03-14 17:14:19 +01002422 setOutputDevices(desc, newDevices, force, delayMs);
2423 // re-apply device specific volume if not done by setOutputDevice()
2424 if (!force) {
2425 applyStreamVolumes(desc, newDevices.types(), delayMs);
2426 }
2427 }
2428 }
jiabin3ff8d7d2022-12-13 06:27:44 +00002429 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent96d1dda2022-03-14 17:14:19 +01002430 }
2431}
2432
Eric Laurent8fc147b2018-07-22 19:13:55 -07002433status_t AudioPolicyManager::stopOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002434{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002435 ALOGV("%s portId %d", __FUNCTION__, portId);
2436
2437 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2438 if (outputDesc == 0) {
2439 ALOGW("stopOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002440 return BAD_VALUE;
2441 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002442 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002443
Jean-Michel Trivib1f6e642023-02-07 20:49:04 +00002444 if (client->hasPreferredDevice(true)) {
2445 // playback activity with preferred device impacts routing occurred, inform upper layers
2446 mpClientInterface->onRoutingUpdated();
2447 }
2448
Eric Laurent97ac8712018-07-27 18:59:02 -07002449 ALOGV("stopOutput() output %d, stream %d, session %d",
2450 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurente552edb2014-03-10 17:42:56 -07002451
Eric Laurent97ac8712018-07-27 18:59:02 -07002452 status_t status = stopSource(outputDesc, client);
Eric Laurent3974e3b2017-12-07 17:58:43 -08002453
Eric Laurent733ce942017-12-07 12:18:25 -08002454 if (status == NO_ERROR ) {
2455 outputDesc->stop();
jiabina84c3d32022-12-02 18:59:55 +00002456 } else {
2457 return status;
2458 }
2459
2460 if (outputDesc->devices().size() == 1) {
2461 sp<PreferredMixerAttributesInfo> info = getPreferredMixerAttributesInfo(
2462 outputDesc->devices()[0]->getId(), client->strategy());
2463 if (info != nullptr && info->getUid() == client->uid()) {
2464 info->decreaseActiveClient();
2465 if (info->getActiveClientCount() == 0) {
2466 reopenOutput(outputDesc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
2467 }
2468 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002469 }
2470 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07002471}
2472
Eric Laurent97ac8712018-07-27 18:59:02 -07002473status_t AudioPolicyManager::stopSource(const sp<SwAudioOutputDescriptor>& outputDesc,
2474 const sp<TrackClientDescriptor>& client)
Eric Laurentc75307b2015-03-17 15:29:32 -07002475{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002476 // always handle stream stop, check which stream type is stopping
Eric Laurent97ac8712018-07-27 18:59:02 -07002477 audio_stream_type_t stream = client->stream();
François Gaffie1c878552018-11-22 16:53:21 +01002478 auto clientVolSrc = client->volumeSource();
Eric Laurent96d1dda2022-03-14 17:14:19 +01002479 bool wasLeUnicastActive = isLeUnicastActive();
Eric Laurent97ac8712018-07-27 18:59:02 -07002480
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002481 handleEventForBeacon(stream == AUDIO_STREAM_TTS ? STOPPING_BEACON : STOPPING_OUTPUT);
2482
François Gaffie1c878552018-11-22 16:53:21 +01002483 if (outputDesc->getActivityCount(clientVolSrc) > 0) {
2484 if (outputDesc->getActivityCount(clientVolSrc) == 1) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002485 // Automatically disable the remote submix input when output is stopped on a
2486 // re routing mix of type MIX_TYPE_RECORDERS
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002487 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
jiabin9a3361e2019-10-01 09:38:30 -07002488 if (isSingleDeviceType(
2489 outputDesc->devices().types(), &audio_is_remote_submix_device) &&
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002490 policyMix != nullptr &&
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002491 policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002492 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2493 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002494 policyMix->mDeviceAddress,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002495 "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07002496 }
2497 }
2498 bool forceDeviceUpdate = false;
Eric Laurent72af8012023-03-15 17:36:22 +01002499 if (client->hasPreferredDevice(true) &&
2500 outputDesc->sameExclusivePreferredDevicesCount() < 2) {
François Gaffiec005e562018-11-06 15:04:49 +01002501 checkStrategyRoute(client->strategy(), AUDIO_IO_HANDLE_NONE);
Eric Laurent97ac8712018-07-27 18:59:02 -07002502 forceDeviceUpdate = true;
2503 }
2504
Eric Laurente552edb2014-03-10 17:42:56 -07002505 // decrement usage count of this stream on the output
Eric Laurent592dd7b2018-08-05 18:58:48 -07002506 outputDesc->setClientActive(client, false);
Paul McLeanaa981192015-03-21 09:55:15 -07002507
Eric Laurente552edb2014-03-10 17:42:56 -07002508 // store time at which the stream was stopped - see isStreamActive()
François Gaffie1c878552018-11-22 16:53:21 +01002509 if (outputDesc->getActivityCount(clientVolSrc) == 0 || forceDeviceUpdate) {
François Gaffiec005e562018-11-06 15:04:49 +01002510 outputDesc->setStopTime(client, systemTime());
François Gaffie11d30102018-11-02 16:09:09 +01002511 DeviceVector newDevices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Francois Gaffie3523ab32021-06-22 13:24:34 +02002512
2513 // If the routing does not change, if an output is routed on a device using HwGain
2514 // (aka setAudioPortConfig) and there are still active clients following different
2515 // volume group(s), force reapply volume
2516 bool requiresVolumeCheck = outputDesc->getActivityCount(clientVolSrc) == 0 &&
2517 outputDesc->useHwGain() && outputDesc->isAnyActive(VOLUME_SOURCE_NONE);
2518
Eric Laurente552edb2014-03-10 17:42:56 -07002519 // delay the device switch by twice the latency because stopOutput() is executed when
2520 // the track stop() command is received and at that time the audio track buffer can
2521 // still contain data that needs to be drained. The latency only covers the audio HAL
2522 // and kernel buffers. Also the latency does not always include additional delay in the
2523 // audio path (audio DSP, CODEC ...)
Francois Gaffie3523ab32021-06-22 13:24:34 +02002524 setOutputDevices(outputDesc, newDevices, false, outputDesc->latency()*2,
2525 nullptr, true /*requiresMuteCheck*/, requiresVolumeCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07002526
2527 // force restoring the device selection on other active outputs if it differs from the
2528 // one being selected for this output
jiabin3ff8d7d2022-12-13 06:27:44 +00002529 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent57de36c2016-09-28 16:59:11 -07002530 uint32_t delayMs = outputDesc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -07002531 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01002532 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07002533 if (desc != outputDesc &&
Eric Laurente552edb2014-03-10 17:42:56 -07002534 desc->isActive() &&
2535 outputDesc->sharesHwModuleWith(desc) &&
François Gaffie11d30102018-11-02 16:09:09 +01002536 (newDevices != desc->devices())) {
2537 DeviceVector newDevices2 = getNewOutputDevices(desc, false /*fromCache*/);
2538 bool force = desc->devices() != newDevices2;
Eric Laurentf3a5a602018-05-22 18:42:55 -07002539
jiabin3ff8d7d2022-12-13 06:27:44 +00002540 if (desc->mUsePreferredMixerAttributes && force) {
2541 // If the device is using preferred mixer attributes, the output need to
2542 // reopen with default configuration when the new selected devices are
2543 // different from current routing devices.
2544 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices2);
2545 continue;
2546 }
François Gaffie11d30102018-11-02 16:09:09 +01002547 setOutputDevices(desc, newDevices2, force, delayMs);
2548
Eric Laurent57de36c2016-09-28 16:59:11 -07002549 // re-apply device specific volume if not done by setOutputDevice()
2550 if (!force) {
François Gaffie11d30102018-11-02 16:09:09 +01002551 applyStreamVolumes(desc, newDevices2.types(), delayMs);
Eric Laurent57de36c2016-09-28 16:59:11 -07002552 }
Eric Laurente552edb2014-03-10 17:42:56 -07002553 }
2554 }
jiabin3ff8d7d2022-12-13 06:27:44 +00002555 reopenOutputsWithDevices(outputsToReopen);
Eric Laurente552edb2014-03-10 17:42:56 -07002556 // update the outputs if stopping one with a stream that can affect notification routing
2557 handleNotificationRoutingForStream(stream);
2558 }
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002559
2560 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
2561 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Jean-Michel Trivi74e01fa2019-02-25 12:18:09 -08002562 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), false, outputDesc);
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002563 }
2564
François Gaffiec005e562018-11-06 15:04:49 +01002565 if (followsSameRouting(client->attributes(), attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07002566 selectOutputForMusicEffects();
2567 }
Eric Laurent96d1dda2022-03-14 17:14:19 +01002568
2569 checkLeBroadcastRoutes(wasLeUnicastActive, outputDesc, outputDesc->latency()*2);
2570
Eric Laurente552edb2014-03-10 17:42:56 -07002571 return NO_ERROR;
2572 } else {
Eric Laurentc75307b2015-03-17 15:29:32 -07002573 ALOGW("stopOutput() refcount is already 0");
Eric Laurente552edb2014-03-10 17:42:56 -07002574 return INVALID_OPERATION;
2575 }
2576}
2577
jiabinbce0c1d2020-10-05 11:20:18 -07002578bool AudioPolicyManager::releaseOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002579{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002580 ALOGV("%s portId %d", __FUNCTION__, portId);
2581
2582 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2583 if (outputDesc == 0) {
Andy Hung39efb7a2018-09-26 15:39:28 -07002584 // If an output descriptor is closed due to a device routing change,
2585 // then there are race conditions with releaseOutput from tracks
2586 // that may be destroyed (with no PlaybackThread) or a PlaybackThread
2587 // destroyed shortly thereafter.
2588 //
2589 // Here we just log a warning, instead of a fatal error.
Eric Laurent8fc147b2018-07-22 19:13:55 -07002590 ALOGW("releaseOutput() no output for client %d", portId);
jiabinbce0c1d2020-10-05 11:20:18 -07002591 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002592 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002593
2594 ALOGV("releaseOutput() %d", outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -07002595
Jaideep Sharma7bf382e2020-11-26 17:07:29 +05302596 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
2597 if (outputDesc->isClientActive(client)) {
2598 ALOGW("releaseOutput() inactivates portId %d in good faith", portId);
2599 stopOutput(portId);
2600 }
2601
Eric Laurent8fc147b2018-07-22 19:13:55 -07002602 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
2603 if (outputDesc->mDirectOpenCount <= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07002604 ALOGW("releaseOutput() invalid open count %d for output %d",
Eric Laurent8fc147b2018-07-22 19:13:55 -07002605 outputDesc->mDirectOpenCount, outputDesc->mIoHandle);
jiabinbce0c1d2020-10-05 11:20:18 -07002606 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002607 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002608 if (--outputDesc->mDirectOpenCount == 0) {
2609 closeOutput(outputDesc->mIoHandle);
Eric Laurentb52c1522014-05-20 11:27:36 -07002610 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07002611 }
2612 }
Jaideep Sharma7bf382e2020-11-26 17:07:29 +05302613
Andy Hung39efb7a2018-09-26 15:39:28 -07002614 outputDesc->removeClient(portId);
jiabinbce0c1d2020-10-05 11:20:18 -07002615 if (outputDesc->mPendingReopenToQueryProfiles && outputDesc->getClientCount() == 0) {
2616 // The output is pending reopened to query dynamic profiles and
2617 // there is no active clients
2618 closeOutput(outputDesc->mIoHandle);
2619 sp<SwAudioOutputDescriptor> newOutputDesc = openOutputWithProfileAndDevice(
2620 outputDesc->mProfile, mEngine->getActiveMediaDevices(mAvailableOutputDevices));
2621 if (newOutputDesc == nullptr) {
2622 ALOGE("%s failed to open output", __func__);
2623 }
2624 return true;
2625 }
2626 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002627}
2628
Eric Laurentcaf7f482014-11-25 17:50:47 -08002629status_t AudioPolicyManager::getInputForAttr(const audio_attributes_t *attr,
2630 audio_io_handle_t *input,
Mikhail Naganov2996f672019-04-18 12:29:59 -07002631 audio_unique_id_t riid,
Eric Laurentcaf7f482014-11-25 17:50:47 -08002632 audio_session_t session,
Svet Ganov3e5f14f2021-05-13 22:51:08 +00002633 const AttributionSourceState& attributionSource,
jiabinf1c73972022-04-14 16:28:52 -07002634 audio_config_base_t *config,
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002635 audio_input_flags_t flags,
Eric Laurent2ac76942017-06-22 17:17:09 -07002636 audio_port_handle_t *selectedDeviceId,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002637 input_type_t *inputType,
2638 audio_port_handle_t *portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002639{
François Gaffiec005e562018-11-06 15:04:49 +01002640 ALOGV("%s() source %d, sampling rate %d, format %#x, channel mask %#x, session %d, "
Eric Laurent2f2c1982021-06-02 14:03:11 +02002641 "flags %#x attributes=%s requested device ID %d",
2642 __func__, attr->source, config->sample_rate, config->format, config->channel_mask,
2643 session, flags, toString(*attr).c_str(), *selectedDeviceId);
Eric Laurente552edb2014-03-10 17:42:56 -07002644
Eric Laurentad2e7b92017-09-14 20:06:42 -07002645 status_t status = NO_ERROR;
Francois Gaffie716e1432019-01-14 16:58:59 +01002646 audio_attributes_t attributes = *attr;
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002647 sp<AudioPolicyMix> policyMix;
François Gaffie11d30102018-11-02 16:09:09 +01002648 sp<DeviceDescriptor> device;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002649 sp<AudioInputDescriptor> inputDesc;
2650 sp<RecordClientDescriptor> clientDesc;
2651 audio_port_handle_t requestedDeviceId = *selectedDeviceId;
Svet Ganov3e5f14f2021-05-13 22:51:08 +00002652 uid_t uid = VALUE_OR_RETURN_STATUS(aidl2legacy_int32_t_uid_t(attributionSource.uid));
Eric Laurent8f42ea12018-08-08 09:08:25 -07002653 bool isSoundTrigger;
Eric Laurent8f42ea12018-08-08 09:08:25 -07002654
2655 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
2656 if (*portId != AUDIO_PORT_HANDLE_NONE) {
2657 return INVALID_OPERATION;
2658 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08002659
Francois Gaffie716e1432019-01-14 16:58:59 +01002660 if (attr->source == AUDIO_SOURCE_DEFAULT) {
2661 attributes.source = AUDIO_SOURCE_MIC;
Eric Laurentfe231122017-11-17 17:48:06 -08002662 }
2663
Paul McLean466dc8e2015-04-17 13:15:36 -06002664 // Explicit routing?
Pattydd807582021-11-04 21:01:03 +08002665 sp<DeviceDescriptor> explicitRoutingDevice =
François Gaffie11d30102018-11-02 16:09:09 +01002666 mAvailableInputDevices.getDeviceFromId(*selectedDeviceId);
Paul McLean466dc8e2015-04-17 13:15:36 -06002667
Eric Laurentad2e7b92017-09-14 20:06:42 -07002668 // special case for mmap capture: if an input IO handle is specified, we reuse this input if
2669 // possible
2670 if ((flags & AUDIO_INPUT_FLAG_MMAP_NOIRQ) == AUDIO_INPUT_FLAG_MMAP_NOIRQ &&
2671 *input != AUDIO_IO_HANDLE_NONE) {
2672 ssize_t index = mInputs.indexOfKey(*input);
2673 if (index < 0) {
2674 ALOGW("getInputForAttr() unknown MMAP input %d", *input);
2675 status = BAD_VALUE;
2676 goto error;
2677 }
2678 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002679 RecordClientVector clients = inputDesc->getClientsForSession(session);
2680 if (clients.size() == 0) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07002681 ALOGW("getInputForAttr() unknown session %d on input %d", session, *input);
2682 status = BAD_VALUE;
2683 goto error;
2684 }
2685 // For MMAP mode, the first call to getInputForAttr() is made on behalf of audioflinger.
2686 // The second call is for the first active client and sets the UID. Any further call
Eric Laurent331679c2018-04-16 17:03:16 -07002687 // corresponds to a new client and is only permitted from the same UID.
2688 // If the first UID is silenced, allow a new UID connection and replace with new UID
Eric Laurent8f42ea12018-08-08 09:08:25 -07002689 if (clients.size() > 1) {
2690 for (const auto& client : clients) {
2691 // The client map is ordered by key values (portId) and portIds are allocated
2692 // incrementaly. So the first client in this list is the one opened by audio flinger
2693 // when the mmap stream is created and should be ignored as it does not correspond
2694 // to an actual client
2695 if (client == *clients.cbegin()) {
2696 continue;
2697 }
2698 if (uid != client->uid() && !client->isSilenced()) {
2699 ALOGW("getInputForAttr() bad uid %d for client %d uid %d",
2700 uid, client->portId(), client->uid());
2701 status = INVALID_OPERATION;
2702 goto error;
2703 }
Eric Laurent331679c2018-04-16 17:03:16 -07002704 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002705 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002706 *inputType = API_INPUT_LEGACY;
François Gaffie11d30102018-11-02 16:09:09 +01002707 device = inputDesc->getDevice();
Eric Laurentad2e7b92017-09-14 20:06:42 -07002708
Eric Laurentfecbceb2021-02-09 14:46:43 +01002709 ALOGV("%s reusing MMAP input %d for session %d", __FUNCTION__, *input, session);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002710 goto exit;
Eric Laurentad2e7b92017-09-14 20:06:42 -07002711 }
2712
2713 *input = AUDIO_IO_HANDLE_NONE;
2714 *inputType = API_INPUT_INVALID;
2715
Francois Gaffie716e1432019-01-14 16:58:59 +01002716 if (attributes.source == AUDIO_SOURCE_REMOTE_SUBMIX &&
Jan Sebechlebskybc56bcd2022-09-26 13:15:19 +02002717 extractAddressFromAudioAttributes(attributes).has_value()) {
Francois Gaffie716e1432019-01-14 16:58:59 +01002718 status = mPolicyMixes.getInputMixForAttr(attributes, &policyMix);
Eric Laurentad2e7b92017-09-14 20:06:42 -07002719 if (status != NO_ERROR) {
jiabinc1de2df2019-05-07 14:26:40 -07002720 ALOGW("%s could not find input mix for attr %s",
2721 __func__, toString(attributes).c_str());
Eric Laurentad2e7b92017-09-14 20:06:42 -07002722 goto error;
François Gaffie036e1e92015-03-19 10:16:24 +01002723 }
jiabinc1de2df2019-05-07 14:26:40 -07002724 device = mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2725 String8(attr->tags + strlen("addr=")),
2726 AUDIO_FORMAT_DEFAULT);
2727 if (device == nullptr) {
Kevin Rocard04ed0462019-05-02 17:53:24 -07002728 ALOGW("%s could not find in Remote Submix device for source %d, tags %s",
jiabinc1de2df2019-05-07 14:26:40 -07002729 __func__, attributes.source, attributes.tags);
2730 status = BAD_VALUE;
2731 goto error;
2732 }
2733
Kevin Rocard25f9b052019-02-27 15:08:54 -08002734 if (is_mix_loopback_render(policyMix->mRouteFlags)) {
2735 *inputType = API_INPUT_MIX_PUBLIC_CAPTURE_PLAYBACK;
2736 } else {
2737 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
2738 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002739 } else {
François Gaffie11d30102018-11-02 16:09:09 +01002740 if (explicitRoutingDevice != nullptr) {
2741 device = explicitRoutingDevice;
Eric Laurent97ac8712018-07-27 18:59:02 -07002742 } else {
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01002743 // Prevent from storing invalid requested device id in clients
2744 requestedDeviceId = AUDIO_PORT_HANDLE_NONE;
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02002745 device = mEngine->getInputDeviceForAttributes(attributes, uid, session, &policyMix);
yuanjiahsu4069d5d2021-04-19 07:54:27 +08002746 ALOGV_IF(device != nullptr, "%s found device type is 0x%X",
2747 __FUNCTION__, device->type());
Eric Laurent97ac8712018-07-27 18:59:02 -07002748 }
François Gaffie11d30102018-11-02 16:09:09 +01002749 if (device == nullptr) {
Francois Gaffie716e1432019-01-14 16:58:59 +01002750 ALOGW("getInputForAttr() could not find device for source %d", attributes.source);
Eric Laurentad2e7b92017-09-14 20:06:42 -07002751 status = BAD_VALUE;
2752 goto error;
Eric Laurent275e8e92014-11-30 15:14:47 -08002753 }
Alden DSouzab7d20782021-02-08 08:51:42 -08002754 if (device->type() == AUDIO_DEVICE_IN_ECHO_REFERENCE) {
2755 *inputType = API_INPUT_MIX_CAPTURE;
2756 } else if (policyMix) {
François Gaffie11d30102018-11-02 16:09:09 +01002757 ALOG_ASSERT(policyMix->mMixType == MIX_TYPE_RECORDERS, "Invalid Mix Type");
2758 // there is an external policy, but this input is attached to a mix of recorders,
2759 // meaning it receives audio injected into the framework, so the recorder doesn't
2760 // know about it and is therefore considered "legacy"
2761 *inputType = API_INPUT_LEGACY;
2762 } else if (audio_is_remote_submix_device(device->type())) {
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002763 *inputType = API_INPUT_MIX_CAPTURE;
François Gaffie11d30102018-11-02 16:09:09 +01002764 } else if (device->type() == AUDIO_DEVICE_IN_TELEPHONY_RX) {
Eric Laurent82db2692015-08-07 13:59:42 -07002765 *inputType = API_INPUT_TELEPHONY_RX;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002766 } else {
2767 *inputType = API_INPUT_LEGACY;
Eric Laurentc722f302014-12-10 11:21:49 -08002768 }
Ravi Kumar Alamandab367f5b2015-08-25 08:21:37 -07002769
Eric Laurent599c7582015-12-07 18:05:55 -08002770 }
2771
François Gaffiec005e562018-11-06 15:04:49 +01002772 *input = getInputForDevice(device, session, attributes, config, flags, policyMix);
Eric Laurent599c7582015-12-07 18:05:55 -08002773 if (*input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07002774 status = INVALID_OPERATION;
jiabinf1c73972022-04-14 16:28:52 -07002775 AudioProfileVector profiles;
2776 status_t ret = getProfilesForDevices(
2777 DeviceVector(device), profiles, flags, true /*isInput*/);
2778 if (ret == NO_ERROR && !profiles.empty()) {
2779 config->channel_mask = profiles[0]->getChannels().empty() ? config->channel_mask
2780 : *profiles[0]->getChannels().begin();
2781 config->sample_rate = profiles[0]->getSampleRates().empty() ? config->sample_rate
2782 : *profiles[0]->getSampleRates().begin();
2783 config->format = profiles[0]->getFormat();
2784 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002785 goto error;
Eric Laurent599c7582015-12-07 18:05:55 -08002786 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08002787
Eric Laurent8f42ea12018-08-08 09:08:25 -07002788exit:
2789
François Gaffiec005e562018-11-06 15:04:49 +01002790 *selectedDeviceId = mAvailableInputDevices.contains(device) ?
2791 device->getId() : AUDIO_PORT_HANDLE_NONE;
Eric Laurent2ac76942017-06-22 17:17:09 -07002792
Francois Gaffie716e1432019-01-14 16:58:59 +01002793 isSoundTrigger = attributes.source == AUDIO_SOURCE_HOTWORD &&
Carter Hsud0cce2e2019-05-03 17:36:28 +08002794 mSoundTriggerSessions.indexOfKey(session) >= 0;
jiabin4ef93452019-09-10 14:29:54 -07002795 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002796
Mikhail Naganov2996f672019-04-18 12:29:59 -07002797 clientDesc = new RecordClientDescriptor(*portId, riid, uid, session, attributes, *config,
Francois Gaffie716e1432019-01-14 16:58:59 +01002798 requestedDeviceId, attributes.source, flags,
2799 isSoundTrigger);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002800 inputDesc = mInputs.valueFor(*input);
Andy Hung39efb7a2018-09-26 15:39:28 -07002801 inputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002802
2803 ALOGV("getInputForAttr() returns input %d type %d selectedDeviceId %d for port ID %d",
2804 *input, *inputType, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07002805
Eric Laurent599c7582015-12-07 18:05:55 -08002806 return NO_ERROR;
Eric Laurentad2e7b92017-09-14 20:06:42 -07002807
2808error:
Eric Laurentad2e7b92017-09-14 20:06:42 -07002809 return status;
Eric Laurent599c7582015-12-07 18:05:55 -08002810}
2811
2812
François Gaffie11d30102018-11-02 16:09:09 +01002813audio_io_handle_t AudioPolicyManager::getInputForDevice(const sp<DeviceDescriptor> &device,
Eric Laurent599c7582015-12-07 18:05:55 -08002814 audio_session_t session,
François Gaffiec005e562018-11-06 15:04:49 +01002815 const audio_attributes_t &attributes,
jiabinf1c73972022-04-14 16:28:52 -07002816 audio_config_base_t *config,
Eric Laurent599c7582015-12-07 18:05:55 -08002817 audio_input_flags_t flags,
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002818 const sp<AudioPolicyMix> &policyMix)
Eric Laurent599c7582015-12-07 18:05:55 -08002819{
2820 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
François Gaffiec005e562018-11-06 15:04:49 +01002821 audio_source_t halInputSource = attributes.source;
Eric Laurent599c7582015-12-07 18:05:55 -08002822 bool isSoundTrigger = false;
2823
François Gaffiec005e562018-11-06 15:04:49 +01002824 if (attributes.source == AUDIO_SOURCE_HOTWORD) {
Eric Laurent599c7582015-12-07 18:05:55 -08002825 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
2826 if (index >= 0) {
2827 input = mSoundTriggerSessions.valueFor(session);
2828 isSoundTrigger = true;
2829 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_HW_HOTWORD);
2830 ALOGV("SoundTrigger capture on session %d input %d", session, input);
2831 } else {
2832 halInputSource = AUDIO_SOURCE_VOICE_RECOGNITION;
Eric Laurent5dbe4712014-09-19 19:04:57 -07002833 }
François Gaffiec005e562018-11-06 15:04:49 +01002834 } else if (attributes.source == AUDIO_SOURCE_VOICE_COMMUNICATION &&
Eric Laurentfe231122017-11-17 17:48:06 -08002835 audio_is_linear_pcm(config->format)) {
Haynes Mathew George851d3ff2017-06-19 20:01:57 -07002836 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_VOIP_TX);
Eric Laurent5dbe4712014-09-19 19:04:57 -07002837 }
2838
Carter Hsua3abb402021-10-26 11:11:20 +08002839 if (attributes.source == AUDIO_SOURCE_ULTRASOUND) {
2840 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_ULTRASOUND);
2841 }
2842
Eric Laurentfe231122017-11-17 17:48:06 -08002843 // sampling rate and flags may be updated by getInputProfile
2844 uint32_t profileSamplingRate = (config->sample_rate == 0) ?
2845 SAMPLE_RATE_HZ_DEFAULT : config->sample_rate;
jiabin2fd710d2022-05-02 23:20:22 +00002846 audio_format_t profileFormat = config->format;
Eric Laurentfe231122017-11-17 17:48:06 -08002847 audio_channel_mask_t profileChannelMask = config->channel_mask;
Andy Hungf129b032015-04-07 13:45:50 -07002848 audio_input_flags_t profileFlags = flags;
jiabin2fd710d2022-05-02 23:20:22 +00002849 // find a compatible input profile (not necessarily identical in parameters)
2850 sp<IOProfile> profile = getInputProfile(
2851 device, profileSamplingRate, profileFormat, profileChannelMask, profileFlags);
2852 if (profile == nullptr) {
2853 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07002854 }
jiabin2fd710d2022-05-02 23:20:22 +00002855
Glenn Kasten05ddca52016-02-11 08:17:12 -08002856 // Pick input sampling rate if not specified by client
Eric Laurentfe231122017-11-17 17:48:06 -08002857 uint32_t samplingRate = config->sample_rate;
Glenn Kasten05ddca52016-02-11 08:17:12 -08002858 if (samplingRate == 0) {
2859 samplingRate = profileSamplingRate;
2860 }
Eric Laurente552edb2014-03-10 17:42:56 -07002861
Eric Laurent322b4d22015-04-03 15:57:54 -07002862 if (profile->getModuleHandle() == 0) {
2863 ALOGE("getInputForAttr(): HW module %s not opened", profile->getModuleName());
Eric Laurent599c7582015-12-07 18:05:55 -08002864 return input;
Eric Laurentcf2c0212014-07-25 16:20:43 -07002865 }
2866
Eric Laurentec376dc2021-04-08 20:41:22 +02002867 // Reuse an already opened input if a client with the same session ID already exists
2868 // on that input
2869 for (size_t i = 0; i < mInputs.size(); i++) {
2870 sp <AudioInputDescriptor> desc = mInputs.valueAt(i);
2871 if (desc->mProfile != profile) {
2872 continue;
2873 }
2874 RecordClientVector clients = desc->clientsList();
2875 for (const auto &client : clients) {
2876 if (session == client->session()) {
2877 return desc->mIoHandle;
2878 }
2879 }
2880 }
2881
Eric Laurent3974e3b2017-12-07 17:58:43 -08002882 if (!profile->canOpenNewIo()) {
Eric Laurent4eb58f12018-12-07 16:41:02 -08002883 for (size_t i = 0; i < mInputs.size(); ) {
Eric Laurentc529cf62020-04-17 18:19:10 -07002884 sp<AudioInputDescriptor> desc = mInputs.valueAt(i);
Eric Laurent4eb58f12018-12-07 16:41:02 -08002885 if (desc->mProfile != profile) {
Carter Hsu9a645a92019-05-15 12:15:32 +08002886 i++;
Eric Laurent4eb58f12018-12-07 16:41:02 -08002887 continue;
2888 }
2889 // if sound trigger, reuse input if used by other sound trigger on same session
2890 // else
2891 // reuse input if active client app is not in IDLE state
2892 //
2893 RecordClientVector clients = desc->clientsList();
2894 bool doClose = false;
2895 for (const auto& client : clients) {
2896 if (isSoundTrigger != client->isSoundTrigger()) {
2897 continue;
2898 }
2899 if (client->isSoundTrigger()) {
2900 if (session == client->session()) {
2901 return desc->mIoHandle;
2902 }
2903 continue;
2904 }
2905 if (client->active() && client->appState() != APP_STATE_IDLE) {
2906 return desc->mIoHandle;
2907 }
2908 doClose = true;
2909 }
2910 if (doClose) {
2911 closeInput(desc->mIoHandle);
2912 } else {
2913 i++;
2914 }
2915 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002916 }
2917
Eric Laurentfe231122017-11-17 17:48:06 -08002918 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07002919
Eric Laurentfe231122017-11-17 17:48:06 -08002920 audio_config_t lConfig = AUDIO_CONFIG_INITIALIZER;
2921 lConfig.sample_rate = profileSamplingRate;
2922 lConfig.channel_mask = profileChannelMask;
2923 lConfig.format = profileFormat;
Eric Laurente3014102017-05-03 11:15:43 -07002924
François Gaffie11d30102018-11-02 16:09:09 +01002925 status_t status = inputDesc->open(&lConfig, device, halInputSource, profileFlags, &input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07002926
2927 // only accept input with the exact requested set of parameters
Eric Laurent599c7582015-12-07 18:05:55 -08002928 if (status != NO_ERROR || input == AUDIO_IO_HANDLE_NONE ||
Eric Laurentfe231122017-11-17 17:48:06 -08002929 (profileSamplingRate != lConfig.sample_rate) ||
2930 !audio_formats_match(profileFormat, lConfig.format) ||
2931 (profileChannelMask != lConfig.channel_mask)) {
2932 ALOGW("getInputForAttr() failed opening input: sampling rate %d"
Glenn Kasten49f36ba2017-12-06 13:02:02 -08002933 ", format %#x, channel mask %#x",
Eric Laurentfe231122017-11-17 17:48:06 -08002934 profileSamplingRate, profileFormat, profileChannelMask);
Eric Laurent599c7582015-12-07 18:05:55 -08002935 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfe231122017-11-17 17:48:06 -08002936 inputDesc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07002937 }
Eric Laurent599c7582015-12-07 18:05:55 -08002938 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07002939 }
2940
Eric Laurentc722f302014-12-10 11:21:49 -08002941 inputDesc->mPolicyMix = policyMix;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002942
Eric Laurent599c7582015-12-07 18:05:55 -08002943 addInput(input, inputDesc);
Eric Laurentb52c1522014-05-20 11:27:36 -07002944 mpClientInterface->onAudioPortListUpdate();
Paul McLean466dc8e2015-04-17 13:15:36 -06002945
Eric Laurent599c7582015-12-07 18:05:55 -08002946 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07002947}
2948
Eric Laurent4eb58f12018-12-07 16:41:02 -08002949status_t AudioPolicyManager::startInput(audio_port_handle_t portId)
Eric Laurentbb948092017-01-23 18:33:30 -08002950{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002951 ALOGV("%s portId %d", __FUNCTION__, portId);
2952
2953 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2954 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002955 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurentd52a28c2020-08-21 17:10:39 -07002956 return DEAD_OBJECT;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002957 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002958 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07002959 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002960 if (client->active()) {
2961 ALOGW("%s input %d client %d already started", __FUNCTION__, input, client->portId());
2962 return INVALID_OPERATION;
Eric Laurent4dc68062014-07-28 17:26:49 -07002963 }
2964
Eric Laurent8f42ea12018-08-08 09:08:25 -07002965 audio_session_t session = client->session();
2966
Eric Laurent4eb58f12018-12-07 16:41:02 -08002967 ALOGV("%s input:%d, session:%d)", __FUNCTION__, input, session);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002968
Eric Laurent4eb58f12018-12-07 16:41:02 -08002969 Vector<sp<AudioInputDescriptor>> activeInputs = mInputs.getActiveInputs();
Eric Laurent74708e72017-04-07 17:13:42 -07002970
Eric Laurent4eb58f12018-12-07 16:41:02 -08002971 status_t status = inputDesc->start();
2972 if (status != NO_ERROR) {
2973 return status;
Eric Laurent74708e72017-04-07 17:13:42 -07002974 }
Eric Laurente552edb2014-03-10 17:42:56 -07002975
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002976 // increment activity count before calling getNewInputDevice() below as only active sessions
Eric Laurent313d1e72016-01-29 09:56:57 -08002977 // are considered for device selection
Eric Laurent8f42ea12018-08-08 09:08:25 -07002978 inputDesc->setClientActive(client, true);
Eric Laurent313d1e72016-01-29 09:56:57 -08002979
Eric Laurent8f42ea12018-08-08 09:08:25 -07002980 // indicate active capture to sound trigger service if starting capture from a mic on
2981 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01002982 sp<DeviceDescriptor> device = getNewInputDevice(inputDesc);
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002983 if (device != nullptr) {
2984 status = setInputDevice(input, device, true /* force */);
2985 } else {
2986 ALOGW("%s no new input device can be found for descriptor %d",
2987 __FUNCTION__, inputDesc->getId());
2988 status = BAD_VALUE;
2989 }
Eric Laurente552edb2014-03-10 17:42:56 -07002990
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002991 if (status == NO_ERROR && inputDesc->activeCount() == 1) {
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002992 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002993 // if input maps to a dynamic policy with an activity listener, notify of state change
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002994 if ((policyMix != nullptr)
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002995 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
2996 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
Eric Laurent8f42ea12018-08-08 09:08:25 -07002997 MIX_STATE_MIXING);
Eric Laurent733ce942017-12-07 12:18:25 -08002998 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002999
François Gaffie11d30102018-11-02 16:09:09 +01003000 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
3001 if (primaryInputDevices.contains(device) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07003002 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 1) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07003003 mpClientInterface->setSoundTriggerCaptureState(true);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003004 }
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07003005
Eric Laurent8f42ea12018-08-08 09:08:25 -07003006 // automatically enable the remote submix output when input is started if not
3007 // used by a policy mix of type MIX_TYPE_RECORDERS
3008 // For remote submix (a virtual device), we open only one input per capture request.
François Gaffie11d30102018-11-02 16:09:09 +01003009 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003010 String8 address = String8("");
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003011 if (policyMix == nullptr) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003012 address = String8("0");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003013 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
3014 address = policyMix->mDeviceAddress;
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07003015 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07003016 if (address != "") {
3017 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
3018 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08003019 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurentc722f302014-12-10 11:21:49 -08003020 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07003021 }
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003022 } else if (status != NO_ERROR) {
3023 // Restore client activity state.
3024 inputDesc->setClientActive(client, false);
3025 inputDesc->stop();
Eric Laurente552edb2014-03-10 17:42:56 -07003026 }
3027
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003028 ALOGV("%s input %d source = %d status = %d exit",
3029 __FUNCTION__, input, client->source(), status);
Eric Laurente552edb2014-03-10 17:42:56 -07003030
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003031 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07003032}
3033
Eric Laurent8fc147b2018-07-22 19:13:55 -07003034status_t AudioPolicyManager::stopInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07003035{
Eric Laurent8fc147b2018-07-22 19:13:55 -07003036 ALOGV("%s portId %d", __FUNCTION__, portId);
3037
3038 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
3039 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003040 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07003041 return BAD_VALUE;
3042 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07003043 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07003044 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003045 if (!client->active()) {
3046 ALOGW("%s input %d client %d already stopped", __FUNCTION__, input, client->portId());
Eric Laurente552edb2014-03-10 17:42:56 -07003047 return INVALID_OPERATION;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003048 }
Carter Hsue6139d52021-07-08 10:30:20 +08003049 auto old_source = inputDesc->source();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003050 inputDesc->setClientActive(client, false);
Paul McLean466dc8e2015-04-17 13:15:36 -06003051
Eric Laurent8f42ea12018-08-08 09:08:25 -07003052 inputDesc->stop();
3053 if (inputDesc->isActive()) {
Carter Hsue6139d52021-07-08 10:30:20 +08003054 auto current_source = inputDesc->source();
3055 setInputDevice(input, getNewInputDevice(inputDesc),
3056 old_source != current_source /* force */);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003057 } else {
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003058 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003059 // if input maps to a dynamic policy with an activity listener, notify of state change
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003060 if ((policyMix != nullptr)
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003061 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
3062 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
Eric Laurent8f42ea12018-08-08 09:08:25 -07003063 MIX_STATE_IDLE);
Eric Laurent84332aa2016-01-28 22:19:18 +00003064 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07003065
3066 // automatically disable the remote submix output when input is stopped if not
3067 // used by a policy mix of type MIX_TYPE_RECORDERS
François Gaffie11d30102018-11-02 16:09:09 +01003068 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003069 String8 address = String8("");
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003070 if (policyMix == nullptr) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003071 address = String8("0");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003072 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
3073 address = policyMix->mDeviceAddress;
Eric Laurent8f42ea12018-08-08 09:08:25 -07003074 }
3075 if (address != "") {
3076 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
3077 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08003078 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003079 }
3080 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07003081 resetInputDevice(input);
3082
3083 // indicate inactive capture to sound trigger service if stopping capture from a mic on
3084 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01003085 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
3086 if (primaryInputDevices.contains(inputDesc->getDevice()) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07003087 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07003088 mpClientInterface->setSoundTriggerCaptureState(false);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003089 }
3090 inputDesc->clearPreemptedSessions();
Eric Laurente552edb2014-03-10 17:42:56 -07003091 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003092 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07003093}
3094
Eric Laurent8fc147b2018-07-22 19:13:55 -07003095void AudioPolicyManager::releaseInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07003096{
Eric Laurent8fc147b2018-07-22 19:13:55 -07003097 ALOGV("%s portId %d", __FUNCTION__, portId);
3098
3099 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
3100 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003101 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07003102 return;
3103 }
Andy Hung39efb7a2018-09-26 15:39:28 -07003104 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8fc147b2018-07-22 19:13:55 -07003105 audio_io_handle_t input = inputDesc->mIoHandle;
3106
Eric Laurent8f42ea12018-08-08 09:08:25 -07003107 ALOGV("%s %d", __FUNCTION__, input);
Paul McLean466dc8e2015-04-17 13:15:36 -06003108
Andy Hung39efb7a2018-09-26 15:39:28 -07003109 inputDesc->removeClient(portId);
Eric Laurent599c7582015-12-07 18:05:55 -08003110
Andy Hung39efb7a2018-09-26 15:39:28 -07003111 if (inputDesc->getClientCount() > 0) {
3112 ALOGV("%s(%d) %zu clients remaining", __func__, portId, inputDesc->getClientCount());
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003113 return;
3114 }
3115
Eric Laurent05b90f82014-08-27 15:32:29 -07003116 closeInput(input);
Eric Laurentb52c1522014-05-20 11:27:36 -07003117 mpClientInterface->onAudioPortListUpdate();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003118 ALOGV("%s exit", __FUNCTION__);
Eric Laurente552edb2014-03-10 17:42:56 -07003119}
3120
Eric Laurent8f42ea12018-08-08 09:08:25 -07003121void AudioPolicyManager::closeActiveClients(const sp<AudioInputDescriptor>& input)
Eric Laurent8fc147b2018-07-22 19:13:55 -07003122{
Eric Laurent8f42ea12018-08-08 09:08:25 -07003123 RecordClientVector clients = input->clientsList(true);
Eric Laurent8fc147b2018-07-22 19:13:55 -07003124
3125 for (const auto& client : clients) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003126 closeClient(client->portId());
Eric Laurent8fc147b2018-07-22 19:13:55 -07003127 }
3128}
3129
Eric Laurent8f42ea12018-08-08 09:08:25 -07003130void AudioPolicyManager::closeClient(audio_port_handle_t portId)
3131{
3132 stopInput(portId);
3133 releaseInput(portId);
3134}
Eric Laurent8fc147b2018-07-22 19:13:55 -07003135
Eric Laurent0dd51852019-04-19 18:18:58 -07003136void AudioPolicyManager::checkCloseInputs() {
3137 // After connecting or disconnecting an input device, close input if:
3138 // - it has no client (was just opened to check profile) OR
3139 // - none of its supported devices are connected anymore OR
3140 // - one of its clients cannot be routed to one of its supported
3141 // devices anymore. Otherwise update device selection
3142 std::vector<audio_io_handle_t> inputsToClose;
3143 for (size_t i = 0; i < mInputs.size(); i++) {
3144 const sp<AudioInputDescriptor> input = mInputs.valueAt(i);
3145 if (input->clientsList().size() == 0
Eric Laurent85732f42020-03-19 11:31:10 -07003146 || !mAvailableInputDevices.containsAtLeastOne(input->supportedDevices())) {
Eric Laurent0dd51852019-04-19 18:18:58 -07003147 inputsToClose.push_back(mInputs.keyAt(i));
3148 } else {
3149 bool close = false;
3150 for (const auto& client : input->clientsList()) {
3151 sp<DeviceDescriptor> device =
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02003152 mEngine->getInputDeviceForAttributes(client->attributes(), client->uid(),
3153 client->session());
Eric Laurent0dd51852019-04-19 18:18:58 -07003154 if (!input->supportedDevices().contains(device)) {
3155 close = true;
3156 break;
3157 }
3158 }
3159 if (close) {
3160 inputsToClose.push_back(mInputs.keyAt(i));
3161 } else {
3162 setInputDevice(input->mIoHandle, getNewInputDevice(input));
3163 }
3164 }
3165 }
3166
3167 for (const audio_io_handle_t handle : inputsToClose) {
3168 ALOGV("%s closing input %d", __func__, handle);
3169 closeInput(handle);
Eric Laurent05b90f82014-08-27 15:32:29 -07003170 }
Eric Laurentd4692962014-05-05 18:13:44 -07003171}
3172
François Gaffie251c7f02018-11-07 10:41:08 +01003173void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream, int indexMin, int indexMax)
Eric Laurente552edb2014-03-10 17:42:56 -07003174{
3175 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08003176 if (indexMin < 0 || indexMax < 0) {
3177 ALOGE("%s for stream %d: invalid min %d or max %d", __func__, stream , indexMin, indexMax);
3178 return;
3179 }
Eric Laurentf5aa58d2019-02-22 18:20:11 -08003180 getVolumeCurves(stream).initVolume(indexMin, indexMax);
Eric Laurent28d09f02016-03-08 10:43:05 -08003181
3182 // initialize other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08003183 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
3184 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08003185 continue;
3186 }
Eric Laurentf5aa58d2019-02-22 18:20:11 -08003187 getVolumeCurves((audio_stream_type_t)curStream).initVolume(indexMin, indexMax);
Eric Laurent223fd5c2014-11-11 13:43:36 -08003188 }
Eric Laurente552edb2014-03-10 17:42:56 -07003189}
3190
Eric Laurente0720872014-03-11 09:30:41 -07003191status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
François Gaffie53615e22015-03-19 09:24:12 +01003192 int index,
3193 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07003194{
François Gaffieaaac0fd2018-11-22 17:56:39 +01003195 auto attributes = mEngine->getAttributesForStreamType(stream);
Eric Laurent242a9f82020-03-23 15:57:04 -07003196 if (attributes == AUDIO_ATTRIBUTES_INITIALIZER) {
3197 ALOGW("%s: no group for stream %s, bailing out", __func__, toString(stream).c_str());
3198 return NO_ERROR;
3199 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01003200 ALOGV("%s: stream %s attributes=%s", __func__,
3201 toString(stream).c_str(), toString(attributes).c_str());
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003202 return setVolumeIndexForAttributes(attributes, index, device);
Eric Laurente552edb2014-03-10 17:42:56 -07003203}
3204
Eric Laurente0720872014-03-11 09:30:41 -07003205status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
François Gaffieaaac0fd2018-11-22 17:56:39 +01003206 int *index,
3207 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07003208{
François Gaffiec005e562018-11-06 15:04:49 +01003209 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
3210 // stream by the engine.
jiabin9a3361e2019-10-01 09:38:30 -07003211 DeviceTypeSet deviceTypes = {device};
Eric Laurent5a2b6292016-04-14 18:05:57 -07003212 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
jiabin9a3361e2019-10-01 09:38:30 -07003213 deviceTypes = mEngine->getOutputDevicesForStream(
3214 stream, true /*fromCache*/).types();
Eric Laurente552edb2014-03-10 17:42:56 -07003215 }
jiabin9a3361e2019-10-01 09:38:30 -07003216 return getVolumeIndex(getVolumeCurves(stream), *index, deviceTypes);
Eric Laurente552edb2014-03-10 17:42:56 -07003217}
3218
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003219status_t AudioPolicyManager::setVolumeIndexForAttributes(const audio_attributes_t &attributes,
François Gaffiecfe17322018-11-07 13:41:29 +01003220 int index,
3221 audio_devices_t device)
3222{
3223 // Get Volume group matching the Audio Attributes
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003224 auto group = mEngine->getVolumeGroupForAttributes(attributes);
3225 if (group == VOLUME_GROUP_NONE) {
3226 ALOGD("%s: no group matching with %s", __FUNCTION__, toString(attributes).c_str());
François Gaffiecfe17322018-11-07 13:41:29 +01003227 return BAD_VALUE;
3228 }
Eric Laurent5baf07c2024-01-11 16:57:27 +00003229 ALOGV("%s: group %d matching with %s index %d",
3230 __FUNCTION__, group, toString(attributes).c_str(), index);
François Gaffiecfe17322018-11-07 13:41:29 +01003231 status_t status = NO_ERROR;
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003232 IVolumeCurves &curves = getVolumeCurves(attributes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01003233 VolumeSource vs = toVolumeSource(group);
Eric Laurentf9cccec2022-11-16 19:12:00 +01003234 // AUDIO_STREAM_BLUETOOTH_SCO is only used for volume control so we remap
3235 // to AUDIO_STREAM_VOICE_CALL to match with relevant playback activity
3236 VolumeSource activityVs = (vs == toVolumeSource(AUDIO_STREAM_BLUETOOTH_SCO, false)) ?
3237 toVolumeSource(AUDIO_STREAM_VOICE_CALL, false) : vs;
François Gaffieaaac0fd2018-11-22 17:56:39 +01003238 product_strategy_t strategy = mEngine->getProductStrategyForAttributes(attributes);
3239
3240 status = setVolumeCurveIndex(index, device, curves);
3241 if (status != NO_ERROR) {
3242 ALOGE("%s failed to set curve index for group %d device 0x%X", __func__, group, device);
3243 return status;
3244 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003245
jiabin9a3361e2019-10-01 09:38:30 -07003246 DeviceTypeSet curSrcDevices;
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003247 auto curCurvAttrs = curves.getAttributes();
3248 if (!curCurvAttrs.empty() && curCurvAttrs.front() != defaultAttr) {
3249 auto attr = curCurvAttrs.front();
jiabin9a3361e2019-10-01 09:38:30 -07003250 curSrcDevices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false).types();
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003251 } else if (!curves.getStreamTypes().empty()) {
3252 auto stream = curves.getStreamTypes().front();
jiabin9a3361e2019-10-01 09:38:30 -07003253 curSrcDevices = mEngine->getOutputDevicesForStream(stream, false).types();
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003254 } else {
3255 ALOGE("%s: Invalid src %d: no valid attributes nor stream",__func__, vs);
3256 return BAD_VALUE;
3257 }
jiabin9a3361e2019-10-01 09:38:30 -07003258 audio_devices_t curSrcDevice = Volume::getDeviceForVolume(curSrcDevices);
3259 resetDeviceTypes(curSrcDevices, curSrcDevice);
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003260
François Gaffiecfe17322018-11-07 13:41:29 +01003261 // update volume on all outputs and streams matching the following:
3262 // - The requested stream (or a stream matching for volume control) is active on the output
3263 // - The device (or devices) selected by the engine for this stream includes
3264 // the requested device
3265 // - For non default requested device, currently selected device on the output is either the
3266 // requested device or one of the devices selected by the engine for this stream
3267 // - For default requested device (AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME), apply volume only if
3268 // no specific device volume value exists for currently selected device.
Henrik Backlund18373a32024-01-24 10:26:42 +01003269 // - Only apply the volume if the requested device is the desired device for volume control.
François Gaffieaaac0fd2018-11-22 17:56:39 +01003270 for (size_t i = 0; i < mOutputs.size(); i++) {
3271 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
jiabin9a3361e2019-10-01 09:38:30 -07003272 DeviceTypeSet curDevices = desc->devices().types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01003273
jiabin9a3361e2019-10-01 09:38:30 -07003274 if (curDevices.erase(AUDIO_DEVICE_OUT_SPEAKER_SAFE)) {
3275 curDevices.insert(AUDIO_DEVICE_OUT_SPEAKER);
Robert Lee5e66e792019-04-03 18:37:15 +08003276 }
Eric Laurentf9cccec2022-11-16 19:12:00 +01003277
3278 if (!(desc->isActive(activityVs) || isInCallOrScreening())) {
François Gaffieed91f582020-01-31 10:35:37 +01003279 continue;
3280 }
3281 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME &&
3282 curDevices.find(device) == curDevices.end()) {
3283 continue;
3284 }
3285 bool applyVolume = false;
3286 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
3287 curSrcDevices.insert(device);
3288 applyVolume = (curSrcDevices.find(
Henrik Backlund18373a32024-01-24 10:26:42 +01003289 Volume::getDeviceForVolume(curDevices)) != curSrcDevices.end())
3290 && Volume::getDeviceForVolume(curSrcDevices) == device;
François Gaffieed91f582020-01-31 10:35:37 +01003291 } else {
3292 applyVolume = !curves.hasVolumeIndexForDevice(curSrcDevice);
3293 }
3294 if (!applyVolume) {
3295 continue; // next output
3296 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01003297 // Inter / intra volume group priority management: Loop on strategies arranged by priority
3298 // If a higher priority strategy is active, and the output is routed to a device with a
3299 // HW Gain management, do not change the volume
François Gaffieaaac0fd2018-11-22 17:56:39 +01003300 if (desc->useHwGain()) {
François Gaffieed91f582020-01-31 10:35:37 +01003301 applyVolume = false;
Francois Gaffie593634d2021-06-22 13:31:31 +02003302 // If the volume source is active with higher priority source, ensure at least Sw Muted
3303 desc->setSwMute((index == 0), vs, curves.getStreamTypes(), curDevices, 0 /*delayMs*/);
François Gaffieaaac0fd2018-11-22 17:56:39 +01003304 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
3305 auto activeClients = desc->clientsList(true /*activeOnly*/, productStrategy,
3306 false /*preferredDevice*/);
3307 if (activeClients.empty()) {
3308 continue;
3309 }
3310 bool isPreempted = false;
3311 bool isHigherPriority = productStrategy < strategy;
3312 for (const auto &client : activeClients) {
Eric Laurentf9cccec2022-11-16 19:12:00 +01003313 if (isHigherPriority && (client->volumeSource() != activityVs)) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01003314 ALOGV("%s: Strategy=%d (\nrequester:\n"
3315 " group %d, volumeGroup=%d attributes=%s)\n"
3316 " higher priority source active:\n"
3317 " volumeGroup=%d attributes=%s) \n"
3318 " on output %zu, bailing out", __func__, productStrategy,
3319 group, group, toString(attributes).c_str(),
3320 client->volumeSource(), toString(client->attributes()).c_str(), i);
3321 applyVolume = false;
3322 isPreempted = true;
3323 break;
3324 }
3325 // However, continue for loop to ensure no higher prio clients running on output
Eric Laurentf9cccec2022-11-16 19:12:00 +01003326 if (client->volumeSource() == activityVs) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01003327 applyVolume = true;
3328 }
3329 }
3330 if (isPreempted || applyVolume) {
3331 break;
3332 }
3333 }
3334 if (!applyVolume) {
3335 continue; // next output
3336 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01003337 }
François Gaffieed91f582020-01-31 10:35:37 +01003338 //FIXME: workaround for truncated touch sounds
3339 // delayed volume change for system stream to be removed when the problem is
3340 // handled by system UI
3341 status_t volStatus = checkAndSetVolume(
3342 curves, vs, index, desc, curDevices,
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003343 ((vs == toVolumeSource(AUDIO_STREAM_SYSTEM, false))?
François Gaffieed91f582020-01-31 10:35:37 +01003344 TOUCH_SOUND_FIXED_DELAY_MS : 0));
3345 if (volStatus != NO_ERROR) {
3346 status = volStatus;
François Gaffieaaac0fd2018-11-22 17:56:39 +01003347 }
3348 }
Eric Laurent5baf07c2024-01-11 16:57:27 +00003349
3350 // update voice volume if the an active call route exists
3351 if (mCallRxSourceClient != nullptr && mCallRxSourceClient->isConnected()
3352 && (curSrcDevices.find(
3353 Volume::getDeviceForVolume({mCallRxSourceClient->sinkDevice()->type()}))
3354 != curSrcDevices.end())) {
3355 bool isVoiceVolSrc;
3356 bool isBtScoVolSrc;
3357 if (isVolumeConsistentForCalls(vs, {mCallRxSourceClient->sinkDevice()->type()},
3358 isVoiceVolSrc, isBtScoVolSrc, __func__)
3359 && (isVoiceVolSrc || isBtScoVolSrc)) {
3360 setVoiceVolume(index, curves, isVoiceVolSrc, 0);
3361 }
3362 }
3363
François Gaffiecfe17322018-11-07 13:41:29 +01003364 mpClientInterface->onAudioVolumeGroupChanged(group, 0 /*flags*/);
3365 return status;
3366}
3367
François Gaffieaaac0fd2018-11-22 17:56:39 +01003368status_t AudioPolicyManager::setVolumeCurveIndex(int index,
François Gaffiecfe17322018-11-07 13:41:29 +01003369 audio_devices_t device,
3370 IVolumeCurves &volumeCurves)
3371{
3372 // VOICE_CALL stream has minVolumeIndex > 0 but can be muted directly by an
3373 // app that has MODIFY_PHONE_STATE permission.
François Gaffieaaac0fd2018-11-22 17:56:39 +01003374 bool hasVoice = hasVoiceStream(volumeCurves.getStreamTypes());
3375 if (((index < volumeCurves.getVolumeIndexMin()) && !(hasVoice && index == 0)) ||
François Gaffiecfe17322018-11-07 13:41:29 +01003376 (index > volumeCurves.getVolumeIndexMax())) {
3377 ALOGD("%s: wrong index %d min=%d max=%d", __FUNCTION__, index,
3378 volumeCurves.getVolumeIndexMin(), volumeCurves.getVolumeIndexMax());
3379 return BAD_VALUE;
3380 }
3381 if (!audio_is_output_device(device)) {
3382 return BAD_VALUE;
3383 }
3384
3385 // Force max volume if stream cannot be muted
3386 if (!volumeCurves.canBeMuted()) index = volumeCurves.getVolumeIndexMax();
3387
François Gaffieaaac0fd2018-11-22 17:56:39 +01003388 ALOGV("%s device %08x, index %d", __FUNCTION__ , device, index);
François Gaffiecfe17322018-11-07 13:41:29 +01003389 volumeCurves.addCurrentVolumeIndex(device, index);
3390 return NO_ERROR;
3391}
3392
3393status_t AudioPolicyManager::getVolumeIndexForAttributes(const audio_attributes_t &attr,
3394 int &index,
3395 audio_devices_t device)
3396{
3397 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
3398 // stream by the engine.
jiabin9a3361e2019-10-01 09:38:30 -07003399 DeviceTypeSet deviceTypes = {device};
François Gaffiecfe17322018-11-07 13:41:29 +01003400 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
Mikhail Naganovbb990f22022-06-15 00:46:43 +00003401 deviceTypes = mEngine->getOutputDevicesForAttributes(
jiabin9a3361e2019-10-01 09:38:30 -07003402 attr, nullptr, true /*fromCache*/).types();
François Gaffiecfe17322018-11-07 13:41:29 +01003403 }
jiabin9a3361e2019-10-01 09:38:30 -07003404 return getVolumeIndex(getVolumeCurves(attr), index, deviceTypes);
François Gaffiecfe17322018-11-07 13:41:29 +01003405}
3406
3407status_t AudioPolicyManager::getVolumeIndex(const IVolumeCurves &curves,
3408 int &index,
jiabin9a3361e2019-10-01 09:38:30 -07003409 const DeviceTypeSet& deviceTypes) const
François Gaffiecfe17322018-11-07 13:41:29 +01003410{
Mikhail Naganovbb990f22022-06-15 00:46:43 +00003411 if (!isSingleDeviceType(deviceTypes, audio_is_output_device)) {
François Gaffiecfe17322018-11-07 13:41:29 +01003412 return BAD_VALUE;
3413 }
jiabin9a3361e2019-10-01 09:38:30 -07003414 index = curves.getVolumeIndex(deviceTypes);
3415 ALOGV("%s: device %s index %d", __FUNCTION__, dumpDeviceTypes(deviceTypes).c_str(), index);
François Gaffiecfe17322018-11-07 13:41:29 +01003416 return NO_ERROR;
3417}
3418
3419status_t AudioPolicyManager::getMinVolumeIndexForAttributes(const audio_attributes_t &attr,
3420 int &index)
3421{
3422 index = getVolumeCurves(attr).getVolumeIndexMin();
3423 return NO_ERROR;
3424}
3425
3426status_t AudioPolicyManager::getMaxVolumeIndexForAttributes(const audio_attributes_t &attr,
3427 int &index)
3428{
3429 index = getVolumeCurves(attr).getVolumeIndexMax();
3430 return NO_ERROR;
3431}
3432
Eric Laurent36829f92017-04-07 19:04:42 -07003433audio_io_handle_t AudioPolicyManager::selectOutputForMusicEffects()
Eric Laurente552edb2014-03-10 17:42:56 -07003434{
3435 // select one output among several suitable for global effects.
3436 // The priority is as follows:
3437 // 1: An offloaded output. If the effect ends up not being offloadable,
3438 // AudioFlinger will invalidate the track and the offloaded output
3439 // will be closed causing the effect to be moved to a PCM output.
3440 // 2: A deep buffer output
Eric Laurent36829f92017-04-07 19:04:42 -07003441 // 3: The primary output
3442 // 4: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07003443
François Gaffiec005e562018-11-06 15:04:49 +01003444 DeviceVector devices = mEngine->getOutputDevicesForAttributes(
3445 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
François Gaffie11d30102018-11-02 16:09:09 +01003446 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07003447
Eric Laurent36829f92017-04-07 19:04:42 -07003448 if (outputs.size() == 0) {
3449 return AUDIO_IO_HANDLE_NONE;
3450 }
Eric Laurente552edb2014-03-10 17:42:56 -07003451
Eric Laurent36829f92017-04-07 19:04:42 -07003452 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
3453 bool activeOnly = true;
3454
3455 while (output == AUDIO_IO_HANDLE_NONE) {
3456 audio_io_handle_t outputOffloaded = AUDIO_IO_HANDLE_NONE;
3457 audio_io_handle_t outputDeepBuffer = AUDIO_IO_HANDLE_NONE;
3458 audio_io_handle_t outputPrimary = AUDIO_IO_HANDLE_NONE;
3459
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003460 for (audio_io_handle_t output : outputs) {
3461 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
Eric Laurent83d17c22019-04-02 17:10:01 -07003462 if (activeOnly && !desc->isActive(toVolumeSource(AUDIO_STREAM_MUSIC))) {
Eric Laurent36829f92017-04-07 19:04:42 -07003463 continue;
3464 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003465 ALOGV("selectOutputForMusicEffects activeOnly %d output %d flags 0x%08x",
3466 activeOnly, output, desc->mFlags);
Eric Laurent36829f92017-04-07 19:04:42 -07003467 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003468 outputOffloaded = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003469 }
3470 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003471 outputDeepBuffer = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003472 }
3473 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003474 outputPrimary = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003475 }
3476 }
3477 if (outputOffloaded != AUDIO_IO_HANDLE_NONE) {
3478 output = outputOffloaded;
3479 } else if (outputDeepBuffer != AUDIO_IO_HANDLE_NONE) {
3480 output = outputDeepBuffer;
3481 } else if (outputPrimary != AUDIO_IO_HANDLE_NONE) {
3482 output = outputPrimary;
3483 } else {
3484 output = outputs[0];
3485 }
3486 activeOnly = false;
3487 }
3488
3489 if (output != mMusicEffectOutput) {
Eric Laurent6c796322019-04-09 14:13:17 -07003490 mEffects.moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output);
Eric Laurent36829f92017-04-07 19:04:42 -07003491 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output);
3492 mMusicEffectOutput = output;
3493 }
3494
3495 ALOGV("selectOutputForMusicEffects selected output %d", output);
Eric Laurente552edb2014-03-10 17:42:56 -07003496 return output;
3497}
3498
Eric Laurent36829f92017-04-07 19:04:42 -07003499audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc __unused)
3500{
3501 return selectOutputForMusicEffects();
3502}
3503
Eric Laurente0720872014-03-11 09:30:41 -07003504status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07003505 audio_io_handle_t io,
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08003506 product_strategy_t strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07003507 int session,
3508 int id)
3509{
Eric Laurentb82e6b72019-11-22 17:25:04 -08003510 if (session != AUDIO_SESSION_DEVICE) {
3511 ssize_t index = mOutputs.indexOfKey(io);
Eric Laurente552edb2014-03-10 17:42:56 -07003512 if (index < 0) {
Eric Laurentb82e6b72019-11-22 17:25:04 -08003513 index = mInputs.indexOfKey(io);
3514 if (index < 0) {
3515 ALOGW("registerEffect() unknown io %d", io);
3516 return INVALID_OPERATION;
3517 }
Eric Laurente552edb2014-03-10 17:42:56 -07003518 }
3519 }
Eric Laurentbf8f69f2022-03-25 17:48:38 +01003520 bool isMusicEffect = (session != AUDIO_SESSION_OUTPUT_STAGE)
3521 && ((strategy == streamToStrategy(AUDIO_STREAM_MUSIC)
3522 || strategy == PRODUCT_STRATEGY_NONE));
3523 return mEffects.registerEffect(desc, io, session, id, isMusicEffect);
Eric Laurente552edb2014-03-10 17:42:56 -07003524}
3525
Eric Laurentc241b0d2018-11-28 09:08:49 -08003526status_t AudioPolicyManager::unregisterEffect(int id)
3527{
3528 if (mEffects.getEffect(id) == nullptr) {
3529 return INVALID_OPERATION;
3530 }
Eric Laurentc241b0d2018-11-28 09:08:49 -08003531 if (mEffects.isEffectEnabled(id)) {
3532 ALOGW("%s effect %d enabled", __FUNCTION__, id);
3533 setEffectEnabled(id, false);
3534 }
3535 return mEffects.unregisterEffect(id);
3536}
3537
3538status_t AudioPolicyManager::setEffectEnabled(int id, bool enabled)
3539{
3540 sp<EffectDescriptor> effect = mEffects.getEffect(id);
3541 if (effect == nullptr) {
3542 return INVALID_OPERATION;
3543 }
3544
3545 status_t status = mEffects.setEffectEnabled(id, enabled);
3546 if (status == NO_ERROR) {
3547 mInputs.trackEffectEnabled(effect, enabled);
3548 }
3549 return status;
3550}
3551
Eric Laurent6c796322019-04-09 14:13:17 -07003552
3553status_t AudioPolicyManager::moveEffectsToIo(const std::vector<int>& ids, audio_io_handle_t io)
3554{
3555 mEffects.moveEffects(ids, io);
3556 return NO_ERROR;
3557}
3558
Eric Laurentc75307b2015-03-17 15:29:32 -07003559bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
3560{
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003561 auto vs = toVolumeSource(stream, false);
3562 return vs != VOLUME_SOURCE_NONE ? mOutputs.isActive(vs, inPastMs) : false;
Eric Laurentc75307b2015-03-17 15:29:32 -07003563}
3564
3565bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream, uint32_t inPastMs) const
3566{
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003567 auto vs = toVolumeSource(stream, false);
3568 return vs != VOLUME_SOURCE_NONE ? mOutputs.isActiveRemotely(vs, inPastMs) : false;
Eric Laurentc75307b2015-03-17 15:29:32 -07003569}
3570
Eric Laurente0720872014-03-11 09:30:41 -07003571bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07003572{
3573 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003574 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08003575 if (inputDescriptor->isSourceActive(source)) {
Eric Laurente552edb2014-03-10 17:42:56 -07003576 return true;
3577 }
3578 }
3579 return false;
3580}
3581
Eric Laurent275e8e92014-11-30 15:14:47 -08003582// Register a list of custom mixes with their attributes and format.
3583// When a mix is registered, corresponding input and output profiles are
3584// added to the remote submix hw module. The profile contains only the
3585// parameters (sampling rate, format...) specified by the mix.
3586// The corresponding input remote submix device is also connected.
3587//
3588// When a remote submix device is connected, the address is checked to select the
3589// appropriate profile and the corresponding input or output stream is opened.
3590//
3591// When capture starts, getInputForAttr() will:
3592// - 1 look for a mix matching the address passed in attribtutes tags if any
3593// - 2 if none found, getDeviceForInputSource() will:
3594// - 2.1 look for a mix matching the attributes source
3595// - 2.2 if none found, default to device selection by policy rules
3596// At this time, the corresponding output remote submix device is also connected
3597// and active playback use cases can be transferred to this mix if needed when reconnecting
3598// after AudioTracks are invalidated
3599//
3600// When playback starts, getOutputForAttr() will:
3601// - 1 look for a mix matching the address passed in attribtutes tags if any
3602// - 2 if none found, look for a mix matching the attributes usage
3603// - 3 if none found, default to device and output selection by policy rules.
3604
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003605status_t AudioPolicyManager::registerPolicyMixes(const Vector<AudioMix>& mixes)
Eric Laurent275e8e92014-11-30 15:14:47 -08003606{
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003607 ALOGV("registerPolicyMixes() %zu mix(es)", mixes.size());
3608 status_t res = NO_ERROR;
Eric Laurentc209fe42020-06-05 18:11:23 -07003609 bool checkOutputs = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003610 sp<HwModule> rSubmixModule;
3611 // examine each mix's route type
3612 for (size_t i = 0; i < mixes.size(); i++) {
Eric Laurent97ac8712018-07-27 18:59:02 -07003613 AudioMix mix = mixes[i];
Kevin Rocard153f92d2018-12-18 18:33:28 -08003614 // Only capture of playback is allowed in LOOP_BACK & RENDER mode
3615 if (is_mix_loopback_render(mix.mRouteFlags) && mix.mMixType != MIX_TYPE_PLAYERS) {
3616 ALOGE("Unsupported Policy Mix %zu of %zu: "
3617 "Only capture of playback is allowed in LOOP_BACK & RENDER mode",
3618 i, mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003619 res = INVALID_OPERATION;
Eric Laurent275e8e92014-11-30 15:14:47 -08003620 break;
3621 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08003622 // LOOP_BACK and LOOP_BACK | RENDER have the same remote submix backend and are handled
3623 // in the same way.
Eric Laurent97ac8712018-07-27 18:59:02 -07003624 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003625 ALOGV("registerPolicyMixes() mix %zu of %zu is LOOP_BACK %d", i, mixes.size(),
3626 mix.mRouteFlags);
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003627 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003628 rSubmixModule = mHwModules.getModuleFromName(
3629 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
3630 if (rSubmixModule == 0) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003631 ALOGE("Unable to find audio module for submix, aborting mix %zu registration",
Mikhail Naganovd4120142017-12-06 15:49:22 -08003632 i);
3633 res = INVALID_OPERATION;
3634 break;
3635 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003636 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003637
Eric Laurent97ac8712018-07-27 18:59:02 -07003638 String8 address = mix.mDeviceAddress;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003639 audio_devices_t deviceTypeToMakeAvailable;
Eric Laurent97ac8712018-07-27 18:59:02 -07003640 if (mix.mMixType == MIX_TYPE_PLAYERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07003641 mix.mDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003642 deviceTypeToMakeAvailable = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
3643 } else {
3644 mix.mDeviceType = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
3645 deviceTypeToMakeAvailable = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Eric Laurent97ac8712018-07-27 18:59:02 -07003646 }
François Gaffie036e1e92015-03-19 10:16:24 +01003647
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003648 if (mPolicyMixes.registerMix(mix, 0 /*output desc*/) != NO_ERROR) {
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00003649 ALOGE("Error registering mix %zu for address %s", i, address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003650 res = INVALID_OPERATION;
3651 break;
3652 }
Eric Laurent97ac8712018-07-27 18:59:02 -07003653 audio_config_t outputConfig = mix.mFormat;
3654 audio_config_t inputConfig = mix.mFormat;
Eric Laurentc529cf62020-04-17 18:19:10 -07003655 // NOTE: audio flinger mixer does not support mono output: configure remote submix HAL
3656 // in stereo and let audio flinger do the channel conversion if needed.
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003657 outputConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
3658 inputConfig.channel_mask = AUDIO_CHANNEL_IN_STEREO;
jiabin5740f082019-08-19 15:08:30 -07003659 rSubmixModule->addOutputProfile(address.c_str(), &outputConfig,
Dean Wheatley80551862023-11-17 01:32:22 +11003660 AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address,
3661 audio_is_linear_pcm(outputConfig.format)
3662 ? AUDIO_OUTPUT_FLAG_NONE : AUDIO_OUTPUT_FLAG_DIRECT);
jiabin5740f082019-08-19 15:08:30 -07003663 rSubmixModule->addInputProfile(address.c_str(), &inputConfig,
Dean Wheatley80551862023-11-17 01:32:22 +11003664 AUDIO_DEVICE_IN_REMOTE_SUBMIX, address,
3665 audio_is_linear_pcm(inputConfig.format)
3666 ? AUDIO_INPUT_FLAG_NONE : AUDIO_INPUT_FLAG_DIRECT);
François Gaffie036e1e92015-03-19 10:16:24 +01003667
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003668 if ((res = setDeviceConnectionStateInt(deviceTypeToMakeAvailable,
jiabinc1de2df2019-05-07 14:26:40 -07003669 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00003670 address.c_str(), "remote-submix", AUDIO_FORMAT_DEFAULT)) != NO_ERROR) {
jiabinc1de2df2019-05-07 14:26:40 -07003671 ALOGE("Failed to set remote submix device available, type %u, address %s",
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00003672 mix.mDeviceType, address.c_str());
jiabinc1de2df2019-05-07 14:26:40 -07003673 break;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003674 }
Eric Laurent97ac8712018-07-27 18:59:02 -07003675 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
3676 String8 address = mix.mDeviceAddress;
Eric Laurent2c80be02019-01-23 18:06:37 -08003677 audio_devices_t type = mix.mDeviceType;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003678 ALOGV(" registerPolicyMixes() mix %zu of %zu is RENDER, dev=0x%X addr=%s",
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00003679 i, mixes.size(), type, address.c_str());
Eric Laurent2c80be02019-01-23 18:06:37 -08003680
3681 sp<DeviceDescriptor> device = mHwModules.getDeviceDescriptor(
3682 mix.mDeviceType, mix.mDeviceAddress,
3683 String8(), AUDIO_FORMAT_DEFAULT);
3684 if (device == nullptr) {
3685 res = INVALID_OPERATION;
3686 break;
3687 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003688
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003689 bool foundOutput = false;
Eric Laurentc529cf62020-04-17 18:19:10 -07003690 // First try to find an already opened output supporting the device
3691 for (size_t j = 0 ; j < mOutputs.size() && !foundOutput && res == NO_ERROR; j++) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003692 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurent2c80be02019-01-23 18:06:37 -08003693
Eric Laurentc529cf62020-04-17 18:19:10 -07003694 if (!desc->isDuplicated() && desc->supportedDevices().contains(device)) {
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003695 if (mPolicyMixes.registerMix(mix, desc) != NO_ERROR) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003696 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00003697 address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003698 res = INVALID_OPERATION;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003699 } else {
3700 foundOutput = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003701 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003702 }
3703 }
Eric Laurentc529cf62020-04-17 18:19:10 -07003704 // If no output found, try to find a direct output profile supporting the device
3705 for (size_t i = 0; i < mHwModules.size() && !foundOutput && res == NO_ERROR; i++) {
3706 sp<HwModule> module = mHwModules[i];
3707 for (size_t j = 0;
3708 j < module->getOutputProfiles().size() && !foundOutput && res == NO_ERROR;
3709 j++) {
3710 sp<IOProfile> profile = module->getOutputProfiles()[j];
3711 if (profile->isDirectOutput() && profile->supportsDevice(device)) {
3712 if (mPolicyMixes.registerMix(mix, nullptr) != NO_ERROR) {
3713 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00003714 address.c_str());
Eric Laurentc529cf62020-04-17 18:19:10 -07003715 res = INVALID_OPERATION;
3716 } else {
3717 foundOutput = true;
3718 }
3719 }
3720 }
3721 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003722 if (res != NO_ERROR) {
3723 ALOGE(" Error registering mix %zu for device 0x%X addr %s",
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00003724 i, type, address.c_str());
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003725 res = INVALID_OPERATION;
3726 break;
3727 } else if (!foundOutput) {
3728 ALOGE(" Output not found for mix %zu for device 0x%X addr %s",
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00003729 i, type, address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003730 res = INVALID_OPERATION;
3731 break;
Eric Laurentc209fe42020-06-05 18:11:23 -07003732 } else {
3733 checkOutputs = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003734 }
Eric Laurentc722f302014-12-10 11:21:49 -08003735 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003736 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003737 if (res != NO_ERROR) {
3738 unregisterPolicyMixes(mixes);
Eric Laurentc209fe42020-06-05 18:11:23 -07003739 } else if (checkOutputs) {
3740 checkForDeviceAndOutputChanges();
3741 updateCallAndOutputRouting();
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003742 }
3743 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08003744}
3745
3746status_t AudioPolicyManager::unregisterPolicyMixes(Vector<AudioMix> mixes)
3747{
Eric Laurent7b279bb2015-12-14 10:18:23 -08003748 ALOGV("unregisterPolicyMixes() num mixes %zu", mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003749 status_t res = NO_ERROR;
Eric Laurentc209fe42020-06-05 18:11:23 -07003750 bool checkOutputs = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003751 sp<HwModule> rSubmixModule;
3752 // examine each mix's route type
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003753 for (const auto& mix : mixes) {
3754 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie036e1e92015-03-19 10:16:24 +01003755
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003756 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003757 rSubmixModule = mHwModules.getModuleFromName(
3758 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
3759 if (rSubmixModule == 0) {
3760 res = INVALID_OPERATION;
3761 continue;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003762 }
3763 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003764
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003765 String8 address = mix.mDeviceAddress;
Eric Laurent275e8e92014-11-30 15:14:47 -08003766
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003767 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003768 res = INVALID_OPERATION;
3769 continue;
3770 }
3771
Kevin Rocard04ed0462019-05-02 17:53:24 -07003772 for (auto device : {AUDIO_DEVICE_IN_REMOTE_SUBMIX, AUDIO_DEVICE_OUT_REMOTE_SUBMIX}) {
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00003773 if (getDeviceConnectionState(device, address.c_str()) ==
Kevin Rocard04ed0462019-05-02 17:53:24 -07003774 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
3775 res = setDeviceConnectionStateInt(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00003776 address.c_str(), "remote-submix",
Kevin Rocard04ed0462019-05-02 17:53:24 -07003777 AUDIO_FORMAT_DEFAULT);
3778 if (res != OK) {
3779 ALOGE("Error making RemoteSubmix device unavailable for mix "
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00003780 "with type %d, address %s", device, address.c_str());
Kevin Rocard04ed0462019-05-02 17:53:24 -07003781 }
3782 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003783 }
jiabin5740f082019-08-19 15:08:30 -07003784 rSubmixModule->removeOutputProfile(address.c_str());
3785 rSubmixModule->removeInputProfile(address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003786
Kevin Rocard153f92d2018-12-18 18:33:28 -08003787 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003788 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003789 res = INVALID_OPERATION;
3790 continue;
Eric Laurentc209fe42020-06-05 18:11:23 -07003791 } else {
3792 checkOutputs = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003793 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003794 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003795 }
Eric Laurentc209fe42020-06-05 18:11:23 -07003796 if (res == NO_ERROR && checkOutputs) {
3797 checkForDeviceAndOutputChanges();
3798 updateCallAndOutputRouting();
3799 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003800 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08003801}
3802
Mikhail Naganov100f0122018-11-29 11:22:16 -08003803void AudioPolicyManager::dumpManualSurroundFormats(String8 *dst) const
3804{
3805 size_t i = 0;
3806 constexpr size_t audioFormatPrefixLen = sizeof("AUDIO_FORMAT_");
3807 for (const auto& fmt : mManualSurroundFormats) {
3808 if (i++ != 0) dst->append(", ");
3809 std::string sfmt;
3810 FormatConverter::toString(fmt, sfmt);
3811 dst->append(sfmt.size() >= audioFormatPrefixLen ?
3812 sfmt.c_str() + audioFormatPrefixLen - 1 : sfmt.c_str());
3813 }
3814}
3815
Eric Laurentc529cf62020-04-17 18:19:10 -07003816// Returns true if all devices types match the predicate and are supported by one HW module
3817bool AudioPolicyManager::areAllDevicesSupported(
jiabin6a02d532020-08-07 11:56:38 -07003818 const AudioDeviceTypeAddrVector& devices,
Eric Laurentc529cf62020-04-17 18:19:10 -07003819 std::function<bool(audio_devices_t)> predicate,
Eric Laurent78fedbf2023-03-09 14:40:44 +01003820 const char *context,
3821 bool matchAddress) {
Eric Laurentc529cf62020-04-17 18:19:10 -07003822 for (size_t i = 0; i < devices.size(); i++) {
3823 sp<DeviceDescriptor> devDesc = mHwModules.getDeviceDescriptor(
jiabin0a488932020-08-07 17:32:40 -07003824 devices[i].mType, devices[i].getAddress(), String8(),
Eric Laurent78fedbf2023-03-09 14:40:44 +01003825 AUDIO_FORMAT_DEFAULT, false /*allowToCreate*/, matchAddress);
Eric Laurentc529cf62020-04-17 18:19:10 -07003826 if (devDesc == nullptr || (predicate != nullptr && !predicate(devices[i].mType))) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003827 ALOGE("%s: device type %#x address %s not supported or not match predicate",
jiabin0a488932020-08-07 17:32:40 -07003828 context, devices[i].mType, devices[i].getAddress());
Eric Laurentc529cf62020-04-17 18:19:10 -07003829 return false;
3830 }
3831 }
3832 return true;
3833}
3834
Oscar Azucena6acf34b2023-04-27 16:32:09 -07003835void AudioPolicyManager::changeOutputDevicesMuteState(
3836 const AudioDeviceTypeAddrVector& devices) {
3837 ALOGVV("%s() num devices %zu", __func__, devices.size());
3838
3839 std::vector<sp<SwAudioOutputDescriptor>> outputs =
3840 getSoftwareOutputsForDevices(devices);
3841
3842 for (size_t i = 0; i < outputs.size(); i++) {
3843 sp<SwAudioOutputDescriptor> outputDesc = outputs[i];
3844 DeviceVector prevDevices = outputDesc->devices();
3845 checkDeviceMuteStrategies(outputDesc, prevDevices, 0 /* delayMs */);
3846 }
3847}
3848
3849std::vector<sp<SwAudioOutputDescriptor>> AudioPolicyManager::getSoftwareOutputsForDevices(
3850 const AudioDeviceTypeAddrVector& devices) const
3851{
3852 std::vector<sp<SwAudioOutputDescriptor>> outputs;
3853 DeviceVector deviceDescriptors;
3854 for (size_t j = 0; j < devices.size(); j++) {
3855 sp<DeviceDescriptor> desc = mHwModules.getDeviceDescriptor(
3856 devices[j].mType, devices[j].getAddress(), String8(), AUDIO_FORMAT_DEFAULT);
3857 if (desc == nullptr || !audio_is_output_device(devices[j].mType)) {
3858 ALOGE("%s: device type %#x address %s not supported or not an output device",
3859 __func__, devices[j].mType, devices[j].getAddress());
3860 continue;
3861 }
3862 deviceDescriptors.add(desc);
3863 }
3864 for (size_t i = 0; i < mOutputs.size(); i++) {
3865 if (!mOutputs.valueAt(i)->supportsAtLeastOne(deviceDescriptors)) {
3866 continue;
3867 }
3868 outputs.push_back(mOutputs.valueAt(i));
3869 }
3870 return outputs;
3871}
3872
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003873status_t AudioPolicyManager::setUidDeviceAffinities(uid_t uid,
jiabin6a02d532020-08-07 11:56:38 -07003874 const AudioDeviceTypeAddrVector& devices) {
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003875 ALOGV("%s() uid=%d num devices %zu", __FUNCTION__, uid, devices.size());
Eric Laurentc529cf62020-04-17 18:19:10 -07003876 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
3877 return BAD_VALUE;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003878 }
3879 status_t res = mPolicyMixes.setUidDeviceAffinities(uid, devices);
Eric Laurentc529cf62020-04-17 18:19:10 -07003880 if (res != NO_ERROR) {
3881 ALOGE("%s() Could not set all device affinities for uid = %d", __FUNCTION__, uid);
3882 return res;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003883 }
Eric Laurentc529cf62020-04-17 18:19:10 -07003884
3885 checkForDeviceAndOutputChanges();
3886 updateCallAndOutputRouting();
3887
3888 return NO_ERROR;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003889}
3890
3891status_t AudioPolicyManager::removeUidDeviceAffinities(uid_t uid) {
3892 ALOGV("%s() uid=%d", __FUNCTION__, uid);
Oscar Azucena4b2a8212019-04-26 23:48:59 -07003893 status_t res = mPolicyMixes.removeUidDeviceAffinities(uid);
3894 if (res != NO_ERROR) {
Eric Laurentc529cf62020-04-17 18:19:10 -07003895 ALOGE("%s() Could not remove all device affinities for uid = %d",
Oscar Azucena4b2a8212019-04-26 23:48:59 -07003896 __FUNCTION__, uid);
3897 return INVALID_OPERATION;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003898 }
3899
Eric Laurentc529cf62020-04-17 18:19:10 -07003900 checkForDeviceAndOutputChanges();
3901 updateCallAndOutputRouting();
3902
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003903 return res;
3904}
3905
Eric Laurent2517af32020-11-25 15:31:27 +01003906
jiabin0a488932020-08-07 17:32:40 -07003907status_t AudioPolicyManager::setDevicesRoleForStrategy(product_strategy_t strategy,
3908 device_role_t role,
3909 const AudioDeviceTypeAddrVector &devices) {
3910 ALOGV("%s() strategy=%d role=%d %s", __func__, strategy, role,
3911 dumpAudioDeviceTypeAddrVector(devices).c_str());
Eric Laurentc529cf62020-04-17 18:19:10 -07003912
Eric Laurentc529cf62020-04-17 18:19:10 -07003913 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003914 return BAD_VALUE;
3915 }
jiabin0a488932020-08-07 17:32:40 -07003916 status_t status = mEngine->setDevicesRoleForStrategy(strategy, role, devices);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003917 if (status != NO_ERROR) {
jiabin0a488932020-08-07 17:32:40 -07003918 ALOGW("Engine could not set preferred devices %s for strategy %d role %d",
3919 dumpAudioDeviceTypeAddrVector(devices).c_str(), strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003920 return status;
3921 }
3922
3923 checkForDeviceAndOutputChanges();
Eric Laurent2517af32020-11-25 15:31:27 +01003924
3925 bool forceVolumeReeval = false;
3926 // FIXME: workaround for truncated touch sounds
3927 // to be removed when the problem is handled by system UI
3928 uint32_t delayMs = 0;
3929 if (strategy == mCommunnicationStrategy) {
3930 forceVolumeReeval = true;
3931 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
3932 updateInputRouting();
3933 }
3934 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003935
3936 return NO_ERROR;
3937}
3938
Oscar Azucena6acf34b2023-04-27 16:32:09 -07003939void AudioPolicyManager::updateCallAndOutputRouting(bool forceVolumeReeval, uint32_t delayMs,
3940 bool skipDelays)
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003941{
3942 uint32_t waitMs = 0;
Eric Laurent96d1dda2022-03-14 17:14:19 +01003943 bool wasLeUnicastActive = isLeUnicastActive();
Francois Gaffie19fd6c52021-02-04 17:02:59 +01003944 if (updateCallRouting(true /*fromCache*/, delayMs, &waitMs) == NO_ERROR) {
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 }
jiabin3ff8d7d2022-12-13 06:27:44 +00003948 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003949 for (size_t i = 0; i < mOutputs.size(); i++) {
3950 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
3951 DeviceVector newDevices = getNewOutputDevices(outputDesc, true /*fromCache*/);
Francois Gaffie601801d2021-06-22 13:27:39 +02003952 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) ||
3953 (outputDesc != mPrimaryOutput && !isTelephonyRxOrTx(outputDesc))) {
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003954 // As done in setDeviceConnectionState, we could also fix default device issue by
3955 // preventing the force re-routing in case of default dev that distinguishes on address.
3956 // Let's give back to engine full device choice decision however.
Francois Gaffie601801d2021-06-22 13:27:39 +02003957 bool forceRouting = !newDevices.isEmpty();
jiabin3ff8d7d2022-12-13 06:27:44 +00003958 if (outputDesc->mUsePreferredMixerAttributes && newDevices != outputDesc->devices()) {
3959 // If the device is using preferred mixer attributes, the output need to reopen
3960 // with default configuration when the new selected devices are different from
3961 // current routing devices.
3962 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices);
3963 continue;
3964 }
Francois Gaffie601801d2021-06-22 13:27:39 +02003965 waitMs = setOutputDevices(outputDesc, newDevices, forceRouting, delayMs, nullptr,
Oscar Azucena6acf34b2023-04-27 16:32:09 -07003966 !skipDelays /*requiresMuteCheck*/,
3967 !forceRouting /*requiresVolumeCheck*/, skipDelays);
Eric Laurentb36b4ac2020-08-21 12:50:41 -07003968 // Only apply special touch sound delay once
3969 delayMs = 0;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003970 }
3971 if (forceVolumeReeval && !newDevices.isEmpty()) {
3972 applyStreamVolumes(outputDesc, newDevices.types(), waitMs, true);
3973 }
3974 }
jiabin3ff8d7d2022-12-13 06:27:44 +00003975 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent96d1dda2022-03-14 17:14:19 +01003976 checkLeBroadcastRoutes(wasLeUnicastActive, nullptr, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003977}
3978
Eric Laurent2517af32020-11-25 15:31:27 +01003979void AudioPolicyManager::updateInputRouting() {
3980 for (const auto& activeDesc : mInputs.getActiveInputs()) {
Jaideep Sharma408349a2020-11-27 14:47:17 +05303981 // Skip for hotword recording as the input device switch
3982 // is handled within sound trigger HAL
3983 if (activeDesc->isSoundTrigger() && activeDesc->source() == AUDIO_SOURCE_HOTWORD) {
3984 continue;
3985 }
Eric Laurent2517af32020-11-25 15:31:27 +01003986 auto newDevice = getNewInputDevice(activeDesc);
3987 // Force new input selection if the new device can not be reached via current input
3988 if (activeDesc->mProfile->getSupportedDevices().contains(newDevice)) {
3989 setInputDevice(activeDesc->mIoHandle, newDevice);
3990 } else {
3991 closeInput(activeDesc->mIoHandle);
3992 }
3993 }
3994}
3995
Paul Wang5d7cdb52022-11-22 09:45:06 +00003996status_t
3997AudioPolicyManager::removeDevicesRoleForStrategy(product_strategy_t strategy,
3998 device_role_t role,
3999 const AudioDeviceTypeAddrVector &devices) {
4000 ALOGV("%s() strategy=%d role=%d %s", __func__, strategy, role,
4001 dumpAudioDeviceTypeAddrVector(devices).c_str());
4002
Eric Laurent78fedbf2023-03-09 14:40:44 +01004003 if (!areAllDevicesSupported(
4004 devices, audio_is_output_device, __func__, /*matchAddress*/false)) {
Paul Wang5d7cdb52022-11-22 09:45:06 +00004005 return BAD_VALUE;
4006 }
4007 status_t status = mEngine->removeDevicesRoleForStrategy(strategy, role, devices);
4008 if (status != NO_ERROR) {
4009 ALOGW("Engine could not remove devices %s for strategy %d role %d",
4010 dumpAudioDeviceTypeAddrVector(devices).c_str(), strategy, role);
4011 return status;
4012 }
4013
4014 checkForDeviceAndOutputChanges();
4015
4016 bool forceVolumeReeval = false;
4017 // TODO(b/263479999): workaround for truncated touch sounds
4018 // to be removed when the problem is handled by system UI
4019 uint32_t delayMs = 0;
4020 if (strategy == mCommunnicationStrategy) {
4021 forceVolumeReeval = true;
4022 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
4023 updateInputRouting();
4024 }
4025 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
4026
4027 return NO_ERROR;
4028}
4029
4030status_t AudioPolicyManager::clearDevicesRoleForStrategy(product_strategy_t strategy,
4031 device_role_t role)
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004032{
Eric Laurentfecbceb2021-02-09 14:46:43 +01004033 ALOGV("%s() strategy=%d role=%d", __func__, strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004034
Paul Wang5d7cdb52022-11-22 09:45:06 +00004035 status_t status = mEngine->clearDevicesRoleForStrategy(strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004036 if (status != NO_ERROR) {
Eric Laurent9ae44f32022-12-14 16:17:02 +01004037 ALOGW_IF(status != NAME_NOT_FOUND,
4038 "Engine could not remove device role for strategy %d status %d",
Eric Laurent2517af32020-11-25 15:31:27 +01004039 strategy, status);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004040 return status;
4041 }
4042
4043 checkForDeviceAndOutputChanges();
Eric Laurent2517af32020-11-25 15:31:27 +01004044
4045 bool forceVolumeReeval = false;
4046 // FIXME: workaround for truncated touch sounds
4047 // to be removed when the problem is handled by system UI
4048 uint32_t delayMs = 0;
4049 if (strategy == mCommunnicationStrategy) {
4050 forceVolumeReeval = true;
4051 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
4052 updateInputRouting();
4053 }
4054 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004055
4056 return NO_ERROR;
4057}
4058
jiabin0a488932020-08-07 17:32:40 -07004059status_t AudioPolicyManager::getDevicesForRoleAndStrategy(product_strategy_t strategy,
4060 device_role_t role,
4061 AudioDeviceTypeAddrVector &devices) {
4062 return mEngine->getDevicesForRoleAndStrategy(strategy, role, devices);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004063}
4064
Jiabin Huang3b98d322020-09-03 17:54:16 +00004065status_t AudioPolicyManager::setDevicesRoleForCapturePreset(
4066 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices) {
4067 ALOGV("%s() audioSource=%d role=%d %s", __func__, audioSource, role,
4068 dumpAudioDeviceTypeAddrVector(devices).c_str());
4069
Mikhail Naganov55773032020-10-01 15:08:13 -07004070 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00004071 return BAD_VALUE;
4072 }
4073 status_t status = mEngine->setDevicesRoleForCapturePreset(audioSource, role, devices);
4074 ALOGW_IF(status != NO_ERROR,
4075 "Engine could not set preferred devices %s for audio source %d role %d",
4076 dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
4077
4078 return status;
4079}
4080
4081status_t AudioPolicyManager::addDevicesRoleForCapturePreset(
4082 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices) {
4083 ALOGV("%s() audioSource=%d role=%d %s", __func__, audioSource, role,
4084 dumpAudioDeviceTypeAddrVector(devices).c_str());
4085
Mikhail Naganov55773032020-10-01 15:08:13 -07004086 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00004087 return BAD_VALUE;
4088 }
4089 status_t status = mEngine->addDevicesRoleForCapturePreset(audioSource, role, devices);
4090 ALOGW_IF(status != NO_ERROR,
4091 "Engine could not add preferred devices %s for audio source %d role %d",
4092 dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
4093
Eric Laurent2517af32020-11-25 15:31:27 +01004094 updateInputRouting();
Jiabin Huang3b98d322020-09-03 17:54:16 +00004095 return status;
4096}
4097
4098status_t AudioPolicyManager::removeDevicesRoleForCapturePreset(
4099 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector& devices)
4100{
4101 ALOGV("%s() audioSource=%d role=%d devices=%s", __func__, audioSource, role,
4102 dumpAudioDeviceTypeAddrVector(devices).c_str());
4103
Eric Laurent78fedbf2023-03-09 14:40:44 +01004104 if (!areAllDevicesSupported(
4105 devices, audio_call_is_input_device, __func__, /*matchAddress*/false)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00004106 return BAD_VALUE;
4107 }
4108
4109 status_t status = mEngine->removeDevicesRoleForCapturePreset(
4110 audioSource, role, devices);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004111 ALOGW_IF(status != NO_ERROR && status != NAME_NOT_FOUND,
Jiabin Huang3b98d322020-09-03 17:54:16 +00004112 "Engine could not remove devices role (%d) for capture preset %d", role, audioSource);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004113 if (status == NO_ERROR) {
4114 updateInputRouting();
4115 }
Jiabin Huang3b98d322020-09-03 17:54:16 +00004116 return status;
4117}
4118
4119status_t AudioPolicyManager::clearDevicesRoleForCapturePreset(audio_source_t audioSource,
4120 device_role_t role) {
4121 ALOGV("%s() audioSource=%d role=%d", __func__, audioSource, role);
4122
4123 status_t status = mEngine->clearDevicesRoleForCapturePreset(audioSource, role);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004124 ALOGW_IF(status != NO_ERROR && status != NAME_NOT_FOUND,
Jiabin Huang3b98d322020-09-03 17:54:16 +00004125 "Engine could not clear devices role (%d) for capture preset %d", role, audioSource);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004126 if (status == NO_ERROR) {
4127 updateInputRouting();
4128 }
Jiabin Huang3b98d322020-09-03 17:54:16 +00004129 return status;
4130}
4131
4132status_t AudioPolicyManager::getDevicesForRoleAndCapturePreset(
4133 audio_source_t audioSource, device_role_t role, AudioDeviceTypeAddrVector &devices) {
4134 return mEngine->getDevicesForRoleAndCapturePreset(audioSource, role, devices);
4135}
4136
Oscar Azucena90e77632019-11-27 17:12:28 -08004137status_t AudioPolicyManager::setUserIdDeviceAffinities(int userId,
jiabin6a02d532020-08-07 11:56:38 -07004138 const AudioDeviceTypeAddrVector& devices) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01004139 ALOGV("%s() userId=%d num devices %zu", __func__, userId, devices.size());
Eric Laurentc529cf62020-04-17 18:19:10 -07004140 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
4141 return BAD_VALUE;
Oscar Azucena90e77632019-11-27 17:12:28 -08004142 }
Oscar Azucena90e77632019-11-27 17:12:28 -08004143 status_t status = mPolicyMixes.setUserIdDeviceAffinities(userId, devices);
4144 if (status != NO_ERROR) {
4145 ALOGE("%s() could not set device affinity for userId %d",
4146 __FUNCTION__, userId);
4147 return status;
4148 }
4149
4150 // reevaluate outputs for all devices
4151 checkForDeviceAndOutputChanges();
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004152 changeOutputDevicesMuteState(devices);
4153 updateCallAndOutputRouting(false /* forceVolumeReeval */, 0 /* delayMs */,
4154 true /* skipDelays */);
4155 changeOutputDevicesMuteState(devices);
Oscar Azucena90e77632019-11-27 17:12:28 -08004156
4157 return NO_ERROR;
4158}
4159
4160status_t AudioPolicyManager::removeUserIdDeviceAffinities(int userId) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01004161 ALOGV("%s() userId=%d", __FUNCTION__, userId);
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004162 AudioDeviceTypeAddrVector devices;
4163 mPolicyMixes.getDevicesForUserId(userId, devices);
Oscar Azucena90e77632019-11-27 17:12:28 -08004164 status_t status = mPolicyMixes.removeUserIdDeviceAffinities(userId);
4165 if (status != NO_ERROR) {
4166 ALOGE("%s() Could not remove all device affinities fo userId = %d",
4167 __FUNCTION__, userId);
4168 return status;
4169 }
4170
4171 // reevaluate outputs for all devices
4172 checkForDeviceAndOutputChanges();
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004173 changeOutputDevicesMuteState(devices);
4174 updateCallAndOutputRouting(false /* forceVolumeReeval */, 0 /* delayMs */,
4175 true /* skipDelays */);
4176 changeOutputDevicesMuteState(devices);
Oscar Azucena90e77632019-11-27 17:12:28 -08004177
4178 return NO_ERROR;
4179}
4180
Andy Hungc29d82b2018-10-05 12:23:17 -07004181void AudioPolicyManager::dump(String8 *dst) const
Eric Laurente552edb2014-03-10 17:42:56 -07004182{
Andy Hungc29d82b2018-10-05 12:23:17 -07004183 dst->appendFormat("\nAudioPolicyManager Dump: %p\n", this);
Mikhail Naganov0dbe87b2021-12-01 02:03:31 +00004184 dst->appendFormat(" Primary Output I/O handle: %d\n",
Eric Laurent87ffa392015-05-22 10:32:38 -07004185 hasPrimaryOutput() ? mPrimaryOutput->mIoHandle : AUDIO_IO_HANDLE_NONE);
Mikhail Naganov0d6a0332016-04-19 17:12:38 -07004186 std::string stateLiteral;
4187 AudioModeConverter::toString(mEngine->getPhoneState(), stateLiteral);
Andy Hungc29d82b2018-10-05 12:23:17 -07004188 dst->appendFormat(" Phone state: %s\n", stateLiteral.c_str());
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07004189 const char* forceUses[AUDIO_POLICY_FORCE_USE_CNT] = {
4190 "communications", "media", "record", "dock", "system",
4191 "HDMI system audio", "encoded surround output", "vibrate ringing" };
4192 for (audio_policy_force_use_t i = AUDIO_POLICY_FORCE_FOR_COMMUNICATION;
4193 i < AUDIO_POLICY_FORCE_USE_CNT; i = (audio_policy_force_use_t)((int)i + 1)) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08004194 audio_policy_forced_cfg_t forceUseValue = mEngine->getForceUse(i);
4195 dst->appendFormat(" Force use for %s: %d", forceUses[i], forceUseValue);
4196 if (i == AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND &&
4197 forceUseValue == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
4198 dst->append(" (MANUAL: ");
4199 dumpManualSurroundFormats(dst);
4200 dst->append(")");
4201 }
4202 dst->append("\n");
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07004203 }
Andy Hungc29d82b2018-10-05 12:23:17 -07004204 dst->appendFormat(" TTS output %savailable\n", mTtsOutputAvailable ? "" : "not ");
4205 dst->appendFormat(" Master mono: %s\n", mMasterMono ? "on" : "off");
Mikhail Naganovb3bcb4f2022-02-23 23:46:56 +00004206 dst->appendFormat(" Communication Strategy id: %d\n", mCommunnicationStrategy);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07004207 dst->appendFormat(" Config source: %s\n", mConfig->getSource().c_str());
Eric Laurent2517af32020-11-25 15:31:27 +01004208
Mikhail Naganov0f413b22021-12-02 05:29:27 +00004209 dst->append("\n");
4210 mAvailableOutputDevices.dump(dst, String8("Available output"), 1);
4211 dst->append("\n");
4212 mAvailableInputDevices.dump(dst, String8("Available input"), 1);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07004213 mHwModules.dump(dst);
Andy Hungc29d82b2018-10-05 12:23:17 -07004214 mOutputs.dump(dst);
4215 mInputs.dump(dst);
Mikhail Naganov0f413b22021-12-02 05:29:27 +00004216 mEffects.dump(dst, 1);
Andy Hungc29d82b2018-10-05 12:23:17 -07004217 mAudioPatches.dump(dst);
4218 mPolicyMixes.dump(dst);
4219 mAudioSources.dump(dst);
François Gaffiec005e562018-11-06 15:04:49 +01004220
Kevin Rocardb99cc752019-03-21 20:52:24 -07004221 dst->appendFormat(" AllowedCapturePolicies:\n");
4222 for (auto& policy : mAllowedCapturePolicies) {
4223 dst->appendFormat(" - uid=%d flag_mask=%#x\n", policy.first, policy.second);
4224 }
4225
jiabina84c3d32022-12-02 18:59:55 +00004226 dst->appendFormat(" Preferred mixer audio configuration:\n");
4227 for (const auto it : mPreferredMixerAttrInfos) {
4228 dst->appendFormat(" - device port id: %d\n", it.first);
4229 for (const auto preferredMixerInfoIt : it.second) {
4230 dst->appendFormat(" - strategy: %d; ", preferredMixerInfoIt.first);
4231 preferredMixerInfoIt.second->dump(dst);
4232 }
4233 }
4234
François Gaffiec005e562018-11-06 15:04:49 +01004235 dst->appendFormat("\nPolicy Engine dump:\n");
4236 mEngine->dump(dst);
Andy Hungc29d82b2018-10-05 12:23:17 -07004237}
4238
4239status_t AudioPolicyManager::dump(int fd)
4240{
4241 String8 result;
4242 dump(&result);
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00004243 write(fd, result.c_str(), result.size());
Eric Laurente552edb2014-03-10 17:42:56 -07004244 return NO_ERROR;
4245}
4246
Kevin Rocardb99cc752019-03-21 20:52:24 -07004247status_t AudioPolicyManager::setAllowedCapturePolicy(uid_t uid, audio_flags_mask_t capturePolicy)
4248{
4249 mAllowedCapturePolicies[uid] = capturePolicy;
4250 return NO_ERROR;
4251}
4252
Eric Laurente552edb2014-03-10 17:42:56 -07004253// This function checks for the parameters which can be offloaded.
4254// This can be enhanced depending on the capability of the DSP and policy
4255// of the system.
Eric Laurent90fe31c2020-11-26 20:06:35 +01004256audio_offload_mode_t AudioPolicyManager::getOffloadSupport(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07004257{
Eric Laurent90fe31c2020-11-26 20:06:35 +01004258 ALOGV("%s: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07004259 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurent90fe31c2020-11-26 20:06:35 +01004260 __func__, offloadInfo.sample_rate, offloadInfo.channel_mask,
Eric Laurente552edb2014-03-10 17:42:56 -07004261 offloadInfo.format,
4262 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
4263 offloadInfo.has_video);
4264
jiabin2b9d5a12021-12-10 01:06:29 +00004265 if (!isOffloadPossible(offloadInfo)) {
Eric Laurent90fe31c2020-11-26 20:06:35 +01004266 return AUDIO_OFFLOAD_NOT_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07004267 }
4268
4269 // See if there is a profile to support this.
4270 // AUDIO_DEVICE_NONE
François Gaffie11d30102018-11-02 16:09:09 +01004271 sp<IOProfile> profile = getProfileForOutput(DeviceVector() /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07004272 offloadInfo.sample_rate,
4273 offloadInfo.format,
4274 offloadInfo.channel_mask,
Michael Chana94fbb22018-04-24 14:31:19 +10004275 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD,
4276 true /* directOnly */);
Eric Laurent94365442021-01-08 18:36:05 +01004277 ALOGV("%s: profile %sfound%s", __func__, profile != nullptr ? "" : "NOT ",
4278 (profile != nullptr && (profile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD) != 0)
4279 ? ", supports gapless" : "");
Eric Laurent90fe31c2020-11-26 20:06:35 +01004280 if (profile == nullptr) {
4281 return AUDIO_OFFLOAD_NOT_SUPPORTED;
4282 }
4283 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD) != 0) {
4284 return AUDIO_OFFLOAD_GAPLESS_SUPPORTED;
4285 }
4286 return AUDIO_OFFLOAD_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07004287}
4288
Michael Chana94fbb22018-04-24 14:31:19 +10004289bool AudioPolicyManager::isDirectOutputSupported(const audio_config_base_t& config,
4290 const audio_attributes_t& attributes) {
4291 audio_output_flags_t output_flags = AUDIO_OUTPUT_FLAG_NONE;
François Gaffie58d4be52018-11-06 15:30:12 +01004292 audio_flags_to_audio_output_flags(attributes.flags, &output_flags);
Dorin Drimus9901eb02022-01-14 11:36:51 +00004293 DeviceVector outputDevices = mEngine->getOutputDevicesForAttributes(attributes);
4294 sp<IOProfile> profile = getProfileForOutput(outputDevices,
Michael Chana94fbb22018-04-24 14:31:19 +10004295 config.sample_rate,
4296 config.format,
4297 config.channel_mask,
4298 output_flags,
4299 true /* directOnly */);
4300 ALOGV("%s() profile %sfound with name: %s, "
4301 "sample rate: %u, format: 0x%x, channel_mask: 0x%x, output flags: 0x%x",
4302 __FUNCTION__, profile != 0 ? "" : "NOT ",
jiabin5740f082019-08-19 15:08:30 -07004303 (profile != 0 ? profile->getTagName().c_str() : "null"),
Michael Chana94fbb22018-04-24 14:31:19 +10004304 config.sample_rate, config.format, config.channel_mask, output_flags);
Dorin Drimusecc9f422022-03-09 17:57:40 +01004305
4306 // also try the MSD module if compatible profile not found
4307 if (profile == nullptr) {
4308 profile = getMsdProfileForOutput(outputDevices,
4309 config.sample_rate,
4310 config.format,
4311 config.channel_mask,
4312 output_flags,
4313 true /* directOnly */);
4314 ALOGV("%s() MSD profile %sfound with name: %s, "
4315 "sample rate: %u, format: 0x%x, channel_mask: 0x%x, output flags: 0x%x",
4316 __FUNCTION__, profile != 0 ? "" : "NOT ",
4317 (profile != 0 ? profile->getTagName().c_str() : "null"),
4318 config.sample_rate, config.format, config.channel_mask, output_flags);
4319 }
4320 return (profile != nullptr);
Michael Chana94fbb22018-04-24 14:31:19 +10004321}
4322
jiabin2b9d5a12021-12-10 01:06:29 +00004323bool AudioPolicyManager::isOffloadPossible(const audio_offload_info_t &offloadInfo,
4324 bool durationIgnored) {
4325 if (mMasterMono) {
4326 return false; // no offloading if mono is set.
4327 }
4328
4329 // Check if offload has been disabled
4330 if (property_get_bool("audio.offload.disable", false /* default_value */)) {
4331 ALOGV("%s: offload disabled by audio.offload.disable", __func__);
4332 return false;
4333 }
4334
4335 // Check if stream type is music, then only allow offload as of now.
4336 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
4337 {
4338 ALOGV("%s: stream_type != MUSIC, returning false", __func__);
4339 return false;
4340 }
4341
4342 //TODO: enable audio offloading with video when ready
4343 const bool allowOffloadWithVideo =
4344 property_get_bool("audio.offload.video", false /* default_value */);
4345 if (offloadInfo.has_video && !allowOffloadWithVideo) {
4346 ALOGV("%s: has_video == true, returning false", __func__);
4347 return false;
4348 }
4349
4350 //If duration is less than minimum value defined in property, return false
4351 const int min_duration_secs = property_get_int32(
4352 "audio.offload.min.duration.secs", -1 /* default_value */);
4353 if (!durationIgnored) {
4354 if (min_duration_secs >= 0) {
4355 if (offloadInfo.duration_us < min_duration_secs * 1000000LL) {
4356 ALOGV("%s: Offload denied by duration < audio.offload.min.duration.secs(=%d)",
4357 __func__, min_duration_secs);
4358 return false;
4359 }
4360 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
4361 ALOGV("%s: Offload denied by duration < default min(=%u)",
4362 __func__, OFFLOAD_DEFAULT_MIN_DURATION_SECS);
4363 return false;
4364 }
4365 }
4366
4367 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
4368 // creating an offloaded track and tearing it down immediately after start when audioflinger
4369 // detects there is an active non offloadable effect.
4370 // FIXME: We should check the audio session here but we do not have it in this context.
4371 // This may prevent offloading in rare situations where effects are left active by apps
4372 // in the background.
4373 if (mEffects.isNonOffloadableEffectEnabled()) {
4374 return false;
4375 }
4376
4377 return true;
4378}
4379
4380audio_direct_mode_t AudioPolicyManager::getDirectPlaybackSupport(const audio_attributes_t *attr,
4381 const audio_config_t *config) {
4382 audio_offload_info_t offloadInfo = AUDIO_INFO_INITIALIZER;
4383 offloadInfo.format = config->format;
4384 offloadInfo.sample_rate = config->sample_rate;
4385 offloadInfo.channel_mask = config->channel_mask;
4386 offloadInfo.stream_type = mEngine->getStreamTypeForAttributes(*attr);
4387 offloadInfo.has_video = false;
4388 offloadInfo.is_streaming = false;
4389 const bool offloadPossible = isOffloadPossible(offloadInfo, true /*durationIgnored*/);
4390
4391 audio_direct_mode_t directMode = AUDIO_DIRECT_NOT_SUPPORTED;
4392 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
4393 audio_flags_to_audio_output_flags(attr->flags, &flags);
4394 // only retain flags that will drive compressed offload or passthrough
4395 uint32_t relevantFlags = AUDIO_OUTPUT_FLAG_HW_AV_SYNC;
4396 if (offloadPossible) {
4397 relevantFlags |= AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD;
4398 }
4399 flags = (audio_output_flags_t)((flags & relevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
4400
Dorin Drimusfae3c642022-03-17 18:36:30 +01004401 DeviceVector engineOutputDevices = mEngine->getOutputDevicesForAttributes(*attr);
jiabin2b9d5a12021-12-10 01:06:29 +00004402 for (const auto& hwModule : mHwModules) {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004403 DeviceVector outputDevices = engineOutputDevices;
4404 // the MSD module checks for different conditions and output devices
4405 if (strcmp(hwModule->getName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0) {
4406 if (!msdHasPatchesToAllDevices(engineOutputDevices.toTypeAddrVector())) {
4407 continue;
4408 }
4409 outputDevices = getMsdAudioOutDevices();
4410 }
jiabin2b9d5a12021-12-10 01:06:29 +00004411 for (const auto& curProfile : hwModule->getOutputProfiles()) {
jiabinc8f7dfc2022-01-06 18:42:08 +00004412 if (!curProfile->isCompatibleProfile(outputDevices,
jiabin2b9d5a12021-12-10 01:06:29 +00004413 config->sample_rate, nullptr /*updatedSamplingRate*/,
4414 config->format, nullptr /*updatedFormat*/,
4415 config->channel_mask, nullptr /*updatedChannelMask*/,
4416 flags)) {
4417 continue;
4418 }
4419 // reject profiles not corresponding to a device currently available
4420 if (!mAvailableOutputDevices.containsAtLeastOne(curProfile->getSupportedDevices())) {
4421 continue;
4422 }
Yinchu Chen9f667582023-10-10 09:44:54 +00004423 if (offloadPossible && ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)
4424 != AUDIO_OUTPUT_FLAG_NONE)) {
jiabinc6132d62022-01-01 07:36:31 +00004425 if ((directMode & AUDIO_DIRECT_OFFLOAD_GAPLESS_SUPPORTED)
jiabin2b9d5a12021-12-10 01:06:29 +00004426 != AUDIO_DIRECT_NOT_SUPPORTED) {
4427 // Already reports offload gapless supported. No need to report offload support.
4428 continue;
4429 }
4430 if ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD)
4431 != AUDIO_OUTPUT_FLAG_NONE) {
4432 // If offload gapless is reported, no need to report offload support.
4433 directMode = (audio_direct_mode_t) ((directMode &
4434 ~AUDIO_DIRECT_OFFLOAD_SUPPORTED) |
4435 AUDIO_DIRECT_OFFLOAD_GAPLESS_SUPPORTED);
4436 } else {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004437 directMode = (audio_direct_mode_t)(directMode | AUDIO_DIRECT_OFFLOAD_SUPPORTED);
jiabin2b9d5a12021-12-10 01:06:29 +00004438 }
4439 } else {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004440 directMode = (audio_direct_mode_t) (directMode | AUDIO_DIRECT_BITSTREAM_SUPPORTED);
jiabin2b9d5a12021-12-10 01:06:29 +00004441 }
4442 }
4443 }
4444 return directMode;
4445}
4446
Dorin Drimusf2196d82022-01-03 12:11:18 +01004447status_t AudioPolicyManager::getDirectProfilesForAttributes(const audio_attributes_t* attr,
4448 AudioProfileVector& audioProfilesVector) {
Dorin Drimus17112632022-09-23 15:28:51 +00004449 if (mEffects.isNonOffloadableEffectEnabled()) {
4450 return OK;
4451 }
jiabinf1c73972022-04-14 16:28:52 -07004452 DeviceVector devices;
4453 status_t status = getDevicesForAttributes(*attr, devices, false /* forVolume */);
Dorin Drimusf2196d82022-01-03 12:11:18 +01004454 if (status != OK) {
4455 return status;
4456 }
4457 ALOGV("%s: found %zu output devices for attributes.", __func__, devices.size());
4458 if (devices.empty()) {
4459 return OK; // no output devices for the attributes
4460 }
jiabinf1c73972022-04-14 16:28:52 -07004461 return getProfilesForDevices(devices, audioProfilesVector,
4462 AUDIO_OUTPUT_FLAG_DIRECT /*flags*/, false /*isInput*/);
Dorin Drimusf2196d82022-01-03 12:11:18 +01004463}
4464
jiabina84c3d32022-12-02 18:59:55 +00004465status_t AudioPolicyManager::getSupportedMixerAttributes(
4466 audio_port_handle_t portId, std::vector<audio_mixer_attributes_t> &mixerAttrs) {
4467 ALOGV("%s, portId=%d", __func__, portId);
4468 sp<DeviceDescriptor> deviceDescriptor = mAvailableOutputDevices.getDeviceFromId(portId);
4469 if (deviceDescriptor == nullptr) {
4470 ALOGE("%s the requested device is currently unavailable", __func__);
4471 return BAD_VALUE;
4472 }
jiabin96daffc2023-05-11 17:51:55 +00004473 if (!audio_is_usb_out_device(deviceDescriptor->type())) {
4474 ALOGE("%s the requested device(type=%#x) is not usb device", __func__,
4475 deviceDescriptor->type());
4476 return BAD_VALUE;
4477 }
jiabina84c3d32022-12-02 18:59:55 +00004478 for (const auto& hwModule : mHwModules) {
4479 for (const auto& curProfile : hwModule->getOutputProfiles()) {
4480 if (curProfile->supportsDevice(deviceDescriptor)) {
4481 curProfile->toSupportedMixerAttributes(&mixerAttrs);
4482 }
4483 }
4484 }
4485 return NO_ERROR;
4486}
4487
4488status_t AudioPolicyManager::setPreferredMixerAttributes(
4489 const audio_attributes_t *attr,
4490 audio_port_handle_t portId,
4491 uid_t uid,
4492 const audio_mixer_attributes_t *mixerAttributes) {
4493 ALOGV("%s, attr=%s, mixerAttributes={format=%#x, channelMask=%#x, samplingRate=%u, "
4494 "mixerBehavior=%d}, uid=%d, portId=%u",
4495 __func__, toString(*attr).c_str(), mixerAttributes->config.format,
4496 mixerAttributes->config.channel_mask, mixerAttributes->config.sample_rate,
4497 mixerAttributes->mixer_behavior, uid, portId);
4498 if (attr->usage != AUDIO_USAGE_MEDIA) {
4499 ALOGE("%s failed, only media is allowed, the given usage is %d", __func__, attr->usage);
4500 return BAD_VALUE;
4501 }
4502 sp<DeviceDescriptor> deviceDescriptor = mAvailableOutputDevices.getDeviceFromId(portId);
4503 if (deviceDescriptor == nullptr) {
4504 ALOGE("%s the requested device is currently unavailable", __func__);
4505 return BAD_VALUE;
4506 }
4507 if (!audio_is_usb_out_device(deviceDescriptor->type())) {
4508 ALOGE("%s(%d), type=%d, is not a usb output device",
4509 __func__, portId, deviceDescriptor->type());
4510 return BAD_VALUE;
4511 }
4512
4513 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
4514 audio_flags_to_audio_output_flags(attr->flags, &flags);
4515 flags = (audio_output_flags_t) (flags |
4516 audio_output_flags_from_mixer_behavior(mixerAttributes->mixer_behavior));
4517 sp<IOProfile> profile = nullptr;
4518 DeviceVector devices(deviceDescriptor);
4519 for (const auto& hwModule : mHwModules) {
4520 for (const auto& curProfile : hwModule->getOutputProfiles()) {
4521 if (curProfile->hasDynamicAudioProfile()
4522 && curProfile->isCompatibleProfile(devices,
4523 mixerAttributes->config.sample_rate,
4524 nullptr /*updatedSamplingRate*/,
4525 mixerAttributes->config.format,
4526 nullptr /*updatedFormat*/,
4527 mixerAttributes->config.channel_mask,
4528 nullptr /*updatedChannelMask*/,
4529 flags,
4530 false /*exactMatchRequiredForInputFlags*/)) {
4531 profile = curProfile;
4532 break;
4533 }
4534 }
4535 }
4536 if (profile == nullptr) {
4537 ALOGE("%s, there is no compatible profile found", __func__);
4538 return BAD_VALUE;
4539 }
4540
4541 sp<PreferredMixerAttributesInfo> mixerAttrInfo =
4542 sp<PreferredMixerAttributesInfo>::make(
4543 uid, portId, profile, flags, *mixerAttributes);
4544 const product_strategy_t strategy = mEngine->getProductStrategyForAttributes(*attr);
4545 mPreferredMixerAttrInfos[portId][strategy] = mixerAttrInfo;
4546
4547 // If 1) there is any client from the preferred mixer configuration owner that is currently
4548 // active and matches the strategy and 2) current output is on the preferred device and the
4549 // mixer configuration doesn't match the preferred one, reopen output with preferred mixer
4550 // configuration.
4551 std::vector<audio_io_handle_t> outputsToReopen;
4552 for (size_t i = 0; i < mOutputs.size(); i++) {
4553 const auto output = mOutputs.valueAt(i);
jiabin3ff8d7d2022-12-13 06:27:44 +00004554 if (output->mProfile == profile && output->devices().onlyContainsDevice(deviceDescriptor)) {
4555 if (output->isConfigurationMatched(mixerAttributes->config, flags)) {
4556 output->mUsePreferredMixerAttributes = true;
4557 } else {
4558 for (const auto &client: output->getActiveClients()) {
4559 if (client->uid() == uid && client->strategy() == strategy) {
4560 client->setIsInvalid();
4561 outputsToReopen.push_back(output->mIoHandle);
4562 }
jiabina84c3d32022-12-02 18:59:55 +00004563 }
4564 }
4565 }
4566 }
4567 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
4568 config.sample_rate = mixerAttributes->config.sample_rate;
4569 config.channel_mask = mixerAttributes->config.channel_mask;
4570 config.format = mixerAttributes->config.format;
4571 for (const auto output : outputsToReopen) {
jiabin3ff8d7d2022-12-13 06:27:44 +00004572 sp<SwAudioOutputDescriptor> desc =
4573 reopenOutput(mOutputs.valueFor(output), &config, flags, __func__);
4574 if (desc == nullptr) {
4575 ALOGE("%s, failed to reopen output with preferred mixer attributes", __func__);
4576 continue;
4577 }
4578 desc->mUsePreferredMixerAttributes = true;
jiabina84c3d32022-12-02 18:59:55 +00004579 }
4580
4581 return NO_ERROR;
4582}
4583
4584sp<PreferredMixerAttributesInfo> AudioPolicyManager::getPreferredMixerAttributesInfo(
jiabind9a58d32023-06-01 17:57:30 +00004585 audio_port_handle_t devicePortId,
4586 product_strategy_t strategy,
4587 bool activeBitPerfectPreferred) {
jiabina84c3d32022-12-02 18:59:55 +00004588 auto it = mPreferredMixerAttrInfos.find(devicePortId);
4589 if (it == mPreferredMixerAttrInfos.end()) {
4590 return nullptr;
4591 }
jiabind9a58d32023-06-01 17:57:30 +00004592 if (activeBitPerfectPreferred) {
4593 for (auto [strategy, info] : it->second) {
4594 if ((info->getFlags() & AUDIO_OUTPUT_FLAG_BIT_PERFECT) != AUDIO_OUTPUT_FLAG_NONE
4595 && info->getActiveClientCount() != 0) {
4596 return info;
4597 }
4598 }
jiabina84c3d32022-12-02 18:59:55 +00004599 }
jiabind9a58d32023-06-01 17:57:30 +00004600 auto strategyMatchedMixerAttrInfoIt = it->second.find(strategy);
4601 return strategyMatchedMixerAttrInfoIt == it->second.end()
4602 ? nullptr : strategyMatchedMixerAttrInfoIt->second;
jiabina84c3d32022-12-02 18:59:55 +00004603}
4604
4605status_t AudioPolicyManager::getPreferredMixerAttributes(
4606 const audio_attributes_t *attr,
4607 audio_port_handle_t portId,
4608 audio_mixer_attributes_t* mixerAttributes) {
4609 sp<PreferredMixerAttributesInfo> info = getPreferredMixerAttributesInfo(
4610 portId, mEngine->getProductStrategyForAttributes(*attr));
4611 if (info == nullptr) {
4612 return NAME_NOT_FOUND;
4613 }
4614 *mixerAttributes = info->getMixerAttributes();
4615 return NO_ERROR;
4616}
4617
4618status_t AudioPolicyManager::clearPreferredMixerAttributes(const audio_attributes_t *attr,
4619 audio_port_handle_t portId,
4620 uid_t uid) {
4621 const product_strategy_t strategy = mEngine->getProductStrategyForAttributes(*attr);
4622 const auto preferredMixerAttrInfo = getPreferredMixerAttributesInfo(portId, strategy);
4623 if (preferredMixerAttrInfo == nullptr) {
4624 return NAME_NOT_FOUND;
4625 }
4626 if (preferredMixerAttrInfo->getUid() != uid) {
4627 ALOGE("%s, requested uid=%d, owned uid=%d",
4628 __func__, uid, preferredMixerAttrInfo->getUid());
4629 return PERMISSION_DENIED;
4630 }
4631 mPreferredMixerAttrInfos[portId].erase(strategy);
4632 if (mPreferredMixerAttrInfos[portId].empty()) {
4633 mPreferredMixerAttrInfos.erase(portId);
4634 }
4635
4636 // Reconfig existing output
4637 std::vector<audio_io_handle_t> potentialOutputsToReopen;
4638 for (size_t i = 0; i < mOutputs.size(); i++) {
4639 if (mOutputs.valueAt(i)->mProfile == preferredMixerAttrInfo->getProfile()) {
4640 potentialOutputsToReopen.push_back(mOutputs.keyAt(i));
4641 }
4642 }
4643 for (const auto output : potentialOutputsToReopen) {
4644 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
4645 if (desc->isConfigurationMatched(preferredMixerAttrInfo->getConfigBase(),
4646 preferredMixerAttrInfo->getFlags())) {
4647 reopenOutput(desc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
4648 }
4649 }
4650 return NO_ERROR;
4651}
4652
Eric Laurent6a94d692014-05-20 11:18:06 -07004653status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
4654 audio_port_type_t type,
4655 unsigned int *num_ports,
jiabin19cdba52020-11-24 11:28:58 -08004656 struct audio_port_v7 *ports,
Eric Laurent6a94d692014-05-20 11:18:06 -07004657 unsigned int *generation)
4658{
jiabin19cdba52020-11-24 11:28:58 -08004659 if (num_ports == nullptr || (*num_ports != 0 && ports == nullptr) ||
4660 generation == nullptr) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004661 return BAD_VALUE;
4662 }
4663 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
jiabin19cdba52020-11-24 11:28:58 -08004664 if (ports == nullptr) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004665 *num_ports = 0;
4666 }
4667
4668 size_t portsWritten = 0;
4669 size_t portsMax = *num_ports;
4670 *num_ports = 0;
4671 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07004672 // do not report devices with type AUDIO_DEVICE_IN_STUB or AUDIO_DEVICE_OUT_STUB
4673 // as they are used by stub HALs by convention
Eric Laurent6a94d692014-05-20 11:18:06 -07004674 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004675 for (const auto& dev : mAvailableOutputDevices) {
4676 if (dev->type() == AUDIO_DEVICE_OUT_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07004677 continue;
4678 }
4679 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004680 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07004681 }
4682 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07004683 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004684 }
4685 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004686 for (const auto& dev : mAvailableInputDevices) {
4687 if (dev->type() == AUDIO_DEVICE_IN_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07004688 continue;
4689 }
4690 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004691 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07004692 }
4693 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07004694 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004695 }
4696 }
4697 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
4698 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
4699 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
4700 mInputs[i]->toAudioPort(&ports[portsWritten++]);
4701 }
4702 *num_ports += mInputs.size();
4703 }
4704 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent84c70242014-06-23 08:46:27 -07004705 size_t numOutputs = 0;
4706 for (size_t i = 0; i < mOutputs.size(); i++) {
4707 if (!mOutputs[i]->isDuplicated()) {
4708 numOutputs++;
4709 if (portsWritten < portsMax) {
4710 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
4711 }
4712 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004713 }
Eric Laurent84c70242014-06-23 08:46:27 -07004714 *num_ports += numOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07004715 }
4716 }
jiabina84c3d32022-12-02 18:59:55 +00004717
Eric Laurent6a94d692014-05-20 11:18:06 -07004718 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07004719 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
Eric Laurent6a94d692014-05-20 11:18:06 -07004720 return NO_ERROR;
4721}
4722
Mikhail Naganov5edc5ed2023-03-23 14:52:15 -07004723status_t AudioPolicyManager::listDeclaredDevicePorts(media::AudioPortRole role,
4724 std::vector<media::AudioPortFw>* _aidl_return) {
4725 auto pushPort = [&](const sp<DeviceDescriptor>& dev) -> status_t {
4726 audio_port_v7 port;
4727 dev->toAudioPort(&port);
4728 auto aidlPort = VALUE_OR_RETURN_STATUS(legacy2aidl_audio_port_v7_AudioPortFw(port));
4729 _aidl_return->push_back(std::move(aidlPort));
4730 return OK;
4731 };
4732
Mikhail Naganov68e3f642023-04-28 13:06:32 -07004733 for (const auto& module : mHwModules) {
Mikhail Naganov5edc5ed2023-03-23 14:52:15 -07004734 for (const auto& dev : module->getDeclaredDevices()) {
4735 if (role == media::AudioPortRole::NONE ||
4736 ((role == media::AudioPortRole::SOURCE)
4737 == audio_is_input_device(dev->type()))) {
4738 RETURN_STATUS_IF_ERROR(pushPort(dev));
4739 }
4740 }
4741 }
4742 return OK;
4743}
4744
jiabin19cdba52020-11-24 11:28:58 -08004745status_t AudioPolicyManager::getAudioPort(struct audio_port_v7 *port)
Eric Laurent6a94d692014-05-20 11:18:06 -07004746{
Eric Laurent99fcae42018-05-17 16:59:18 -07004747 if (port == nullptr || port->id == AUDIO_PORT_HANDLE_NONE) {
4748 return BAD_VALUE;
4749 }
4750 sp<DeviceDescriptor> dev = mAvailableOutputDevices.getDeviceFromId(port->id);
4751 if (dev != 0) {
4752 dev->toAudioPort(port);
4753 return NO_ERROR;
4754 }
4755 dev = mAvailableInputDevices.getDeviceFromId(port->id);
4756 if (dev != 0) {
4757 dev->toAudioPort(port);
4758 return NO_ERROR;
4759 }
4760 sp<SwAudioOutputDescriptor> out = mOutputs.getOutputFromId(port->id);
4761 if (out != 0) {
4762 out->toAudioPort(port);
4763 return NO_ERROR;
4764 }
4765 sp<AudioInputDescriptor> in = mInputs.getInputFromId(port->id);
4766 if (in != 0) {
4767 in->toAudioPort(port);
4768 return NO_ERROR;
4769 }
4770 return BAD_VALUE;
Eric Laurent6a94d692014-05-20 11:18:06 -07004771}
4772
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004773status_t AudioPolicyManager::createAudioPatch(const struct audio_patch *patch,
4774 audio_patch_handle_t *handle,
4775 uid_t uid)
Eric Laurent6a94d692014-05-20 11:18:06 -07004776{
François Gaffieafd4cea2019-11-18 15:50:22 +01004777 ALOGV("%s", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004778 if (handle == NULL || patch == NULL) {
4779 return BAD_VALUE;
4780 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004781 ALOGV("%s num sources %d num sinks %d", __func__, patch->num_sources, patch->num_sinks);
Mikhail Naganovac9858b2018-06-15 13:12:37 -07004782 if (!audio_patch_is_valid(patch)) {
Eric Laurent874c42872014-08-08 15:13:39 -07004783 return BAD_VALUE;
4784 }
4785 // only one source per audio patch supported for now
4786 if (patch->num_sources > 1) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004787 return INVALID_OPERATION;
4788 }
Eric Laurent874c42872014-08-08 15:13:39 -07004789 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004790 return INVALID_OPERATION;
4791 }
Eric Laurent874c42872014-08-08 15:13:39 -07004792 for (size_t i = 0; i < patch->num_sinks; i++) {
4793 if (patch->sinks[i].role != AUDIO_PORT_ROLE_SINK) {
4794 return INVALID_OPERATION;
4795 }
4796 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004797
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004798 sp<DeviceDescriptor> srcDevice = mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
4799 sp<DeviceDescriptor> sinkDevice = mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id);
4800 if (srcDevice == nullptr || sinkDevice == nullptr) {
4801 ALOGW("%s could not create patch, invalid sink and/or source device(s)", __func__);
4802 return BAD_VALUE;
4803 }
4804 ALOGV("%s between source %s and sink %s", __func__,
4805 srcDevice->toString().c_str(), sinkDevice->toString().c_str());
4806 audio_port_handle_t portId = PolicyAudioPort::getNextUniqueId();
4807 // Default attributes, default volume priority, not to infer with non raw audio patches.
4808 audio_attributes_t attributes = attributes_initializer(AUDIO_USAGE_MEDIA);
4809 const struct audio_port_config *source = &patch->sources[0];
4810 sp<SourceClientDescriptor> sourceDesc =
4811 new InternalSourceClientDescriptor(
4812 portId, uid, attributes, *source, srcDevice, sinkDevice,
4813 mEngine->getProductStrategyForAttributes(attributes), toVolumeSource(attributes));
4814
4815 status_t status =
4816 connectAudioSourceToSink(sourceDesc, sinkDevice, patch, *handle, uid, 0 /* delayMs */);
4817
4818 if (status != NO_ERROR) {
4819 return INVALID_OPERATION;
4820 }
4821 mAudioSources.add(portId, sourceDesc);
4822 return NO_ERROR;
4823}
4824
4825status_t AudioPolicyManager::connectAudioSourceToSink(
4826 const sp<SourceClientDescriptor>& sourceDesc, const sp<DeviceDescriptor> &sinkDevice,
4827 const struct audio_patch *patch,
4828 audio_patch_handle_t &handle,
4829 uid_t uid, uint32_t delayMs)
4830{
4831 status_t status = createAudioPatchInternal(patch, &handle, uid, delayMs, sourceDesc);
4832 if (status != NO_ERROR || mAudioPatches.indexOfKey(handle) < 0) {
4833 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
4834 return INVALID_OPERATION;
4835 }
4836 sourceDesc->connect(handle, sinkDevice);
4837 if (isMsdPatch(handle)) {
4838 return NO_ERROR;
4839 }
4840 // SW Bridge? (@todo: HW bridge, keep track of HwOutput for device selection "reconsideration")
4841 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
4842 ALOG_ASSERT(swOutput != nullptr, "%s: a swOutput shall always be associated", __func__);
4843 if (swOutput->getClient(sourceDesc->portId()) != nullptr) {
4844 ALOGW("%s source portId has already been attached to outputDesc", __func__);
4845 goto FailurePatchAdded;
4846 }
4847 status = swOutput->start();
4848 if (status != NO_ERROR) {
4849 goto FailureSourceAdded;
4850 }
4851 swOutput->addClient(sourceDesc);
4852 status = startSource(swOutput, sourceDesc, &delayMs);
4853 if (status != NO_ERROR) {
4854 ALOGW("%s failed to start source, error %d", __FUNCTION__, status);
4855 goto FailureSourceActive;
4856 }
4857 if (delayMs != 0) {
4858 usleep(delayMs * 1000);
4859 }
4860 return NO_ERROR;
4861
4862FailureSourceActive:
4863 swOutput->stop();
4864 releaseOutput(sourceDesc->portId());
4865FailureSourceAdded:
4866 sourceDesc->setSwOutput(nullptr);
4867FailurePatchAdded:
4868 releaseAudioPatchInternal(handle);
4869 return INVALID_OPERATION;
4870}
4871
4872status_t AudioPolicyManager::createAudioPatchInternal(const struct audio_patch *patch,
4873 audio_patch_handle_t *handle,
4874 uid_t uid, uint32_t delayMs,
4875 const sp<SourceClientDescriptor>& sourceDesc)
4876{
4877 ALOGV("%s num sources %d num sinks %d", __func__, patch->num_sources, patch->num_sinks);
Eric Laurent6a94d692014-05-20 11:18:06 -07004878 sp<AudioPatch> patchDesc;
4879 ssize_t index = mAudioPatches.indexOfKey(*handle);
4880
François Gaffieafd4cea2019-11-18 15:50:22 +01004881 ALOGV("%s source id %d role %d type %d", __func__, patch->sources[0].id,
4882 patch->sources[0].role,
4883 patch->sources[0].type);
Eric Laurent874c42872014-08-08 15:13:39 -07004884#if LOG_NDEBUG == 0
4885 for (size_t i = 0; i < patch->num_sinks; i++) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004886 ALOGV("%s sink %zu: id %d role %d type %d", __func__ ,i, patch->sinks[i].id,
4887 patch->sinks[i].role,
4888 patch->sinks[i].type);
Eric Laurent874c42872014-08-08 15:13:39 -07004889 }
4890#endif
Eric Laurent6a94d692014-05-20 11:18:06 -07004891
4892 if (index >= 0) {
4893 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01004894 ALOGV("%s mUidCached %d patchDesc->mUid %d uid %d",
4895 __func__, mUidCached, patchDesc->getUid(), uid);
4896 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004897 return INVALID_OPERATION;
4898 }
4899 } else {
Glenn Kastena13cde92016-03-28 15:26:02 -07004900 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07004901 }
4902
4903 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004904 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004905 if (outputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004906 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004907 return BAD_VALUE;
4908 }
Eric Laurent84c70242014-06-23 08:46:27 -07004909 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
4910 outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004911 if (patchDesc != 0) {
4912 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004913 ALOGV("%s source id differs for patch current id %d new id %d",
4914 __func__, patchDesc->mPatch.sources[0].id, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004915 return BAD_VALUE;
4916 }
4917 }
Eric Laurent874c42872014-08-08 15:13:39 -07004918 DeviceVector devices;
4919 for (size_t i = 0; i < patch->num_sinks; i++) {
4920 // Only support mix to devices connection
4921 // TODO add support for mix to mix connection
4922 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004923 ALOGV("%s source mix but sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07004924 return INVALID_OPERATION;
4925 }
4926 sp<DeviceDescriptor> devDesc =
4927 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
4928 if (devDesc == 0) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004929 ALOGV("%s out device not found for id %d", __func__, patch->sinks[i].id);
Eric Laurent874c42872014-08-08 15:13:39 -07004930 return BAD_VALUE;
4931 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004932
François Gaffie11d30102018-11-02 16:09:09 +01004933 if (!outputDesc->mProfile->isCompatibleProfile(DeviceVector(devDesc),
Eric Laurent874c42872014-08-08 15:13:39 -07004934 patch->sources[0].sample_rate,
François Gaffie53615e22015-03-19 09:24:12 +01004935 NULL, // updatedSamplingRate
4936 patch->sources[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07004937 NULL, // updatedFormat
François Gaffie53615e22015-03-19 09:24:12 +01004938 patch->sources[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07004939 NULL, // updatedChannelMask
François Gaffie53615e22015-03-19 09:24:12 +01004940 AUDIO_OUTPUT_FLAG_NONE /*FIXME*/)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004941 ALOGV("%s profile not supported for device %08x", __func__, devDesc->type());
Eric Laurent874c42872014-08-08 15:13:39 -07004942 return INVALID_OPERATION;
4943 }
4944 devices.add(devDesc);
4945 }
4946 if (devices.size() == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004947 return INVALID_OPERATION;
4948 }
Eric Laurent874c42872014-08-08 15:13:39 -07004949
Eric Laurent6a94d692014-05-20 11:18:06 -07004950 // TODO: reconfigure output format and channels here
François Gaffieafd4cea2019-11-18 15:50:22 +01004951 ALOGV("%s setting device %s on output %d",
4952 __func__, dumpDeviceTypes(devices.types()).c_str(), outputDesc->mIoHandle);
François Gaffie11d30102018-11-02 16:09:09 +01004953 setOutputDevices(outputDesc, devices, true, 0, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004954 index = mAudioPatches.indexOfKey(*handle);
4955 if (index >= 0) {
4956 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004957 ALOGW("%s setOutputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004958 }
4959 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01004960 patchDesc->setUid(uid);
4961 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004962 } else {
François Gaffieafd4cea2019-11-18 15:50:22 +01004963 ALOGW("%s setOutputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004964 return INVALID_OPERATION;
4965 }
4966 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
4967 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
4968 // input device to input mix connection
Eric Laurent874c42872014-08-08 15:13:39 -07004969 // only one sink supported when connecting an input device to a mix
4970 if (patch->num_sinks > 1) {
4971 return INVALID_OPERATION;
4972 }
François Gaffie53615e22015-03-19 09:24:12 +01004973 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004974 if (inputDesc == NULL) {
4975 return BAD_VALUE;
4976 }
4977 if (patchDesc != 0) {
4978 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
4979 return BAD_VALUE;
4980 }
4981 }
François Gaffie11d30102018-11-02 16:09:09 +01004982 sp<DeviceDescriptor> device =
Eric Laurent6a94d692014-05-20 11:18:06 -07004983 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01004984 if (device == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004985 return BAD_VALUE;
4986 }
4987
François Gaffie11d30102018-11-02 16:09:09 +01004988 if (!inputDesc->mProfile->isCompatibleProfile(DeviceVector(device),
Eric Laurent275e8e92014-11-30 15:14:47 -08004989 patch->sinks[0].sample_rate,
4990 NULL, /*updatedSampleRate*/
4991 patch->sinks[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07004992 NULL, /*updatedFormat*/
Eric Laurent275e8e92014-11-30 15:14:47 -08004993 patch->sinks[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07004994 NULL, /*updatedChannelMask*/
Eric Laurent275e8e92014-11-30 15:14:47 -08004995 // FIXME for the parameter type,
4996 // and the NONE
4997 (audio_output_flags_t)
Glenn Kasten6a8ab052014-07-24 14:08:35 -07004998 AUDIO_INPUT_FLAG_NONE)) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004999 return INVALID_OPERATION;
5000 }
5001 // TODO: reconfigure output format and channels here
François Gaffieafd4cea2019-11-18 15:50:22 +01005002 ALOGV("%s setting device %s on output %d", __func__,
François Gaffie11d30102018-11-02 16:09:09 +01005003 device->toString().c_str(), inputDesc->mIoHandle);
5004 setInputDevice(inputDesc->mIoHandle, device, true, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005005 index = mAudioPatches.indexOfKey(*handle);
5006 if (index >= 0) {
5007 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005008 ALOGW("%s setInputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005009 }
5010 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005011 patchDesc->setUid(uid);
5012 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005013 } else {
François Gaffieafd4cea2019-11-18 15:50:22 +01005014 ALOGW("%s setInputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005015 return INVALID_OPERATION;
5016 }
5017 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
5018 // device to device connection
5019 if (patchDesc != 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07005020 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005021 return BAD_VALUE;
5022 }
5023 }
François Gaffie11d30102018-11-02 16:09:09 +01005024 sp<DeviceDescriptor> srcDevice =
Eric Laurent6a94d692014-05-20 11:18:06 -07005025 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01005026 if (srcDevice == 0) {
Eric Laurent58f8eb72014-09-12 16:19:41 -07005027 return BAD_VALUE;
5028 }
Eric Laurent874c42872014-08-08 15:13:39 -07005029
Eric Laurent6a94d692014-05-20 11:18:06 -07005030 //update source and sink with our own data as the data passed in the patch may
5031 // be incomplete.
François Gaffieafd4cea2019-11-18 15:50:22 +01005032 PatchBuilder patchBuilder;
5033 audio_port_config sourcePortConfig = {};
Dean Wheatley8bee85a2021-02-10 16:02:23 +11005034
5035 // if first sink is to MSD, establish single MSD patch
5036 if (getMsdAudioOutDevices().contains(
5037 mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id))) {
5038 ALOGV("%s patching to MSD", __FUNCTION__);
5039 patchBuilder = buildMsdPatch(false /*msdIsSource*/, srcDevice);
5040 goto installPatch;
5041 }
5042
François Gaffieafd4cea2019-11-18 15:50:22 +01005043 srcDevice->toAudioPortConfig(&sourcePortConfig, &patch->sources[0]);
5044 patchBuilder.addSource(sourcePortConfig);
Eric Laurent6a94d692014-05-20 11:18:06 -07005045
Eric Laurent874c42872014-08-08 15:13:39 -07005046 for (size_t i = 0; i < patch->num_sinks; i++) {
5047 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005048 ALOGV("%s source device but one sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07005049 return INVALID_OPERATION;
5050 }
François Gaffie11d30102018-11-02 16:09:09 +01005051 sp<DeviceDescriptor> sinkDevice =
Eric Laurent874c42872014-08-08 15:13:39 -07005052 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
François Gaffie11d30102018-11-02 16:09:09 +01005053 if (sinkDevice == 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07005054 return BAD_VALUE;
5055 }
François Gaffieafd4cea2019-11-18 15:50:22 +01005056 audio_port_config sinkPortConfig = {};
5057 sinkDevice->toAudioPortConfig(&sinkPortConfig, &patch->sinks[i]);
5058 patchBuilder.addSink(sinkPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07005059
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005060 // Whatever Sw or Hw bridge, we do attach an SwOutput to an Audio Source for
5061 // volume management purpose (tracking activity)
5062 // In case of Hw bridge, it is a Work Around. The mixPort used is the one declared
5063 // in config XML to reach the sink so that is can be declared as available.
5064 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurent78b07302022-10-07 16:20:34 +02005065 sp<SwAudioOutputDescriptor> outputDesc;
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005066 if (!sourceDesc->isInternal()) {
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005067 // take care of dynamic routing for SwOutput selection,
5068 audio_attributes_t attributes = sourceDesc->attributes();
5069 audio_stream_type_t stream = sourceDesc->stream();
5070 audio_attributes_t resultAttr;
5071 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
5072 config.sample_rate = sourceDesc->config().sample_rate;
François Gaffie2a24db42022-04-04 16:45:02 +02005073 audio_channel_mask_t sourceMask = sourceDesc->config().channel_mask;
5074 config.channel_mask =
5075 (audio_channel_mask_get_representation(sourceMask)
5076 == AUDIO_CHANNEL_REPRESENTATION_INDEX) ? sourceMask
5077 : audio_channel_mask_in_to_out(sourceMask);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005078 config.format = sourceDesc->config().format;
5079 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
5080 audio_port_handle_t selectedDeviceId = AUDIO_PORT_HANDLE_NONE;
5081 bool isRequestedDeviceForExclusiveUse = false;
5082 output_type_t outputType;
Eric Laurentb0a7bc92022-04-05 15:06:08 +02005083 bool isSpatialized;
jiabinc658e452022-10-21 20:52:21 +00005084 bool isBitPerfect;
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005085 getOutputForAttrInt(&resultAttr, &output, AUDIO_SESSION_NONE, &attributes,
5086 &stream, sourceDesc->uid(), &config, &flags,
5087 &selectedDeviceId, &isRequestedDeviceForExclusiveUse,
jiabinc658e452022-10-21 20:52:21 +00005088 nullptr, &outputType, &isSpatialized, &isBitPerfect);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005089 if (output == AUDIO_IO_HANDLE_NONE) {
5090 ALOGV("%s no output for device %s",
5091 __FUNCTION__, sinkDevice->toString().c_str());
5092 return INVALID_OPERATION;
5093 }
5094 outputDesc = mOutputs.valueFor(output);
5095 if (outputDesc->isDuplicated()) {
5096 ALOGE("%s output is duplicated", __func__);
5097 return INVALID_OPERATION;
5098 }
François Gaffie7e39df22022-04-26 12:48:49 +02005099 bool closeOutput = outputDesc->mDirectOpenCount != 0;
5100 sourceDesc->setSwOutput(outputDesc, closeOutput);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005101 } else {
5102 // Same for "raw patches" aka created from createAudioPatch API
5103 SortedVector<audio_io_handle_t> outputs =
5104 getOutputsForDevices(DeviceVector(sinkDevice), mOutputs);
5105 // if the sink device is reachable via an opened output stream, request to
5106 // go via this output stream by adding a second source to the patch
5107 // description
5108 output = selectOutput(outputs);
5109 if (output == AUDIO_IO_HANDLE_NONE) {
5110 ALOGE("%s no output available for internal patch sink", __func__);
5111 return INVALID_OPERATION;
5112 }
5113 outputDesc = mOutputs.valueFor(output);
5114 if (outputDesc->isDuplicated()) {
5115 ALOGV("%s output for device %s is duplicated",
5116 __func__, sinkDevice->toString().c_str());
5117 return INVALID_OPERATION;
5118 }
François Gaffie7e39df22022-04-26 12:48:49 +02005119 sourceDesc->setSwOutput(outputDesc, /* closeOutput= */ false);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005120 }
Eric Laurent3bcf8592015-04-03 12:13:24 -07005121 // create a software bridge in PatchPanel if:
Scott Randolphf3172402018-01-23 17:06:53 -08005122 // - source and sink devices are on different HW modules OR
Eric Laurent3bcf8592015-04-03 12:13:24 -07005123 // - audio HAL version is < 3.0
Francois Gaffie99896da2018-04-09 11:05:33 +02005124 // - audio HAL version is >= 3.0 but no route has been declared between devices
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005125 // - called from startAudioSource (aka sourceDesc is not internal) and source device
5126 // does not have a gain controller
François Gaffie11d30102018-11-02 16:09:09 +01005127 if (!srcDevice->hasSameHwModuleAs(sinkDevice) ||
5128 (srcDevice->getModuleVersionMajor() < 3) ||
François Gaffieafd4cea2019-11-18 15:50:22 +01005129 !srcDevice->getModule()->supportsPatch(srcDevice, sinkDevice) ||
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005130 (!sourceDesc->isInternal() &&
François Gaffieafd4cea2019-11-18 15:50:22 +01005131 srcDevice->getAudioPort()->getGains().size() == 0)) {
Eric Laurent3bcf8592015-04-03 12:13:24 -07005132 // support only one sink device for now to simplify output selection logic
Eric Laurent874c42872014-08-08 15:13:39 -07005133 if (patch->num_sinks > 1) {
Eric Laurent83b88082014-06-20 18:31:16 -07005134 return INVALID_OPERATION;
5135 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005136 sourceDesc->setUseSwBridge();
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005137 if (outputDesc != nullptr) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005138 audio_port_config srcMixPortConfig = {};
Ytai Ben-Tsvic9d2a912021-11-22 16:43:09 -08005139 outputDesc->toAudioPortConfig(&srcMixPortConfig, nullptr);
François Gaffieafd4cea2019-11-18 15:50:22 +01005140 // for volume control, we may need a valid stream
Eric Laurent78b07302022-10-07 16:20:34 +02005141 srcMixPortConfig.ext.mix.usecase.stream =
5142 (!sourceDesc->isInternal() || isCallTxAudioSource(sourceDesc)) ?
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005143 mEngine->getStreamTypeForAttributes(sourceDesc->attributes()) :
5144 AUDIO_STREAM_PATCH;
François Gaffieafd4cea2019-11-18 15:50:22 +01005145 patchBuilder.addSource(srcMixPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07005146 }
Eric Laurent83b88082014-06-20 18:31:16 -07005147 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005148 }
5149 // TODO: check from routing capabilities in config file and other conflicting patches
5150
Dean Wheatley8bee85a2021-02-10 16:02:23 +11005151installPatch:
François Gaffieafd4cea2019-11-18 15:50:22 +01005152 status_t status = installPatch(
5153 __func__, index, handle, patchBuilder.patch(), delayMs, uid, &patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07005154 if (status != NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005155 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
Eric Laurent6a94d692014-05-20 11:18:06 -07005156 return INVALID_OPERATION;
5157 }
5158 } else {
5159 return BAD_VALUE;
5160 }
5161 } else {
5162 return BAD_VALUE;
5163 }
5164 return NO_ERROR;
5165}
5166
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005167status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle, uid_t uid)
Eric Laurent6a94d692014-05-20 11:18:06 -07005168{
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005169 ALOGV("%s patch %d", __func__, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005170 ssize_t index = mAudioPatches.indexOfKey(handle);
5171
5172 if (index < 0) {
5173 return BAD_VALUE;
5174 }
5175 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005176 ALOGV("%s() mUidCached %d patchDesc->mUid %d uid %d",
5177 __func__, mUidCached, patchDesc->getUid(), uid);
5178 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005179 return INVALID_OPERATION;
5180 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005181 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
5182 for (size_t i = 0; i < mAudioSources.size(); i++) {
5183 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
5184 if (sourceDesc != nullptr && sourceDesc->getPatchHandle() == handle) {
5185 portId = sourceDesc->portId();
5186 break;
5187 }
5188 }
5189 return portId != AUDIO_PORT_HANDLE_NONE ?
5190 stopAudioSource(portId) : releaseAudioPatchInternal(handle);
François Gaffieafd4cea2019-11-18 15:50:22 +01005191}
Eric Laurent6a94d692014-05-20 11:18:06 -07005192
François Gaffieafd4cea2019-11-18 15:50:22 +01005193status_t AudioPolicyManager::releaseAudioPatchInternal(audio_patch_handle_t handle,
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005194 uint32_t delayMs,
5195 const sp<SourceClientDescriptor>& sourceDesc)
François Gaffieafd4cea2019-11-18 15:50:22 +01005196{
5197 ALOGV("%s patch %d", __func__, handle);
5198 if (mAudioPatches.indexOfKey(handle) < 0) {
5199 ALOGE("%s: no patch found with handle=%d", __func__, handle);
5200 return BAD_VALUE;
5201 }
5202 sp<AudioPatch> patchDesc = mAudioPatches.valueFor(handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005203 struct audio_patch *patch = &patchDesc->mPatch;
François Gaffieafd4cea2019-11-18 15:50:22 +01005204 patchDesc->setUid(mUidCached);
Eric Laurent6a94d692014-05-20 11:18:06 -07005205 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005206 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005207 if (outputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005208 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005209 return BAD_VALUE;
5210 }
5211
François Gaffie11d30102018-11-02 16:09:09 +01005212 setOutputDevices(outputDesc,
5213 getNewOutputDevices(outputDesc, true /*fromCache*/),
5214 true,
5215 0,
5216 NULL);
Eric Laurent6a94d692014-05-20 11:18:06 -07005217 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
5218 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
François Gaffie53615e22015-03-19 09:24:12 +01005219 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005220 if (inputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005221 ALOGV("%s input not found for id %d", __func__, patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005222 return BAD_VALUE;
5223 }
5224 setInputDevice(inputDesc->mIoHandle,
Eric Laurentfb66dd92016-01-28 18:32:03 -08005225 getNewInputDevice(inputDesc),
Eric Laurent6a94d692014-05-20 11:18:06 -07005226 true,
5227 NULL);
5228 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005229 status_t status =
5230 mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
5231 ALOGV("%s patch panel returned %d patchHandle %d",
5232 __func__, status, patchDesc->getAfHandle());
5233 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005234 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005235 mpClientInterface->onAudioPatchListUpdate();
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005236 // SW or HW Bridge
5237 sp<SwAudioOutputDescriptor> outputDesc = nullptr;
5238 audio_patch_handle_t patchHandle = AUDIO_PATCH_HANDLE_NONE;
Francois Gaffie7feb8542020-04-06 17:39:47 +02005239 if (patch->num_sources > 1 && patch->sources[1].type == AUDIO_PORT_TYPE_MIX) {
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005240 outputDesc = mOutputs.getOutputFromId(patch->sources[1].id);
5241 } else if (patch->num_sources == 1 && sourceDesc != nullptr) {
5242 outputDesc = sourceDesc->swOutput().promote();
5243 }
5244 if (outputDesc == nullptr) {
5245 ALOGW("%s no output for id %d", __func__, patch->sources[0].id);
5246 // releaseOutput has already called closeOutput in case of direct output
5247 return NO_ERROR;
5248 }
François Gaffie7e39df22022-04-26 12:48:49 +02005249 patchHandle = outputDesc->getPatchHandle();
5250 // When a Sw bridge is released, the mixer used by this bridge will release its
5251 // patch at AudioFlinger side. Hence, the mixer audio patch must be recreated
5252 // Reuse patch handle to force audio flinger removing initial mixer patch removal
5253 // updating hal patch handle (prevent leaks).
5254 // While using a HwBridge, force reconsidering device only if not reusing an existing
5255 // output and no more activity on output (will force to close).
5256 bool force = sourceDesc->useSwBridge() ||
5257 (sourceDesc->canCloseOutput() && !outputDesc->isActive());
5258 // APM pattern is to have always outputs opened / patch realized for reachable devices.
5259 // Update device may result to NONE (empty), coupled with force, it releases the patch.
5260 // Reconsider device only for cases:
5261 // 1 / Active Output
5262 // 2 / Inactive Output previously hosting HwBridge
5263 // 3 / Inactive Output previously hosting SwBridge that can be closed.
5264 bool updateDevice = outputDesc->isActive() || !sourceDesc->useSwBridge() ||
5265 sourceDesc->canCloseOutput();
5266 setOutputDevices(outputDesc,
5267 updateDevice ? getNewOutputDevices(outputDesc, true /*fromCache*/) :
5268 outputDesc->devices(),
5269 force,
5270 0,
5271 patchHandle == AUDIO_PATCH_HANDLE_NONE ? nullptr : &patchHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005272 } else {
5273 return BAD_VALUE;
5274 }
5275 } else {
5276 return BAD_VALUE;
5277 }
5278 return NO_ERROR;
5279}
5280
5281status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
5282 struct audio_patch *patches,
5283 unsigned int *generation)
5284{
François Gaffie53615e22015-03-19 09:24:12 +01005285 if (generation == NULL) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005286 return BAD_VALUE;
5287 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005288 *generation = curAudioPortGeneration();
François Gaffie53615e22015-03-19 09:24:12 +01005289 return mAudioPatches.listAudioPatches(num_patches, patches);
Eric Laurent6a94d692014-05-20 11:18:06 -07005290}
5291
Eric Laurente1715a42014-05-20 11:30:42 -07005292status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07005293{
Eric Laurente1715a42014-05-20 11:30:42 -07005294 ALOGV("setAudioPortConfig()");
5295
5296 if (config == NULL) {
5297 return BAD_VALUE;
5298 }
5299 ALOGV("setAudioPortConfig() on port handle %d", config->id);
5300 // Only support gain configuration for now
Eric Laurenta121f902014-06-03 13:32:54 -07005301 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
5302 return INVALID_OPERATION;
Eric Laurente1715a42014-05-20 11:30:42 -07005303 }
5304
Eric Laurenta121f902014-06-03 13:32:54 -07005305 sp<AudioPortConfig> audioPortConfig;
Eric Laurente1715a42014-05-20 11:30:42 -07005306 if (config->type == AUDIO_PORT_TYPE_MIX) {
5307 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005308 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07005309 if (outputDesc == NULL) {
5310 return BAD_VALUE;
5311 }
Eric Laurent84c70242014-06-23 08:46:27 -07005312 ALOG_ASSERT(!outputDesc->isDuplicated(),
5313 "setAudioPortConfig() called on duplicated output %d",
5314 outputDesc->mIoHandle);
Eric Laurenta121f902014-06-03 13:32:54 -07005315 audioPortConfig = outputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07005316 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
François Gaffie53615e22015-03-19 09:24:12 +01005317 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07005318 if (inputDesc == NULL) {
5319 return BAD_VALUE;
5320 }
Eric Laurenta121f902014-06-03 13:32:54 -07005321 audioPortConfig = inputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07005322 } else {
5323 return BAD_VALUE;
5324 }
5325 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
5326 sp<DeviceDescriptor> deviceDesc;
5327 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
5328 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
5329 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
5330 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
5331 } else {
5332 return BAD_VALUE;
5333 }
5334 if (deviceDesc == NULL) {
5335 return BAD_VALUE;
5336 }
Eric Laurenta121f902014-06-03 13:32:54 -07005337 audioPortConfig = deviceDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07005338 } else {
5339 return BAD_VALUE;
5340 }
5341
Mikhail Naganov7be71d22018-05-23 16:51:46 -07005342 struct audio_port_config backupConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07005343 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
5344 if (status == NO_ERROR) {
Mikhail Naganov7be71d22018-05-23 16:51:46 -07005345 struct audio_port_config newConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07005346 audioPortConfig->toAudioPortConfig(&newConfig, config);
5347 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
Eric Laurente1715a42014-05-20 11:30:42 -07005348 }
Eric Laurenta121f902014-06-03 13:32:54 -07005349 if (status != NO_ERROR) {
5350 audioPortConfig->applyAudioPortConfig(&backupConfig);
Eric Laurente1715a42014-05-20 11:30:42 -07005351 }
Eric Laurente1715a42014-05-20 11:30:42 -07005352
5353 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07005354}
5355
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005356void AudioPolicyManager::releaseResourcesForUid(uid_t uid)
5357{
Eric Laurentd60560a2015-04-10 11:31:20 -07005358 clearAudioSources(uid);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005359 clearAudioPatches(uid);
5360 clearSessionRoutes(uid);
5361}
5362
Eric Laurent6a94d692014-05-20 11:18:06 -07005363void AudioPolicyManager::clearAudioPatches(uid_t uid)
5364{
Eric Laurent0add0fd2014-12-04 18:58:14 -08005365 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005366 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
François Gaffieafd4cea2019-11-18 15:50:22 +01005367 if (patchDesc->getUid() == uid) {
Eric Laurent0add0fd2014-12-04 18:58:14 -08005368 releaseAudioPatch(mAudioPatches.keyAt(i), uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07005369 }
5370 }
5371}
5372
François Gaffiec005e562018-11-06 15:04:49 +01005373void AudioPolicyManager::checkStrategyRoute(product_strategy_t ps, audio_io_handle_t ouptutToSkip)
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005374{
François Gaffiec005e562018-11-06 15:04:49 +01005375 // Take the first attributes following the product strategy as it is used to retrieve the routed
5376 // device. All attributes wihin a strategy follows the same "routing strategy"
5377 auto attributes = mEngine->getAllAttributesForProductStrategy(ps).front();
5378 DeviceVector devices = mEngine->getOutputDevicesForAttributes(attributes, nullptr, false);
François Gaffie11d30102018-11-02 16:09:09 +01005379 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
jiabin3ff8d7d2022-12-13 06:27:44 +00005380 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005381 for (size_t j = 0; j < mOutputs.size(); j++) {
5382 if (mOutputs.keyAt(j) == ouptutToSkip) {
5383 continue;
5384 }
5385 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(j);
François Gaffiec005e562018-11-06 15:04:49 +01005386 if (!outputDesc->isStrategyActive(ps)) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005387 continue;
5388 }
5389 // If the default device for this strategy is on another output mix,
5390 // invalidate all tracks in this strategy to force re connection.
5391 // Otherwise select new device on the output mix.
5392 if (outputs.indexOf(mOutputs.keyAt(j)) < 0) {
jiabinc44b3462022-12-08 12:52:31 -08005393 invalidateStreams(mEngine->getStreamTypesForProductStrategy(ps));
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005394 } else {
jiabin3ff8d7d2022-12-13 06:27:44 +00005395 DeviceVector newDevices = getNewOutputDevices(outputDesc, false /*fromCache*/);
5396 if (outputDesc->mUsePreferredMixerAttributes && outputDesc->devices() != newDevices) {
5397 // If the device is using preferred mixer attributes, the output need to reopen
5398 // with default configuration when the new selected devices are different from
5399 // current routing devices.
5400 outputsToReopen.emplace(mOutputs.keyAt(j), newDevices);
5401 continue;
5402 }
5403 setOutputDevices(outputDesc, newDevices, false);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005404 }
5405 }
jiabin3ff8d7d2022-12-13 06:27:44 +00005406 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005407}
5408
5409void AudioPolicyManager::clearSessionRoutes(uid_t uid)
5410{
5411 // remove output routes associated with this uid
François Gaffiec005e562018-11-06 15:04:49 +01005412 std::vector<product_strategy_t> affectedStrategies;
Eric Laurent97ac8712018-07-27 18:59:02 -07005413 for (size_t i = 0; i < mOutputs.size(); i++) {
5414 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07005415 for (const auto& client : outputDesc->getClientIterable()) {
5416 if (client->hasPreferredDevice() && client->uid() == uid) {
5417 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
François Gaffiec005e562018-11-06 15:04:49 +01005418 auto clientStrategy = client->strategy();
5419 if (std::find(begin(affectedStrategies), end(affectedStrategies), clientStrategy) !=
5420 end(affectedStrategies)) {
5421 continue;
5422 }
5423 affectedStrategies.push_back(client->strategy());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005424 }
5425 }
5426 }
5427 // reroute outputs if necessary
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005428 for (const auto& strategy : affectedStrategies) {
5429 checkStrategyRoute(strategy, AUDIO_IO_HANDLE_NONE);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005430 }
5431
5432 // remove input routes associated with this uid
5433 SortedVector<audio_source_t> affectedSources;
Eric Laurent97ac8712018-07-27 18:59:02 -07005434 for (size_t i = 0; i < mInputs.size(); i++) {
5435 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07005436 for (const auto& client : inputDesc->getClientIterable()) {
5437 if (client->hasPreferredDevice() && client->uid() == uid) {
5438 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
5439 affectedSources.add(client->source());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005440 }
5441 }
5442 }
5443 // reroute inputs if necessary
5444 SortedVector<audio_io_handle_t> inputsToClose;
5445 for (size_t i = 0; i < mInputs.size(); i++) {
5446 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Eric Laurent4eb58f12018-12-07 16:41:02 -08005447 if (affectedSources.indexOf(inputDesc->source()) >= 0) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005448 inputsToClose.add(inputDesc->mIoHandle);
5449 }
5450 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005451 for (const auto& input : inputsToClose) {
5452 closeInput(input);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005453 }
5454}
5455
Eric Laurentd60560a2015-04-10 11:31:20 -07005456void AudioPolicyManager::clearAudioSources(uid_t uid)
5457{
5458 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005459 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
5460 if (sourceDesc->uid() == uid) {
Eric Laurentd60560a2015-04-10 11:31:20 -07005461 stopAudioSource(mAudioSources.keyAt(i));
5462 }
5463 }
5464}
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005465
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005466status_t AudioPolicyManager::acquireSoundTriggerSession(audio_session_t *session,
5467 audio_io_handle_t *ioHandle,
5468 audio_devices_t *device)
5469{
Glenn Kastenf0c6d7d2016-02-26 10:44:04 -08005470 *session = (audio_session_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
5471 *ioHandle = (audio_io_handle_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
Francois Gaffie716e1432019-01-14 16:58:59 +01005472 audio_attributes_t attr = { .source = AUDIO_SOURCE_HOTWORD };
Eric Laurentcedd5b52023-03-22 00:03:31 +00005473 sp<DeviceDescriptor> deviceDesc = mEngine->getInputDeviceForAttributes(attr);
5474 if (deviceDesc == nullptr) {
5475 return INVALID_OPERATION;
5476 }
5477 *device = deviceDesc->type();
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005478
François Gaffiedf372692015-03-19 10:43:27 +01005479 return mSoundTriggerSessions.acquireSession(*session, *ioHandle);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005480}
5481
Eric Laurentd60560a2015-04-10 11:31:20 -07005482status_t AudioPolicyManager::startAudioSource(const struct audio_port_config *source,
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005483 const audio_attributes_t *attributes,
5484 audio_port_handle_t *portId,
5485 uid_t uid)
Eric Laurent554a2772015-04-10 11:29:24 -07005486{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005487 ALOGV("%s", __FUNCTION__);
5488 *portId = AUDIO_PORT_HANDLE_NONE;
5489
5490 if (source == NULL || attributes == NULL || portId == NULL) {
5491 ALOGW("%s invalid argument: source %p attributes %p handle %p",
5492 __FUNCTION__, source, attributes, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005493 return BAD_VALUE;
5494 }
5495
Eric Laurentd60560a2015-04-10 11:31:20 -07005496 if (source->role != AUDIO_PORT_ROLE_SOURCE ||
5497 source->type != AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005498 ALOGW("%s INVALID_OPERATION source->role %d source->type %d",
5499 __FUNCTION__, source->role, source->type);
Eric Laurentd60560a2015-04-10 11:31:20 -07005500 return INVALID_OPERATION;
5501 }
5502
François Gaffie11d30102018-11-02 16:09:09 +01005503 sp<DeviceDescriptor> srcDevice =
Eric Laurentd60560a2015-04-10 11:31:20 -07005504 mAvailableInputDevices.getDevice(source->ext.device.type,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005505 String8(source->ext.device.address),
5506 AUDIO_FORMAT_DEFAULT);
François Gaffie11d30102018-11-02 16:09:09 +01005507 if (srcDevice == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005508 ALOGW("%s source->ext.device.type %08x not found", __FUNCTION__, source->ext.device.type);
Eric Laurentd60560a2015-04-10 11:31:20 -07005509 return BAD_VALUE;
5510 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005511
jiabin4ef93452019-09-10 14:29:54 -07005512 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurentd60560a2015-04-10 11:31:20 -07005513
François Gaffieaaac0fd2018-11-22 17:56:39 +01005514 sp<SourceClientDescriptor> sourceDesc =
François Gaffieafd4cea2019-11-18 15:50:22 +01005515 new SourceClientDescriptor(*portId, uid, *attributes, *source, srcDevice,
François Gaffieaaac0fd2018-11-22 17:56:39 +01005516 mEngine->getStreamTypeForAttributes(*attributes),
5517 mEngine->getProductStrategyForAttributes(*attributes),
5518 toVolumeSource(*attributes));
Eric Laurentd60560a2015-04-10 11:31:20 -07005519
5520 status_t status = connectAudioSource(sourceDesc);
5521 if (status == NO_ERROR) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005522 mAudioSources.add(*portId, sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07005523 }
5524 return status;
5525}
5526
Francois Gaffie601801d2021-06-22 13:27:39 +02005527sp<SourceClientDescriptor> AudioPolicyManager::startAudioSourceInternal(
5528 const struct audio_port_config *source, const audio_attributes_t *attributes, uid_t uid)
5529{
5530 ALOGV("%s", __FUNCTION__);
5531 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
5532
5533 status_t status = startAudioSource(source, attributes, &portId, uid);
5534 ALOGE_IF(status != OK, "%s: failed to start audio source (%d)", __func__, status);
5535 return mAudioSources.valueFor(portId);
5536}
5537
5538
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005539status_t AudioPolicyManager::connectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07005540{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005541 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->portId());
Eric Laurentd60560a2015-04-10 11:31:20 -07005542
5543 // make sure we only have one patch per source.
5544 disconnectAudioSource(sourceDesc);
5545
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005546 audio_attributes_t attributes = sourceDesc->attributes();
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005547 // May the device (dynamic) have been disconnected/reconnected, id has changed.
5548 sp<DeviceDescriptor> srcDevice = mAvailableInputDevices.getDevice(
5549 sourceDesc->srcDevice()->type(),
5550 String8(sourceDesc->srcDevice()->address().c_str()),
5551 AUDIO_FORMAT_DEFAULT);
François Gaffiec005e562018-11-06 15:04:49 +01005552 DeviceVector sinkDevices =
Francois Gaffieff1eb522020-05-06 18:37:04 +02005553 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false /*fromCache*/);
François Gaffiec005e562018-11-06 15:04:49 +01005554 ALOG_ASSERT(!sinkDevices.isEmpty(), "connectAudioSource(): no device found for attributes");
François Gaffie11d30102018-11-02 16:09:09 +01005555 sp<DeviceDescriptor> sinkDevice = sinkDevices.itemAt(0);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005556 if (!mAvailableOutputDevices.contains(sinkDevice)) {
5557 ALOGE("%s Device %s not available", __func__, sinkDevice->toString().c_str());
5558 return INVALID_OPERATION;
5559 }
François Gaffieafd4cea2019-11-18 15:50:22 +01005560 PatchBuilder patchBuilder;
5561 patchBuilder.addSink(sinkDevice).addSource(srcDevice);
5562 audio_patch_handle_t handle = AUDIO_PATCH_HANDLE_NONE;
François Gaffieafd4cea2019-11-18 15:50:22 +01005563
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005564 return connectAudioSourceToSink(
5565 sourceDesc, sinkDevice, patchBuilder.patch(), handle, mUidCached, 0 /*delayMs*/);
Eric Laurent554a2772015-04-10 11:29:24 -07005566}
5567
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005568status_t AudioPolicyManager::stopAudioSource(audio_port_handle_t portId)
Eric Laurent554a2772015-04-10 11:29:24 -07005569{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005570 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueFor(portId);
5571 ALOGV("%s port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005572 if (sourceDesc == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005573 ALOGW("%s unknown source for port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005574 return BAD_VALUE;
5575 }
5576 status_t status = disconnectAudioSource(sourceDesc);
5577
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005578 mAudioSources.removeItem(portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005579 return status;
5580}
5581
Andy Hung2ddee192015-12-18 17:34:44 -08005582status_t AudioPolicyManager::setMasterMono(bool mono)
5583{
5584 if (mMasterMono == mono) {
5585 return NO_ERROR;
5586 }
5587 mMasterMono = mono;
5588 // if enabling mono we close all offloaded devices, which will invalidate the
5589 // corresponding AudioTrack. The AudioTrack client/MediaPlayer is responsible
5590 // for recreating the new AudioTrack as non-offloaded PCM.
5591 //
5592 // If disabling mono, we leave all tracks as is: we don't know which clients
5593 // and tracks are able to be recreated as offloaded. The next "song" should
5594 // play back offloaded.
5595 if (mMasterMono) {
5596 Vector<audio_io_handle_t> offloaded;
5597 for (size_t i = 0; i < mOutputs.size(); ++i) {
5598 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
5599 if (desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
5600 offloaded.push(desc->mIoHandle);
5601 }
5602 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005603 for (const auto& handle : offloaded) {
5604 closeOutput(handle);
Andy Hung2ddee192015-12-18 17:34:44 -08005605 }
5606 }
5607 // update master mono for all remaining outputs
5608 for (size_t i = 0; i < mOutputs.size(); ++i) {
5609 updateMono(mOutputs.keyAt(i));
5610 }
5611 return NO_ERROR;
5612}
5613
5614status_t AudioPolicyManager::getMasterMono(bool *mono)
5615{
5616 *mono = mMasterMono;
5617 return NO_ERROR;
5618}
5619
Eric Laurentac9cef52017-06-09 15:46:26 -07005620float AudioPolicyManager::getStreamVolumeDB(
5621 audio_stream_type_t stream, int index, audio_devices_t device)
5622{
jiabin9a3361e2019-10-01 09:38:30 -07005623 return computeVolume(getVolumeCurves(stream), toVolumeSource(stream), index, {device});
Eric Laurentac9cef52017-06-09 15:46:26 -07005624}
5625
jiabin81772902018-04-02 17:52:27 -07005626status_t AudioPolicyManager::getSurroundFormats(unsigned int *numSurroundFormats,
5627 audio_format_t *surroundFormats,
Kriti Dang6537def2021-03-02 13:46:59 +01005628 bool *surroundFormatsEnabled)
jiabin81772902018-04-02 17:52:27 -07005629{
Kriti Dang6537def2021-03-02 13:46:59 +01005630 if (numSurroundFormats == nullptr || (*numSurroundFormats != 0 &&
5631 (surroundFormats == nullptr || surroundFormatsEnabled == nullptr))) {
jiabin81772902018-04-02 17:52:27 -07005632 return BAD_VALUE;
5633 }
Kriti Dang6537def2021-03-02 13:46:59 +01005634 ALOGV("%s() numSurroundFormats %d surroundFormats %p surroundFormatsEnabled %p",
5635 __func__, *numSurroundFormats, surroundFormats, surroundFormatsEnabled);
jiabin81772902018-04-02 17:52:27 -07005636
5637 size_t formatsWritten = 0;
5638 size_t formatsMax = *numSurroundFormats;
Kriti Dangef6be8f2020-11-05 11:58:19 +01005639
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005640 *numSurroundFormats = mConfig->getSurroundFormats().size();
Mikhail Naganov100f0122018-11-29 11:22:16 -08005641 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
5642 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005643 for (const auto& format: mConfig->getSurroundFormats()) {
jiabin81772902018-04-02 17:52:27 -07005644 if (formatsWritten < formatsMax) {
Kriti Dang6537def2021-03-02 13:46:59 +01005645 surroundFormats[formatsWritten] = format.first;
Mikhail Naganov100f0122018-11-29 11:22:16 -08005646 bool formatEnabled = true;
5647 switch (forceUse) {
5648 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL:
Kriti Dang6537def2021-03-02 13:46:59 +01005649 formatEnabled = mManualSurroundFormats.count(format.first) != 0;
Mikhail Naganov100f0122018-11-29 11:22:16 -08005650 break;
5651 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER:
5652 formatEnabled = false;
5653 break;
5654 default: // AUTO or ALWAYS => true
5655 break;
jiabin81772902018-04-02 17:52:27 -07005656 }
5657 surroundFormatsEnabled[formatsWritten++] = formatEnabled;
5658 }
jiabin81772902018-04-02 17:52:27 -07005659 }
5660 return NO_ERROR;
5661}
5662
Kriti Dang6537def2021-03-02 13:46:59 +01005663status_t AudioPolicyManager::getReportedSurroundFormats(unsigned int *numSurroundFormats,
5664 audio_format_t *surroundFormats) {
5665 if (numSurroundFormats == nullptr || (*numSurroundFormats != 0 && surroundFormats == nullptr)) {
5666 return BAD_VALUE;
5667 }
5668 ALOGV("%s() numSurroundFormats %d surroundFormats %p",
5669 __func__, *numSurroundFormats, surroundFormats);
5670
5671 size_t formatsWritten = 0;
5672 size_t formatsMax = *numSurroundFormats;
5673 std::unordered_set<audio_format_t> formats; // Uses primary surround formats only
5674
5675 // Return formats from all device profiles that have already been resolved by
5676 // checkOutputsForDevice().
5677 for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
5678 sp<DeviceDescriptor> device = mAvailableOutputDevices[i];
5679 audio_devices_t deviceType = device->type();
5680 // Enabling/disabling formats are applied to only HDMI devices. So, this function
5681 // returns formats reported by HDMI devices.
5682 if (deviceType != AUDIO_DEVICE_OUT_HDMI) {
5683 continue;
5684 }
5685 // Formats reported by sink devices
5686 std::unordered_set<audio_format_t> formatset;
5687 if (auto it = mReportedFormatsMap.find(device); it != mReportedFormatsMap.end()) {
5688 formatset.insert(it->second.begin(), it->second.end());
5689 }
5690
5691 // Formats hard-coded in the in policy configuration file (if any).
5692 FormatVector encodedFormats = device->encodedFormats();
5693 formatset.insert(encodedFormats.begin(), encodedFormats.end());
5694 // Filter the formats which are supported by the vendor hardware.
5695 for (auto it = formatset.begin(); it != formatset.end(); ++it) {
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005696 if (mConfig->getSurroundFormats().count(*it) != 0) {
Kriti Dang6537def2021-03-02 13:46:59 +01005697 formats.insert(*it);
5698 } else {
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005699 for (const auto& pair : mConfig->getSurroundFormats()) {
Kriti Dang6537def2021-03-02 13:46:59 +01005700 if (pair.second.count(*it) != 0) {
5701 formats.insert(pair.first);
5702 break;
5703 }
5704 }
5705 }
5706 }
5707 }
5708 *numSurroundFormats = formats.size();
5709 for (const auto& format: formats) {
5710 if (formatsWritten < formatsMax) {
5711 surroundFormats[formatsWritten++] = format;
5712 }
5713 }
5714 return NO_ERROR;
5715}
5716
jiabin81772902018-04-02 17:52:27 -07005717status_t AudioPolicyManager::setSurroundFormatEnabled(audio_format_t audioFormat, bool enabled)
5718{
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005719 ALOGV("%s() format 0x%X enabled %d", __func__, audioFormat, enabled);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005720 const auto& formatIter = mConfig->getSurroundFormats().find(audioFormat);
5721 if (formatIter == mConfig->getSurroundFormats().end()) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005722 ALOGW("%s() format 0x%X is not a known surround format", __func__, audioFormat);
jiabin81772902018-04-02 17:52:27 -07005723 return BAD_VALUE;
5724 }
5725
Mikhail Naganov100f0122018-11-29 11:22:16 -08005726 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND) !=
5727 AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005728 ALOGW("%s() not in manual mode for surround sound format selection", __func__);
jiabin81772902018-04-02 17:52:27 -07005729 return INVALID_OPERATION;
5730 }
5731
Mikhail Naganov100f0122018-11-29 11:22:16 -08005732 if ((mManualSurroundFormats.count(audioFormat) != 0) == enabled) {
jiabin81772902018-04-02 17:52:27 -07005733 return NO_ERROR;
5734 }
5735
Mikhail Naganov100f0122018-11-29 11:22:16 -08005736 std::unordered_set<audio_format_t> surroundFormatsBackup(mManualSurroundFormats);
jiabin81772902018-04-02 17:52:27 -07005737 if (enabled) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005738 mManualSurroundFormats.insert(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07005739 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005740 mManualSurroundFormats.insert(subFormat);
jiabin81772902018-04-02 17:52:27 -07005741 }
5742 } else {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005743 mManualSurroundFormats.erase(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07005744 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005745 mManualSurroundFormats.erase(subFormat);
jiabin81772902018-04-02 17:52:27 -07005746 }
5747 }
5748
5749 sp<SwAudioOutputDescriptor> outputDesc;
5750 bool profileUpdated = false;
jiabin9a3361e2019-10-01 09:38:30 -07005751 DeviceVector hdmiOutputDevices = mAvailableOutputDevices.getDevicesFromType(
5752 AUDIO_DEVICE_OUT_HDMI);
jiabin81772902018-04-02 17:52:27 -07005753 for (size_t i = 0; i < hdmiOutputDevices.size(); i++) {
5754 // Simulate reconnection to update enabled surround sound formats.
jiabince9f20e2019-09-12 16:29:15 -07005755 String8 address = String8(hdmiOutputDevices[i]->address().c_str());
jiabin5740f082019-08-19 15:08:30 -07005756 std::string name = hdmiOutputDevices[i]->getName();
jiabin81772902018-04-02 17:52:27 -07005757 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
5758 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
5759 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005760 name.c_str(),
5761 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005762 if (status != NO_ERROR) {
5763 continue;
5764 }
5765 status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
5766 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
5767 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005768 name.c_str(),
5769 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005770 profileUpdated |= (status == NO_ERROR);
5771 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08005772 // FIXME: Why doing this for input HDMI devices if we don't augment their reported formats?
jiabin9a3361e2019-10-01 09:38:30 -07005773 DeviceVector hdmiInputDevices = mAvailableInputDevices.getDevicesFromType(
jiabin81772902018-04-02 17:52:27 -07005774 AUDIO_DEVICE_IN_HDMI);
5775 for (size_t i = 0; i < hdmiInputDevices.size(); i++) {
5776 // Simulate reconnection to update enabled surround sound formats.
jiabince9f20e2019-09-12 16:29:15 -07005777 String8 address = String8(hdmiInputDevices[i]->address().c_str());
jiabin5740f082019-08-19 15:08:30 -07005778 std::string name = hdmiInputDevices[i]->getName();
jiabin81772902018-04-02 17:52:27 -07005779 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
5780 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
5781 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005782 name.c_str(),
5783 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005784 if (status != NO_ERROR) {
5785 continue;
5786 }
5787 status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
5788 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
5789 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005790 name.c_str(),
5791 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005792 profileUpdated |= (status == NO_ERROR);
5793 }
5794
jiabin81772902018-04-02 17:52:27 -07005795 if (!profileUpdated) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005796 ALOGW("%s() no audio profiles updated, undoing surround formats change", __func__);
Mikhail Naganov100f0122018-11-29 11:22:16 -08005797 mManualSurroundFormats = std::move(surroundFormatsBackup);
jiabin81772902018-04-02 17:52:27 -07005798 }
5799
5800 return profileUpdated ? NO_ERROR : INVALID_OPERATION;
5801}
5802
Eric Laurent5ada82e2019-08-29 17:53:54 -07005803void AudioPolicyManager::setAppState(audio_port_handle_t portId, app_state_t state)
Svet Ganovf4ddfef2018-01-16 07:37:58 -08005804{
Eric Laurent5ada82e2019-08-29 17:53:54 -07005805 ALOGV("%s(portId:%d, state:%d)", __func__, portId, state);
Eric Laurenta9f86652018-11-28 17:23:11 -08005806 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent5ada82e2019-08-29 17:53:54 -07005807 mInputs.valueAt(i)->setAppState(portId, state);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08005808 }
5809}
5810
jiabin6012f912018-11-02 17:06:30 -07005811bool AudioPolicyManager::isHapticPlaybackSupported()
5812{
5813 for (const auto& hwModule : mHwModules) {
5814 const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
5815 for (const auto &outProfile : outputProfiles) {
5816 struct audio_port audioPort;
5817 outProfile->toAudioPort(&audioPort);
5818 for (size_t i = 0; i < audioPort.num_channel_masks; i++) {
5819 if (audioPort.channel_masks[i] & AUDIO_CHANNEL_HAPTIC_ALL) {
5820 return true;
5821 }
5822 }
5823 }
5824 }
5825 return false;
5826}
5827
Carter Hsu325a8eb2022-01-19 19:56:51 +08005828bool AudioPolicyManager::isUltrasoundSupported()
5829{
5830 bool hasUltrasoundOutput = false;
5831 bool hasUltrasoundInput = false;
5832 for (const auto& hwModule : mHwModules) {
5833 const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
5834 if (!hasUltrasoundOutput) {
5835 for (const auto &outProfile : outputProfiles) {
5836 if (outProfile->getFlags() & AUDIO_OUTPUT_FLAG_ULTRASOUND) {
5837 hasUltrasoundOutput = true;
5838 break;
5839 }
5840 }
5841 }
5842
5843 const InputProfileCollection &inputProfiles = hwModule->getInputProfiles();
5844 if (!hasUltrasoundInput) {
5845 for (const auto &inputProfile : inputProfiles) {
5846 if (inputProfile->getFlags() & AUDIO_INPUT_FLAG_ULTRASOUND) {
5847 hasUltrasoundInput = true;
5848 break;
5849 }
5850 }
5851 }
5852
5853 if (hasUltrasoundOutput && hasUltrasoundInput)
5854 return true;
5855 }
5856 return false;
5857}
5858
Atneya Nair698f5ef2022-12-15 16:15:09 -08005859bool AudioPolicyManager::isHotwordStreamSupported(bool lookbackAudio)
5860{
5861 const auto mask = AUDIO_INPUT_FLAG_HOTWORD_TAP |
5862 (lookbackAudio ? AUDIO_INPUT_FLAG_HW_LOOKBACK : 0);
5863 for (const auto& hwModule : mHwModules) {
5864 const InputProfileCollection &inputProfiles = hwModule->getInputProfiles();
5865 for (const auto &inputProfile : inputProfiles) {
5866 if ((inputProfile->getFlags() & mask) == mask) {
5867 return true;
5868 }
5869 }
5870 }
5871 return false;
5872}
5873
Eric Laurent8340e672019-11-06 11:01:08 -08005874bool AudioPolicyManager::isCallScreenModeSupported()
5875{
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005876 return mConfig->isCallScreenModeSupported();
Eric Laurent8340e672019-11-06 11:01:08 -08005877}
5878
5879
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005880status_t AudioPolicyManager::disconnectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07005881{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005882 ALOGV("%s port Id %d", __FUNCTION__, sourceDesc->portId());
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005883 if (!sourceDesc->isConnected()) {
5884 ALOGV("%s port Id %d already disconnected", __FUNCTION__, sourceDesc->portId());
5885 return NO_ERROR;
5886 }
François Gaffieafd4cea2019-11-18 15:50:22 +01005887 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
5888 if (swOutput != 0) {
5889 status_t status = stopSource(swOutput, sourceDesc);
Eric Laurent733ce942017-12-07 12:18:25 -08005890 if (status == NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005891 swOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08005892 }
jiabinbce0c1d2020-10-05 11:20:18 -07005893 if (releaseOutput(sourceDesc->portId())) {
5894 // The output descriptor is reopened to query dynamic profiles. In that case, there is
5895 // no need to release audio patch here but just return NO_ERROR.
5896 return NO_ERROR;
5897 }
Eric Laurentd60560a2015-04-10 11:31:20 -07005898 } else {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005899 sp<HwAudioOutputDescriptor> hwOutputDesc = sourceDesc->hwOutput().promote();
Eric Laurentd60560a2015-04-10 11:31:20 -07005900 if (hwOutputDesc != 0) {
Eric Laurentd60560a2015-04-10 11:31:20 -07005901 // close Hwoutput and remove from mHwOutputs
5902 } else {
5903 ALOGW("%s source has neither SW nor HW output", __FUNCTION__);
5904 }
5905 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005906 status_t status = releaseAudioPatchInternal(sourceDesc->getPatchHandle(), 0, sourceDesc);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005907 sourceDesc->disconnect();
5908 return status;
Eric Laurentd60560a2015-04-10 11:31:20 -07005909}
5910
François Gaffiec005e562018-11-06 15:04:49 +01005911sp<SourceClientDescriptor> AudioPolicyManager::getSourceForAttributesOnOutput(
5912 audio_io_handle_t output, const audio_attributes_t &attr)
Eric Laurentd60560a2015-04-10 11:31:20 -07005913{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005914 sp<SourceClientDescriptor> source;
Eric Laurentd60560a2015-04-10 11:31:20 -07005915 for (size_t i = 0; i < mAudioSources.size(); i++) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005916 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005917 sp<SwAudioOutputDescriptor> outputDesc = sourceDesc->swOutput().promote();
François Gaffiec005e562018-11-06 15:04:49 +01005918 if (followsSameRouting(attr, sourceDesc->attributes()) &&
5919 outputDesc != 0 && outputDesc->mIoHandle == output) {
Eric Laurentd60560a2015-04-10 11:31:20 -07005920 source = sourceDesc;
5921 break;
5922 }
5923 }
5924 return source;
Eric Laurent554a2772015-04-10 11:29:24 -07005925}
5926
Eric Laurentb4f42a92022-01-17 17:37:31 +01005927bool AudioPolicyManager::canBeSpatializedInt(const audio_attributes_t *attr,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005928 const audio_config_t *config,
Andy Hung9dd1a5b2022-05-10 15:39:39 -07005929 const AudioDeviceTypeAddrVector &devices) const
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005930{
5931 // The caller can have the audio attributes criteria ignored by either passing a null ptr or
5932 // the AUDIO_ATTRIBUTES_INITIALIZER value.
Eric Laurentfa0f6742021-08-17 18:39:44 +02005933 // If attributes are specified, current policy is to only allow spatialization for media
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005934 // and game usages.
Eric Laurent39095982021-08-24 18:29:27 +02005935 if (attr != nullptr && *attr != AUDIO_ATTRIBUTES_INITIALIZER) {
5936 if (attr->usage != AUDIO_USAGE_MEDIA && attr->usage != AUDIO_USAGE_GAME) {
5937 return false;
5938 }
5939 if ((attr->flags & (AUDIO_FLAG_CONTENT_SPATIALIZED | AUDIO_FLAG_NEVER_SPATIALIZE)) != 0) {
5940 return false;
5941 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005942 }
5943
Eric Laurentd332bc82023-08-04 11:45:23 +02005944 // The caller can have the audio config criteria ignored by either passing a null ptr or
5945 // the AUDIO_CONFIG_INITIALIZER value.
5946 // If an audio config is specified, current policy is to only allow spatialization for
5947 // some positional channel masks and PCM format
5948
5949 if (config != nullptr && *config != AUDIO_CONFIG_INITIALIZER) {
5950 if (!audio_is_channel_mask_spatialized(config->channel_mask)) {
5951 return false;
5952 }
5953 if (!audio_is_linear_pcm(config->format)) {
5954 return false;
5955 }
5956 }
5957
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005958 sp<IOProfile> profile =
Eric Laurent39095982021-08-24 18:29:27 +02005959 getSpatializerOutputProfile(config, devices);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005960 if (profile == nullptr) {
5961 return false;
5962 }
5963
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005964 return true;
5965}
5966
5967void AudioPolicyManager::checkVirtualizerClientRoutes() {
5968 std::set<audio_stream_type_t> streamsToInvalidate;
5969 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent39095982021-08-24 18:29:27 +02005970 const sp<SwAudioOutputDescriptor>& desc = mOutputs[i];
5971 for (const sp<TrackClientDescriptor>& client : desc->getClientIterable()) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005972 audio_attributes_t attr = client->attributes();
5973 DeviceVector devices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false);
5974 AudioDeviceTypeAddrVector devicesTypeAddress = devices.toTypeAddrVector();
5975 audio_config_base_t clientConfig = client->config();
5976 audio_config_t config = audio_config_initializer(&clientConfig);
Eric Laurent39095982021-08-24 18:29:27 +02005977 if (desc != mSpatializerOutput
Andy Hung9dd1a5b2022-05-10 15:39:39 -07005978 && canBeSpatializedInt(&attr, &config, devicesTypeAddress)) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005979 streamsToInvalidate.insert(client->stream());
5980 }
5981 }
5982 }
5983
jiabinc44b3462022-12-08 12:52:31 -08005984 invalidateStreams(StreamTypeVector(streamsToInvalidate.begin(), streamsToInvalidate.end()));
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005985}
5986
Eric Laurente191d1b2022-04-15 11:59:25 +02005987
5988bool AudioPolicyManager::isOutputOnlyAvailableRouteToSomeDevice(
5989 const sp<SwAudioOutputDescriptor>& outputDesc) {
5990 if (outputDesc->isDuplicated()) {
5991 return false;
5992 }
5993 DeviceVector devices = outputDesc->supportedDevices();
5994 for (size_t i = 0; i < mOutputs.size(); i++) {
5995 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
5996 if (desc == outputDesc || desc->isDuplicated()) {
5997 continue;
5998 }
5999 DeviceVector sharedDevices = desc->filterSupportedDevices(devices);
6000 if (!sharedDevices.isEmpty()
6001 && (desc->devicesSupportEncodedFormats(sharedDevices.types())
6002 == outputDesc->devicesSupportEncodedFormats(sharedDevices.types()))) {
6003 return false;
6004 }
6005 }
6006 return true;
6007}
6008
6009
Eric Laurentfa0f6742021-08-17 18:39:44 +02006010status_t AudioPolicyManager::getSpatializerOutput(const audio_config_base_t *mixerConfig,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006011 const audio_attributes_t *attr,
6012 audio_io_handle_t *output) {
6013 *output = AUDIO_IO_HANDLE_NONE;
6014
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006015 DeviceVector devices = mEngine->getOutputDevicesForAttributes(*attr, nullptr, false);
6016 AudioDeviceTypeAddrVector devicesTypeAddress = devices.toTypeAddrVector();
6017 audio_config_t *configPtr = nullptr;
6018 audio_config_t config;
6019 if (mixerConfig != nullptr) {
6020 config = audio_config_initializer(mixerConfig);
6021 configPtr = &config;
6022 }
Andy Hung9dd1a5b2022-05-10 15:39:39 -07006023 if (!canBeSpatializedInt(attr, configPtr, devicesTypeAddress)) {
Eric Laurente191d1b2022-04-15 11:59:25 +02006024 ALOGV("%s provided attributes or mixer config cannot be spatialized", __func__);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006025 return BAD_VALUE;
6026 }
6027
6028 sp<IOProfile> profile =
Eric Laurent39095982021-08-24 18:29:27 +02006029 getSpatializerOutputProfile(configPtr, devicesTypeAddress);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006030 if (profile == nullptr) {
Eric Laurente191d1b2022-04-15 11:59:25 +02006031 ALOGV("%s no suitable output profile for provided attributes or mixer config", __func__);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006032 return BAD_VALUE;
6033 }
6034
Eric Laurente191d1b2022-04-15 11:59:25 +02006035 std::vector<sp<SwAudioOutputDescriptor>> spatializerOutputs;
Eric Laurent39095982021-08-24 18:29:27 +02006036 for (size_t i = 0; i < mOutputs.size(); i++) {
6037 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente191d1b2022-04-15 11:59:25 +02006038 if (!desc->isDuplicated()
6039 && (desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0) {
6040 spatializerOutputs.push_back(desc);
6041 ALOGV("%s adding opened spatializer Output %d", __func__, desc->mIoHandle);
Eric Laurent39095982021-08-24 18:29:27 +02006042 }
6043 }
Eric Laurente191d1b2022-04-15 11:59:25 +02006044 mSpatializerOutput.clear();
6045 bool outputsChanged = false;
6046 for (const auto& desc : spatializerOutputs) {
6047 if (desc->mProfile == profile
6048 && (configPtr == nullptr
6049 || configPtr->channel_mask == desc->mMixerChannelMask)) {
6050 mSpatializerOutput = desc;
6051 ALOGV("%s reusing current spatializer output %d", __func__, desc->mIoHandle);
6052 } else {
6053 ALOGV("%s closing spatializerOutput output %d to match channel mask %#x"
6054 " and devices %s", __func__, desc->mIoHandle,
6055 configPtr != nullptr ? configPtr->channel_mask : 0,
6056 devices.toString().c_str());
6057 closeOutput(desc->mIoHandle);
6058 outputsChanged = true;
6059 }
Eric Laurent39095982021-08-24 18:29:27 +02006060 }
6061
Eric Laurente191d1b2022-04-15 11:59:25 +02006062 if (mSpatializerOutput == nullptr) {
Eric Laurentb4f42a92022-01-17 17:37:31 +01006063 sp<SwAudioOutputDescriptor> desc =
6064 openOutputWithProfileAndDevice(profile, devices, mixerConfig);
Eric Laurente191d1b2022-04-15 11:59:25 +02006065 if (desc != nullptr) {
6066 mSpatializerOutput = desc;
6067 outputsChanged = true;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006068 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006069 }
6070
6071 checkVirtualizerClientRoutes();
6072
Eric Laurente191d1b2022-04-15 11:59:25 +02006073 if (outputsChanged) {
6074 mPreviousOutputs = mOutputs;
6075 mpClientInterface->onAudioPortListUpdate();
6076 }
6077
6078 if (mSpatializerOutput == nullptr) {
6079 ALOGV("%s could not open spatializer output with requested config", __func__);
6080 return BAD_VALUE;
6081 }
Eric Laurent39095982021-08-24 18:29:27 +02006082 *output = mSpatializerOutput->mIoHandle;
Eric Laurente191d1b2022-04-15 11:59:25 +02006083 ALOGV("%s returning new spatializer output %d", __func__, *output);
6084 return OK;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006085}
6086
Eric Laurentfa0f6742021-08-17 18:39:44 +02006087status_t AudioPolicyManager::releaseSpatializerOutput(audio_io_handle_t output) {
6088 if (mSpatializerOutput == nullptr) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006089 return INVALID_OPERATION;
6090 }
Eric Laurentfa0f6742021-08-17 18:39:44 +02006091 if (mSpatializerOutput->mIoHandle != output) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006092 return BAD_VALUE;
6093 }
Eric Laurent39095982021-08-24 18:29:27 +02006094
Eric Laurente191d1b2022-04-15 11:59:25 +02006095 if (!isOutputOnlyAvailableRouteToSomeDevice(mSpatializerOutput)) {
6096 ALOGV("%s closing spatializer output %d", __func__, mSpatializerOutput->mIoHandle);
6097 closeOutput(mSpatializerOutput->mIoHandle);
6098 //from now on mSpatializerOutput is null
6099 checkVirtualizerClientRoutes();
6100 }
Eric Laurent39095982021-08-24 18:29:27 +02006101
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006102 return NO_ERROR;
6103}
6104
Eric Laurente552edb2014-03-10 17:42:56 -07006105// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07006106// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07006107// ----------------------------------------------------------------------------
Eric Laurent6a94d692014-05-20 11:18:06 -07006108uint32_t AudioPolicyManager::nextAudioPortGeneration()
6109{
Mikhail Naganov2773dd72017-12-08 10:12:11 -08006110 return mAudioPortGeneration++;
Eric Laurent6a94d692014-05-20 11:18:06 -07006111}
6112
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006113AudioPolicyManager::AudioPolicyManager(const sp<const AudioPolicyConfig>& config,
Mikhail Naganovf1b6d972023-05-02 13:56:01 -07006114 EngineInstance&& engine,
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006115 AudioPolicyClientInterface *clientInterface)
Eric Laurente552edb2014-03-10 17:42:56 -07006116 :
Andy Hung4ef19fa2018-05-15 19:35:29 -07006117 mUidCached(AID_AUDIOSERVER), // no need to call getuid(), there's only one of us running.
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006118 mConfig(config),
Mikhail Naganovf1b6d972023-05-02 13:56:01 -07006119 mEngine(std::move(engine)),
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006120 mpClientInterface(clientInterface),
Eric Laurente552edb2014-03-10 17:42:56 -07006121 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
Eric Laurent3a4311c2014-03-17 12:00:47 -07006122 mA2dpSuspended(false),
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006123 mAudioPortGeneration(1),
6124 mBeaconMuteRefCount(0),
6125 mBeaconPlayingRefCount(0),
Eric Laurent9459fb02015-08-12 18:36:32 -07006126 mBeaconMuted(false),
Andy Hung2ddee192015-12-18 17:34:44 -08006127 mTtsOutputAvailable(false),
Eric Laurent36829f92017-04-07 19:04:42 -07006128 mMasterMono(false),
Eric Laurent4eb58f12018-12-07 16:41:02 -08006129 mMusicEffectOutput(AUDIO_IO_HANDLE_NONE)
Eric Laurente552edb2014-03-10 17:42:56 -07006130{
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006131}
François Gaffied1ab2bd2015-12-02 18:20:06 +01006132
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006133status_t AudioPolicyManager::initialize() {
Mikhail Naganovf1b6d972023-05-02 13:56:01 -07006134 if (mEngine == nullptr) {
6135 return NO_INIT;
François Gaffie2110e042015-03-24 08:41:51 +01006136 }
6137 mEngine->setObserver(this);
6138 status_t status = mEngine->initCheck();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006139 if (status != NO_ERROR) {
6140 LOG_FATAL("Policy engine not initialized(err=%d)", status);
6141 return status;
6142 }
François Gaffie2110e042015-03-24 08:41:51 +01006143
jiabin29230182023-04-04 21:02:36 +00006144 // The actual device selection cache will be updated when calling `updateDevicesAndOutputs`
6145 // at the end of this function.
6146 mEngine->initializeDeviceSelectionCache();
Eric Laurent1d69c872021-01-11 18:53:01 +01006147 mCommunnicationStrategy = mEngine->getProductStrategyForAttributes(
6148 mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL));
6149
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006150 // after parsing the config, mConfig contain all known devices;
Eric Laurente552edb2014-03-10 17:42:56 -07006151 // open all output streams needed to access attached devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006152 onNewAudioModulesAvailableInt(nullptr /*newDevices*/);
François Gaffie11d30102018-11-02 16:09:09 +01006153
Eric Laurent3a4311c2014-03-17 12:00:47 -07006154 // make sure default device is reachable
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006155 if (const auto defaultOutputDevice = mConfig->getDefaultOutputDevice();
6156 defaultOutputDevice == nullptr ||
6157 !mAvailableOutputDevices.contains(defaultOutputDevice)) {
6158 ALOGE_IF(defaultOutputDevice != nullptr, "Default device %s is unreachable",
6159 defaultOutputDevice->toString().c_str());
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006160 status = NO_INIT;
Eric Laurent3a4311c2014-03-17 12:00:47 -07006161 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02006162 ALOGW_IF(mPrimaryOutput == nullptr, "The policy configuration does not declare a primary output");
Eric Laurente552edb2014-03-10 17:42:56 -07006163
Tomoharu Kasahara71c90912018-10-31 09:10:12 +09006164 // Silence ALOGV statements
6165 property_set("log.tag." LOG_TAG, "D");
6166
Eric Laurente552edb2014-03-10 17:42:56 -07006167 updateDevicesAndOutputs();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006168 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07006169}
6170
Eric Laurente0720872014-03-11 09:30:41 -07006171AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07006172{
Eric Laurente552edb2014-03-10 17:42:56 -07006173 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08006174 mOutputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07006175 }
6176 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08006177 mInputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07006178 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07006179 mAvailableOutputDevices.clear();
6180 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07006181 mOutputs.clear();
6182 mInputs.clear();
6183 mHwModules.clear();
Mikhail Naganov100f0122018-11-29 11:22:16 -08006184 mManualSurroundFormats.clear();
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006185 mConfig.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07006186}
6187
Eric Laurente0720872014-03-11 09:30:41 -07006188status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07006189{
Eric Laurent87ffa392015-05-22 10:32:38 -07006190 return hasPrimaryOutput() ? NO_ERROR : NO_INIT;
Eric Laurente552edb2014-03-10 17:42:56 -07006191}
6192
Eric Laurente552edb2014-03-10 17:42:56 -07006193// ---
6194
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006195void AudioPolicyManager::onNewAudioModulesAvailable()
6196{
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006197 DeviceVector newDevices;
6198 onNewAudioModulesAvailableInt(&newDevices);
6199 if (!newDevices.empty()) {
6200 nextAudioPortGeneration();
6201 mpClientInterface->onAudioPortListUpdate();
6202 }
6203}
6204
6205void AudioPolicyManager::onNewAudioModulesAvailableInt(DeviceVector *newDevices)
6206{
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006207 for (const auto& hwModule : mConfig->getHwModules()) {
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006208 if (std::find(mHwModules.begin(), mHwModules.end(), hwModule) != mHwModules.end()) {
6209 continue;
6210 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006211 if (hwModule->getHandle() == AUDIO_MODULE_HANDLE_NONE) {
Mikhail Naganovffd97712023-05-03 17:45:36 -07006212 if (audio_module_handle_t handle = mpClientInterface->loadHwModule(hwModule->getName());
6213 handle != AUDIO_MODULE_HANDLE_NONE) {
6214 hwModule->setHandle(handle);
6215 } else {
6216 ALOGW("could not load HW module %s", hwModule->getName());
6217 continue;
6218 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006219 }
6220 mHwModules.push_back(hwModule);
Dean Wheatley12a87132021-04-16 10:08:49 +10006221 // open all output streams needed to access attached devices.
6222 // direct outputs are closed immediately after checking the availability of attached devices
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006223 // This also validates mAvailableOutputDevices list
6224 for (const auto& outProfile : hwModule->getOutputProfiles()) {
6225 if (!outProfile->canOpenNewIo()) {
6226 ALOGE("Invalid Output profile max open count %u for profile %s",
6227 outProfile->maxOpenCount, outProfile->getTagName().c_str());
6228 continue;
6229 }
6230 if (!outProfile->hasSupportedDevices()) {
6231 ALOGW("Output profile contains no device on module %s", hwModule->getName());
6232 continue;
6233 }
Carter Hsu1a3364a2022-01-21 15:32:56 +08006234 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_TTS) != 0 ||
6235 (outProfile->getFlags() & AUDIO_OUTPUT_FLAG_ULTRASOUND) != 0) {
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006236 mTtsOutputAvailable = true;
6237 }
6238
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006239 const DeviceVector &supportedDevices = outProfile->getSupportedDevices();
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006240 DeviceVector availProfileDevices = supportedDevices.filter(mConfig->getOutputDevices());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006241 sp<DeviceDescriptor> supportedDevice = 0;
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006242 if (supportedDevices.contains(mConfig->getDefaultOutputDevice())) {
6243 supportedDevice = mConfig->getDefaultOutputDevice();
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006244 } else {
6245 // choose first device present in profile's SupportedDevices also part of
6246 // mAvailableOutputDevices.
6247 if (availProfileDevices.isEmpty()) {
6248 continue;
6249 }
6250 supportedDevice = availProfileDevices.itemAt(0);
6251 }
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006252 if (!mConfig->getOutputDevices().contains(supportedDevice)) {
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006253 continue;
6254 }
6255 sp<SwAudioOutputDescriptor> outputDesc = new SwAudioOutputDescriptor(outProfile,
6256 mpClientInterface);
6257 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentf1f22e72021-07-13 14:04:14 +02006258 status_t status = outputDesc->open(nullptr /* halConfig */, nullptr /* mixerConfig */,
6259 DeviceVector(supportedDevice),
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006260 AUDIO_STREAM_DEFAULT,
6261 AUDIO_OUTPUT_FLAG_NONE, &output);
6262 if (status != NO_ERROR) {
6263 ALOGW("Cannot open output stream for devices %s on hw module %s",
6264 supportedDevice->toString().c_str(), hwModule->getName());
6265 continue;
6266 }
6267 for (const auto &device : availProfileDevices) {
6268 // give a valid ID to an attached device once confirmed it is reachable
6269 if (!device->isAttached()) {
6270 device->attach(hwModule);
6271 mAvailableOutputDevices.add(device);
jiabin1c4794b2020-05-05 10:08:05 -07006272 device->setEncapsulationInfoFromHal(mpClientInterface);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006273 if (newDevices) newDevices->add(device);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006274 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
6275 }
6276 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02006277 if (mPrimaryOutput == nullptr &&
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006278 outProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
6279 mPrimaryOutput = outputDesc;
6280 }
Eric Laurent39095982021-08-24 18:29:27 +02006281 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
Eric Laurentc529cf62020-04-17 18:19:10 -07006282 outputDesc->close();
6283 } else {
6284 addOutput(output, outputDesc);
6285 setOutputDevices(outputDesc,
6286 DeviceVector(supportedDevice),
6287 true,
6288 0,
6289 NULL);
6290 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006291 }
6292 // open input streams needed to access attached devices to validate
6293 // mAvailableInputDevices list
6294 for (const auto& inProfile : hwModule->getInputProfiles()) {
6295 if (!inProfile->canOpenNewIo()) {
6296 ALOGE("Invalid Input profile max open count %u for profile %s",
6297 inProfile->maxOpenCount, inProfile->getTagName().c_str());
6298 continue;
6299 }
6300 if (!inProfile->hasSupportedDevices()) {
6301 ALOGW("Input profile contains no device on module %s", hwModule->getName());
6302 continue;
6303 }
6304 // chose first device present in profile's SupportedDevices also part of
6305 // available input devices
6306 const DeviceVector &supportedDevices = inProfile->getSupportedDevices();
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006307 DeviceVector availProfileDevices = supportedDevices.filter(mConfig->getInputDevices());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006308 if (availProfileDevices.isEmpty()) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01006309 ALOGV("%s: Input device list is empty! for profile %s",
6310 __func__, inProfile->getTagName().c_str());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006311 continue;
6312 }
6313 sp<AudioInputDescriptor> inputDesc =
6314 new AudioInputDescriptor(inProfile, mpClientInterface);
6315
6316 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
6317 status_t status = inputDesc->open(nullptr,
6318 availProfileDevices.itemAt(0),
6319 AUDIO_SOURCE_MIC,
6320 AUDIO_INPUT_FLAG_NONE,
6321 &input);
6322 if (status != NO_ERROR) {
6323 ALOGW("Cannot open input stream for device %s on hw module %s",
6324 availProfileDevices.toString().c_str(),
6325 hwModule->getName());
6326 continue;
6327 }
6328 for (const auto &device : availProfileDevices) {
6329 // give a valid ID to an attached device once confirmed it is reachable
6330 if (!device->isAttached()) {
6331 device->attach(hwModule);
6332 device->importAudioPortAndPickAudioProfile(inProfile, true);
6333 mAvailableInputDevices.add(device);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006334 if (newDevices) newDevices->add(device);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006335 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
6336 }
6337 }
6338 inputDesc->close();
6339 }
6340 }
Eric Laurente191d1b2022-04-15 11:59:25 +02006341
6342 // Check if spatializer outputs can be closed until used.
6343 // mOutputs vector never contains duplicated outputs at this point.
6344 std::vector<audio_io_handle_t> outputsClosed;
6345 for (size_t i = 0; i < mOutputs.size(); i++) {
6346 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
6347 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0
6348 && !isOutputOnlyAvailableRouteToSomeDevice(desc)) {
6349 outputsClosed.push_back(desc->mIoHandle);
6350 desc->close();
6351 }
6352 }
6353 for (auto output : outputsClosed) {
6354 removeOutput(output);
6355 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006356}
6357
Eric Laurent98e38192018-02-15 18:31:53 -08006358void AudioPolicyManager::addOutput(audio_io_handle_t output,
6359 const sp<SwAudioOutputDescriptor>& outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07006360{
Eric Laurent1c333e22014-05-20 10:48:17 -07006361 mOutputs.add(output, outputDesc);
jiabin9a3361e2019-10-01 09:38:30 -07006362 applyStreamVolumes(outputDesc, DeviceTypeSet(), 0 /* delayMs */, true /* force */);
Andy Hung2ddee192015-12-18 17:34:44 -08006363 updateMono(output); // update mono status when adding to output list
Eric Laurent36829f92017-04-07 19:04:42 -07006364 selectOutputForMusicEffects();
Eric Laurent6a94d692014-05-20 11:18:06 -07006365 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07006366}
6367
François Gaffie53615e22015-03-19 09:24:12 +01006368void AudioPolicyManager::removeOutput(audio_io_handle_t output)
6369{
Francois Gaffiebce7cd42020-10-14 16:13:20 +02006370 if (mPrimaryOutput != 0 && mPrimaryOutput == mOutputs.valueFor(output)) {
6371 ALOGV("%s: removing primary output", __func__);
6372 mPrimaryOutput = nullptr;
6373 }
François Gaffie53615e22015-03-19 09:24:12 +01006374 mOutputs.removeItem(output);
Eric Laurent36829f92017-04-07 19:04:42 -07006375 selectOutputForMusicEffects();
François Gaffie53615e22015-03-19 09:24:12 +01006376}
6377
Eric Laurent98e38192018-02-15 18:31:53 -08006378void AudioPolicyManager::addInput(audio_io_handle_t input,
6379 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07006380{
Eric Laurent1c333e22014-05-20 10:48:17 -07006381 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07006382 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07006383}
Eric Laurente552edb2014-03-10 17:42:56 -07006384
François Gaffie11d30102018-11-02 16:09:09 +01006385status_t AudioPolicyManager::checkOutputsForDevice(const sp<DeviceDescriptor>& device,
François Gaffie53615e22015-03-19 09:24:12 +01006386 audio_policy_dev_state_t state,
François Gaffie11d30102018-11-02 16:09:09 +01006387 SortedVector<audio_io_handle_t>& outputs)
Eric Laurente552edb2014-03-10 17:42:56 -07006388{
François Gaffie11d30102018-11-02 16:09:09 +01006389 audio_devices_t deviceType = device->type();
jiabince9f20e2019-09-12 16:29:15 -07006390 const String8 &address = String8(device->address().c_str());
Eric Laurentc75307b2015-03-17 15:29:32 -07006391 sp<SwAudioOutputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07006392
François Gaffie11d30102018-11-02 16:09:09 +01006393 if (audio_device_is_digital(deviceType)) {
Eric Laurentcc750d32015-06-25 11:48:20 -07006394 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01006395 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07006396 }
Eric Laurente552edb2014-03-10 17:42:56 -07006397
Eric Laurent3b73df72014-03-11 09:06:29 -07006398 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
jiabinb4fed192020-09-22 14:45:40 -07006399 // first call getAudioPort to get the supported attributes from the HAL
6400 struct audio_port_v7 port = {};
6401 device->toAudioPort(&port);
6402 status_t status = mpClientInterface->getAudioPort(&port);
6403 if (status == NO_ERROR) {
6404 device->importAudioPort(port);
6405 }
6406
6407 // then list already open outputs that can be routed to this device
Eric Laurente552edb2014-03-10 17:42:56 -07006408 for (size_t i = 0; i < mOutputs.size(); i++) {
6409 desc = mOutputs.valueAt(i);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006410 if (!desc->isDuplicated() && desc->supportsDevice(device)
jiabin9a3361e2019-10-01 09:38:30 -07006411 && desc->devicesSupportEncodedFormats({deviceType})) {
François Gaffie11d30102018-11-02 16:09:09 +01006412 ALOGV("checkOutputsForDevice(): adding opened output %d on device %s",
6413 mOutputs.keyAt(i), device->toString().c_str());
6414 outputs.add(mOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07006415 }
6416 }
6417 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07006418 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006419 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006420 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
6421 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
François Gaffie11d30102018-11-02 16:09:09 +01006422 if (profile->supportsDevice(device)) {
6423 profiles.add(profile);
6424 ALOGV("checkOutputsForDevice(): adding profile %zu from module %s",
6425 j, hwModule->getName());
Eric Laurente552edb2014-03-10 17:42:56 -07006426 }
6427 }
6428 }
6429
Eric Laurent7b279bb2015-12-14 10:18:23 -08006430 ALOGV(" found %zu profiles, %zu outputs", profiles.size(), outputs.size());
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006431
Eric Laurente552edb2014-03-10 17:42:56 -07006432 if (profiles.isEmpty() && outputs.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006433 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07006434 return BAD_VALUE;
6435 }
6436
6437 // open outputs for matching profiles if needed. Direct outputs are also opened to
6438 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
6439 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07006440 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07006441
6442 // nothing to do if one output is already opened for this profile
6443 size_t j;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006444 for (j = 0; j < outputs.size(); j++) {
6445 desc = mOutputs.valueFor(outputs.itemAt(j));
Eric Laurente552edb2014-03-10 17:42:56 -07006446 if (!desc->isDuplicated() && desc->mProfile == profile) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07006447 // matching profile: save the sample rates, format and channel masks supported
6448 // by the profile in our device descriptor
François Gaffie11d30102018-11-02 16:09:09 +01006449 if (audio_device_is_digital(deviceType)) {
jiabin4ef93452019-09-10 14:29:54 -07006450 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006451 }
Eric Laurente552edb2014-03-10 17:42:56 -07006452 break;
6453 }
6454 }
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006455 if (j != outputs.size()) {
Eric Laurente552edb2014-03-10 17:42:56 -07006456 continue;
6457 }
6458
Eric Laurent3974e3b2017-12-07 17:58:43 -08006459 if (!profile->canOpenNewIo()) {
6460 ALOGW("Max Output number %u already opened for this profile %s",
6461 profile->maxOpenCount, profile->getTagName().c_str());
6462 continue;
6463 }
6464
Eric Laurent83efe1c2017-07-09 16:51:08 -07006465 ALOGV("opening output for device %08x with params %s profile %p name %s",
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00006466 deviceType, address.c_str(), profile.get(), profile->getName().c_str());
jiabinbce0c1d2020-10-05 11:20:18 -07006467 desc = openOutputWithProfileAndDevice(profile, DeviceVector(device));
6468 audio_io_handle_t output = desc == nullptr ? AUDIO_IO_HANDLE_NONE : desc->mIoHandle;
Eric Laurentcf2c0212014-07-25 16:20:43 -07006469 if (output == AUDIO_IO_HANDLE_NONE) {
François Gaffie11d30102018-11-02 16:09:09 +01006470 ALOGW("checkOutputsForDevice() could not open output for device %x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07006471 profiles.removeAt(profile_index);
6472 profile_index--;
6473 } else {
6474 outputs.add(output);
Paul McLean9080a4c2015-06-18 08:24:02 -07006475 // Load digital format info only for digital devices
François Gaffie11d30102018-11-02 16:09:09 +01006476 if (audio_device_is_digital(deviceType)) {
jiabinbce0c1d2020-10-05 11:20:18 -07006477 // TODO: when getAudioPort is ready, it may not be needed to import the audio
6478 // port but just pick audio profile
jiabin4ef93452019-09-10 14:29:54 -07006479 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006480 }
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07006481
François Gaffie11d30102018-11-02 16:09:09 +01006482 if (device_distinguishes_on_address(deviceType)) {
6483 ALOGV("checkOutputsForDevice(): setOutputDevices %s",
6484 device->toString().c_str());
6485 setOutputDevices(desc, DeviceVector(device), true/*force*/, 0/*delay*/,
6486 NULL/*patch handle*/);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006487 }
Eric Laurente552edb2014-03-10 17:42:56 -07006488 ALOGV("checkOutputsForDevice(): adding output %d", output);
6489 }
6490 }
6491
6492 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006493 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07006494 return BAD_VALUE;
6495 }
Eric Laurentd4692962014-05-05 18:13:44 -07006496 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07006497 // check if one opened output is not needed any more after disconnecting one device
6498 for (size_t i = 0; i < mOutputs.size(); i++) {
6499 desc = mOutputs.valueAt(i);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006500 if (!desc->isDuplicated()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08006501 // exact match on device
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006502 if (device_distinguishes_on_address(deviceType) && desc->supportsDevice(device)
Francois Gaffiec7d4c222021-12-02 11:12:52 +01006503 && desc->containsSingleDeviceSupportingEncodedFormats(device)) {
François Gaffie11d30102018-11-02 16:09:09 +01006504 outputs.add(mOutputs.keyAt(i));
Francois Gaffie716e1432019-01-14 16:58:59 +01006505 } else if (!mAvailableOutputDevices.containsAtLeastOne(desc->supportedDevices())) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006506 ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
6507 mOutputs.keyAt(i));
6508 outputs.add(mOutputs.keyAt(i));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006509 }
Eric Laurente552edb2014-03-10 17:42:56 -07006510 }
6511 }
Eric Laurentd4692962014-05-05 18:13:44 -07006512 // Clear any profiles associated with the disconnected device.
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006513 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006514 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
6515 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
jiabinbce0c1d2020-10-05 11:20:18 -07006516 if (!profile->supportsDevice(device)) {
6517 continue;
6518 }
6519 ALOGV("checkOutputsForDevice(): "
6520 "clearing direct output profile %zu on module %s",
6521 j, hwModule->getName());
6522 profile->clearAudioProfiles();
6523 if (!profile->hasDynamicAudioProfile()) {
6524 continue;
6525 }
6526 // When a device is disconnected, if there is an IOProfile that contains dynamic
6527 // profiles and supports the disconnected device, call getAudioPort to repopulate
6528 // the capabilities of the devices that is supported by the IOProfile.
6529 for (const auto& supportedDevice : profile->getSupportedDevices()) {
6530 if (supportedDevice == device ||
6531 !mAvailableOutputDevices.contains(supportedDevice)) {
6532 continue;
6533 }
6534 struct audio_port_v7 port;
6535 supportedDevice->toAudioPort(&port);
6536 status_t status = mpClientInterface->getAudioPort(&port);
6537 if (status == NO_ERROR) {
6538 supportedDevice->importAudioPort(port);
6539 }
Eric Laurente552edb2014-03-10 17:42:56 -07006540 }
6541 }
6542 }
6543 }
6544 return NO_ERROR;
6545}
6546
François Gaffie11d30102018-11-02 16:09:09 +01006547status_t AudioPolicyManager::checkInputsForDevice(const sp<DeviceDescriptor>& device,
Eric Laurent0dd51852019-04-19 18:18:58 -07006548 audio_policy_dev_state_t state)
Eric Laurentd4692962014-05-05 18:13:44 -07006549{
Eric Laurent1f2f2232014-06-02 12:01:23 -07006550 sp<AudioInputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07006551
François Gaffie11d30102018-11-02 16:09:09 +01006552 if (audio_device_is_digital(device->type())) {
Eric Laurentcc750d32015-06-25 11:48:20 -07006553 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01006554 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07006555 }
6556
Eric Laurentd4692962014-05-05 18:13:44 -07006557 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
jiabinbf5f4262023-04-12 21:48:34 +00006558 // first call getAudioPort to get the supported attributes from the HAL
6559 struct audio_port_v7 port = {};
6560 device->toAudioPort(&port);
6561 status_t status = mpClientInterface->getAudioPort(&port);
6562 if (status == NO_ERROR) {
6563 device->importAudioPort(port);
6564 }
6565
Eric Laurent0dd51852019-04-19 18:18:58 -07006566 // look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07006567 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006568 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07006569 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006570 profile_index < hwModule->getInputProfiles().size();
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006571 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006572 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Eric Laurent275e8e92014-11-30 15:14:47 -08006573
François Gaffie11d30102018-11-02 16:09:09 +01006574 if (profile->supportsDevice(device)) {
6575 profiles.add(profile);
6576 ALOGV("checkInputsForDevice(): adding profile %zu from module %s",
6577 profile_index, hwModule->getName());
Eric Laurentd4692962014-05-05 18:13:44 -07006578 }
6579 }
6580 }
6581
Eric Laurent0dd51852019-04-19 18:18:58 -07006582 if (profiles.isEmpty()) {
6583 ALOGW("%s: No input profile available for device %s",
6584 __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07006585 return BAD_VALUE;
6586 }
6587
6588 // open inputs for matching profiles if needed. Direct inputs are also opened to
6589 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
6590 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
6591
Eric Laurent1c333e22014-05-20 10:48:17 -07006592 sp<IOProfile> profile = profiles[profile_index];
Eric Laurent3974e3b2017-12-07 17:58:43 -08006593
Eric Laurentd4692962014-05-05 18:13:44 -07006594 // nothing to do if one input is already opened for this profile
6595 size_t input_index;
6596 for (input_index = 0; input_index < mInputs.size(); input_index++) {
6597 desc = mInputs.valueAt(input_index);
6598 if (desc->mProfile == profile) {
François Gaffie11d30102018-11-02 16:09:09 +01006599 if (audio_device_is_digital(device->type())) {
jiabin4ef93452019-09-10 14:29:54 -07006600 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006601 }
Eric Laurentd4692962014-05-05 18:13:44 -07006602 break;
6603 }
6604 }
6605 if (input_index != mInputs.size()) {
6606 continue;
6607 }
6608
Eric Laurent3974e3b2017-12-07 17:58:43 -08006609 if (!profile->canOpenNewIo()) {
6610 ALOGW("Max Input number %u already opened for this profile %s",
6611 profile->maxOpenCount, profile->getTagName().c_str());
6612 continue;
6613 }
6614
Eric Laurentfe231122017-11-17 17:48:06 -08006615 desc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentcf2c0212014-07-25 16:20:43 -07006616 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
jiabinbf5f4262023-04-12 21:48:34 +00006617 status = desc->open(nullptr, device, AUDIO_SOURCE_MIC, AUDIO_INPUT_FLAG_NONE, &input);
Eric Laurentd4692962014-05-05 18:13:44 -07006618
Eric Laurentcf2c0212014-07-25 16:20:43 -07006619 if (status == NO_ERROR) {
jiabince9f20e2019-09-12 16:29:15 -07006620 const String8& address = String8(device->address().c_str());
Tomasz Wasilczykfd9ffd12023-08-14 17:56:22 +00006621 if (!address.empty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006622 char *param = audio_device_address_to_parameter(device->type(), address);
Eric Laurentcf2c0212014-07-25 16:20:43 -07006623 mpClientInterface->setParameters(input, String8(param));
6624 free(param);
Eric Laurentd4692962014-05-05 18:13:44 -07006625 }
jiabin12537fc2023-10-12 17:56:08 +00006626 updateAudioProfiles(device, input, profile);
François Gaffie112b0af2015-11-19 16:13:25 +01006627 if (!profile->hasValidAudioProfile()) {
Eric Laurentd4692962014-05-05 18:13:44 -07006628 ALOGW("checkInputsForDevice() direct input missing param");
Eric Laurentfe231122017-11-17 17:48:06 -08006629 desc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07006630 input = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07006631 }
6632
Eric Laurent0dd51852019-04-19 18:18:58 -07006633 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07006634 addInput(input, desc);
6635 }
6636 } // endif input != 0
6637
Eric Laurentcf2c0212014-07-25 16:20:43 -07006638 if (input == AUDIO_IO_HANDLE_NONE) {
Pattydd807582021-11-04 21:01:03 +08006639 ALOGW("%s could not open input for device %s", __func__,
François Gaffie11d30102018-11-02 16:09:09 +01006640 device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07006641 profiles.removeAt(profile_index);
6642 profile_index--;
6643 } else {
François Gaffie11d30102018-11-02 16:09:09 +01006644 if (audio_device_is_digital(device->type())) {
jiabin4ef93452019-09-10 14:29:54 -07006645 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006646 }
Eric Laurentd4692962014-05-05 18:13:44 -07006647 ALOGV("checkInputsForDevice(): adding input %d", input);
6648 }
6649 } // end scan profiles
6650
6651 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006652 ALOGW("%s: No input available for device %s", __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07006653 return BAD_VALUE;
6654 }
6655 } else {
6656 // Disconnect
Eric Laurentd4692962014-05-05 18:13:44 -07006657 // Clear any profiles associated with the disconnected device.
Mikhail Naganovd4120142017-12-06 15:49:22 -08006658 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07006659 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006660 profile_index < hwModule->getInputProfiles().size();
Eric Laurentd4692962014-05-05 18:13:44 -07006661 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006662 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Francois Gaffie716e1432019-01-14 16:58:59 +01006663 if (profile->supportsDevice(device)) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08006664 ALOGV("checkInputsForDevice(): clearing direct input profile %zu on module %s",
6665 profile_index, hwModule->getName());
François Gaffie112b0af2015-11-19 16:13:25 +01006666 profile->clearAudioProfiles();
Eric Laurentd4692962014-05-05 18:13:44 -07006667 }
6668 }
6669 }
6670 } // end disconnect
6671
6672 return NO_ERROR;
6673}
6674
6675
Eric Laurente0720872014-03-11 09:30:41 -07006676void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07006677{
6678 ALOGV("closeOutput(%d)", output);
6679
François Gaffie1c878552018-11-22 16:53:21 +01006680 sp<SwAudioOutputDescriptor> closingOutput = mOutputs.valueFor(output);
6681 if (closingOutput == NULL) {
Eric Laurente552edb2014-03-10 17:42:56 -07006682 ALOGW("closeOutput() unknown output %d", output);
6683 return;
6684 }
Mikhail Naganov32ebca32019-03-22 15:42:52 -07006685 const bool closingOutputWasActive = closingOutput->isActive();
François Gaffie1c878552018-11-22 16:53:21 +01006686 mPolicyMixes.closeOutput(closingOutput);
Eric Laurent275e8e92014-11-30 15:14:47 -08006687
Eric Laurente552edb2014-03-10 17:42:56 -07006688 // look for duplicated outputs connected to the output being removed.
6689 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie1c878552018-11-22 16:53:21 +01006690 sp<SwAudioOutputDescriptor> dupOutput = mOutputs.valueAt(i);
6691 if (dupOutput->isDuplicated() &&
6692 (dupOutput->mOutput1 == closingOutput || dupOutput->mOutput2 == closingOutput)) {
6693 sp<SwAudioOutputDescriptor> remainingOutput =
6694 dupOutput->mOutput1 == closingOutput ? dupOutput->mOutput2 : dupOutput->mOutput1;
Eric Laurente552edb2014-03-10 17:42:56 -07006695 // As all active tracks on duplicated output will be deleted,
6696 // and as they were also referenced on the other output, the reference
6697 // count for their stream type must be adjusted accordingly on
6698 // the other output.
François Gaffie1c878552018-11-22 16:53:21 +01006699 const bool wasActive = remainingOutput->isActive();
6700 // Note: no-op on the closing output where all clients has already been set inactive
6701 dupOutput->setAllClientsInactive();
Eric Laurent733ce942017-12-07 12:18:25 -08006702 // stop() will be a no op if the output is still active but is needed in case all
6703 // active streams refcounts where cleared above
6704 if (wasActive) {
François Gaffie1c878552018-11-22 16:53:21 +01006705 remainingOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08006706 }
Eric Laurente552edb2014-03-10 17:42:56 -07006707 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
6708 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
6709
6710 mpClientInterface->closeOutput(duplicatedOutput);
François Gaffie53615e22015-03-19 09:24:12 +01006711 removeOutput(duplicatedOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07006712 }
6713 }
6714
Eric Laurent05b90f82014-08-27 15:32:29 -07006715 nextAudioPortGeneration();
6716
François Gaffie1c878552018-11-22 16:53:21 +01006717 ssize_t index = mAudioPatches.indexOfKey(closingOutput->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07006718 if (index >= 0) {
6719 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006720 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
6721 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07006722 mAudioPatches.removeItemsAt(index);
6723 mpClientInterface->onAudioPatchListUpdate();
6724 }
6725
Mikhail Naganov32ebca32019-03-22 15:42:52 -07006726 if (closingOutputWasActive) {
6727 closingOutput->stop();
6728 }
François Gaffie1c878552018-11-22 16:53:21 +01006729 closingOutput->close();
Eric Laurente552edb2014-03-10 17:42:56 -07006730
François Gaffie53615e22015-03-19 09:24:12 +01006731 removeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07006732 mPreviousOutputs = mOutputs;
Eric Laurentb4f42a92022-01-17 17:37:31 +01006733 if (closingOutput == mSpatializerOutput) {
6734 mSpatializerOutput.clear();
6735 }
Dean Wheatley3023b382018-08-09 07:42:40 +10006736
6737 // MSD patches may have been released to support a non-MSD direct output. Reset MSD patch if
6738 // no direct outputs are open.
François Gaffie11d30102018-11-02 16:09:09 +01006739 if (!getMsdAudioOutDevices().isEmpty()) {
Dean Wheatley3023b382018-08-09 07:42:40 +10006740 bool directOutputOpen = false;
6741 for (size_t i = 0; i < mOutputs.size(); i++) {
6742 if (mOutputs[i]->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
6743 directOutputOpen = true;
6744 break;
6745 }
6746 }
6747 if (!directOutputOpen) {
Michael Chan6fb34492020-12-08 15:44:49 +11006748 ALOGV("no direct outputs open, reset MSD patches");
6749 // TODO: The MSD patches to be established here may differ to current MSD patches due to
6750 // how output devices for patching are resolved. Avoid by caching and reusing the
6751 // arguments to mEngine->getOutputDevicesForAttributes() when resolving which output
6752 // devices to patch to. This may be complicated by the fact that devices may become
6753 // unavailable.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11006754 setMsdOutputPatches();
Dean Wheatley3023b382018-08-09 07:42:40 +10006755 }
6756 }
Eric Laurent05b90f82014-08-27 15:32:29 -07006757}
6758
6759void AudioPolicyManager::closeInput(audio_io_handle_t input)
6760{
6761 ALOGV("closeInput(%d)", input);
6762
6763 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
6764 if (inputDesc == NULL) {
6765 ALOGW("closeInput() unknown input %d", input);
6766 return;
6767 }
6768
Eric Laurent6a94d692014-05-20 11:18:06 -07006769 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07006770
François Gaffie11d30102018-11-02 16:09:09 +01006771 sp<DeviceDescriptor> device = inputDesc->getDevice();
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08006772 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07006773 if (index >= 0) {
6774 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006775 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
6776 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07006777 mAudioPatches.removeItemsAt(index);
6778 mpClientInterface->onAudioPatchListUpdate();
6779 }
6780
Eric Laurentfe231122017-11-17 17:48:06 -08006781 inputDesc->close();
Eric Laurent05b90f82014-08-27 15:32:29 -07006782 mInputs.removeItem(input);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07006783
François Gaffie11d30102018-11-02 16:09:09 +01006784 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
6785 if (primaryInputDevices.contains(device) &&
Haynes Mathew George1d539d92018-03-16 11:40:49 -07006786 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07006787 mpClientInterface->setSoundTriggerCaptureState(false);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07006788 }
Eric Laurente552edb2014-03-10 17:42:56 -07006789}
6790
François Gaffie11d30102018-11-02 16:09:09 +01006791SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevices(
6792 const DeviceVector &devices,
6793 const SwAudioOutputCollection& openOutputs)
Eric Laurente552edb2014-03-10 17:42:56 -07006794{
6795 SortedVector<audio_io_handle_t> outputs;
6796
François Gaffie11d30102018-11-02 16:09:09 +01006797 ALOGVV("%s() devices %s", __func__, devices.toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07006798 for (size_t i = 0; i < openOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01006799 ALOGVV("output %zu isDuplicated=%d device=%s",
Eric Laurent8c7e6da2015-04-21 17:37:00 -07006800 i, openOutputs.valueAt(i)->isDuplicated(),
François Gaffie11d30102018-11-02 16:09:09 +01006801 openOutputs.valueAt(i)->supportedDevices().toString().c_str());
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006802 if (openOutputs.valueAt(i)->supportsAllDevices(devices)
jiabin9a3361e2019-10-01 09:38:30 -07006803 && openOutputs.valueAt(i)->devicesSupportEncodedFormats(devices.types())) {
François Gaffie11d30102018-11-02 16:09:09 +01006804 ALOGVV("%s() found output %d", __func__, openOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07006805 outputs.add(openOutputs.keyAt(i));
6806 }
6807 }
6808 return outputs;
6809}
6810
Mikhail Naganov37977152018-07-11 15:54:44 -07006811void AudioPolicyManager::checkForDeviceAndOutputChanges(std::function<bool()> onOutputsChecked)
6812{
6813 // checkA2dpSuspend must run before checkOutputForAllStrategies so that A2DP
6814 // output is suspended before any tracks are moved to it
6815 checkA2dpSuspend();
6816 checkOutputForAllStrategies();
Kevin Rocard153f92d2018-12-18 18:33:28 -08006817 checkSecondaryOutputs();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11006818 if (onOutputsChecked != nullptr && onOutputsChecked()) checkA2dpSuspend();
Mikhail Naganov37977152018-07-11 15:54:44 -07006819 updateDevicesAndOutputs();
Mikhail Naganov7bd9b8d2018-11-15 02:09:03 +00006820 if (mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD) != 0) {
Michael Chan6fb34492020-12-08 15:44:49 +11006821 // TODO: The MSD patches to be established here may differ to current MSD patches due to how
6822 // output devices for patching are resolved. Nevertheless, AudioTracks affected by device
6823 // configuration changes will ultimately be rerouted correctly. We can still avoid
6824 // unnecessary rerouting by caching and reusing the arguments to
6825 // mEngine->getOutputDevicesForAttributes() when resolving which output devices to patch to.
6826 // This may be complicated by the fact that devices may become unavailable.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11006827 setMsdOutputPatches();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11006828 }
Jean-Michel Trivi9a6b9ad2020-10-22 16:46:43 -07006829 // an event that changed routing likely occurred, inform upper layers
6830 mpClientInterface->onRoutingUpdated();
Mikhail Naganov37977152018-07-11 15:54:44 -07006831}
6832
François Gaffiec005e562018-11-06 15:04:49 +01006833bool AudioPolicyManager::followsSameRouting(const audio_attributes_t &lAttr,
6834 const audio_attributes_t &rAttr) const
Eric Laurente552edb2014-03-10 17:42:56 -07006835{
François Gaffiec005e562018-11-06 15:04:49 +01006836 return mEngine->getProductStrategyForAttributes(lAttr) ==
6837 mEngine->getProductStrategyForAttributes(rAttr);
6838}
6839
Francois Gaffieff1eb522020-05-06 18:37:04 +02006840void AudioPolicyManager::checkAudioSourceForAttributes(const audio_attributes_t &attr)
6841{
6842 for (size_t i = 0; i < mAudioSources.size(); i++) {
6843 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
6844 if (sourceDesc != nullptr && followsSameRouting(attr, sourceDesc->attributes())
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02006845 && sourceDesc->getPatchHandle() == AUDIO_PATCH_HANDLE_NONE
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02006846 && !isCallRxAudioSource(sourceDesc) && !sourceDesc->isInternal()) {
Francois Gaffieff1eb522020-05-06 18:37:04 +02006847 connectAudioSource(sourceDesc);
6848 }
6849 }
6850}
6851
6852void AudioPolicyManager::clearAudioSourcesForOutput(audio_io_handle_t output)
6853{
6854 for (size_t i = 0; i < mAudioSources.size(); i++) {
6855 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
6856 if (sourceDesc != nullptr && sourceDesc->swOutput().promote() != nullptr
6857 && sourceDesc->swOutput().promote()->mIoHandle == output) {
6858 disconnectAudioSource(sourceDesc);
6859 }
6860 }
6861}
6862
François Gaffiec005e562018-11-06 15:04:49 +01006863void AudioPolicyManager::checkOutputForAttributes(const audio_attributes_t &attr)
6864{
6865 auto psId = mEngine->getProductStrategyForAttributes(attr);
6866
6867 DeviceVector oldDevices = mEngine->getOutputDevicesForAttributes(attr, 0, true /*fromCache*/);
6868 DeviceVector newDevices = mEngine->getOutputDevicesForAttributes(attr, 0, false /*fromCache*/);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07006869
François Gaffie11d30102018-11-02 16:09:09 +01006870 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevices(oldDevices, mPreviousOutputs);
6871 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevices(newDevices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07006872
Eric Laurentc209fe42020-06-05 18:11:23 -07006873 uint32_t maxLatency = 0;
Oscar Azucena873d10f2023-01-12 18:34:42 -08006874 bool unneededUsePrimaryOutputFromPolicyMixes = false;
Eric Laurent56ed8842022-11-15 16:04:41 +01006875 std::vector<sp<SwAudioOutputDescriptor>> invalidatedOutputs;
Eric Laurentc209fe42020-06-05 18:11:23 -07006876 // take into account dynamic audio policies related changes: if a client is now associated
6877 // to a different policy mix than at creation time, invalidate corresponding stream
Eric Laurent56ed8842022-11-15 16:04:41 +01006878 for (size_t i = 0; i < mPreviousOutputs.size(); i++) {
Eric Laurentc209fe42020-06-05 18:11:23 -07006879 const sp<SwAudioOutputDescriptor>& desc = mPreviousOutputs.valueAt(i);
6880 if (desc->isDuplicated()) {
6881 continue;
Jean-Michel Trivife472e22014-12-16 14:23:13 -08006882 }
Eric Laurentc209fe42020-06-05 18:11:23 -07006883 for (const sp<TrackClientDescriptor>& client : desc->getClientIterable()) {
6884 if (mEngine->getProductStrategyForAttributes(client->attributes()) != psId) {
6885 continue;
6886 }
6887 sp<AudioPolicyMix> primaryMix;
Dean Wheatleyd082f472022-02-04 11:10:48 +11006888 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->config(),
Oscar Azucena873d10f2023-01-12 18:34:42 -08006889 client->uid(), client->session(), client->flags(), mAvailableOutputDevices,
6890 nullptr /* requestedDevice */, primaryMix, nullptr /* secondaryMixes */,
6891 unneededUsePrimaryOutputFromPolicyMixes);
Eric Laurentc209fe42020-06-05 18:11:23 -07006892 if (status != OK) {
6893 continue;
6894 }
yucliuf4de36d2020-09-14 14:57:56 -07006895 if (client->getPrimaryMix() != primaryMix || client->hasLostPrimaryMix()) {
Eric Laurent56ed8842022-11-15 16:04:41 +01006896 if (desc->isStrategyActive(psId) && maxLatency < desc->latency()) {
Eric Laurentc209fe42020-06-05 18:11:23 -07006897 maxLatency = desc->latency();
6898 }
Eric Laurent56ed8842022-11-15 16:04:41 +01006899 invalidatedOutputs.push_back(desc);
Eric Laurentc209fe42020-06-05 18:11:23 -07006900 }
Jean-Michel Trivife472e22014-12-16 14:23:13 -08006901 }
6902 }
6903
Eric Laurent56ed8842022-11-15 16:04:41 +01006904 if (srcOutputs != dstOutputs || !invalidatedOutputs.empty()) {
Eric Laurentac3a6902018-05-11 16:39:10 -07006905 // get maximum latency of all source outputs to determine the minimum mute time guaranteeing
6906 // audio from invalidated tracks will be rendered when unmuting
Eric Laurentac3a6902018-05-11 16:39:10 -07006907 for (audio_io_handle_t srcOut : srcOutputs) {
6908 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
Eric Laurentaa02db82019-09-05 17:31:49 -07006909 if (desc == nullptr) continue;
6910
6911 if (desc->isStrategyActive(psId) && maxLatency < desc->latency()) {
Eric Laurentac3a6902018-05-11 16:39:10 -07006912 maxLatency = desc->latency();
6913 }
Eric Laurentaa02db82019-09-05 17:31:49 -07006914
Eric Laurent56ed8842022-11-15 16:04:41 +01006915 bool invalidate = false;
Eric Laurentaa02db82019-09-05 17:31:49 -07006916 for (auto client : desc->clientsList(false /*activeOnly*/)) {
Eric Laurent78aade82019-09-13 18:55:08 -07006917 if (desc->isDuplicated() || !desc->mProfile->isDirectOutput()) {
Eric Laurentaa02db82019-09-05 17:31:49 -07006918 // a client on a non direct outputs has necessarily a linear PCM format
6919 // so we can call selectOutput() safely
6920 const audio_io_handle_t newOutput = selectOutput(dstOutputs,
6921 client->flags(),
6922 client->config().format,
6923 client->config().channel_mask,
jiabinebb6af42020-06-09 17:31:17 -07006924 client->config().sample_rate,
6925 client->session());
Eric Laurentaa02db82019-09-05 17:31:49 -07006926 if (newOutput != srcOut) {
6927 invalidate = true;
6928 break;
6929 }
6930 } else {
6931 sp<IOProfile> profile = getProfileForOutput(newDevices,
6932 client->config().sample_rate,
6933 client->config().format,
6934 client->config().channel_mask,
6935 client->flags(),
6936 true /* directOnly */);
6937 if (profile != desc->mProfile) {
6938 invalidate = true;
6939 break;
6940 }
6941 }
6942 }
Eric Laurent56ed8842022-11-15 16:04:41 +01006943 // mute strategy while moving tracks from one output to another
6944 if (invalidate) {
6945 invalidatedOutputs.push_back(desc);
6946 if (desc->isStrategyActive(psId)) {
6947 setStrategyMute(psId, true, desc);
6948 setStrategyMute(psId, false, desc, maxLatency * LATENCY_MUTE_FACTOR,
6949 newDevices.types());
6950 }
Eric Laurente552edb2014-03-10 17:42:56 -07006951 }
François Gaffiec005e562018-11-06 15:04:49 +01006952 sp<SourceClientDescriptor> source = getSourceForAttributesOnOutput(srcOut, attr);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02006953 if (source != nullptr && !isCallRxAudioSource(source) && !source->isInternal()) {
Eric Laurentd60560a2015-04-10 11:31:20 -07006954 connectAudioSource(source);
6955 }
Eric Laurente552edb2014-03-10 17:42:56 -07006956 }
6957
Eric Laurent56ed8842022-11-15 16:04:41 +01006958 ALOGV_IF(!(srcOutputs.isEmpty() || dstOutputs.isEmpty()),
6959 "%s: strategy %d, moving from output %s to output %s", __func__, psId,
6960 std::to_string(srcOutputs[0]).c_str(),
6961 std::to_string(dstOutputs[0]).c_str());
6962
François Gaffiec005e562018-11-06 15:04:49 +01006963 // Move effects associated to this stream from previous output to new output
6964 if (followsSameRouting(attr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07006965 selectOutputForMusicEffects();
Eric Laurente552edb2014-03-10 17:42:56 -07006966 }
François Gaffiec005e562018-11-06 15:04:49 +01006967 // Move tracks associated to this stream (and linked) from previous output to new output
Eric Laurent56ed8842022-11-15 16:04:41 +01006968 if (!invalidatedOutputs.empty()) {
jiabinc44b3462022-12-08 12:52:31 -08006969 invalidateStreams(mEngine->getStreamTypesForProductStrategy(psId));
Eric Laurent56ed8842022-11-15 16:04:41 +01006970 for (sp<SwAudioOutputDescriptor> desc : invalidatedOutputs) {
jiabin49256852022-03-09 11:21:35 -08006971 desc->setTracksInvalidatedStatusByStrategy(psId);
6972 }
Eric Laurente552edb2014-03-10 17:42:56 -07006973 }
6974 }
6975}
6976
Eric Laurente0720872014-03-11 09:30:41 -07006977void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07006978{
François Gaffiec005e562018-11-06 15:04:49 +01006979 for (const auto &strategy : mEngine->getOrderedProductStrategies()) {
6980 auto attributes = mEngine->getAllAttributesForProductStrategy(strategy).front();
6981 checkOutputForAttributes(attributes);
Francois Gaffieff1eb522020-05-06 18:37:04 +02006982 checkAudioSourceForAttributes(attributes);
François Gaffiec005e562018-11-06 15:04:49 +01006983 }
Eric Laurente552edb2014-03-10 17:42:56 -07006984}
6985
Kevin Rocard153f92d2018-12-18 18:33:28 -08006986void AudioPolicyManager::checkSecondaryOutputs() {
jiabinc44b3462022-12-08 12:52:31 -08006987 PortHandleVector clientsToInvalidate;
jiabin10a03f12021-05-07 23:46:28 +00006988 TrackSecondaryOutputsMap trackSecondaryOutputs;
Oscar Azucena873d10f2023-01-12 18:34:42 -08006989 bool unneededUsePrimaryOutputFromPolicyMixes = false;
Kevin Rocard153f92d2018-12-18 18:33:28 -08006990 for (size_t i = 0; i < mOutputs.size(); i++) {
6991 const sp<SwAudioOutputDescriptor>& outputDescriptor = mOutputs[i];
6992 for (const sp<TrackClientDescriptor>& client : outputDescriptor->getClientIterable()) {
Eric Laurentc529cf62020-04-17 18:19:10 -07006993 sp<AudioPolicyMix> primaryMix;
6994 std::vector<sp<AudioPolicyMix>> secondaryMixes;
Dean Wheatleyd082f472022-02-04 11:10:48 +11006995 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->config(),
Oscar Azucena873d10f2023-01-12 18:34:42 -08006996 client->uid(), client->session(), client->flags(), mAvailableOutputDevices,
6997 nullptr /* requestedDevice */, primaryMix, &secondaryMixes,
6998 unneededUsePrimaryOutputFromPolicyMixes);
Eric Laurentc529cf62020-04-17 18:19:10 -07006999 std::vector<sp<SwAudioOutputDescriptor>> secondaryDescs;
7000 for (auto &secondaryMix : secondaryMixes) {
7001 sp<SwAudioOutputDescriptor> outputDesc = secondaryMix->getOutput();
7002 if (outputDesc != nullptr &&
7003 outputDesc->mIoHandle != AUDIO_IO_HANDLE_NONE) {
7004 secondaryDescs.push_back(outputDesc);
7005 }
7006 }
7007
jiabinc44b3462022-12-08 12:52:31 -08007008 if (status != OK &&
7009 (client->flags() & AUDIO_OUTPUT_FLAG_MMAP_NOIRQ) == AUDIO_OUTPUT_FLAG_NONE) {
7010 // When it failed to query secondary output, only invalidate the client that is not
7011 // MMAP. The reason is that MMAP stream will not support secondary output.
7012 clientsToInvalidate.push_back(client->portId());
jiabin10a03f12021-05-07 23:46:28 +00007013 } else if (!std::equal(
7014 client->getSecondaryOutputs().begin(),
7015 client->getSecondaryOutputs().end(),
7016 secondaryDescs.begin(), secondaryDescs.end())) {
jiabina5281062021-11-23 00:10:23 +00007017 if (!audio_is_linear_pcm(client->config().format)) {
7018 // If the format is not PCM, the tracks should be invalidated to get correct
7019 // behavior when the secondary output is changed.
jiabinc44b3462022-12-08 12:52:31 -08007020 clientsToInvalidate.push_back(client->portId());
jiabina5281062021-11-23 00:10:23 +00007021 } else {
7022 std::vector<wp<SwAudioOutputDescriptor>> weakSecondaryDescs;
7023 std::vector<audio_io_handle_t> secondaryOutputIds;
7024 for (const auto &secondaryDesc: secondaryDescs) {
7025 secondaryOutputIds.push_back(secondaryDesc->mIoHandle);
7026 weakSecondaryDescs.push_back(secondaryDesc);
7027 }
7028 trackSecondaryOutputs.emplace(client->portId(), secondaryOutputIds);
7029 client->setSecondaryOutputs(std::move(weakSecondaryDescs));
jiabin10a03f12021-05-07 23:46:28 +00007030 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08007031 }
7032 }
7033 }
jiabin10a03f12021-05-07 23:46:28 +00007034 if (!trackSecondaryOutputs.empty()) {
7035 mpClientInterface->updateSecondaryOutputs(trackSecondaryOutputs);
7036 }
jiabinc44b3462022-12-08 12:52:31 -08007037 if (!clientsToInvalidate.empty()) {
7038 ALOGD("%s Invalidate clients due to fail getting output for attr", __func__);
7039 mpClientInterface->invalidateTracks(clientsToInvalidate);
Kevin Rocard153f92d2018-12-18 18:33:28 -08007040 }
7041}
7042
Eric Laurent2517af32020-11-25 15:31:27 +01007043bool AudioPolicyManager::isScoRequestedForComm() const {
7044 AudioDeviceTypeAddrVector devices;
7045 mEngine->getDevicesForRoleAndStrategy(mCommunnicationStrategy, DEVICE_ROLE_PREFERRED, devices);
7046 for (const auto &device : devices) {
7047 if (audio_is_bluetooth_out_sco_device(device.mType)) {
7048 return true;
7049 }
7050 }
7051 return false;
7052}
7053
Eric Laurent1a8b45f2022-04-13 16:01:47 +02007054bool AudioPolicyManager::isHearingAidUsedForComm() const {
7055 DeviceVector devices = mEngine->getOutputDevicesForStream(AUDIO_STREAM_VOICE_CALL,
7056 true /*fromCache*/);
7057 for (const auto &device : devices) {
7058 if (device->type() == AUDIO_DEVICE_OUT_HEARING_AID) {
7059 return true;
7060 }
7061 }
7062 return false;
7063}
7064
7065
Eric Laurente0720872014-03-11 09:30:41 -07007066void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07007067{
François Gaffie53615e22015-03-19 09:24:12 +01007068 audio_io_handle_t a2dpOutput = mOutputs.getA2dpOutput();
Aniket Kumar Lataa8ee9962018-01-31 20:24:23 -08007069 if (a2dpOutput == 0 || mOutputs.isA2dpOffloadedOnPrimary()) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07007070 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07007071 return;
7072 }
7073
Eric Laurent3a4311c2014-03-17 12:00:47 -07007074 bool isScoConnected =
jiabin9a3361e2019-10-01 09:38:30 -07007075 (mAvailableInputDevices.types().count(AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) != 0 ||
7076 !Intersection(mAvailableOutputDevices.types(), getAudioDeviceOutAllScoSet()).empty());
Eric Laurent2517af32020-11-25 15:31:27 +01007077 bool isScoRequested = isScoRequestedForComm();
Eric Laurentf732e072016-08-03 19:30:28 -07007078
7079 // if suspended, restore A2DP output if:
7080 // ((SCO device is NOT connected) ||
Eric Laurent2517af32020-11-25 15:31:27 +01007081 // ((SCO is not requested) &&
Eric Laurentf732e072016-08-03 19:30:28 -07007082 // (phone state is NOT in call) && (phone state is NOT ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07007083 //
Eric Laurentf732e072016-08-03 19:30:28 -07007084 // if not suspended, suspend A2DP output if:
7085 // (SCO device is connected) &&
Eric Laurent2517af32020-11-25 15:31:27 +01007086 // ((SCO is requested) ||
Eric Laurentf732e072016-08-03 19:30:28 -07007087 // ((phone state is in call) || (phone state is ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07007088 //
7089 if (mA2dpSuspended) {
Eric Laurentf732e072016-08-03 19:30:28 -07007090 if (!isScoConnected ||
Eric Laurent2517af32020-11-25 15:31:27 +01007091 (!isScoRequested &&
Eric Laurentf732e072016-08-03 19:30:28 -07007092 (mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) &&
François Gaffie2110e042015-03-24 08:41:51 +01007093 (mEngine->getPhoneState() != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07007094
7095 mpClientInterface->restoreOutput(a2dpOutput);
7096 mA2dpSuspended = false;
7097 }
7098 } else {
Eric Laurentf732e072016-08-03 19:30:28 -07007099 if (isScoConnected &&
Eric Laurent2517af32020-11-25 15:31:27 +01007100 (isScoRequested ||
Eric Laurentf732e072016-08-03 19:30:28 -07007101 (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) ||
François Gaffie2110e042015-03-24 08:41:51 +01007102 (mEngine->getPhoneState() == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07007103
7104 mpClientInterface->suspendOutput(a2dpOutput);
7105 mA2dpSuspended = true;
7106 }
7107 }
7108}
7109
François Gaffie11d30102018-11-02 16:09:09 +01007110DeviceVector AudioPolicyManager::getNewOutputDevices(const sp<SwAudioOutputDescriptor>& outputDesc,
7111 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07007112{
François Gaffie11d30102018-11-02 16:09:09 +01007113 DeviceVector devices;
7114
Jean-Michel Triviff155c62016-02-26 12:07:16 -08007115 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007116 if (index >= 0) {
7117 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007118 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01007119 ALOGV("%s device %s forced by patch %d", __func__,
7120 outputDesc->devices().toString().c_str(), outputDesc->getPatchHandle());
7121 return outputDesc->devices();
Eric Laurent6a94d692014-05-20 11:18:06 -07007122 }
7123 }
7124
Dean Wheatley514b4312020-06-17 21:45:00 +10007125 // Do not retrieve engine device for outputs through MSD
7126 // TODO: support explicit routing requests by resetting MSD patch to engine device.
7127 if (outputDesc->devices() == getMsdAudioOutDevices()) {
7128 return outputDesc->devices();
7129 }
7130
Eric Laurent97ac8712018-07-27 18:59:02 -07007131 // Honor explicit routing requests only if no client using default routing is active on this
7132 // input: a specific app can not force routing for other apps by setting a preferred device.
7133 bool active; // unused
François Gaffie11d30102018-11-02 16:09:09 +01007134 sp<DeviceDescriptor> device =
François Gaffiec005e562018-11-06 15:04:49 +01007135 findPreferredDevice(outputDesc, PRODUCT_STRATEGY_NONE, active, mAvailableOutputDevices);
François Gaffie11d30102018-11-02 16:09:09 +01007136 if (device != nullptr) {
7137 return DeviceVector(device);
Eric Laurentf3a5a602018-05-22 18:42:55 -07007138 }
7139
François Gaffiea807ef92018-11-05 10:44:33 +01007140 // Legacy Engine cannot take care of bus devices and mix, so we need to handle the conflict
7141 // of setForceUse / Default Bus device here
7142 device = mPolicyMixes.getDeviceAndMixForOutput(outputDesc, mAvailableOutputDevices);
7143 if (device != nullptr) {
7144 return DeviceVector(device);
7145 }
7146
François Gaffiec005e562018-11-06 15:04:49 +01007147 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
7148 StreamTypeVector streams = mEngine->getStreamTypesForProductStrategy(productStrategy);
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307149 auto hasStreamActive = [&](auto stream) {
7150 return hasStream(streams, stream) && isStreamActive(stream, 0);
7151 };
Eric Laurent484e9272018-06-07 17:29:23 -07007152
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307153 auto doGetOutputDevicesForVoice = [&]() {
7154 return hasVoiceStream(streams) && (outputDesc == mPrimaryOutput ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007155 outputDesc->isActive(toVolumeSource(AUDIO_STREAM_VOICE_CALL, false))) &&
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307156 (isInCall() ||
Henrik Backlund07c654a2021-10-14 15:57:10 +02007157 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc)) &&
7158 !isStreamActive(AUDIO_STREAM_ENFORCED_AUDIBLE, 0);
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307159 };
7160
7161 // With low-latency playing on speaker, music on WFD, when the first low-latency
7162 // output is stopped, getNewOutputDevices checks for a product strategy
7163 // from the list, as STRATEGY_SONIFICATION comes prior to STRATEGY_MEDIA.
Carter Hsucc58a6b2021-07-20 08:44:50 +00007164 // If an ALARM or ENFORCED_AUDIBLE stream is supported by the product strategy,
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307165 // devices are returned for STRATEGY_SONIFICATION without checking whether the
7166 // stream is associated to the output descriptor.
7167 if (doGetOutputDevicesForVoice() || outputDesc->isStrategyActive(productStrategy) ||
7168 ((hasStreamActive(AUDIO_STREAM_ALARM) ||
7169 hasStreamActive(AUDIO_STREAM_ENFORCED_AUDIBLE)) &&
7170 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc))) {
François Gaffiec005e562018-11-06 15:04:49 +01007171 // Retrieval of devices for voice DL is done on primary output profile, cannot
7172 // check the route (would force modifying configuration file for this profile)
jiangyao94780942024-03-05 10:43:14 +08007173 auto attr = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
François Gaffiec005e562018-11-06 15:04:49 +01007174 devices = mEngine->getOutputDevicesForAttributes(attr, nullptr, fromCache);
7175 break;
7176 }
Eric Laurente552edb2014-03-10 17:42:56 -07007177 }
François Gaffiec005e562018-11-06 15:04:49 +01007178 ALOGV("%s selected devices %s", __func__, devices.toString().c_str());
François Gaffie11d30102018-11-02 16:09:09 +01007179 return devices;
Eric Laurent1c333e22014-05-20 10:48:17 -07007180}
7181
François Gaffie11d30102018-11-02 16:09:09 +01007182sp<DeviceDescriptor> AudioPolicyManager::getNewInputDevice(
7183 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurent1c333e22014-05-20 10:48:17 -07007184{
François Gaffie11d30102018-11-02 16:09:09 +01007185 sp<DeviceDescriptor> device;
Eric Laurent6a94d692014-05-20 11:18:06 -07007186
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08007187 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007188 if (index >= 0) {
7189 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007190 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01007191 ALOGV("getNewInputDevice() device %s forced by patch %d",
7192 inputDesc->getDevice()->toString().c_str(), inputDesc->getPatchHandle());
7193 return inputDesc->getDevice();
Eric Laurent6a94d692014-05-20 11:18:06 -07007194 }
7195 }
7196
Eric Laurent97ac8712018-07-27 18:59:02 -07007197 // Honor explicit routing requests only if no client using default routing is active on this
7198 // input: a specific app can not force routing for other apps by setting a preferred device.
7199 bool active;
François Gaffie11d30102018-11-02 16:09:09 +01007200 device = findPreferredDevice(inputDesc, AUDIO_SOURCE_DEFAULT, active, mAvailableInputDevices);
7201 if (device != nullptr) {
7202 return device;
Eric Laurent97ac8712018-07-27 18:59:02 -07007203 }
7204
Eric Laurentdc95a252018-04-12 12:46:56 -07007205 // If we are not in call and no client is active on this input, this methods returns
Andy Hungf024a9e2019-01-30 16:01:02 -08007206 // a null sp<>, causing the patch on the input stream to be released.
yuanjiahsu0735bf32021-03-18 08:12:54 +08007207 audio_attributes_t attributes;
7208 uid_t uid;
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007209 audio_session_t session;
yuanjiahsu0735bf32021-03-18 08:12:54 +08007210 sp<RecordClientDescriptor> topClient = inputDesc->getHighestPriorityClient();
7211 if (topClient != nullptr) {
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01007212 attributes = topClient->attributes();
7213 uid = topClient->uid();
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007214 session = topClient->session();
yuanjiahsu0735bf32021-03-18 08:12:54 +08007215 } else {
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01007216 attributes = { .source = AUDIO_SOURCE_DEFAULT };
7217 uid = 0;
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007218 session = AUDIO_SESSION_NONE;
yuanjiahsu0735bf32021-03-18 08:12:54 +08007219 }
7220
Francois Gaffie716e1432019-01-14 16:58:59 +01007221 if (attributes.source == AUDIO_SOURCE_DEFAULT && isInCall()) {
7222 attributes.source = AUDIO_SOURCE_VOICE_COMMUNICATION;
Eric Laurentdc95a252018-04-12 12:46:56 -07007223 }
Francois Gaffie716e1432019-01-14 16:58:59 +01007224 if (attributes.source != AUDIO_SOURCE_DEFAULT) {
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007225 device = mEngine->getInputDeviceForAttributes(attributes, uid, session);
Eric Laurentfb66dd92016-01-28 18:32:03 -08007226 }
Eric Laurent1c333e22014-05-20 10:48:17 -07007227
Eric Laurente552edb2014-03-10 17:42:56 -07007228 return device;
7229}
7230
Eric Laurent794fde22016-03-11 09:50:45 -08007231bool AudioPolicyManager::streamsMatchForvolume(audio_stream_type_t stream1,
7232 audio_stream_type_t stream2) {
Jean-Michel Trivi99bb2f92016-11-23 15:52:07 -08007233 return (stream1 == stream2);
Eric Laurent28d09f02016-03-08 10:43:05 -08007234}
7235
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08007236status_t AudioPolicyManager::getDevicesForAttributes(
Andy Hung6d23c0f2022-02-16 09:37:15 -08007237 const audio_attributes_t &attr, AudioDeviceTypeAddrVector *devices, bool forVolume) {
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08007238 if (devices == nullptr) {
7239 return BAD_VALUE;
7240 }
Andy Hung6d23c0f2022-02-16 09:37:15 -08007241
Andy Hung6d23c0f2022-02-16 09:37:15 -08007242 DeviceVector curDevices;
jiabinf1c73972022-04-14 16:28:52 -07007243 if (status_t status = getDevicesForAttributes(attr, curDevices, forVolume); status != OK) {
7244 return status;
Andy Hung6d23c0f2022-02-16 09:37:15 -08007245 }
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08007246 for (const auto& device : curDevices) {
7247 devices->push_back(device->getDeviceTypeAddr());
7248 }
7249 return NO_ERROR;
7250}
7251
Eric Laurente0720872014-03-11 09:30:41 -07007252void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07007253 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07007254 case AUDIO_STREAM_MUSIC:
François Gaffiec005e562018-11-06 15:04:49 +01007255 checkOutputForAttributes(attributes_initializer(AUDIO_USAGE_NOTIFICATION));
Eric Laurente552edb2014-03-10 17:42:56 -07007256 updateDevicesAndOutputs();
7257 break;
7258 default:
7259 break;
7260 }
7261}
7262
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007263uint32_t AudioPolicyManager::handleEventForBeacon(int event) {
Eric Laurent9459fb02015-08-12 18:36:32 -07007264
7265 // skip beacon mute management if a dedicated TTS output is available
7266 if (mTtsOutputAvailable) {
7267 return 0;
7268 }
7269
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007270 switch(event) {
7271 case STARTING_OUTPUT:
7272 mBeaconMuteRefCount++;
7273 break;
7274 case STOPPING_OUTPUT:
7275 if (mBeaconMuteRefCount > 0) {
7276 mBeaconMuteRefCount--;
7277 }
7278 break;
7279 case STARTING_BEACON:
7280 mBeaconPlayingRefCount++;
7281 break;
7282 case STOPPING_BEACON:
7283 if (mBeaconPlayingRefCount > 0) {
7284 mBeaconPlayingRefCount--;
7285 }
7286 break;
7287 }
7288
7289 if (mBeaconMuteRefCount > 0) {
7290 // any playback causes beacon to be muted
7291 return setBeaconMute(true);
7292 } else {
7293 // no other playback: unmute when beacon starts playing, mute when it stops
7294 return setBeaconMute(mBeaconPlayingRefCount == 0);
7295 }
7296}
7297
7298uint32_t AudioPolicyManager::setBeaconMute(bool mute) {
7299 ALOGV("setBeaconMute(%d) mBeaconMuteRefCount=%d mBeaconPlayingRefCount=%d",
7300 mute, mBeaconMuteRefCount, mBeaconPlayingRefCount);
7301 // keep track of muted state to avoid repeating mute/unmute operations
7302 if (mBeaconMuted != mute) {
7303 // mute/unmute AUDIO_STREAM_TTS on all outputs
7304 ALOGV("\t muting %d", mute);
7305 uint32_t maxLatency = 0;
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007306 auto ttsVolumeSource = toVolumeSource(AUDIO_STREAM_TTS, false);
7307 if (ttsVolumeSource == VOLUME_SOURCE_NONE) {
7308 ALOGV("\t no tts volume source available");
7309 return 0;
7310 }
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007311 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07007312 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
jiabin9a3361e2019-10-01 09:38:30 -07007313 setVolumeSourceMute(ttsVolumeSource, mute/*on*/, desc, 0 /*delay*/, DeviceTypeSet());
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007314 const uint32_t latency = desc->latency() * 2;
Eric Laurentcdb2b352020-07-23 10:57:02 -07007315 if (desc->isActive(latency * 2) && latency > maxLatency) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007316 maxLatency = latency;
7317 }
7318 }
7319 mBeaconMuted = mute;
7320 return maxLatency;
7321 }
7322 return 0;
7323}
7324
Eric Laurente0720872014-03-11 09:30:41 -07007325void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07007326{
François Gaffiec005e562018-11-06 15:04:49 +01007327 mEngine->updateDeviceSelectionCache();
Eric Laurente552edb2014-03-10 17:42:56 -07007328 mPreviousOutputs = mOutputs;
7329}
7330
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07007331uint32_t AudioPolicyManager::checkDeviceMuteStrategies(const sp<AudioOutputDescriptor>& outputDesc,
François Gaffiec005e562018-11-06 15:04:49 +01007332 const DeviceVector &prevDevices,
Eric Laurente552edb2014-03-10 17:42:56 -07007333 uint32_t delayMs)
7334{
7335 // mute/unmute strategies using an incompatible device combination
7336 // if muting, wait for the audio in pcm buffer to be drained before proceeding
7337 // if unmuting, unmute only after the specified delay
7338 if (outputDesc->isDuplicated()) {
7339 return 0;
7340 }
7341
7342 uint32_t muteWaitMs = 0;
François Gaffiec005e562018-11-06 15:04:49 +01007343 DeviceVector devices = outputDesc->devices();
7344 bool shouldMute = outputDesc->isActive() && (devices.size() >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07007345
François Gaffiec005e562018-11-06 15:04:49 +01007346 auto productStrategies = mEngine->getOrderedProductStrategies();
7347 for (const auto &productStrategy : productStrategies) {
7348 auto attributes = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
7349 DeviceVector curDevices =
7350 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false/*fromCache*/);
7351 curDevices = curDevices.filter(outputDesc->supportedDevices());
7352 bool mute = shouldMute && curDevices.containsAtLeastOne(devices) && curDevices != devices;
Eric Laurente552edb2014-03-10 17:42:56 -07007353 bool doMute = false;
7354
François Gaffiec005e562018-11-06 15:04:49 +01007355 if (mute && !outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07007356 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01007357 outputDesc->setStrategyMutedByDevice(productStrategy, true);
7358 } else if (!mute && outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07007359 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01007360 outputDesc->setStrategyMutedByDevice(productStrategy, false);
Eric Laurente552edb2014-03-10 17:42:56 -07007361 }
Eric Laurent99401132014-05-07 19:48:15 -07007362 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07007363 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07007364 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07007365 // skip output if it does not share any device with current output
François Gaffie11d30102018-11-02 16:09:09 +01007366 if (!desc->supportedDevices().containsAtLeastOne(outputDesc->supportedDevices())) {
Eric Laurente552edb2014-03-10 17:42:56 -07007367 continue;
7368 }
François Gaffiec005e562018-11-06 15:04:49 +01007369 ALOGVV("%s() %s (curDevice %s)", __func__,
7370 mute ? "muting" : "unmuting", curDevices.toString().c_str());
7371 setStrategyMute(productStrategy, mute, desc, mute ? 0 : delayMs);
7372 if (desc->isStrategyActive(productStrategy)) {
Eric Laurent99401132014-05-07 19:48:15 -07007373 if (mute) {
7374 // FIXME: should not need to double latency if volume could be applied
7375 // immediately by the audioflinger mixer. We must account for the delay
7376 // between now and the next time the audioflinger thread for this output
7377 // will process a buffer (which corresponds to one buffer size,
7378 // usually 1/2 or 1/4 of the latency).
7379 if (muteWaitMs < desc->latency() * 2) {
7380 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07007381 }
7382 }
7383 }
7384 }
7385 }
7386 }
7387
Eric Laurent99401132014-05-07 19:48:15 -07007388 // temporary mute output if device selection changes to avoid volume bursts due to
7389 // different per device volumes
François Gaffiec005e562018-11-06 15:04:49 +01007390 if (outputDesc->isActive() && (devices != prevDevices)) {
Eric Laurentdc462862016-07-19 12:29:53 -07007391 uint32_t tempMuteWaitMs = outputDesc->latency() * 2;
Jasmine Chaf6074fe2021-08-17 13:44:31 +08007392
Eric Laurentdc462862016-07-19 12:29:53 -07007393 if (muteWaitMs < tempMuteWaitMs) {
7394 muteWaitMs = tempMuteWaitMs;
Eric Laurent99401132014-05-07 19:48:15 -07007395 }
Jasmine Chaf6074fe2021-08-17 13:44:31 +08007396
7397 // If recommended duration is defined, replace temporary mute duration to avoid
7398 // truncated notifications at beginning, which depends on duration of changing path in HAL.
7399 // Otherwise, temporary mute duration is conservatively set to 4 times the reported latency.
7400 uint32_t tempRecommendedMuteDuration = outputDesc->getRecommendedMuteDurationMs();
7401 uint32_t tempMuteDurationMs = tempRecommendedMuteDuration > 0 ?
7402 tempRecommendedMuteDuration : outputDesc->latency() * 4;
7403
François Gaffieaaac0fd2018-11-22 17:56:39 +01007404 for (const auto &activeVs : outputDesc->getActiveVolumeSources()) {
7405 // make sure that we do not start the temporary mute period too early in case of
7406 // delayed device change
7407 setVolumeSourceMute(activeVs, true, outputDesc, delayMs);
7408 setVolumeSourceMute(activeVs, false, outputDesc, delayMs + tempMuteDurationMs,
François Gaffiec005e562018-11-06 15:04:49 +01007409 devices.types());
Eric Laurent99401132014-05-07 19:48:15 -07007410 }
7411 }
7412
Eric Laurente552edb2014-03-10 17:42:56 -07007413 // wait for the PCM output buffers to empty before proceeding with the rest of the command
7414 if (muteWaitMs > delayMs) {
7415 muteWaitMs -= delayMs;
7416 usleep(muteWaitMs * 1000);
7417 return muteWaitMs;
7418 }
7419 return 0;
7420}
7421
François Gaffie11d30102018-11-02 16:09:09 +01007422uint32_t AudioPolicyManager::setOutputDevices(const sp<SwAudioOutputDescriptor>& outputDesc,
7423 const DeviceVector &devices,
7424 bool force,
7425 int delayMs,
7426 audio_patch_handle_t *patchHandle,
Oscar Azucena6acf34b2023-04-27 16:32:09 -07007427 bool requiresMuteCheck, bool requiresVolumeCheck,
7428 bool skipMuteDelay)
Eric Laurente552edb2014-03-10 17:42:56 -07007429{
jiabin3ff8d7d2022-12-13 06:27:44 +00007430 // TODO(b/262404095): Consider if the output need to be reopened.
François Gaffie11d30102018-11-02 16:09:09 +01007431 ALOGV("%s device %s delayMs %d", __func__, devices.toString().c_str(), delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07007432 uint32_t muteWaitMs;
7433
7434 if (outputDesc->isDuplicated()) {
François Gaffie11d30102018-11-02 16:09:09 +01007435 muteWaitMs = setOutputDevices(outputDesc->subOutput1(), devices, force, delayMs,
Oscar Azucena6acf34b2023-04-27 16:32:09 -07007436 nullptr /* patchHandle */, requiresMuteCheck, skipMuteDelay);
François Gaffie11d30102018-11-02 16:09:09 +01007437 muteWaitMs += setOutputDevices(outputDesc->subOutput2(), devices, force, delayMs,
Oscar Azucena6acf34b2023-04-27 16:32:09 -07007438 nullptr /* patchHandle */, requiresMuteCheck, skipMuteDelay);
Eric Laurente552edb2014-03-10 17:42:56 -07007439 return muteWaitMs;
7440 }
Eric Laurente552edb2014-03-10 17:42:56 -07007441
7442 // filter devices according to output selected
Francois Gaffie716e1432019-01-14 16:58:59 +01007443 DeviceVector filteredDevices = outputDesc->filterSupportedDevices(devices);
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01007444 DeviceVector prevDevices = outputDesc->devices();
Francois Gaffie3523ab32021-06-22 13:24:34 +02007445 DeviceVector availPrevDevices = mAvailableOutputDevices.filter(prevDevices);
Eric Laurente552edb2014-03-10 17:42:56 -07007446
François Gaffie11d30102018-11-02 16:09:09 +01007447 ALOGV("setOutputDevices() prevDevice %s", prevDevices.toString().c_str());
7448
7449 if (!filteredDevices.isEmpty()) {
7450 outputDesc->setDevices(filteredDevices);
Eric Laurente552edb2014-03-10 17:42:56 -07007451 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00007452
7453 // if the outputs are not materially active, there is no need to mute.
7454 if (requiresMuteCheck) {
François Gaffiec005e562018-11-06 15:04:49 +01007455 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevices, delayMs);
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00007456 } else {
7457 ALOGV("%s: suppressing checkDeviceMuteStrategies", __func__);
7458 muteWaitMs = 0;
7459 }
Eric Laurente552edb2014-03-10 17:42:56 -07007460
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02007461 bool outputRouted = outputDesc->isRouted();
7462
Eric Laurent79ea9582020-06-11 18:49:24 -07007463 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
7464 // output profile or if new device is not supported AND previous device(s) is(are) still
7465 // available (otherwise reset device must be done on the output)
Francois Gaffie3523ab32021-06-22 13:24:34 +02007466 if (!devices.isEmpty() && filteredDevices.isEmpty() && !availPrevDevices.empty()) {
Eric Laurent79ea9582020-06-11 18:49:24 -07007467 ALOGV("%s: unsupported device %s for output", __func__, devices.toString().c_str());
7468 // restore previous device after evaluating strategy mute state
7469 outputDesc->setDevices(prevDevices);
7470 return muteWaitMs;
7471 }
7472
Eric Laurente552edb2014-03-10 17:42:56 -07007473 // Do not change the routing if:
Eric Laurentb80a2a82014-10-27 16:07:59 -07007474 // the requested device is AUDIO_DEVICE_NONE
7475 // OR the requested device is the same as current device
7476 // AND force is not specified
7477 // AND the output is connected by a valid audio patch.
François Gaffie11d30102018-11-02 16:09:09 +01007478 // Doing this check here allows the caller to call setOutputDevices() without conditions
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02007479 if ((filteredDevices.isEmpty() || filteredDevices == prevDevices) && !force && outputRouted) {
François Gaffie11d30102018-11-02 16:09:09 +01007480 ALOGV("%s setting same device %s or null device, force=%d, patch handle=%d", __func__,
7481 filteredDevices.toString().c_str(), force, outputDesc->getPatchHandle());
Francois Gaffie3523ab32021-06-22 13:24:34 +02007482 if (requiresVolumeCheck && !filteredDevices.isEmpty()) {
7483 ALOGV("%s setting same device on routed output, force apply volumes", __func__);
7484 applyStreamVolumes(outputDesc, filteredDevices.types(), delayMs, true /*force*/);
7485 }
Eric Laurente552edb2014-03-10 17:42:56 -07007486 return muteWaitMs;
7487 }
7488
François Gaffie11d30102018-11-02 16:09:09 +01007489 ALOGV("%s changing device to %s", __func__, filteredDevices.toString().c_str());
Eric Laurent1c333e22014-05-20 10:48:17 -07007490
Eric Laurente552edb2014-03-10 17:42:56 -07007491 // do the routing
Francois Gaffie3523ab32021-06-22 13:24:34 +02007492 if (filteredDevices.isEmpty() || mAvailableOutputDevices.filter(filteredDevices).empty()) {
Eric Laurentc75307b2015-03-17 15:29:32 -07007493 resetOutputDevice(outputDesc, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07007494 } else {
François Gaffie11d30102018-11-02 16:09:09 +01007495 PatchBuilder patchBuilder;
7496 patchBuilder.addSource(outputDesc);
7497 ALOG_ASSERT(filteredDevices.size() <= AUDIO_PATCH_PORTS_MAX, "Too many sink ports");
7498 for (const auto &filteredDevice : filteredDevices) {
7499 patchBuilder.addSink(filteredDevice);
Eric Laurentc40d9692016-04-13 19:14:13 -07007500 }
7501
Jasmine Cha7f82d1a2020-03-16 13:21:47 +08007502 // Add half reported latency to delayMs when muteWaitMs is null in order
7503 // to avoid disordered sequence of muting volume and changing devices.
Oscar Azucena6acf34b2023-04-27 16:32:09 -07007504 int actualDelayMs = !skipMuteDelay && muteWaitMs == 0
7505 ? (delayMs + (outputDesc->latency() / 2)) : delayMs;
7506 installPatch(__func__, patchHandle, outputDesc.get(), patchBuilder.patch(), actualDelayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07007507 }
Eric Laurente552edb2014-03-10 17:42:56 -07007508
Oscar Azucena6acf34b2023-04-27 16:32:09 -07007509 // Since the mute is skip, also skip the apply stream volume as that will be applied externally
7510 if (!skipMuteDelay) {
7511 // update stream volumes according to new device
7512 applyStreamVolumes(outputDesc, filteredDevices.types(), delayMs);
7513 }
Eric Laurente552edb2014-03-10 17:42:56 -07007514
7515 return muteWaitMs;
7516}
7517
Eric Laurentc75307b2015-03-17 15:29:32 -07007518status_t AudioPolicyManager::resetOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurent6a94d692014-05-20 11:18:06 -07007519 int delayMs,
7520 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07007521{
Eric Laurent6a94d692014-05-20 11:18:06 -07007522 ssize_t index;
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02007523 if (patchHandle == nullptr && !outputDesc->isRouted()) {
7524 return INVALID_OPERATION;
7525 }
Eric Laurent6a94d692014-05-20 11:18:06 -07007526 if (patchHandle) {
7527 index = mAudioPatches.indexOfKey(*patchHandle);
7528 } else {
Jean-Michel Triviff155c62016-02-26 12:07:16 -08007529 index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007530 }
7531 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07007532 return INVALID_OPERATION;
7533 }
Eric Laurent6a94d692014-05-20 11:18:06 -07007534 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007535 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07007536 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07007537 outputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
François Gaffieafd4cea2019-11-18 15:50:22 +01007538 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007539 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07007540 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07007541 return status;
7542}
7543
7544status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
François Gaffie11d30102018-11-02 16:09:09 +01007545 const sp<DeviceDescriptor> &device,
Eric Laurent6a94d692014-05-20 11:18:06 -07007546 bool force,
7547 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07007548{
7549 status_t status = NO_ERROR;
7550
Eric Laurent1f2f2232014-06-02 12:01:23 -07007551 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
François Gaffie11d30102018-11-02 16:09:09 +01007552 if ((device != nullptr) && ((device != inputDesc->getDevice()) || force)) {
7553 inputDesc->setDevice(device);
Eric Laurent1c333e22014-05-20 10:48:17 -07007554
François Gaffie11d30102018-11-02 16:09:09 +01007555 if (mAvailableInputDevices.contains(device)) {
Mikhail Naganovdc769682018-05-04 15:34:08 -07007556 PatchBuilder patchBuilder;
7557 patchBuilder.addSink(inputDesc,
Eric Laurentdaf92cc2014-07-22 15:36:10 -07007558 // AUDIO_SOURCE_HOTWORD is for internal use only:
7559 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
Mikhail Naganovdc769682018-05-04 15:34:08 -07007560 [inputDesc](const PatchBuilder::mix_usecase_t& usecase) {
7561 auto result = usecase;
7562 if (result.source == AUDIO_SOURCE_HOTWORD && !inputDesc->isSoundTrigger()) {
7563 result.source = AUDIO_SOURCE_VOICE_RECOGNITION;
7564 }
7565 return result; }).
Eric Laurent1c333e22014-05-20 10:48:17 -07007566 //only one input device for now
François Gaffie11d30102018-11-02 16:09:09 +01007567 addSource(device);
Mikhail Naganovdc769682018-05-04 15:34:08 -07007568 status = installPatch(__func__, patchHandle, inputDesc.get(), patchBuilder.patch(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07007569 }
7570 }
7571 return status;
7572}
7573
Eric Laurent6a94d692014-05-20 11:18:06 -07007574status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
7575 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07007576{
Eric Laurent1f2f2232014-06-02 12:01:23 -07007577 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07007578 ssize_t index;
7579 if (patchHandle) {
7580 index = mAudioPatches.indexOfKey(*patchHandle);
7581 } else {
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08007582 index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007583 }
7584 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07007585 return INVALID_OPERATION;
7586 }
Eric Laurent6a94d692014-05-20 11:18:06 -07007587 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007588 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07007589 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07007590 inputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
François Gaffieafd4cea2019-11-18 15:50:22 +01007591 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007592 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07007593 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07007594 return status;
7595}
7596
François Gaffie11d30102018-11-02 16:09:09 +01007597sp<IOProfile> AudioPolicyManager::getInputProfile(const sp<DeviceDescriptor> &device,
François Gaffie53615e22015-03-19 09:24:12 +01007598 uint32_t& samplingRate,
Andy Hungf129b032015-04-07 13:45:50 -07007599 audio_format_t& format,
7600 audio_channel_mask_t& channelMask,
François Gaffie53615e22015-03-19 09:24:12 +01007601 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07007602{
7603 // Choose an input profile based on the requested capture parameters: select the first available
7604 // profile supporting all requested parameters.
jiabin2fd710d2022-05-02 23:20:22 +00007605 // The flags can be ignored if it doesn't contain a much match flag.
Andy Hungf129b032015-04-07 13:45:50 -07007606 //
7607 // TODO: perhaps isCompatibleProfile should return a "matching" score so we can return
7608 // the best matching profile, not the first one.
Eric Laurente552edb2014-03-10 17:42:56 -07007609
Atneya Nair0f0a8032022-12-12 16:20:12 -08007610 using underlying_input_flag_t = std::underlying_type_t<audio_input_flags_t>;
7611 const underlying_input_flag_t mustMatchFlag = AUDIO_INPUT_FLAG_MMAP_NOIRQ |
7612 AUDIO_INPUT_FLAG_HOTWORD_TAP | AUDIO_INPUT_FLAG_HW_LOOKBACK;
7613
7614 const underlying_input_flag_t oriFlags = flags;
Glenn Kasten730b9262018-03-29 15:01:26 -07007615
jiabin2fd710d2022-05-02 23:20:22 +00007616 for (;;) {
7617 sp<IOProfile> firstInexact = nullptr;
7618 uint32_t updatedSamplingRate = 0;
7619 audio_format_t updatedFormat = AUDIO_FORMAT_INVALID;
7620 audio_channel_mask_t updatedChannelMask = AUDIO_CHANNEL_INVALID;
7621 for (const auto& hwModule : mHwModules) {
7622 for (const auto& profile : hwModule->getInputProfiles()) {
7623 // profile->log();
7624 //updatedFormat = format;
7625 if (profile->isCompatibleProfile(DeviceVector(device), samplingRate,
7626 &samplingRate /*updatedSamplingRate*/,
7627 format,
7628 &format, /*updatedFormat*/
7629 channelMask,
7630 &channelMask /*updatedChannelMask*/,
7631 // FIXME ugly cast
7632 (audio_output_flags_t) flags,
7633 true /*exactMatchRequiredForInputFlags*/)) {
7634 return profile;
7635 }
7636 if (firstInexact == nullptr && profile->isCompatibleProfile(DeviceVector(device),
7637 samplingRate,
7638 &updatedSamplingRate,
7639 format,
7640 &updatedFormat,
7641 channelMask,
7642 &updatedChannelMask,
7643 // FIXME ugly cast
7644 (audio_output_flags_t) flags,
7645 false /*exactMatchRequiredForInputFlags*/)) {
7646 firstInexact = profile;
7647 }
7648 }
7649 }
7650
7651 if (firstInexact != nullptr) {
7652 samplingRate = updatedSamplingRate;
7653 format = updatedFormat;
7654 channelMask = updatedChannelMask;
7655 return firstInexact;
7656 } else if (flags & AUDIO_INPUT_FLAG_RAW) {
7657 flags = (audio_input_flags_t) (flags & ~AUDIO_INPUT_FLAG_RAW); // retry
7658 } else if ((flags & mustMatchFlag) == AUDIO_INPUT_FLAG_NONE &&
7659 flags != AUDIO_INPUT_FLAG_NONE && audio_is_linear_pcm(format)) {
7660 flags = AUDIO_INPUT_FLAG_NONE;
7661 } else { // fail
7662 ALOGW("%s could not find profile for device %s, sampling rate %u, format %#x, "
7663 "channel mask 0x%X, flags %#x", __func__, device->toString().c_str(),
7664 samplingRate, format, channelMask, oriFlags);
7665 break;
Eric Laurente552edb2014-03-10 17:42:56 -07007666 }
7667 }
jiabin2fd710d2022-05-02 23:20:22 +00007668
7669 return nullptr;
Eric Laurente552edb2014-03-10 17:42:56 -07007670}
7671
François Gaffieaaac0fd2018-11-22 17:56:39 +01007672float AudioPolicyManager::computeVolume(IVolumeCurves &curves,
7673 VolumeSource volumeSource,
François Gaffied1ab2bd2015-12-02 18:20:06 +01007674 int index,
jiabin9a3361e2019-10-01 09:38:30 -07007675 const DeviceTypeSet& deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07007676{
jiabin9a3361e2019-10-01 09:38:30 -07007677 float volumeDb = curves.volIndexToDb(Volume::getDeviceCategory(deviceTypes), index);
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07007678
7679 // handle the case of accessibility active while a ringtone is playing: if the ringtone is much
7680 // louder than the accessibility prompt, the prompt cannot be heard, thus masking the touch
7681 // exploration of the dialer UI. In this situation, bring the accessibility volume closer to
7682 // the ringtone volume
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007683 const auto callVolumeSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL, false);
7684 const auto ringVolumeSrc = toVolumeSource(AUDIO_STREAM_RING, false);
7685 const auto musicVolumeSrc = toVolumeSource(AUDIO_STREAM_MUSIC, false);
7686 const auto alarmVolumeSrc = toVolumeSource(AUDIO_STREAM_ALARM, false);
7687 const auto a11yVolumeSrc = toVolumeSource(AUDIO_STREAM_ACCESSIBILITY, false);
Oscar Azucena5300db62023-08-30 18:45:18 -07007688 // Verify that the current volume source is not the ringer volume to prevent recursively
7689 // calling to compute volume. This could happen in cases where a11y and ringer sounds belong
7690 // to the same volume group.
7691 if (volumeSource != ringVolumeSrc && volumeSource == a11yVolumeSrc
François Gaffieaaac0fd2018-11-22 17:56:39 +01007692 && (AUDIO_MODE_RINGTONE == mEngine->getPhoneState()) &&
7693 mOutputs.isActive(ringVolumeSrc, 0)) {
7694 auto &ringCurves = getVolumeCurves(AUDIO_STREAM_RING);
jiabin9a3361e2019-10-01 09:38:30 -07007695 const float ringVolumeDb = computeVolume(ringCurves, ringVolumeSrc, index, deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007696 return ringVolumeDb - 4 > volumeDb ? ringVolumeDb - 4 : volumeDb;
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07007697 }
7698
Eric Laurentdcd4ab12018-06-29 17:45:13 -07007699 // in-call: always cap volume by voice volume + some low headroom
François Gaffieaaac0fd2018-11-22 17:56:39 +01007700 if ((volumeSource != callVolumeSrc && (isInCall() ||
7701 mOutputs.isActiveLocally(callVolumeSrc))) &&
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007702 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM, false) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01007703 volumeSource == ringVolumeSrc || volumeSource == musicVolumeSrc ||
7704 volumeSource == alarmVolumeSrc ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007705 volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION, false) ||
7706 volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false) ||
7707 volumeSource == toVolumeSource(AUDIO_STREAM_DTMF, false) ||
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07007708 volumeSource == a11yVolumeSrc)) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007709 auto &voiceCurves = getVolumeCurves(callVolumeSrc);
jiabin9a3361e2019-10-01 09:38:30 -07007710 int voiceVolumeIndex = voiceCurves.getVolumeIndex(deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007711 const float maxVoiceVolDb =
jiabin9a3361e2019-10-01 09:38:30 -07007712 computeVolume(voiceCurves, callVolumeSrc, voiceVolumeIndex, deviceTypes)
Eric Laurent7731b5a2018-04-06 15:47:22 -07007713 + IN_CALL_EARPIECE_HEADROOM_DB;
Abhijith Shastry329ddab2019-04-23 11:53:26 -07007714 // FIXME: Workaround for call screening applications until a proper audio mode is defined
7715 // to support this scenario : Exempt the RING stream from the audio cap if the audio was
7716 // programmatically muted.
7717 // VOICE_CALL stream has minVolumeIndex > 0 : Users cannot set the volume of voice calls to
7718 // 0. We don't want to cap volume when the system has programmatically muted the voice call
7719 // stream. See setVolumeCurveIndex() for more information.
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07007720 bool exemptFromCapping =
7721 ((volumeSource == ringVolumeSrc) || (volumeSource == a11yVolumeSrc))
7722 && (voiceVolumeIndex == 0);
Abhijith Shastry329ddab2019-04-23 11:53:26 -07007723 ALOGV_IF(exemptFromCapping, "%s volume source %d at vol=%f not capped", __func__,
7724 volumeSource, volumeDb);
7725 if ((volumeDb > maxVoiceVolDb) && !exemptFromCapping) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007726 ALOGV("%s volume source %d at vol=%f overriden by volume group %d at vol=%f", __func__,
7727 volumeSource, volumeDb, callVolumeSrc, maxVoiceVolDb);
7728 volumeDb = maxVoiceVolDb;
Jean-Michel Trivi719a9872017-08-05 13:51:35 -07007729 }
7730 }
Eric Laurente552edb2014-03-10 17:42:56 -07007731 // if a headset is connected, apply the following rules to ring tones and notifications
7732 // to avoid sound level bursts in user's ears:
Eric Laurent6af1c1d2016-04-14 11:20:44 -07007733 // - always attenuate notifications volume by 6dB
7734 // - attenuate ring tones volume by 6dB unless music is not playing and
7735 // speaker is part of the select devices
Eric Laurente552edb2014-03-10 17:42:56 -07007736 // - if music is playing, always limit the volume to current music volume,
7737 // with a minimum threshold at -36dB so that notification is always perceived.
jiabin9a3361e2019-10-01 09:38:30 -07007738 if (!Intersection(deviceTypes,
7739 {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP, AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES,
7740 AUDIO_DEVICE_OUT_WIRED_HEADSET, AUDIO_DEVICE_OUT_WIRED_HEADPHONE,
Eric Laurentc42df452020-08-07 10:51:53 -07007741 AUDIO_DEVICE_OUT_USB_HEADSET, AUDIO_DEVICE_OUT_HEARING_AID,
7742 AUDIO_DEVICE_OUT_BLE_HEADSET}).empty() &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01007743 ((volumeSource == alarmVolumeSrc ||
7744 volumeSource == ringVolumeSrc) ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007745 (volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION, false)) ||
7746 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM, false)) ||
7747 ((volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false)) &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01007748 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) &&
7749 curves.canBeMuted()) {
7750
Eric Laurente552edb2014-03-10 17:42:56 -07007751 // when the phone is ringing we must consider that music could have been paused just before
7752 // by the music application and behave as if music was active if the last music track was
7753 // just stopped
Oscar Azucena5300db62023-08-30 18:45:18 -07007754 // Verify that the current volume source is not the music volume to prevent recursively
7755 // calling to compute volume. This could happen in cases where music and
7756 // (alarm, ring, notification, system, etc.) sounds belong to the same volume group.
7757 if (volumeSource != musicVolumeSrc &&
7758 (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY)
7759 || mLimitRingtoneVolume)) {
François Gaffie43c73442018-11-08 08:21:55 +01007760 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
jiabin9a3361e2019-10-01 09:38:30 -07007761 DeviceTypeSet musicDevice =
François Gaffiec005e562018-11-06 15:04:49 +01007762 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
7763 nullptr, true /*fromCache*/).types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01007764 auto &musicCurves = getVolumeCurves(AUDIO_STREAM_MUSIC);
jiabin9a3361e2019-10-01 09:38:30 -07007765 float musicVolDb = computeVolume(musicCurves,
7766 musicVolumeSrc,
7767 musicCurves.getVolumeIndex(musicDevice),
7768 musicDevice);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007769 float minVolDb = (musicVolDb > SONIFICATION_HEADSET_VOLUME_MIN_DB) ?
7770 musicVolDb : SONIFICATION_HEADSET_VOLUME_MIN_DB;
7771 if (volumeDb > minVolDb) {
7772 volumeDb = minVolDb;
7773 ALOGV("computeVolume limiting volume to %f musicVol %f", minVolDb, musicVolDb);
Eric Laurente552edb2014-03-10 17:42:56 -07007774 }
Eric Laurent7b6385c2021-05-12 17:55:36 +02007775 if (Volume::getDeviceForVolume(deviceTypes) != AUDIO_DEVICE_OUT_SPEAKER
7776 && !Intersection(deviceTypes, {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP,
7777 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES}).empty()) {
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07007778 // on A2DP, also ensure notification volume is not too low compared to media when
7779 // intended to be played
François Gaffie43c73442018-11-08 08:21:55 +01007780 if ((volumeDb > -96.0f) &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01007781 (musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB > volumeDb)) {
jiabin9a3361e2019-10-01 09:38:30 -07007782 ALOGV("%s increasing volume for volume source=%d device=%s from %f to %f",
7783 __func__, volumeSource, dumpDeviceTypes(deviceTypes).c_str(), volumeDb,
François Gaffieaaac0fd2018-11-22 17:56:39 +01007784 musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB);
7785 volumeDb = musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB;
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07007786 }
7787 }
jiabin9a3361e2019-10-01 09:38:30 -07007788 } else if ((Volume::getDeviceForVolume(deviceTypes) != AUDIO_DEVICE_OUT_SPEAKER) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01007789 (!(volumeSource == alarmVolumeSrc || volumeSource == ringVolumeSrc))) {
François Gaffie43c73442018-11-08 08:21:55 +01007790 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07007791 }
7792 }
7793
François Gaffie43c73442018-11-08 08:21:55 +01007794 return volumeDb;
Eric Laurente552edb2014-03-10 17:42:56 -07007795}
7796
Eric Laurent3839bc02018-07-10 18:33:34 -07007797int AudioPolicyManager::rescaleVolumeIndex(int srcIndex,
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01007798 VolumeSource fromVolumeSource,
7799 VolumeSource toVolumeSource)
Eric Laurent3839bc02018-07-10 18:33:34 -07007800{
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01007801 if (fromVolumeSource == toVolumeSource) {
Eric Laurent3839bc02018-07-10 18:33:34 -07007802 return srcIndex;
7803 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01007804 auto &srcCurves = getVolumeCurves(fromVolumeSource);
7805 auto &dstCurves = getVolumeCurves(toVolumeSource);
Eric Laurentf5aa58d2019-02-22 18:20:11 -08007806 float minSrc = (float)srcCurves.getVolumeIndexMin();
7807 float maxSrc = (float)srcCurves.getVolumeIndexMax();
7808 float minDst = (float)dstCurves.getVolumeIndexMin();
7809 float maxDst = (float)dstCurves.getVolumeIndexMax();
Eric Laurent3839bc02018-07-10 18:33:34 -07007810
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08007811 // preserve mute request or correct range
7812 if (srcIndex < minSrc) {
7813 if (srcIndex == 0) {
7814 return 0;
7815 }
7816 srcIndex = minSrc;
7817 } else if (srcIndex > maxSrc) {
7818 srcIndex = maxSrc;
7819 }
Eric Laurent3839bc02018-07-10 18:33:34 -07007820 return (int)(minDst + ((srcIndex - minSrc) * (maxDst - minDst)) / (maxSrc - minSrc));
7821}
7822
François Gaffieaaac0fd2018-11-22 17:56:39 +01007823status_t AudioPolicyManager::checkAndSetVolume(IVolumeCurves &curves,
7824 VolumeSource volumeSource,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08007825 int index,
7826 const sp<AudioOutputDescriptor>& outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07007827 DeviceTypeSet deviceTypes,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08007828 int delayMs,
7829 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07007830{
François Gaffieaaac0fd2018-11-22 17:56:39 +01007831 // do not change actual attributes volume if the attributes is muted
7832 if (outputDesc->isMuted(volumeSource)) {
7833 ALOGVV("%s: volume source %d muted count %d active=%d", __func__, volumeSource,
7834 outputDesc->getMuteCount(volumeSource), outputDesc->isActive(volumeSource));
Eric Laurente552edb2014-03-10 17:42:56 -07007835 return NO_ERROR;
7836 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01007837
Eric Laurent5baf07c2024-01-11 16:57:27 +00007838 bool isVoiceVolSrc;
7839 bool isBtScoVolSrc;
7840 if (!isVolumeConsistentForCalls(
7841 volumeSource, deviceTypes, isVoiceVolSrc, isBtScoVolSrc, __func__)) {
Eric Laurent571ef962020-07-24 11:43:48 -07007842 // Do not return an error here as AudioService will always set both voice call
Eric Laurent5baf07c2024-01-11 16:57:27 +00007843 // and Bluetooth SCO volumes due to stream aliasing.
Eric Laurent571ef962020-07-24 11:43:48 -07007844 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07007845 }
Eric Laurent5baf07c2024-01-11 16:57:27 +00007846
jiabin9a3361e2019-10-01 09:38:30 -07007847 if (deviceTypes.empty()) {
7848 deviceTypes = outputDesc->devices().types();
chenxin2080986da2023-07-17 11:45:21 +08007849 index = curves.getVolumeIndex(deviceTypes);
7850 ALOGD("%s if deviceTypes is change from none to device %s, need get index %d",
7851 __func__, dumpDeviceTypes(deviceTypes).c_str(), index);
Eric Laurentc75307b2015-03-17 15:29:32 -07007852 }
Eric Laurent275e8e92014-11-30 15:14:47 -08007853
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00007854 if (curves.getVolumeIndexMin() < 0 || curves.getVolumeIndexMax() < 0) {
7855 ALOGE("invalid volume index range");
7856 return BAD_VALUE;
7857 }
7858
jiabin9a3361e2019-10-01 09:38:30 -07007859 float volumeDb = computeVolume(curves, volumeSource, index, deviceTypes);
7860 if (outputDesc->isFixedVolume(deviceTypes) ||
Eric Laurent9698a4c2020-10-12 17:10:23 -07007861 // Force VoIP volume to max for bluetooth SCO device except if muted
7862 (index != 0 && (isVoiceVolSrc || isBtScoVolSrc) &&
jiabin9a3361e2019-10-01 09:38:30 -07007863 isSingleDeviceType(deviceTypes, audio_is_bluetooth_out_sco_device))) {
Eric Laurentffbc80f2015-03-18 18:30:19 -07007864 volumeDb = 0.0f;
Eric Laurent275e8e92014-11-30 15:14:47 -08007865 }
Francois Gaffie593634d2021-06-22 13:31:31 +02007866 const bool muted = (index == 0) && (volumeDb != 0.0f);
Eric Laurent31a428a2023-08-11 12:16:28 +02007867 outputDesc->setVolume(volumeDb, muted, volumeSource, curves.getStreamTypes(),
7868 deviceTypes, delayMs, force, isVoiceVolSrc);
Eric Laurentc75307b2015-03-17 15:29:32 -07007869
Eric Laurente8f2c0f2021-08-17 11:17:19 +02007870 if (outputDesc == mPrimaryOutput && (isVoiceVolSrc || isBtScoVolSrc)) {
Eric Laurent5baf07c2024-01-11 16:57:27 +00007871 setVoiceVolume(index, curves, isVoiceVolSrc, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07007872 }
Eric Laurente552edb2014-03-10 17:42:56 -07007873 return NO_ERROR;
7874}
7875
Eric Laurent5baf07c2024-01-11 16:57:27 +00007876void AudioPolicyManager::setVoiceVolume(
7877 int index, IVolumeCurves &curves, bool isVoiceVolSrc, int delayMs) {
7878 float voiceVolume;
7879 // Force voice volume to max or mute for Bluetooth SCO as other attenuations are managed
7880 // by the headset
7881 if (isVoiceVolSrc) {
7882 voiceVolume = (float)index/(float)curves.getVolumeIndexMax();
7883 } else {
7884 voiceVolume = index == 0 ? 0.0 : 1.0;
7885 }
7886 if (voiceVolume != mLastVoiceVolume) {
7887 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
7888 mLastVoiceVolume = voiceVolume;
7889 }
7890}
7891
7892bool AudioPolicyManager::isVolumeConsistentForCalls(VolumeSource volumeSource,
7893 const DeviceTypeSet& deviceTypes,
7894 bool& isVoiceVolSrc,
7895 bool& isBtScoVolSrc,
7896 const char* caller) {
7897 const VolumeSource callVolSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL, false);
7898 const VolumeSource btScoVolSrc = toVolumeSource(AUDIO_STREAM_BLUETOOTH_SCO, false);
7899 const bool isScoRequested = isScoRequestedForComm();
7900 const bool isHAUsed = isHearingAidUsedForComm();
7901
7902 isVoiceVolSrc = (volumeSource != VOLUME_SOURCE_NONE) && (callVolSrc == volumeSource);
7903 isBtScoVolSrc = (volumeSource != VOLUME_SOURCE_NONE) && (btScoVolSrc == volumeSource);
7904
7905 if ((callVolSrc != btScoVolSrc) &&
7906 ((isVoiceVolSrc && isScoRequested) ||
7907 (isBtScoVolSrc && !(isScoRequested || isHAUsed))) &&
7908 !isSingleDeviceType(deviceTypes, AUDIO_DEVICE_OUT_TELEPHONY_TX)) {
7909 ALOGV("%s cannot set volume group %d volume when is%srequested for comm", caller,
7910 volumeSource, isScoRequested ? " " : " not ");
7911 return false;
7912 }
7913 return true;
7914}
7915
Eric Laurentc75307b2015-03-17 15:29:32 -07007916void AudioPolicyManager::applyStreamVolumes(const sp<AudioOutputDescriptor>& outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07007917 const DeviceTypeSet& deviceTypes,
7918 int delayMs,
7919 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07007920{
jiabincd510522020-01-22 09:40:55 -08007921 ALOGVV("applyStreamVolumes() for device %s", dumpDeviceTypes(deviceTypes).c_str());
François Gaffieaaac0fd2018-11-22 17:56:39 +01007922 for (const auto &volumeGroup : mEngine->getVolumeGroups()) {
7923 auto &curves = getVolumeCurves(toVolumeSource(volumeGroup));
7924 checkAndSetVolume(curves, toVolumeSource(volumeGroup),
jiabin9a3361e2019-10-01 09:38:30 -07007925 curves.getVolumeIndex(deviceTypes),
7926 outputDesc, deviceTypes, delayMs, force);
Eric Laurente552edb2014-03-10 17:42:56 -07007927 }
7928}
7929
François Gaffiec005e562018-11-06 15:04:49 +01007930void AudioPolicyManager::setStrategyMute(product_strategy_t strategy,
7931 bool on,
7932 const sp<AudioOutputDescriptor>& outputDesc,
7933 int delayMs,
jiabin9a3361e2019-10-01 09:38:30 -07007934 DeviceTypeSet deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07007935{
François Gaffieaaac0fd2018-11-22 17:56:39 +01007936 std::vector<VolumeSource> sourcesToMute;
7937 for (auto attributes: mEngine->getAllAttributesForProductStrategy(strategy)) {
7938 ALOGVV("%s() attributes %s, mute %d, output ID %d", __func__,
7939 toString(attributes).c_str(), on, outputDesc->getId());
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007940 VolumeSource source = toVolumeSource(attributes, false);
7941 if ((source != VOLUME_SOURCE_NONE) &&
7942 (std::find(begin(sourcesToMute), end(sourcesToMute), source)
7943 == end(sourcesToMute))) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007944 sourcesToMute.push_back(source);
7945 }
Eric Laurente552edb2014-03-10 17:42:56 -07007946 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01007947 for (auto source : sourcesToMute) {
jiabin9a3361e2019-10-01 09:38:30 -07007948 setVolumeSourceMute(source, on, outputDesc, delayMs, deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007949 }
7950
Eric Laurente552edb2014-03-10 17:42:56 -07007951}
7952
François Gaffieaaac0fd2018-11-22 17:56:39 +01007953void AudioPolicyManager::setVolumeSourceMute(VolumeSource volumeSource,
7954 bool on,
7955 const sp<AudioOutputDescriptor>& outputDesc,
7956 int delayMs,
jiabin9a3361e2019-10-01 09:38:30 -07007957 DeviceTypeSet deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07007958{
jiabin9a3361e2019-10-01 09:38:30 -07007959 if (deviceTypes.empty()) {
7960 deviceTypes = outputDesc->devices().types();
Eric Laurente552edb2014-03-10 17:42:56 -07007961 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01007962 auto &curves = getVolumeCurves(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07007963 if (on) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007964 if (!outputDesc->isMuted(volumeSource)) {
Eric Laurentf5aa58d2019-02-22 18:20:11 -08007965 if (curves.canBeMuted() &&
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007966 (volumeSource != toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01007967 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) ==
7968 AUDIO_POLICY_FORCE_NONE))) {
jiabin9a3361e2019-10-01 09:38:30 -07007969 checkAndSetVolume(curves, volumeSource, 0, outputDesc, deviceTypes, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07007970 }
7971 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01007972 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not
7973 // ignored
7974 outputDesc->incMuteCount(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07007975 } else {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007976 if (!outputDesc->isMuted(volumeSource)) {
7977 ALOGV("%s unmuting non muted attributes!", __func__);
Eric Laurente552edb2014-03-10 17:42:56 -07007978 return;
7979 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01007980 if (outputDesc->decMuteCount(volumeSource) == 0) {
7981 checkAndSetVolume(curves, volumeSource,
jiabin9a3361e2019-10-01 09:38:30 -07007982 curves.getVolumeIndex(deviceTypes),
Eric Laurentc75307b2015-03-17 15:29:32 -07007983 outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07007984 deviceTypes,
Eric Laurente552edb2014-03-10 17:42:56 -07007985 delayMs);
7986 }
7987 }
7988}
7989
François Gaffie53615e22015-03-19 09:24:12 +01007990bool AudioPolicyManager::isValidAttributes(const audio_attributes_t *paa)
7991{
François Gaffiec005e562018-11-06 15:04:49 +01007992 // has flags that map to a stream type?
Eric Laurente83b55d2014-11-14 10:06:21 -08007993 if ((paa->flags & (AUDIO_FLAG_AUDIBILITY_ENFORCED | AUDIO_FLAG_SCO | AUDIO_FLAG_BEACON)) != 0) {
7994 return true;
7995 }
7996
7997 // has known usage?
7998 switch (paa->usage) {
7999 case AUDIO_USAGE_UNKNOWN:
8000 case AUDIO_USAGE_MEDIA:
8001 case AUDIO_USAGE_VOICE_COMMUNICATION:
8002 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
8003 case AUDIO_USAGE_ALARM:
8004 case AUDIO_USAGE_NOTIFICATION:
8005 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
8006 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
8007 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
8008 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
8009 case AUDIO_USAGE_NOTIFICATION_EVENT:
8010 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
8011 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
8012 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
8013 case AUDIO_USAGE_GAME:
Eric Laurent275e8e92014-11-30 15:14:47 -08008014 case AUDIO_USAGE_VIRTUAL_SOURCE:
Jean-Michel Trivi36867762016-12-29 12:03:28 -08008015 case AUDIO_USAGE_ASSISTANT:
Eric Laurent21777f82019-12-06 18:12:06 -08008016 case AUDIO_USAGE_CALL_ASSISTANT:
Hayden Gomes524159d2019-12-23 14:41:47 -08008017 case AUDIO_USAGE_EMERGENCY:
8018 case AUDIO_USAGE_SAFETY:
8019 case AUDIO_USAGE_VEHICLE_STATUS:
8020 case AUDIO_USAGE_ANNOUNCEMENT:
Eric Laurente83b55d2014-11-14 10:06:21 -08008021 break;
8022 default:
8023 return false;
8024 }
8025 return true;
8026}
8027
François Gaffie2110e042015-03-24 08:41:51 +01008028audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
8029{
8030 return mEngine->getForceUse(usage);
8031}
8032
Eric Laurent96d1dda2022-03-14 17:14:19 +01008033bool AudioPolicyManager::isInCall() const {
François Gaffie2110e042015-03-24 08:41:51 +01008034 return isStateInCall(mEngine->getPhoneState());
8035}
8036
Eric Laurent96d1dda2022-03-14 17:14:19 +01008037bool AudioPolicyManager::isStateInCall(int state) const {
François Gaffie2110e042015-03-24 08:41:51 +01008038 return is_state_in_call(state);
8039}
8040
Eric Laurentf9cccec2022-11-16 19:12:00 +01008041bool AudioPolicyManager::isCallAudioAccessible() const {
Eric Laurent74b71512019-11-06 17:21:57 -08008042 audio_mode_t mode = mEngine->getPhoneState();
8043 return (mode == AUDIO_MODE_IN_CALL)
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01008044 || (mode == AUDIO_MODE_CALL_SCREEN)
8045 || (mode == AUDIO_MODE_CALL_REDIRECT);
Eric Laurent74b71512019-11-06 17:21:57 -08008046}
8047
Eric Laurentf9cccec2022-11-16 19:12:00 +01008048bool AudioPolicyManager::isInCallOrScreening() const {
8049 audio_mode_t mode = mEngine->getPhoneState();
8050 return isStateInCall(mode) || mode == AUDIO_MODE_CALL_SCREEN;
8051}
8052
Eric Laurentd60560a2015-04-10 11:31:20 -07008053void AudioPolicyManager::cleanUpForDevice(const sp<DeviceDescriptor>& deviceDesc)
8054{
8055 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07008056 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008057 if (sourceDesc->isConnected() && (sourceDesc->srcDevice()->equals(deviceDesc) ||
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02008058 sourceDesc->sinkDevice()->equals(deviceDesc))
8059 && !isCallRxAudioSource(sourceDesc)) {
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008060 disconnectAudioSource(sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07008061 }
8062 }
8063
8064 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
8065 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
8066 bool release = false;
8067 for (size_t j = 0; j < patchDesc->mPatch.num_sources && !release; j++) {
8068 const struct audio_port_config *source = &patchDesc->mPatch.sources[j];
8069 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
8070 source->ext.device.type == deviceDesc->type()) {
8071 release = true;
8072 }
8073 }
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008074 const char *address = deviceDesc->address().c_str();
Eric Laurentd60560a2015-04-10 11:31:20 -07008075 for (size_t j = 0; j < patchDesc->mPatch.num_sinks && !release; j++) {
8076 const struct audio_port_config *sink = &patchDesc->mPatch.sinks[j];
8077 if (sink->type == AUDIO_PORT_TYPE_DEVICE &&
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008078 sink->ext.device.type == deviceDesc->type() &&
8079 (strnlen(address, AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0
8080 || strncmp(sink->ext.device.address, address,
8081 AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0)) {
Eric Laurentd60560a2015-04-10 11:31:20 -07008082 release = true;
8083 }
8084 }
8085 if (release) {
François Gaffieafd4cea2019-11-18 15:50:22 +01008086 ALOGV("%s releasing patch %u", __FUNCTION__, patchDesc->getHandle());
8087 releaseAudioPatch(patchDesc->getHandle(), patchDesc->getUid());
Eric Laurentd60560a2015-04-10 11:31:20 -07008088 }
8089 }
Francois Gaffie716e1432019-01-14 16:58:59 +01008090
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01008091 mInputs.clearSessionRoutesForDevice(deviceDesc);
8092
Francois Gaffie716e1432019-01-14 16:58:59 +01008093 mHwModules.cleanUpForDevice(deviceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07008094}
8095
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008096void AudioPolicyManager::modifySurroundFormats(
8097 const sp<DeviceDescriptor>& devDesc, FormatVector *formatsPtr) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008098 std::unordered_set<audio_format_t> enforcedSurround(
8099 devDesc->encodedFormats().begin(), devDesc->encodedFormats().end());
Mikhail Naganov100f0122018-11-29 11:22:16 -08008100 std::unordered_set<audio_format_t> allSurround; // A flat set of all known surround formats
Mikhail Naganov68e3f642023-04-28 13:06:32 -07008101 for (const auto& pair : mConfig->getSurroundFormats()) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008102 allSurround.insert(pair.first);
8103 for (const auto& subformat : pair.second) allSurround.insert(subformat);
8104 }
Phil Burk09bc4612016-02-24 15:58:15 -08008105
8106 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
8107 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Phil Burk0709b0a2016-03-31 12:54:57 -07008108 ALOGD("%s: forced use = %d", __FUNCTION__, forceUse);
Mikhail Naganov100f0122018-11-29 11:22:16 -08008109 // This is the resulting set of formats depending on the surround mode:
8110 // 'all surround' = allSurround
8111 // 'enforced surround' = enforcedSurround [may include IEC69137 which isn't raw surround fmt]
8112 // 'non-surround' = not in 'all surround' and not in 'enforced surround'
8113 // 'manual surround' = mManualSurroundFormats
8114 // AUTO: formats v 'enforced surround'
8115 // ALWAYS: formats v 'all surround' v 'enforced surround'
8116 // NEVER: formats ^ 'non-surround'
8117 // MANUAL: formats ^ ('non-surround' v 'manual surround' v (IEC69137 ^ 'enforced surround'))
Phil Burk09bc4612016-02-24 15:58:15 -08008118
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008119 std::unordered_set<audio_format_t> formatSet;
8120 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL
8121 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008122 // formatSet is (formats ^ 'non-surround')
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008123 for (auto formatIter = formatsPtr->begin(); formatIter != formatsPtr->end(); ++formatIter) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008124 if (allSurround.count(*formatIter) == 0 && enforcedSurround.count(*formatIter) == 0) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008125 formatSet.insert(*formatIter);
8126 }
8127 }
8128 } else {
8129 formatSet.insert(formatsPtr->begin(), formatsPtr->end());
8130 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08008131 formatsPtr->clear(); // Re-filled from the formatSet at the end.
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008132
jiabin81772902018-04-02 17:52:27 -07008133 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008134 formatSet.insert(mManualSurroundFormats.begin(), mManualSurroundFormats.end());
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008135 // Enable IEC61937 when in MANUAL mode if it's enforced for this device.
8136 if (enforcedSurround.count(AUDIO_FORMAT_IEC61937) != 0) {
8137 formatSet.insert(AUDIO_FORMAT_IEC61937);
Phil Burk09bc4612016-02-24 15:58:15 -08008138 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08008139 } else if (forceUse != AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) { // AUTO or ALWAYS
8140 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS) {
8141 formatSet.insert(allSurround.begin(), allSurround.end());
Phil Burk07ac1142016-03-25 13:39:29 -07008142 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08008143 formatSet.insert(enforcedSurround.begin(), enforcedSurround.end());
Phil Burk09bc4612016-02-24 15:58:15 -08008144 }
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008145 for (const auto& format : formatSet) {
jiabin06e4bab2019-07-29 10:13:34 -07008146 formatsPtr->push_back(format);
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008147 }
Phil Burk0709b0a2016-03-31 12:54:57 -07008148}
8149
jiabin06e4bab2019-07-29 10:13:34 -07008150void AudioPolicyManager::modifySurroundChannelMasks(ChannelMaskSet *channelMasksPtr) {
8151 ChannelMaskSet &channelMasks = *channelMasksPtr;
Phil Burk0709b0a2016-03-31 12:54:57 -07008152 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
8153 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
8154
8155 // If NEVER, then remove support for channelMasks > stereo.
8156 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
jiabin06e4bab2019-07-29 10:13:34 -07008157 for (auto it = channelMasks.begin(); it != channelMasks.end();) {
8158 audio_channel_mask_t channelMask = *it;
Phil Burk0709b0a2016-03-31 12:54:57 -07008159 if (channelMask & ~AUDIO_CHANNEL_OUT_STEREO) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01008160 ALOGV("%s: force NEVER, so remove channelMask 0x%08x", __FUNCTION__, channelMask);
jiabin06e4bab2019-07-29 10:13:34 -07008161 it = channelMasks.erase(it);
Phil Burk0709b0a2016-03-31 12:54:57 -07008162 } else {
jiabin06e4bab2019-07-29 10:13:34 -07008163 ++it;
Phil Burk0709b0a2016-03-31 12:54:57 -07008164 }
8165 }
jiabin81772902018-04-02 17:52:27 -07008166 // If ALWAYS or MANUAL, then make sure we at least support 5.1
8167 } else if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS
8168 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Phil Burk0709b0a2016-03-31 12:54:57 -07008169 bool supports5dot1 = false;
8170 // Are there any channel masks that can be considered "surround"?
Mikhail Naganovcf84e592017-12-07 11:25:11 -08008171 for (audio_channel_mask_t channelMask : channelMasks) {
Phil Burk0709b0a2016-03-31 12:54:57 -07008172 if ((channelMask & AUDIO_CHANNEL_OUT_5POINT1) == AUDIO_CHANNEL_OUT_5POINT1) {
8173 supports5dot1 = true;
8174 break;
8175 }
8176 }
8177 // If not then add 5.1 support.
8178 if (!supports5dot1) {
jiabin06e4bab2019-07-29 10:13:34 -07008179 channelMasks.insert(AUDIO_CHANNEL_OUT_5POINT1);
Eric Laurentfecbceb2021-02-09 14:46:43 +01008180 ALOGV("%s: force MANUAL or ALWAYS, so adding channelMask for 5.1 surround", __func__);
Phil Burk0709b0a2016-03-31 12:54:57 -07008181 }
Phil Burk09bc4612016-02-24 15:58:15 -08008182 }
8183}
8184
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008185void AudioPolicyManager::updateAudioProfiles(const sp<DeviceDescriptor>& devDesc,
Phil Burk00eeb322016-03-31 12:41:00 -07008186 audio_io_handle_t ioHandle,
jiabin12537fc2023-10-12 17:56:08 +00008187 const sp<IOProfile>& profile) {
8188 if (!profile->hasDynamicAudioProfile()) {
8189 return;
François Gaffie112b0af2015-11-19 16:13:25 +01008190 }
François Gaffie112b0af2015-11-19 16:13:25 +01008191
jiabin12537fc2023-10-12 17:56:08 +00008192 audio_port_v7 devicePort;
8193 devDesc->toAudioPort(&devicePort);
François Gaffie112b0af2015-11-19 16:13:25 +01008194
jiabin12537fc2023-10-12 17:56:08 +00008195 audio_port_v7 mixPort;
8196 profile->toAudioPort(&mixPort);
8197 mixPort.ext.mix.handle = ioHandle;
8198
8199 status_t status = mpClientInterface->getAudioMixPort(&devicePort, &mixPort);
8200 if (status != NO_ERROR) {
8201 ALOGE("%s failed to query the attributes of the mix port", __func__);
8202 return;
François Gaffie112b0af2015-11-19 16:13:25 +01008203 }
jiabin12537fc2023-10-12 17:56:08 +00008204
8205 std::set<audio_format_t> supportedFormats;
8206 for (size_t i = 0; i < mixPort.num_audio_profiles; ++i) {
8207 supportedFormats.insert(mixPort.audio_profiles[i].format);
8208 }
8209 FormatVector formats(supportedFormats.begin(), supportedFormats.end());
8210 mReportedFormatsMap[devDesc] = formats;
8211
8212 if (devDesc->type() == AUDIO_DEVICE_OUT_HDMI ||
8213 isDeviceOfModule(devDesc,AUDIO_HARDWARE_MODULE_ID_MSD)) {
8214 modifySurroundFormats(devDesc, &formats);
8215 size_t modifiedNumProfiles = 0;
8216 for (size_t i = 0; i < mixPort.num_audio_profiles; ++i) {
8217 if (std::find(formats.begin(), formats.end(), mixPort.audio_profiles[i].format) ==
8218 formats.end()) {
8219 // Skip the format that is not present after modifying surround formats.
8220 continue;
8221 }
8222 memcpy(&mixPort.audio_profiles[modifiedNumProfiles], &mixPort.audio_profiles[i],
8223 sizeof(struct audio_profile));
8224 ChannelMaskSet channels(mixPort.audio_profiles[modifiedNumProfiles].channel_masks,
8225 mixPort.audio_profiles[modifiedNumProfiles].channel_masks +
8226 mixPort.audio_profiles[modifiedNumProfiles].num_channel_masks);
8227 modifySurroundChannelMasks(&channels);
8228 std::copy(channels.begin(), channels.end(),
8229 std::begin(mixPort.audio_profiles[modifiedNumProfiles].channel_masks));
8230 mixPort.audio_profiles[modifiedNumProfiles++].num_channel_masks = channels.size();
8231 }
8232 mixPort.num_audio_profiles = modifiedNumProfiles;
8233 }
8234 profile->importAudioPort(mixPort);
François Gaffie112b0af2015-11-19 16:13:25 +01008235}
Eric Laurentd60560a2015-04-10 11:31:20 -07008236
Mikhail Naganovdc769682018-05-04 15:34:08 -07008237status_t AudioPolicyManager::installPatch(const char *caller,
8238 audio_patch_handle_t *patchHandle,
8239 AudioIODescriptorInterface *ioDescriptor,
8240 const struct audio_patch *patch,
8241 int delayMs)
8242{
8243 ssize_t index = mAudioPatches.indexOfKey(
8244 patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE ?
8245 *patchHandle : ioDescriptor->getPatchHandle());
8246 sp<AudioPatch> patchDesc;
8247 status_t status = installPatch(
8248 caller, index, patchHandle, patch, delayMs, mUidCached, &patchDesc);
8249 if (status == NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01008250 ioDescriptor->setPatchHandle(patchDesc->getHandle());
Mikhail Naganovdc769682018-05-04 15:34:08 -07008251 }
8252 return status;
8253}
8254
8255status_t AudioPolicyManager::installPatch(const char *caller,
8256 ssize_t index,
8257 audio_patch_handle_t *patchHandle,
8258 const struct audio_patch *patch,
8259 int delayMs,
8260 uid_t uid,
8261 sp<AudioPatch> *patchDescPtr)
8262{
8263 sp<AudioPatch> patchDesc;
8264 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
8265 if (index >= 0) {
8266 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01008267 afPatchHandle = patchDesc->getAfHandle();
Mikhail Naganovdc769682018-05-04 15:34:08 -07008268 }
8269
8270 status_t status = mpClientInterface->createAudioPatch(patch, &afPatchHandle, delayMs);
8271 ALOGV("%s() AF::createAudioPatch returned %d patchHandle %d num_sources %d num_sinks %d",
8272 caller, status, afPatchHandle, patch->num_sources, patch->num_sinks);
8273 if (status == NO_ERROR) {
8274 if (index < 0) {
8275 patchDesc = new AudioPatch(patch, uid);
François Gaffieafd4cea2019-11-18 15:50:22 +01008276 addAudioPatch(patchDesc->getHandle(), patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07008277 } else {
8278 patchDesc->mPatch = *patch;
8279 }
François Gaffieafd4cea2019-11-18 15:50:22 +01008280 patchDesc->setAfHandle(afPatchHandle);
Mikhail Naganovdc769682018-05-04 15:34:08 -07008281 if (patchHandle) {
François Gaffieafd4cea2019-11-18 15:50:22 +01008282 *patchHandle = patchDesc->getHandle();
Mikhail Naganovdc769682018-05-04 15:34:08 -07008283 }
8284 nextAudioPortGeneration();
8285 mpClientInterface->onAudioPatchListUpdate();
8286 }
8287 if (patchDescPtr) *patchDescPtr = patchDesc;
8288 return status;
8289}
8290
jiabinbce0c1d2020-10-05 11:20:18 -07008291bool AudioPolicyManager::areAllActiveTracksRerouted(const sp<SwAudioOutputDescriptor>& output)
8292{
8293 const TrackClientVector activeClients = output->getActiveClients();
8294 if (activeClients.empty()) {
8295 return true;
8296 }
8297 ssize_t index = mAudioPatches.indexOfKey(output->getPatchHandle());
8298 if (index < 0) {
8299 ALOGE("%s, no audio patch found while there are active clients on output %d",
8300 __func__, output->getId());
8301 return false;
8302 }
8303 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
8304 DeviceVector routedDevices;
8305 for (int i = 0; i < patchDesc->mPatch.num_sinks; ++i) {
8306 sp<DeviceDescriptor> device = mAvailableOutputDevices.getDeviceFromId(
8307 patchDesc->mPatch.sinks[i].id);
8308 if (device == nullptr) {
8309 ALOGE("%s, no audio device found with id(%d)",
8310 __func__, patchDesc->mPatch.sinks[i].id);
8311 return false;
8312 }
8313 routedDevices.add(device);
8314 }
8315 for (const auto& client : activeClients) {
jiabin49256852022-03-09 11:21:35 -08008316 if (client->isInvalid()) {
8317 // No need to take care about invalidated clients.
8318 continue;
8319 }
jiabinbce0c1d2020-10-05 11:20:18 -07008320 sp<DeviceDescriptor> preferredDevice =
8321 mAvailableOutputDevices.getDeviceFromId(client->preferredDeviceId());
8322 if (mEngine->getOutputDevicesForAttributes(
8323 client->attributes(), preferredDevice, false) == routedDevices) {
8324 return false;
8325 }
8326 }
8327 return true;
8328}
8329
8330sp<SwAudioOutputDescriptor> AudioPolicyManager::openOutputWithProfileAndDevice(
Eric Laurentb4f42a92022-01-17 17:37:31 +01008331 const sp<IOProfile>& profile, const DeviceVector& devices,
jiabina84c3d32022-12-02 18:59:55 +00008332 const audio_config_base_t *mixerConfig, const audio_config_t *halConfig,
8333 audio_output_flags_t flags)
jiabinbce0c1d2020-10-05 11:20:18 -07008334{
8335 for (const auto& device : devices) {
8336 // TODO: This should be checking if the profile supports the device combo.
8337 if (!profile->supportsDevice(device)) {
jiabina84c3d32022-12-02 18:59:55 +00008338 ALOGE("%s profile(%s) doesn't support device %#x", __func__, profile->getName().c_str(),
8339 device->type());
jiabinbce0c1d2020-10-05 11:20:18 -07008340 return nullptr;
8341 }
8342 }
8343 sp<SwAudioOutputDescriptor> desc = new SwAudioOutputDescriptor(profile, mpClientInterface);
8344 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
jiabina84c3d32022-12-02 18:59:55 +00008345 status_t status = desc->open(halConfig, mixerConfig, devices,
8346 AUDIO_STREAM_DEFAULT, flags, &output);
jiabinbce0c1d2020-10-05 11:20:18 -07008347 if (status != NO_ERROR) {
jiabina84c3d32022-12-02 18:59:55 +00008348 ALOGE("%s failed to open output %d", __func__, status);
jiabinbce0c1d2020-10-05 11:20:18 -07008349 return nullptr;
8350 }
8351
8352 // Here is where the out_set_parameters() for card & device gets called
8353 sp<DeviceDescriptor> device = devices.getDeviceForOpening();
8354 const audio_devices_t deviceType = device->type();
8355 const String8 &address = String8(device->address().c_str());
Tomasz Wasilczykfd9ffd12023-08-14 17:56:22 +00008356 if (!address.empty()) {
jiabinbce0c1d2020-10-05 11:20:18 -07008357 char *param = audio_device_address_to_parameter(deviceType, address.c_str());
8358 mpClientInterface->setParameters(output, String8(param));
8359 free(param);
8360 }
jiabin12537fc2023-10-12 17:56:08 +00008361 updateAudioProfiles(device, output, profile);
jiabinbce0c1d2020-10-05 11:20:18 -07008362 if (!profile->hasValidAudioProfile()) {
8363 ALOGW("%s() missing param", __func__);
8364 desc->close();
8365 return nullptr;
jiabina84c3d32022-12-02 18:59:55 +00008366 } else if (profile->hasDynamicAudioProfile() && halConfig == nullptr) {
8367 // Reopen the output with the best audio profile picked by APM when the profile supports
8368 // dynamic audio profile and the hal config is not specified.
jiabinbce0c1d2020-10-05 11:20:18 -07008369 desc->close();
8370 output = AUDIO_IO_HANDLE_NONE;
8371 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
8372 profile->pickAudioProfile(
8373 config.sample_rate, config.channel_mask, config.format);
8374 config.offload_info.sample_rate = config.sample_rate;
8375 config.offload_info.channel_mask = config.channel_mask;
8376 config.offload_info.format = config.format;
8377
jiabina84c3d32022-12-02 18:59:55 +00008378 status = desc->open(&config, mixerConfig, devices, AUDIO_STREAM_DEFAULT, flags, &output);
jiabinbce0c1d2020-10-05 11:20:18 -07008379 if (status != NO_ERROR) {
8380 return nullptr;
8381 }
8382 }
8383
8384 addOutput(output, desc);
Eric Laurentb4f42a92022-01-17 17:37:31 +01008385
baek.kim -61c20122022-07-27 10:05:32 +00008386 sp<DeviceDescriptor> speaker = mAvailableOutputDevices.getDevice(
8387 AUDIO_DEVICE_OUT_SPEAKER, String8(""), AUDIO_FORMAT_DEFAULT);
8388
jiabinbce0c1d2020-10-05 11:20:18 -07008389 if (audio_is_remote_submix_device(deviceType) && address != "0") {
8390 sp<AudioPolicyMix> policyMix;
8391 if (mPolicyMixes.getAudioPolicyMix(deviceType, address, policyMix) == NO_ERROR) {
8392 policyMix->setOutput(desc);
8393 desc->mPolicyMix = policyMix;
8394 } else {
8395 ALOGW("checkOutputsForDevice() cannot find policy for address %s",
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00008396 address.c_str());
jiabinbce0c1d2020-10-05 11:20:18 -07008397 }
8398
baek.kim -61c20122022-07-27 10:05:32 +00008399 } else if (hasPrimaryOutput() && speaker != nullptr
8400 && mPrimaryOutput->supportsDevice(speaker) && !desc->supportsDevice(speaker)
Eric Laurentb4f42a92022-01-17 17:37:31 +01008401 && ((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0)) {
8402 // no duplicated output for:
8403 // - direct outputs
8404 // - outputs used by dynamic policy mixes
baek.kim -61c20122022-07-27 10:05:32 +00008405 // - outputs that supports SPEAKER while the primary output does not.
jiabinbce0c1d2020-10-05 11:20:18 -07008406 audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE;
8407
8408 //TODO: configure audio effect output stage here
8409
8410 // open a duplicating output thread for the new output and the primary output
8411 sp<SwAudioOutputDescriptor> dupOutputDesc =
8412 new SwAudioOutputDescriptor(nullptr, mpClientInterface);
8413 status = dupOutputDesc->openDuplicating(mPrimaryOutput, desc, &duplicatedOutput);
8414 if (status == NO_ERROR) {
8415 // add duplicated output descriptor
8416 addOutput(duplicatedOutput, dupOutputDesc);
8417 } else {
8418 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
8419 mPrimaryOutput->mIoHandle, output);
8420 desc->close();
8421 removeOutput(output);
8422 nextAudioPortGeneration();
8423 return nullptr;
8424 }
8425 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02008426 if (mPrimaryOutput == nullptr && profile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
8427 ALOGV("%s(): re-assigning mPrimaryOutput", __func__);
8428 mPrimaryOutput = desc;
8429 }
jiabinbce0c1d2020-10-05 11:20:18 -07008430 return desc;
8431}
8432
jiabinf1c73972022-04-14 16:28:52 -07008433status_t AudioPolicyManager::getDevicesForAttributes(
8434 const audio_attributes_t &attr, DeviceVector &devices, bool forVolume) {
8435 // Devices are determined in the following precedence:
8436 //
8437 // 1) Devices associated with a dynamic policy matching the attributes. This is often
8438 // a remote submix from MIX_ROUTE_FLAG_LOOP_BACK.
8439 //
8440 // If no such dynamic policy then
8441 // 2) Devices containing an active client using setPreferredDevice
8442 // with same strategy as the attributes.
8443 // (from the default Engine::getOutputDevicesForAttributes() implementation).
8444 //
8445 // If no corresponding active client with setPreferredDevice then
8446 // 3) Devices associated with the strategy determined by the attributes
8447 // (from the default Engine::getOutputDevicesForAttributes() implementation).
8448 //
8449 // See related getOutputForAttrInt().
8450
8451 // check dynamic policies but only for primary descriptors (secondary not used for audible
8452 // audio routing, only used for duplication for playback capture)
8453 sp<AudioPolicyMix> policyMix;
Oscar Azucena873d10f2023-01-12 18:34:42 -08008454 bool unneededUsePrimaryOutputFromPolicyMixes = false;
jiabinf1c73972022-04-14 16:28:52 -07008455 status_t status = mPolicyMixes.getOutputForAttr(attr, AUDIO_CONFIG_BASE_INITIALIZER,
Oscar Azucena873d10f2023-01-12 18:34:42 -08008456 0 /*uid unknown here*/, AUDIO_SESSION_NONE, AUDIO_OUTPUT_FLAG_NONE,
8457 mAvailableOutputDevices, nullptr /* requestedDevice */, policyMix,
8458 nullptr /* secondaryMixes */, unneededUsePrimaryOutputFromPolicyMixes);
jiabinf1c73972022-04-14 16:28:52 -07008459 if (status != OK) {
8460 return status;
8461 }
8462
8463 if (policyMix != nullptr && policyMix->getOutput() != nullptr &&
8464 // For volume control, skip LOOPBACK mixes which use AUDIO_DEVICE_OUT_REMOTE_SUBMIX
8465 // as they are unaffected by device/stream volume
8466 // (per SwAudioOutputDescriptor::isFixedVolume()).
8467 (!forVolume || policyMix->mDeviceType != AUDIO_DEVICE_OUT_REMOTE_SUBMIX)
8468 ) {
8469 sp<DeviceDescriptor> deviceDesc = mAvailableOutputDevices.getDevice(
8470 policyMix->mDeviceType, policyMix->mDeviceAddress, AUDIO_FORMAT_DEFAULT);
8471 devices.add(deviceDesc);
8472 } else {
8473 // The default Engine::getOutputDevicesForAttributes() uses findPreferredDevice()
8474 // which selects setPreferredDevice if active. This means forVolume call
8475 // will take an active setPreferredDevice, if such exists.
8476
8477 devices = mEngine->getOutputDevicesForAttributes(
8478 attr, nullptr /* preferredDevice */, false /* fromCache */);
8479 }
8480
8481 if (forVolume) {
8482 // We alias the device AUDIO_DEVICE_OUT_SPEAKER_SAFE to AUDIO_DEVICE_OUT_SPEAKER
8483 // for single volume control in AudioService (such relationship should exist if
8484 // SPEAKER_SAFE is present).
8485 //
8486 // (This is unrelated to a different device grouping as Volume::getDeviceCategory)
8487 DeviceVector speakerSafeDevices =
8488 devices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER_SAFE);
8489 if (!speakerSafeDevices.isEmpty()) {
8490 devices.merge(mAvailableOutputDevices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER));
8491 devices.remove(speakerSafeDevices);
8492 }
8493 }
8494
8495 return NO_ERROR;
8496}
8497
8498status_t AudioPolicyManager::getProfilesForDevices(const DeviceVector& devices,
8499 AudioProfileVector& audioProfiles,
8500 uint32_t flags,
8501 bool isInput) {
8502 for (const auto& hwModule : mHwModules) {
8503 // the MSD module checks for different conditions
8504 if (strcmp(hwModule->getName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0) {
8505 continue;
8506 }
8507 IOProfileCollection ioProfiles = isInput ? hwModule->getInputProfiles()
8508 : hwModule->getOutputProfiles();
8509 for (const auto& profile : ioProfiles) {
8510 if (!profile->areAllDevicesSupported(devices) ||
8511 !profile->isCompatibleProfileForFlags(
8512 flags, false /*exactMatchRequiredForInputFlags*/)) {
8513 continue;
8514 }
8515 audioProfiles.addAllValidProfiles(profile->asAudioPort()->getAudioProfiles());
8516 }
8517 }
8518
8519 if (!isInput) {
8520 // add the direct profiles from MSD if present and has audio patches to all the output(s)
8521 const auto &msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
8522 if (msdModule != nullptr) {
8523 if (msdHasPatchesToAllDevices(devices.toTypeAddrVector())) {
8524 ALOGV("%s: MSD audio patches set to all output devices.", __func__);
8525 for (const auto &profile: msdModule->getOutputProfiles()) {
8526 if (!profile->asAudioPort()->isDirectOutput()) {
8527 continue;
8528 }
8529 audioProfiles.addAllValidProfiles(profile->asAudioPort()->getAudioProfiles());
8530 }
8531 } else {
8532 ALOGV("%s: MSD audio patches NOT set to all output devices.", __func__);
8533 }
8534 }
8535 }
8536
8537 return NO_ERROR;
8538}
8539
jiabin3ff8d7d2022-12-13 06:27:44 +00008540sp<SwAudioOutputDescriptor> AudioPolicyManager::reopenOutput(sp<SwAudioOutputDescriptor> outputDesc,
8541 const audio_config_t *config,
8542 audio_output_flags_t flags,
8543 const char* caller) {
jiabina84c3d32022-12-02 18:59:55 +00008544 closeOutput(outputDesc->mIoHandle);
8545 sp<SwAudioOutputDescriptor> preferredOutput = openOutputWithProfileAndDevice(
8546 outputDesc->mProfile, outputDesc->devices(), nullptr /*mixerConfig*/, config, flags);
8547 if (preferredOutput == nullptr) {
8548 ALOGE("%s failed to reopen output device=%d, caller=%s",
8549 __func__, outputDesc->devices()[0]->getId(), caller);
jiabina84c3d32022-12-02 18:59:55 +00008550 }
jiabin3ff8d7d2022-12-13 06:27:44 +00008551 return preferredOutput;
8552}
8553
8554void AudioPolicyManager::reopenOutputsWithDevices(
8555 const std::map<audio_io_handle_t, DeviceVector> &outputsToReopen) {
8556 for (const auto& [output, devices] : outputsToReopen) {
8557 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
8558 closeOutput(output);
8559 openOutputWithProfileAndDevice(desc->mProfile, devices);
8560 }
jiabina84c3d32022-12-02 18:59:55 +00008561}
8562
jiabinc44b3462022-12-08 12:52:31 -08008563PortHandleVector AudioPolicyManager::getClientsForStream(
8564 audio_stream_type_t streamType) const {
8565 PortHandleVector clients;
8566 for (size_t i = 0; i < mOutputs.size(); ++i) {
8567 PortHandleVector clientsForStream = mOutputs.valueAt(i)->getClientsForStream(streamType);
8568 clients.insert(clients.end(), clientsForStream.begin(), clientsForStream.end());
8569 }
8570 return clients;
8571}
8572
8573void AudioPolicyManager::invalidateStreams(StreamTypeVector streams) const {
8574 PortHandleVector clients;
8575 for (auto stream : streams) {
8576 PortHandleVector clientsForStream = getClientsForStream(stream);
8577 clients.insert(clients.end(), clientsForStream.begin(), clientsForStream.end());
8578 }
8579 mpClientInterface->invalidateTracks(clients);
8580}
8581
Mikhail Naganov1b2a7942017-12-08 10:18:09 -08008582} // namespace android