blob: ad8cdb9c31ffc1620c2b3693a490cce382aa1512 [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>
Mikhail Naganovd5e18052018-11-30 14:55:45 -080037#include <unordered_set>
Mikhail Naganov15be9d22017-11-08 14:18:13 +110038#include <vector>
Mikhail Naganov946c0032020-10-21 13:04:58 -070039
40#include <Serializer.h>
Nathalie Le Clair88fa2752021-11-23 13:03:41 +010041#include <android/media/audio/common/AudioPort.h>
Glenn Kasten76a13442020-07-01 12:10:59 -070042#include <cutils/bitops.h>
Eric Laurente552edb2014-03-10 17:42:56 -070043#include <cutils/properties.h>
Eric Laurent3b73df72014-03-11 09:06:29 -070044#include <media/AudioParameter.h>
Mikhail Naganov946c0032020-10-21 13:04:58 -070045#include <policy.h>
Andy Hung4ef19fa2018-05-15 19:35:29 -070046#include <private/android_filesystem_config.h>
Mikhail Naganovcbc8f612016-10-11 18:05:13 -070047#include <system/audio.h>
Mikhail Naganov27cf37c2020-04-14 14:47:01 -070048#include <system/audio_config.h>
jiabinebb6af42020-06-09 17:31:17 -070049#include <system/audio_effects/effect_hapticgenerator.h>
Mikhail Naganov946c0032020-10-21 13:04:58 -070050#include <utils/Log.h>
51
Eric Laurentd4692962014-05-05 18:13:44 -070052#include "AudioPolicyManager.h"
François Gaffiea8ecc2c2015-11-09 16:10:40 +010053#include "TypeConverter.h"
Eric Laurente552edb2014-03-10 17:42:56 -070054
Eric Laurent3b73df72014-03-11 09:06:29 -070055namespace android {
Eric Laurente552edb2014-03-10 17:42:56 -070056
Nathalie Le Clair88fa2752021-11-23 13:03:41 +010057using android::media::audio::common::AudioDevice;
58using android::media::audio::common::AudioDeviceAddress;
59using android::media::audio::common::AudioPortDeviceExt;
60using android::media::audio::common::AudioPortExt;
Svet Ganov3e5f14f2021-05-13 22:51:08 +000061using content::AttributionSourceState;
Philip P. Moltmannbda45752020-07-17 16:41:18 -070062
Eric Laurentdc462862016-07-19 12:29:53 -070063//FIXME: workaround for truncated touch sounds
64// to be removed when the problem is handled by system UI
65#define TOUCH_SOUND_FIXED_DELAY_MS 100
Jean-Michel Trivi719a9872017-08-05 13:51:35 -070066
67// Largest difference in dB on earpiece in call between the voice volume and another
68// media / notification / system volume.
69constexpr float IN_CALL_EARPIECE_HEADROOM_DB = 3.f;
70
jiabin06e4bab2019-07-29 10:13:34 -070071template <typename T>
72bool operator== (const SortedVector<T> &left, const SortedVector<T> &right)
73{
74 if (left.size() != right.size()) {
75 return false;
76 }
77 for (size_t index = 0; index < right.size(); index++) {
78 if (left[index] != right[index]) {
79 return false;
80 }
81 }
82 return true;
83}
84
85template <typename T>
86bool operator!= (const SortedVector<T> &left, const SortedVector<T> &right)
87{
88 return !(left == right);
89}
90
Eric Laurente552edb2014-03-10 17:42:56 -070091// ----------------------------------------------------------------------------
92// AudioPolicyInterface implementation
93// ----------------------------------------------------------------------------
94
Nathalie Le Clair88fa2752021-11-23 13:03:41 +010095status_t AudioPolicyManager::setDeviceConnectionState(audio_policy_dev_state_t state,
96 const android::media::audio::common::AudioPort& port, audio_format_t encodedFormat) {
97 status_t status = setDeviceConnectionStateInt(state, port, encodedFormat);
jiabina7b43792018-02-15 16:04:46 -080098 nextAudioPortGeneration();
99 return status;
Eric Laurentc73ca6e2014-12-12 14:34:22 -0800100}
101
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100102status_t AudioPolicyManager::setDeviceConnectionState(audio_devices_t device,
103 audio_policy_dev_state_t state,
104 const char* device_address,
105 const char* device_name,
106 audio_format_t encodedFormat) {
Atneya Nairc18e9a12022-12-18 16:45:15 -0800107 media::AudioPortFw aidlPort;
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100108 if (status_t status = deviceToAudioPort(device, device_address, device_name, &aidlPort);
109 status == OK) {
110 return setDeviceConnectionState(state, aidlPort.hal, encodedFormat);
111 } else {
112 ALOGE("Failed to convert to AudioPort Parcelable: %s", statusToString(status).c_str());
113 return status;
114 }
115}
116
François Gaffie11d30102018-11-02 16:09:09 +0100117void AudioPolicyManager::broadcastDeviceConnectionState(const sp<DeviceDescriptor> &device,
jiabin872de702023-04-27 22:04:31 +0000118 media::DeviceConnectedState state)
François Gaffie44481e72016-04-20 07:49:57 +0200119{
Mikhail Naganov516d3982022-02-01 23:53:59 +0000120 audio_port_v7 devicePort;
121 device->toAudioPort(&devicePort);
jiabin872de702023-04-27 22:04:31 +0000122 if (status_t status = mpClientInterface->setDeviceConnectedState(&devicePort, state);
Mikhail Naganov516d3982022-02-01 23:53:59 +0000123 status != OK) {
jiabin872de702023-04-27 22:04:31 +0000124 ALOGE("Error %d while setting connected state for device %s", state,
Mikhail Naganov516d3982022-02-01 23:53:59 +0000125 device->getDeviceTypeAddr().toString(false).c_str());
126 }
François Gaffie44481e72016-04-20 07:49:57 +0200127}
128
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100129status_t AudioPolicyManager::setDeviceConnectionStateInt(
130 audio_policy_dev_state_t state, const android::media::audio::common::AudioPort& port,
131 audio_format_t encodedFormat) {
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100132 if (port.ext.getTag() != AudioPortExt::device) {
133 return BAD_VALUE;
134 }
135 audio_devices_t device_type;
136 std::string device_address;
137 if (status_t status = aidl2legacy_AudioDevice_audio_device(
138 port.ext.get<AudioPortExt::device>().device, &device_type, &device_address);
139 status != OK) {
140 return status;
141 };
142 const char* device_name = port.name.c_str();
143 // connect/disconnect only 1 device at a time
144 if (!audio_is_output_device(device_type) && !audio_is_input_device(device_type))
145 return BAD_VALUE;
146
147 sp<DeviceDescriptor> device = mHwModules.getDeviceDescriptor(
148 device_type, device_address.c_str(), device_name, encodedFormat,
149 state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
Mikhail Naganov0566bac2022-06-11 00:47:52 +0000150 if (device == nullptr) {
151 return INVALID_OPERATION;
152 }
153 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
154 device->setExtraAudioDescriptors(port.extraAudioDescriptors);
155 }
156 return setDeviceConnectionStateInt(device, state);
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100157}
158
François Gaffie11d30102018-11-02 16:09:09 +0100159status_t AudioPolicyManager::setDeviceConnectionStateInt(audio_devices_t deviceType,
Eric Laurenta1d525f2015-01-29 13:36:45 -0800160 audio_policy_dev_state_t state,
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100161 const char* device_address,
162 const char* device_name,
163 audio_format_t encodedFormat) {
Atneya Nairc18e9a12022-12-18 16:45:15 -0800164 media::AudioPortFw aidlPort;
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100165 if (status_t status = deviceToAudioPort(deviceType, device_address, device_name, &aidlPort);
166 status == OK) {
167 return setDeviceConnectionStateInt(state, aidlPort.hal, encodedFormat);
168 } else {
169 ALOGE("Failed to convert to AudioPort Parcelable: %s", statusToString(status).c_str());
170 return status;
171 }
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700172}
Paul McLeane743a472015-01-28 11:07:31 -0800173
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700174status_t AudioPolicyManager::setDeviceConnectionStateInt(const sp<DeviceDescriptor> &device,
175 audio_policy_dev_state_t state)
176{
Eric Laurente552edb2014-03-10 17:42:56 -0700177 // handle output devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700178 if (audio_is_output_device(device->type())) {
Eric Laurentd4692962014-05-05 18:13:44 -0700179 SortedVector <audio_io_handle_t> outputs;
180
François Gaffie11d30102018-11-02 16:09:09 +0100181 ssize_t index = mAvailableOutputDevices.indexOf(device);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700182
Eric Laurente552edb2014-03-10 17:42:56 -0700183 // save a copy of the opened output descriptors before any output is opened or closed
184 // by checkOutputsForDevice(). This will be needed by checkOutputForAllStrategies()
185 mPreviousOutputs = mOutputs;
Eric Laurent96d1dda2022-03-14 17:14:19 +0100186
187 bool wasLeUnicastActive = isLeUnicastActive();
188
Eric Laurente552edb2014-03-10 17:42:56 -0700189 switch (state)
190 {
191 // handle output device connection
Eric Laurent3ae5f312015-02-03 17:12:08 -0800192 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700193 if (index >= 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100194 ALOGW("%s() device already connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700195 return INVALID_OPERATION;
196 }
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800197 ALOGV("%s() connecting device %s format %x",
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700198 __func__, device->toString().c_str(), device->getEncodedFormat());
Eric Laurente552edb2014-03-10 17:42:56 -0700199
Eric Laurente552edb2014-03-10 17:42:56 -0700200 // register new device as available
Francois Gaffie993f3902019-04-10 15:39:27 +0200201 if (mAvailableOutputDevices.add(device) < 0) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700202 return NO_MEMORY;
Eric Laurente552edb2014-03-10 17:42:56 -0700203 }
204
François Gaffie44481e72016-04-20 07:49:57 +0200205 // Before checking outputs, broadcast connect event to allow HAL to retrieve dynamic
206 // parameters on newly connected devices (instead of opening the outputs...)
jiabin872de702023-04-27 22:04:31 +0000207 broadcastDeviceConnectionState(device, media::DeviceConnectedState::CONNECTED);
François Gaffie44481e72016-04-20 07:49:57 +0200208
François Gaffie11d30102018-11-02 16:09:09 +0100209 if (checkOutputsForDevice(device, state, outputs) != NO_ERROR) {
210 mAvailableOutputDevices.remove(device);
François Gaffie44481e72016-04-20 07:49:57 +0200211
Francois Gaffie716e1432019-01-14 16:58:59 +0100212 mHwModules.cleanUpForDevice(device);
213
jiabin872de702023-04-27 22:04:31 +0000214 broadcastDeviceConnectionState(device, media::DeviceConnectedState::DISCONNECTED);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700215 return INVALID_OPERATION;
216 }
François Gaffie2110e042015-03-24 08:41:51 +0100217
jiabin1c4794b2020-05-05 10:08:05 -0700218 // Populate encapsulation information when a output device is connected.
219 device->setEncapsulationInfoFromHal(mpClientInterface);
220
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700221 // outputs should never be empty here
222 ALOG_ASSERT(outputs.size() != 0, "setDeviceConnectionState():"
223 "checkOutputsForDevice() returned no outputs but status OK");
François Gaffie11d30102018-11-02 16:09:09 +0100224 ALOGV("%s() checkOutputsForDevice() returned %zu outputs", __func__, outputs.size());
Eric Laurent3ae5f312015-02-03 17:12:08 -0800225
Eric Laurent3ae5f312015-02-03 17:12:08 -0800226 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700227 // handle output device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700228 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700229 if (index < 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100230 ALOGW("%s() device not connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700231 return INVALID_OPERATION;
232 }
233
François Gaffie11d30102018-11-02 16:09:09 +0100234 ALOGV("%s() disconnecting output device %s", __func__, device->toString().c_str());
Paul McLean5c477aa2014-08-20 16:47:57 -0700235
jiabin872de702023-04-27 22:04:31 +0000236 // Notify the HAL to prepare to disconnect device
237 broadcastDeviceConnectionState(
238 device, media::DeviceConnectedState::PREPARE_TO_DISCONNECT);
Paul McLean5c477aa2014-08-20 16:47:57 -0700239
Eric Laurente552edb2014-03-10 17:42:56 -0700240 // remove device from available output devices
François Gaffie11d30102018-11-02 16:09:09 +0100241 mAvailableOutputDevices.remove(device);
Eric Laurente552edb2014-03-10 17:42:56 -0700242
Francois Gaffieba2cf0f2018-12-12 16:40:25 +0100243 mOutputs.clearSessionRoutesForDevice(device);
244
François Gaffie11d30102018-11-02 16:09:09 +0100245 checkOutputsForDevice(device, state, outputs);
François Gaffie2110e042015-03-24 08:41:51 +0100246
jiabin872de702023-04-27 22:04:31 +0000247 // Send Disconnect to HALs
248 broadcastDeviceConnectionState(device, media::DeviceConnectedState::DISCONNECTED);
249
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800250 // Reset active device codec
251 device->setEncodedFormat(AUDIO_FORMAT_DEFAULT);
252
Kriti Dangef6be8f2020-11-05 11:58:19 +0100253 // remove device from mReportedFormatsMap cache
254 mReportedFormatsMap.erase(device);
255
Eric Laurente552edb2014-03-10 17:42:56 -0700256 } break;
257
258 default:
François Gaffie11d30102018-11-02 16:09:09 +0100259 ALOGE("%s() invalid state: %x", __func__, state);
Eric Laurente552edb2014-03-10 17:42:56 -0700260 return BAD_VALUE;
261 }
262
Eric Laurent736a1022019-03-27 18:28:46 -0700263 // Propagate device availability to Engine
264 setEngineDeviceConnectionState(device, state);
265
Eric Laurentae970022019-01-29 14:25:04 -0800266 // No need to evaluate playback routing when connecting a remote submix
267 // output device used by a dynamic policy of type recorder as no
268 // playback use case is affected.
269 bool doCheckForDeviceAndOutputChanges = true;
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700270 if (device->type() == AUDIO_DEVICE_OUT_REMOTE_SUBMIX && device->address() != "0") {
Eric Laurentae970022019-01-29 14:25:04 -0800271 for (audio_io_handle_t output : outputs) {
272 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
Mikhail Naganovbfac5832019-03-05 16:55:28 -0800273 sp<AudioPolicyMix> policyMix = desc->mPolicyMix.promote();
274 if (policyMix != nullptr
275 && policyMix->mMixType == MIX_TYPE_RECORDERS
Tomasz Wasilczyk8f36f6e2023-08-15 20:59:35 +0000276 && device->address() == policyMix->mDeviceAddress.c_str()) {
Eric Laurentae970022019-01-29 14:25:04 -0800277 doCheckForDeviceAndOutputChanges = false;
278 break;
279 }
280 }
281 }
282
283 auto checkCloseOutputs = [&]() {
Mikhail Naganov37977152018-07-11 15:54:44 -0700284 // outputs must be closed after checkOutputForAllStrategies() is executed
285 if (!outputs.isEmpty()) {
286 for (audio_io_handle_t output : outputs) {
287 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
François Gaffie11d30102018-11-02 16:09:09 +0100288 // close unused outputs after device disconnection or direct outputs that have
289 // been opened by checkOutputsForDevice() to query dynamic parameters
Eric Laurente191d1b2022-04-15 11:59:25 +0200290 // "outputs" vector never contains duplicated outputs
Eric Laurentcad6c0d2021-07-13 15:12:39 +0200291 if ((state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE)
292 || (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != 0) &&
Eric Laurente191d1b2022-04-15 11:59:25 +0200293 (desc->mDirectOpenCount == 0))
294 || (((desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0) &&
295 !isOutputOnlyAvailableRouteToSomeDevice(desc))) {
Francois Gaffieff1eb522020-05-06 18:37:04 +0200296 clearAudioSourcesForOutput(output);
Mikhail Naganov37977152018-07-11 15:54:44 -0700297 closeOutput(output);
298 }
Eric Laurente552edb2014-03-10 17:42:56 -0700299 }
Mikhail Naganov37977152018-07-11 15:54:44 -0700300 // check A2DP again after closing A2DP output to reset mA2dpSuspended if needed
301 return true;
Eric Laurente552edb2014-03-10 17:42:56 -0700302 }
Mikhail Naganov37977152018-07-11 15:54:44 -0700303 return false;
Eric Laurentae970022019-01-29 14:25:04 -0800304 };
305
306 if (doCheckForDeviceAndOutputChanges) {
307 checkForDeviceAndOutputChanges(checkCloseOutputs);
308 } else {
309 checkCloseOutputs();
310 }
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100311 (void)updateCallRouting(false /*fromCache*/);
jiabinbce0c1d2020-10-05 11:20:18 -0700312 std::vector<audio_io_handle_t> outputsToReopen;
François Gaffie11d30102018-11-02 16:09:09 +0100313 const DeviceVector msdOutDevices = getMsdAudioOutDevices();
jiabinbce0c1d2020-10-05 11:20:18 -0700314 const DeviceVector activeMediaDevices =
315 mEngine->getActiveMediaDevices(mAvailableOutputDevices);
Eric Laurente552edb2014-03-10 17:42:56 -0700316 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700317 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Jaideep Sharma89b5b852020-11-23 16:41:33 +0530318 if (desc->isActive() && ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) ||
319 (desc != mPrimaryOutput))) {
François Gaffie11d30102018-11-02 16:09:09 +0100320 DeviceVector newDevices = getNewOutputDevices(desc, true /*fromCache*/);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700321 // do not force device change on duplicated output because if device is 0, it will
322 // also force a device 0 for the two outputs it is duplicated to which may override
323 // a valid device selection on those outputs.
François Gaffie11d30102018-11-02 16:09:09 +0100324 bool force = (msdOutDevices.isEmpty() || msdOutDevices != desc->devices())
Mikhail Naganov15be9d22017-11-08 14:18:13 +1100325 && !desc->isDuplicated()
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700326 && (!device_distinguishes_on_address(device->type())
Eric Laurentc2730ba2014-07-20 15:47:07 -0700327 // always force when disconnecting (a non-duplicated device)
328 || (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE));
François Gaffie11d30102018-11-02 16:09:09 +0100329 setOutputDevices(desc, newDevices, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700330 }
jiabinbce0c1d2020-10-05 11:20:18 -0700331 if (!desc->isDuplicated() && desc->mProfile->hasDynamicAudioProfile() &&
jiabin498d2152021-04-02 00:26:46 +0000332 !activeMediaDevices.empty() && desc->devices() != activeMediaDevices &&
jiabinbce0c1d2020-10-05 11:20:18 -0700333 desc->supportsDevicesForPlayback(activeMediaDevices)) {
334 // Reopen the output to query the dynamic profiles when there is not active
335 // clients or all active clients will be rerouted. Otherwise, set the flag
336 // `mPendingReopenToQueryProfiles` in the SwOutputDescriptor so that the output
337 // can be reopened to query dynamic profiles when all clients are inactive.
338 if (areAllActiveTracksRerouted(desc)) {
339 outputsToReopen.push_back(mOutputs.keyAt(i));
340 } else {
341 desc->mPendingReopenToQueryProfiles = true;
342 }
343 }
344 if (!desc->supportsDevicesForPlayback(activeMediaDevices)) {
345 // Clear the flag that previously set for re-querying profiles.
346 desc->mPendingReopenToQueryProfiles = false;
347 }
348 }
349 for (const auto& output : outputsToReopen) {
350 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
351 closeOutput(output);
352 openOutputWithProfileAndDevice(desc->mProfile, activeMediaDevices);
Eric Laurente552edb2014-03-10 17:42:56 -0700353 }
354
Eric Laurentd60560a2015-04-10 11:31:20 -0700355 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
François Gaffie11d30102018-11-02 16:09:09 +0100356 cleanUpForDevice(device);
Eric Laurentd60560a2015-04-10 11:31:20 -0700357 }
358
Eric Laurent96d1dda2022-03-14 17:14:19 +0100359 checkLeBroadcastRoutes(wasLeUnicastActive, nullptr, 0);
360
Eric Laurent72aa32f2014-05-30 18:51:48 -0700361 mpClientInterface->onAudioPortListUpdate();
Eric Laurentb71e58b2014-05-29 16:08:11 -0700362 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700363 } // end if is output device
364
Eric Laurente552edb2014-03-10 17:42:56 -0700365 // handle input devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700366 if (audio_is_input_device(device->type())) {
François Gaffie11d30102018-11-02 16:09:09 +0100367 ssize_t index = mAvailableInputDevices.indexOf(device);
Eric Laurente552edb2014-03-10 17:42:56 -0700368 switch (state)
369 {
370 // handle input device connection
Eric Laurent3b73df72014-03-11 09:06:29 -0700371 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700372 if (index >= 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100373 ALOGW("%s() device already connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700374 return INVALID_OPERATION;
375 }
Eric Laurent0dd51852019-04-19 18:18:58 -0700376
377 if (mAvailableInputDevices.add(device) < 0) {
378 return NO_MEMORY;
379 }
380
François Gaffie44481e72016-04-20 07:49:57 +0200381 // Before checking intputs, broadcast connect event to allow HAL to retrieve dynamic
382 // parameters on newly connected devices (instead of opening the inputs...)
jiabin872de702023-04-27 22:04:31 +0000383 broadcastDeviceConnectionState(device, media::DeviceConnectedState::CONNECTED);
François Gaffie44481e72016-04-20 07:49:57 +0200384
Eric Laurent0dd51852019-04-19 18:18:58 -0700385 if (checkInputsForDevice(device, state) != NO_ERROR) {
386 mAvailableInputDevices.remove(device);
387
jiabin872de702023-04-27 22:04:31 +0000388 broadcastDeviceConnectionState(device, media::DeviceConnectedState::DISCONNECTED);
Francois Gaffie716e1432019-01-14 16:58:59 +0100389
390 mHwModules.cleanUpForDevice(device);
391
Eric Laurentd4692962014-05-05 18:13:44 -0700392 return INVALID_OPERATION;
393 }
394
Eric Laurentd4692962014-05-05 18:13:44 -0700395 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700396
397 // handle input device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700398 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700399 if (index < 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100400 ALOGW("%s() device not connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700401 return INVALID_OPERATION;
402 }
Paul McLean5c477aa2014-08-20 16:47:57 -0700403
François Gaffie11d30102018-11-02 16:09:09 +0100404 ALOGV("%s() disconnecting input device %s", __func__, device->toString().c_str());
Paul McLean5c477aa2014-08-20 16:47:57 -0700405
jiabin872de702023-04-27 22:04:31 +0000406 // Notify the HAL to prepare to disconnect device
407 broadcastDeviceConnectionState(
408 device, media::DeviceConnectedState::PREPARE_TO_DISCONNECT);
Paul McLean5c477aa2014-08-20 16:47:57 -0700409
François Gaffie11d30102018-11-02 16:09:09 +0100410 mAvailableInputDevices.remove(device);
Eric Laurent0dd51852019-04-19 18:18:58 -0700411
412 checkInputsForDevice(device, state);
Kriti Dangef6be8f2020-11-05 11:58:19 +0100413
jiabin872de702023-04-27 22:04:31 +0000414 // Set Disconnect to HALs
415 broadcastDeviceConnectionState(device, media::DeviceConnectedState::DISCONNECTED);
416
Kriti Dangef6be8f2020-11-05 11:58:19 +0100417 // remove device from mReportedFormatsMap cache
418 mReportedFormatsMap.erase(device);
Eric Laurentd4692962014-05-05 18:13:44 -0700419 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700420
421 default:
François Gaffie11d30102018-11-02 16:09:09 +0100422 ALOGE("%s() invalid state: %x", __func__, state);
Eric Laurente552edb2014-03-10 17:42:56 -0700423 return BAD_VALUE;
424 }
425
Eric Laurent736a1022019-03-27 18:28:46 -0700426 // Propagate device availability to Engine
427 setEngineDeviceConnectionState(device, state);
428
Eric Laurent0dd51852019-04-19 18:18:58 -0700429 checkCloseInputs();
Eric Laurent5f5fca52016-08-04 11:48:57 -0700430 // As the input device list can impact the output device selection, update
431 // getDeviceForStrategy() cache
432 updateDevicesAndOutputs();
Eric Laurente552edb2014-03-10 17:42:56 -0700433
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100434 (void)updateCallRouting(false /*fromCache*/);
Francois Gaffiea0e5c992020-09-29 16:05:07 +0200435 // Reconnect Audio Source
436 for (const auto &strategy : mEngine->getOrderedProductStrategies()) {
437 auto attributes = mEngine->getAllAttributesForProductStrategy(strategy).front();
438 checkAudioSourceForAttributes(attributes);
439 }
Eric Laurentd60560a2015-04-10 11:31:20 -0700440 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
François Gaffie11d30102018-11-02 16:09:09 +0100441 cleanUpForDevice(device);
Eric Laurentd60560a2015-04-10 11:31:20 -0700442 }
443
Eric Laurentb52c1522014-05-20 11:27:36 -0700444 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -0700445 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700446 } // end if is input device
Eric Laurente552edb2014-03-10 17:42:56 -0700447
François Gaffie11d30102018-11-02 16:09:09 +0100448 ALOGW("%s() invalid device: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700449 return BAD_VALUE;
450}
451
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100452status_t AudioPolicyManager::deviceToAudioPort(audio_devices_t device, const char* device_address,
453 const char* device_name,
Atneya Nairc18e9a12022-12-18 16:45:15 -0800454 media::AudioPortFw* aidlPort) {
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100455 DeviceDescriptorBase devDescr(device, device_address);
456 devDescr.setName(device_name);
457 return devDescr.writeToParcelable(aidlPort);
458}
459
Eric Laurent736a1022019-03-27 18:28:46 -0700460void AudioPolicyManager::setEngineDeviceConnectionState(const sp<DeviceDescriptor> device,
461 audio_policy_dev_state_t state) {
462
463 // the Engine does not have to know about remote submix devices used by dynamic audio policies
464 if (audio_is_remote_submix_device(device->type()) && device->address() != "0") {
465 return;
466 }
467 mEngine->setDeviceConnectionState(device, state);
468}
469
470
Eric Laurente0720872014-03-11 09:30:41 -0700471audio_policy_dev_state_t AudioPolicyManager::getDeviceConnectionState(audio_devices_t device,
François Gaffie53615e22015-03-19 09:24:12 +0100472 const char *device_address)
Eric Laurente552edb2014-03-10 17:42:56 -0700473{
Eric Laurent634b7142016-04-20 13:48:02 -0700474 sp<DeviceDescriptor> devDesc =
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800475 mHwModules.getDeviceDescriptor(device, device_address, "", AUDIO_FORMAT_DEFAULT,
476 false /* allowToCreate */,
Eric Laurent634b7142016-04-20 13:48:02 -0700477 (strlen(device_address) != 0)/*matchAddress*/);
478
479 if (devDesc == 0) {
François Gaffie251c7f02018-11-07 10:41:08 +0100480 ALOGV("getDeviceConnectionState() undeclared device, type %08x, address: %s",
Eric Laurent634b7142016-04-20 13:48:02 -0700481 device, device_address);
482 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
483 }
François Gaffie53615e22015-03-19 09:24:12 +0100484
Eric Laurent3a4311c2014-03-17 12:00:47 -0700485 DeviceVector *deviceVector;
486
Eric Laurente552edb2014-03-10 17:42:56 -0700487 if (audio_is_output_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700488 deviceVector = &mAvailableOutputDevices;
Eric Laurente552edb2014-03-10 17:42:56 -0700489 } else if (audio_is_input_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700490 deviceVector = &mAvailableInputDevices;
491 } else {
François Gaffie11d30102018-11-02 16:09:09 +0100492 ALOGW("%s() invalid device type %08x", __func__, device);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700493 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurente552edb2014-03-10 17:42:56 -0700494 }
Eric Laurent634b7142016-04-20 13:48:02 -0700495
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800496 return (deviceVector->getDevice(
497 device, String8(device_address), AUDIO_FORMAT_DEFAULT) != 0) ?
Eric Laurent634b7142016-04-20 13:48:02 -0700498 AUDIO_POLICY_DEVICE_STATE_AVAILABLE : AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurenta1d525f2015-01-29 13:36:45 -0800499}
500
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800501status_t AudioPolicyManager::handleDeviceConfigChange(audio_devices_t device,
502 const char *device_address,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800503 const char *device_name,
504 audio_format_t encodedFormat)
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800505{
506 status_t status;
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700507 String8 reply;
508 AudioParameter param;
509 int isReconfigA2dpSupported = 0;
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800510
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800511 ALOGV("handleDeviceConfigChange(() device: 0x%X, address %s name %s encodedFormat: 0x%X",
512 device, device_address, device_name, encodedFormat);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800513
Pavlin Radoslavovc694ff42017-01-09 23:27:29 -0800514 // connect/disconnect only 1 device at a time
515 if (!audio_is_output_device(device) && !audio_is_input_device(device)) return BAD_VALUE;
516
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800517 // Check if the device is currently connected
jiabin9a3361e2019-10-01 09:38:30 -0700518 DeviceVector deviceList = mAvailableOutputDevices.getDevicesFromType(device);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800519 if (deviceList.empty()) {
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800520 // Nothing to do: device is not connected
521 return NO_ERROR;
522 }
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800523 sp<DeviceDescriptor> devDesc = deviceList.itemAt(0);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800524
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700525 // For offloaded A2DP, Hw modules may have the capability to
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800526 // configure codecs.
527 // Handle two specific cases by sending a set parameter to
528 // configure A2DP codecs. No need to toggle device state.
529 // Case 1: A2DP active device switches from primary to primary
530 // module
531 // Case 2: A2DP device config changes on primary module.
Francois Gaffiebce7cd42020-10-14 16:13:20 +0200532 if (audio_is_a2dp_out_device(device) && hasPrimaryOutput()) {
jiabin9a3361e2019-10-01 09:38:30 -0700533 sp<HwModule> module = mHwModules.getModuleForDeviceType(device, encodedFormat);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800534 audio_module_handle_t primaryHandle = mPrimaryOutput->getModuleHandle();
535 if (availablePrimaryOutputDevices().contains(devDesc) &&
536 (module != 0 && module->getHandle() == primaryHandle)) {
537 reply = mpClientInterface->getParameters(
538 AUDIO_IO_HANDLE_NONE,
539 String8(AudioParameter::keyReconfigA2dpSupported));
540 AudioParameter repliedParameters(reply);
541 repliedParameters.getInt(
542 String8(AudioParameter::keyReconfigA2dpSupported), isReconfigA2dpSupported);
543 if (isReconfigA2dpSupported) {
544 const String8 key(AudioParameter::keyReconfigA2dp);
545 param.add(key, String8("true"));
546 mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString());
547 devDesc->setEncodedFormat(encodedFormat);
548 return NO_ERROR;
549 }
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700550 }
551 }
cnx421bd2dcc42020-07-11 14:58:44 +0800552 auto musicStrategy = streamToStrategy(AUDIO_STREAM_MUSIC);
553 for (size_t i = 0; i < mOutputs.size(); i++) {
554 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
555 // mute media strategies and delay device switch by the largest
556 // This avoid sending the music tail into the earpiece or headset.
557 setStrategyMute(musicStrategy, true, desc);
558 setStrategyMute(musicStrategy, false, desc, MUTE_TIME_MS,
559 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
560 nullptr, true /*fromCache*/).types());
561 }
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800562 // Toggle the device state: UNAVAILABLE -> AVAILABLE
563 // This will force reading again the device configuration
564 status = setDeviceConnectionState(device,
565 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800566 device_address, device_name,
567 devDesc->getEncodedFormat());
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800568 if (status != NO_ERROR) {
569 ALOGW("handleDeviceConfigChange() error disabling connection state: %d",
570 status);
571 return status;
572 }
573
574 status = setDeviceConnectionState(device,
575 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800576 device_address, device_name, encodedFormat);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800577 if (status != NO_ERROR) {
578 ALOGW("handleDeviceConfigChange() error enabling connection state: %d",
579 status);
580 return status;
581 }
582
583 return NO_ERROR;
584}
585
Pattydd807582021-11-04 21:01:03 +0800586status_t AudioPolicyManager::getHwOffloadFormatsSupportedForBluetoothMedia(
587 audio_devices_t device, std::vector<audio_format_t> *formats)
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800588{
Pattydd807582021-11-04 21:01:03 +0800589 ALOGV("getHwOffloadFormatsSupportedForBluetoothMedia()");
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800590 status_t status = NO_ERROR;
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800591 std::unordered_set<audio_format_t> formatSet;
592 sp<HwModule> primaryModule =
593 mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_PRIMARY);
Aniket Kumar Latafedb5982019-07-03 11:20:36 -0700594 if (primaryModule == nullptr) {
595 ALOGE("%s() unable to get primary module", __func__);
596 return NO_INIT;
597 }
Pattydd807582021-11-04 21:01:03 +0800598
599 DeviceTypeSet audioDeviceSet;
600
601 switch(device) {
602 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP:
603 audioDeviceSet = getAudioDeviceOutAllA2dpSet();
604 break;
605 case AUDIO_DEVICE_OUT_BLE_HEADSET:
Patty Huangf5082dd2022-07-06 00:14:12 +0800606 audioDeviceSet = getAudioDeviceOutLeAudioUnicastSet();
607 break;
608 case AUDIO_DEVICE_OUT_BLE_BROADCAST:
609 audioDeviceSet = getAudioDeviceOutLeAudioBroadcastSet();
Pattydd807582021-11-04 21:01:03 +0800610 break;
611 default:
612 ALOGE("%s() device type 0x%08x not supported", __func__, device);
613 return BAD_VALUE;
614 }
615
jiabin9a3361e2019-10-01 09:38:30 -0700616 DeviceVector declaredDevices = primaryModule->getDeclaredDevices().getDevicesFromTypes(
Pattydd807582021-11-04 21:01:03 +0800617 audioDeviceSet);
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800618 for (const auto& device : declaredDevices) {
619 formatSet.insert(device->encodedFormats().begin(), device->encodedFormats().end());
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800620 }
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800621 formats->assign(formatSet.begin(), formatSet.end());
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800622 return status;
623}
624
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100625DeviceVector AudioPolicyManager::selectBestRxSinkDevicesForCall(bool fromCache)
626{
627 DeviceVector rxSinkdevices{};
628 rxSinkdevices = mEngine->getOutputDevicesForAttributes(
629 attributes_initializer(AUDIO_USAGE_VOICE_COMMUNICATION), nullptr, fromCache);
630 if (!rxSinkdevices.isEmpty() && mAvailableOutputDevices.contains(rxSinkdevices.itemAt(0))) {
631 auto rxSinkDevice = rxSinkdevices.itemAt(0);
632 auto telephonyRxModule = mHwModules.getModuleForDeviceType(
633 AUDIO_DEVICE_IN_TELEPHONY_RX, AUDIO_FORMAT_DEFAULT);
634 // retrieve Rx Source device descriptor
635 sp<DeviceDescriptor> rxSourceDevice = mAvailableInputDevices.getDevice(
636 AUDIO_DEVICE_IN_TELEPHONY_RX, String8(), AUDIO_FORMAT_DEFAULT);
637
638 // RX Telephony and Rx sink devices are declared by Primary Audio HAL
639 if (isPrimaryModule(telephonyRxModule) && (telephonyRxModule->getHalVersionMajor() >= 3) &&
640 telephonyRxModule->supportsPatch(rxSourceDevice, rxSinkDevice)) {
641 ALOGW("%s() device %s using HW Bridge", __func__, rxSinkDevice->toString().c_str());
642 return DeviceVector(rxSinkDevice);
643 }
644 }
645 // Note that despite the fact that getNewOutputDevices() is called on the primary output,
646 // the device returned is not necessarily reachable via this output
647 // (filter later by setOutputDevices())
648 return getNewOutputDevices(mPrimaryOutput, fromCache);
649}
650
651status_t AudioPolicyManager::updateCallRouting(bool fromCache, uint32_t delayMs, uint32_t *waitMs)
652{
653 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL && hasPrimaryOutput()) {
654 DeviceVector rxDevices = selectBestRxSinkDevicesForCall(fromCache);
655 return updateCallRoutingInternal(rxDevices, delayMs, waitMs);
656 }
657 return INVALID_OPERATION;
658}
659
660status_t AudioPolicyManager::updateCallRoutingInternal(
661 const DeviceVector &rxDevices, uint32_t delayMs, uint32_t *waitMs)
Eric Laurentc2730ba2014-07-20 15:47:07 -0700662{
663 bool createTxPatch = false;
François Gaffie9eb18552018-11-05 10:33:26 +0100664 bool createRxPatch = false;
Eric Laurentdc462862016-07-19 12:29:53 -0700665 uint32_t muteWaitMs = 0;
jiabin9a3361e2019-10-01 09:38:30 -0700666 if(!hasPrimaryOutput() ||
667 mPrimaryOutput->devices().onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_STUB)) {
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100668 return INVALID_OPERATION;
Eric Laurent87ffa392015-05-22 10:32:38 -0700669 }
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100670 ALOG_ASSERT(!rxDevices.isEmpty(), "%s() no selected output device", __func__);
François Gaffie11d30102018-11-02 16:09:09 +0100671
Francois Gaffie716e1432019-01-14 16:58:59 +0100672 audio_attributes_t attr = { .source = AUDIO_SOURCE_VOICE_COMMUNICATION };
François Gaffiec005e562018-11-06 15:04:49 +0100673 auto txSourceDevice = mEngine->getInputDeviceForAttributes(attr);
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100674 ALOG_ASSERT(txSourceDevice != 0, "%s() input selected device not available", __func__);
François Gaffiec005e562018-11-06 15:04:49 +0100675
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100676 ALOGV("%s device rxDevice %s txDevice %s", __func__,
François Gaffie9eb18552018-11-05 10:33:26 +0100677 rxDevices.itemAt(0)->toString().c_str(), txSourceDevice->toString().c_str());
Eric Laurentc2730ba2014-07-20 15:47:07 -0700678
Francois Gaffie601801d2021-06-22 13:27:39 +0200679 disconnectTelephonyAudioSource(mCallRxSourceClient);
680 disconnectTelephonyAudioSource(mCallTxSourceClient);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700681
François Gaffie9eb18552018-11-05 10:33:26 +0100682 auto telephonyRxModule =
jiabin9a3361e2019-10-01 09:38:30 -0700683 mHwModules.getModuleForDeviceType(AUDIO_DEVICE_IN_TELEPHONY_RX, AUDIO_FORMAT_DEFAULT);
François Gaffie9eb18552018-11-05 10:33:26 +0100684 auto telephonyTxModule =
jiabin9a3361e2019-10-01 09:38:30 -0700685 mHwModules.getModuleForDeviceType(AUDIO_DEVICE_OUT_TELEPHONY_TX, AUDIO_FORMAT_DEFAULT);
François Gaffie9eb18552018-11-05 10:33:26 +0100686 // retrieve Rx Source and Tx Sink device descriptors
687 sp<DeviceDescriptor> rxSourceDevice =
688 mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_TELEPHONY_RX,
689 String8(),
690 AUDIO_FORMAT_DEFAULT);
691 sp<DeviceDescriptor> txSinkDevice =
692 mAvailableOutputDevices.getDevice(AUDIO_DEVICE_OUT_TELEPHONY_TX,
693 String8(),
694 AUDIO_FORMAT_DEFAULT);
695
696 // RX and TX Telephony device are declared by Primary Audio HAL
697 if (isPrimaryModule(telephonyRxModule) && isPrimaryModule(telephonyTxModule) &&
698 (telephonyRxModule->getHalVersionMajor() >= 3)) {
699 if (rxSourceDevice == 0 || txSinkDevice == 0) {
700 // RX / TX Telephony device(s) is(are) not currently available
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100701 ALOGE("%s() no telephony Tx and/or RX device", __func__);
702 return INVALID_OPERATION;
François Gaffie9eb18552018-11-05 10:33:26 +0100703 }
François Gaffieafd4cea2019-11-18 15:50:22 +0100704 // createAudioPatchInternal now supports both HW / SW bridging
705 createRxPatch = true;
706 createTxPatch = true;
François Gaffie9eb18552018-11-05 10:33:26 +0100707 } else {
708 // If the RX device is on the primary HW module, then use legacy routing method for
709 // voice calls via setOutputDevice() on primary output.
710 // Otherwise, create two audio patches for TX and RX path.
711 createRxPatch = !(availablePrimaryOutputDevices().contains(rxDevices.itemAt(0))) &&
712 (rxSourceDevice != 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700713 // If the TX device is also on the primary HW module, setOutputDevice() will take care
714 // of it due to legacy implementation. If not, create a patch.
François Gaffie9eb18552018-11-05 10:33:26 +0100715 createTxPatch = !(availablePrimaryModuleInputDevices().contains(txSourceDevice)) &&
716 (txSinkDevice != 0);
717 }
718 // Use legacy routing method for voice calls via setOutputDevice() on primary output.
719 // Otherwise, create two audio patches for TX and RX path.
720 if (!createRxPatch) {
721 muteWaitMs = setOutputDevices(mPrimaryOutput, rxDevices, true, delayMs);
Eric Laurent8ae73122016-04-12 10:13:29 -0700722 } else { // create RX path audio patch
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200723 connectTelephonyRxAudioSource();
juyuchen2224c5a2019-01-21 12:00:58 +0800724 // If the TX device is on the primary HW module but RX device is
725 // on other HW module, SinkMetaData of telephony input should handle it
726 // assuming the device uses audio HAL V5.0 and above
Eric Laurentc2730ba2014-07-20 15:47:07 -0700727 }
Eric Laurent8ae73122016-04-12 10:13:29 -0700728 if (createTxPatch) { // create TX path audio patch
François Gaffieafd4cea2019-11-18 15:50:22 +0100729 // terminate active capture if on the same HW module as the call TX source device
730 // FIXME: would be better to refine to only inputs whose profile connects to the
731 // call TX device but this information is not in the audio patch and logic here must be
732 // symmetric to the one in startInput()
733 for (const auto& activeDesc : mInputs.getActiveInputs()) {
734 if (activeDesc->hasSameHwModuleAs(txSourceDevice)) {
735 closeActiveClients(activeDesc);
736 }
737 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200738 connectTelephonyTxAudioSource(txSourceDevice, txSinkDevice, delayMs);
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800739 }
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100740 if (waitMs != nullptr) {
741 *waitMs = muteWaitMs;
742 }
743 return NO_ERROR;
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800744}
Eric Laurentc2730ba2014-07-20 15:47:07 -0700745
Mikhail Naganov100f0122018-11-29 11:22:16 -0800746bool AudioPolicyManager::isDeviceOfModule(
747 const sp<DeviceDescriptor>& devDesc, const char *moduleId) const {
748 sp<HwModule> module = mHwModules.getModuleFromName(moduleId);
749 if (module != 0) {
750 return mAvailableOutputDevices.getDevicesFromHwModule(module->getHandle())
751 .indexOf(devDesc) != NAME_NOT_FOUND
752 || mAvailableInputDevices.getDevicesFromHwModule(module->getHandle())
753 .indexOf(devDesc) != NAME_NOT_FOUND;
754 }
755 return false;
756}
757
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200758void AudioPolicyManager::connectTelephonyRxAudioSource()
759{
Francois Gaffie601801d2021-06-22 13:27:39 +0200760 disconnectTelephonyAudioSource(mCallRxSourceClient);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200761 const struct audio_port_config source = {
762 .role = AUDIO_PORT_ROLE_SOURCE, .type = AUDIO_PORT_TYPE_DEVICE,
763 .ext.device.type = AUDIO_DEVICE_IN_TELEPHONY_RX, .ext.device.address = ""
764 };
765 const auto aa = mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL);
Francois Gaffie601801d2021-06-22 13:27:39 +0200766 mCallRxSourceClient = startAudioSourceInternal(&source, &aa, 0/*uid*/);
767 ALOGE_IF(mCallRxSourceClient == nullptr,
768 "%s failed to start Telephony Rx AudioSource", __func__);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200769}
770
Francois Gaffie601801d2021-06-22 13:27:39 +0200771void AudioPolicyManager::disconnectTelephonyAudioSource(sp<SourceClientDescriptor> &clientDesc)
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200772{
Francois Gaffie601801d2021-06-22 13:27:39 +0200773 if (clientDesc == nullptr) {
774 return;
775 }
776 ALOGW_IF(stopAudioSource(clientDesc->portId()) != NO_ERROR,
777 "%s error stopping audio source", __func__);
778 clientDesc.clear();
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200779}
780
781void AudioPolicyManager::connectTelephonyTxAudioSource(
782 const sp<DeviceDescriptor> &srcDevice, const sp<DeviceDescriptor> &sinkDevice,
783 uint32_t delayMs)
784{
Francois Gaffie601801d2021-06-22 13:27:39 +0200785 disconnectTelephonyAudioSource(mCallTxSourceClient);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200786 if (srcDevice == nullptr || sinkDevice == nullptr) {
787 ALOGW("%s could not create patch, invalid sink and/or source device(s)", __func__);
788 return;
789 }
790 PatchBuilder patchBuilder;
791 patchBuilder.addSource(srcDevice).addSink(sinkDevice);
792 ALOGV("%s between source %s and sink %s", __func__,
793 srcDevice->toString().c_str(), sinkDevice->toString().c_str());
Francois Gaffie601801d2021-06-22 13:27:39 +0200794 auto callTxSourceClientPortId = PolicyAudioPort::getNextUniqueId();
Eric Laurent78b07302022-10-07 16:20:34 +0200795 const auto aa = mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL);
796
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200797 struct audio_port_config source = {};
798 srcDevice->toAudioPortConfig(&source);
Francois Gaffie601801d2021-06-22 13:27:39 +0200799 mCallTxSourceClient = new InternalSourceClientDescriptor(
800 callTxSourceClientPortId, mUidCached, aa, source, srcDevice, sinkDevice,
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200801 mCommunnicationStrategy, toVolumeSource(aa));
802 audio_patch_handle_t patchHandle = AUDIO_PATCH_HANDLE_NONE;
803 status_t status = connectAudioSourceToSink(
Francois Gaffie601801d2021-06-22 13:27:39 +0200804 mCallTxSourceClient, sinkDevice, patchBuilder.patch(), patchHandle, mUidCached,
805 delayMs);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200806 ALOGE_IF(status != NO_ERROR, "%s() error %d creating TX audio patch", __func__, status);
807 if (status == NO_ERROR) {
Francois Gaffie601801d2021-06-22 13:27:39 +0200808 mAudioSources.add(callTxSourceClientPortId, mCallTxSourceClient);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200809 }
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200810}
811
Eric Laurente0720872014-03-11 09:30:41 -0700812void AudioPolicyManager::setPhoneState(audio_mode_t state)
Eric Laurente552edb2014-03-10 17:42:56 -0700813{
814 ALOGV("setPhoneState() state %d", state);
François Gaffie2110e042015-03-24 08:41:51 +0100815 // store previous phone state for management of sonification strategy below
816 int oldState = mEngine->getPhoneState();
Eric Laurent96d1dda2022-03-14 17:14:19 +0100817 bool wasLeUnicastActive = isLeUnicastActive();
François Gaffie2110e042015-03-24 08:41:51 +0100818
819 if (mEngine->setPhoneState(state) != NO_ERROR) {
820 ALOGW("setPhoneState() invalid or same state %d", state);
Eric Laurente552edb2014-03-10 17:42:56 -0700821 return;
822 }
François Gaffie2110e042015-03-24 08:41:51 +0100823 /// Opens: can these line be executed after the switch of volume curves???
Eric Laurent63dea1d2015-07-02 17:10:28 -0700824 if (isStateInCall(oldState)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700825 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent63dea1d2015-07-02 17:10:28 -0700826 // force reevaluating accessibility routing when call stops
Eric Laurent2cbe89a2014-12-19 11:49:08 -0800827 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -0700828 }
829
François Gaffie2110e042015-03-24 08:41:51 +0100830 /**
831 * Switching to or from incall state or switching between telephony and VoIP lead to force
832 * routing command.
833 */
Eric Laurent74b71512019-11-06 17:21:57 -0800834 bool force = ((isStateInCall(oldState) != isStateInCall(state))
835 || (isStateInCall(state) && (state != oldState)));
Eric Laurente552edb2014-03-10 17:42:56 -0700836
837 // check for device and output changes triggered by new phone state
Mikhail Naganov37977152018-07-11 15:54:44 -0700838 checkForDeviceAndOutputChanges();
Eric Laurente552edb2014-03-10 17:42:56 -0700839
Eric Laurente552edb2014-03-10 17:42:56 -0700840 int delayMs = 0;
841 if (isStateInCall(state)) {
842 nsecs_t sysTime = systemTime();
François Gaffiec005e562018-11-06 15:04:49 +0100843 auto musicStrategy = streamToStrategy(AUDIO_STREAM_MUSIC);
844 auto sonificationStrategy = streamToStrategy(AUDIO_STREAM_ALARM);
Eric Laurente552edb2014-03-10 17:42:56 -0700845 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700846 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700847 // mute media and sonification strategies and delay device switch by the largest
848 // latency of any output where either strategy is active.
849 // This avoid sending the ring tone or music tail into the earpiece or headset.
François Gaffiec005e562018-11-06 15:04:49 +0100850 if ((desc->isStrategyActive(musicStrategy, SONIFICATION_HEADSET_MUSIC_DELAY, sysTime) ||
851 desc->isStrategyActive(sonificationStrategy, SONIFICATION_HEADSET_MUSIC_DELAY,
852 sysTime)) &&
Eric Laurentc75307b2015-03-17 15:29:32 -0700853 (delayMs < (int)desc->latency()*2)) {
854 delayMs = desc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -0700855 }
François Gaffiec005e562018-11-06 15:04:49 +0100856 setStrategyMute(musicStrategy, true, desc);
857 setStrategyMute(musicStrategy, false, desc, MUTE_TIME_MS,
858 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
859 nullptr, true /*fromCache*/).types());
860 setStrategyMute(sonificationStrategy, true, desc);
861 setStrategyMute(sonificationStrategy, false, desc, MUTE_TIME_MS,
862 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_ALARM),
863 nullptr, true /*fromCache*/).types());
Eric Laurente552edb2014-03-10 17:42:56 -0700864 }
865 }
866
Eric Laurent87ffa392015-05-22 10:32:38 -0700867 if (hasPrimaryOutput()) {
Eric Laurent87ffa392015-05-22 10:32:38 -0700868 if (state == AUDIO_MODE_IN_CALL) {
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100869 (void)updateCallRouting(false /*fromCache*/, delayMs);
Eric Laurent87ffa392015-05-22 10:32:38 -0700870 } else {
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100871 DeviceVector rxDevices = getNewOutputDevices(mPrimaryOutput, false /*fromCache*/);
872 // force routing command to audio hardware when ending call
873 // even if no device change is needed
874 if (isStateInCall(oldState) && rxDevices.isEmpty()) {
875 rxDevices = mPrimaryOutput->devices();
876 }
877 if (oldState == AUDIO_MODE_IN_CALL) {
Francois Gaffie601801d2021-06-22 13:27:39 +0200878 disconnectTelephonyAudioSource(mCallRxSourceClient);
879 disconnectTelephonyAudioSource(mCallTxSourceClient);
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100880 }
François Gaffie11d30102018-11-02 16:09:09 +0100881 setOutputDevices(mPrimaryOutput, rxDevices, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700882 }
Eric Laurentc2730ba2014-07-20 15:47:07 -0700883 }
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700884
885 // reevaluate routing on all outputs in case tracks have been started during the call
886 for (size_t i = 0; i < mOutputs.size(); i++) {
887 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
François Gaffie11d30102018-11-02 16:09:09 +0100888 DeviceVector newDevices = getNewOutputDevices(desc, true /*fromCache*/);
Francois Gaffie601801d2021-06-22 13:27:39 +0200889 if (state != AUDIO_MODE_IN_CALL || (desc != mPrimaryOutput && !isTelephonyRxOrTx(desc))) {
890 bool forceRouting = !newDevices.isEmpty();
891 setOutputDevices(desc, newDevices, forceRouting, 0 /*delayMs*/, nullptr,
892 true /*requiresMuteCheck*/, !forceRouting /*requiresVolumeCheck*/);
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700893 }
894 }
895
Eric Laurent96d1dda2022-03-14 17:14:19 +0100896 checkLeBroadcastRoutes(wasLeUnicastActive, nullptr, delayMs);
897
Eric Laurente552edb2014-03-10 17:42:56 -0700898 if (isStateInCall(state)) {
899 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent63dea1d2015-07-02 17:10:28 -0700900 // force reevaluating accessibility routing when call starts
901 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -0700902 }
903
904 // Flag that ringtone volume must be limited to music volume until we exit MODE_RINGTONE
François Gaffiec005e562018-11-06 15:04:49 +0100905 mLimitRingtoneVolume = (state == AUDIO_MODE_RINGTONE &&
906 isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY));
Eric Laurente552edb2014-03-10 17:42:56 -0700907}
908
Jean-Michel Trivi887a9ed2015-03-31 18:02:24 -0700909audio_mode_t AudioPolicyManager::getPhoneState() {
910 return mEngine->getPhoneState();
911}
912
Eric Laurente0720872014-03-11 09:30:41 -0700913void AudioPolicyManager::setForceUse(audio_policy_force_use_t usage,
François Gaffie11d30102018-11-02 16:09:09 +0100914 audio_policy_forced_cfg_t config)
Eric Laurente552edb2014-03-10 17:42:56 -0700915{
François Gaffie2110e042015-03-24 08:41:51 +0100916 ALOGV("setForceUse() usage %d, config %d, mPhoneState %d", usage, config, mEngine->getPhoneState());
Eric Laurent8dc87a62017-05-16 19:00:40 -0700917 if (config == mEngine->getForceUse(usage)) {
918 return;
919 }
Eric Laurente552edb2014-03-10 17:42:56 -0700920
François Gaffie2110e042015-03-24 08:41:51 +0100921 if (mEngine->setForceUse(usage, config) != NO_ERROR) {
922 ALOGW("setForceUse() could not set force cfg %d for usage %d", config, usage);
923 return;
Eric Laurente552edb2014-03-10 17:42:56 -0700924 }
François Gaffie2110e042015-03-24 08:41:51 +0100925 bool forceVolumeReeval = (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) ||
926 (usage == AUDIO_POLICY_FORCE_FOR_DOCK) ||
927 (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM);
Eric Laurente552edb2014-03-10 17:42:56 -0700928
929 // check for device and output changes triggered by new force usage
Mikhail Naganov37977152018-07-11 15:54:44 -0700930 checkForDeviceAndOutputChanges();
Phil Burk09bc4612016-02-24 15:58:15 -0800931
Eric Laurent22fcda22019-05-17 16:28:47 -0700932 // force client reconnection to reevaluate flag AUDIO_FLAG_AUDIBILITY_ENFORCED
933 if (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM) {
934 mpClientInterface->invalidateStream(AUDIO_STREAM_SYSTEM);
935 mpClientInterface->invalidateStream(AUDIO_STREAM_ENFORCED_AUDIBLE);
936 }
937
Eric Laurentdc462862016-07-19 12:29:53 -0700938 //FIXME: workaround for truncated touch sounds
939 // to be removed when the problem is handled by system UI
940 uint32_t delayMs = 0;
Eric Laurentdc462862016-07-19 12:29:53 -0700941 if (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) {
942 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
943 }
Jean-Michel Trivi30857152019-11-01 11:04:15 -0700944
945 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Eric Laurent2517af32020-11-25 15:31:27 +0100946 updateInputRouting();
Eric Laurente552edb2014-03-10 17:42:56 -0700947}
948
Eric Laurente0720872014-03-11 09:30:41 -0700949void AudioPolicyManager::setSystemProperty(const char* property, const char* value)
Eric Laurente552edb2014-03-10 17:42:56 -0700950{
951 ALOGV("setSystemProperty() property %s, value %s", property, value);
952}
953
Dorin Drimusecc9f422022-03-09 17:57:40 +0100954// Find an MSD output profile compatible with the parameters passed.
955// When "directOnly" is set, restrict search to profiles for direct outputs.
956sp<IOProfile> AudioPolicyManager::getMsdProfileForOutput(
957 const DeviceVector& devices,
958 uint32_t samplingRate,
959 audio_format_t format,
960 audio_channel_mask_t channelMask,
961 audio_output_flags_t flags,
962 bool directOnly)
963{
964 flags = getRelevantFlags(flags, directOnly);
965
966 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
967 if (msdModule != nullptr) {
968 // for the msd module check if there are patches to the output devices
969 if (msdHasPatchesToAllDevices(devices.toTypeAddrVector())) {
970 HwModuleCollection modules;
971 modules.add(msdModule);
972 return searchCompatibleProfileHwModules(
973 modules, getMsdAudioOutDevices(), samplingRate, format, channelMask,
974 flags, directOnly);
975 }
976 }
977 return nullptr;
978}
979
Michael Chana94fbb22018-04-24 14:31:19 +1000980// Find an output profile compatible with the parameters passed. When "directOnly" is set, restrict
981// search to profiles for direct outputs.
982sp<IOProfile> AudioPolicyManager::getProfileForOutput(
François Gaffie11d30102018-11-02 16:09:09 +0100983 const DeviceVector& devices,
Michael Chana94fbb22018-04-24 14:31:19 +1000984 uint32_t samplingRate,
985 audio_format_t format,
986 audio_channel_mask_t channelMask,
987 audio_output_flags_t flags,
988 bool directOnly)
Eric Laurente552edb2014-03-10 17:42:56 -0700989{
Dorin Drimusecc9f422022-03-09 17:57:40 +0100990 flags = getRelevantFlags(flags, directOnly);
991
992 return searchCompatibleProfileHwModules(
993 mHwModules, devices, samplingRate, format, channelMask, flags, directOnly);
994}
995
996audio_output_flags_t AudioPolicyManager::getRelevantFlags (
997 audio_output_flags_t flags, bool directOnly) {
Michael Chana94fbb22018-04-24 14:31:19 +1000998 if (directOnly) {
Dorin Drimusecc9f422022-03-09 17:57:40 +0100999 // only retain flags that will drive the direct output profile selection
1000 // if explicitly requested
1001 static const uint32_t kRelevantFlags =
Michael Chana94fbb22018-04-24 14:31:19 +10001002 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD |
Dorin Drimusecc9f422022-03-09 17:57:40 +01001003 AUDIO_OUTPUT_FLAG_VOIP_RX | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ);
1004 flags = (audio_output_flags_t)((flags & kRelevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
Michael Chana94fbb22018-04-24 14:31:19 +10001005 }
Dorin Drimusecc9f422022-03-09 17:57:40 +01001006 return flags;
1007}
Eric Laurent861a6282015-05-18 15:40:16 -07001008
Dorin Drimusecc9f422022-03-09 17:57:40 +01001009sp<IOProfile> AudioPolicyManager::searchCompatibleProfileHwModules (
1010 const HwModuleCollection& hwModules,
1011 const DeviceVector& devices,
1012 uint32_t samplingRate,
1013 audio_format_t format,
1014 audio_channel_mask_t channelMask,
1015 audio_output_flags_t flags,
1016 bool directOnly) {
Eric Laurent861a6282015-05-18 15:40:16 -07001017 sp<IOProfile> profile;
Dorin Drimusecc9f422022-03-09 17:57:40 +01001018 for (const auto& hwModule : hwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08001019 for (const auto& curProfile : hwModule->getOutputProfiles()) {
Dorin Drimusecc9f422022-03-09 17:57:40 +01001020 if (!curProfile->isCompatibleProfile(devices,
1021 samplingRate, NULL /*updatedSamplingRate*/,
1022 format, NULL /*updatedFormat*/,
1023 channelMask, NULL /*updatedChannelMask*/,
1024 flags)) {
1025 continue;
1026 }
1027 // reject profiles not corresponding to a device currently available
1028 if (!mAvailableOutputDevices.containsAtLeastOne(curProfile->getSupportedDevices())) {
1029 continue;
1030 }
1031 // reject profiles if connected device does not support codec
1032 if (!curProfile->devicesSupportEncodedFormats(devices.types())) {
1033 continue;
1034 }
1035 if (!directOnly) {
1036 return curProfile;
1037 }
1038
1039 // when searching for direct outputs, if several profiles are compatible, give priority
1040 // to one with offload capability
Patty Huangf5082dd2022-07-06 00:14:12 +08001041 if (profile != 0 &&
Dorin Drimusecc9f422022-03-09 17:57:40 +01001042 ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0)) {
Eric Laurent861a6282015-05-18 15:40:16 -07001043 continue;
Dorin Drimusecc9f422022-03-09 17:57:40 +01001044 }
1045 profile = curProfile;
1046 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1047 break;
1048 }
Eric Laurente552edb2014-03-10 17:42:56 -07001049 }
1050 }
Eric Laurent861a6282015-05-18 15:40:16 -07001051 return profile;
Eric Laurente552edb2014-03-10 17:42:56 -07001052}
1053
Eric Laurentfa0f6742021-08-17 18:39:44 +02001054sp<IOProfile> AudioPolicyManager::getSpatializerOutputProfile(
Eric Laurent39095982021-08-24 18:29:27 +02001055 const audio_config_t *config __unused, const AudioDeviceTypeAddrVector &devices) const
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001056{
1057 for (const auto& hwModule : mHwModules) {
1058 for (const auto& curProfile : hwModule->getOutputProfiles()) {
Eric Laurent1c5e2e32021-08-18 18:50:28 +02001059 if (curProfile->getFlags() != AUDIO_OUTPUT_FLAG_SPATIALIZER) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001060 continue;
1061 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001062 if (!devices.empty()) {
Eric Laurent0c8f7cc2022-06-24 14:32:36 +02001063 // reject profiles not corresponding to a device currently available
1064 DeviceVector supportedDevices = curProfile->getSupportedDevices();
1065 if (!mAvailableOutputDevices.containsAtLeastOne(supportedDevices)) {
1066 continue;
1067 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001068 if (supportedDevices.getDevicesFromDeviceTypeAddrVec(devices).size()
1069 != devices.size()) {
1070 continue;
1071 }
1072 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001073 ALOGV("%s found profile %s", __func__, curProfile->getName().c_str());
1074 return curProfile;
1075 }
1076 }
1077 return nullptr;
1078}
1079
Eric Laurentf4e63452017-11-06 19:31:46 +00001080audio_io_handle_t AudioPolicyManager::getOutput(audio_stream_type_t stream)
Eric Laurente552edb2014-03-10 17:42:56 -07001081{
François Gaffiec005e562018-11-06 15:04:49 +01001082 DeviceVector devices = mEngine->getOutputDevicesForStream(stream, false /*fromCache*/);
Andy Hungc9901522017-11-10 20:07:54 -08001083
1084 // Note that related method getOutputForAttr() uses getOutputForDevice() not selectOutput().
1085 // We use selectOutput() here since we don't have the desired AudioTrack sample rate,
1086 // format, flags, etc. This may result in some discrepancy for functions that utilize
1087 // getOutput() solely on audio_stream_type such as AudioSystem::getOutputFrameCount()
1088 // and AudioSystem::getOutputSamplingRate().
1089
François Gaffie11d30102018-11-02 16:09:09 +01001090 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Mingyu Shih75563d32023-05-24 04:47:40 +08001091 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
1092 if (stream == AUDIO_STREAM_MUSIC &&
1093 property_get_bool("audio.deep_buffer.media", false /* default_value */)) {
1094 flags = AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
1095 }
1096 const audio_io_handle_t output = selectOutput(outputs, flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001097
François Gaffie11d30102018-11-02 16:09:09 +01001098 ALOGV("getOutput() stream %d selected devices %s, output %d", stream,
1099 devices.toString().c_str(), output);
Eric Laurentf4e63452017-11-06 19:31:46 +00001100 return output;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001101}
1102
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001103status_t AudioPolicyManager::getAudioAttributes(audio_attributes_t *dstAttr,
1104 const audio_attributes_t *srcAttr,
1105 audio_stream_type_t srcStream)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001106{
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001107 if (srcAttr != NULL) {
1108 if (!isValidAttributes(srcAttr)) {
1109 ALOGE("%s invalid attributes: usage=%d content=%d flags=0x%x tags=[%s]",
1110 __func__,
1111 srcAttr->usage, srcAttr->content_type, srcAttr->flags,
1112 srcAttr->tags);
1113 return BAD_VALUE;
1114 }
1115 *dstAttr = *srcAttr;
1116 } else {
1117 if (srcStream < AUDIO_STREAM_MIN || srcStream >= AUDIO_STREAM_PUBLIC_CNT) {
1118 ALOGE("%s: invalid stream type", __func__);
1119 return BAD_VALUE;
1120 }
François Gaffiec005e562018-11-06 15:04:49 +01001121 *dstAttr = mEngine->getAttributesForStreamType(srcStream);
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001122 }
Eric Laurent22fcda22019-05-17 16:28:47 -07001123
1124 // Only honor audibility enforced when required. The client will be
1125 // forced to reconnect if the forced usage changes.
1126 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Mikhail Naganov55773032020-10-01 15:08:13 -07001127 dstAttr->flags = static_cast<audio_flags_mask_t>(
1128 dstAttr->flags & ~AUDIO_FLAG_AUDIBILITY_ENFORCED);
Eric Laurent22fcda22019-05-17 16:28:47 -07001129 }
1130
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001131 return NO_ERROR;
1132}
1133
Kevin Rocard153f92d2018-12-18 18:33:28 -08001134status_t AudioPolicyManager::getOutputForAttrInt(
1135 audio_attributes_t *resultAttr,
1136 audio_io_handle_t *output,
1137 audio_session_t session,
1138 const audio_attributes_t *attr,
1139 audio_stream_type_t *stream,
1140 uid_t uid,
1141 const audio_config_t *config,
1142 audio_output_flags_t *flags,
1143 audio_port_handle_t *selectedDeviceId,
1144 bool *isRequestedDeviceForExclusiveUse,
Eric Laurentc529cf62020-04-17 18:19:10 -07001145 std::vector<sp<AudioPolicyMix>> *secondaryMixes,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001146 output_type_t *outputType,
1147 bool *isSpatialized)
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001148{
François Gaffiec005e562018-11-06 15:04:49 +01001149 DeviceVector outputDevices;
Francois Gaffie716e1432019-01-14 16:58:59 +01001150 const audio_port_handle_t requestedPortId = *selectedDeviceId;
François Gaffie11d30102018-11-02 16:09:09 +01001151 DeviceVector msdDevices = getMsdAudioOutDevices();
François Gaffiec005e562018-11-06 15:04:49 +01001152 const sp<DeviceDescriptor> requestedDevice =
1153 mAvailableOutputDevices.getDeviceFromId(requestedPortId);
1154
Eric Laurent8a1095a2019-11-08 14:44:16 -08001155 *outputType = API_OUTPUT_INVALID;
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001156 *isSpatialized = false;
1157
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001158 status_t status = getAudioAttributes(resultAttr, attr, *stream);
1159 if (status != NO_ERROR) {
1160 return status;
Eric Laurent8f42ea12018-08-08 09:08:25 -07001161 }
Kevin Rocardb99cc752019-03-21 20:52:24 -07001162 if (auto it = mAllowedCapturePolicies.find(uid); it != end(mAllowedCapturePolicies)) {
Mikhail Naganov55773032020-10-01 15:08:13 -07001163 resultAttr->flags = static_cast<audio_flags_mask_t>(resultAttr->flags | it->second);
Kevin Rocardb99cc752019-03-21 20:52:24 -07001164 }
François Gaffiec005e562018-11-06 15:04:49 +01001165 *stream = mEngine->getStreamTypeForAttributes(*resultAttr);
Eric Laurent8f42ea12018-08-08 09:08:25 -07001166
François Gaffiec005e562018-11-06 15:04:49 +01001167 ALOGV("%s() attributes=%s stream=%s session %d selectedDeviceId %d", __func__,
1168 toString(*resultAttr).c_str(), toString(*stream).c_str(), session, requestedPortId);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001169
Kevin Rocard153f92d2018-12-18 18:33:28 -08001170 // The primary output is the explicit routing (eg. setPreferredDevice) if specified,
1171 // otherwise, fallback to the dynamic policies, if none match, query the engine.
1172 // Secondary outputs are always found by dynamic policies as the engine do not support them
Eric Laurentc529cf62020-04-17 18:19:10 -07001173 sp<AudioPolicyMix> primaryMix;
Dean Wheatleyd082f472022-02-04 11:10:48 +11001174 const audio_config_base_t clientConfig = {.sample_rate = config->sample_rate,
1175 .channel_mask = config->channel_mask,
1176 .format = config->format,
1177 };
1178 status = mPolicyMixes.getOutputForAttr(*resultAttr, clientConfig, uid, *flags, primaryMix,
1179 secondaryMixes);
Kevin Rocard94114a22019-04-01 19:38:23 -07001180 if (status != OK) {
1181 return status;
Kevin Rocard153f92d2018-12-18 18:33:28 -08001182 }
Kevin Rocard94114a22019-04-01 19:38:23 -07001183
Kevin Rocard153f92d2018-12-18 18:33:28 -08001184 // Explicit routing is higher priority then any dynamic policy primary output
Eric Laurentc529cf62020-04-17 18:19:10 -07001185 bool usePrimaryOutputFromPolicyMixes = requestedDevice == nullptr && primaryMix != nullptr;
Kevin Rocard153f92d2018-12-18 18:33:28 -08001186
1187 // FIXME: in case of RENDER policy, the output capabilities should be checked
Dean Wheatleyd082f472022-02-04 11:10:48 +11001188 if ((secondaryMixes != nullptr && !secondaryMixes->empty())
1189 && !audio_is_linear_pcm(config->format)) {
1190 ALOGD("%s: rejecting request as secondary mixes only support pcm", __func__);
Kevin Rocard153f92d2018-12-18 18:33:28 -08001191 return BAD_VALUE;
1192 }
1193 if (usePrimaryOutputFromPolicyMixes) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001194 sp<DeviceDescriptor> deviceDesc =
1195 mAvailableOutputDevices.getDevice(primaryMix->mDeviceType,
1196 primaryMix->mDeviceAddress,
1197 AUDIO_FORMAT_DEFAULT);
1198 sp<SwAudioOutputDescriptor> policyDesc = primaryMix->getOutput();
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001199 bool tryDirectForFlags = policyDesc == nullptr ||
1200 (policyDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT);
1201 // if a direct output can be opened to deliver the track's multi-channel content to the
1202 // output rather than being downmixed by the primary output, then use this direct
1203 // output by by-passing the primary mix if possible, otherwise fall-through to primary
1204 // mix.
1205 bool tryDirectForChannelMask = policyDesc != nullptr
1206 && (audio_channel_count_from_out_mask(policyDesc->getConfig().channel_mask) <
1207 audio_channel_count_from_out_mask(config->channel_mask));
1208 if (deviceDesc != nullptr && (tryDirectForFlags || tryDirectForChannelMask)) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001209 audio_io_handle_t newOutput;
1210 status = openDirectOutput(
1211 *stream, session, config,
1212 (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT),
1213 DeviceVector(deviceDesc), &newOutput);
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001214 if (status == NO_ERROR) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001215 policyDesc = mOutputs.valueFor(newOutput);
1216 primaryMix->setOutput(policyDesc);
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001217 } else if (tryDirectForFlags) {
1218 policyDesc = nullptr;
1219 } // otherwise use primary if available.
Eric Laurentc529cf62020-04-17 18:19:10 -07001220 }
1221 if (policyDesc != nullptr) {
1222 policyDesc->mPolicyMix = primaryMix;
1223 *output = policyDesc->mIoHandle;
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08001224 *selectedDeviceId = deviceDesc != 0 ? deviceDesc->getId() : AUDIO_PORT_HANDLE_NONE;
Eric Laurent8a1095a2019-11-08 14:44:16 -08001225
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08001226 ALOGV("getOutputForAttr() returns output %d", *output);
1227 if (resultAttr->usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
1228 *outputType = API_OUT_MIX_PLAYBACK;
1229 } else {
1230 *outputType = API_OUTPUT_LEGACY;
1231 }
1232 return NO_ERROR;
Eric Laurent8a1095a2019-11-08 14:44:16 -08001233 }
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001234 }
François Gaffiec005e562018-11-06 15:04:49 +01001235 // Virtual sources must always be dynamicaly or explicitly routed
1236 if (resultAttr->usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
1237 ALOGW("getOutputForAttr() no policy mix found for usage AUDIO_USAGE_VIRTUAL_SOURCE");
1238 return BAD_VALUE;
1239 }
1240 // explicit routing managed by getDeviceForStrategy in APM is now handled by engine
1241 // in order to let the choice of the order to future vendor engine
1242 outputDevices = mEngine->getOutputDevicesForAttributes(*resultAttr, requestedDevice, false);
Scott Randolph7b1fd232018-06-18 15:33:03 -07001243
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001244 if ((resultAttr->flags & AUDIO_FLAG_HW_AV_SYNC) != 0) {
Nadav Bar766fb022018-01-07 12:18:03 +02001245 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
Eric Laurent93c3d412014-08-01 14:48:35 -07001246 }
1247
Nadav Barb2f18162018-07-18 13:01:53 +03001248 // Set incall music only if device was explicitly set, and fallback to the device which is
1249 // chosen by the engine if not.
1250 // FIXME: provide a more generic approach which is not device specific and move this back
1251 // to getOutputForDevice.
Nadav Bar20919492018-11-20 10:20:51 +02001252 // TODO: Remove check of AUDIO_STREAM_MUSIC once migration is completed on the app side.
jiabin9a3361e2019-10-01 09:38:30 -07001253 if (outputDevices.onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_TELEPHONY_TX) &&
François Gaffiec005e562018-11-06 15:04:49 +01001254 (*stream == AUDIO_STREAM_MUSIC || resultAttr->usage == AUDIO_USAGE_VOICE_COMMUNICATION) &&
Nadav Barb2f18162018-07-18 13:01:53 +03001255 audio_is_linear_pcm(config->format) &&
Eric Laurent74b71512019-11-06 17:21:57 -08001256 isCallAudioAccessible()) {
Francois Gaffie716e1432019-01-14 16:58:59 +01001257 if (requestedPortId != AUDIO_PORT_HANDLE_NONE) {
Nadav Barb2f18162018-07-18 13:01:53 +03001258 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_INCALL_MUSIC;
François Gaffief579db52018-11-13 11:25:16 +01001259 *isRequestedDeviceForExclusiveUse = true;
Nadav Barb2f18162018-07-18 13:01:53 +03001260 }
1261 }
1262
François Gaffiec005e562018-11-06 15:04:49 +01001263 ALOGV("%s() device %s, sampling rate %d, format %#x, channel mask %#x, flags %#x stream %s",
1264 __func__, outputDevices.toString().c_str(), config->sample_rate, config->format,
1265 config->channel_mask, *flags, toString(*stream).c_str());
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001266
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001267 *output = AUDIO_IO_HANDLE_NONE;
François Gaffie11d30102018-11-02 16:09:09 +01001268 if (!msdDevices.isEmpty()) {
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001269 *output = getOutputForDevices(msdDevices, session, resultAttr, config, flags, isSpatialized);
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001270 if (*output != AUDIO_IO_HANDLE_NONE && setMsdOutputPatches(&outputDevices) == NO_ERROR) {
François Gaffiec005e562018-11-06 15:04:49 +01001271 ALOGV("%s() Using MSD devices %s instead of devices %s",
1272 __func__, msdDevices.toString().c_str(), outputDevices.toString().c_str());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001273 } else {
1274 *output = AUDIO_IO_HANDLE_NONE;
1275 }
1276 }
1277 if (*output == AUDIO_IO_HANDLE_NONE) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001278 *output = getOutputForDevices(outputDevices, session, resultAttr, config,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001279 flags, isSpatialized, resultAttr->flags & AUDIO_FLAG_MUTE_HAPTIC);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001280 }
Eric Laurente83b55d2014-11-14 10:06:21 -08001281 if (*output == AUDIO_IO_HANDLE_NONE) {
1282 return INVALID_OPERATION;
1283 }
Paul McLeanaa981192015-03-21 09:55:15 -07001284
François Gaffiec005e562018-11-06 15:04:49 +01001285 *selectedDeviceId = getFirstDeviceId(outputDevices);
Michael Chan6fb34492020-12-08 15:44:49 +11001286 for (auto &outputDevice : outputDevices) {
Mikhail Naganovb0fbc1b2023-04-28 13:06:32 -07001287 if (outputDevice->getId() == mConfig->getDefaultOutputDevice()->getId()) {
Michael Chan6fb34492020-12-08 15:44:49 +11001288 *selectedDeviceId = outputDevice->getId();
1289 break;
1290 }
1291 }
Eric Laurent2ac76942017-06-22 17:17:09 -07001292
Eric Laurent8a1095a2019-11-08 14:44:16 -08001293 if (outputDevices.onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_TELEPHONY_TX)) {
1294 *outputType = API_OUTPUT_TELEPHONY_TX;
1295 } else {
1296 *outputType = API_OUTPUT_LEGACY;
1297 }
1298
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001299 ALOGV("%s returns output %d selectedDeviceId %d", __func__, *output, *selectedDeviceId);
1300
1301 return NO_ERROR;
1302}
1303
1304status_t AudioPolicyManager::getOutputForAttr(const audio_attributes_t *attr,
1305 audio_io_handle_t *output,
1306 audio_session_t session,
1307 audio_stream_type_t *stream,
Svet Ganov3e5f14f2021-05-13 22:51:08 +00001308 const AttributionSourceState& attributionSource,
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001309 const audio_config_t *config,
1310 audio_output_flags_t *flags,
1311 audio_port_handle_t *selectedDeviceId,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001312 audio_port_handle_t *portId,
Eric Laurent8a1095a2019-11-08 14:44:16 -08001313 std::vector<audio_io_handle_t> *secondaryOutputs,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001314 output_type_t *outputType,
1315 bool *isSpatialized)
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001316{
1317 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
1318 if (*portId != AUDIO_PORT_HANDLE_NONE) {
1319 return INVALID_OPERATION;
1320 }
Philip P. Moltmannbda45752020-07-17 16:41:18 -07001321 const uid_t uid = VALUE_OR_RETURN_STATUS(
Svet Ganov3e5f14f2021-05-13 22:51:08 +00001322 aidl2legacy_int32_t_uid_t(attributionSource.uid));
Francois Gaffie716e1432019-01-14 16:58:59 +01001323 const audio_port_handle_t requestedPortId = *selectedDeviceId;
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001324 audio_attributes_t resultAttr;
François Gaffief579db52018-11-13 11:25:16 +01001325 bool isRequestedDeviceForExclusiveUse = false;
Eric Laurentc529cf62020-04-17 18:19:10 -07001326 std::vector<sp<AudioPolicyMix>> secondaryMixes;
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001327 const sp<DeviceDescriptor> requestedDevice =
1328 mAvailableOutputDevices.getDeviceFromId(requestedPortId);
1329
1330 // Prevent from storing invalid requested device id in clients
1331 const audio_port_handle_t sanitizedRequestedPortId =
1332 requestedDevice != nullptr ? requestedPortId : AUDIO_PORT_HANDLE_NONE;
1333 *selectedDeviceId = sanitizedRequestedPortId;
1334
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001335 status_t status = getOutputForAttrInt(&resultAttr, output, session, attr, stream, uid,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001336 config, flags, selectedDeviceId, &isRequestedDeviceForExclusiveUse,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001337 secondaryOutputs != nullptr ? &secondaryMixes : nullptr, outputType, isSpatialized);
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001338 if (status != NO_ERROR) {
1339 return status;
1340 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001341 std::vector<wp<SwAudioOutputDescriptor>> weakSecondaryOutputDescs;
Eric Laurentc529cf62020-04-17 18:19:10 -07001342 if (secondaryOutputs != nullptr) {
1343 for (auto &secondaryMix : secondaryMixes) {
1344 sp<SwAudioOutputDescriptor> outputDesc = secondaryMix->getOutput();
1345 if (outputDesc != nullptr &&
1346 outputDesc->mIoHandle != AUDIO_IO_HANDLE_NONE) {
1347 secondaryOutputs->push_back(outputDesc->mIoHandle);
1348 weakSecondaryOutputDescs.push_back(outputDesc);
1349 }
1350 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001351 }
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001352
Eric Laurent8fc147b2018-07-22 19:13:55 -07001353 audio_config_base_t clientConfig = {.sample_rate = config->sample_rate,
Nick Desaulniersa30e3202019-10-18 13:38:23 -07001354 .channel_mask = config->channel_mask,
Eric Laurent8fc147b2018-07-22 19:13:55 -07001355 .format = config->format,
Nick Desaulniersa30e3202019-10-18 13:38:23 -07001356 };
jiabin4ef93452019-09-10 14:29:54 -07001357 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurent8f42ea12018-08-08 09:08:25 -07001358
Eric Laurentc209fe42020-06-05 18:11:23 -07001359 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(*output);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001360 sp<TrackClientDescriptor> clientDesc =
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001361 new TrackClientDescriptor(*portId, uid, session, resultAttr, clientConfig,
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001362 sanitizedRequestedPortId, *stream,
François Gaffiec005e562018-11-06 15:04:49 +01001363 mEngine->getProductStrategyForAttributes(resultAttr),
François Gaffieaaac0fd2018-11-22 17:56:39 +01001364 toVolumeSource(resultAttr),
Kevin Rocard153f92d2018-12-18 18:33:28 -08001365 *flags, isRequestedDeviceForExclusiveUse,
Eric Laurentc209fe42020-06-05 18:11:23 -07001366 std::move(weakSecondaryOutputDescs),
1367 outputDesc->mPolicyMix);
Andy Hung39efb7a2018-09-26 15:39:28 -07001368 outputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001369
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001370 ALOGV("%s() returns output %d requestedPortId %d selectedDeviceId %d for port ID %d", __func__,
1371 *output, requestedPortId, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07001372
Eric Laurente83b55d2014-11-14 10:06:21 -08001373 return NO_ERROR;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001374}
1375
Eric Laurentc529cf62020-04-17 18:19:10 -07001376status_t AudioPolicyManager::openDirectOutput(audio_stream_type_t stream,
1377 audio_session_t session,
1378 const audio_config_t *config,
1379 audio_output_flags_t flags,
1380 const DeviceVector &devices,
1381 audio_io_handle_t *output) {
1382
1383 *output = AUDIO_IO_HANDLE_NONE;
1384
1385 // skip direct output selection if the request can obviously be attached to a mixed output
1386 // and not explicitly requested
1387 if (((flags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
1388 audio_is_linear_pcm(config->format) && config->sample_rate <= SAMPLE_RATE_HZ_MAX &&
1389 audio_channel_count_from_out_mask(config->channel_mask) <= 2) {
1390 return NAME_NOT_FOUND;
1391 }
1392
1393 // Do not allow offloading if one non offloadable effect is enabled or MasterMono is enabled.
1394 // This prevents creating an offloaded track and tearing it down immediately after start
1395 // when audioflinger detects there is an active non offloadable effect.
1396 // FIXME: We should check the audio session here but we do not have it in this context.
1397 // This may prevent offloading in rare situations where effects are left active by apps
1398 // in the background.
1399 sp<IOProfile> profile;
1400 if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) ||
1401 !(mEffects.isNonOffloadableEffectEnabled() || mMasterMono)) {
1402 profile = getProfileForOutput(
1403 devices, config->sample_rate, config->format, config->channel_mask,
1404 flags, true /* directOnly */);
1405 }
1406
1407 if (profile == nullptr) {
1408 return NAME_NOT_FOUND;
1409 }
1410
1411 // exclusive outputs for MMAP and Offload are enforced by different session ids.
1412 for (size_t i = 0; i < mOutputs.size(); i++) {
1413 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
1414 if (!desc->isDuplicated() && (profile == desc->mProfile)) {
1415 // reuse direct output if currently open by the same client
1416 // and configured with same parameters
1417 if ((config->sample_rate == desc->getSamplingRate()) &&
1418 (config->format == desc->getFormat()) &&
1419 (config->channel_mask == desc->getChannelMask()) &&
1420 (session == desc->mDirectClientSession)) {
1421 desc->mDirectOpenCount++;
Eric Laurentfecbceb2021-02-09 14:46:43 +01001422 ALOGV("%s reusing direct output %d for session %d", __func__,
Eric Laurentc529cf62020-04-17 18:19:10 -07001423 mOutputs.keyAt(i), session);
1424 *output = mOutputs.keyAt(i);
1425 return NO_ERROR;
1426 }
1427 }
1428 }
1429
1430 if (!profile->canOpenNewIo()) {
1431 return NAME_NOT_FOUND;
1432 }
1433
1434 sp<SwAudioOutputDescriptor> outputDesc =
1435 new SwAudioOutputDescriptor(profile, mpClientInterface);
1436
Michael Chan6fb34492020-12-08 15:44:49 +11001437 // An MSD patch may be using the only output stream that can service this request. Release
1438 // all MSD patches to prioritize this request over any active output on MSD.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001439 releaseMsdOutputPatches(devices);
Eric Laurentc529cf62020-04-17 18:19:10 -07001440
Eric Laurentf1f22e72021-07-13 14:04:14 +02001441 status_t status =
1442 outputDesc->open(config, nullptr /* mixerConfig */, devices, stream, flags, output);
Eric Laurentc529cf62020-04-17 18:19:10 -07001443
1444 // only accept an output with the requested parameters
1445 if (status != NO_ERROR ||
1446 (config->sample_rate != 0 && config->sample_rate != outputDesc->getSamplingRate()) ||
1447 (config->format != AUDIO_FORMAT_DEFAULT && config->format != outputDesc->getFormat()) ||
1448 (config->channel_mask != 0 && config->channel_mask != outputDesc->getChannelMask())) {
1449 ALOGV("%s failed opening direct output: output %d sample rate %d %d,"
1450 "format %d %d, channel mask %04x %04x", __func__, *output, config->sample_rate,
1451 outputDesc->getSamplingRate(), config->format, outputDesc->getFormat(),
1452 config->channel_mask, outputDesc->getChannelMask());
1453 if (*output != AUDIO_IO_HANDLE_NONE) {
1454 outputDesc->close();
1455 }
1456 // fall back to mixer output if possible when the direct output could not be open
1457 if (audio_is_linear_pcm(config->format) &&
1458 config->sample_rate <= SAMPLE_RATE_HZ_MAX) {
1459 return NAME_NOT_FOUND;
1460 }
1461 *output = AUDIO_IO_HANDLE_NONE;
1462 return BAD_VALUE;
1463 }
1464 outputDesc->mDirectOpenCount = 1;
1465 outputDesc->mDirectClientSession = session;
1466
1467 addOutput(*output, outputDesc);
1468 mPreviousOutputs = mOutputs;
1469 ALOGV("%s returns new direct output %d", __func__, *output);
1470 mpClientInterface->onAudioPortListUpdate();
1471 return NO_ERROR;
1472}
1473
François Gaffie11d30102018-11-02 16:09:09 +01001474audio_io_handle_t AudioPolicyManager::getOutputForDevices(
1475 const DeviceVector &devices,
Kevin Rocard169753c2017-03-06 14:18:23 -08001476 audio_session_t session,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001477 const audio_attributes_t *attr,
Eric Laurentfe231122017-11-17 17:48:06 -08001478 const audio_config_t *config,
jiabine375d412019-02-26 12:54:53 -08001479 audio_output_flags_t *flags,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001480 bool *isSpatialized,
jiabine375d412019-02-26 12:54:53 -08001481 bool forceMutingHaptic)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001482{
Andy Hungc88b0642018-04-27 15:42:35 -07001483 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001484
jiabine375d412019-02-26 12:54:53 -08001485 // Discard haptic channel mask when forcing muting haptic channels.
1486 audio_channel_mask_t channelMask = forceMutingHaptic
Mikhail Naganov55773032020-10-01 15:08:13 -07001487 ? static_cast<audio_channel_mask_t>(config->channel_mask & ~AUDIO_CHANNEL_HAPTIC_ALL)
1488 : config->channel_mask;
jiabine375d412019-02-26 12:54:53 -08001489
Eric Laurente552edb2014-03-10 17:42:56 -07001490 // open a direct output if required by specified parameters
1491 //force direct flag if offload flag is set: offloading implies a direct output stream
1492 // and all common behaviors are driven by checking only the direct flag
1493 // this should normally be set appropriately in the policy configuration file
Nadav Bar766fb022018-01-07 12:18:03 +02001494 if ((*flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1495 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurente552edb2014-03-10 17:42:56 -07001496 }
Nadav Bar766fb022018-01-07 12:18:03 +02001497 if ((*flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
1498 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent93c3d412014-08-01 14:48:35 -07001499 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001500
1501 audio_stream_type_t stream = mEngine->getStreamTypeForAttributes(*attr);
1502
Eric Laurente83b55d2014-11-14 10:06:21 -08001503 // only allow deep buffering for music stream type
1504 if (stream != AUDIO_STREAM_MUSIC) {
Nadav Bar766fb022018-01-07 12:18:03 +02001505 *flags = (audio_output_flags_t)(*flags &~AUDIO_OUTPUT_FLAG_DEEP_BUFFER);
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -07001506 } else if (/* stream == AUDIO_STREAM_MUSIC && */
Nadav Bar766fb022018-01-07 12:18:03 +02001507 *flags == AUDIO_OUTPUT_FLAG_NONE &&
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -07001508 property_get_bool("audio.deep_buffer.media", false /* default_value */)) {
1509 // use DEEP_BUFFER as default output for music stream type
Nadav Bar766fb022018-01-07 12:18:03 +02001510 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
Eric Laurente83b55d2014-11-14 10:06:21 -08001511 }
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -07001512 if (stream == AUDIO_STREAM_TTS) {
Nadav Bar766fb022018-01-07 12:18:03 +02001513 *flags = AUDIO_OUTPUT_FLAG_TTS;
Haynes Mathew George84c621e2017-04-25 11:41:50 -07001514 } else if (stream == AUDIO_STREAM_VOICE_CALL &&
Nadav Bar20919492018-11-20 10:20:51 +02001515 audio_is_linear_pcm(config->format) &&
1516 (*flags & AUDIO_OUTPUT_FLAG_INCALL_MUSIC) == 0) {
Nadav Bar766fb022018-01-07 12:18:03 +02001517 *flags = (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_VOIP_RX |
Haynes Mathew George84c621e2017-04-25 11:41:50 -07001518 AUDIO_OUTPUT_FLAG_DIRECT);
1519 ALOGV("Set VoIP and Direct output flags for PCM format");
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -07001520 }
Eric Laurente552edb2014-03-10 17:42:56 -07001521
Carter Hsua3abb402021-10-26 11:11:20 +08001522 // Attach the Ultrasound flag for the AUDIO_CONTENT_TYPE_ULTRASOUND
1523 if (attr->content_type == AUDIO_CONTENT_TYPE_ULTRASOUND) {
1524 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_ULTRASOUND);
1525 }
1526
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001527 *isSpatialized = false;
Eric Laurentfa0f6742021-08-17 18:39:44 +02001528 if (mSpatializerOutput != nullptr
Andy Hung9dd1a5b2022-05-10 15:39:39 -07001529 && canBeSpatializedInt(attr, config, devices.toTypeAddrVector())) {
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001530 *isSpatialized = true;
Eric Laurentfa0f6742021-08-17 18:39:44 +02001531 return mSpatializerOutput->mIoHandle;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001532 }
1533
Eric Laurentc529cf62020-04-17 18:19:10 -07001534 audio_config_t directConfig = *config;
1535 directConfig.channel_mask = channelMask;
1536 status_t status = openDirectOutput(stream, session, &directConfig, *flags, devices, &output);
1537 if (status != NAME_NOT_FOUND) {
Eric Laurente552edb2014-03-10 17:42:56 -07001538 return output;
1539 }
1540
Eric Laurent14cbfca2016-03-17 09:42:16 -07001541 // A request for HW A/V sync cannot fallback to a mixed output because time
1542 // stamps are embedded in audio data
Phil Burk2d059932018-02-15 15:55:11 -08001543 if ((*flags & (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ)) != 0) {
Eric Laurent14cbfca2016-03-17 09:42:16 -07001544 return AUDIO_IO_HANDLE_NONE;
1545 }
Pierre Couillaude73496b2023-03-06 16:19:05 +00001546 // A request for Tuner cannot fallback to a mixed output
1547 if ((directConfig.offload_info.content_id || directConfig.offload_info.sync_id)) {
1548 return AUDIO_IO_HANDLE_NONE;
1549 }
Eric Laurent14cbfca2016-03-17 09:42:16 -07001550
Eric Laurente552edb2014-03-10 17:42:56 -07001551 // ignoring channel mask due to downmix capability in mixer
1552
1553 // open a non direct output
1554
1555 // for non direct outputs, only PCM is supported
Eric Laurentfe231122017-11-17 17:48:06 -08001556 if (audio_is_linear_pcm(config->format)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001557 // get which output is suitable for the specified stream. The actual
1558 // routing change will happen when startOutput() will be called
François Gaffie11d30102018-11-02 16:09:09 +01001559 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07001560
Eric Laurent8838a382014-09-08 16:44:28 -07001561 // at this stage we should ignore the DIRECT flag as no direct output could be found earlier
Nadav Bar766fb022018-01-07 12:18:03 +02001562 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
jiabinebb6af42020-06-09 17:31:17 -07001563 output = selectOutput(
1564 outputs, *flags, config->format, channelMask, config->sample_rate, session);
Eric Laurente552edb2014-03-10 17:42:56 -07001565 }
François Gaffie11d30102018-11-02 16:09:09 +01001566 ALOGW_IF((output == 0), "getOutputForDevices() could not find output for stream %d, "
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001567 "sampling rate %d, format %#x, channels %#x, flags %#x",
jiabine375d412019-02-26 12:54:53 -08001568 stream, config->sample_rate, config->format, channelMask, *flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001569
Eric Laurente552edb2014-03-10 17:42:56 -07001570 return output;
1571}
1572
Mikhail Naganovf02f3672018-11-09 12:44:16 -08001573sp<DeviceDescriptor> AudioPolicyManager::getMsdAudioInDevice() const {
François Gaffie11d30102018-11-02 16:09:09 +01001574 auto msdInDevices = mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1575 mAvailableInputDevices);
1576 return msdInDevices.isEmpty()? nullptr : msdInDevices.itemAt(0);
1577}
1578
1579DeviceVector AudioPolicyManager::getMsdAudioOutDevices() const {
1580 return mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1581 mAvailableOutputDevices);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001582}
1583
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001584const AudioPatchCollection AudioPolicyManager::getMsdOutputPatches() const {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001585 AudioPatchCollection msdPatches;
Mikhail Naganov86112352018-10-04 09:02:49 -07001586 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1587 if (msdModule != 0) {
1588 for (size_t i = 0; i < mAudioPatches.size(); ++i) {
1589 sp<AudioPatch> patch = mAudioPatches.valueAt(i);
1590 for (size_t j = 0; j < patch->mPatch.num_sources; ++j) {
1591 const struct audio_port_config *source = &patch->mPatch.sources[j];
1592 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
1593 source->ext.device.hw_module == msdModule->getHandle()) {
François Gaffieafd4cea2019-11-18 15:50:22 +01001594 msdPatches.addAudioPatch(patch->getHandle(), patch);
Mikhail Naganov86112352018-10-04 09:02:49 -07001595 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001596 }
1597 }
1598 }
1599 return msdPatches;
1600}
1601
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02001602bool AudioPolicyManager::isMsdPatch(const audio_patch_handle_t &handle) const {
1603 ssize_t index = mAudioPatches.indexOfKey(handle);
1604 if (index < 0) {
1605 return false;
1606 }
1607 const sp<AudioPatch> patch = mAudioPatches.valueAt(index);
1608 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1609 if (msdModule == nullptr) {
1610 return false;
1611 }
1612 const struct audio_port_config *sink = &patch->mPatch.sinks[0];
1613 if (getMsdAudioOutDevices().contains(mAvailableOutputDevices.getDeviceFromId(sink->id))) {
1614 return true;
1615 }
1616 index = getMsdOutputPatches().indexOfKey(handle);
1617 if (index < 0) {
1618 return false;
1619 }
1620 return true;
1621}
1622
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001623status_t AudioPolicyManager::getMsdProfiles(bool hwAvSync,
1624 const InputProfileCollection &inputProfiles,
1625 const OutputProfileCollection &outputProfiles,
1626 const sp<DeviceDescriptor> &sourceDevice,
1627 const sp<DeviceDescriptor> &sinkDevice,
1628 AudioProfileVector& sourceProfiles,
1629 AudioProfileVector& sinkProfiles) const {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001630 if (inputProfiles.isEmpty()) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001631 ALOGE("%s() no input profiles for source module", __func__);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001632 return NO_INIT;
1633 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001634 if (outputProfiles.isEmpty()) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001635 ALOGE("%s() no output profiles for sink module", __func__);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001636 return NO_INIT;
1637 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001638 for (const auto &inProfile : inputProfiles) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001639 if (hwAvSync == ((inProfile->getFlags() & AUDIO_INPUT_FLAG_HW_AV_SYNC) != 0) &&
1640 inProfile->supportsDevice(sourceDevice)) {
1641 appendAudioProfiles(sourceProfiles, inProfile->getAudioProfiles());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001642 }
1643 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001644 for (const auto &outProfile : outputProfiles) {
Michael Chan6fb34492020-12-08 15:44:49 +11001645 if (hwAvSync == ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) &&
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001646 outProfile->supportsDevice(sinkDevice)) {
1647 appendAudioProfiles(sinkProfiles, outProfile->getAudioProfiles());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001648 }
1649 }
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001650 return NO_ERROR;
1651}
1652
1653status_t AudioPolicyManager::getBestMsdConfig(bool hwAvSync,
1654 const AudioProfileVector &sourceProfiles, const AudioProfileVector &sinkProfiles,
1655 audio_port_config *sourceConfig, audio_port_config *sinkConfig) const
1656{
Dean Wheatley16809da2022-12-09 14:55:46 +11001657 // Compressed formats for MSD module, ordered from most preferred to least preferred.
1658 static const std::vector<audio_format_t> formatsOrder = {{
1659 AUDIO_FORMAT_IEC60958, AUDIO_FORMAT_MAT_2_1, AUDIO_FORMAT_MAT_2_0, AUDIO_FORMAT_E_AC3,
1660 AUDIO_FORMAT_AC3, AUDIO_FORMAT_PCM_16_BIT }};
1661 static const std::vector<audio_channel_mask_t> channelMasksOrder = [](){
1662 // Channel position masks for MSD module, 3D > 2D > 1D ordering (most preferred to least
1663 // preferred).
1664 std::vector<audio_channel_mask_t> masks = {{
1665 AUDIO_CHANNEL_OUT_3POINT1POINT2, AUDIO_CHANNEL_OUT_3POINT0POINT2,
1666 AUDIO_CHANNEL_OUT_2POINT1POINT2, AUDIO_CHANNEL_OUT_2POINT0POINT2,
1667 AUDIO_CHANNEL_OUT_5POINT1, AUDIO_CHANNEL_OUT_STEREO }};
1668 // insert index masks (higher counts most preferred) as preferred over position masks
1669 for (int i = 1; i <= AUDIO_CHANNEL_COUNT_MAX; i++) {
1670 masks.insert(
1671 masks.begin(), audio_channel_mask_for_index_assignment_from_count(i));
1672 }
1673 return masks;
1674 }();
1675
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001676 struct audio_config_base bestSinkConfig;
Dean Wheatley16809da2022-12-09 14:55:46 +11001677 status_t result = findBestMatchingOutputConfig(sourceProfiles, sinkProfiles, formatsOrder,
1678 channelMasksOrder, true /*preferHigherSamplingRates*/, bestSinkConfig);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001679 if (result != NO_ERROR) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001680 ALOGD("%s() no matching config found for sink, hwAvSync: %d",
1681 __func__, hwAvSync);
Greg Kaiser83289652018-07-30 06:13:57 -07001682 return result;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001683 }
1684 sinkConfig->sample_rate = bestSinkConfig.sample_rate;
1685 sinkConfig->channel_mask = bestSinkConfig.channel_mask;
1686 sinkConfig->format = bestSinkConfig.format;
1687 // For encoded streams force direct flag to prevent downstream mixing.
1688 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1689 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_DIRECT);
Dean Wheatley5c9f0832019-11-21 13:39:31 +11001690 if (audio_is_iec61937_compatible(sinkConfig->format)) {
1691 // For formats compatible with IEC61937 encapsulation, assume that
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001692 // the input is IEC61937 framed (for proportional buffer sizing).
Dean Wheatley5c9f0832019-11-21 13:39:31 +11001693 // Add the AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO flag so downstream HAL can distinguish between
1694 // raw and IEC61937 framed streams.
1695 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1696 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO);
1697 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001698 sourceConfig->sample_rate = bestSinkConfig.sample_rate;
1699 // Specify exact channel mask to prevent guessing by bit count in PatchPanel.
Dean Wheatley16809da2022-12-09 14:55:46 +11001700 sourceConfig->channel_mask =
1701 audio_channel_mask_get_representation(bestSinkConfig.channel_mask)
1702 == AUDIO_CHANNEL_REPRESENTATION_INDEX ?
1703 bestSinkConfig.channel_mask : audio_channel_mask_out_to_in(bestSinkConfig.channel_mask);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001704 sourceConfig->format = bestSinkConfig.format;
1705 // Copy input stream directly without any processing (e.g. resampling).
1706 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1707 sourceConfig->flags.input | AUDIO_INPUT_FLAG_DIRECT);
1708 if (hwAvSync) {
1709 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1710 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
1711 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1712 sourceConfig->flags.input | AUDIO_INPUT_FLAG_HW_AV_SYNC);
1713 }
1714 const unsigned int config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE |
1715 AUDIO_PORT_CONFIG_CHANNEL_MASK | AUDIO_PORT_CONFIG_FORMAT | AUDIO_PORT_CONFIG_FLAGS;
1716 sinkConfig->config_mask |= config_mask;
1717 sourceConfig->config_mask |= config_mask;
1718 return NO_ERROR;
1719}
1720
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001721PatchBuilder AudioPolicyManager::buildMsdPatch(bool msdIsSource,
1722 const sp<DeviceDescriptor> &device) const
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001723{
1724 PatchBuilder patchBuilder;
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001725 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1726 ALOG_ASSERT(msdModule != nullptr, "MSD module not available");
1727 sp<HwModule> deviceModule = mHwModules.getModuleForDevice(device, AUDIO_FORMAT_DEFAULT);
1728 if (deviceModule == nullptr) {
1729 ALOGE("%s() unable to get module for %s", __func__, device->toString().c_str());
1730 return patchBuilder;
1731 }
1732 const InputProfileCollection inputProfiles = msdIsSource ?
1733 msdModule->getInputProfiles() : deviceModule->getInputProfiles();
1734 const OutputProfileCollection outputProfiles = msdIsSource ?
1735 deviceModule->getOutputProfiles() : msdModule->getOutputProfiles();
1736
1737 const sp<DeviceDescriptor> sourceDevice = msdIsSource ? getMsdAudioInDevice() : device;
1738 const sp<DeviceDescriptor> sinkDevice = msdIsSource ?
1739 device : getMsdAudioOutDevices().itemAt(0);
1740 patchBuilder.addSource(sourceDevice).addSink(sinkDevice);
1741
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001742 audio_port_config sourceConfig = patchBuilder.patch()->sources[0];
1743 audio_port_config sinkConfig = patchBuilder.patch()->sinks[0];
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001744 AudioProfileVector sourceProfiles;
1745 AudioProfileVector sinkProfiles;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001746 // TODO: Figure out whether MSD module has HW_AV_SYNC flag set in the AP config file.
1747 // For now, we just forcefully try with HwAvSync first.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001748 for (auto hwAvSync : { true, false }) {
1749 if (getMsdProfiles(hwAvSync, inputProfiles, outputProfiles, sourceDevice, sinkDevice,
1750 sourceProfiles, sinkProfiles) != NO_ERROR) {
1751 continue;
1752 }
1753 if (getBestMsdConfig(hwAvSync, sourceProfiles, sinkProfiles, &sourceConfig,
1754 &sinkConfig) == NO_ERROR) {
1755 // Found a matching config. Re-create PatchBuilder with this config.
1756 return (PatchBuilder()).addSource(sourceConfig).addSink(sinkConfig);
1757 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001758 }
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001759 ALOGV("%s() no matching config found. Fall through to default PCM patch"
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001760 " supporting PCM format conversion.", __func__);
1761 return patchBuilder;
1762}
1763
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001764status_t AudioPolicyManager::setMsdOutputPatches(const DeviceVector *outputDevices) {
Michael Chan6fb34492020-12-08 15:44:49 +11001765 DeviceVector devices;
1766 if (outputDevices != nullptr && outputDevices->size() > 0) {
1767 devices.add(*outputDevices);
1768 } else {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001769 // Use media strategy for unspecified output device. This should only
1770 // occur on checkForDeviceAndOutputChanges(). Device connection events may
1771 // therefore invalidate explicit routing requests.
Michael Chan6fb34492020-12-08 15:44:49 +11001772 devices = mEngine->getOutputDevicesForAttributes(
François Gaffiec005e562018-11-06 15:04:49 +01001773 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
Michael Chan6fb34492020-12-08 15:44:49 +11001774 LOG_ALWAYS_FATAL_IF(devices.isEmpty(), "no output device to set MSD patch");
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001775 }
Michael Chan6fb34492020-12-08 15:44:49 +11001776 std::vector<PatchBuilder> patchesToCreate;
1777 for (auto i = 0u; i < devices.size(); ++i) {
1778 ALOGV("%s() for device %s", __func__, devices[i]->toString().c_str());
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001779 patchesToCreate.push_back(buildMsdPatch(true /*msdIsSource*/, devices[i]));
Michael Chan6fb34492020-12-08 15:44:49 +11001780 }
1781 // Retain only the MSD patches associated with outputDevices request.
1782 // Tear down the others, and create new ones as needed.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001783 AudioPatchCollection patchesToRemove = getMsdOutputPatches();
Michael Chan6fb34492020-12-08 15:44:49 +11001784 for (auto it = patchesToCreate.begin(); it != patchesToCreate.end(); ) {
1785 auto retainedPatch = false;
1786 for (auto i = 0u; i < patchesToRemove.size(); ++i) {
1787 if (audio_patches_are_equal(it->patch(), &patchesToRemove[i]->mPatch)) {
1788 patchesToRemove.removeItemsAt(i);
1789 retainedPatch = true;
1790 break;
1791 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001792 }
Michael Chan6fb34492020-12-08 15:44:49 +11001793 if (retainedPatch) {
1794 it = patchesToCreate.erase(it);
1795 continue;
1796 }
1797 ++it;
1798 }
1799 if (patchesToCreate.size() == 0 && patchesToRemove.size() == 0) {
1800 return NO_ERROR;
1801 }
1802 for (auto i = 0u; i < patchesToRemove.size(); ++i) {
1803 auto &currentPatch = patchesToRemove.valueAt(i);
François Gaffieafd4cea2019-11-18 15:50:22 +01001804 releaseAudioPatch(currentPatch->getHandle(), mUidCached);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001805 }
Michael Chan6fb34492020-12-08 15:44:49 +11001806 status_t status = NO_ERROR;
1807 for (const auto &p : patchesToCreate) {
1808 auto currStatus = installPatch(__func__, -1 /*index*/, nullptr /*patchHandle*/,
1809 p.patch(), 0 /*delayMs*/, mUidCached, nullptr /*patchDescPtr*/);
1810 char message[256];
1811 snprintf(message, sizeof(message), "%s() %s: creating MSD patch from device:IN_BUS to "
1812 "device:%#x (format:%#x channels:%#x samplerate:%d)", __func__,
1813 currStatus == NO_ERROR ? "Success" : "Error",
1814 p.patch()->sinks[0].ext.device.type, p.patch()->sources[0].format,
1815 p.patch()->sources[0].channel_mask, p.patch()->sources[0].sample_rate);
1816 if (currStatus == NO_ERROR) {
1817 ALOGD("%s", message);
1818 } else {
1819 ALOGE("%s", message);
1820 if (status == NO_ERROR) {
1821 status = currStatus;
1822 }
1823 }
1824 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001825 return status;
1826}
1827
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001828void AudioPolicyManager::releaseMsdOutputPatches(const DeviceVector& devices) {
1829 AudioPatchCollection msdPatches = getMsdOutputPatches();
Michael Chan6fb34492020-12-08 15:44:49 +11001830 for (size_t i = 0; i < msdPatches.size(); i++) {
1831 const auto& patch = msdPatches[i];
1832 for (size_t j = 0; j < patch->mPatch.num_sinks; ++j) {
1833 const struct audio_port_config *sink = &patch->mPatch.sinks[j];
1834 if (sink->type == AUDIO_PORT_TYPE_DEVICE && devices.getDevice(sink->ext.device.type,
1835 String8(sink->ext.device.address), AUDIO_FORMAT_DEFAULT) != nullptr) {
1836 releaseAudioPatch(patch->getHandle(), mUidCached);
1837 break;
1838 }
1839 }
1840 }
1841}
1842
Dorin Drimus94d94412022-02-02 09:05:02 +01001843bool AudioPolicyManager::msdHasPatchesToAllDevices(const AudioDeviceTypeAddrVector& devices) {
Mikhail Naganovb0fbc1b2023-04-28 13:06:32 -07001844 DeviceVector devicesToCheck =
1845 mConfig->getOutputDevices().getDevicesFromDeviceTypeAddrVec(devices);
Dorin Drimus94d94412022-02-02 09:05:02 +01001846 AudioPatchCollection msdPatches = getMsdOutputPatches();
1847 for (size_t i = 0; i < msdPatches.size(); i++) {
1848 const auto& patch = msdPatches[i];
1849 for (size_t j = 0; j < patch->mPatch.num_sinks; ++j) {
1850 const struct audio_port_config *sink = &patch->mPatch.sinks[j];
1851 if (sink->type == AUDIO_PORT_TYPE_DEVICE) {
1852 const auto& foundDevice = devicesToCheck.getDevice(
1853 sink->ext.device.type, String8(sink->ext.device.address), AUDIO_FORMAT_DEFAULT);
1854 if (foundDevice != nullptr) {
1855 devicesToCheck.remove(foundDevice);
1856 if (devicesToCheck.isEmpty()) {
1857 return true;
1858 }
1859 }
1860 }
1861 }
1862 }
1863 return false;
1864}
1865
Eric Laurente0720872014-03-11 09:30:41 -07001866audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
jiabinebb6af42020-06-09 17:31:17 -07001867 audio_output_flags_t flags,
1868 audio_format_t format,
1869 audio_channel_mask_t channelMask,
1870 uint32_t samplingRate,
1871 audio_session_t sessionId)
Eric Laurente552edb2014-03-10 17:42:56 -07001872{
Eric Laurent16c66dd2019-05-01 17:54:10 -07001873 LOG_ALWAYS_FATAL_IF(!(format == AUDIO_FORMAT_INVALID || audio_is_linear_pcm(format)),
1874 "%s called with format %#x", __func__, format);
1875
jiabinebb6af42020-06-09 17:31:17 -07001876 // Return the output that haptic-generating attached to when 1) session id is specified,
1877 // 2) haptic-generating effect exists for given session id and 3) the output that
1878 // haptic-generating effect attached to is in given outputs.
1879 if (sessionId != AUDIO_SESSION_NONE) {
1880 audio_io_handle_t hapticGeneratingOutput = mEffects.getIoForSession(
1881 sessionId, FX_IID_HAPTICGENERATOR);
1882 if (outputs.indexOf(hapticGeneratingOutput) >= 0) {
1883 return hapticGeneratingOutput;
1884 }
1885 }
1886
Eric Laurent16c66dd2019-05-01 17:54:10 -07001887 // Flags disqualifying an output: the match must happen before calling selectOutput()
1888 static const audio_output_flags_t kExcludedFlags = (audio_output_flags_t)
1889 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ | AUDIO_OUTPUT_FLAG_DIRECT);
1890
1891 // Flags expressing a functional request: must be honored in priority over
1892 // other criteria
1893 static const audio_output_flags_t kFunctionalFlags = (audio_output_flags_t)
1894 (AUDIO_OUTPUT_FLAG_VOIP_RX | AUDIO_OUTPUT_FLAG_INCALL_MUSIC |
Eric Laurente28c66d2022-01-21 13:40:41 +01001895 AUDIO_OUTPUT_FLAG_TTS | AUDIO_OUTPUT_FLAG_DIRECT_PCM | AUDIO_OUTPUT_FLAG_ULTRASOUND |
1896 AUDIO_OUTPUT_FLAG_SPATIALIZER);
Eric Laurent16c66dd2019-05-01 17:54:10 -07001897 // Flags expressing a performance request: have lower priority than serving
1898 // requested sampling rate or channel mask
1899 static const audio_output_flags_t kPerformanceFlags = (audio_output_flags_t)
1900 (AUDIO_OUTPUT_FLAG_FAST | AUDIO_OUTPUT_FLAG_DEEP_BUFFER |
1901 AUDIO_OUTPUT_FLAG_RAW | AUDIO_OUTPUT_FLAG_SYNC);
1902
1903 const audio_output_flags_t functionalFlags =
1904 (audio_output_flags_t)(flags & kFunctionalFlags);
1905 const audio_output_flags_t performanceFlags =
1906 (audio_output_flags_t)(flags & kPerformanceFlags);
1907
1908 audio_io_handle_t bestOutput = (outputs.size() == 0) ? AUDIO_IO_HANDLE_NONE : outputs[0];
1909
Eric Laurente552edb2014-03-10 17:42:56 -07001910 // select one output among several that provide a path to a particular device or set of
François Gaffie11d30102018-11-02 16:09:09 +01001911 // devices (the list was previously build by getOutputsForDevices()).
Eric Laurente552edb2014-03-10 17:42:56 -07001912 // The priority is as follows:
jiabin40573322018-11-08 12:08:02 -08001913 // 1: the output supporting haptic playback when requesting haptic playback
Eric Laurent16c66dd2019-05-01 17:54:10 -07001914 // 2: the output with the highest number of requested functional flags
Carter Hsu199f1892021-10-15 15:47:29 +08001915 // with tiebreak preferring the minimum number of extra functional flags
1916 // (see b/200293124, the incorrect selection of AUDIO_OUTPUT_FLAG_VOIP_RX).
Eric Laurent16c66dd2019-05-01 17:54:10 -07001917 // 3: the output supporting the exact channel mask
1918 // 4: the output with a higher channel count than requested
jiabind1785f72022-06-03 20:48:18 +00001919 // 5: the output with the highest sampling rate if the requested sample rate is
1920 // greater than default sampling rate
Eric Laurent16c66dd2019-05-01 17:54:10 -07001921 // 6: the output with the highest number of requested performance flags
1922 // 7: the output with the bit depth the closest to the requested one
1923 // 8: the primary output
1924 // 9: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07001925
Eric Laurent16c66dd2019-05-01 17:54:10 -07001926 // matching criteria values in priority order for best matching output so far
1927 std::vector<uint32_t> bestMatchCriteria(8, 0);
Eric Laurente552edb2014-03-10 17:42:56 -07001928
Eric Laurent16c66dd2019-05-01 17:54:10 -07001929 const uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
1930 const uint32_t hapticChannelCount = audio_channel_count_from_out_mask(
1931 channelMask & AUDIO_CHANNEL_HAPTIC_ALL);
Eric Laurente78b6762018-12-19 16:29:01 -08001932
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001933 for (audio_io_handle_t output : outputs) {
1934 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent16c66dd2019-05-01 17:54:10 -07001935 // matching criteria values in priority order for current output
1936 std::vector<uint32_t> currentMatchCriteria(8, 0);
jiabin40573322018-11-08 12:08:02 -08001937
Eric Laurent16c66dd2019-05-01 17:54:10 -07001938 if (outputDesc->isDuplicated()) {
1939 continue;
1940 }
1941 if ((kExcludedFlags & outputDesc->mFlags) != 0) {
1942 continue;
1943 }
Eric Laurent8838a382014-09-08 16:44:28 -07001944
Eric Laurent16c66dd2019-05-01 17:54:10 -07001945 // If haptic channel is specified, use the haptic output if present.
1946 // When using haptic output, same audio format and sample rate are required.
1947 const uint32_t outputHapticChannelCount = audio_channel_count_from_out_mask(
jiabin5740f082019-08-19 15:08:30 -07001948 outputDesc->getChannelMask() & AUDIO_CHANNEL_HAPTIC_ALL);
Eric Laurent16c66dd2019-05-01 17:54:10 -07001949 if ((hapticChannelCount == 0) != (outputHapticChannelCount == 0)) {
1950 continue;
1951 }
1952 if (outputHapticChannelCount >= hapticChannelCount
jiabin5740f082019-08-19 15:08:30 -07001953 && format == outputDesc->getFormat()
1954 && samplingRate == outputDesc->getSamplingRate()) {
Eric Laurent16c66dd2019-05-01 17:54:10 -07001955 currentMatchCriteria[0] = outputHapticChannelCount;
1956 }
1957
1958 // functional flags match
Carter Hsu199f1892021-10-15 15:47:29 +08001959 const int matchingFunctionalFlags =
1960 __builtin_popcount(outputDesc->mFlags & functionalFlags);
1961 const int totalFunctionalFlags =
1962 __builtin_popcount(outputDesc->mFlags & kFunctionalFlags);
1963 // Prefer matching functional flags, but subtract unnecessary functional flags.
1964 currentMatchCriteria[1] = 100 * (matchingFunctionalFlags + 1) - totalFunctionalFlags;
Eric Laurent16c66dd2019-05-01 17:54:10 -07001965
1966 // channel mask and channel count match
jiabin5740f082019-08-19 15:08:30 -07001967 uint32_t outputChannelCount = audio_channel_count_from_out_mask(
1968 outputDesc->getChannelMask());
Eric Laurent16c66dd2019-05-01 17:54:10 -07001969 if (channelMask != AUDIO_CHANNEL_NONE && channelCount > 2 &&
1970 channelCount <= outputChannelCount) {
1971 if ((audio_channel_mask_get_representation(channelMask) ==
jiabin5740f082019-08-19 15:08:30 -07001972 audio_channel_mask_get_representation(outputDesc->getChannelMask())) &&
1973 ((channelMask & outputDesc->getChannelMask()) == channelMask)) {
Eric Laurent16c66dd2019-05-01 17:54:10 -07001974 currentMatchCriteria[2] = outputChannelCount;
Eric Laurente552edb2014-03-10 17:42:56 -07001975 }
Eric Laurent16c66dd2019-05-01 17:54:10 -07001976 currentMatchCriteria[3] = outputChannelCount;
1977 }
1978
1979 // sampling rate match
jiabind1785f72022-06-03 20:48:18 +00001980 if (samplingRate > SAMPLE_RATE_HZ_DEFAULT) {
jiabin5740f082019-08-19 15:08:30 -07001981 currentMatchCriteria[4] = outputDesc->getSamplingRate();
Eric Laurent16c66dd2019-05-01 17:54:10 -07001982 }
1983
1984 // performance flags match
1985 currentMatchCriteria[5] = popcount(outputDesc->mFlags & performanceFlags);
1986
1987 // format match
1988 if (format != AUDIO_FORMAT_INVALID) {
1989 currentMatchCriteria[6] =
jiabin4ef93452019-09-10 14:29:54 -07001990 PolicyAudioPort::kFormatDistanceMax -
1991 PolicyAudioPort::formatDistance(format, outputDesc->getFormat());
Eric Laurent16c66dd2019-05-01 17:54:10 -07001992 }
1993
1994 // primary output match
1995 currentMatchCriteria[7] = outputDesc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY;
1996
1997 // compare match criteria by priority then value
1998 if (std::lexicographical_compare(bestMatchCriteria.begin(), bestMatchCriteria.end(),
1999 currentMatchCriteria.begin(), currentMatchCriteria.end())) {
2000 bestMatchCriteria = currentMatchCriteria;
2001 bestOutput = output;
2002
2003 std::stringstream result;
2004 std::copy(bestMatchCriteria.begin(), bestMatchCriteria.end(),
2005 std::ostream_iterator<int>(result, " "));
2006 ALOGV("%s new bestOutput %d criteria %s",
2007 __func__, bestOutput, result.str().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07002008 }
2009 }
2010
Eric Laurent16c66dd2019-05-01 17:54:10 -07002011 return bestOutput;
Eric Laurente552edb2014-03-10 17:42:56 -07002012}
2013
Eric Laurent8fc147b2018-07-22 19:13:55 -07002014status_t AudioPolicyManager::startOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002015{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002016 ALOGV("%s portId %d", __FUNCTION__, portId);
2017
2018 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2019 if (outputDesc == 0) {
2020 ALOGW("startOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002021 return BAD_VALUE;
2022 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002023 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002024
Eric Laurent8fc147b2018-07-22 19:13:55 -07002025 ALOGV("startOutput() output %d, stream %d, session %d",
Eric Laurent97ac8712018-07-27 18:59:02 -07002026 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurentc75307b2015-03-17 15:29:32 -07002027
Eric Laurent733ce942017-12-07 12:18:25 -08002028 status_t status = outputDesc->start();
2029 if (status != NO_ERROR) {
2030 return status;
Eric Laurent3974e3b2017-12-07 17:58:43 -08002031 }
2032
Eric Laurent97ac8712018-07-27 18:59:02 -07002033 uint32_t delayMs;
2034 status = startSource(outputDesc, client, &delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07002035
2036 if (status != NO_ERROR) {
Eric Laurent733ce942017-12-07 12:18:25 -08002037 outputDesc->stop();
Eric Laurent8c7e6da2015-04-21 17:37:00 -07002038 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07002039 }
Jean-Michel Trivi32b7a102023-02-07 20:49:04 +00002040 if (client->hasPreferredDevice()) {
2041 // playback activity with preferred device impacts routing occurred, inform upper layers
2042 mpClientInterface->onRoutingUpdated();
2043 }
Eric Laurentc75307b2015-03-17 15:29:32 -07002044 if (delayMs != 0) {
2045 usleep(delayMs * 1000);
2046 }
2047
2048 return status;
2049}
2050
Eric Laurent96d1dda2022-03-14 17:14:19 +01002051bool AudioPolicyManager::isLeUnicastActive() const {
2052 if (isInCall()) {
2053 return true;
2054 }
2055 return isAnyDeviceTypeActive(getAudioDeviceOutLeAudioUnicastSet());
2056}
2057
2058bool AudioPolicyManager::isAnyDeviceTypeActive(const DeviceTypeSet& deviceTypes) const {
2059 if (mAvailableOutputDevices.getDevicesFromTypes(deviceTypes).isEmpty()) {
2060 return false;
2061 }
2062 bool active = mOutputs.isAnyDeviceTypeActive(deviceTypes);
2063 ALOGV("%s active %d", __func__, active);
2064 return active;
2065}
2066
Eric Laurent97ac8712018-07-27 18:59:02 -07002067status_t AudioPolicyManager::startSource(const sp<SwAudioOutputDescriptor>& outputDesc,
2068 const sp<TrackClientDescriptor>& client,
2069 uint32_t *delayMs)
Eric Laurentc75307b2015-03-17 15:29:32 -07002070{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002071 // cannot start playback of STREAM_TTS if any other output is being used
2072 uint32_t beaconMuteLatency = 0;
Eric Laurentc75307b2015-03-17 15:29:32 -07002073
2074 *delayMs = 0;
Eric Laurent97ac8712018-07-27 18:59:02 -07002075 audio_stream_type_t stream = client->stream();
François Gaffie1c878552018-11-22 16:53:21 +01002076 auto clientVolSrc = client->volumeSource();
François Gaffiec005e562018-11-06 15:04:49 +01002077 auto clientStrategy = client->strategy();
2078 auto clientAttr = client->attributes();
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002079 if (stream == AUDIO_STREAM_TTS) {
2080 ALOGV("\t found BEACON stream");
François Gaffie1c878552018-11-22 16:53:21 +01002081 if (!mTtsOutputAvailable && mOutputs.isAnyOutputActive(
Francois Gaffie4404ddb2021-02-04 17:03:38 +01002082 toVolumeSource(AUDIO_STREAM_TTS, false) /*sourceToIgnore*/)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002083 return INVALID_OPERATION;
2084 } else {
2085 beaconMuteLatency = handleEventForBeacon(STARTING_BEACON);
2086 }
2087 } else {
2088 // some playback other than beacon starts
2089 beaconMuteLatency = handleEventForBeacon(STARTING_OUTPUT);
2090 }
2091
Eric Laurent77305a62016-07-25 16:39:22 -07002092 // force device change if the output is inactive and no audio patch is already present.
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002093 // check active before incrementing usage count
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02002094 bool force = !outputDesc->isActive() && !outputDesc->isRouted();
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002095
François Gaffie11d30102018-11-02 16:09:09 +01002096 DeviceVector devices;
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002097 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
Eric Laurent97ac8712018-07-27 18:59:02 -07002098 const char *address = NULL;
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002099 if (policyMix != nullptr) {
François Gaffie11d30102018-11-02 16:09:09 +01002100 audio_devices_t newDeviceType;
Tomasz Wasilczyk8f36f6e2023-08-15 20:59:35 +00002101 address = policyMix->mDeviceAddress.c_str();
Kevin Rocard153f92d2018-12-18 18:33:28 -08002102 if ((policyMix->mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie11d30102018-11-02 16:09:09 +01002103 newDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Kevin Rocard153f92d2018-12-18 18:33:28 -08002104 } else {
2105 newDeviceType = policyMix->mDeviceType;
Eric Laurent97ac8712018-07-27 18:59:02 -07002106 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08002107 sp device = mAvailableOutputDevices.getDevice(newDeviceType, String8(address),
2108 AUDIO_FORMAT_DEFAULT);
2109 ALOG_ASSERT(device, "%s: no device found t=%u, a=%s", __func__, newDeviceType, address);
2110 devices.add(device);
Eric Laurent97ac8712018-07-27 18:59:02 -07002111 }
2112
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002113 // requiresMuteCheck is false when we can bypass mute strategy.
2114 // It covers a common case when there is no materially active audio
2115 // and muting would result in unnecessary delay and dropped audio.
2116 const uint32_t outputLatencyMs = outputDesc->latency();
2117 bool requiresMuteCheck = outputDesc->isActive(outputLatencyMs * 2); // account for drain
Eric Laurent96d1dda2022-03-14 17:14:19 +01002118 bool wasLeUnicastActive = isLeUnicastActive();
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002119
Eric Laurente552edb2014-03-10 17:42:56 -07002120 // increment usage count for this stream on the requested output:
2121 // NOTE that the usage count is the same for duplicated output and hardware output which is
2122 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
Eric Laurent592dd7b2018-08-05 18:58:48 -07002123 outputDesc->setClientActive(client, true);
Eric Laurent97ac8712018-07-27 18:59:02 -07002124
2125 if (client->hasPreferredDevice(true)) {
Eric Laurent72af8012023-03-15 17:36:22 +01002126 if (outputDesc->sameExclusivePreferredDevicesCount() > 0) {
François Gaffief96e5432019-04-09 17:13:56 +02002127 // Preferred device may be exclusive, use only if no other active clients on this output
2128 devices = DeviceVector(
2129 mAvailableOutputDevices.getDeviceFromId(client->preferredDeviceId()));
2130 } else {
2131 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
2132 }
François Gaffie11d30102018-11-02 16:09:09 +01002133 if (devices != outputDesc->devices()) {
François Gaffiec005e562018-11-06 15:04:49 +01002134 checkStrategyRoute(clientStrategy, outputDesc->mIoHandle);
Eric Laurent97ac8712018-07-27 18:59:02 -07002135 }
2136 }
Eric Laurente552edb2014-03-10 17:42:56 -07002137
François Gaffiec005e562018-11-06 15:04:49 +01002138 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07002139 selectOutputForMusicEffects();
2140 }
2141
François Gaffie1c878552018-11-22 16:53:21 +01002142 if (outputDesc->getActivityCount(clientVolSrc) == 1 || !devices.isEmpty()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08002143 // starting an output being rerouted?
François Gaffie11d30102018-11-02 16:09:09 +01002144 if (devices.isEmpty()) {
2145 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Eric Laurent275e8e92014-11-30 15:14:47 -08002146 }
François Gaffiec005e562018-11-06 15:04:49 +01002147 bool shouldWait =
2148 (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM)) ||
2149 followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_NOTIFICATION)) ||
2150 (beaconMuteLatency > 0));
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002151 uint32_t waitMs = beaconMuteLatency;
Eric Laurente552edb2014-03-10 17:42:56 -07002152 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01002153 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07002154 if (desc != outputDesc) {
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002155 // An output has a shared device if
2156 // - managed by the same hw module
2157 // - supports the currently selected device
2158 const bool sharedDevice = outputDesc->sharesHwModuleWith(desc)
François Gaffie11d30102018-11-02 16:09:09 +01002159 && (!desc->filterSupportedDevices(devices).isEmpty());
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002160
Eric Laurent77305a62016-07-25 16:39:22 -07002161 // force a device change if any other output is:
2162 // - managed by the same hw module
Jean-Michel Trivi4a5b4812018-02-08 17:22:32 +00002163 // - supports currently selected device
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002164 // - has a current device selection that differs from selected device.
Eric Laurent77305a62016-07-25 16:39:22 -07002165 // - has an active audio patch
Eric Laurente552edb2014-03-10 17:42:56 -07002166 // In this case, the audio HAL must receive the new device selection so that it can
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002167 // change the device currently selected by the other output.
2168 if (sharedDevice &&
François Gaffie11d30102018-11-02 16:09:09 +01002169 desc->devices() != devices &&
Eric Laurent77305a62016-07-25 16:39:22 -07002170 desc->getPatchHandle() != AUDIO_PATCH_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07002171 force = true;
2172 }
2173 // wait for audio on other active outputs to be presented when starting
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002174 // a notification so that audio focus effect can propagate, or that a mute/unmute
2175 // event occurred for beacon
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002176 const uint32_t latencyMs = desc->latency();
2177 const bool isActive = desc->isActive(latencyMs * 2); // account for drain
2178
2179 if (shouldWait && isActive && (waitMs < latencyMs)) {
2180 waitMs = latencyMs;
Eric Laurente552edb2014-03-10 17:42:56 -07002181 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002182
2183 // Require mute check if another output is on a shared device
2184 // and currently active to have proper drain and avoid pops.
2185 // Note restoring AudioTracks onto this output needs to invoke
2186 // a volume ramp if there is no mute.
2187 requiresMuteCheck |= sharedDevice && isActive;
Eric Laurente552edb2014-03-10 17:42:56 -07002188 }
2189 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002190
2191 const uint32_t muteWaitMs =
François Gaffie11d30102018-11-02 16:09:09 +01002192 setOutputDevices(outputDesc, devices, force, 0, NULL, requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07002193
Eric Laurente552edb2014-03-10 17:42:56 -07002194 // apply volume rules for current stream and device if necessary
François Gaffieaaac0fd2018-11-22 17:56:39 +01002195 auto &curves = getVolumeCurves(client->attributes());
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00002196 if (NO_ERROR != checkAndSetVolume(curves, client->volumeSource(),
François Gaffieaaac0fd2018-11-22 17:56:39 +01002197 curves.getVolumeIndex(outputDesc->devices().types()),
Eric Laurentc75307b2015-03-17 15:29:32 -07002198 outputDesc,
Francois Gaffied11442b2020-04-27 11:51:09 +02002199 outputDesc->devices().types(), 0 /*delay*/,
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00002200 outputDesc->useHwGain() /*force*/)) {
2201 // request AudioService to reinitialize the volume curves asynchronously
2202 ALOGE("checkAndSetVolume failed, requesting volume range init");
2203 mpClientInterface->onVolumeRangeInitRequest();
2204 };
Eric Laurente552edb2014-03-10 17:42:56 -07002205
2206 // update the outputs if starting an output with a stream that can affect notification
2207 // routing
2208 handleNotificationRoutingForStream(stream);
Eric Laurentc722f302014-12-10 11:21:49 -08002209
Eric Laurent2cbe89a2014-12-19 11:49:08 -08002210 // force reevaluating accessibility routing when ringtone or alarm starts
François Gaffiec005e562018-11-06 15:04:49 +01002211 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM))) {
Eric Laurent2cbe89a2014-12-19 11:49:08 -08002212 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
2213 }
Eric Laurentdc462862016-07-19 12:29:53 -07002214
2215 if (waitMs > muteWaitMs) {
2216 *delayMs = waitMs - muteWaitMs;
2217 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002218
2219 // FIXME: A device change (muteWaitMs > 0) likely introduces a volume change.
2220 // A volume change enacted by APM with 0 delay is not synchronous, as it goes
2221 // via AudioCommandThread to AudioFlinger. Hence it is possible that the volume
2222 // change occurs after the MixerThread starts and causes a stream volume
2223 // glitch.
2224 //
2225 // We do not introduce additional delay here.
Eric Laurente552edb2014-03-10 17:42:56 -07002226 }
Eric Laurentdc462862016-07-19 12:29:53 -07002227
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002228 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
jiabin9a3361e2019-10-01 09:38:30 -07002229 mEngine->getForceUse(
2230 AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
François Gaffiec005e562018-11-06 15:04:49 +01002231 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), true, outputDesc);
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002232 }
2233
Eric Laurent97ac8712018-07-27 18:59:02 -07002234 // Automatically enable the remote submix input when output is started on a re routing mix
2235 // of type MIX_TYPE_RECORDERS
jiabin9a3361e2019-10-01 09:38:30 -07002236 if (isSingleDeviceType(devices.types(), &audio_is_remote_submix_device) &&
2237 policyMix != NULL && policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002238 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2239 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2240 address,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002241 "remote-submix",
2242 AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07002243 }
2244
Eric Laurent96d1dda2022-03-14 17:14:19 +01002245 checkLeBroadcastRoutes(wasLeUnicastActive, outputDesc, *delayMs);
2246
Eric Laurente552edb2014-03-10 17:42:56 -07002247 return NO_ERROR;
2248}
2249
Eric Laurent96d1dda2022-03-14 17:14:19 +01002250void AudioPolicyManager::checkLeBroadcastRoutes(bool wasUnicastActive,
2251 sp<SwAudioOutputDescriptor> ignoredOutput, uint32_t delayMs) {
2252 bool isUnicastActive = isLeUnicastActive();
2253
2254 if (wasUnicastActive != isUnicastActive) {
2255 //reroute all outputs routed to LE broadcast if LE unicast activy changed on any output
2256 for (size_t i = 0; i < mOutputs.size(); i++) {
2257 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
2258 if (desc != ignoredOutput && desc->isActive()
2259 && ((isUnicastActive &&
2260 !desc->devices().
2261 getDevicesFromType(AUDIO_DEVICE_OUT_BLE_BROADCAST).isEmpty())
2262 || (wasUnicastActive &&
2263 !desc->devices().getDevicesFromTypes(
2264 getAudioDeviceOutLeAudioUnicastSet()).isEmpty()))) {
2265 DeviceVector newDevices = getNewOutputDevices(desc, false /*fromCache*/);
2266 bool force = desc->devices() != newDevices;
2267 setOutputDevices(desc, newDevices, force, delayMs);
2268 // re-apply device specific volume if not done by setOutputDevice()
2269 if (!force) {
2270 applyStreamVolumes(desc, newDevices.types(), delayMs);
2271 }
2272 }
2273 }
2274 }
2275}
2276
Eric Laurent8fc147b2018-07-22 19:13:55 -07002277status_t AudioPolicyManager::stopOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002278{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002279 ALOGV("%s portId %d", __FUNCTION__, portId);
2280
2281 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2282 if (outputDesc == 0) {
2283 ALOGW("stopOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002284 return BAD_VALUE;
2285 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002286 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002287
Jean-Michel Trivi32b7a102023-02-07 20:49:04 +00002288 if (client->hasPreferredDevice(true)) {
2289 // playback activity with preferred device impacts routing occurred, inform upper layers
2290 mpClientInterface->onRoutingUpdated();
2291 }
2292
Eric Laurent97ac8712018-07-27 18:59:02 -07002293 ALOGV("stopOutput() output %d, stream %d, session %d",
2294 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurente552edb2014-03-10 17:42:56 -07002295
Eric Laurent97ac8712018-07-27 18:59:02 -07002296 status_t status = stopSource(outputDesc, client);
Eric Laurent3974e3b2017-12-07 17:58:43 -08002297
Eric Laurent733ce942017-12-07 12:18:25 -08002298 if (status == NO_ERROR ) {
2299 outputDesc->stop();
Eric Laurent3974e3b2017-12-07 17:58:43 -08002300 }
2301 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07002302}
2303
Eric Laurent97ac8712018-07-27 18:59:02 -07002304status_t AudioPolicyManager::stopSource(const sp<SwAudioOutputDescriptor>& outputDesc,
2305 const sp<TrackClientDescriptor>& client)
Eric Laurentc75307b2015-03-17 15:29:32 -07002306{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002307 // always handle stream stop, check which stream type is stopping
Eric Laurent97ac8712018-07-27 18:59:02 -07002308 audio_stream_type_t stream = client->stream();
François Gaffie1c878552018-11-22 16:53:21 +01002309 auto clientVolSrc = client->volumeSource();
Eric Laurent96d1dda2022-03-14 17:14:19 +01002310 bool wasLeUnicastActive = isLeUnicastActive();
Eric Laurent97ac8712018-07-27 18:59:02 -07002311
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002312 handleEventForBeacon(stream == AUDIO_STREAM_TTS ? STOPPING_BEACON : STOPPING_OUTPUT);
2313
François Gaffie1c878552018-11-22 16:53:21 +01002314 if (outputDesc->getActivityCount(clientVolSrc) > 0) {
2315 if (outputDesc->getActivityCount(clientVolSrc) == 1) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002316 // Automatically disable the remote submix input when output is stopped on a
2317 // re routing mix of type MIX_TYPE_RECORDERS
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002318 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
jiabin9a3361e2019-10-01 09:38:30 -07002319 if (isSingleDeviceType(
2320 outputDesc->devices().types(), &audio_is_remote_submix_device) &&
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002321 policyMix != nullptr &&
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002322 policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002323 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2324 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002325 policyMix->mDeviceAddress,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002326 "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07002327 }
2328 }
2329 bool forceDeviceUpdate = false;
Eric Laurent72af8012023-03-15 17:36:22 +01002330 if (client->hasPreferredDevice(true) &&
2331 outputDesc->sameExclusivePreferredDevicesCount() < 2) {
François Gaffiec005e562018-11-06 15:04:49 +01002332 checkStrategyRoute(client->strategy(), AUDIO_IO_HANDLE_NONE);
Eric Laurent97ac8712018-07-27 18:59:02 -07002333 forceDeviceUpdate = true;
2334 }
2335
Eric Laurente552edb2014-03-10 17:42:56 -07002336 // decrement usage count of this stream on the output
Eric Laurent592dd7b2018-08-05 18:58:48 -07002337 outputDesc->setClientActive(client, false);
Paul McLeanaa981192015-03-21 09:55:15 -07002338
Eric Laurente552edb2014-03-10 17:42:56 -07002339 // store time at which the stream was stopped - see isStreamActive()
François Gaffie1c878552018-11-22 16:53:21 +01002340 if (outputDesc->getActivityCount(clientVolSrc) == 0 || forceDeviceUpdate) {
François Gaffiec005e562018-11-06 15:04:49 +01002341 outputDesc->setStopTime(client, systemTime());
François Gaffie11d30102018-11-02 16:09:09 +01002342 DeviceVector newDevices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Francois Gaffie3523ab32021-06-22 13:24:34 +02002343
2344 // If the routing does not change, if an output is routed on a device using HwGain
2345 // (aka setAudioPortConfig) and there are still active clients following different
2346 // volume group(s), force reapply volume
2347 bool requiresVolumeCheck = outputDesc->getActivityCount(clientVolSrc) == 0 &&
2348 outputDesc->useHwGain() && outputDesc->isAnyActive(VOLUME_SOURCE_NONE);
2349
Eric Laurente552edb2014-03-10 17:42:56 -07002350 // delay the device switch by twice the latency because stopOutput() is executed when
2351 // the track stop() command is received and at that time the audio track buffer can
2352 // still contain data that needs to be drained. The latency only covers the audio HAL
2353 // and kernel buffers. Also the latency does not always include additional delay in the
2354 // audio path (audio DSP, CODEC ...)
Francois Gaffie3523ab32021-06-22 13:24:34 +02002355 setOutputDevices(outputDesc, newDevices, false, outputDesc->latency()*2,
2356 nullptr, true /*requiresMuteCheck*/, requiresVolumeCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07002357
2358 // force restoring the device selection on other active outputs if it differs from the
2359 // one being selected for this output
Eric Laurent57de36c2016-09-28 16:59:11 -07002360 uint32_t delayMs = outputDesc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -07002361 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01002362 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07002363 if (desc != outputDesc &&
Eric Laurente552edb2014-03-10 17:42:56 -07002364 desc->isActive() &&
2365 outputDesc->sharesHwModuleWith(desc) &&
François Gaffie11d30102018-11-02 16:09:09 +01002366 (newDevices != desc->devices())) {
2367 DeviceVector newDevices2 = getNewOutputDevices(desc, false /*fromCache*/);
2368 bool force = desc->devices() != newDevices2;
Eric Laurentf3a5a602018-05-22 18:42:55 -07002369
François Gaffie11d30102018-11-02 16:09:09 +01002370 setOutputDevices(desc, newDevices2, force, delayMs);
2371
Eric Laurent57de36c2016-09-28 16:59:11 -07002372 // re-apply device specific volume if not done by setOutputDevice()
2373 if (!force) {
François Gaffie11d30102018-11-02 16:09:09 +01002374 applyStreamVolumes(desc, newDevices2.types(), delayMs);
Eric Laurent57de36c2016-09-28 16:59:11 -07002375 }
Eric Laurente552edb2014-03-10 17:42:56 -07002376 }
2377 }
2378 // update the outputs if stopping one with a stream that can affect notification routing
2379 handleNotificationRoutingForStream(stream);
2380 }
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002381
2382 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
2383 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Jean-Michel Trivi74e01fa2019-02-25 12:18:09 -08002384 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), false, outputDesc);
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002385 }
2386
François Gaffiec005e562018-11-06 15:04:49 +01002387 if (followsSameRouting(client->attributes(), attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07002388 selectOutputForMusicEffects();
2389 }
Eric Laurent96d1dda2022-03-14 17:14:19 +01002390
2391 checkLeBroadcastRoutes(wasLeUnicastActive, outputDesc, outputDesc->latency()*2);
2392
Eric Laurente552edb2014-03-10 17:42:56 -07002393 return NO_ERROR;
2394 } else {
Eric Laurentc75307b2015-03-17 15:29:32 -07002395 ALOGW("stopOutput() refcount is already 0");
Eric Laurente552edb2014-03-10 17:42:56 -07002396 return INVALID_OPERATION;
2397 }
2398}
2399
jiabinbce0c1d2020-10-05 11:20:18 -07002400bool AudioPolicyManager::releaseOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002401{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002402 ALOGV("%s portId %d", __FUNCTION__, portId);
2403
2404 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2405 if (outputDesc == 0) {
Andy Hung39efb7a2018-09-26 15:39:28 -07002406 // If an output descriptor is closed due to a device routing change,
2407 // then there are race conditions with releaseOutput from tracks
2408 // that may be destroyed (with no PlaybackThread) or a PlaybackThread
2409 // destroyed shortly thereafter.
2410 //
2411 // Here we just log a warning, instead of a fatal error.
Eric Laurent8fc147b2018-07-22 19:13:55 -07002412 ALOGW("releaseOutput() no output for client %d", portId);
jiabinbce0c1d2020-10-05 11:20:18 -07002413 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002414 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002415
2416 ALOGV("releaseOutput() %d", outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -07002417
Jaideep Sharma7bf382e2020-11-26 17:07:29 +05302418 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
2419 if (outputDesc->isClientActive(client)) {
2420 ALOGW("releaseOutput() inactivates portId %d in good faith", portId);
2421 stopOutput(portId);
2422 }
2423
Eric Laurent8fc147b2018-07-22 19:13:55 -07002424 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
2425 if (outputDesc->mDirectOpenCount <= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07002426 ALOGW("releaseOutput() invalid open count %d for output %d",
Eric Laurent8fc147b2018-07-22 19:13:55 -07002427 outputDesc->mDirectOpenCount, outputDesc->mIoHandle);
jiabinbce0c1d2020-10-05 11:20:18 -07002428 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002429 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002430 if (--outputDesc->mDirectOpenCount == 0) {
2431 closeOutput(outputDesc->mIoHandle);
Eric Laurentb52c1522014-05-20 11:27:36 -07002432 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07002433 }
2434 }
Jaideep Sharma7bf382e2020-11-26 17:07:29 +05302435
Andy Hung39efb7a2018-09-26 15:39:28 -07002436 outputDesc->removeClient(portId);
jiabinbce0c1d2020-10-05 11:20:18 -07002437 if (outputDesc->mPendingReopenToQueryProfiles && outputDesc->getClientCount() == 0) {
2438 // The output is pending reopened to query dynamic profiles and
2439 // there is no active clients
2440 closeOutput(outputDesc->mIoHandle);
2441 sp<SwAudioOutputDescriptor> newOutputDesc = openOutputWithProfileAndDevice(
2442 outputDesc->mProfile, mEngine->getActiveMediaDevices(mAvailableOutputDevices));
2443 if (newOutputDesc == nullptr) {
2444 ALOGE("%s failed to open output", __func__);
2445 }
2446 return true;
2447 }
2448 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002449}
2450
Eric Laurentcaf7f482014-11-25 17:50:47 -08002451status_t AudioPolicyManager::getInputForAttr(const audio_attributes_t *attr,
2452 audio_io_handle_t *input,
Mikhail Naganov2996f672019-04-18 12:29:59 -07002453 audio_unique_id_t riid,
Eric Laurentcaf7f482014-11-25 17:50:47 -08002454 audio_session_t session,
Svet Ganov3e5f14f2021-05-13 22:51:08 +00002455 const AttributionSourceState& attributionSource,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002456 const audio_config_base_t *config,
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002457 audio_input_flags_t flags,
Eric Laurent2ac76942017-06-22 17:17:09 -07002458 audio_port_handle_t *selectedDeviceId,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002459 input_type_t *inputType,
2460 audio_port_handle_t *portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002461{
François Gaffiec005e562018-11-06 15:04:49 +01002462 ALOGV("%s() source %d, sampling rate %d, format %#x, channel mask %#x, session %d, "
Eric Laurent2f2c1982021-06-02 14:03:11 +02002463 "flags %#x attributes=%s requested device ID %d",
2464 __func__, attr->source, config->sample_rate, config->format, config->channel_mask,
2465 session, flags, toString(*attr).c_str(), *selectedDeviceId);
Eric Laurente552edb2014-03-10 17:42:56 -07002466
Eric Laurentad2e7b92017-09-14 20:06:42 -07002467 status_t status = NO_ERROR;
Francois Gaffie716e1432019-01-14 16:58:59 +01002468 audio_attributes_t attributes = *attr;
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002469 sp<AudioPolicyMix> policyMix;
François Gaffie11d30102018-11-02 16:09:09 +01002470 sp<DeviceDescriptor> device;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002471 sp<AudioInputDescriptor> inputDesc;
2472 sp<RecordClientDescriptor> clientDesc;
2473 audio_port_handle_t requestedDeviceId = *selectedDeviceId;
Svet Ganov3e5f14f2021-05-13 22:51:08 +00002474 uid_t uid = VALUE_OR_RETURN_STATUS(aidl2legacy_int32_t_uid_t(attributionSource.uid));
Eric Laurent8f42ea12018-08-08 09:08:25 -07002475 bool isSoundTrigger;
Eric Laurent8f42ea12018-08-08 09:08:25 -07002476
2477 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
2478 if (*portId != AUDIO_PORT_HANDLE_NONE) {
2479 return INVALID_OPERATION;
2480 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08002481
Francois Gaffie716e1432019-01-14 16:58:59 +01002482 if (attr->source == AUDIO_SOURCE_DEFAULT) {
2483 attributes.source = AUDIO_SOURCE_MIC;
Eric Laurentfe231122017-11-17 17:48:06 -08002484 }
2485
Paul McLean466dc8e2015-04-17 13:15:36 -06002486 // Explicit routing?
Pattydd807582021-11-04 21:01:03 +08002487 sp<DeviceDescriptor> explicitRoutingDevice =
François Gaffie11d30102018-11-02 16:09:09 +01002488 mAvailableInputDevices.getDeviceFromId(*selectedDeviceId);
Paul McLean466dc8e2015-04-17 13:15:36 -06002489
Eric Laurentad2e7b92017-09-14 20:06:42 -07002490 // special case for mmap capture: if an input IO handle is specified, we reuse this input if
2491 // possible
2492 if ((flags & AUDIO_INPUT_FLAG_MMAP_NOIRQ) == AUDIO_INPUT_FLAG_MMAP_NOIRQ &&
2493 *input != AUDIO_IO_HANDLE_NONE) {
2494 ssize_t index = mInputs.indexOfKey(*input);
2495 if (index < 0) {
2496 ALOGW("getInputForAttr() unknown MMAP input %d", *input);
2497 status = BAD_VALUE;
2498 goto error;
2499 }
2500 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002501 RecordClientVector clients = inputDesc->getClientsForSession(session);
2502 if (clients.size() == 0) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07002503 ALOGW("getInputForAttr() unknown session %d on input %d", session, *input);
2504 status = BAD_VALUE;
2505 goto error;
2506 }
2507 // For MMAP mode, the first call to getInputForAttr() is made on behalf of audioflinger.
2508 // The second call is for the first active client and sets the UID. Any further call
Eric Laurent331679c2018-04-16 17:03:16 -07002509 // corresponds to a new client and is only permitted from the same UID.
2510 // If the first UID is silenced, allow a new UID connection and replace with new UID
Eric Laurent8f42ea12018-08-08 09:08:25 -07002511 if (clients.size() > 1) {
2512 for (const auto& client : clients) {
2513 // The client map is ordered by key values (portId) and portIds are allocated
2514 // incrementaly. So the first client in this list is the one opened by audio flinger
2515 // when the mmap stream is created and should be ignored as it does not correspond
2516 // to an actual client
2517 if (client == *clients.cbegin()) {
2518 continue;
2519 }
2520 if (uid != client->uid() && !client->isSilenced()) {
2521 ALOGW("getInputForAttr() bad uid %d for client %d uid %d",
2522 uid, client->portId(), client->uid());
2523 status = INVALID_OPERATION;
2524 goto error;
2525 }
Eric Laurent331679c2018-04-16 17:03:16 -07002526 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002527 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002528 *inputType = API_INPUT_LEGACY;
François Gaffie11d30102018-11-02 16:09:09 +01002529 device = inputDesc->getDevice();
Eric Laurentad2e7b92017-09-14 20:06:42 -07002530
Eric Laurentfecbceb2021-02-09 14:46:43 +01002531 ALOGV("%s reusing MMAP input %d for session %d", __FUNCTION__, *input, session);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002532 goto exit;
Eric Laurentad2e7b92017-09-14 20:06:42 -07002533 }
2534
2535 *input = AUDIO_IO_HANDLE_NONE;
2536 *inputType = API_INPUT_INVALID;
2537
Francois Gaffie716e1432019-01-14 16:58:59 +01002538 if (attributes.source == AUDIO_SOURCE_REMOTE_SUBMIX &&
2539 strncmp(attributes.tags, "addr=", strlen("addr=")) == 0) {
2540 status = mPolicyMixes.getInputMixForAttr(attributes, &policyMix);
Eric Laurentad2e7b92017-09-14 20:06:42 -07002541 if (status != NO_ERROR) {
jiabinc1de2df2019-05-07 14:26:40 -07002542 ALOGW("%s could not find input mix for attr %s",
2543 __func__, toString(attributes).c_str());
Eric Laurentad2e7b92017-09-14 20:06:42 -07002544 goto error;
François Gaffie036e1e92015-03-19 10:16:24 +01002545 }
jiabinc1de2df2019-05-07 14:26:40 -07002546 device = mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2547 String8(attr->tags + strlen("addr=")),
2548 AUDIO_FORMAT_DEFAULT);
2549 if (device == nullptr) {
Kevin Rocard04ed0462019-05-02 17:53:24 -07002550 ALOGW("%s could not find in Remote Submix device for source %d, tags %s",
jiabinc1de2df2019-05-07 14:26:40 -07002551 __func__, attributes.source, attributes.tags);
2552 status = BAD_VALUE;
2553 goto error;
2554 }
2555
Kevin Rocard25f9b052019-02-27 15:08:54 -08002556 if (is_mix_loopback_render(policyMix->mRouteFlags)) {
2557 *inputType = API_INPUT_MIX_PUBLIC_CAPTURE_PLAYBACK;
2558 } else {
2559 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
2560 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002561 } else {
François Gaffie11d30102018-11-02 16:09:09 +01002562 if (explicitRoutingDevice != nullptr) {
2563 device = explicitRoutingDevice;
Eric Laurent97ac8712018-07-27 18:59:02 -07002564 } else {
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01002565 // Prevent from storing invalid requested device id in clients
2566 requestedDeviceId = AUDIO_PORT_HANDLE_NONE;
yuanjiahsu0735bf32021-03-18 08:12:54 +08002567 device = mEngine->getInputDeviceForAttributes(attributes, uid, &policyMix);
yuanjiahsu4069d5d2021-04-19 07:54:27 +08002568 ALOGV_IF(device != nullptr, "%s found device type is 0x%X",
2569 __FUNCTION__, device->type());
Eric Laurent97ac8712018-07-27 18:59:02 -07002570 }
François Gaffie11d30102018-11-02 16:09:09 +01002571 if (device == nullptr) {
Francois Gaffie716e1432019-01-14 16:58:59 +01002572 ALOGW("getInputForAttr() could not find device for source %d", attributes.source);
Eric Laurentad2e7b92017-09-14 20:06:42 -07002573 status = BAD_VALUE;
2574 goto error;
Eric Laurent275e8e92014-11-30 15:14:47 -08002575 }
Alden DSouzab7d20782021-02-08 08:51:42 -08002576 if (device->type() == AUDIO_DEVICE_IN_ECHO_REFERENCE) {
2577 *inputType = API_INPUT_MIX_CAPTURE;
2578 } else if (policyMix) {
François Gaffie11d30102018-11-02 16:09:09 +01002579 ALOG_ASSERT(policyMix->mMixType == MIX_TYPE_RECORDERS, "Invalid Mix Type");
2580 // there is an external policy, but this input is attached to a mix of recorders,
2581 // meaning it receives audio injected into the framework, so the recorder doesn't
2582 // know about it and is therefore considered "legacy"
2583 *inputType = API_INPUT_LEGACY;
2584 } else if (audio_is_remote_submix_device(device->type())) {
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002585 *inputType = API_INPUT_MIX_CAPTURE;
François Gaffie11d30102018-11-02 16:09:09 +01002586 } else if (device->type() == AUDIO_DEVICE_IN_TELEPHONY_RX) {
Eric Laurent82db2692015-08-07 13:59:42 -07002587 *inputType = API_INPUT_TELEPHONY_RX;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002588 } else {
2589 *inputType = API_INPUT_LEGACY;
Eric Laurentc722f302014-12-10 11:21:49 -08002590 }
Ravi Kumar Alamandab367f5b2015-08-25 08:21:37 -07002591
Eric Laurent599c7582015-12-07 18:05:55 -08002592 }
2593
François Gaffiec005e562018-11-06 15:04:49 +01002594 *input = getInputForDevice(device, session, attributes, config, flags, policyMix);
Eric Laurent599c7582015-12-07 18:05:55 -08002595 if (*input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07002596 status = INVALID_OPERATION;
2597 goto error;
Eric Laurent599c7582015-12-07 18:05:55 -08002598 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08002599
Eric Laurent8f42ea12018-08-08 09:08:25 -07002600exit:
2601
François Gaffiec005e562018-11-06 15:04:49 +01002602 *selectedDeviceId = mAvailableInputDevices.contains(device) ?
2603 device->getId() : AUDIO_PORT_HANDLE_NONE;
Eric Laurent2ac76942017-06-22 17:17:09 -07002604
Francois Gaffie716e1432019-01-14 16:58:59 +01002605 isSoundTrigger = attributes.source == AUDIO_SOURCE_HOTWORD &&
Carter Hsud0cce2e2019-05-03 17:36:28 +08002606 mSoundTriggerSessions.indexOfKey(session) >= 0;
jiabin4ef93452019-09-10 14:29:54 -07002607 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002608
Mikhail Naganov2996f672019-04-18 12:29:59 -07002609 clientDesc = new RecordClientDescriptor(*portId, riid, uid, session, attributes, *config,
Francois Gaffie716e1432019-01-14 16:58:59 +01002610 requestedDeviceId, attributes.source, flags,
2611 isSoundTrigger);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002612 inputDesc = mInputs.valueFor(*input);
Andy Hung39efb7a2018-09-26 15:39:28 -07002613 inputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002614
2615 ALOGV("getInputForAttr() returns input %d type %d selectedDeviceId %d for port ID %d",
2616 *input, *inputType, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07002617
Eric Laurent599c7582015-12-07 18:05:55 -08002618 return NO_ERROR;
Eric Laurentad2e7b92017-09-14 20:06:42 -07002619
2620error:
Eric Laurentad2e7b92017-09-14 20:06:42 -07002621 return status;
Eric Laurent599c7582015-12-07 18:05:55 -08002622}
2623
2624
François Gaffie11d30102018-11-02 16:09:09 +01002625audio_io_handle_t AudioPolicyManager::getInputForDevice(const sp<DeviceDescriptor> &device,
Eric Laurent599c7582015-12-07 18:05:55 -08002626 audio_session_t session,
François Gaffiec005e562018-11-06 15:04:49 +01002627 const audio_attributes_t &attributes,
Eric Laurentfe231122017-11-17 17:48:06 -08002628 const audio_config_base_t *config,
Eric Laurent599c7582015-12-07 18:05:55 -08002629 audio_input_flags_t flags,
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002630 const sp<AudioPolicyMix> &policyMix)
Eric Laurent599c7582015-12-07 18:05:55 -08002631{
2632 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
François Gaffiec005e562018-11-06 15:04:49 +01002633 audio_source_t halInputSource = attributes.source;
Eric Laurent599c7582015-12-07 18:05:55 -08002634 bool isSoundTrigger = false;
2635
François Gaffiec005e562018-11-06 15:04:49 +01002636 if (attributes.source == AUDIO_SOURCE_HOTWORD) {
Eric Laurent599c7582015-12-07 18:05:55 -08002637 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
2638 if (index >= 0) {
2639 input = mSoundTriggerSessions.valueFor(session);
2640 isSoundTrigger = true;
2641 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_HW_HOTWORD);
2642 ALOGV("SoundTrigger capture on session %d input %d", session, input);
2643 } else {
2644 halInputSource = AUDIO_SOURCE_VOICE_RECOGNITION;
Eric Laurent5dbe4712014-09-19 19:04:57 -07002645 }
François Gaffiec005e562018-11-06 15:04:49 +01002646 } else if (attributes.source == AUDIO_SOURCE_VOICE_COMMUNICATION &&
Eric Laurentfe231122017-11-17 17:48:06 -08002647 audio_is_linear_pcm(config->format)) {
Haynes Mathew George851d3ff2017-06-19 20:01:57 -07002648 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_VOIP_TX);
Eric Laurent5dbe4712014-09-19 19:04:57 -07002649 }
2650
Carter Hsua3abb402021-10-26 11:11:20 +08002651 if (attributes.source == AUDIO_SOURCE_ULTRASOUND) {
2652 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_ULTRASOUND);
2653 }
2654
Andy Hungf129b032015-04-07 13:45:50 -07002655 // find a compatible input profile (not necessarily identical in parameters)
2656 sp<IOProfile> profile;
Eric Laurentfe231122017-11-17 17:48:06 -08002657 // sampling rate and flags may be updated by getInputProfile
2658 uint32_t profileSamplingRate = (config->sample_rate == 0) ?
2659 SAMPLE_RATE_HZ_DEFAULT : config->sample_rate;
Glenn Kasten730b9262018-03-29 15:01:26 -07002660 audio_format_t profileFormat;
Eric Laurentfe231122017-11-17 17:48:06 -08002661 audio_channel_mask_t profileChannelMask = config->channel_mask;
Andy Hungf129b032015-04-07 13:45:50 -07002662 audio_input_flags_t profileFlags = flags;
2663 for (;;) {
Glenn Kasten730b9262018-03-29 15:01:26 -07002664 profileFormat = config->format; // reset each time through loop, in case it is updated
François Gaffie11d30102018-11-02 16:09:09 +01002665 profile = getInputProfile(device, profileSamplingRate, profileFormat, profileChannelMask,
Andy Hungf129b032015-04-07 13:45:50 -07002666 profileFlags);
2667 if (profile != 0) {
2668 break; // success
Eric Laurent05067782016-06-01 18:27:28 -07002669 } else if (profileFlags & AUDIO_INPUT_FLAG_RAW) {
2670 profileFlags = (audio_input_flags_t) (profileFlags & ~AUDIO_INPUT_FLAG_RAW); // retry
Atneya Nair497fff12022-01-18 16:23:04 -05002671 } else if (profileFlags != AUDIO_INPUT_FLAG_NONE && audio_is_linear_pcm(config->format)) {
Andy Hungf129b032015-04-07 13:45:50 -07002672 profileFlags = AUDIO_INPUT_FLAG_NONE; // retry
2673 } else { // fail
François Gaffie11d30102018-11-02 16:09:09 +01002674 ALOGW("%s could not find profile for device %s, sampling rate %u, format %#x, "
Pattydd807582021-11-04 21:01:03 +08002675 "channel mask 0x%X, flags %#x", __func__, device->toString().c_str(),
François Gaffie11d30102018-11-02 16:09:09 +01002676 config->sample_rate, config->format, config->channel_mask, flags);
Eric Laurent599c7582015-12-07 18:05:55 -08002677 return input;
Eric Laurent5dbe4712014-09-19 19:04:57 -07002678 }
Eric Laurente552edb2014-03-10 17:42:56 -07002679 }
Glenn Kasten05ddca52016-02-11 08:17:12 -08002680 // Pick input sampling rate if not specified by client
Eric Laurentfe231122017-11-17 17:48:06 -08002681 uint32_t samplingRate = config->sample_rate;
Glenn Kasten05ddca52016-02-11 08:17:12 -08002682 if (samplingRate == 0) {
2683 samplingRate = profileSamplingRate;
2684 }
Eric Laurente552edb2014-03-10 17:42:56 -07002685
Eric Laurent322b4d22015-04-03 15:57:54 -07002686 if (profile->getModuleHandle() == 0) {
2687 ALOGE("getInputForAttr(): HW module %s not opened", profile->getModuleName());
Eric Laurent599c7582015-12-07 18:05:55 -08002688 return input;
Eric Laurentcf2c0212014-07-25 16:20:43 -07002689 }
2690
Eric Laurentec376dc2021-04-08 20:41:22 +02002691 // Reuse an already opened input if a client with the same session ID already exists
2692 // on that input
2693 for (size_t i = 0; i < mInputs.size(); i++) {
2694 sp <AudioInputDescriptor> desc = mInputs.valueAt(i);
2695 if (desc->mProfile != profile) {
2696 continue;
2697 }
2698 RecordClientVector clients = desc->clientsList();
2699 for (const auto &client : clients) {
2700 if (session == client->session()) {
2701 return desc->mIoHandle;
2702 }
2703 }
2704 }
2705
Eric Laurent3974e3b2017-12-07 17:58:43 -08002706 if (!profile->canOpenNewIo()) {
Eric Laurent4eb58f12018-12-07 16:41:02 -08002707 for (size_t i = 0; i < mInputs.size(); ) {
Eric Laurentc529cf62020-04-17 18:19:10 -07002708 sp<AudioInputDescriptor> desc = mInputs.valueAt(i);
Eric Laurent4eb58f12018-12-07 16:41:02 -08002709 if (desc->mProfile != profile) {
Carter Hsu9a645a92019-05-15 12:15:32 +08002710 i++;
Eric Laurent4eb58f12018-12-07 16:41:02 -08002711 continue;
2712 }
2713 // if sound trigger, reuse input if used by other sound trigger on same session
2714 // else
2715 // reuse input if active client app is not in IDLE state
2716 //
2717 RecordClientVector clients = desc->clientsList();
2718 bool doClose = false;
2719 for (const auto& client : clients) {
2720 if (isSoundTrigger != client->isSoundTrigger()) {
2721 continue;
2722 }
2723 if (client->isSoundTrigger()) {
2724 if (session == client->session()) {
2725 return desc->mIoHandle;
2726 }
2727 continue;
2728 }
2729 if (client->active() && client->appState() != APP_STATE_IDLE) {
2730 return desc->mIoHandle;
2731 }
2732 doClose = true;
2733 }
2734 if (doClose) {
2735 closeInput(desc->mIoHandle);
2736 } else {
2737 i++;
2738 }
2739 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002740 }
2741
Eric Laurentfe231122017-11-17 17:48:06 -08002742 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07002743
Eric Laurentfe231122017-11-17 17:48:06 -08002744 audio_config_t lConfig = AUDIO_CONFIG_INITIALIZER;
2745 lConfig.sample_rate = profileSamplingRate;
2746 lConfig.channel_mask = profileChannelMask;
2747 lConfig.format = profileFormat;
Eric Laurente3014102017-05-03 11:15:43 -07002748
François Gaffie11d30102018-11-02 16:09:09 +01002749 status_t status = inputDesc->open(&lConfig, device, halInputSource, profileFlags, &input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07002750
2751 // only accept input with the exact requested set of parameters
Eric Laurent599c7582015-12-07 18:05:55 -08002752 if (status != NO_ERROR || input == AUDIO_IO_HANDLE_NONE ||
Eric Laurentfe231122017-11-17 17:48:06 -08002753 (profileSamplingRate != lConfig.sample_rate) ||
2754 !audio_formats_match(profileFormat, lConfig.format) ||
2755 (profileChannelMask != lConfig.channel_mask)) {
2756 ALOGW("getInputForAttr() failed opening input: sampling rate %d"
Glenn Kasten49f36ba2017-12-06 13:02:02 -08002757 ", format %#x, channel mask %#x",
Eric Laurentfe231122017-11-17 17:48:06 -08002758 profileSamplingRate, profileFormat, profileChannelMask);
Eric Laurent599c7582015-12-07 18:05:55 -08002759 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfe231122017-11-17 17:48:06 -08002760 inputDesc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07002761 }
Eric Laurent599c7582015-12-07 18:05:55 -08002762 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07002763 }
2764
Eric Laurentc722f302014-12-10 11:21:49 -08002765 inputDesc->mPolicyMix = policyMix;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002766
Eric Laurent599c7582015-12-07 18:05:55 -08002767 addInput(input, inputDesc);
Eric Laurentb52c1522014-05-20 11:27:36 -07002768 mpClientInterface->onAudioPortListUpdate();
Paul McLean466dc8e2015-04-17 13:15:36 -06002769
Eric Laurent599c7582015-12-07 18:05:55 -08002770 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07002771}
2772
Eric Laurent4eb58f12018-12-07 16:41:02 -08002773status_t AudioPolicyManager::startInput(audio_port_handle_t portId)
Eric Laurentbb948092017-01-23 18:33:30 -08002774{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002775 ALOGV("%s portId %d", __FUNCTION__, portId);
2776
2777 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2778 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002779 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurentd52a28c2020-08-21 17:10:39 -07002780 return DEAD_OBJECT;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002781 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002782 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07002783 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002784 if (client->active()) {
2785 ALOGW("%s input %d client %d already started", __FUNCTION__, input, client->portId());
2786 return INVALID_OPERATION;
Eric Laurent4dc68062014-07-28 17:26:49 -07002787 }
2788
Eric Laurent8f42ea12018-08-08 09:08:25 -07002789 audio_session_t session = client->session();
2790
Eric Laurent4eb58f12018-12-07 16:41:02 -08002791 ALOGV("%s input:%d, session:%d)", __FUNCTION__, input, session);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002792
Eric Laurent4eb58f12018-12-07 16:41:02 -08002793 Vector<sp<AudioInputDescriptor>> activeInputs = mInputs.getActiveInputs();
Eric Laurent74708e72017-04-07 17:13:42 -07002794
Eric Laurent4eb58f12018-12-07 16:41:02 -08002795 status_t status = inputDesc->start();
2796 if (status != NO_ERROR) {
2797 return status;
Eric Laurent74708e72017-04-07 17:13:42 -07002798 }
Eric Laurente552edb2014-03-10 17:42:56 -07002799
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002800 // increment activity count before calling getNewInputDevice() below as only active sessions
Eric Laurent313d1e72016-01-29 09:56:57 -08002801 // are considered for device selection
Eric Laurent8f42ea12018-08-08 09:08:25 -07002802 inputDesc->setClientActive(client, true);
Eric Laurent313d1e72016-01-29 09:56:57 -08002803
Eric Laurent8f42ea12018-08-08 09:08:25 -07002804 // indicate active capture to sound trigger service if starting capture from a mic on
2805 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01002806 sp<DeviceDescriptor> device = getNewInputDevice(inputDesc);
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002807 if (device != nullptr) {
2808 status = setInputDevice(input, device, true /* force */);
2809 } else {
2810 ALOGW("%s no new input device can be found for descriptor %d",
2811 __FUNCTION__, inputDesc->getId());
2812 status = BAD_VALUE;
2813 }
Eric Laurente552edb2014-03-10 17:42:56 -07002814
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002815 if (status == NO_ERROR && inputDesc->activeCount() == 1) {
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002816 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002817 // if input maps to a dynamic policy with an activity listener, notify of state change
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002818 if ((policyMix != nullptr)
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002819 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
2820 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
Eric Laurent8f42ea12018-08-08 09:08:25 -07002821 MIX_STATE_MIXING);
Eric Laurent733ce942017-12-07 12:18:25 -08002822 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002823
François Gaffie11d30102018-11-02 16:09:09 +01002824 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
2825 if (primaryInputDevices.contains(device) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07002826 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 1) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07002827 mpClientInterface->setSoundTriggerCaptureState(true);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002828 }
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002829
Eric Laurent8f42ea12018-08-08 09:08:25 -07002830 // automatically enable the remote submix output when input is started if not
2831 // used by a policy mix of type MIX_TYPE_RECORDERS
2832 // For remote submix (a virtual device), we open only one input per capture request.
François Gaffie11d30102018-11-02 16:09:09 +01002833 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002834 String8 address = String8("");
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002835 if (policyMix == nullptr) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002836 address = String8("0");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002837 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
2838 address = policyMix->mDeviceAddress;
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002839 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07002840 if (address != "") {
2841 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2842 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002843 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurentc722f302014-12-10 11:21:49 -08002844 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07002845 }
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002846 } else if (status != NO_ERROR) {
2847 // Restore client activity state.
2848 inputDesc->setClientActive(client, false);
2849 inputDesc->stop();
Eric Laurente552edb2014-03-10 17:42:56 -07002850 }
2851
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002852 ALOGV("%s input %d source = %d status = %d exit",
2853 __FUNCTION__, input, client->source(), status);
Eric Laurente552edb2014-03-10 17:42:56 -07002854
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002855 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07002856}
2857
Eric Laurent8fc147b2018-07-22 19:13:55 -07002858status_t AudioPolicyManager::stopInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002859{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002860 ALOGV("%s portId %d", __FUNCTION__, portId);
2861
2862 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2863 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002864 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002865 return BAD_VALUE;
2866 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002867 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07002868 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002869 if (!client->active()) {
2870 ALOGW("%s input %d client %d already stopped", __FUNCTION__, input, client->portId());
Eric Laurente552edb2014-03-10 17:42:56 -07002871 return INVALID_OPERATION;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002872 }
Carter Hsue6139d52021-07-08 10:30:20 +08002873 auto old_source = inputDesc->source();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002874 inputDesc->setClientActive(client, false);
Paul McLean466dc8e2015-04-17 13:15:36 -06002875
Eric Laurent8f42ea12018-08-08 09:08:25 -07002876 inputDesc->stop();
2877 if (inputDesc->isActive()) {
Carter Hsue6139d52021-07-08 10:30:20 +08002878 auto current_source = inputDesc->source();
2879 setInputDevice(input, getNewInputDevice(inputDesc),
2880 old_source != current_source /* force */);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002881 } else {
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002882 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002883 // if input maps to a dynamic policy with an activity listener, notify of state change
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002884 if ((policyMix != nullptr)
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002885 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
2886 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
Eric Laurent8f42ea12018-08-08 09:08:25 -07002887 MIX_STATE_IDLE);
Eric Laurent84332aa2016-01-28 22:19:18 +00002888 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07002889
2890 // automatically disable the remote submix output when input is stopped if not
2891 // used by a policy mix of type MIX_TYPE_RECORDERS
François Gaffie11d30102018-11-02 16:09:09 +01002892 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002893 String8 address = String8("");
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002894 if (policyMix == nullptr) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002895 address = String8("0");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002896 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
2897 address = policyMix->mDeviceAddress;
Eric Laurent8f42ea12018-08-08 09:08:25 -07002898 }
2899 if (address != "") {
2900 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2901 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002902 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002903 }
2904 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07002905 resetInputDevice(input);
2906
2907 // indicate inactive capture to sound trigger service if stopping capture from a mic on
2908 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01002909 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
2910 if (primaryInputDevices.contains(inputDesc->getDevice()) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07002911 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07002912 mpClientInterface->setSoundTriggerCaptureState(false);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002913 }
2914 inputDesc->clearPreemptedSessions();
Eric Laurente552edb2014-03-10 17:42:56 -07002915 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002916 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07002917}
2918
Eric Laurent8fc147b2018-07-22 19:13:55 -07002919void AudioPolicyManager::releaseInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002920{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002921 ALOGV("%s portId %d", __FUNCTION__, portId);
2922
2923 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2924 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002925 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002926 return;
2927 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002928 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002929 audio_io_handle_t input = inputDesc->mIoHandle;
2930
Eric Laurent8f42ea12018-08-08 09:08:25 -07002931 ALOGV("%s %d", __FUNCTION__, input);
Paul McLean466dc8e2015-04-17 13:15:36 -06002932
Andy Hung39efb7a2018-09-26 15:39:28 -07002933 inputDesc->removeClient(portId);
Eric Laurent599c7582015-12-07 18:05:55 -08002934
Andy Hung39efb7a2018-09-26 15:39:28 -07002935 if (inputDesc->getClientCount() > 0) {
2936 ALOGV("%s(%d) %zu clients remaining", __func__, portId, inputDesc->getClientCount());
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002937 return;
2938 }
2939
Eric Laurent05b90f82014-08-27 15:32:29 -07002940 closeInput(input);
Eric Laurentb52c1522014-05-20 11:27:36 -07002941 mpClientInterface->onAudioPortListUpdate();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002942 ALOGV("%s exit", __FUNCTION__);
Eric Laurente552edb2014-03-10 17:42:56 -07002943}
2944
Eric Laurent8f42ea12018-08-08 09:08:25 -07002945void AudioPolicyManager::closeActiveClients(const sp<AudioInputDescriptor>& input)
Eric Laurent8fc147b2018-07-22 19:13:55 -07002946{
Eric Laurent8f42ea12018-08-08 09:08:25 -07002947 RecordClientVector clients = input->clientsList(true);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002948
2949 for (const auto& client : clients) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002950 closeClient(client->portId());
Eric Laurent8fc147b2018-07-22 19:13:55 -07002951 }
2952}
2953
Eric Laurent8f42ea12018-08-08 09:08:25 -07002954void AudioPolicyManager::closeClient(audio_port_handle_t portId)
2955{
2956 stopInput(portId);
2957 releaseInput(portId);
2958}
Eric Laurent8fc147b2018-07-22 19:13:55 -07002959
Eric Laurent0dd51852019-04-19 18:18:58 -07002960void AudioPolicyManager::checkCloseInputs() {
2961 // After connecting or disconnecting an input device, close input if:
2962 // - it has no client (was just opened to check profile) OR
2963 // - none of its supported devices are connected anymore OR
2964 // - one of its clients cannot be routed to one of its supported
2965 // devices anymore. Otherwise update device selection
2966 std::vector<audio_io_handle_t> inputsToClose;
2967 for (size_t i = 0; i < mInputs.size(); i++) {
2968 const sp<AudioInputDescriptor> input = mInputs.valueAt(i);
2969 if (input->clientsList().size() == 0
Eric Laurent85732f42020-03-19 11:31:10 -07002970 || !mAvailableInputDevices.containsAtLeastOne(input->supportedDevices())) {
Eric Laurent0dd51852019-04-19 18:18:58 -07002971 inputsToClose.push_back(mInputs.keyAt(i));
2972 } else {
2973 bool close = false;
2974 for (const auto& client : input->clientsList()) {
2975 sp<DeviceDescriptor> device =
yuanjiahsu0735bf32021-03-18 08:12:54 +08002976 mEngine->getInputDeviceForAttributes(client->attributes(), client->uid());
Eric Laurent0dd51852019-04-19 18:18:58 -07002977 if (!input->supportedDevices().contains(device)) {
2978 close = true;
2979 break;
2980 }
2981 }
2982 if (close) {
2983 inputsToClose.push_back(mInputs.keyAt(i));
2984 } else {
2985 setInputDevice(input->mIoHandle, getNewInputDevice(input));
2986 }
2987 }
2988 }
2989
2990 for (const audio_io_handle_t handle : inputsToClose) {
2991 ALOGV("%s closing input %d", __func__, handle);
2992 closeInput(handle);
Eric Laurent05b90f82014-08-27 15:32:29 -07002993 }
Eric Laurentd4692962014-05-05 18:13:44 -07002994}
2995
François Gaffie251c7f02018-11-07 10:41:08 +01002996void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream, int indexMin, int indexMax)
Eric Laurente552edb2014-03-10 17:42:56 -07002997{
2998 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08002999 if (indexMin < 0 || indexMax < 0) {
3000 ALOGE("%s for stream %d: invalid min %d or max %d", __func__, stream , indexMin, indexMax);
3001 return;
3002 }
Eric Laurentf5aa58d2019-02-22 18:20:11 -08003003 getVolumeCurves(stream).initVolume(indexMin, indexMax);
Eric Laurent28d09f02016-03-08 10:43:05 -08003004
3005 // initialize other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08003006 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
3007 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08003008 continue;
3009 }
Eric Laurentf5aa58d2019-02-22 18:20:11 -08003010 getVolumeCurves((audio_stream_type_t)curStream).initVolume(indexMin, indexMax);
Eric Laurent223fd5c2014-11-11 13:43:36 -08003011 }
Eric Laurente552edb2014-03-10 17:42:56 -07003012}
3013
Eric Laurente0720872014-03-11 09:30:41 -07003014status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
François Gaffie53615e22015-03-19 09:24:12 +01003015 int index,
3016 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07003017{
François Gaffieaaac0fd2018-11-22 17:56:39 +01003018 auto attributes = mEngine->getAttributesForStreamType(stream);
Eric Laurent242a9f82020-03-23 15:57:04 -07003019 if (attributes == AUDIO_ATTRIBUTES_INITIALIZER) {
3020 ALOGW("%s: no group for stream %s, bailing out", __func__, toString(stream).c_str());
3021 return NO_ERROR;
3022 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01003023 ALOGV("%s: stream %s attributes=%s", __func__,
3024 toString(stream).c_str(), toString(attributes).c_str());
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003025 return setVolumeIndexForAttributes(attributes, index, device);
Eric Laurente552edb2014-03-10 17:42:56 -07003026}
3027
Eric Laurente0720872014-03-11 09:30:41 -07003028status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
François Gaffieaaac0fd2018-11-22 17:56:39 +01003029 int *index,
3030 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07003031{
François Gaffiec005e562018-11-06 15:04:49 +01003032 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
3033 // stream by the engine.
jiabin9a3361e2019-10-01 09:38:30 -07003034 DeviceTypeSet deviceTypes = {device};
Eric Laurent5a2b6292016-04-14 18:05:57 -07003035 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
jiabin9a3361e2019-10-01 09:38:30 -07003036 deviceTypes = mEngine->getOutputDevicesForStream(
3037 stream, true /*fromCache*/).types();
Eric Laurente552edb2014-03-10 17:42:56 -07003038 }
jiabin9a3361e2019-10-01 09:38:30 -07003039 return getVolumeIndex(getVolumeCurves(stream), *index, deviceTypes);
Eric Laurente552edb2014-03-10 17:42:56 -07003040}
3041
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003042status_t AudioPolicyManager::setVolumeIndexForAttributes(const audio_attributes_t &attributes,
François Gaffiecfe17322018-11-07 13:41:29 +01003043 int index,
3044 audio_devices_t device)
3045{
3046 // Get Volume group matching the Audio Attributes
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003047 auto group = mEngine->getVolumeGroupForAttributes(attributes);
3048 if (group == VOLUME_GROUP_NONE) {
3049 ALOGD("%s: no group matching with %s", __FUNCTION__, toString(attributes).c_str());
François Gaffiecfe17322018-11-07 13:41:29 +01003050 return BAD_VALUE;
3051 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003052 ALOGV("%s: group %d matching with %s", __FUNCTION__, group, toString(attributes).c_str());
François Gaffiecfe17322018-11-07 13:41:29 +01003053 status_t status = NO_ERROR;
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003054 IVolumeCurves &curves = getVolumeCurves(attributes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01003055 VolumeSource vs = toVolumeSource(group);
Eric Laurentf9cccec2022-11-16 19:12:00 +01003056 // AUDIO_STREAM_BLUETOOTH_SCO is only used for volume control so we remap
3057 // to AUDIO_STREAM_VOICE_CALL to match with relevant playback activity
3058 VolumeSource activityVs = (vs == toVolumeSource(AUDIO_STREAM_BLUETOOTH_SCO, false)) ?
3059 toVolumeSource(AUDIO_STREAM_VOICE_CALL, false) : vs;
François Gaffieaaac0fd2018-11-22 17:56:39 +01003060 product_strategy_t strategy = mEngine->getProductStrategyForAttributes(attributes);
3061
3062 status = setVolumeCurveIndex(index, device, curves);
3063 if (status != NO_ERROR) {
3064 ALOGE("%s failed to set curve index for group %d device 0x%X", __func__, group, device);
3065 return status;
3066 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003067
jiabin9a3361e2019-10-01 09:38:30 -07003068 DeviceTypeSet curSrcDevices;
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003069 auto curCurvAttrs = curves.getAttributes();
3070 if (!curCurvAttrs.empty() && curCurvAttrs.front() != defaultAttr) {
3071 auto attr = curCurvAttrs.front();
jiabin9a3361e2019-10-01 09:38:30 -07003072 curSrcDevices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false).types();
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003073 } else if (!curves.getStreamTypes().empty()) {
3074 auto stream = curves.getStreamTypes().front();
jiabin9a3361e2019-10-01 09:38:30 -07003075 curSrcDevices = mEngine->getOutputDevicesForStream(stream, false).types();
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003076 } else {
3077 ALOGE("%s: Invalid src %d: no valid attributes nor stream",__func__, vs);
3078 return BAD_VALUE;
3079 }
jiabin9a3361e2019-10-01 09:38:30 -07003080 audio_devices_t curSrcDevice = Volume::getDeviceForVolume(curSrcDevices);
3081 resetDeviceTypes(curSrcDevices, curSrcDevice);
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003082
François Gaffiecfe17322018-11-07 13:41:29 +01003083 // update volume on all outputs and streams matching the following:
3084 // - The requested stream (or a stream matching for volume control) is active on the output
3085 // - The device (or devices) selected by the engine for this stream includes
3086 // the requested device
3087 // - For non default requested device, currently selected device on the output is either the
3088 // requested device or one of the devices selected by the engine for this stream
3089 // - For default requested device (AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME), apply volume only if
3090 // no specific device volume value exists for currently selected device.
François Gaffieaaac0fd2018-11-22 17:56:39 +01003091 for (size_t i = 0; i < mOutputs.size(); i++) {
3092 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
jiabin9a3361e2019-10-01 09:38:30 -07003093 DeviceTypeSet curDevices = desc->devices().types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01003094
jiabin9a3361e2019-10-01 09:38:30 -07003095 if (curDevices.erase(AUDIO_DEVICE_OUT_SPEAKER_SAFE)) {
3096 curDevices.insert(AUDIO_DEVICE_OUT_SPEAKER);
Robert Lee5e66e792019-04-03 18:37:15 +08003097 }
Eric Laurentf9cccec2022-11-16 19:12:00 +01003098
3099 if (!(desc->isActive(activityVs) || isInCallOrScreening())) {
François Gaffieed91f582020-01-31 10:35:37 +01003100 continue;
3101 }
3102 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME &&
3103 curDevices.find(device) == curDevices.end()) {
3104 continue;
3105 }
3106 bool applyVolume = false;
3107 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
3108 curSrcDevices.insert(device);
3109 applyVolume = (curSrcDevices.find(
3110 Volume::getDeviceForVolume(curDevices)) != curSrcDevices.end());
3111 } else {
3112 applyVolume = !curves.hasVolumeIndexForDevice(curSrcDevice);
3113 }
3114 if (!applyVolume) {
3115 continue; // next output
3116 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01003117 // Inter / intra volume group priority management: Loop on strategies arranged by priority
3118 // If a higher priority strategy is active, and the output is routed to a device with a
3119 // HW Gain management, do not change the volume
François Gaffieaaac0fd2018-11-22 17:56:39 +01003120 if (desc->useHwGain()) {
François Gaffieed91f582020-01-31 10:35:37 +01003121 applyVolume = false;
Francois Gaffie593634d2021-06-22 13:31:31 +02003122 // If the volume source is active with higher priority source, ensure at least Sw Muted
3123 desc->setSwMute((index == 0), vs, curves.getStreamTypes(), curDevices, 0 /*delayMs*/);
François Gaffieaaac0fd2018-11-22 17:56:39 +01003124 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
3125 auto activeClients = desc->clientsList(true /*activeOnly*/, productStrategy,
3126 false /*preferredDevice*/);
3127 if (activeClients.empty()) {
3128 continue;
3129 }
3130 bool isPreempted = false;
3131 bool isHigherPriority = productStrategy < strategy;
3132 for (const auto &client : activeClients) {
Eric Laurentf9cccec2022-11-16 19:12:00 +01003133 if (isHigherPriority && (client->volumeSource() != activityVs)) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01003134 ALOGV("%s: Strategy=%d (\nrequester:\n"
3135 " group %d, volumeGroup=%d attributes=%s)\n"
3136 " higher priority source active:\n"
3137 " volumeGroup=%d attributes=%s) \n"
3138 " on output %zu, bailing out", __func__, productStrategy,
3139 group, group, toString(attributes).c_str(),
3140 client->volumeSource(), toString(client->attributes()).c_str(), i);
3141 applyVolume = false;
3142 isPreempted = true;
3143 break;
3144 }
3145 // However, continue for loop to ensure no higher prio clients running on output
Eric Laurentf9cccec2022-11-16 19:12:00 +01003146 if (client->volumeSource() == activityVs) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01003147 applyVolume = true;
3148 }
3149 }
3150 if (isPreempted || applyVolume) {
3151 break;
3152 }
3153 }
3154 if (!applyVolume) {
3155 continue; // next output
3156 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01003157 }
François Gaffieed91f582020-01-31 10:35:37 +01003158 //FIXME: workaround for truncated touch sounds
3159 // delayed volume change for system stream to be removed when the problem is
3160 // handled by system UI
3161 status_t volStatus = checkAndSetVolume(
3162 curves, vs, index, desc, curDevices,
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003163 ((vs == toVolumeSource(AUDIO_STREAM_SYSTEM, false))?
François Gaffieed91f582020-01-31 10:35:37 +01003164 TOUCH_SOUND_FIXED_DELAY_MS : 0));
3165 if (volStatus != NO_ERROR) {
3166 status = volStatus;
François Gaffieaaac0fd2018-11-22 17:56:39 +01003167 }
3168 }
François Gaffiecfe17322018-11-07 13:41:29 +01003169 mpClientInterface->onAudioVolumeGroupChanged(group, 0 /*flags*/);
3170 return status;
3171}
3172
François Gaffieaaac0fd2018-11-22 17:56:39 +01003173status_t AudioPolicyManager::setVolumeCurveIndex(int index,
François Gaffiecfe17322018-11-07 13:41:29 +01003174 audio_devices_t device,
3175 IVolumeCurves &volumeCurves)
3176{
3177 // VOICE_CALL stream has minVolumeIndex > 0 but can be muted directly by an
3178 // app that has MODIFY_PHONE_STATE permission.
François Gaffieaaac0fd2018-11-22 17:56:39 +01003179 bool hasVoice = hasVoiceStream(volumeCurves.getStreamTypes());
3180 if (((index < volumeCurves.getVolumeIndexMin()) && !(hasVoice && index == 0)) ||
François Gaffiecfe17322018-11-07 13:41:29 +01003181 (index > volumeCurves.getVolumeIndexMax())) {
3182 ALOGD("%s: wrong index %d min=%d max=%d", __FUNCTION__, index,
3183 volumeCurves.getVolumeIndexMin(), volumeCurves.getVolumeIndexMax());
3184 return BAD_VALUE;
3185 }
3186 if (!audio_is_output_device(device)) {
3187 return BAD_VALUE;
3188 }
3189
3190 // Force max volume if stream cannot be muted
3191 if (!volumeCurves.canBeMuted()) index = volumeCurves.getVolumeIndexMax();
3192
François Gaffieaaac0fd2018-11-22 17:56:39 +01003193 ALOGV("%s device %08x, index %d", __FUNCTION__ , device, index);
François Gaffiecfe17322018-11-07 13:41:29 +01003194 volumeCurves.addCurrentVolumeIndex(device, index);
3195 return NO_ERROR;
3196}
3197
3198status_t AudioPolicyManager::getVolumeIndexForAttributes(const audio_attributes_t &attr,
3199 int &index,
3200 audio_devices_t device)
3201{
3202 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
3203 // stream by the engine.
jiabin9a3361e2019-10-01 09:38:30 -07003204 DeviceTypeSet deviceTypes = {device};
François Gaffiecfe17322018-11-07 13:41:29 +01003205 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
Mikhail Naganovbb990f22022-06-15 00:46:43 +00003206 deviceTypes = mEngine->getOutputDevicesForAttributes(
jiabin9a3361e2019-10-01 09:38:30 -07003207 attr, nullptr, true /*fromCache*/).types();
François Gaffiecfe17322018-11-07 13:41:29 +01003208 }
jiabin9a3361e2019-10-01 09:38:30 -07003209 return getVolumeIndex(getVolumeCurves(attr), index, deviceTypes);
François Gaffiecfe17322018-11-07 13:41:29 +01003210}
3211
3212status_t AudioPolicyManager::getVolumeIndex(const IVolumeCurves &curves,
3213 int &index,
jiabin9a3361e2019-10-01 09:38:30 -07003214 const DeviceTypeSet& deviceTypes) const
François Gaffiecfe17322018-11-07 13:41:29 +01003215{
Mikhail Naganovbb990f22022-06-15 00:46:43 +00003216 if (!isSingleDeviceType(deviceTypes, audio_is_output_device)) {
François Gaffiecfe17322018-11-07 13:41:29 +01003217 return BAD_VALUE;
3218 }
jiabin9a3361e2019-10-01 09:38:30 -07003219 index = curves.getVolumeIndex(deviceTypes);
3220 ALOGV("%s: device %s index %d", __FUNCTION__, dumpDeviceTypes(deviceTypes).c_str(), index);
François Gaffiecfe17322018-11-07 13:41:29 +01003221 return NO_ERROR;
3222}
3223
3224status_t AudioPolicyManager::getMinVolumeIndexForAttributes(const audio_attributes_t &attr,
3225 int &index)
3226{
3227 index = getVolumeCurves(attr).getVolumeIndexMin();
3228 return NO_ERROR;
3229}
3230
3231status_t AudioPolicyManager::getMaxVolumeIndexForAttributes(const audio_attributes_t &attr,
3232 int &index)
3233{
3234 index = getVolumeCurves(attr).getVolumeIndexMax();
3235 return NO_ERROR;
3236}
3237
Eric Laurent36829f92017-04-07 19:04:42 -07003238audio_io_handle_t AudioPolicyManager::selectOutputForMusicEffects()
Eric Laurente552edb2014-03-10 17:42:56 -07003239{
3240 // select one output among several suitable for global effects.
3241 // The priority is as follows:
3242 // 1: An offloaded output. If the effect ends up not being offloadable,
3243 // AudioFlinger will invalidate the track and the offloaded output
3244 // will be closed causing the effect to be moved to a PCM output.
3245 // 2: A deep buffer output
Eric Laurent36829f92017-04-07 19:04:42 -07003246 // 3: The primary output
3247 // 4: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07003248
François Gaffiec005e562018-11-06 15:04:49 +01003249 DeviceVector devices = mEngine->getOutputDevicesForAttributes(
3250 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
François Gaffie11d30102018-11-02 16:09:09 +01003251 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07003252
Eric Laurent36829f92017-04-07 19:04:42 -07003253 if (outputs.size() == 0) {
3254 return AUDIO_IO_HANDLE_NONE;
3255 }
Eric Laurente552edb2014-03-10 17:42:56 -07003256
Eric Laurent36829f92017-04-07 19:04:42 -07003257 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
3258 bool activeOnly = true;
3259
3260 while (output == AUDIO_IO_HANDLE_NONE) {
3261 audio_io_handle_t outputOffloaded = AUDIO_IO_HANDLE_NONE;
3262 audio_io_handle_t outputDeepBuffer = AUDIO_IO_HANDLE_NONE;
3263 audio_io_handle_t outputPrimary = AUDIO_IO_HANDLE_NONE;
3264
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003265 for (audio_io_handle_t output : outputs) {
3266 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
Eric Laurent83d17c22019-04-02 17:10:01 -07003267 if (activeOnly && !desc->isActive(toVolumeSource(AUDIO_STREAM_MUSIC))) {
Eric Laurent36829f92017-04-07 19:04:42 -07003268 continue;
3269 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003270 ALOGV("selectOutputForMusicEffects activeOnly %d output %d flags 0x%08x",
3271 activeOnly, output, desc->mFlags);
Eric Laurent36829f92017-04-07 19:04:42 -07003272 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003273 outputOffloaded = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003274 }
3275 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003276 outputDeepBuffer = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003277 }
3278 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003279 outputPrimary = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003280 }
3281 }
3282 if (outputOffloaded != AUDIO_IO_HANDLE_NONE) {
3283 output = outputOffloaded;
3284 } else if (outputDeepBuffer != AUDIO_IO_HANDLE_NONE) {
3285 output = outputDeepBuffer;
3286 } else if (outputPrimary != AUDIO_IO_HANDLE_NONE) {
3287 output = outputPrimary;
3288 } else {
3289 output = outputs[0];
3290 }
3291 activeOnly = false;
3292 }
3293
3294 if (output != mMusicEffectOutput) {
Eric Laurent6c796322019-04-09 14:13:17 -07003295 mEffects.moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output);
Eric Laurent36829f92017-04-07 19:04:42 -07003296 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output);
3297 mMusicEffectOutput = output;
3298 }
3299
3300 ALOGV("selectOutputForMusicEffects selected output %d", output);
Eric Laurente552edb2014-03-10 17:42:56 -07003301 return output;
3302}
3303
Eric Laurent36829f92017-04-07 19:04:42 -07003304audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc __unused)
3305{
3306 return selectOutputForMusicEffects();
3307}
3308
Eric Laurente0720872014-03-11 09:30:41 -07003309status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07003310 audio_io_handle_t io,
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08003311 product_strategy_t strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07003312 int session,
3313 int id)
3314{
Eric Laurentb82e6b72019-11-22 17:25:04 -08003315 if (session != AUDIO_SESSION_DEVICE) {
3316 ssize_t index = mOutputs.indexOfKey(io);
Eric Laurente552edb2014-03-10 17:42:56 -07003317 if (index < 0) {
Eric Laurentb82e6b72019-11-22 17:25:04 -08003318 index = mInputs.indexOfKey(io);
3319 if (index < 0) {
3320 ALOGW("registerEffect() unknown io %d", io);
3321 return INVALID_OPERATION;
3322 }
Eric Laurente552edb2014-03-10 17:42:56 -07003323 }
3324 }
Eric Laurentbf8f69f2022-03-25 17:48:38 +01003325 bool isMusicEffect = (session != AUDIO_SESSION_OUTPUT_STAGE)
3326 && ((strategy == streamToStrategy(AUDIO_STREAM_MUSIC)
3327 || strategy == PRODUCT_STRATEGY_NONE));
3328 return mEffects.registerEffect(desc, io, session, id, isMusicEffect);
Eric Laurente552edb2014-03-10 17:42:56 -07003329}
3330
Eric Laurentc241b0d2018-11-28 09:08:49 -08003331status_t AudioPolicyManager::unregisterEffect(int id)
3332{
3333 if (mEffects.getEffect(id) == nullptr) {
3334 return INVALID_OPERATION;
3335 }
Eric Laurentc241b0d2018-11-28 09:08:49 -08003336 if (mEffects.isEffectEnabled(id)) {
3337 ALOGW("%s effect %d enabled", __FUNCTION__, id);
3338 setEffectEnabled(id, false);
3339 }
3340 return mEffects.unregisterEffect(id);
3341}
3342
3343status_t AudioPolicyManager::setEffectEnabled(int id, bool enabled)
3344{
3345 sp<EffectDescriptor> effect = mEffects.getEffect(id);
3346 if (effect == nullptr) {
3347 return INVALID_OPERATION;
3348 }
3349
3350 status_t status = mEffects.setEffectEnabled(id, enabled);
3351 if (status == NO_ERROR) {
3352 mInputs.trackEffectEnabled(effect, enabled);
3353 }
3354 return status;
3355}
3356
Eric Laurent6c796322019-04-09 14:13:17 -07003357
3358status_t AudioPolicyManager::moveEffectsToIo(const std::vector<int>& ids, audio_io_handle_t io)
3359{
3360 mEffects.moveEffects(ids, io);
3361 return NO_ERROR;
3362}
3363
Eric Laurentc75307b2015-03-17 15:29:32 -07003364bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
3365{
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003366 auto vs = toVolumeSource(stream, false);
3367 return vs != VOLUME_SOURCE_NONE ? mOutputs.isActive(vs, inPastMs) : false;
Eric Laurentc75307b2015-03-17 15:29:32 -07003368}
3369
3370bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream, uint32_t inPastMs) const
3371{
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003372 auto vs = toVolumeSource(stream, false);
3373 return vs != VOLUME_SOURCE_NONE ? mOutputs.isActiveRemotely(vs, inPastMs) : false;
Eric Laurentc75307b2015-03-17 15:29:32 -07003374}
3375
Eric Laurente0720872014-03-11 09:30:41 -07003376bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07003377{
3378 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003379 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08003380 if (inputDescriptor->isSourceActive(source)) {
Eric Laurente552edb2014-03-10 17:42:56 -07003381 return true;
3382 }
3383 }
3384 return false;
3385}
3386
Eric Laurent275e8e92014-11-30 15:14:47 -08003387// Register a list of custom mixes with their attributes and format.
3388// When a mix is registered, corresponding input and output profiles are
3389// added to the remote submix hw module. The profile contains only the
3390// parameters (sampling rate, format...) specified by the mix.
3391// The corresponding input remote submix device is also connected.
3392//
3393// When a remote submix device is connected, the address is checked to select the
3394// appropriate profile and the corresponding input or output stream is opened.
3395//
3396// When capture starts, getInputForAttr() will:
3397// - 1 look for a mix matching the address passed in attribtutes tags if any
3398// - 2 if none found, getDeviceForInputSource() will:
3399// - 2.1 look for a mix matching the attributes source
3400// - 2.2 if none found, default to device selection by policy rules
3401// At this time, the corresponding output remote submix device is also connected
3402// and active playback use cases can be transferred to this mix if needed when reconnecting
3403// after AudioTracks are invalidated
3404//
3405// When playback starts, getOutputForAttr() will:
3406// - 1 look for a mix matching the address passed in attribtutes tags if any
3407// - 2 if none found, look for a mix matching the attributes usage
3408// - 3 if none found, default to device and output selection by policy rules.
3409
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003410status_t AudioPolicyManager::registerPolicyMixes(const Vector<AudioMix>& mixes)
Eric Laurent275e8e92014-11-30 15:14:47 -08003411{
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003412 ALOGV("registerPolicyMixes() %zu mix(es)", mixes.size());
3413 status_t res = NO_ERROR;
Eric Laurentc209fe42020-06-05 18:11:23 -07003414 bool checkOutputs = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003415 sp<HwModule> rSubmixModule;
3416 // examine each mix's route type
3417 for (size_t i = 0; i < mixes.size(); i++) {
Eric Laurent97ac8712018-07-27 18:59:02 -07003418 AudioMix mix = mixes[i];
Kevin Rocard153f92d2018-12-18 18:33:28 -08003419 // Only capture of playback is allowed in LOOP_BACK & RENDER mode
3420 if (is_mix_loopback_render(mix.mRouteFlags) && mix.mMixType != MIX_TYPE_PLAYERS) {
3421 ALOGE("Unsupported Policy Mix %zu of %zu: "
3422 "Only capture of playback is allowed in LOOP_BACK & RENDER mode",
3423 i, mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003424 res = INVALID_OPERATION;
Eric Laurent275e8e92014-11-30 15:14:47 -08003425 break;
3426 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08003427 // LOOP_BACK and LOOP_BACK | RENDER have the same remote submix backend and are handled
3428 // in the same way.
Eric Laurent97ac8712018-07-27 18:59:02 -07003429 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003430 ALOGV("registerPolicyMixes() mix %zu of %zu is LOOP_BACK %d", i, mixes.size(),
3431 mix.mRouteFlags);
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003432 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003433 rSubmixModule = mHwModules.getModuleFromName(
3434 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
3435 if (rSubmixModule == 0) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003436 ALOGE("Unable to find audio module for submix, aborting mix %zu registration",
Mikhail Naganovd4120142017-12-06 15:49:22 -08003437 i);
3438 res = INVALID_OPERATION;
3439 break;
3440 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003441 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003442
Eric Laurent97ac8712018-07-27 18:59:02 -07003443 String8 address = mix.mDeviceAddress;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003444 audio_devices_t deviceTypeToMakeAvailable;
Eric Laurent97ac8712018-07-27 18:59:02 -07003445 if (mix.mMixType == MIX_TYPE_PLAYERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07003446 mix.mDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003447 deviceTypeToMakeAvailable = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
3448 } else {
3449 mix.mDeviceType = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
3450 deviceTypeToMakeAvailable = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Eric Laurent97ac8712018-07-27 18:59:02 -07003451 }
François Gaffie036e1e92015-03-19 10:16:24 +01003452
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003453 if (mPolicyMixes.registerMix(mix, 0 /*output desc*/) != NO_ERROR) {
Tomasz Wasilczyk8f36f6e2023-08-15 20:59:35 +00003454 ALOGE("Error registering mix %zu for address %s", i, address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003455 res = INVALID_OPERATION;
3456 break;
3457 }
Eric Laurent97ac8712018-07-27 18:59:02 -07003458 audio_config_t outputConfig = mix.mFormat;
3459 audio_config_t inputConfig = mix.mFormat;
Eric Laurentc529cf62020-04-17 18:19:10 -07003460 // NOTE: audio flinger mixer does not support mono output: configure remote submix HAL
3461 // in stereo and let audio flinger do the channel conversion if needed.
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003462 outputConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
3463 inputConfig.channel_mask = AUDIO_CHANNEL_IN_STEREO;
jiabin5740f082019-08-19 15:08:30 -07003464 rSubmixModule->addOutputProfile(address.c_str(), &outputConfig,
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003465 AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address);
jiabin5740f082019-08-19 15:08:30 -07003466 rSubmixModule->addInputProfile(address.c_str(), &inputConfig,
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003467 AUDIO_DEVICE_IN_REMOTE_SUBMIX, address);
François Gaffie036e1e92015-03-19 10:16:24 +01003468
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003469 if ((res = setDeviceConnectionStateInt(deviceTypeToMakeAvailable,
jiabinc1de2df2019-05-07 14:26:40 -07003470 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Tomasz Wasilczyk8f36f6e2023-08-15 20:59:35 +00003471 address.c_str(), "remote-submix", AUDIO_FORMAT_DEFAULT)) != NO_ERROR) {
jiabinc1de2df2019-05-07 14:26:40 -07003472 ALOGE("Failed to set remote submix device available, type %u, address %s",
Tomasz Wasilczyk8f36f6e2023-08-15 20:59:35 +00003473 mix.mDeviceType, address.c_str());
jiabinc1de2df2019-05-07 14:26:40 -07003474 break;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003475 }
Eric Laurent97ac8712018-07-27 18:59:02 -07003476 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
3477 String8 address = mix.mDeviceAddress;
Eric Laurent2c80be02019-01-23 18:06:37 -08003478 audio_devices_t type = mix.mDeviceType;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003479 ALOGV(" registerPolicyMixes() mix %zu of %zu is RENDER, dev=0x%X addr=%s",
Tomasz Wasilczyk8f36f6e2023-08-15 20:59:35 +00003480 i, mixes.size(), type, address.c_str());
Eric Laurent2c80be02019-01-23 18:06:37 -08003481
3482 sp<DeviceDescriptor> device = mHwModules.getDeviceDescriptor(
3483 mix.mDeviceType, mix.mDeviceAddress,
3484 String8(), AUDIO_FORMAT_DEFAULT);
3485 if (device == nullptr) {
3486 res = INVALID_OPERATION;
3487 break;
3488 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003489
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003490 bool foundOutput = false;
Eric Laurentc529cf62020-04-17 18:19:10 -07003491 // First try to find an already opened output supporting the device
3492 for (size_t j = 0 ; j < mOutputs.size() && !foundOutput && res == NO_ERROR; j++) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003493 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurent2c80be02019-01-23 18:06:37 -08003494
Eric Laurentc529cf62020-04-17 18:19:10 -07003495 if (!desc->isDuplicated() && desc->supportedDevices().contains(device)) {
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003496 if (mPolicyMixes.registerMix(mix, desc) != NO_ERROR) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003497 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
Tomasz Wasilczyk8f36f6e2023-08-15 20:59:35 +00003498 address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003499 res = INVALID_OPERATION;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003500 } else {
3501 foundOutput = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003502 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003503 }
3504 }
Eric Laurentc529cf62020-04-17 18:19:10 -07003505 // If no output found, try to find a direct output profile supporting the device
3506 for (size_t i = 0; i < mHwModules.size() && !foundOutput && res == NO_ERROR; i++) {
3507 sp<HwModule> module = mHwModules[i];
3508 for (size_t j = 0;
3509 j < module->getOutputProfiles().size() && !foundOutput && res == NO_ERROR;
3510 j++) {
3511 sp<IOProfile> profile = module->getOutputProfiles()[j];
3512 if (profile->isDirectOutput() && profile->supportsDevice(device)) {
3513 if (mPolicyMixes.registerMix(mix, nullptr) != NO_ERROR) {
3514 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
Tomasz Wasilczyk8f36f6e2023-08-15 20:59:35 +00003515 address.c_str());
Eric Laurentc529cf62020-04-17 18:19:10 -07003516 res = INVALID_OPERATION;
3517 } else {
3518 foundOutput = true;
3519 }
3520 }
3521 }
3522 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003523 if (res != NO_ERROR) {
3524 ALOGE(" Error registering mix %zu for device 0x%X addr %s",
Tomasz Wasilczyk8f36f6e2023-08-15 20:59:35 +00003525 i, type, address.c_str());
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003526 res = INVALID_OPERATION;
3527 break;
3528 } else if (!foundOutput) {
3529 ALOGE(" Output not found for mix %zu for device 0x%X addr %s",
Tomasz Wasilczyk8f36f6e2023-08-15 20:59:35 +00003530 i, type, address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003531 res = INVALID_OPERATION;
3532 break;
Eric Laurentc209fe42020-06-05 18:11:23 -07003533 } else {
3534 checkOutputs = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003535 }
Eric Laurentc722f302014-12-10 11:21:49 -08003536 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003537 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003538 if (res != NO_ERROR) {
3539 unregisterPolicyMixes(mixes);
Eric Laurentc209fe42020-06-05 18:11:23 -07003540 } else if (checkOutputs) {
3541 checkForDeviceAndOutputChanges();
3542 updateCallAndOutputRouting();
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003543 }
3544 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08003545}
3546
3547status_t AudioPolicyManager::unregisterPolicyMixes(Vector<AudioMix> mixes)
3548{
Eric Laurent7b279bb2015-12-14 10:18:23 -08003549 ALOGV("unregisterPolicyMixes() num mixes %zu", mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003550 status_t res = NO_ERROR;
Eric Laurentc209fe42020-06-05 18:11:23 -07003551 bool checkOutputs = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003552 sp<HwModule> rSubmixModule;
3553 // examine each mix's route type
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003554 for (const auto& mix : mixes) {
3555 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie036e1e92015-03-19 10:16:24 +01003556
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003557 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003558 rSubmixModule = mHwModules.getModuleFromName(
3559 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
3560 if (rSubmixModule == 0) {
3561 res = INVALID_OPERATION;
3562 continue;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003563 }
3564 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003565
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003566 String8 address = mix.mDeviceAddress;
Eric Laurent275e8e92014-11-30 15:14:47 -08003567
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003568 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003569 res = INVALID_OPERATION;
3570 continue;
3571 }
3572
Kevin Rocard04ed0462019-05-02 17:53:24 -07003573 for (auto device : {AUDIO_DEVICE_IN_REMOTE_SUBMIX, AUDIO_DEVICE_OUT_REMOTE_SUBMIX}) {
Tomasz Wasilczyk8f36f6e2023-08-15 20:59:35 +00003574 if (getDeviceConnectionState(device, address.c_str()) ==
Kevin Rocard04ed0462019-05-02 17:53:24 -07003575 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
3576 res = setDeviceConnectionStateInt(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Tomasz Wasilczyk8f36f6e2023-08-15 20:59:35 +00003577 address.c_str(), "remote-submix",
Kevin Rocard04ed0462019-05-02 17:53:24 -07003578 AUDIO_FORMAT_DEFAULT);
3579 if (res != OK) {
3580 ALOGE("Error making RemoteSubmix device unavailable for mix "
Tomasz Wasilczyk8f36f6e2023-08-15 20:59:35 +00003581 "with type %d, address %s", device, address.c_str());
Kevin Rocard04ed0462019-05-02 17:53:24 -07003582 }
3583 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003584 }
jiabin5740f082019-08-19 15:08:30 -07003585 rSubmixModule->removeOutputProfile(address.c_str());
3586 rSubmixModule->removeInputProfile(address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003587
Kevin Rocard153f92d2018-12-18 18:33:28 -08003588 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003589 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003590 res = INVALID_OPERATION;
3591 continue;
Eric Laurentc209fe42020-06-05 18:11:23 -07003592 } else {
3593 checkOutputs = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003594 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003595 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003596 }
Eric Laurentc209fe42020-06-05 18:11:23 -07003597 if (res == NO_ERROR && checkOutputs) {
3598 checkForDeviceAndOutputChanges();
3599 updateCallAndOutputRouting();
3600 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003601 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08003602}
3603
Mikhail Naganov100f0122018-11-29 11:22:16 -08003604void AudioPolicyManager::dumpManualSurroundFormats(String8 *dst) const
3605{
3606 size_t i = 0;
3607 constexpr size_t audioFormatPrefixLen = sizeof("AUDIO_FORMAT_");
3608 for (const auto& fmt : mManualSurroundFormats) {
3609 if (i++ != 0) dst->append(", ");
3610 std::string sfmt;
3611 FormatConverter::toString(fmt, sfmt);
3612 dst->append(sfmt.size() >= audioFormatPrefixLen ?
3613 sfmt.c_str() + audioFormatPrefixLen - 1 : sfmt.c_str());
3614 }
3615}
3616
Eric Laurentc529cf62020-04-17 18:19:10 -07003617// Returns true if all devices types match the predicate and are supported by one HW module
3618bool AudioPolicyManager::areAllDevicesSupported(
jiabin6a02d532020-08-07 11:56:38 -07003619 const AudioDeviceTypeAddrVector& devices,
Eric Laurentc529cf62020-04-17 18:19:10 -07003620 std::function<bool(audio_devices_t)> predicate,
3621 const char *context) {
3622 for (size_t i = 0; i < devices.size(); i++) {
3623 sp<DeviceDescriptor> devDesc = mHwModules.getDeviceDescriptor(
jiabin0a488932020-08-07 17:32:40 -07003624 devices[i].mType, devices[i].getAddress(), String8(),
Eric Laurent0e26e3f2020-04-29 14:24:16 -07003625 AUDIO_FORMAT_DEFAULT, false /*allowToCreate*/, true /*matchAddress*/);
Eric Laurentc529cf62020-04-17 18:19:10 -07003626 if (devDesc == nullptr || (predicate != nullptr && !predicate(devices[i].mType))) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003627 ALOGE("%s: device type %#x address %s not supported or not match predicate",
jiabin0a488932020-08-07 17:32:40 -07003628 context, devices[i].mType, devices[i].getAddress());
Eric Laurentc529cf62020-04-17 18:19:10 -07003629 return false;
3630 }
3631 }
3632 return true;
3633}
3634
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003635status_t AudioPolicyManager::setUidDeviceAffinities(uid_t uid,
jiabin6a02d532020-08-07 11:56:38 -07003636 const AudioDeviceTypeAddrVector& devices) {
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003637 ALOGV("%s() uid=%d num devices %zu", __FUNCTION__, uid, devices.size());
Eric Laurentc529cf62020-04-17 18:19:10 -07003638 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
3639 return BAD_VALUE;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003640 }
3641 status_t res = mPolicyMixes.setUidDeviceAffinities(uid, devices);
Eric Laurentc529cf62020-04-17 18:19:10 -07003642 if (res != NO_ERROR) {
3643 ALOGE("%s() Could not set all device affinities for uid = %d", __FUNCTION__, uid);
3644 return res;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003645 }
Eric Laurentc529cf62020-04-17 18:19:10 -07003646
3647 checkForDeviceAndOutputChanges();
3648 updateCallAndOutputRouting();
3649
3650 return NO_ERROR;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003651}
3652
3653status_t AudioPolicyManager::removeUidDeviceAffinities(uid_t uid) {
3654 ALOGV("%s() uid=%d", __FUNCTION__, uid);
Oscar Azucena4b2a8212019-04-26 23:48:59 -07003655 status_t res = mPolicyMixes.removeUidDeviceAffinities(uid);
3656 if (res != NO_ERROR) {
Eric Laurentc529cf62020-04-17 18:19:10 -07003657 ALOGE("%s() Could not remove all device affinities for uid = %d",
Oscar Azucena4b2a8212019-04-26 23:48:59 -07003658 __FUNCTION__, uid);
3659 return INVALID_OPERATION;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003660 }
3661
Eric Laurentc529cf62020-04-17 18:19:10 -07003662 checkForDeviceAndOutputChanges();
3663 updateCallAndOutputRouting();
3664
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003665 return res;
3666}
3667
Eric Laurent2517af32020-11-25 15:31:27 +01003668
jiabin0a488932020-08-07 17:32:40 -07003669status_t AudioPolicyManager::setDevicesRoleForStrategy(product_strategy_t strategy,
3670 device_role_t role,
3671 const AudioDeviceTypeAddrVector &devices) {
3672 ALOGV("%s() strategy=%d role=%d %s", __func__, strategy, role,
3673 dumpAudioDeviceTypeAddrVector(devices).c_str());
Eric Laurentc529cf62020-04-17 18:19:10 -07003674
Eric Laurentc529cf62020-04-17 18:19:10 -07003675 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003676 return BAD_VALUE;
3677 }
jiabin0a488932020-08-07 17:32:40 -07003678 status_t status = mEngine->setDevicesRoleForStrategy(strategy, role, devices);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003679 if (status != NO_ERROR) {
jiabin0a488932020-08-07 17:32:40 -07003680 ALOGW("Engine could not set preferred devices %s for strategy %d role %d",
3681 dumpAudioDeviceTypeAddrVector(devices).c_str(), strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003682 return status;
3683 }
3684
3685 checkForDeviceAndOutputChanges();
Eric Laurent2517af32020-11-25 15:31:27 +01003686
3687 bool forceVolumeReeval = false;
3688 // FIXME: workaround for truncated touch sounds
3689 // to be removed when the problem is handled by system UI
3690 uint32_t delayMs = 0;
3691 if (strategy == mCommunnicationStrategy) {
3692 forceVolumeReeval = true;
3693 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
3694 updateInputRouting();
3695 }
3696 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003697
3698 return NO_ERROR;
3699}
3700
3701void AudioPolicyManager::updateCallAndOutputRouting(bool forceVolumeReeval, uint32_t delayMs)
3702{
3703 uint32_t waitMs = 0;
Eric Laurent96d1dda2022-03-14 17:14:19 +01003704 bool wasLeUnicastActive = isLeUnicastActive();
Francois Gaffie19fd6c52021-02-04 17:02:59 +01003705 if (updateCallRouting(true /*fromCache*/, delayMs, &waitMs) == NO_ERROR) {
Eric Laurentb36b4ac2020-08-21 12:50:41 -07003706 // Only apply special touch sound delay once
3707 delayMs = 0;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003708 }
3709 for (size_t i = 0; i < mOutputs.size(); i++) {
3710 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
3711 DeviceVector newDevices = getNewOutputDevices(outputDesc, true /*fromCache*/);
Francois Gaffie601801d2021-06-22 13:27:39 +02003712 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) ||
3713 (outputDesc != mPrimaryOutput && !isTelephonyRxOrTx(outputDesc))) {
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003714 // As done in setDeviceConnectionState, we could also fix default device issue by
3715 // preventing the force re-routing in case of default dev that distinguishes on address.
3716 // Let's give back to engine full device choice decision however.
Francois Gaffie601801d2021-06-22 13:27:39 +02003717 bool forceRouting = !newDevices.isEmpty();
3718 waitMs = setOutputDevices(outputDesc, newDevices, forceRouting, delayMs, nullptr,
3719 true /*requiresMuteCheck*/,
3720 !forceRouting /*requiresVolumeCheck*/);
Eric Laurentb36b4ac2020-08-21 12:50:41 -07003721 // Only apply special touch sound delay once
3722 delayMs = 0;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003723 }
3724 if (forceVolumeReeval && !newDevices.isEmpty()) {
3725 applyStreamVolumes(outputDesc, newDevices.types(), waitMs, true);
3726 }
3727 }
Eric Laurent96d1dda2022-03-14 17:14:19 +01003728 checkLeBroadcastRoutes(wasLeUnicastActive, nullptr, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003729}
3730
Eric Laurent2517af32020-11-25 15:31:27 +01003731void AudioPolicyManager::updateInputRouting() {
3732 for (const auto& activeDesc : mInputs.getActiveInputs()) {
Jaideep Sharma408349a2020-11-27 14:47:17 +05303733 // Skip for hotword recording as the input device switch
3734 // is handled within sound trigger HAL
3735 if (activeDesc->isSoundTrigger() && activeDesc->source() == AUDIO_SOURCE_HOTWORD) {
3736 continue;
3737 }
Eric Laurent2517af32020-11-25 15:31:27 +01003738 auto newDevice = getNewInputDevice(activeDesc);
3739 // Force new input selection if the new device can not be reached via current input
3740 if (activeDesc->mProfile->getSupportedDevices().contains(newDevice)) {
3741 setInputDevice(activeDesc->mIoHandle, newDevice);
3742 } else {
3743 closeInput(activeDesc->mIoHandle);
3744 }
3745 }
3746}
3747
jiabin0a488932020-08-07 17:32:40 -07003748status_t AudioPolicyManager::removeDevicesRoleForStrategy(product_strategy_t strategy,
3749 device_role_t role)
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003750{
Eric Laurentfecbceb2021-02-09 14:46:43 +01003751 ALOGV("%s() strategy=%d role=%d", __func__, strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003752
jiabin0a488932020-08-07 17:32:40 -07003753 status_t status = mEngine->removeDevicesRoleForStrategy(strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003754 if (status != NO_ERROR) {
Eric Laurent2517af32020-11-25 15:31:27 +01003755 ALOGV("Engine could not remove preferred device for strategy %d status %d",
3756 strategy, status);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003757 return status;
3758 }
3759
3760 checkForDeviceAndOutputChanges();
Eric Laurent2517af32020-11-25 15:31:27 +01003761
3762 bool forceVolumeReeval = false;
3763 // FIXME: workaround for truncated touch sounds
3764 // to be removed when the problem is handled by system UI
3765 uint32_t delayMs = 0;
3766 if (strategy == mCommunnicationStrategy) {
3767 forceVolumeReeval = true;
3768 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
3769 updateInputRouting();
3770 }
3771 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003772
3773 return NO_ERROR;
3774}
3775
jiabin0a488932020-08-07 17:32:40 -07003776status_t AudioPolicyManager::getDevicesForRoleAndStrategy(product_strategy_t strategy,
3777 device_role_t role,
3778 AudioDeviceTypeAddrVector &devices) {
3779 return mEngine->getDevicesForRoleAndStrategy(strategy, role, devices);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003780}
3781
Jiabin Huang3b98d322020-09-03 17:54:16 +00003782status_t AudioPolicyManager::setDevicesRoleForCapturePreset(
3783 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices) {
3784 ALOGV("%s() audioSource=%d role=%d %s", __func__, audioSource, role,
3785 dumpAudioDeviceTypeAddrVector(devices).c_str());
3786
Mikhail Naganov55773032020-10-01 15:08:13 -07003787 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003788 return BAD_VALUE;
3789 }
3790 status_t status = mEngine->setDevicesRoleForCapturePreset(audioSource, role, devices);
3791 ALOGW_IF(status != NO_ERROR,
3792 "Engine could not set preferred devices %s for audio source %d role %d",
3793 dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
3794
3795 return status;
3796}
3797
3798status_t AudioPolicyManager::addDevicesRoleForCapturePreset(
3799 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices) {
3800 ALOGV("%s() audioSource=%d role=%d %s", __func__, audioSource, role,
3801 dumpAudioDeviceTypeAddrVector(devices).c_str());
3802
Mikhail Naganov55773032020-10-01 15:08:13 -07003803 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003804 return BAD_VALUE;
3805 }
3806 status_t status = mEngine->addDevicesRoleForCapturePreset(audioSource, role, devices);
3807 ALOGW_IF(status != NO_ERROR,
3808 "Engine could not add preferred devices %s for audio source %d role %d",
3809 dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
3810
Eric Laurent2517af32020-11-25 15:31:27 +01003811 updateInputRouting();
Jiabin Huang3b98d322020-09-03 17:54:16 +00003812 return status;
3813}
3814
3815status_t AudioPolicyManager::removeDevicesRoleForCapturePreset(
3816 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector& devices)
3817{
3818 ALOGV("%s() audioSource=%d role=%d devices=%s", __func__, audioSource, role,
3819 dumpAudioDeviceTypeAddrVector(devices).c_str());
3820
Mikhail Naganov55773032020-10-01 15:08:13 -07003821 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003822 return BAD_VALUE;
3823 }
3824
3825 status_t status = mEngine->removeDevicesRoleForCapturePreset(
3826 audioSource, role, devices);
3827 ALOGW_IF(status != NO_ERROR,
3828 "Engine could not remove devices role (%d) for capture preset %d", role, audioSource);
3829
Eric Laurent2517af32020-11-25 15:31:27 +01003830 updateInputRouting();
Jiabin Huang3b98d322020-09-03 17:54:16 +00003831 return status;
3832}
3833
3834status_t AudioPolicyManager::clearDevicesRoleForCapturePreset(audio_source_t audioSource,
3835 device_role_t role) {
3836 ALOGV("%s() audioSource=%d role=%d", __func__, audioSource, role);
3837
3838 status_t status = mEngine->clearDevicesRoleForCapturePreset(audioSource, role);
3839 ALOGW_IF(status != NO_ERROR,
3840 "Engine could not clear devices role (%d) for capture preset %d", role, audioSource);
3841
Eric Laurent2517af32020-11-25 15:31:27 +01003842 updateInputRouting();
Jiabin Huang3b98d322020-09-03 17:54:16 +00003843 return status;
3844}
3845
3846status_t AudioPolicyManager::getDevicesForRoleAndCapturePreset(
3847 audio_source_t audioSource, device_role_t role, AudioDeviceTypeAddrVector &devices) {
3848 return mEngine->getDevicesForRoleAndCapturePreset(audioSource, role, devices);
3849}
3850
Oscar Azucena90e77632019-11-27 17:12:28 -08003851status_t AudioPolicyManager::setUserIdDeviceAffinities(int userId,
jiabin6a02d532020-08-07 11:56:38 -07003852 const AudioDeviceTypeAddrVector& devices) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01003853 ALOGV("%s() userId=%d num devices %zu", __func__, userId, devices.size());
Eric Laurentc529cf62020-04-17 18:19:10 -07003854 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
3855 return BAD_VALUE;
Oscar Azucena90e77632019-11-27 17:12:28 -08003856 }
Oscar Azucena90e77632019-11-27 17:12:28 -08003857 status_t status = mPolicyMixes.setUserIdDeviceAffinities(userId, devices);
3858 if (status != NO_ERROR) {
3859 ALOGE("%s() could not set device affinity for userId %d",
3860 __FUNCTION__, userId);
3861 return status;
3862 }
3863
3864 // reevaluate outputs for all devices
3865 checkForDeviceAndOutputChanges();
3866 updateCallAndOutputRouting();
3867
3868 return NO_ERROR;
3869}
3870
3871status_t AudioPolicyManager::removeUserIdDeviceAffinities(int userId) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01003872 ALOGV("%s() userId=%d", __FUNCTION__, userId);
Oscar Azucena90e77632019-11-27 17:12:28 -08003873 status_t status = mPolicyMixes.removeUserIdDeviceAffinities(userId);
3874 if (status != NO_ERROR) {
3875 ALOGE("%s() Could not remove all device affinities fo userId = %d",
3876 __FUNCTION__, userId);
3877 return status;
3878 }
3879
3880 // reevaluate outputs for all devices
3881 checkForDeviceAndOutputChanges();
3882 updateCallAndOutputRouting();
3883
3884 return NO_ERROR;
3885}
3886
Andy Hungc29d82b2018-10-05 12:23:17 -07003887void AudioPolicyManager::dump(String8 *dst) const
Eric Laurente552edb2014-03-10 17:42:56 -07003888{
Andy Hungc29d82b2018-10-05 12:23:17 -07003889 dst->appendFormat("\nAudioPolicyManager Dump: %p\n", this);
Mikhail Naganov0dbe87b2021-12-01 02:03:31 +00003890 dst->appendFormat(" Primary Output I/O handle: %d\n",
Eric Laurent87ffa392015-05-22 10:32:38 -07003891 hasPrimaryOutput() ? mPrimaryOutput->mIoHandle : AUDIO_IO_HANDLE_NONE);
Mikhail Naganov0d6a0332016-04-19 17:12:38 -07003892 std::string stateLiteral;
3893 AudioModeConverter::toString(mEngine->getPhoneState(), stateLiteral);
Andy Hungc29d82b2018-10-05 12:23:17 -07003894 dst->appendFormat(" Phone state: %s\n", stateLiteral.c_str());
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07003895 const char* forceUses[AUDIO_POLICY_FORCE_USE_CNT] = {
3896 "communications", "media", "record", "dock", "system",
3897 "HDMI system audio", "encoded surround output", "vibrate ringing" };
3898 for (audio_policy_force_use_t i = AUDIO_POLICY_FORCE_FOR_COMMUNICATION;
3899 i < AUDIO_POLICY_FORCE_USE_CNT; i = (audio_policy_force_use_t)((int)i + 1)) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08003900 audio_policy_forced_cfg_t forceUseValue = mEngine->getForceUse(i);
3901 dst->appendFormat(" Force use for %s: %d", forceUses[i], forceUseValue);
3902 if (i == AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND &&
3903 forceUseValue == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
3904 dst->append(" (MANUAL: ");
3905 dumpManualSurroundFormats(dst);
3906 dst->append(")");
3907 }
3908 dst->append("\n");
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07003909 }
Andy Hungc29d82b2018-10-05 12:23:17 -07003910 dst->appendFormat(" TTS output %savailable\n", mTtsOutputAvailable ? "" : "not ");
3911 dst->appendFormat(" Master mono: %s\n", mMasterMono ? "on" : "off");
Mikhail Naganovb3bcb4f2022-02-23 23:46:56 +00003912 dst->appendFormat(" Communication Strategy id: %d\n", mCommunnicationStrategy);
Mikhail Naganovb0fbc1b2023-04-28 13:06:32 -07003913 dst->appendFormat(" Config source: %s\n", mConfig->getSource().c_str());
Eric Laurent2517af32020-11-25 15:31:27 +01003914
Mikhail Naganov0f413b22021-12-02 05:29:27 +00003915 dst->append("\n");
3916 mAvailableOutputDevices.dump(dst, String8("Available output"), 1);
3917 dst->append("\n");
3918 mAvailableInputDevices.dump(dst, String8("Available input"), 1);
Mikhail Naganovb0fbc1b2023-04-28 13:06:32 -07003919 mHwModules.dump(dst);
Andy Hungc29d82b2018-10-05 12:23:17 -07003920 mOutputs.dump(dst);
3921 mInputs.dump(dst);
Mikhail Naganov0f413b22021-12-02 05:29:27 +00003922 mEffects.dump(dst, 1);
Andy Hungc29d82b2018-10-05 12:23:17 -07003923 mAudioPatches.dump(dst);
3924 mPolicyMixes.dump(dst);
3925 mAudioSources.dump(dst);
François Gaffiec005e562018-11-06 15:04:49 +01003926
Kevin Rocardb99cc752019-03-21 20:52:24 -07003927 dst->appendFormat(" AllowedCapturePolicies:\n");
3928 for (auto& policy : mAllowedCapturePolicies) {
3929 dst->appendFormat(" - uid=%d flag_mask=%#x\n", policy.first, policy.second);
3930 }
3931
François Gaffiec005e562018-11-06 15:04:49 +01003932 dst->appendFormat("\nPolicy Engine dump:\n");
3933 mEngine->dump(dst);
Andy Hungc29d82b2018-10-05 12:23:17 -07003934}
3935
3936status_t AudioPolicyManager::dump(int fd)
3937{
3938 String8 result;
3939 dump(&result);
Tomasz Wasilczyk8f36f6e2023-08-15 20:59:35 +00003940 write(fd, result.c_str(), result.size());
Eric Laurente552edb2014-03-10 17:42:56 -07003941 return NO_ERROR;
3942}
3943
Kevin Rocardb99cc752019-03-21 20:52:24 -07003944status_t AudioPolicyManager::setAllowedCapturePolicy(uid_t uid, audio_flags_mask_t capturePolicy)
3945{
3946 mAllowedCapturePolicies[uid] = capturePolicy;
3947 return NO_ERROR;
3948}
3949
Eric Laurente552edb2014-03-10 17:42:56 -07003950// This function checks for the parameters which can be offloaded.
3951// This can be enhanced depending on the capability of the DSP and policy
3952// of the system.
Eric Laurent90fe31c2020-11-26 20:06:35 +01003953audio_offload_mode_t AudioPolicyManager::getOffloadSupport(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07003954{
Eric Laurent90fe31c2020-11-26 20:06:35 +01003955 ALOGV("%s: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07003956 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurent90fe31c2020-11-26 20:06:35 +01003957 __func__, offloadInfo.sample_rate, offloadInfo.channel_mask,
Eric Laurente552edb2014-03-10 17:42:56 -07003958 offloadInfo.format,
3959 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
3960 offloadInfo.has_video);
3961
jiabin2b9d5a12021-12-10 01:06:29 +00003962 if (!isOffloadPossible(offloadInfo)) {
Eric Laurent90fe31c2020-11-26 20:06:35 +01003963 return AUDIO_OFFLOAD_NOT_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07003964 }
3965
3966 // See if there is a profile to support this.
3967 // AUDIO_DEVICE_NONE
François Gaffie11d30102018-11-02 16:09:09 +01003968 sp<IOProfile> profile = getProfileForOutput(DeviceVector() /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07003969 offloadInfo.sample_rate,
3970 offloadInfo.format,
3971 offloadInfo.channel_mask,
Michael Chana94fbb22018-04-24 14:31:19 +10003972 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD,
3973 true /* directOnly */);
Eric Laurent94365442021-01-08 18:36:05 +01003974 ALOGV("%s: profile %sfound%s", __func__, profile != nullptr ? "" : "NOT ",
3975 (profile != nullptr && (profile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD) != 0)
3976 ? ", supports gapless" : "");
Eric Laurent90fe31c2020-11-26 20:06:35 +01003977 if (profile == nullptr) {
3978 return AUDIO_OFFLOAD_NOT_SUPPORTED;
3979 }
3980 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD) != 0) {
3981 return AUDIO_OFFLOAD_GAPLESS_SUPPORTED;
3982 }
3983 return AUDIO_OFFLOAD_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07003984}
3985
Michael Chana94fbb22018-04-24 14:31:19 +10003986bool AudioPolicyManager::isDirectOutputSupported(const audio_config_base_t& config,
3987 const audio_attributes_t& attributes) {
3988 audio_output_flags_t output_flags = AUDIO_OUTPUT_FLAG_NONE;
François Gaffie58d4be52018-11-06 15:30:12 +01003989 audio_flags_to_audio_output_flags(attributes.flags, &output_flags);
Dorin Drimus9901eb02022-01-14 11:36:51 +00003990 DeviceVector outputDevices = mEngine->getOutputDevicesForAttributes(attributes);
3991 sp<IOProfile> profile = getProfileForOutput(outputDevices,
Michael Chana94fbb22018-04-24 14:31:19 +10003992 config.sample_rate,
3993 config.format,
3994 config.channel_mask,
3995 output_flags,
3996 true /* directOnly */);
3997 ALOGV("%s() profile %sfound with name: %s, "
3998 "sample rate: %u, format: 0x%x, channel_mask: 0x%x, output flags: 0x%x",
3999 __FUNCTION__, profile != 0 ? "" : "NOT ",
jiabin5740f082019-08-19 15:08:30 -07004000 (profile != 0 ? profile->getTagName().c_str() : "null"),
Michael Chana94fbb22018-04-24 14:31:19 +10004001 config.sample_rate, config.format, config.channel_mask, output_flags);
Dorin Drimusecc9f422022-03-09 17:57:40 +01004002
4003 // also try the MSD module if compatible profile not found
4004 if (profile == nullptr) {
4005 profile = getMsdProfileForOutput(outputDevices,
4006 config.sample_rate,
4007 config.format,
4008 config.channel_mask,
4009 output_flags,
4010 true /* directOnly */);
4011 ALOGV("%s() MSD profile %sfound with name: %s, "
4012 "sample rate: %u, format: 0x%x, channel_mask: 0x%x, output flags: 0x%x",
4013 __FUNCTION__, profile != 0 ? "" : "NOT ",
4014 (profile != 0 ? profile->getTagName().c_str() : "null"),
4015 config.sample_rate, config.format, config.channel_mask, output_flags);
4016 }
4017 return (profile != nullptr);
Michael Chana94fbb22018-04-24 14:31:19 +10004018}
4019
jiabin2b9d5a12021-12-10 01:06:29 +00004020bool AudioPolicyManager::isOffloadPossible(const audio_offload_info_t &offloadInfo,
4021 bool durationIgnored) {
4022 if (mMasterMono) {
4023 return false; // no offloading if mono is set.
4024 }
4025
4026 // Check if offload has been disabled
4027 if (property_get_bool("audio.offload.disable", false /* default_value */)) {
4028 ALOGV("%s: offload disabled by audio.offload.disable", __func__);
4029 return false;
4030 }
4031
4032 // Check if stream type is music, then only allow offload as of now.
4033 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
4034 {
4035 ALOGV("%s: stream_type != MUSIC, returning false", __func__);
4036 return false;
4037 }
4038
4039 //TODO: enable audio offloading with video when ready
4040 const bool allowOffloadWithVideo =
4041 property_get_bool("audio.offload.video", false /* default_value */);
4042 if (offloadInfo.has_video && !allowOffloadWithVideo) {
4043 ALOGV("%s: has_video == true, returning false", __func__);
4044 return false;
4045 }
4046
4047 //If duration is less than minimum value defined in property, return false
4048 const int min_duration_secs = property_get_int32(
4049 "audio.offload.min.duration.secs", -1 /* default_value */);
4050 if (!durationIgnored) {
4051 if (min_duration_secs >= 0) {
4052 if (offloadInfo.duration_us < min_duration_secs * 1000000LL) {
4053 ALOGV("%s: Offload denied by duration < audio.offload.min.duration.secs(=%d)",
4054 __func__, min_duration_secs);
4055 return false;
4056 }
4057 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
4058 ALOGV("%s: Offload denied by duration < default min(=%u)",
4059 __func__, OFFLOAD_DEFAULT_MIN_DURATION_SECS);
4060 return false;
4061 }
4062 }
4063
4064 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
4065 // creating an offloaded track and tearing it down immediately after start when audioflinger
4066 // detects there is an active non offloadable effect.
4067 // FIXME: We should check the audio session here but we do not have it in this context.
4068 // This may prevent offloading in rare situations where effects are left active by apps
4069 // in the background.
4070 if (mEffects.isNonOffloadableEffectEnabled()) {
4071 return false;
4072 }
4073
4074 return true;
4075}
4076
4077audio_direct_mode_t AudioPolicyManager::getDirectPlaybackSupport(const audio_attributes_t *attr,
4078 const audio_config_t *config) {
4079 audio_offload_info_t offloadInfo = AUDIO_INFO_INITIALIZER;
4080 offloadInfo.format = config->format;
4081 offloadInfo.sample_rate = config->sample_rate;
4082 offloadInfo.channel_mask = config->channel_mask;
4083 offloadInfo.stream_type = mEngine->getStreamTypeForAttributes(*attr);
4084 offloadInfo.has_video = false;
4085 offloadInfo.is_streaming = false;
4086 const bool offloadPossible = isOffloadPossible(offloadInfo, true /*durationIgnored*/);
4087
4088 audio_direct_mode_t directMode = AUDIO_DIRECT_NOT_SUPPORTED;
4089 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
4090 audio_flags_to_audio_output_flags(attr->flags, &flags);
4091 // only retain flags that will drive compressed offload or passthrough
4092 uint32_t relevantFlags = AUDIO_OUTPUT_FLAG_HW_AV_SYNC;
4093 if (offloadPossible) {
4094 relevantFlags |= AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD;
4095 }
4096 flags = (audio_output_flags_t)((flags & relevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
4097
Dorin Drimusfae3c642022-03-17 18:36:30 +01004098 DeviceVector engineOutputDevices = mEngine->getOutputDevicesForAttributes(*attr);
jiabin2b9d5a12021-12-10 01:06:29 +00004099 for (const auto& hwModule : mHwModules) {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004100 DeviceVector outputDevices = engineOutputDevices;
4101 // the MSD module checks for different conditions and output devices
4102 if (strcmp(hwModule->getName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0) {
4103 if (!msdHasPatchesToAllDevices(engineOutputDevices.toTypeAddrVector())) {
4104 continue;
4105 }
4106 outputDevices = getMsdAudioOutDevices();
4107 }
jiabin2b9d5a12021-12-10 01:06:29 +00004108 for (const auto& curProfile : hwModule->getOutputProfiles()) {
jiabinc8f7dfc2022-01-06 18:42:08 +00004109 if (!curProfile->isCompatibleProfile(outputDevices,
jiabin2b9d5a12021-12-10 01:06:29 +00004110 config->sample_rate, nullptr /*updatedSamplingRate*/,
4111 config->format, nullptr /*updatedFormat*/,
4112 config->channel_mask, nullptr /*updatedChannelMask*/,
4113 flags)) {
4114 continue;
4115 }
4116 // reject profiles not corresponding to a device currently available
4117 if (!mAvailableOutputDevices.containsAtLeastOne(curProfile->getSupportedDevices())) {
4118 continue;
4119 }
4120 if ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)
4121 != AUDIO_OUTPUT_FLAG_NONE) {
jiabinc6132d62022-01-01 07:36:31 +00004122 if ((directMode & AUDIO_DIRECT_OFFLOAD_GAPLESS_SUPPORTED)
jiabin2b9d5a12021-12-10 01:06:29 +00004123 != AUDIO_DIRECT_NOT_SUPPORTED) {
4124 // Already reports offload gapless supported. No need to report offload support.
4125 continue;
4126 }
4127 if ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD)
4128 != AUDIO_OUTPUT_FLAG_NONE) {
4129 // If offload gapless is reported, no need to report offload support.
4130 directMode = (audio_direct_mode_t) ((directMode &
4131 ~AUDIO_DIRECT_OFFLOAD_SUPPORTED) |
4132 AUDIO_DIRECT_OFFLOAD_GAPLESS_SUPPORTED);
4133 } else {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004134 directMode = (audio_direct_mode_t)(directMode | AUDIO_DIRECT_OFFLOAD_SUPPORTED);
jiabin2b9d5a12021-12-10 01:06:29 +00004135 }
4136 } else {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004137 directMode = (audio_direct_mode_t) (directMode | AUDIO_DIRECT_BITSTREAM_SUPPORTED);
jiabin2b9d5a12021-12-10 01:06:29 +00004138 }
4139 }
4140 }
4141 return directMode;
4142}
4143
Dorin Drimusf2196d82022-01-03 12:11:18 +01004144status_t AudioPolicyManager::getDirectProfilesForAttributes(const audio_attributes_t* attr,
4145 AudioProfileVector& audioProfilesVector) {
Dorin Drimus76e69572022-09-23 15:28:51 +00004146 if (mEffects.isNonOffloadableEffectEnabled()) {
4147 return OK;
4148 }
Dorin Drimusf2196d82022-01-03 12:11:18 +01004149 AudioDeviceTypeAddrVector devices;
Andy Hung6d23c0f2022-02-16 09:37:15 -08004150 status_t status = getDevicesForAttributes(*attr, &devices, false /* forVolume */);
Dorin Drimusf2196d82022-01-03 12:11:18 +01004151 if (status != OK) {
4152 return status;
4153 }
4154 ALOGV("%s: found %zu output devices for attributes.", __func__, devices.size());
4155 if (devices.empty()) {
4156 return OK; // no output devices for the attributes
4157 }
4158
4159 for (const auto& hwModule : mHwModules) {
Dorin Drimus94d94412022-02-02 09:05:02 +01004160 // the MSD module checks for different conditions
4161 if (strcmp(hwModule->getName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0) {
4162 continue;
4163 }
4164 for (const auto& outputProfile : hwModule->getOutputProfiles()) {
4165 if (!outputProfile->asAudioPort()->isDirectOutput()) {
Dorin Drimusf2196d82022-01-03 12:11:18 +01004166 continue;
4167 }
Dorin Drimus94d94412022-02-02 09:05:02 +01004168 // allow only profiles that support all the available and routed devices
4169 if (outputProfile->getSupportedDevices().getDevicesFromDeviceTypeAddrVec(devices).size()
Dorin Drimusf2196d82022-01-03 12:11:18 +01004170 != devices.size()) {
4171 continue;
4172 }
Dorin Drimus94d94412022-02-02 09:05:02 +01004173 audioProfilesVector.addAllValidProfiles(
4174 outputProfile->asAudioPort()->getAudioProfiles());
Dorin Drimusf2196d82022-01-03 12:11:18 +01004175 }
4176 }
Dorin Drimus94d94412022-02-02 09:05:02 +01004177
4178 // add the direct profiles from MSD if present and has audio patches to all the output(s)
4179 const auto& msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
4180 if (msdModule != nullptr) {
4181 if (msdHasPatchesToAllDevices(devices)) {
4182 ALOGV("%s: MSD audio patches set to all output devices.", __func__);
4183 for (const auto& outputProfile : msdModule->getOutputProfiles()) {
4184 if (!outputProfile->asAudioPort()->isDirectOutput()) {
4185 continue;
4186 }
4187 audioProfilesVector.addAllValidProfiles(
4188 outputProfile->asAudioPort()->getAudioProfiles());
4189 }
4190 } else {
4191 ALOGV("%s: MSD audio patches NOT set to all output devices.", __func__);
4192 }
4193 }
4194
Dorin Drimusf2196d82022-01-03 12:11:18 +01004195 return NO_ERROR;
4196}
4197
Eric Laurent6a94d692014-05-20 11:18:06 -07004198status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
4199 audio_port_type_t type,
4200 unsigned int *num_ports,
jiabin19cdba52020-11-24 11:28:58 -08004201 struct audio_port_v7 *ports,
Eric Laurent6a94d692014-05-20 11:18:06 -07004202 unsigned int *generation)
4203{
jiabin19cdba52020-11-24 11:28:58 -08004204 if (num_ports == nullptr || (*num_ports != 0 && ports == nullptr) ||
4205 generation == nullptr) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004206 return BAD_VALUE;
4207 }
4208 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
jiabin19cdba52020-11-24 11:28:58 -08004209 if (ports == nullptr) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004210 *num_ports = 0;
4211 }
4212
4213 size_t portsWritten = 0;
4214 size_t portsMax = *num_ports;
4215 *num_ports = 0;
4216 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07004217 // do not report devices with type AUDIO_DEVICE_IN_STUB or AUDIO_DEVICE_OUT_STUB
4218 // as they are used by stub HALs by convention
Eric Laurent6a94d692014-05-20 11:18:06 -07004219 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004220 for (const auto& dev : mAvailableOutputDevices) {
4221 if (dev->type() == AUDIO_DEVICE_OUT_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07004222 continue;
4223 }
4224 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004225 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07004226 }
4227 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07004228 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004229 }
4230 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004231 for (const auto& dev : mAvailableInputDevices) {
4232 if (dev->type() == AUDIO_DEVICE_IN_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07004233 continue;
4234 }
4235 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004236 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07004237 }
4238 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07004239 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004240 }
4241 }
4242 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
4243 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
4244 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
4245 mInputs[i]->toAudioPort(&ports[portsWritten++]);
4246 }
4247 *num_ports += mInputs.size();
4248 }
4249 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent84c70242014-06-23 08:46:27 -07004250 size_t numOutputs = 0;
4251 for (size_t i = 0; i < mOutputs.size(); i++) {
4252 if (!mOutputs[i]->isDuplicated()) {
4253 numOutputs++;
4254 if (portsWritten < portsMax) {
4255 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
4256 }
4257 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004258 }
Eric Laurent84c70242014-06-23 08:46:27 -07004259 *num_ports += numOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07004260 }
4261 }
4262 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07004263 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
Eric Laurent6a94d692014-05-20 11:18:06 -07004264 return NO_ERROR;
4265}
4266
Mikhail Naganov15f46712023-03-23 14:52:15 -07004267status_t AudioPolicyManager::listDeclaredDevicePorts(media::AudioPortRole role,
4268 std::vector<media::AudioPortFw>* _aidl_return) {
4269 auto pushPort = [&](const sp<DeviceDescriptor>& dev) -> status_t {
4270 audio_port_v7 port;
4271 dev->toAudioPort(&port);
4272 auto aidlPort = VALUE_OR_RETURN_STATUS(legacy2aidl_audio_port_v7_AudioPortFw(port));
4273 _aidl_return->push_back(std::move(aidlPort));
4274 return OK;
4275 };
4276
Mikhail Naganovb0fbc1b2023-04-28 13:06:32 -07004277 for (const auto& module : mHwModules) {
Mikhail Naganov15f46712023-03-23 14:52:15 -07004278 for (const auto& dev : module->getDeclaredDevices()) {
4279 if (role == media::AudioPortRole::NONE ||
4280 ((role == media::AudioPortRole::SOURCE)
4281 == audio_is_input_device(dev->type()))) {
4282 RETURN_STATUS_IF_ERROR(pushPort(dev));
4283 }
4284 }
4285 }
4286 return OK;
4287}
4288
jiabin19cdba52020-11-24 11:28:58 -08004289status_t AudioPolicyManager::getAudioPort(struct audio_port_v7 *port)
Eric Laurent6a94d692014-05-20 11:18:06 -07004290{
Eric Laurent99fcae42018-05-17 16:59:18 -07004291 if (port == nullptr || port->id == AUDIO_PORT_HANDLE_NONE) {
4292 return BAD_VALUE;
4293 }
4294 sp<DeviceDescriptor> dev = mAvailableOutputDevices.getDeviceFromId(port->id);
4295 if (dev != 0) {
4296 dev->toAudioPort(port);
4297 return NO_ERROR;
4298 }
4299 dev = mAvailableInputDevices.getDeviceFromId(port->id);
4300 if (dev != 0) {
4301 dev->toAudioPort(port);
4302 return NO_ERROR;
4303 }
4304 sp<SwAudioOutputDescriptor> out = mOutputs.getOutputFromId(port->id);
4305 if (out != 0) {
4306 out->toAudioPort(port);
4307 return NO_ERROR;
4308 }
4309 sp<AudioInputDescriptor> in = mInputs.getInputFromId(port->id);
4310 if (in != 0) {
4311 in->toAudioPort(port);
4312 return NO_ERROR;
4313 }
4314 return BAD_VALUE;
Eric Laurent6a94d692014-05-20 11:18:06 -07004315}
4316
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004317status_t AudioPolicyManager::createAudioPatch(const struct audio_patch *patch,
4318 audio_patch_handle_t *handle,
4319 uid_t uid)
Eric Laurent6a94d692014-05-20 11:18:06 -07004320{
François Gaffieafd4cea2019-11-18 15:50:22 +01004321 ALOGV("%s", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004322 if (handle == NULL || patch == NULL) {
4323 return BAD_VALUE;
4324 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004325 ALOGV("%s num sources %d num sinks %d", __func__, patch->num_sources, patch->num_sinks);
Mikhail Naganovac9858b2018-06-15 13:12:37 -07004326 if (!audio_patch_is_valid(patch)) {
Eric Laurent874c42872014-08-08 15:13:39 -07004327 return BAD_VALUE;
4328 }
4329 // only one source per audio patch supported for now
4330 if (patch->num_sources > 1) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004331 return INVALID_OPERATION;
4332 }
Eric Laurent874c42872014-08-08 15:13:39 -07004333 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004334 return INVALID_OPERATION;
4335 }
Eric Laurent874c42872014-08-08 15:13:39 -07004336 for (size_t i = 0; i < patch->num_sinks; i++) {
4337 if (patch->sinks[i].role != AUDIO_PORT_ROLE_SINK) {
4338 return INVALID_OPERATION;
4339 }
4340 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004341
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004342 sp<DeviceDescriptor> srcDevice = mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
4343 sp<DeviceDescriptor> sinkDevice = mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id);
4344 if (srcDevice == nullptr || sinkDevice == nullptr) {
4345 ALOGW("%s could not create patch, invalid sink and/or source device(s)", __func__);
4346 return BAD_VALUE;
4347 }
4348 ALOGV("%s between source %s and sink %s", __func__,
4349 srcDevice->toString().c_str(), sinkDevice->toString().c_str());
4350 audio_port_handle_t portId = PolicyAudioPort::getNextUniqueId();
4351 // Default attributes, default volume priority, not to infer with non raw audio patches.
4352 audio_attributes_t attributes = attributes_initializer(AUDIO_USAGE_MEDIA);
4353 const struct audio_port_config *source = &patch->sources[0];
4354 sp<SourceClientDescriptor> sourceDesc =
4355 new InternalSourceClientDescriptor(
4356 portId, uid, attributes, *source, srcDevice, sinkDevice,
4357 mEngine->getProductStrategyForAttributes(attributes), toVolumeSource(attributes));
4358
4359 status_t status =
4360 connectAudioSourceToSink(sourceDesc, sinkDevice, patch, *handle, uid, 0 /* delayMs */);
4361
4362 if (status != NO_ERROR) {
4363 return INVALID_OPERATION;
4364 }
4365 mAudioSources.add(portId, sourceDesc);
4366 return NO_ERROR;
4367}
4368
4369status_t AudioPolicyManager::connectAudioSourceToSink(
4370 const sp<SourceClientDescriptor>& sourceDesc, const sp<DeviceDescriptor> &sinkDevice,
4371 const struct audio_patch *patch,
4372 audio_patch_handle_t &handle,
4373 uid_t uid, uint32_t delayMs)
4374{
4375 status_t status = createAudioPatchInternal(patch, &handle, uid, delayMs, sourceDesc);
4376 if (status != NO_ERROR || mAudioPatches.indexOfKey(handle) < 0) {
4377 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
4378 return INVALID_OPERATION;
4379 }
4380 sourceDesc->connect(handle, sinkDevice);
4381 if (isMsdPatch(handle)) {
4382 return NO_ERROR;
4383 }
4384 // SW Bridge? (@todo: HW bridge, keep track of HwOutput for device selection "reconsideration")
4385 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
4386 ALOG_ASSERT(swOutput != nullptr, "%s: a swOutput shall always be associated", __func__);
4387 if (swOutput->getClient(sourceDesc->portId()) != nullptr) {
4388 ALOGW("%s source portId has already been attached to outputDesc", __func__);
4389 goto FailurePatchAdded;
4390 }
4391 status = swOutput->start();
4392 if (status != NO_ERROR) {
4393 goto FailureSourceAdded;
4394 }
4395 swOutput->addClient(sourceDesc);
4396 status = startSource(swOutput, sourceDesc, &delayMs);
4397 if (status != NO_ERROR) {
4398 ALOGW("%s failed to start source, error %d", __FUNCTION__, status);
4399 goto FailureSourceActive;
4400 }
4401 if (delayMs != 0) {
4402 usleep(delayMs * 1000);
4403 }
4404 return NO_ERROR;
4405
4406FailureSourceActive:
4407 swOutput->stop();
4408 releaseOutput(sourceDesc->portId());
4409FailureSourceAdded:
4410 sourceDesc->setSwOutput(nullptr);
4411FailurePatchAdded:
4412 releaseAudioPatchInternal(handle);
4413 return INVALID_OPERATION;
4414}
4415
4416status_t AudioPolicyManager::createAudioPatchInternal(const struct audio_patch *patch,
4417 audio_patch_handle_t *handle,
4418 uid_t uid, uint32_t delayMs,
4419 const sp<SourceClientDescriptor>& sourceDesc)
4420{
4421 ALOGV("%s num sources %d num sinks %d", __func__, patch->num_sources, patch->num_sinks);
Eric Laurent6a94d692014-05-20 11:18:06 -07004422 sp<AudioPatch> patchDesc;
4423 ssize_t index = mAudioPatches.indexOfKey(*handle);
4424
François Gaffieafd4cea2019-11-18 15:50:22 +01004425 ALOGV("%s source id %d role %d type %d", __func__, patch->sources[0].id,
4426 patch->sources[0].role,
4427 patch->sources[0].type);
Eric Laurent874c42872014-08-08 15:13:39 -07004428#if LOG_NDEBUG == 0
4429 for (size_t i = 0; i < patch->num_sinks; i++) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004430 ALOGV("%s sink %zu: id %d role %d type %d", __func__ ,i, patch->sinks[i].id,
4431 patch->sinks[i].role,
4432 patch->sinks[i].type);
Eric Laurent874c42872014-08-08 15:13:39 -07004433 }
4434#endif
Eric Laurent6a94d692014-05-20 11:18:06 -07004435
4436 if (index >= 0) {
4437 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01004438 ALOGV("%s mUidCached %d patchDesc->mUid %d uid %d",
4439 __func__, mUidCached, patchDesc->getUid(), uid);
4440 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004441 return INVALID_OPERATION;
4442 }
4443 } else {
Glenn Kastena13cde92016-03-28 15:26:02 -07004444 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07004445 }
4446
4447 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004448 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004449 if (outputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004450 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004451 return BAD_VALUE;
4452 }
Eric Laurent84c70242014-06-23 08:46:27 -07004453 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
4454 outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004455 if (patchDesc != 0) {
4456 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004457 ALOGV("%s source id differs for patch current id %d new id %d",
4458 __func__, patchDesc->mPatch.sources[0].id, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004459 return BAD_VALUE;
4460 }
4461 }
Eric Laurent874c42872014-08-08 15:13:39 -07004462 DeviceVector devices;
4463 for (size_t i = 0; i < patch->num_sinks; i++) {
4464 // Only support mix to devices connection
4465 // TODO add support for mix to mix connection
4466 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004467 ALOGV("%s source mix but sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07004468 return INVALID_OPERATION;
4469 }
4470 sp<DeviceDescriptor> devDesc =
4471 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
4472 if (devDesc == 0) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004473 ALOGV("%s out device not found for id %d", __func__, patch->sinks[i].id);
Eric Laurent874c42872014-08-08 15:13:39 -07004474 return BAD_VALUE;
4475 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004476
François Gaffie11d30102018-11-02 16:09:09 +01004477 if (!outputDesc->mProfile->isCompatibleProfile(DeviceVector(devDesc),
Eric Laurent874c42872014-08-08 15:13:39 -07004478 patch->sources[0].sample_rate,
François Gaffie53615e22015-03-19 09:24:12 +01004479 NULL, // updatedSamplingRate
4480 patch->sources[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07004481 NULL, // updatedFormat
François Gaffie53615e22015-03-19 09:24:12 +01004482 patch->sources[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07004483 NULL, // updatedChannelMask
François Gaffie53615e22015-03-19 09:24:12 +01004484 AUDIO_OUTPUT_FLAG_NONE /*FIXME*/)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004485 ALOGV("%s profile not supported for device %08x", __func__, devDesc->type());
Eric Laurent874c42872014-08-08 15:13:39 -07004486 return INVALID_OPERATION;
4487 }
4488 devices.add(devDesc);
4489 }
4490 if (devices.size() == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004491 return INVALID_OPERATION;
4492 }
Eric Laurent874c42872014-08-08 15:13:39 -07004493
Eric Laurent6a94d692014-05-20 11:18:06 -07004494 // TODO: reconfigure output format and channels here
François Gaffieafd4cea2019-11-18 15:50:22 +01004495 ALOGV("%s setting device %s on output %d",
4496 __func__, dumpDeviceTypes(devices.types()).c_str(), outputDesc->mIoHandle);
François Gaffie11d30102018-11-02 16:09:09 +01004497 setOutputDevices(outputDesc, devices, true, 0, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004498 index = mAudioPatches.indexOfKey(*handle);
4499 if (index >= 0) {
4500 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004501 ALOGW("%s setOutputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004502 }
4503 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01004504 patchDesc->setUid(uid);
4505 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004506 } else {
François Gaffieafd4cea2019-11-18 15:50:22 +01004507 ALOGW("%s setOutputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004508 return INVALID_OPERATION;
4509 }
4510 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
4511 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
4512 // input device to input mix connection
Eric Laurent874c42872014-08-08 15:13:39 -07004513 // only one sink supported when connecting an input device to a mix
4514 if (patch->num_sinks > 1) {
4515 return INVALID_OPERATION;
4516 }
François Gaffie53615e22015-03-19 09:24:12 +01004517 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004518 if (inputDesc == NULL) {
4519 return BAD_VALUE;
4520 }
4521 if (patchDesc != 0) {
4522 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
4523 return BAD_VALUE;
4524 }
4525 }
François Gaffie11d30102018-11-02 16:09:09 +01004526 sp<DeviceDescriptor> device =
Eric Laurent6a94d692014-05-20 11:18:06 -07004527 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01004528 if (device == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004529 return BAD_VALUE;
4530 }
4531
François Gaffie11d30102018-11-02 16:09:09 +01004532 if (!inputDesc->mProfile->isCompatibleProfile(DeviceVector(device),
Eric Laurent275e8e92014-11-30 15:14:47 -08004533 patch->sinks[0].sample_rate,
4534 NULL, /*updatedSampleRate*/
4535 patch->sinks[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07004536 NULL, /*updatedFormat*/
Eric Laurent275e8e92014-11-30 15:14:47 -08004537 patch->sinks[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07004538 NULL, /*updatedChannelMask*/
Eric Laurent275e8e92014-11-30 15:14:47 -08004539 // FIXME for the parameter type,
4540 // and the NONE
4541 (audio_output_flags_t)
Glenn Kasten6a8ab052014-07-24 14:08:35 -07004542 AUDIO_INPUT_FLAG_NONE)) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004543 return INVALID_OPERATION;
4544 }
4545 // TODO: reconfigure output format and channels here
François Gaffieafd4cea2019-11-18 15:50:22 +01004546 ALOGV("%s setting device %s on output %d", __func__,
François Gaffie11d30102018-11-02 16:09:09 +01004547 device->toString().c_str(), inputDesc->mIoHandle);
4548 setInputDevice(inputDesc->mIoHandle, device, true, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004549 index = mAudioPatches.indexOfKey(*handle);
4550 if (index >= 0) {
4551 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004552 ALOGW("%s setInputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004553 }
4554 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01004555 patchDesc->setUid(uid);
4556 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004557 } else {
François Gaffieafd4cea2019-11-18 15:50:22 +01004558 ALOGW("%s setInputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004559 return INVALID_OPERATION;
4560 }
4561 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
4562 // device to device connection
4563 if (patchDesc != 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07004564 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004565 return BAD_VALUE;
4566 }
4567 }
François Gaffie11d30102018-11-02 16:09:09 +01004568 sp<DeviceDescriptor> srcDevice =
Eric Laurent6a94d692014-05-20 11:18:06 -07004569 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01004570 if (srcDevice == 0) {
Eric Laurent58f8eb72014-09-12 16:19:41 -07004571 return BAD_VALUE;
4572 }
Eric Laurent874c42872014-08-08 15:13:39 -07004573
Eric Laurent6a94d692014-05-20 11:18:06 -07004574 //update source and sink with our own data as the data passed in the patch may
4575 // be incomplete.
François Gaffieafd4cea2019-11-18 15:50:22 +01004576 PatchBuilder patchBuilder;
4577 audio_port_config sourcePortConfig = {};
Dean Wheatley8bee85a2021-02-10 16:02:23 +11004578
4579 // if first sink is to MSD, establish single MSD patch
4580 if (getMsdAudioOutDevices().contains(
4581 mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id))) {
4582 ALOGV("%s patching to MSD", __FUNCTION__);
4583 patchBuilder = buildMsdPatch(false /*msdIsSource*/, srcDevice);
4584 goto installPatch;
4585 }
4586
François Gaffieafd4cea2019-11-18 15:50:22 +01004587 srcDevice->toAudioPortConfig(&sourcePortConfig, &patch->sources[0]);
4588 patchBuilder.addSource(sourcePortConfig);
Eric Laurent6a94d692014-05-20 11:18:06 -07004589
Eric Laurent874c42872014-08-08 15:13:39 -07004590 for (size_t i = 0; i < patch->num_sinks; i++) {
4591 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004592 ALOGV("%s source device but one sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07004593 return INVALID_OPERATION;
4594 }
François Gaffie11d30102018-11-02 16:09:09 +01004595 sp<DeviceDescriptor> sinkDevice =
Eric Laurent874c42872014-08-08 15:13:39 -07004596 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
François Gaffie11d30102018-11-02 16:09:09 +01004597 if (sinkDevice == 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07004598 return BAD_VALUE;
4599 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004600 audio_port_config sinkPortConfig = {};
4601 sinkDevice->toAudioPortConfig(&sinkPortConfig, &patch->sinks[i]);
4602 patchBuilder.addSink(sinkPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07004603
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004604 // Whatever Sw or Hw bridge, we do attach an SwOutput to an Audio Source for
4605 // volume management purpose (tracking activity)
4606 // In case of Hw bridge, it is a Work Around. The mixPort used is the one declared
4607 // in config XML to reach the sink so that is can be declared as available.
4608 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurent78b07302022-10-07 16:20:34 +02004609 sp<SwAudioOutputDescriptor> outputDesc;
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004610 if (!sourceDesc->isInternal()) {
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004611 // take care of dynamic routing for SwOutput selection,
4612 audio_attributes_t attributes = sourceDesc->attributes();
4613 audio_stream_type_t stream = sourceDesc->stream();
4614 audio_attributes_t resultAttr;
4615 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
4616 config.sample_rate = sourceDesc->config().sample_rate;
4617 config.channel_mask = sourceDesc->config().channel_mask;
4618 config.format = sourceDesc->config().format;
4619 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
4620 audio_port_handle_t selectedDeviceId = AUDIO_PORT_HANDLE_NONE;
4621 bool isRequestedDeviceForExclusiveUse = false;
4622 output_type_t outputType;
Eric Laurentb0a7bc92022-04-05 15:06:08 +02004623 bool isSpatialized;
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004624 getOutputForAttrInt(&resultAttr, &output, AUDIO_SESSION_NONE, &attributes,
4625 &stream, sourceDesc->uid(), &config, &flags,
4626 &selectedDeviceId, &isRequestedDeviceForExclusiveUse,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02004627 nullptr, &outputType, &isSpatialized);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004628 if (output == AUDIO_IO_HANDLE_NONE) {
4629 ALOGV("%s no output for device %s",
4630 __FUNCTION__, sinkDevice->toString().c_str());
4631 return INVALID_OPERATION;
4632 }
4633 outputDesc = mOutputs.valueFor(output);
4634 if (outputDesc->isDuplicated()) {
4635 ALOGE("%s output is duplicated", __func__);
4636 return INVALID_OPERATION;
4637 }
François Gaffie1765c5b2022-04-26 12:48:49 +02004638 bool closeOutput = outputDesc->mDirectOpenCount != 0;
4639 sourceDesc->setSwOutput(outputDesc, closeOutput);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004640 } else {
4641 // Same for "raw patches" aka created from createAudioPatch API
4642 SortedVector<audio_io_handle_t> outputs =
4643 getOutputsForDevices(DeviceVector(sinkDevice), mOutputs);
4644 // if the sink device is reachable via an opened output stream, request to
4645 // go via this output stream by adding a second source to the patch
4646 // description
4647 output = selectOutput(outputs);
4648 if (output == AUDIO_IO_HANDLE_NONE) {
4649 ALOGE("%s no output available for internal patch sink", __func__);
4650 return INVALID_OPERATION;
4651 }
4652 outputDesc = mOutputs.valueFor(output);
4653 if (outputDesc->isDuplicated()) {
4654 ALOGV("%s output for device %s is duplicated",
4655 __func__, sinkDevice->toString().c_str());
4656 return INVALID_OPERATION;
4657 }
François Gaffie1765c5b2022-04-26 12:48:49 +02004658 sourceDesc->setSwOutput(outputDesc, /* closeOutput= */ false);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004659 }
Eric Laurent3bcf8592015-04-03 12:13:24 -07004660 // create a software bridge in PatchPanel if:
Scott Randolphf3172402018-01-23 17:06:53 -08004661 // - source and sink devices are on different HW modules OR
Eric Laurent3bcf8592015-04-03 12:13:24 -07004662 // - audio HAL version is < 3.0
Francois Gaffie99896da2018-04-09 11:05:33 +02004663 // - audio HAL version is >= 3.0 but no route has been declared between devices
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004664 // - called from startAudioSource (aka sourceDesc is not internal) and source device
4665 // does not have a gain controller
François Gaffie11d30102018-11-02 16:09:09 +01004666 if (!srcDevice->hasSameHwModuleAs(sinkDevice) ||
4667 (srcDevice->getModuleVersionMajor() < 3) ||
François Gaffieafd4cea2019-11-18 15:50:22 +01004668 !srcDevice->getModule()->supportsPatch(srcDevice, sinkDevice) ||
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004669 (!sourceDesc->isInternal() &&
François Gaffieafd4cea2019-11-18 15:50:22 +01004670 srcDevice->getAudioPort()->getGains().size() == 0)) {
Eric Laurent3bcf8592015-04-03 12:13:24 -07004671 // support only one sink device for now to simplify output selection logic
Eric Laurent874c42872014-08-08 15:13:39 -07004672 if (patch->num_sinks > 1) {
Eric Laurent83b88082014-06-20 18:31:16 -07004673 return INVALID_OPERATION;
4674 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004675 sourceDesc->setUseSwBridge();
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004676 if (outputDesc != nullptr) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004677 audio_port_config srcMixPortConfig = {};
Ytai Ben-Tsvic9d2a912021-11-22 16:43:09 -08004678 outputDesc->toAudioPortConfig(&srcMixPortConfig, nullptr);
François Gaffieafd4cea2019-11-18 15:50:22 +01004679 // for volume control, we may need a valid stream
Eric Laurent78b07302022-10-07 16:20:34 +02004680 srcMixPortConfig.ext.mix.usecase.stream =
4681 (!sourceDesc->isInternal() || isCallTxAudioSource(sourceDesc)) ?
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004682 mEngine->getStreamTypeForAttributes(sourceDesc->attributes()) :
4683 AUDIO_STREAM_PATCH;
François Gaffieafd4cea2019-11-18 15:50:22 +01004684 patchBuilder.addSource(srcMixPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07004685 }
Eric Laurent83b88082014-06-20 18:31:16 -07004686 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004687 }
4688 // TODO: check from routing capabilities in config file and other conflicting patches
4689
Dean Wheatley8bee85a2021-02-10 16:02:23 +11004690installPatch:
François Gaffieafd4cea2019-11-18 15:50:22 +01004691 status_t status = installPatch(
4692 __func__, index, handle, patchBuilder.patch(), delayMs, uid, &patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07004693 if (status != NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004694 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
Eric Laurent6a94d692014-05-20 11:18:06 -07004695 return INVALID_OPERATION;
4696 }
4697 } else {
4698 return BAD_VALUE;
4699 }
4700 } else {
4701 return BAD_VALUE;
4702 }
4703 return NO_ERROR;
4704}
4705
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004706status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle, uid_t uid)
Eric Laurent6a94d692014-05-20 11:18:06 -07004707{
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004708 ALOGV("%s patch %d", __func__, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004709 ssize_t index = mAudioPatches.indexOfKey(handle);
4710
4711 if (index < 0) {
4712 return BAD_VALUE;
4713 }
4714 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01004715 ALOGV("%s() mUidCached %d patchDesc->mUid %d uid %d",
4716 __func__, mUidCached, patchDesc->getUid(), uid);
4717 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004718 return INVALID_OPERATION;
4719 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004720 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
4721 for (size_t i = 0; i < mAudioSources.size(); i++) {
4722 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
4723 if (sourceDesc != nullptr && sourceDesc->getPatchHandle() == handle) {
4724 portId = sourceDesc->portId();
4725 break;
4726 }
4727 }
4728 return portId != AUDIO_PORT_HANDLE_NONE ?
4729 stopAudioSource(portId) : releaseAudioPatchInternal(handle);
François Gaffieafd4cea2019-11-18 15:50:22 +01004730}
Eric Laurent6a94d692014-05-20 11:18:06 -07004731
François Gaffieafd4cea2019-11-18 15:50:22 +01004732status_t AudioPolicyManager::releaseAudioPatchInternal(audio_patch_handle_t handle,
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004733 uint32_t delayMs,
4734 const sp<SourceClientDescriptor>& sourceDesc)
François Gaffieafd4cea2019-11-18 15:50:22 +01004735{
4736 ALOGV("%s patch %d", __func__, handle);
4737 if (mAudioPatches.indexOfKey(handle) < 0) {
4738 ALOGE("%s: no patch found with handle=%d", __func__, handle);
4739 return BAD_VALUE;
4740 }
4741 sp<AudioPatch> patchDesc = mAudioPatches.valueFor(handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004742 struct audio_patch *patch = &patchDesc->mPatch;
François Gaffieafd4cea2019-11-18 15:50:22 +01004743 patchDesc->setUid(mUidCached);
Eric Laurent6a94d692014-05-20 11:18:06 -07004744 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004745 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004746 if (outputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004747 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004748 return BAD_VALUE;
4749 }
4750
François Gaffie11d30102018-11-02 16:09:09 +01004751 setOutputDevices(outputDesc,
4752 getNewOutputDevices(outputDesc, true /*fromCache*/),
4753 true,
4754 0,
4755 NULL);
Eric Laurent6a94d692014-05-20 11:18:06 -07004756 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
4757 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
François Gaffie53615e22015-03-19 09:24:12 +01004758 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004759 if (inputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004760 ALOGV("%s input not found for id %d", __func__, patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004761 return BAD_VALUE;
4762 }
4763 setInputDevice(inputDesc->mIoHandle,
Eric Laurentfb66dd92016-01-28 18:32:03 -08004764 getNewInputDevice(inputDesc),
Eric Laurent6a94d692014-05-20 11:18:06 -07004765 true,
4766 NULL);
4767 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004768 status_t status =
4769 mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
4770 ALOGV("%s patch panel returned %d patchHandle %d",
4771 __func__, status, patchDesc->getAfHandle());
4772 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004773 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004774 mpClientInterface->onAudioPatchListUpdate();
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004775 // SW or HW Bridge
4776 sp<SwAudioOutputDescriptor> outputDesc = nullptr;
4777 audio_patch_handle_t patchHandle = AUDIO_PATCH_HANDLE_NONE;
Francois Gaffie7feb8542020-04-06 17:39:47 +02004778 if (patch->num_sources > 1 && patch->sources[1].type == AUDIO_PORT_TYPE_MIX) {
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004779 outputDesc = mOutputs.getOutputFromId(patch->sources[1].id);
4780 } else if (patch->num_sources == 1 && sourceDesc != nullptr) {
4781 outputDesc = sourceDesc->swOutput().promote();
4782 }
4783 if (outputDesc == nullptr) {
4784 ALOGW("%s no output for id %d", __func__, patch->sources[0].id);
4785 // releaseOutput has already called closeOutput in case of direct output
4786 return NO_ERROR;
4787 }
François Gaffie1765c5b2022-04-26 12:48:49 +02004788 patchHandle = outputDesc->getPatchHandle();
4789 // When a Sw bridge is released, the mixer used by this bridge will release its
4790 // patch at AudioFlinger side. Hence, the mixer audio patch must be recreated
4791 // Reuse patch handle to force audio flinger removing initial mixer patch removal
4792 // updating hal patch handle (prevent leaks).
4793 // While using a HwBridge, force reconsidering device only if not reusing an existing
4794 // output and no more activity on output (will force to close).
4795 bool force = sourceDesc->useSwBridge() ||
4796 (sourceDesc->canCloseOutput() && !outputDesc->isActive());
4797 // APM pattern is to have always outputs opened / patch realized for reachable devices.
4798 // Update device may result to NONE (empty), coupled with force, it releases the patch.
4799 // Reconsider device only for cases:
4800 // 1 / Active Output
4801 // 2 / Inactive Output previously hosting HwBridge
4802 // 3 / Inactive Output previously hosting SwBridge that can be closed.
4803 bool updateDevice = outputDesc->isActive() || !sourceDesc->useSwBridge() ||
4804 sourceDesc->canCloseOutput();
4805 setOutputDevices(outputDesc,
4806 updateDevice ? getNewOutputDevices(outputDesc, true /*fromCache*/) :
4807 outputDesc->devices(),
4808 force,
4809 0,
4810 patchHandle == AUDIO_PATCH_HANDLE_NONE ? nullptr : &patchHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004811 } else {
4812 return BAD_VALUE;
4813 }
4814 } else {
4815 return BAD_VALUE;
4816 }
4817 return NO_ERROR;
4818}
4819
4820status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
4821 struct audio_patch *patches,
4822 unsigned int *generation)
4823{
François Gaffie53615e22015-03-19 09:24:12 +01004824 if (generation == NULL) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004825 return BAD_VALUE;
4826 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004827 *generation = curAudioPortGeneration();
François Gaffie53615e22015-03-19 09:24:12 +01004828 return mAudioPatches.listAudioPatches(num_patches, patches);
Eric Laurent6a94d692014-05-20 11:18:06 -07004829}
4830
Eric Laurente1715a42014-05-20 11:30:42 -07004831status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07004832{
Eric Laurente1715a42014-05-20 11:30:42 -07004833 ALOGV("setAudioPortConfig()");
4834
4835 if (config == NULL) {
4836 return BAD_VALUE;
4837 }
4838 ALOGV("setAudioPortConfig() on port handle %d", config->id);
4839 // Only support gain configuration for now
Eric Laurenta121f902014-06-03 13:32:54 -07004840 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
4841 return INVALID_OPERATION;
Eric Laurente1715a42014-05-20 11:30:42 -07004842 }
4843
Eric Laurenta121f902014-06-03 13:32:54 -07004844 sp<AudioPortConfig> audioPortConfig;
Eric Laurente1715a42014-05-20 11:30:42 -07004845 if (config->type == AUDIO_PORT_TYPE_MIX) {
4846 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004847 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07004848 if (outputDesc == NULL) {
4849 return BAD_VALUE;
4850 }
Eric Laurent84c70242014-06-23 08:46:27 -07004851 ALOG_ASSERT(!outputDesc->isDuplicated(),
4852 "setAudioPortConfig() called on duplicated output %d",
4853 outputDesc->mIoHandle);
Eric Laurenta121f902014-06-03 13:32:54 -07004854 audioPortConfig = outputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07004855 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
François Gaffie53615e22015-03-19 09:24:12 +01004856 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07004857 if (inputDesc == NULL) {
4858 return BAD_VALUE;
4859 }
Eric Laurenta121f902014-06-03 13:32:54 -07004860 audioPortConfig = inputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07004861 } else {
4862 return BAD_VALUE;
4863 }
4864 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
4865 sp<DeviceDescriptor> deviceDesc;
4866 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
4867 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
4868 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
4869 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
4870 } else {
4871 return BAD_VALUE;
4872 }
4873 if (deviceDesc == NULL) {
4874 return BAD_VALUE;
4875 }
Eric Laurenta121f902014-06-03 13:32:54 -07004876 audioPortConfig = deviceDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07004877 } else {
4878 return BAD_VALUE;
4879 }
4880
Mikhail Naganov7be71d22018-05-23 16:51:46 -07004881 struct audio_port_config backupConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07004882 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
4883 if (status == NO_ERROR) {
Mikhail Naganov7be71d22018-05-23 16:51:46 -07004884 struct audio_port_config newConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07004885 audioPortConfig->toAudioPortConfig(&newConfig, config);
4886 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
Eric Laurente1715a42014-05-20 11:30:42 -07004887 }
Eric Laurenta121f902014-06-03 13:32:54 -07004888 if (status != NO_ERROR) {
4889 audioPortConfig->applyAudioPortConfig(&backupConfig);
Eric Laurente1715a42014-05-20 11:30:42 -07004890 }
Eric Laurente1715a42014-05-20 11:30:42 -07004891
4892 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07004893}
4894
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004895void AudioPolicyManager::releaseResourcesForUid(uid_t uid)
4896{
Eric Laurentd60560a2015-04-10 11:31:20 -07004897 clearAudioSources(uid);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004898 clearAudioPatches(uid);
4899 clearSessionRoutes(uid);
4900}
4901
Eric Laurent6a94d692014-05-20 11:18:06 -07004902void AudioPolicyManager::clearAudioPatches(uid_t uid)
4903{
Eric Laurent0add0fd2014-12-04 18:58:14 -08004904 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004905 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
François Gaffieafd4cea2019-11-18 15:50:22 +01004906 if (patchDesc->getUid() == uid) {
Eric Laurent0add0fd2014-12-04 18:58:14 -08004907 releaseAudioPatch(mAudioPatches.keyAt(i), uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07004908 }
4909 }
4910}
4911
François Gaffiec005e562018-11-06 15:04:49 +01004912void AudioPolicyManager::checkStrategyRoute(product_strategy_t ps, audio_io_handle_t ouptutToSkip)
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004913{
François Gaffiec005e562018-11-06 15:04:49 +01004914 // Take the first attributes following the product strategy as it is used to retrieve the routed
4915 // device. All attributes wihin a strategy follows the same "routing strategy"
4916 auto attributes = mEngine->getAllAttributesForProductStrategy(ps).front();
4917 DeviceVector devices = mEngine->getOutputDevicesForAttributes(attributes, nullptr, false);
François Gaffie11d30102018-11-02 16:09:09 +01004918 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004919 for (size_t j = 0; j < mOutputs.size(); j++) {
4920 if (mOutputs.keyAt(j) == ouptutToSkip) {
4921 continue;
4922 }
4923 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(j);
François Gaffiec005e562018-11-06 15:04:49 +01004924 if (!outputDesc->isStrategyActive(ps)) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004925 continue;
4926 }
4927 // If the default device for this strategy is on another output mix,
4928 // invalidate all tracks in this strategy to force re connection.
4929 // Otherwise select new device on the output mix.
4930 if (outputs.indexOf(mOutputs.keyAt(j)) < 0) {
François Gaffiec005e562018-11-06 15:04:49 +01004931 for (auto stream : mEngine->getStreamTypesForProductStrategy(ps)) {
4932 mpClientInterface->invalidateStream(stream);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004933 }
4934 } else {
François Gaffie11d30102018-11-02 16:09:09 +01004935 setOutputDevices(
4936 outputDesc, getNewOutputDevices(outputDesc, false /*fromCache*/), false);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004937 }
4938 }
4939}
4940
4941void AudioPolicyManager::clearSessionRoutes(uid_t uid)
4942{
4943 // remove output routes associated with this uid
François Gaffiec005e562018-11-06 15:04:49 +01004944 std::vector<product_strategy_t> affectedStrategies;
Eric Laurent97ac8712018-07-27 18:59:02 -07004945 for (size_t i = 0; i < mOutputs.size(); i++) {
4946 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07004947 for (const auto& client : outputDesc->getClientIterable()) {
4948 if (client->hasPreferredDevice() && client->uid() == uid) {
4949 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
François Gaffiec005e562018-11-06 15:04:49 +01004950 auto clientStrategy = client->strategy();
4951 if (std::find(begin(affectedStrategies), end(affectedStrategies), clientStrategy) !=
4952 end(affectedStrategies)) {
4953 continue;
4954 }
4955 affectedStrategies.push_back(client->strategy());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004956 }
4957 }
4958 }
4959 // reroute outputs if necessary
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004960 for (const auto& strategy : affectedStrategies) {
4961 checkStrategyRoute(strategy, AUDIO_IO_HANDLE_NONE);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004962 }
4963
4964 // remove input routes associated with this uid
4965 SortedVector<audio_source_t> affectedSources;
Eric Laurent97ac8712018-07-27 18:59:02 -07004966 for (size_t i = 0; i < mInputs.size(); i++) {
4967 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07004968 for (const auto& client : inputDesc->getClientIterable()) {
4969 if (client->hasPreferredDevice() && client->uid() == uid) {
4970 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
4971 affectedSources.add(client->source());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004972 }
4973 }
4974 }
4975 // reroute inputs if necessary
4976 SortedVector<audio_io_handle_t> inputsToClose;
4977 for (size_t i = 0; i < mInputs.size(); i++) {
4978 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Eric Laurent4eb58f12018-12-07 16:41:02 -08004979 if (affectedSources.indexOf(inputDesc->source()) >= 0) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004980 inputsToClose.add(inputDesc->mIoHandle);
4981 }
4982 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004983 for (const auto& input : inputsToClose) {
4984 closeInput(input);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004985 }
4986}
4987
Eric Laurentd60560a2015-04-10 11:31:20 -07004988void AudioPolicyManager::clearAudioSources(uid_t uid)
4989{
4990 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004991 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
4992 if (sourceDesc->uid() == uid) {
Eric Laurentd60560a2015-04-10 11:31:20 -07004993 stopAudioSource(mAudioSources.keyAt(i));
4994 }
4995 }
4996}
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004997
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07004998status_t AudioPolicyManager::acquireSoundTriggerSession(audio_session_t *session,
4999 audio_io_handle_t *ioHandle,
5000 audio_devices_t *device)
5001{
Glenn Kastenf0c6d7d2016-02-26 10:44:04 -08005002 *session = (audio_session_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
5003 *ioHandle = (audio_io_handle_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
Francois Gaffie716e1432019-01-14 16:58:59 +01005004 audio_attributes_t attr = { .source = AUDIO_SOURCE_HOTWORD };
François Gaffiec005e562018-11-06 15:04:49 +01005005 *device = mEngine->getInputDeviceForAttributes(attr)->type();
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005006
François Gaffiedf372692015-03-19 10:43:27 +01005007 return mSoundTriggerSessions.acquireSession(*session, *ioHandle);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005008}
5009
Eric Laurentd60560a2015-04-10 11:31:20 -07005010status_t AudioPolicyManager::startAudioSource(const struct audio_port_config *source,
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005011 const audio_attributes_t *attributes,
5012 audio_port_handle_t *portId,
5013 uid_t uid)
Eric Laurent554a2772015-04-10 11:29:24 -07005014{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005015 ALOGV("%s", __FUNCTION__);
5016 *portId = AUDIO_PORT_HANDLE_NONE;
5017
5018 if (source == NULL || attributes == NULL || portId == NULL) {
5019 ALOGW("%s invalid argument: source %p attributes %p handle %p",
5020 __FUNCTION__, source, attributes, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005021 return BAD_VALUE;
5022 }
5023
Eric Laurentd60560a2015-04-10 11:31:20 -07005024 if (source->role != AUDIO_PORT_ROLE_SOURCE ||
5025 source->type != AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005026 ALOGW("%s INVALID_OPERATION source->role %d source->type %d",
5027 __FUNCTION__, source->role, source->type);
Eric Laurentd60560a2015-04-10 11:31:20 -07005028 return INVALID_OPERATION;
5029 }
5030
François Gaffie11d30102018-11-02 16:09:09 +01005031 sp<DeviceDescriptor> srcDevice =
Eric Laurentd60560a2015-04-10 11:31:20 -07005032 mAvailableInputDevices.getDevice(source->ext.device.type,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005033 String8(source->ext.device.address),
5034 AUDIO_FORMAT_DEFAULT);
François Gaffie11d30102018-11-02 16:09:09 +01005035 if (srcDevice == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005036 ALOGW("%s source->ext.device.type %08x not found", __FUNCTION__, source->ext.device.type);
Eric Laurentd60560a2015-04-10 11:31:20 -07005037 return BAD_VALUE;
5038 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005039
jiabin4ef93452019-09-10 14:29:54 -07005040 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurentd60560a2015-04-10 11:31:20 -07005041
François Gaffieaaac0fd2018-11-22 17:56:39 +01005042 sp<SourceClientDescriptor> sourceDesc =
François Gaffieafd4cea2019-11-18 15:50:22 +01005043 new SourceClientDescriptor(*portId, uid, *attributes, *source, srcDevice,
François Gaffieaaac0fd2018-11-22 17:56:39 +01005044 mEngine->getStreamTypeForAttributes(*attributes),
5045 mEngine->getProductStrategyForAttributes(*attributes),
5046 toVolumeSource(*attributes));
Eric Laurentd60560a2015-04-10 11:31:20 -07005047
5048 status_t status = connectAudioSource(sourceDesc);
5049 if (status == NO_ERROR) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005050 mAudioSources.add(*portId, sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07005051 }
5052 return status;
5053}
5054
Francois Gaffie601801d2021-06-22 13:27:39 +02005055sp<SourceClientDescriptor> AudioPolicyManager::startAudioSourceInternal(
5056 const struct audio_port_config *source, const audio_attributes_t *attributes, uid_t uid)
5057{
5058 ALOGV("%s", __FUNCTION__);
5059 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
5060
5061 status_t status = startAudioSource(source, attributes, &portId, uid);
5062 ALOGE_IF(status != OK, "%s: failed to start audio source (%d)", __func__, status);
5063 return mAudioSources.valueFor(portId);
5064}
5065
5066
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005067status_t AudioPolicyManager::connectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07005068{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005069 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->portId());
Eric Laurentd60560a2015-04-10 11:31:20 -07005070
5071 // make sure we only have one patch per source.
5072 disconnectAudioSource(sourceDesc);
5073
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005074 audio_attributes_t attributes = sourceDesc->attributes();
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005075 // May the device (dynamic) have been disconnected/reconnected, id has changed.
5076 sp<DeviceDescriptor> srcDevice = mAvailableInputDevices.getDevice(
5077 sourceDesc->srcDevice()->type(),
5078 String8(sourceDesc->srcDevice()->address().c_str()),
5079 AUDIO_FORMAT_DEFAULT);
François Gaffiec005e562018-11-06 15:04:49 +01005080 DeviceVector sinkDevices =
Francois Gaffieff1eb522020-05-06 18:37:04 +02005081 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false /*fromCache*/);
François Gaffiec005e562018-11-06 15:04:49 +01005082 ALOG_ASSERT(!sinkDevices.isEmpty(), "connectAudioSource(): no device found for attributes");
François Gaffie11d30102018-11-02 16:09:09 +01005083 sp<DeviceDescriptor> sinkDevice = sinkDevices.itemAt(0);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005084 if (!mAvailableOutputDevices.contains(sinkDevice)) {
5085 ALOGE("%s Device %s not available", __func__, sinkDevice->toString().c_str());
5086 return INVALID_OPERATION;
5087 }
François Gaffieafd4cea2019-11-18 15:50:22 +01005088 PatchBuilder patchBuilder;
5089 patchBuilder.addSink(sinkDevice).addSource(srcDevice);
5090 audio_patch_handle_t handle = AUDIO_PATCH_HANDLE_NONE;
François Gaffieafd4cea2019-11-18 15:50:22 +01005091
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005092 return connectAudioSourceToSink(
5093 sourceDesc, sinkDevice, patchBuilder.patch(), handle, mUidCached, 0 /*delayMs*/);
Eric Laurent554a2772015-04-10 11:29:24 -07005094}
5095
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005096status_t AudioPolicyManager::stopAudioSource(audio_port_handle_t portId)
Eric Laurent554a2772015-04-10 11:29:24 -07005097{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005098 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueFor(portId);
5099 ALOGV("%s port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005100 if (sourceDesc == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005101 ALOGW("%s unknown source for port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005102 return BAD_VALUE;
5103 }
5104 status_t status = disconnectAudioSource(sourceDesc);
5105
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005106 mAudioSources.removeItem(portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005107 return status;
5108}
5109
Andy Hung2ddee192015-12-18 17:34:44 -08005110status_t AudioPolicyManager::setMasterMono(bool mono)
5111{
5112 if (mMasterMono == mono) {
5113 return NO_ERROR;
5114 }
5115 mMasterMono = mono;
5116 // if enabling mono we close all offloaded devices, which will invalidate the
5117 // corresponding AudioTrack. The AudioTrack client/MediaPlayer is responsible
5118 // for recreating the new AudioTrack as non-offloaded PCM.
5119 //
5120 // If disabling mono, we leave all tracks as is: we don't know which clients
5121 // and tracks are able to be recreated as offloaded. The next "song" should
5122 // play back offloaded.
5123 if (mMasterMono) {
5124 Vector<audio_io_handle_t> offloaded;
5125 for (size_t i = 0; i < mOutputs.size(); ++i) {
5126 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
5127 if (desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
5128 offloaded.push(desc->mIoHandle);
5129 }
5130 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005131 for (const auto& handle : offloaded) {
5132 closeOutput(handle);
Andy Hung2ddee192015-12-18 17:34:44 -08005133 }
5134 }
5135 // update master mono for all remaining outputs
5136 for (size_t i = 0; i < mOutputs.size(); ++i) {
5137 updateMono(mOutputs.keyAt(i));
5138 }
5139 return NO_ERROR;
5140}
5141
5142status_t AudioPolicyManager::getMasterMono(bool *mono)
5143{
5144 *mono = mMasterMono;
5145 return NO_ERROR;
5146}
5147
Eric Laurentac9cef52017-06-09 15:46:26 -07005148float AudioPolicyManager::getStreamVolumeDB(
5149 audio_stream_type_t stream, int index, audio_devices_t device)
5150{
jiabin9a3361e2019-10-01 09:38:30 -07005151 return computeVolume(getVolumeCurves(stream), toVolumeSource(stream), index, {device});
Eric Laurentac9cef52017-06-09 15:46:26 -07005152}
5153
jiabin81772902018-04-02 17:52:27 -07005154status_t AudioPolicyManager::getSurroundFormats(unsigned int *numSurroundFormats,
5155 audio_format_t *surroundFormats,
Kriti Dang6537def2021-03-02 13:46:59 +01005156 bool *surroundFormatsEnabled)
jiabin81772902018-04-02 17:52:27 -07005157{
Kriti Dang6537def2021-03-02 13:46:59 +01005158 if (numSurroundFormats == nullptr || (*numSurroundFormats != 0 &&
5159 (surroundFormats == nullptr || surroundFormatsEnabled == nullptr))) {
jiabin81772902018-04-02 17:52:27 -07005160 return BAD_VALUE;
5161 }
Kriti Dang6537def2021-03-02 13:46:59 +01005162 ALOGV("%s() numSurroundFormats %d surroundFormats %p surroundFormatsEnabled %p",
5163 __func__, *numSurroundFormats, surroundFormats, surroundFormatsEnabled);
jiabin81772902018-04-02 17:52:27 -07005164
5165 size_t formatsWritten = 0;
5166 size_t formatsMax = *numSurroundFormats;
Kriti Dangef6be8f2020-11-05 11:58:19 +01005167
Mikhail Naganovb0fbc1b2023-04-28 13:06:32 -07005168 *numSurroundFormats = mConfig->getSurroundFormats().size();
Mikhail Naganov100f0122018-11-29 11:22:16 -08005169 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
5170 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Mikhail Naganovb0fbc1b2023-04-28 13:06:32 -07005171 for (const auto& format: mConfig->getSurroundFormats()) {
jiabin81772902018-04-02 17:52:27 -07005172 if (formatsWritten < formatsMax) {
Kriti Dang6537def2021-03-02 13:46:59 +01005173 surroundFormats[formatsWritten] = format.first;
Mikhail Naganov100f0122018-11-29 11:22:16 -08005174 bool formatEnabled = true;
5175 switch (forceUse) {
5176 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL:
Kriti Dang6537def2021-03-02 13:46:59 +01005177 formatEnabled = mManualSurroundFormats.count(format.first) != 0;
Mikhail Naganov100f0122018-11-29 11:22:16 -08005178 break;
5179 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER:
5180 formatEnabled = false;
5181 break;
5182 default: // AUTO or ALWAYS => true
5183 break;
jiabin81772902018-04-02 17:52:27 -07005184 }
5185 surroundFormatsEnabled[formatsWritten++] = formatEnabled;
5186 }
jiabin81772902018-04-02 17:52:27 -07005187 }
5188 return NO_ERROR;
5189}
5190
Kriti Dang6537def2021-03-02 13:46:59 +01005191status_t AudioPolicyManager::getReportedSurroundFormats(unsigned int *numSurroundFormats,
5192 audio_format_t *surroundFormats) {
5193 if (numSurroundFormats == nullptr || (*numSurroundFormats != 0 && surroundFormats == nullptr)) {
5194 return BAD_VALUE;
5195 }
5196 ALOGV("%s() numSurroundFormats %d surroundFormats %p",
5197 __func__, *numSurroundFormats, surroundFormats);
5198
5199 size_t formatsWritten = 0;
5200 size_t formatsMax = *numSurroundFormats;
5201 std::unordered_set<audio_format_t> formats; // Uses primary surround formats only
5202
5203 // Return formats from all device profiles that have already been resolved by
5204 // checkOutputsForDevice().
5205 for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
5206 sp<DeviceDescriptor> device = mAvailableOutputDevices[i];
5207 audio_devices_t deviceType = device->type();
5208 // Enabling/disabling formats are applied to only HDMI devices. So, this function
5209 // returns formats reported by HDMI devices.
5210 if (deviceType != AUDIO_DEVICE_OUT_HDMI) {
5211 continue;
5212 }
5213 // Formats reported by sink devices
5214 std::unordered_set<audio_format_t> formatset;
5215 if (auto it = mReportedFormatsMap.find(device); it != mReportedFormatsMap.end()) {
5216 formatset.insert(it->second.begin(), it->second.end());
5217 }
5218
5219 // Formats hard-coded in the in policy configuration file (if any).
5220 FormatVector encodedFormats = device->encodedFormats();
5221 formatset.insert(encodedFormats.begin(), encodedFormats.end());
5222 // Filter the formats which are supported by the vendor hardware.
5223 for (auto it = formatset.begin(); it != formatset.end(); ++it) {
Mikhail Naganovb0fbc1b2023-04-28 13:06:32 -07005224 if (mConfig->getSurroundFormats().count(*it) != 0) {
Kriti Dang6537def2021-03-02 13:46:59 +01005225 formats.insert(*it);
5226 } else {
Mikhail Naganovb0fbc1b2023-04-28 13:06:32 -07005227 for (const auto& pair : mConfig->getSurroundFormats()) {
Kriti Dang6537def2021-03-02 13:46:59 +01005228 if (pair.second.count(*it) != 0) {
5229 formats.insert(pair.first);
5230 break;
5231 }
5232 }
5233 }
5234 }
5235 }
5236 *numSurroundFormats = formats.size();
5237 for (const auto& format: formats) {
5238 if (formatsWritten < formatsMax) {
5239 surroundFormats[formatsWritten++] = format;
5240 }
5241 }
5242 return NO_ERROR;
5243}
5244
jiabin81772902018-04-02 17:52:27 -07005245status_t AudioPolicyManager::setSurroundFormatEnabled(audio_format_t audioFormat, bool enabled)
5246{
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005247 ALOGV("%s() format 0x%X enabled %d", __func__, audioFormat, enabled);
Mikhail Naganovb0fbc1b2023-04-28 13:06:32 -07005248 const auto& formatIter = mConfig->getSurroundFormats().find(audioFormat);
5249 if (formatIter == mConfig->getSurroundFormats().end()) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005250 ALOGW("%s() format 0x%X is not a known surround format", __func__, audioFormat);
jiabin81772902018-04-02 17:52:27 -07005251 return BAD_VALUE;
5252 }
5253
Mikhail Naganov100f0122018-11-29 11:22:16 -08005254 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND) !=
5255 AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005256 ALOGW("%s() not in manual mode for surround sound format selection", __func__);
jiabin81772902018-04-02 17:52:27 -07005257 return INVALID_OPERATION;
5258 }
5259
Mikhail Naganov100f0122018-11-29 11:22:16 -08005260 if ((mManualSurroundFormats.count(audioFormat) != 0) == enabled) {
jiabin81772902018-04-02 17:52:27 -07005261 return NO_ERROR;
5262 }
5263
Mikhail Naganov100f0122018-11-29 11:22:16 -08005264 std::unordered_set<audio_format_t> surroundFormatsBackup(mManualSurroundFormats);
jiabin81772902018-04-02 17:52:27 -07005265 if (enabled) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005266 mManualSurroundFormats.insert(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07005267 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005268 mManualSurroundFormats.insert(subFormat);
jiabin81772902018-04-02 17:52:27 -07005269 }
5270 } else {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005271 mManualSurroundFormats.erase(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07005272 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005273 mManualSurroundFormats.erase(subFormat);
jiabin81772902018-04-02 17:52:27 -07005274 }
5275 }
5276
5277 sp<SwAudioOutputDescriptor> outputDesc;
5278 bool profileUpdated = false;
jiabin9a3361e2019-10-01 09:38:30 -07005279 DeviceVector hdmiOutputDevices = mAvailableOutputDevices.getDevicesFromType(
5280 AUDIO_DEVICE_OUT_HDMI);
jiabin81772902018-04-02 17:52:27 -07005281 for (size_t i = 0; i < hdmiOutputDevices.size(); i++) {
5282 // Simulate reconnection to update enabled surround sound formats.
jiabince9f20e2019-09-12 16:29:15 -07005283 String8 address = String8(hdmiOutputDevices[i]->address().c_str());
jiabin5740f082019-08-19 15:08:30 -07005284 std::string name = hdmiOutputDevices[i]->getName();
jiabin81772902018-04-02 17:52:27 -07005285 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
5286 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
5287 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005288 name.c_str(),
5289 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005290 if (status != NO_ERROR) {
5291 continue;
5292 }
5293 status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
5294 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
5295 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005296 name.c_str(),
5297 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005298 profileUpdated |= (status == NO_ERROR);
5299 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08005300 // FIXME: Why doing this for input HDMI devices if we don't augment their reported formats?
jiabin9a3361e2019-10-01 09:38:30 -07005301 DeviceVector hdmiInputDevices = mAvailableInputDevices.getDevicesFromType(
jiabin81772902018-04-02 17:52:27 -07005302 AUDIO_DEVICE_IN_HDMI);
5303 for (size_t i = 0; i < hdmiInputDevices.size(); i++) {
5304 // Simulate reconnection to update enabled surround sound formats.
jiabince9f20e2019-09-12 16:29:15 -07005305 String8 address = String8(hdmiInputDevices[i]->address().c_str());
jiabin5740f082019-08-19 15:08:30 -07005306 std::string name = hdmiInputDevices[i]->getName();
jiabin81772902018-04-02 17:52:27 -07005307 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
5308 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
5309 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005310 name.c_str(),
5311 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005312 if (status != NO_ERROR) {
5313 continue;
5314 }
5315 status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
5316 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
5317 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005318 name.c_str(),
5319 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005320 profileUpdated |= (status == NO_ERROR);
5321 }
5322
jiabin81772902018-04-02 17:52:27 -07005323 if (!profileUpdated) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005324 ALOGW("%s() no audio profiles updated, undoing surround formats change", __func__);
Mikhail Naganov100f0122018-11-29 11:22:16 -08005325 mManualSurroundFormats = std::move(surroundFormatsBackup);
jiabin81772902018-04-02 17:52:27 -07005326 }
5327
5328 return profileUpdated ? NO_ERROR : INVALID_OPERATION;
5329}
5330
Eric Laurent5ada82e2019-08-29 17:53:54 -07005331void AudioPolicyManager::setAppState(audio_port_handle_t portId, app_state_t state)
Svet Ganovf4ddfef2018-01-16 07:37:58 -08005332{
Eric Laurent5ada82e2019-08-29 17:53:54 -07005333 ALOGV("%s(portId:%d, state:%d)", __func__, portId, state);
Eric Laurenta9f86652018-11-28 17:23:11 -08005334 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent5ada82e2019-08-29 17:53:54 -07005335 mInputs.valueAt(i)->setAppState(portId, state);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08005336 }
5337}
5338
jiabin6012f912018-11-02 17:06:30 -07005339bool AudioPolicyManager::isHapticPlaybackSupported()
5340{
5341 for (const auto& hwModule : mHwModules) {
5342 const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
5343 for (const auto &outProfile : outputProfiles) {
5344 struct audio_port audioPort;
5345 outProfile->toAudioPort(&audioPort);
5346 for (size_t i = 0; i < audioPort.num_channel_masks; i++) {
5347 if (audioPort.channel_masks[i] & AUDIO_CHANNEL_HAPTIC_ALL) {
5348 return true;
5349 }
5350 }
5351 }
5352 }
5353 return false;
5354}
5355
Carter Hsu325a8eb2022-01-19 19:56:51 +08005356bool AudioPolicyManager::isUltrasoundSupported()
5357{
5358 bool hasUltrasoundOutput = false;
5359 bool hasUltrasoundInput = false;
5360 for (const auto& hwModule : mHwModules) {
5361 const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
5362 if (!hasUltrasoundOutput) {
5363 for (const auto &outProfile : outputProfiles) {
5364 if (outProfile->getFlags() & AUDIO_OUTPUT_FLAG_ULTRASOUND) {
5365 hasUltrasoundOutput = true;
5366 break;
5367 }
5368 }
5369 }
5370
5371 const InputProfileCollection &inputProfiles = hwModule->getInputProfiles();
5372 if (!hasUltrasoundInput) {
5373 for (const auto &inputProfile : inputProfiles) {
5374 if (inputProfile->getFlags() & AUDIO_INPUT_FLAG_ULTRASOUND) {
5375 hasUltrasoundInput = true;
5376 break;
5377 }
5378 }
5379 }
5380
5381 if (hasUltrasoundOutput && hasUltrasoundInput)
5382 return true;
5383 }
5384 return false;
5385}
5386
Eric Laurent8340e672019-11-06 11:01:08 -08005387bool AudioPolicyManager::isCallScreenModeSupported()
5388{
Mikhail Naganovb0fbc1b2023-04-28 13:06:32 -07005389 return mConfig->isCallScreenModeSupported();
Eric Laurent8340e672019-11-06 11:01:08 -08005390}
5391
5392
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005393status_t AudioPolicyManager::disconnectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07005394{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005395 ALOGV("%s port Id %d", __FUNCTION__, sourceDesc->portId());
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005396 if (!sourceDesc->isConnected()) {
5397 ALOGV("%s port Id %d already disconnected", __FUNCTION__, sourceDesc->portId());
5398 return NO_ERROR;
5399 }
François Gaffieafd4cea2019-11-18 15:50:22 +01005400 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
5401 if (swOutput != 0) {
5402 status_t status = stopSource(swOutput, sourceDesc);
Eric Laurent733ce942017-12-07 12:18:25 -08005403 if (status == NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005404 swOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08005405 }
jiabinbce0c1d2020-10-05 11:20:18 -07005406 if (releaseOutput(sourceDesc->portId())) {
5407 // The output descriptor is reopened to query dynamic profiles. In that case, there is
5408 // no need to release audio patch here but just return NO_ERROR.
5409 return NO_ERROR;
5410 }
Eric Laurentd60560a2015-04-10 11:31:20 -07005411 } else {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005412 sp<HwAudioOutputDescriptor> hwOutputDesc = sourceDesc->hwOutput().promote();
Eric Laurentd60560a2015-04-10 11:31:20 -07005413 if (hwOutputDesc != 0) {
Eric Laurentd60560a2015-04-10 11:31:20 -07005414 // close Hwoutput and remove from mHwOutputs
5415 } else {
5416 ALOGW("%s source has neither SW nor HW output", __FUNCTION__);
5417 }
5418 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005419 status_t status = releaseAudioPatchInternal(sourceDesc->getPatchHandle(), 0, sourceDesc);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005420 sourceDesc->disconnect();
5421 return status;
Eric Laurentd60560a2015-04-10 11:31:20 -07005422}
5423
François Gaffiec005e562018-11-06 15:04:49 +01005424sp<SourceClientDescriptor> AudioPolicyManager::getSourceForAttributesOnOutput(
5425 audio_io_handle_t output, const audio_attributes_t &attr)
Eric Laurentd60560a2015-04-10 11:31:20 -07005426{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005427 sp<SourceClientDescriptor> source;
Eric Laurentd60560a2015-04-10 11:31:20 -07005428 for (size_t i = 0; i < mAudioSources.size(); i++) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005429 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005430 sp<SwAudioOutputDescriptor> outputDesc = sourceDesc->swOutput().promote();
François Gaffiec005e562018-11-06 15:04:49 +01005431 if (followsSameRouting(attr, sourceDesc->attributes()) &&
5432 outputDesc != 0 && outputDesc->mIoHandle == output) {
Eric Laurentd60560a2015-04-10 11:31:20 -07005433 source = sourceDesc;
5434 break;
5435 }
5436 }
5437 return source;
Eric Laurent554a2772015-04-10 11:29:24 -07005438}
5439
Eric Laurentb4f42a92022-01-17 17:37:31 +01005440bool AudioPolicyManager::canBeSpatializedInt(const audio_attributes_t *attr,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005441 const audio_config_t *config,
Andy Hung9dd1a5b2022-05-10 15:39:39 -07005442 const AudioDeviceTypeAddrVector &devices) const
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005443{
5444 // The caller can have the audio attributes criteria ignored by either passing a null ptr or
5445 // the AUDIO_ATTRIBUTES_INITIALIZER value.
Eric Laurentfa0f6742021-08-17 18:39:44 +02005446 // If attributes are specified, current policy is to only allow spatialization for media
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005447 // and game usages.
Eric Laurent39095982021-08-24 18:29:27 +02005448 if (attr != nullptr && *attr != AUDIO_ATTRIBUTES_INITIALIZER) {
5449 if (attr->usage != AUDIO_USAGE_MEDIA && attr->usage != AUDIO_USAGE_GAME) {
5450 return false;
5451 }
5452 if ((attr->flags & (AUDIO_FLAG_CONTENT_SPATIALIZED | AUDIO_FLAG_NEVER_SPATIALIZE)) != 0) {
5453 return false;
5454 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005455 }
5456
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005457 sp<IOProfile> profile =
Eric Laurent39095982021-08-24 18:29:27 +02005458 getSpatializerOutputProfile(config, devices);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005459 if (profile == nullptr) {
5460 return false;
5461 }
5462
5463 // The caller can have the audio config criteria ignored by either passing a null ptr or
5464 // the AUDIO_CONFIG_INITIALIZER value.
Eric Laurentfa0f6742021-08-17 18:39:44 +02005465 // If an audio config is specified, current policy is to only allow spatialization for
Eric Laurent39095982021-08-24 18:29:27 +02005466 // some positional channel masks.
Eric Laurent39095982021-08-24 18:29:27 +02005467
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005468 if (config != nullptr && *config != AUDIO_CONFIG_INITIALIZER) {
Andy Hung9dd1a5b2022-05-10 15:39:39 -07005469 if (!audio_is_channel_mask_spatialized(config->channel_mask)) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005470 return false;
5471 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005472 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005473 return true;
5474}
5475
5476void AudioPolicyManager::checkVirtualizerClientRoutes() {
5477 std::set<audio_stream_type_t> streamsToInvalidate;
5478 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent39095982021-08-24 18:29:27 +02005479 const sp<SwAudioOutputDescriptor>& desc = mOutputs[i];
5480 for (const sp<TrackClientDescriptor>& client : desc->getClientIterable()) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005481 audio_attributes_t attr = client->attributes();
5482 DeviceVector devices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false);
5483 AudioDeviceTypeAddrVector devicesTypeAddress = devices.toTypeAddrVector();
5484 audio_config_base_t clientConfig = client->config();
5485 audio_config_t config = audio_config_initializer(&clientConfig);
Eric Laurent39095982021-08-24 18:29:27 +02005486 if (desc != mSpatializerOutput
Andy Hung9dd1a5b2022-05-10 15:39:39 -07005487 && canBeSpatializedInt(&attr, &config, devicesTypeAddress)) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005488 streamsToInvalidate.insert(client->stream());
5489 }
5490 }
5491 }
5492
5493 for (audio_stream_type_t stream : streamsToInvalidate) {
5494 mpClientInterface->invalidateStream(stream);
5495 }
5496}
5497
Eric Laurente191d1b2022-04-15 11:59:25 +02005498
5499bool AudioPolicyManager::isOutputOnlyAvailableRouteToSomeDevice(
5500 const sp<SwAudioOutputDescriptor>& outputDesc) {
5501 if (outputDesc->isDuplicated()) {
5502 return false;
5503 }
5504 DeviceVector devices = outputDesc->supportedDevices();
5505 for (size_t i = 0; i < mOutputs.size(); i++) {
5506 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
5507 if (desc == outputDesc || desc->isDuplicated()) {
5508 continue;
5509 }
5510 DeviceVector sharedDevices = desc->filterSupportedDevices(devices);
5511 if (!sharedDevices.isEmpty()
5512 && (desc->devicesSupportEncodedFormats(sharedDevices.types())
5513 == outputDesc->devicesSupportEncodedFormats(sharedDevices.types()))) {
5514 return false;
5515 }
5516 }
5517 return true;
5518}
5519
5520
Eric Laurentfa0f6742021-08-17 18:39:44 +02005521status_t AudioPolicyManager::getSpatializerOutput(const audio_config_base_t *mixerConfig,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005522 const audio_attributes_t *attr,
5523 audio_io_handle_t *output) {
5524 *output = AUDIO_IO_HANDLE_NONE;
5525
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005526 DeviceVector devices = mEngine->getOutputDevicesForAttributes(*attr, nullptr, false);
5527 AudioDeviceTypeAddrVector devicesTypeAddress = devices.toTypeAddrVector();
5528 audio_config_t *configPtr = nullptr;
5529 audio_config_t config;
5530 if (mixerConfig != nullptr) {
5531 config = audio_config_initializer(mixerConfig);
5532 configPtr = &config;
5533 }
Andy Hung9dd1a5b2022-05-10 15:39:39 -07005534 if (!canBeSpatializedInt(attr, configPtr, devicesTypeAddress)) {
Eric Laurente191d1b2022-04-15 11:59:25 +02005535 ALOGV("%s provided attributes or mixer config cannot be spatialized", __func__);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005536 return BAD_VALUE;
5537 }
5538
5539 sp<IOProfile> profile =
Eric Laurent39095982021-08-24 18:29:27 +02005540 getSpatializerOutputProfile(configPtr, devicesTypeAddress);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005541 if (profile == nullptr) {
Eric Laurente191d1b2022-04-15 11:59:25 +02005542 ALOGV("%s no suitable output profile for provided attributes or mixer config", __func__);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005543 return BAD_VALUE;
5544 }
5545
Eric Laurente191d1b2022-04-15 11:59:25 +02005546 std::vector<sp<SwAudioOutputDescriptor>> spatializerOutputs;
Eric Laurent39095982021-08-24 18:29:27 +02005547 for (size_t i = 0; i < mOutputs.size(); i++) {
5548 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente191d1b2022-04-15 11:59:25 +02005549 if (!desc->isDuplicated()
5550 && (desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0) {
5551 spatializerOutputs.push_back(desc);
5552 ALOGV("%s adding opened spatializer Output %d", __func__, desc->mIoHandle);
Eric Laurent39095982021-08-24 18:29:27 +02005553 }
5554 }
Eric Laurente191d1b2022-04-15 11:59:25 +02005555 mSpatializerOutput.clear();
5556 bool outputsChanged = false;
5557 for (const auto& desc : spatializerOutputs) {
5558 if (desc->mProfile == profile
5559 && (configPtr == nullptr
5560 || configPtr->channel_mask == desc->mMixerChannelMask)) {
5561 mSpatializerOutput = desc;
5562 ALOGV("%s reusing current spatializer output %d", __func__, desc->mIoHandle);
5563 } else {
5564 ALOGV("%s closing spatializerOutput output %d to match channel mask %#x"
5565 " and devices %s", __func__, desc->mIoHandle,
5566 configPtr != nullptr ? configPtr->channel_mask : 0,
5567 devices.toString().c_str());
5568 closeOutput(desc->mIoHandle);
5569 outputsChanged = true;
5570 }
Eric Laurent39095982021-08-24 18:29:27 +02005571 }
5572
Eric Laurente191d1b2022-04-15 11:59:25 +02005573 if (mSpatializerOutput == nullptr) {
Eric Laurentb4f42a92022-01-17 17:37:31 +01005574 sp<SwAudioOutputDescriptor> desc =
5575 openOutputWithProfileAndDevice(profile, devices, mixerConfig);
Eric Laurente191d1b2022-04-15 11:59:25 +02005576 if (desc != nullptr) {
5577 mSpatializerOutput = desc;
5578 outputsChanged = true;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005579 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005580 }
5581
5582 checkVirtualizerClientRoutes();
5583
Eric Laurente191d1b2022-04-15 11:59:25 +02005584 if (outputsChanged) {
5585 mPreviousOutputs = mOutputs;
5586 mpClientInterface->onAudioPortListUpdate();
5587 }
5588
5589 if (mSpatializerOutput == nullptr) {
5590 ALOGV("%s could not open spatializer output with requested config", __func__);
5591 return BAD_VALUE;
5592 }
Eric Laurent39095982021-08-24 18:29:27 +02005593 *output = mSpatializerOutput->mIoHandle;
Eric Laurente191d1b2022-04-15 11:59:25 +02005594 ALOGV("%s returning new spatializer output %d", __func__, *output);
5595 return OK;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005596}
5597
Eric Laurentfa0f6742021-08-17 18:39:44 +02005598status_t AudioPolicyManager::releaseSpatializerOutput(audio_io_handle_t output) {
5599 if (mSpatializerOutput == nullptr) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005600 return INVALID_OPERATION;
5601 }
Eric Laurentfa0f6742021-08-17 18:39:44 +02005602 if (mSpatializerOutput->mIoHandle != output) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005603 return BAD_VALUE;
5604 }
Eric Laurent39095982021-08-24 18:29:27 +02005605
Eric Laurente191d1b2022-04-15 11:59:25 +02005606 if (!isOutputOnlyAvailableRouteToSomeDevice(mSpatializerOutput)) {
5607 ALOGV("%s closing spatializer output %d", __func__, mSpatializerOutput->mIoHandle);
5608 closeOutput(mSpatializerOutput->mIoHandle);
5609 //from now on mSpatializerOutput is null
5610 checkVirtualizerClientRoutes();
5611 }
Eric Laurent39095982021-08-24 18:29:27 +02005612
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005613 return NO_ERROR;
5614}
5615
Eric Laurente552edb2014-03-10 17:42:56 -07005616// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07005617// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07005618// ----------------------------------------------------------------------------
Eric Laurent6a94d692014-05-20 11:18:06 -07005619uint32_t AudioPolicyManager::nextAudioPortGeneration()
5620{
Mikhail Naganov2773dd72017-12-08 10:12:11 -08005621 return mAudioPortGeneration++;
Eric Laurent6a94d692014-05-20 11:18:06 -07005622}
5623
Mikhail Naganovb0fbc1b2023-04-28 13:06:32 -07005624AudioPolicyManager::AudioPolicyManager(const sp<const AudioPolicyConfig>& config,
Mikhail Naganovabb04782023-05-02 13:56:01 -07005625 EngineInstance&& engine,
Mikhail Naganovb0fbc1b2023-04-28 13:06:32 -07005626 AudioPolicyClientInterface *clientInterface)
Eric Laurente552edb2014-03-10 17:42:56 -07005627 :
Andy Hung4ef19fa2018-05-15 19:35:29 -07005628 mUidCached(AID_AUDIOSERVER), // no need to call getuid(), there's only one of us running.
Mikhail Naganovb0fbc1b2023-04-28 13:06:32 -07005629 mConfig(config),
Mikhail Naganovabb04782023-05-02 13:56:01 -07005630 mEngine(std::move(engine)),
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005631 mpClientInterface(clientInterface),
Eric Laurente552edb2014-03-10 17:42:56 -07005632 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
Eric Laurent3a4311c2014-03-17 12:00:47 -07005633 mA2dpSuspended(false),
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005634 mAudioPortGeneration(1),
5635 mBeaconMuteRefCount(0),
5636 mBeaconPlayingRefCount(0),
Eric Laurent9459fb02015-08-12 18:36:32 -07005637 mBeaconMuted(false),
Andy Hung2ddee192015-12-18 17:34:44 -08005638 mTtsOutputAvailable(false),
Eric Laurent36829f92017-04-07 19:04:42 -07005639 mMasterMono(false),
Eric Laurent4eb58f12018-12-07 16:41:02 -08005640 mMusicEffectOutput(AUDIO_IO_HANDLE_NONE)
Eric Laurente552edb2014-03-10 17:42:56 -07005641{
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005642}
François Gaffied1ab2bd2015-12-02 18:20:06 +01005643
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005644status_t AudioPolicyManager::initialize() {
Mikhail Naganovabb04782023-05-02 13:56:01 -07005645 if (mEngine == nullptr) {
5646 return NO_INIT;
François Gaffie2110e042015-03-24 08:41:51 +01005647 }
5648 mEngine->setObserver(this);
5649 status_t status = mEngine->initCheck();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005650 if (status != NO_ERROR) {
5651 LOG_FATAL("Policy engine not initialized(err=%d)", status);
5652 return status;
5653 }
François Gaffie2110e042015-03-24 08:41:51 +01005654
jiabin76e829d2023-04-04 21:02:36 +00005655 // The actual device selection cache will be updated when calling `updateDevicesAndOutputs`
5656 // at the end of this function.
5657 mEngine->initializeDeviceSelectionCache();
Eric Laurent1d69c872021-01-11 18:53:01 +01005658 mCommunnicationStrategy = mEngine->getProductStrategyForAttributes(
5659 mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL));
5660
Mikhail Naganovb0fbc1b2023-04-28 13:06:32 -07005661 // after parsing the config, mConfig contain all known devices;
Eric Laurente552edb2014-03-10 17:42:56 -07005662 // open all output streams needed to access attached devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07005663 onNewAudioModulesAvailableInt(nullptr /*newDevices*/);
François Gaffie11d30102018-11-02 16:09:09 +01005664
Eric Laurent3a4311c2014-03-17 12:00:47 -07005665 // make sure default device is reachable
Mikhail Naganovb0fbc1b2023-04-28 13:06:32 -07005666 if (const auto defaultOutputDevice = mConfig->getDefaultOutputDevice();
5667 defaultOutputDevice == nullptr ||
5668 !mAvailableOutputDevices.contains(defaultOutputDevice)) {
5669 ALOGE_IF(defaultOutputDevice != nullptr, "Default device %s is unreachable",
5670 defaultOutputDevice->toString().c_str());
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005671 status = NO_INIT;
Eric Laurent3a4311c2014-03-17 12:00:47 -07005672 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02005673 ALOGW_IF(mPrimaryOutput == nullptr, "The policy configuration does not declare a primary output");
Eric Laurente552edb2014-03-10 17:42:56 -07005674
Tomoharu Kasahara71c90912018-10-31 09:10:12 +09005675 // Silence ALOGV statements
5676 property_set("log.tag." LOG_TAG, "D");
5677
Eric Laurente552edb2014-03-10 17:42:56 -07005678 updateDevicesAndOutputs();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005679 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07005680}
5681
Eric Laurente0720872014-03-11 09:30:41 -07005682AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07005683{
Eric Laurente552edb2014-03-10 17:42:56 -07005684 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08005685 mOutputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07005686 }
5687 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08005688 mInputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07005689 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07005690 mAvailableOutputDevices.clear();
5691 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07005692 mOutputs.clear();
5693 mInputs.clear();
5694 mHwModules.clear();
Mikhail Naganov100f0122018-11-29 11:22:16 -08005695 mManualSurroundFormats.clear();
Mikhail Naganovb0fbc1b2023-04-28 13:06:32 -07005696 mConfig.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07005697}
5698
Eric Laurente0720872014-03-11 09:30:41 -07005699status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07005700{
Eric Laurent87ffa392015-05-22 10:32:38 -07005701 return hasPrimaryOutput() ? NO_ERROR : NO_INIT;
Eric Laurente552edb2014-03-10 17:42:56 -07005702}
5703
Eric Laurente552edb2014-03-10 17:42:56 -07005704// ---
5705
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005706void AudioPolicyManager::onNewAudioModulesAvailable()
5707{
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07005708 DeviceVector newDevices;
5709 onNewAudioModulesAvailableInt(&newDevices);
5710 if (!newDevices.empty()) {
5711 nextAudioPortGeneration();
5712 mpClientInterface->onAudioPortListUpdate();
5713 }
5714}
5715
5716void AudioPolicyManager::onNewAudioModulesAvailableInt(DeviceVector *newDevices)
5717{
Mikhail Naganovb0fbc1b2023-04-28 13:06:32 -07005718 for (const auto& hwModule : mConfig->getHwModules()) {
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005719 if (std::find(mHwModules.begin(), mHwModules.end(), hwModule) != mHwModules.end()) {
5720 continue;
5721 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005722 if (hwModule->getHandle() == AUDIO_MODULE_HANDLE_NONE) {
Mikhail Naganov1fba38c2023-05-03 17:45:36 -07005723 if (audio_module_handle_t handle = mpClientInterface->loadHwModule(hwModule->getName());
5724 handle != AUDIO_MODULE_HANDLE_NONE) {
5725 hwModule->setHandle(handle);
5726 } else {
5727 ALOGW("could not load HW module %s", hwModule->getName());
5728 continue;
5729 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005730 }
5731 mHwModules.push_back(hwModule);
Dean Wheatley12a87132021-04-16 10:08:49 +10005732 // open all output streams needed to access attached devices.
5733 // direct outputs are closed immediately after checking the availability of attached devices
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005734 // This also validates mAvailableOutputDevices list
5735 for (const auto& outProfile : hwModule->getOutputProfiles()) {
5736 if (!outProfile->canOpenNewIo()) {
5737 ALOGE("Invalid Output profile max open count %u for profile %s",
5738 outProfile->maxOpenCount, outProfile->getTagName().c_str());
5739 continue;
5740 }
5741 if (!outProfile->hasSupportedDevices()) {
5742 ALOGW("Output profile contains no device on module %s", hwModule->getName());
5743 continue;
5744 }
Carter Hsu1a3364a2022-01-21 15:32:56 +08005745 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_TTS) != 0 ||
5746 (outProfile->getFlags() & AUDIO_OUTPUT_FLAG_ULTRASOUND) != 0) {
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005747 mTtsOutputAvailable = true;
5748 }
5749
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005750 const DeviceVector &supportedDevices = outProfile->getSupportedDevices();
Mikhail Naganovb0fbc1b2023-04-28 13:06:32 -07005751 DeviceVector availProfileDevices = supportedDevices.filter(mConfig->getOutputDevices());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005752 sp<DeviceDescriptor> supportedDevice = 0;
Mikhail Naganovb0fbc1b2023-04-28 13:06:32 -07005753 if (supportedDevices.contains(mConfig->getDefaultOutputDevice())) {
5754 supportedDevice = mConfig->getDefaultOutputDevice();
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005755 } else {
5756 // choose first device present in profile's SupportedDevices also part of
5757 // mAvailableOutputDevices.
5758 if (availProfileDevices.isEmpty()) {
5759 continue;
5760 }
5761 supportedDevice = availProfileDevices.itemAt(0);
5762 }
Mikhail Naganovb0fbc1b2023-04-28 13:06:32 -07005763 if (!mConfig->getOutputDevices().contains(supportedDevice)) {
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005764 continue;
5765 }
5766 sp<SwAudioOutputDescriptor> outputDesc = new SwAudioOutputDescriptor(outProfile,
5767 mpClientInterface);
5768 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentf1f22e72021-07-13 14:04:14 +02005769 status_t status = outputDesc->open(nullptr /* halConfig */, nullptr /* mixerConfig */,
5770 DeviceVector(supportedDevice),
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005771 AUDIO_STREAM_DEFAULT,
5772 AUDIO_OUTPUT_FLAG_NONE, &output);
5773 if (status != NO_ERROR) {
5774 ALOGW("Cannot open output stream for devices %s on hw module %s",
5775 supportedDevice->toString().c_str(), hwModule->getName());
5776 continue;
5777 }
5778 for (const auto &device : availProfileDevices) {
5779 // give a valid ID to an attached device once confirmed it is reachable
5780 if (!device->isAttached()) {
5781 device->attach(hwModule);
5782 mAvailableOutputDevices.add(device);
jiabin1c4794b2020-05-05 10:08:05 -07005783 device->setEncapsulationInfoFromHal(mpClientInterface);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07005784 if (newDevices) newDevices->add(device);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005785 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
5786 }
5787 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02005788 if (mPrimaryOutput == nullptr &&
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005789 outProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
5790 mPrimaryOutput = outputDesc;
5791 }
Eric Laurent39095982021-08-24 18:29:27 +02005792 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
Eric Laurentc529cf62020-04-17 18:19:10 -07005793 outputDesc->close();
5794 } else {
5795 addOutput(output, outputDesc);
5796 setOutputDevices(outputDesc,
5797 DeviceVector(supportedDevice),
5798 true,
5799 0,
5800 NULL);
5801 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005802 }
5803 // open input streams needed to access attached devices to validate
5804 // mAvailableInputDevices list
5805 for (const auto& inProfile : hwModule->getInputProfiles()) {
5806 if (!inProfile->canOpenNewIo()) {
5807 ALOGE("Invalid Input profile max open count %u for profile %s",
5808 inProfile->maxOpenCount, inProfile->getTagName().c_str());
5809 continue;
5810 }
5811 if (!inProfile->hasSupportedDevices()) {
5812 ALOGW("Input profile contains no device on module %s", hwModule->getName());
5813 continue;
5814 }
5815 // chose first device present in profile's SupportedDevices also part of
5816 // available input devices
5817 const DeviceVector &supportedDevices = inProfile->getSupportedDevices();
Mikhail Naganovb0fbc1b2023-04-28 13:06:32 -07005818 DeviceVector availProfileDevices = supportedDevices.filter(mConfig->getInputDevices());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005819 if (availProfileDevices.isEmpty()) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01005820 ALOGV("%s: Input device list is empty! for profile %s",
5821 __func__, inProfile->getTagName().c_str());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005822 continue;
5823 }
5824 sp<AudioInputDescriptor> inputDesc =
5825 new AudioInputDescriptor(inProfile, mpClientInterface);
5826
5827 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
5828 status_t status = inputDesc->open(nullptr,
5829 availProfileDevices.itemAt(0),
5830 AUDIO_SOURCE_MIC,
5831 AUDIO_INPUT_FLAG_NONE,
5832 &input);
5833 if (status != NO_ERROR) {
5834 ALOGW("Cannot open input stream for device %s on hw module %s",
5835 availProfileDevices.toString().c_str(),
5836 hwModule->getName());
5837 continue;
5838 }
5839 for (const auto &device : availProfileDevices) {
5840 // give a valid ID to an attached device once confirmed it is reachable
5841 if (!device->isAttached()) {
5842 device->attach(hwModule);
5843 device->importAudioPortAndPickAudioProfile(inProfile, true);
5844 mAvailableInputDevices.add(device);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07005845 if (newDevices) newDevices->add(device);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005846 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
5847 }
5848 }
5849 inputDesc->close();
5850 }
5851 }
Eric Laurente191d1b2022-04-15 11:59:25 +02005852
5853 // Check if spatializer outputs can be closed until used.
5854 // mOutputs vector never contains duplicated outputs at this point.
5855 std::vector<audio_io_handle_t> outputsClosed;
5856 for (size_t i = 0; i < mOutputs.size(); i++) {
5857 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
5858 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0
5859 && !isOutputOnlyAvailableRouteToSomeDevice(desc)) {
5860 outputsClosed.push_back(desc->mIoHandle);
5861 desc->close();
5862 }
5863 }
5864 for (auto output : outputsClosed) {
5865 removeOutput(output);
5866 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005867}
5868
Eric Laurent98e38192018-02-15 18:31:53 -08005869void AudioPolicyManager::addOutput(audio_io_handle_t output,
5870 const sp<SwAudioOutputDescriptor>& outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07005871{
Eric Laurent1c333e22014-05-20 10:48:17 -07005872 mOutputs.add(output, outputDesc);
jiabin9a3361e2019-10-01 09:38:30 -07005873 applyStreamVolumes(outputDesc, DeviceTypeSet(), 0 /* delayMs */, true /* force */);
Andy Hung2ddee192015-12-18 17:34:44 -08005874 updateMono(output); // update mono status when adding to output list
Eric Laurent36829f92017-04-07 19:04:42 -07005875 selectOutputForMusicEffects();
Eric Laurent6a94d692014-05-20 11:18:06 -07005876 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07005877}
5878
François Gaffie53615e22015-03-19 09:24:12 +01005879void AudioPolicyManager::removeOutput(audio_io_handle_t output)
5880{
Francois Gaffiebce7cd42020-10-14 16:13:20 +02005881 if (mPrimaryOutput != 0 && mPrimaryOutput == mOutputs.valueFor(output)) {
5882 ALOGV("%s: removing primary output", __func__);
5883 mPrimaryOutput = nullptr;
5884 }
François Gaffie53615e22015-03-19 09:24:12 +01005885 mOutputs.removeItem(output);
Eric Laurent36829f92017-04-07 19:04:42 -07005886 selectOutputForMusicEffects();
François Gaffie53615e22015-03-19 09:24:12 +01005887}
5888
Eric Laurent98e38192018-02-15 18:31:53 -08005889void AudioPolicyManager::addInput(audio_io_handle_t input,
5890 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07005891{
Eric Laurent1c333e22014-05-20 10:48:17 -07005892 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07005893 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07005894}
Eric Laurente552edb2014-03-10 17:42:56 -07005895
François Gaffie11d30102018-11-02 16:09:09 +01005896status_t AudioPolicyManager::checkOutputsForDevice(const sp<DeviceDescriptor>& device,
François Gaffie53615e22015-03-19 09:24:12 +01005897 audio_policy_dev_state_t state,
François Gaffie11d30102018-11-02 16:09:09 +01005898 SortedVector<audio_io_handle_t>& outputs)
Eric Laurente552edb2014-03-10 17:42:56 -07005899{
François Gaffie11d30102018-11-02 16:09:09 +01005900 audio_devices_t deviceType = device->type();
jiabince9f20e2019-09-12 16:29:15 -07005901 const String8 &address = String8(device->address().c_str());
Eric Laurentc75307b2015-03-17 15:29:32 -07005902 sp<SwAudioOutputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07005903
François Gaffie11d30102018-11-02 16:09:09 +01005904 if (audio_device_is_digital(deviceType)) {
Eric Laurentcc750d32015-06-25 11:48:20 -07005905 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01005906 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07005907 }
Eric Laurente552edb2014-03-10 17:42:56 -07005908
Eric Laurent3b73df72014-03-11 09:06:29 -07005909 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
jiabinb4fed192020-09-22 14:45:40 -07005910 // first call getAudioPort to get the supported attributes from the HAL
5911 struct audio_port_v7 port = {};
5912 device->toAudioPort(&port);
5913 status_t status = mpClientInterface->getAudioPort(&port);
5914 if (status == NO_ERROR) {
5915 device->importAudioPort(port);
5916 }
5917
5918 // then list already open outputs that can be routed to this device
Eric Laurente552edb2014-03-10 17:42:56 -07005919 for (size_t i = 0; i < mOutputs.size(); i++) {
5920 desc = mOutputs.valueAt(i);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005921 if (!desc->isDuplicated() && desc->supportsDevice(device)
jiabin9a3361e2019-10-01 09:38:30 -07005922 && desc->devicesSupportEncodedFormats({deviceType})) {
François Gaffie11d30102018-11-02 16:09:09 +01005923 ALOGV("checkOutputsForDevice(): adding opened output %d on device %s",
5924 mOutputs.keyAt(i), device->toString().c_str());
5925 outputs.add(mOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07005926 }
5927 }
5928 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07005929 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08005930 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005931 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
5932 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
François Gaffie11d30102018-11-02 16:09:09 +01005933 if (profile->supportsDevice(device)) {
5934 profiles.add(profile);
5935 ALOGV("checkOutputsForDevice(): adding profile %zu from module %s",
5936 j, hwModule->getName());
Eric Laurente552edb2014-03-10 17:42:56 -07005937 }
5938 }
5939 }
5940
Eric Laurent7b279bb2015-12-14 10:18:23 -08005941 ALOGV(" found %zu profiles, %zu outputs", profiles.size(), outputs.size());
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005942
Eric Laurente552edb2014-03-10 17:42:56 -07005943 if (profiles.isEmpty() && outputs.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01005944 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07005945 return BAD_VALUE;
5946 }
5947
5948 // open outputs for matching profiles if needed. Direct outputs are also opened to
5949 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
5950 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07005951 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07005952
5953 // nothing to do if one output is already opened for this profile
5954 size_t j;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005955 for (j = 0; j < outputs.size(); j++) {
5956 desc = mOutputs.valueFor(outputs.itemAt(j));
Eric Laurente552edb2014-03-10 17:42:56 -07005957 if (!desc->isDuplicated() && desc->mProfile == profile) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07005958 // matching profile: save the sample rates, format and channel masks supported
5959 // by the profile in our device descriptor
François Gaffie11d30102018-11-02 16:09:09 +01005960 if (audio_device_is_digital(deviceType)) {
jiabin4ef93452019-09-10 14:29:54 -07005961 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07005962 }
Eric Laurente552edb2014-03-10 17:42:56 -07005963 break;
5964 }
5965 }
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005966 if (j != outputs.size()) {
Eric Laurente552edb2014-03-10 17:42:56 -07005967 continue;
5968 }
5969
Eric Laurent3974e3b2017-12-07 17:58:43 -08005970 if (!profile->canOpenNewIo()) {
5971 ALOGW("Max Output number %u already opened for this profile %s",
5972 profile->maxOpenCount, profile->getTagName().c_str());
5973 continue;
5974 }
5975
Eric Laurent83efe1c2017-07-09 16:51:08 -07005976 ALOGV("opening output for device %08x with params %s profile %p name %s",
Tomasz Wasilczyk8f36f6e2023-08-15 20:59:35 +00005977 deviceType, address.c_str(), profile.get(), profile->getName().c_str());
jiabinbce0c1d2020-10-05 11:20:18 -07005978 desc = openOutputWithProfileAndDevice(profile, DeviceVector(device));
5979 audio_io_handle_t output = desc == nullptr ? AUDIO_IO_HANDLE_NONE : desc->mIoHandle;
Eric Laurentcf2c0212014-07-25 16:20:43 -07005980 if (output == AUDIO_IO_HANDLE_NONE) {
François Gaffie11d30102018-11-02 16:09:09 +01005981 ALOGW("checkOutputsForDevice() could not open output for device %x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07005982 profiles.removeAt(profile_index);
5983 profile_index--;
5984 } else {
5985 outputs.add(output);
Paul McLean9080a4c2015-06-18 08:24:02 -07005986 // Load digital format info only for digital devices
François Gaffie11d30102018-11-02 16:09:09 +01005987 if (audio_device_is_digital(deviceType)) {
jiabinbce0c1d2020-10-05 11:20:18 -07005988 // TODO: when getAudioPort is ready, it may not be needed to import the audio
5989 // port but just pick audio profile
jiabin4ef93452019-09-10 14:29:54 -07005990 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07005991 }
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07005992
François Gaffie11d30102018-11-02 16:09:09 +01005993 if (device_distinguishes_on_address(deviceType)) {
5994 ALOGV("checkOutputsForDevice(): setOutputDevices %s",
5995 device->toString().c_str());
5996 setOutputDevices(desc, DeviceVector(device), true/*force*/, 0/*delay*/,
5997 NULL/*patch handle*/);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005998 }
Eric Laurente552edb2014-03-10 17:42:56 -07005999 ALOGV("checkOutputsForDevice(): adding output %d", output);
6000 }
6001 }
6002
6003 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006004 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07006005 return BAD_VALUE;
6006 }
Eric Laurentd4692962014-05-05 18:13:44 -07006007 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07006008 // check if one opened output is not needed any more after disconnecting one device
6009 for (size_t i = 0; i < mOutputs.size(); i++) {
6010 desc = mOutputs.valueAt(i);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006011 if (!desc->isDuplicated()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08006012 // exact match on device
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006013 if (device_distinguishes_on_address(deviceType) && desc->supportsDevice(device)
Francois Gaffiec7d4c222021-12-02 11:12:52 +01006014 && desc->containsSingleDeviceSupportingEncodedFormats(device)) {
François Gaffie11d30102018-11-02 16:09:09 +01006015 outputs.add(mOutputs.keyAt(i));
Francois Gaffie716e1432019-01-14 16:58:59 +01006016 } else if (!mAvailableOutputDevices.containsAtLeastOne(desc->supportedDevices())) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006017 ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
6018 mOutputs.keyAt(i));
6019 outputs.add(mOutputs.keyAt(i));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006020 }
Eric Laurente552edb2014-03-10 17:42:56 -07006021 }
6022 }
Eric Laurentd4692962014-05-05 18:13:44 -07006023 // Clear any profiles associated with the disconnected device.
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006024 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006025 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
6026 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
jiabinbce0c1d2020-10-05 11:20:18 -07006027 if (!profile->supportsDevice(device)) {
6028 continue;
6029 }
6030 ALOGV("checkOutputsForDevice(): "
6031 "clearing direct output profile %zu on module %s",
6032 j, hwModule->getName());
6033 profile->clearAudioProfiles();
6034 if (!profile->hasDynamicAudioProfile()) {
6035 continue;
6036 }
6037 // When a device is disconnected, if there is an IOProfile that contains dynamic
6038 // profiles and supports the disconnected device, call getAudioPort to repopulate
6039 // the capabilities of the devices that is supported by the IOProfile.
6040 for (const auto& supportedDevice : profile->getSupportedDevices()) {
6041 if (supportedDevice == device ||
6042 !mAvailableOutputDevices.contains(supportedDevice)) {
6043 continue;
6044 }
6045 struct audio_port_v7 port;
6046 supportedDevice->toAudioPort(&port);
6047 status_t status = mpClientInterface->getAudioPort(&port);
6048 if (status == NO_ERROR) {
6049 supportedDevice->importAudioPort(port);
6050 }
Eric Laurente552edb2014-03-10 17:42:56 -07006051 }
6052 }
6053 }
6054 }
6055 return NO_ERROR;
6056}
6057
François Gaffie11d30102018-11-02 16:09:09 +01006058status_t AudioPolicyManager::checkInputsForDevice(const sp<DeviceDescriptor>& device,
Eric Laurent0dd51852019-04-19 18:18:58 -07006059 audio_policy_dev_state_t state)
Eric Laurentd4692962014-05-05 18:13:44 -07006060{
Eric Laurent1f2f2232014-06-02 12:01:23 -07006061 sp<AudioInputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07006062
François Gaffie11d30102018-11-02 16:09:09 +01006063 if (audio_device_is_digital(device->type())) {
Eric Laurentcc750d32015-06-25 11:48:20 -07006064 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01006065 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07006066 }
6067
Eric Laurentd4692962014-05-05 18:13:44 -07006068 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
jiabinbf5f4262023-04-12 21:48:34 +00006069 // first call getAudioPort to get the supported attributes from the HAL
6070 struct audio_port_v7 port = {};
6071 device->toAudioPort(&port);
6072 status_t status = mpClientInterface->getAudioPort(&port);
6073 if (status == NO_ERROR) {
6074 device->importAudioPort(port);
6075 }
6076
Eric Laurent0dd51852019-04-19 18:18:58 -07006077 // look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07006078 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006079 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07006080 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006081 profile_index < hwModule->getInputProfiles().size();
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006082 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006083 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Eric Laurent275e8e92014-11-30 15:14:47 -08006084
François Gaffie11d30102018-11-02 16:09:09 +01006085 if (profile->supportsDevice(device)) {
6086 profiles.add(profile);
6087 ALOGV("checkInputsForDevice(): adding profile %zu from module %s",
6088 profile_index, hwModule->getName());
Eric Laurentd4692962014-05-05 18:13:44 -07006089 }
6090 }
6091 }
6092
Eric Laurent0dd51852019-04-19 18:18:58 -07006093 if (profiles.isEmpty()) {
6094 ALOGW("%s: No input profile available for device %s",
6095 __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07006096 return BAD_VALUE;
6097 }
6098
6099 // open inputs for matching profiles if needed. Direct inputs are also opened to
6100 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
6101 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
6102
Eric Laurent1c333e22014-05-20 10:48:17 -07006103 sp<IOProfile> profile = profiles[profile_index];
Eric Laurent3974e3b2017-12-07 17:58:43 -08006104
Eric Laurentd4692962014-05-05 18:13:44 -07006105 // nothing to do if one input is already opened for this profile
6106 size_t input_index;
6107 for (input_index = 0; input_index < mInputs.size(); input_index++) {
6108 desc = mInputs.valueAt(input_index);
6109 if (desc->mProfile == profile) {
François Gaffie11d30102018-11-02 16:09:09 +01006110 if (audio_device_is_digital(device->type())) {
jiabin4ef93452019-09-10 14:29:54 -07006111 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006112 }
Eric Laurentd4692962014-05-05 18:13:44 -07006113 break;
6114 }
6115 }
6116 if (input_index != mInputs.size()) {
6117 continue;
6118 }
6119
Eric Laurent3974e3b2017-12-07 17:58:43 -08006120 if (!profile->canOpenNewIo()) {
6121 ALOGW("Max Input number %u already opened for this profile %s",
6122 profile->maxOpenCount, profile->getTagName().c_str());
6123 continue;
6124 }
6125
Eric Laurentfe231122017-11-17 17:48:06 -08006126 desc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentcf2c0212014-07-25 16:20:43 -07006127 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
jiabinbf5f4262023-04-12 21:48:34 +00006128 status = desc->open(nullptr, device, AUDIO_SOURCE_MIC, AUDIO_INPUT_FLAG_NONE, &input);
Eric Laurentd4692962014-05-05 18:13:44 -07006129
Eric Laurentcf2c0212014-07-25 16:20:43 -07006130 if (status == NO_ERROR) {
jiabince9f20e2019-09-12 16:29:15 -07006131 const String8& address = String8(device->address().c_str());
Tomasz Wasilczykfd9ffd12023-08-14 17:56:22 +00006132 if (!address.empty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006133 char *param = audio_device_address_to_parameter(device->type(), address);
Eric Laurentcf2c0212014-07-25 16:20:43 -07006134 mpClientInterface->setParameters(input, String8(param));
6135 free(param);
Eric Laurentd4692962014-05-05 18:13:44 -07006136 }
François Gaffie11d30102018-11-02 16:09:09 +01006137 updateAudioProfiles(device, input, profile->getAudioProfiles());
François Gaffie112b0af2015-11-19 16:13:25 +01006138 if (!profile->hasValidAudioProfile()) {
Eric Laurentd4692962014-05-05 18:13:44 -07006139 ALOGW("checkInputsForDevice() direct input missing param");
Eric Laurentfe231122017-11-17 17:48:06 -08006140 desc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07006141 input = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07006142 }
6143
Eric Laurent0dd51852019-04-19 18:18:58 -07006144 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07006145 addInput(input, desc);
6146 }
6147 } // endif input != 0
6148
Eric Laurentcf2c0212014-07-25 16:20:43 -07006149 if (input == AUDIO_IO_HANDLE_NONE) {
Pattydd807582021-11-04 21:01:03 +08006150 ALOGW("%s could not open input for device %s", __func__,
François Gaffie11d30102018-11-02 16:09:09 +01006151 device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07006152 profiles.removeAt(profile_index);
6153 profile_index--;
6154 } else {
François Gaffie11d30102018-11-02 16:09:09 +01006155 if (audio_device_is_digital(device->type())) {
jiabin4ef93452019-09-10 14:29:54 -07006156 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006157 }
Eric Laurentd4692962014-05-05 18:13:44 -07006158 ALOGV("checkInputsForDevice(): adding input %d", input);
6159 }
6160 } // end scan profiles
6161
6162 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006163 ALOGW("%s: No input available for device %s", __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07006164 return BAD_VALUE;
6165 }
6166 } else {
6167 // Disconnect
Eric Laurentd4692962014-05-05 18:13:44 -07006168 // Clear any profiles associated with the disconnected device.
Mikhail Naganovd4120142017-12-06 15:49:22 -08006169 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07006170 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006171 profile_index < hwModule->getInputProfiles().size();
Eric Laurentd4692962014-05-05 18:13:44 -07006172 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006173 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Francois Gaffie716e1432019-01-14 16:58:59 +01006174 if (profile->supportsDevice(device)) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08006175 ALOGV("checkInputsForDevice(): clearing direct input profile %zu on module %s",
6176 profile_index, hwModule->getName());
François Gaffie112b0af2015-11-19 16:13:25 +01006177 profile->clearAudioProfiles();
Eric Laurentd4692962014-05-05 18:13:44 -07006178 }
6179 }
6180 }
6181 } // end disconnect
6182
6183 return NO_ERROR;
6184}
6185
6186
Eric Laurente0720872014-03-11 09:30:41 -07006187void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07006188{
6189 ALOGV("closeOutput(%d)", output);
6190
François Gaffie1c878552018-11-22 16:53:21 +01006191 sp<SwAudioOutputDescriptor> closingOutput = mOutputs.valueFor(output);
6192 if (closingOutput == NULL) {
Eric Laurente552edb2014-03-10 17:42:56 -07006193 ALOGW("closeOutput() unknown output %d", output);
6194 return;
6195 }
Mikhail Naganov32ebca32019-03-22 15:42:52 -07006196 const bool closingOutputWasActive = closingOutput->isActive();
François Gaffie1c878552018-11-22 16:53:21 +01006197 mPolicyMixes.closeOutput(closingOutput);
Eric Laurent275e8e92014-11-30 15:14:47 -08006198
Eric Laurente552edb2014-03-10 17:42:56 -07006199 // look for duplicated outputs connected to the output being removed.
6200 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie1c878552018-11-22 16:53:21 +01006201 sp<SwAudioOutputDescriptor> dupOutput = mOutputs.valueAt(i);
6202 if (dupOutput->isDuplicated() &&
6203 (dupOutput->mOutput1 == closingOutput || dupOutput->mOutput2 == closingOutput)) {
6204 sp<SwAudioOutputDescriptor> remainingOutput =
6205 dupOutput->mOutput1 == closingOutput ? dupOutput->mOutput2 : dupOutput->mOutput1;
Eric Laurente552edb2014-03-10 17:42:56 -07006206 // As all active tracks on duplicated output will be deleted,
6207 // and as they were also referenced on the other output, the reference
6208 // count for their stream type must be adjusted accordingly on
6209 // the other output.
François Gaffie1c878552018-11-22 16:53:21 +01006210 const bool wasActive = remainingOutput->isActive();
6211 // Note: no-op on the closing output where all clients has already been set inactive
6212 dupOutput->setAllClientsInactive();
Eric Laurent733ce942017-12-07 12:18:25 -08006213 // stop() will be a no op if the output is still active but is needed in case all
6214 // active streams refcounts where cleared above
6215 if (wasActive) {
François Gaffie1c878552018-11-22 16:53:21 +01006216 remainingOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08006217 }
Eric Laurente552edb2014-03-10 17:42:56 -07006218 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
6219 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
6220
6221 mpClientInterface->closeOutput(duplicatedOutput);
François Gaffie53615e22015-03-19 09:24:12 +01006222 removeOutput(duplicatedOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07006223 }
6224 }
6225
Eric Laurent05b90f82014-08-27 15:32:29 -07006226 nextAudioPortGeneration();
6227
François Gaffie1c878552018-11-22 16:53:21 +01006228 ssize_t index = mAudioPatches.indexOfKey(closingOutput->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07006229 if (index >= 0) {
6230 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006231 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
6232 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07006233 mAudioPatches.removeItemsAt(index);
6234 mpClientInterface->onAudioPatchListUpdate();
6235 }
6236
Mikhail Naganov32ebca32019-03-22 15:42:52 -07006237 if (closingOutputWasActive) {
6238 closingOutput->stop();
6239 }
François Gaffie1c878552018-11-22 16:53:21 +01006240 closingOutput->close();
Eric Laurente552edb2014-03-10 17:42:56 -07006241
François Gaffie53615e22015-03-19 09:24:12 +01006242 removeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07006243 mPreviousOutputs = mOutputs;
Eric Laurentb4f42a92022-01-17 17:37:31 +01006244 if (closingOutput == mSpatializerOutput) {
6245 mSpatializerOutput.clear();
6246 }
Dean Wheatley3023b382018-08-09 07:42:40 +10006247
6248 // MSD patches may have been released to support a non-MSD direct output. Reset MSD patch if
6249 // no direct outputs are open.
François Gaffie11d30102018-11-02 16:09:09 +01006250 if (!getMsdAudioOutDevices().isEmpty()) {
Dean Wheatley3023b382018-08-09 07:42:40 +10006251 bool directOutputOpen = false;
6252 for (size_t i = 0; i < mOutputs.size(); i++) {
6253 if (mOutputs[i]->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
6254 directOutputOpen = true;
6255 break;
6256 }
6257 }
6258 if (!directOutputOpen) {
Michael Chan6fb34492020-12-08 15:44:49 +11006259 ALOGV("no direct outputs open, reset MSD patches");
6260 // TODO: The MSD patches to be established here may differ to current MSD patches due to
6261 // how output devices for patching are resolved. Avoid by caching and reusing the
6262 // arguments to mEngine->getOutputDevicesForAttributes() when resolving which output
6263 // devices to patch to. This may be complicated by the fact that devices may become
6264 // unavailable.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11006265 setMsdOutputPatches();
Dean Wheatley3023b382018-08-09 07:42:40 +10006266 }
6267 }
Eric Laurent05b90f82014-08-27 15:32:29 -07006268}
6269
6270void AudioPolicyManager::closeInput(audio_io_handle_t input)
6271{
6272 ALOGV("closeInput(%d)", input);
6273
6274 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
6275 if (inputDesc == NULL) {
6276 ALOGW("closeInput() unknown input %d", input);
6277 return;
6278 }
6279
Eric Laurent6a94d692014-05-20 11:18:06 -07006280 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07006281
François Gaffie11d30102018-11-02 16:09:09 +01006282 sp<DeviceDescriptor> device = inputDesc->getDevice();
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08006283 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07006284 if (index >= 0) {
6285 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006286 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
6287 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07006288 mAudioPatches.removeItemsAt(index);
6289 mpClientInterface->onAudioPatchListUpdate();
6290 }
6291
Eric Laurentfe231122017-11-17 17:48:06 -08006292 inputDesc->close();
Eric Laurent05b90f82014-08-27 15:32:29 -07006293 mInputs.removeItem(input);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07006294
François Gaffie11d30102018-11-02 16:09:09 +01006295 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
6296 if (primaryInputDevices.contains(device) &&
Haynes Mathew George1d539d92018-03-16 11:40:49 -07006297 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07006298 mpClientInterface->setSoundTriggerCaptureState(false);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07006299 }
Eric Laurente552edb2014-03-10 17:42:56 -07006300}
6301
François Gaffie11d30102018-11-02 16:09:09 +01006302SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevices(
6303 const DeviceVector &devices,
6304 const SwAudioOutputCollection& openOutputs)
Eric Laurente552edb2014-03-10 17:42:56 -07006305{
6306 SortedVector<audio_io_handle_t> outputs;
6307
François Gaffie11d30102018-11-02 16:09:09 +01006308 ALOGVV("%s() devices %s", __func__, devices.toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07006309 for (size_t i = 0; i < openOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01006310 ALOGVV("output %zu isDuplicated=%d device=%s",
Eric Laurent8c7e6da2015-04-21 17:37:00 -07006311 i, openOutputs.valueAt(i)->isDuplicated(),
François Gaffie11d30102018-11-02 16:09:09 +01006312 openOutputs.valueAt(i)->supportedDevices().toString().c_str());
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006313 if (openOutputs.valueAt(i)->supportsAllDevices(devices)
jiabin9a3361e2019-10-01 09:38:30 -07006314 && openOutputs.valueAt(i)->devicesSupportEncodedFormats(devices.types())) {
François Gaffie11d30102018-11-02 16:09:09 +01006315 ALOGVV("%s() found output %d", __func__, openOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07006316 outputs.add(openOutputs.keyAt(i));
6317 }
6318 }
6319 return outputs;
6320}
6321
Mikhail Naganov37977152018-07-11 15:54:44 -07006322void AudioPolicyManager::checkForDeviceAndOutputChanges(std::function<bool()> onOutputsChecked)
6323{
6324 // checkA2dpSuspend must run before checkOutputForAllStrategies so that A2DP
6325 // output is suspended before any tracks are moved to it
6326 checkA2dpSuspend();
6327 checkOutputForAllStrategies();
Kevin Rocard153f92d2018-12-18 18:33:28 -08006328 checkSecondaryOutputs();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11006329 if (onOutputsChecked != nullptr && onOutputsChecked()) checkA2dpSuspend();
Mikhail Naganov37977152018-07-11 15:54:44 -07006330 updateDevicesAndOutputs();
Mikhail Naganov7bd9b8d2018-11-15 02:09:03 +00006331 if (mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD) != 0) {
Michael Chan6fb34492020-12-08 15:44:49 +11006332 // TODO: The MSD patches to be established here may differ to current MSD patches due to how
6333 // output devices for patching are resolved. Nevertheless, AudioTracks affected by device
6334 // configuration changes will ultimately be rerouted correctly. We can still avoid
6335 // unnecessary rerouting by caching and reusing the arguments to
6336 // mEngine->getOutputDevicesForAttributes() when resolving which output devices to patch to.
6337 // This may be complicated by the fact that devices may become unavailable.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11006338 setMsdOutputPatches();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11006339 }
Jean-Michel Trivi9a6b9ad2020-10-22 16:46:43 -07006340 // an event that changed routing likely occurred, inform upper layers
6341 mpClientInterface->onRoutingUpdated();
Mikhail Naganov37977152018-07-11 15:54:44 -07006342}
6343
François Gaffiec005e562018-11-06 15:04:49 +01006344bool AudioPolicyManager::followsSameRouting(const audio_attributes_t &lAttr,
6345 const audio_attributes_t &rAttr) const
Eric Laurente552edb2014-03-10 17:42:56 -07006346{
François Gaffiec005e562018-11-06 15:04:49 +01006347 return mEngine->getProductStrategyForAttributes(lAttr) ==
6348 mEngine->getProductStrategyForAttributes(rAttr);
6349}
6350
Francois Gaffieff1eb522020-05-06 18:37:04 +02006351void AudioPolicyManager::checkAudioSourceForAttributes(const audio_attributes_t &attr)
6352{
6353 for (size_t i = 0; i < mAudioSources.size(); i++) {
6354 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
6355 if (sourceDesc != nullptr && followsSameRouting(attr, sourceDesc->attributes())
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02006356 && sourceDesc->getPatchHandle() == AUDIO_PATCH_HANDLE_NONE
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02006357 && !isCallRxAudioSource(sourceDesc) && !sourceDesc->isInternal()) {
Francois Gaffieff1eb522020-05-06 18:37:04 +02006358 connectAudioSource(sourceDesc);
6359 }
6360 }
6361}
6362
6363void AudioPolicyManager::clearAudioSourcesForOutput(audio_io_handle_t output)
6364{
6365 for (size_t i = 0; i < mAudioSources.size(); i++) {
6366 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
6367 if (sourceDesc != nullptr && sourceDesc->swOutput().promote() != nullptr
6368 && sourceDesc->swOutput().promote()->mIoHandle == output) {
6369 disconnectAudioSource(sourceDesc);
6370 }
6371 }
6372}
6373
François Gaffiec005e562018-11-06 15:04:49 +01006374void AudioPolicyManager::checkOutputForAttributes(const audio_attributes_t &attr)
6375{
6376 auto psId = mEngine->getProductStrategyForAttributes(attr);
6377
6378 DeviceVector oldDevices = mEngine->getOutputDevicesForAttributes(attr, 0, true /*fromCache*/);
6379 DeviceVector newDevices = mEngine->getOutputDevicesForAttributes(attr, 0, false /*fromCache*/);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07006380
François Gaffie11d30102018-11-02 16:09:09 +01006381 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevices(oldDevices, mPreviousOutputs);
6382 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevices(newDevices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07006383
Eric Laurentc209fe42020-06-05 18:11:23 -07006384 uint32_t maxLatency = 0;
Eric Laurent56ed8842022-11-15 16:04:41 +01006385 std::vector<sp<SwAudioOutputDescriptor>> invalidatedOutputs;
Eric Laurentc209fe42020-06-05 18:11:23 -07006386 // take into account dynamic audio policies related changes: if a client is now associated
6387 // to a different policy mix than at creation time, invalidate corresponding stream
Eric Laurent56ed8842022-11-15 16:04:41 +01006388 for (size_t i = 0; i < mPreviousOutputs.size(); i++) {
Eric Laurentc209fe42020-06-05 18:11:23 -07006389 const sp<SwAudioOutputDescriptor>& desc = mPreviousOutputs.valueAt(i);
6390 if (desc->isDuplicated()) {
6391 continue;
Jean-Michel Trivife472e22014-12-16 14:23:13 -08006392 }
Eric Laurentc209fe42020-06-05 18:11:23 -07006393 for (const sp<TrackClientDescriptor>& client : desc->getClientIterable()) {
6394 if (mEngine->getProductStrategyForAttributes(client->attributes()) != psId) {
6395 continue;
6396 }
6397 sp<AudioPolicyMix> primaryMix;
Dean Wheatleyd082f472022-02-04 11:10:48 +11006398 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->config(),
6399 client->uid(), client->flags(), primaryMix, nullptr);
Eric Laurentc209fe42020-06-05 18:11:23 -07006400 if (status != OK) {
6401 continue;
6402 }
yucliuf4de36d2020-09-14 14:57:56 -07006403 if (client->getPrimaryMix() != primaryMix || client->hasLostPrimaryMix()) {
Eric Laurent56ed8842022-11-15 16:04:41 +01006404 if (desc->isStrategyActive(psId) && maxLatency < desc->latency()) {
Eric Laurentc209fe42020-06-05 18:11:23 -07006405 maxLatency = desc->latency();
6406 }
Eric Laurent56ed8842022-11-15 16:04:41 +01006407 invalidatedOutputs.push_back(desc);
Eric Laurentc209fe42020-06-05 18:11:23 -07006408 }
Jean-Michel Trivife472e22014-12-16 14:23:13 -08006409 }
6410 }
6411
Eric Laurent56ed8842022-11-15 16:04:41 +01006412 if (srcOutputs != dstOutputs || !invalidatedOutputs.empty()) {
Eric Laurentac3a6902018-05-11 16:39:10 -07006413 // get maximum latency of all source outputs to determine the minimum mute time guaranteeing
6414 // audio from invalidated tracks will be rendered when unmuting
Eric Laurentac3a6902018-05-11 16:39:10 -07006415 for (audio_io_handle_t srcOut : srcOutputs) {
6416 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
Eric Laurentaa02db82019-09-05 17:31:49 -07006417 if (desc == nullptr) continue;
6418
6419 if (desc->isStrategyActive(psId) && maxLatency < desc->latency()) {
Eric Laurentac3a6902018-05-11 16:39:10 -07006420 maxLatency = desc->latency();
6421 }
Eric Laurentaa02db82019-09-05 17:31:49 -07006422
Eric Laurent56ed8842022-11-15 16:04:41 +01006423 bool invalidate = false;
Eric Laurentaa02db82019-09-05 17:31:49 -07006424 for (auto client : desc->clientsList(false /*activeOnly*/)) {
Eric Laurent78aade82019-09-13 18:55:08 -07006425 if (desc->isDuplicated() || !desc->mProfile->isDirectOutput()) {
Eric Laurentaa02db82019-09-05 17:31:49 -07006426 // a client on a non direct outputs has necessarily a linear PCM format
6427 // so we can call selectOutput() safely
6428 const audio_io_handle_t newOutput = selectOutput(dstOutputs,
6429 client->flags(),
6430 client->config().format,
6431 client->config().channel_mask,
jiabinebb6af42020-06-09 17:31:17 -07006432 client->config().sample_rate,
6433 client->session());
Eric Laurentaa02db82019-09-05 17:31:49 -07006434 if (newOutput != srcOut) {
6435 invalidate = true;
6436 break;
6437 }
6438 } else {
6439 sp<IOProfile> profile = getProfileForOutput(newDevices,
6440 client->config().sample_rate,
6441 client->config().format,
6442 client->config().channel_mask,
6443 client->flags(),
6444 true /* directOnly */);
6445 if (profile != desc->mProfile) {
6446 invalidate = true;
6447 break;
6448 }
6449 }
6450 }
Eric Laurent56ed8842022-11-15 16:04:41 +01006451 // mute strategy while moving tracks from one output to another
6452 if (invalidate) {
6453 invalidatedOutputs.push_back(desc);
6454 if (desc->isStrategyActive(psId)) {
6455 setStrategyMute(psId, true, desc);
6456 setStrategyMute(psId, false, desc, maxLatency * LATENCY_MUTE_FACTOR,
6457 newDevices.types());
6458 }
Eric Laurente552edb2014-03-10 17:42:56 -07006459 }
François Gaffiec005e562018-11-06 15:04:49 +01006460 sp<SourceClientDescriptor> source = getSourceForAttributesOnOutput(srcOut, attr);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02006461 if (source != nullptr && !isCallRxAudioSource(source) && !source->isInternal()) {
Eric Laurentd60560a2015-04-10 11:31:20 -07006462 connectAudioSource(source);
6463 }
Eric Laurente552edb2014-03-10 17:42:56 -07006464 }
6465
Eric Laurent56ed8842022-11-15 16:04:41 +01006466 ALOGV_IF(!(srcOutputs.isEmpty() || dstOutputs.isEmpty()),
6467 "%s: strategy %d, moving from output %s to output %s", __func__, psId,
6468 std::to_string(srcOutputs[0]).c_str(),
6469 std::to_string(dstOutputs[0]).c_str());
6470
François Gaffiec005e562018-11-06 15:04:49 +01006471 // Move effects associated to this stream from previous output to new output
6472 if (followsSameRouting(attr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07006473 selectOutputForMusicEffects();
Eric Laurente552edb2014-03-10 17:42:56 -07006474 }
François Gaffiec005e562018-11-06 15:04:49 +01006475 // Move tracks associated to this stream (and linked) from previous output to new output
Eric Laurent56ed8842022-11-15 16:04:41 +01006476 if (!invalidatedOutputs.empty()) {
Eric Laurentaa02db82019-09-05 17:31:49 -07006477 for (auto stream : mEngine->getStreamTypesForProductStrategy(psId)) {
6478 mpClientInterface->invalidateStream(stream);
6479 }
Eric Laurent56ed8842022-11-15 16:04:41 +01006480 for (sp<SwAudioOutputDescriptor> desc : invalidatedOutputs) {
jiabin49256852022-03-09 11:21:35 -08006481 desc->setTracksInvalidatedStatusByStrategy(psId);
6482 }
Eric Laurente552edb2014-03-10 17:42:56 -07006483 }
6484 }
6485}
6486
Eric Laurente0720872014-03-11 09:30:41 -07006487void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07006488{
François Gaffiec005e562018-11-06 15:04:49 +01006489 for (const auto &strategy : mEngine->getOrderedProductStrategies()) {
6490 auto attributes = mEngine->getAllAttributesForProductStrategy(strategy).front();
6491 checkOutputForAttributes(attributes);
Francois Gaffieff1eb522020-05-06 18:37:04 +02006492 checkAudioSourceForAttributes(attributes);
François Gaffiec005e562018-11-06 15:04:49 +01006493 }
Eric Laurente552edb2014-03-10 17:42:56 -07006494}
6495
Kevin Rocard153f92d2018-12-18 18:33:28 -08006496void AudioPolicyManager::checkSecondaryOutputs() {
6497 std::set<audio_stream_type_t> streamsToInvalidate;
jiabin10a03f12021-05-07 23:46:28 +00006498 TrackSecondaryOutputsMap trackSecondaryOutputs;
Kevin Rocard153f92d2018-12-18 18:33:28 -08006499 for (size_t i = 0; i < mOutputs.size(); i++) {
6500 const sp<SwAudioOutputDescriptor>& outputDescriptor = mOutputs[i];
6501 for (const sp<TrackClientDescriptor>& client : outputDescriptor->getClientIterable()) {
Eric Laurentc529cf62020-04-17 18:19:10 -07006502 sp<AudioPolicyMix> primaryMix;
6503 std::vector<sp<AudioPolicyMix>> secondaryMixes;
Dean Wheatleyd082f472022-02-04 11:10:48 +11006504 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->config(),
6505 client->uid(), client->flags(), primaryMix, &secondaryMixes);
Eric Laurentc529cf62020-04-17 18:19:10 -07006506 std::vector<sp<SwAudioOutputDescriptor>> secondaryDescs;
6507 for (auto &secondaryMix : secondaryMixes) {
6508 sp<SwAudioOutputDescriptor> outputDesc = secondaryMix->getOutput();
6509 if (outputDesc != nullptr &&
6510 outputDesc->mIoHandle != AUDIO_IO_HANDLE_NONE) {
6511 secondaryDescs.push_back(outputDesc);
6512 }
6513 }
6514
jiabin10a03f12021-05-07 23:46:28 +00006515 if (status != OK) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08006516 streamsToInvalidate.insert(client->stream());
jiabin10a03f12021-05-07 23:46:28 +00006517 } else if (!std::equal(
6518 client->getSecondaryOutputs().begin(),
6519 client->getSecondaryOutputs().end(),
6520 secondaryDescs.begin(), secondaryDescs.end())) {
jiabina5281062021-11-23 00:10:23 +00006521 if (!audio_is_linear_pcm(client->config().format)) {
6522 // If the format is not PCM, the tracks should be invalidated to get correct
6523 // behavior when the secondary output is changed.
6524 streamsToInvalidate.insert(client->stream());
6525 } else {
6526 std::vector<wp<SwAudioOutputDescriptor>> weakSecondaryDescs;
6527 std::vector<audio_io_handle_t> secondaryOutputIds;
6528 for (const auto &secondaryDesc: secondaryDescs) {
6529 secondaryOutputIds.push_back(secondaryDesc->mIoHandle);
6530 weakSecondaryDescs.push_back(secondaryDesc);
6531 }
6532 trackSecondaryOutputs.emplace(client->portId(), secondaryOutputIds);
6533 client->setSecondaryOutputs(std::move(weakSecondaryDescs));
jiabin10a03f12021-05-07 23:46:28 +00006534 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08006535 }
6536 }
6537 }
jiabin10a03f12021-05-07 23:46:28 +00006538 if (!trackSecondaryOutputs.empty()) {
6539 mpClientInterface->updateSecondaryOutputs(trackSecondaryOutputs);
6540 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08006541 for (audio_stream_type_t stream : streamsToInvalidate) {
jiabin10a03f12021-05-07 23:46:28 +00006542 ALOGD("%s Invalidate stream %d due to fail getting output for attr", __func__, stream);
Kevin Rocard153f92d2018-12-18 18:33:28 -08006543 mpClientInterface->invalidateStream(stream);
6544 }
6545}
6546
Eric Laurent2517af32020-11-25 15:31:27 +01006547bool AudioPolicyManager::isScoRequestedForComm() const {
6548 AudioDeviceTypeAddrVector devices;
6549 mEngine->getDevicesForRoleAndStrategy(mCommunnicationStrategy, DEVICE_ROLE_PREFERRED, devices);
6550 for (const auto &device : devices) {
6551 if (audio_is_bluetooth_out_sco_device(device.mType)) {
6552 return true;
6553 }
6554 }
6555 return false;
6556}
6557
Eric Laurent1a8b45f2022-04-13 16:01:47 +02006558bool AudioPolicyManager::isHearingAidUsedForComm() const {
6559 DeviceVector devices = mEngine->getOutputDevicesForStream(AUDIO_STREAM_VOICE_CALL,
6560 true /*fromCache*/);
6561 for (const auto &device : devices) {
6562 if (device->type() == AUDIO_DEVICE_OUT_HEARING_AID) {
6563 return true;
6564 }
6565 }
6566 return false;
6567}
6568
6569
Eric Laurente0720872014-03-11 09:30:41 -07006570void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07006571{
François Gaffie53615e22015-03-19 09:24:12 +01006572 audio_io_handle_t a2dpOutput = mOutputs.getA2dpOutput();
Aniket Kumar Lataa8ee9962018-01-31 20:24:23 -08006573 if (a2dpOutput == 0 || mOutputs.isA2dpOffloadedOnPrimary()) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07006574 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07006575 return;
6576 }
6577
Eric Laurent3a4311c2014-03-17 12:00:47 -07006578 bool isScoConnected =
jiabin9a3361e2019-10-01 09:38:30 -07006579 (mAvailableInputDevices.types().count(AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) != 0 ||
6580 !Intersection(mAvailableOutputDevices.types(), getAudioDeviceOutAllScoSet()).empty());
Eric Laurent2517af32020-11-25 15:31:27 +01006581 bool isScoRequested = isScoRequestedForComm();
Eric Laurentf732e072016-08-03 19:30:28 -07006582
6583 // if suspended, restore A2DP output if:
6584 // ((SCO device is NOT connected) ||
Eric Laurent2517af32020-11-25 15:31:27 +01006585 // ((SCO is not requested) &&
Eric Laurentf732e072016-08-03 19:30:28 -07006586 // (phone state is NOT in call) && (phone state is NOT ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07006587 //
Eric Laurentf732e072016-08-03 19:30:28 -07006588 // if not suspended, suspend A2DP output if:
6589 // (SCO device is connected) &&
Eric Laurent2517af32020-11-25 15:31:27 +01006590 // ((SCO is requested) ||
Eric Laurentf732e072016-08-03 19:30:28 -07006591 // ((phone state is in call) || (phone state is ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07006592 //
6593 if (mA2dpSuspended) {
Eric Laurentf732e072016-08-03 19:30:28 -07006594 if (!isScoConnected ||
Eric Laurent2517af32020-11-25 15:31:27 +01006595 (!isScoRequested &&
Eric Laurentf732e072016-08-03 19:30:28 -07006596 (mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) &&
François Gaffie2110e042015-03-24 08:41:51 +01006597 (mEngine->getPhoneState() != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07006598
6599 mpClientInterface->restoreOutput(a2dpOutput);
6600 mA2dpSuspended = false;
6601 }
6602 } else {
Eric Laurentf732e072016-08-03 19:30:28 -07006603 if (isScoConnected &&
Eric Laurent2517af32020-11-25 15:31:27 +01006604 (isScoRequested ||
Eric Laurentf732e072016-08-03 19:30:28 -07006605 (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) ||
François Gaffie2110e042015-03-24 08:41:51 +01006606 (mEngine->getPhoneState() == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07006607
6608 mpClientInterface->suspendOutput(a2dpOutput);
6609 mA2dpSuspended = true;
6610 }
6611 }
6612}
6613
François Gaffie11d30102018-11-02 16:09:09 +01006614DeviceVector AudioPolicyManager::getNewOutputDevices(const sp<SwAudioOutputDescriptor>& outputDesc,
6615 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07006616{
François Gaffie11d30102018-11-02 16:09:09 +01006617 DeviceVector devices;
6618
Jean-Michel Triviff155c62016-02-26 12:07:16 -08006619 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07006620 if (index >= 0) {
6621 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006622 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01006623 ALOGV("%s device %s forced by patch %d", __func__,
6624 outputDesc->devices().toString().c_str(), outputDesc->getPatchHandle());
6625 return outputDesc->devices();
Eric Laurent6a94d692014-05-20 11:18:06 -07006626 }
6627 }
6628
Dean Wheatley514b4312020-06-17 21:45:00 +10006629 // Do not retrieve engine device for outputs through MSD
6630 // TODO: support explicit routing requests by resetting MSD patch to engine device.
6631 if (outputDesc->devices() == getMsdAudioOutDevices()) {
6632 return outputDesc->devices();
6633 }
6634
Eric Laurent97ac8712018-07-27 18:59:02 -07006635 // Honor explicit routing requests only if no client using default routing is active on this
6636 // input: a specific app can not force routing for other apps by setting a preferred device.
6637 bool active; // unused
François Gaffie11d30102018-11-02 16:09:09 +01006638 sp<DeviceDescriptor> device =
François Gaffiec005e562018-11-06 15:04:49 +01006639 findPreferredDevice(outputDesc, PRODUCT_STRATEGY_NONE, active, mAvailableOutputDevices);
François Gaffie11d30102018-11-02 16:09:09 +01006640 if (device != nullptr) {
6641 return DeviceVector(device);
Eric Laurentf3a5a602018-05-22 18:42:55 -07006642 }
6643
François Gaffiea807ef92018-11-05 10:44:33 +01006644 // Legacy Engine cannot take care of bus devices and mix, so we need to handle the conflict
6645 // of setForceUse / Default Bus device here
6646 device = mPolicyMixes.getDeviceAndMixForOutput(outputDesc, mAvailableOutputDevices);
6647 if (device != nullptr) {
6648 return DeviceVector(device);
6649 }
6650
François Gaffiec005e562018-11-06 15:04:49 +01006651 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
6652 StreamTypeVector streams = mEngine->getStreamTypesForProductStrategy(productStrategy);
6653 auto attr = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05306654 auto hasStreamActive = [&](auto stream) {
6655 return hasStream(streams, stream) && isStreamActive(stream, 0);
6656 };
Eric Laurent484e9272018-06-07 17:29:23 -07006657
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05306658 auto doGetOutputDevicesForVoice = [&]() {
6659 return hasVoiceStream(streams) && (outputDesc == mPrimaryOutput ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01006660 outputDesc->isActive(toVolumeSource(AUDIO_STREAM_VOICE_CALL, false))) &&
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05306661 (isInCall() ||
Henrik Backlund07c654a2021-10-14 15:57:10 +02006662 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc)) &&
6663 !isStreamActive(AUDIO_STREAM_ENFORCED_AUDIBLE, 0);
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05306664 };
6665
6666 // With low-latency playing on speaker, music on WFD, when the first low-latency
6667 // output is stopped, getNewOutputDevices checks for a product strategy
6668 // from the list, as STRATEGY_SONIFICATION comes prior to STRATEGY_MEDIA.
Carter Hsucc58a6b2021-07-20 08:44:50 +00006669 // If an ALARM or ENFORCED_AUDIBLE stream is supported by the product strategy,
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05306670 // devices are returned for STRATEGY_SONIFICATION without checking whether the
6671 // stream is associated to the output descriptor.
6672 if (doGetOutputDevicesForVoice() || outputDesc->isStrategyActive(productStrategy) ||
6673 ((hasStreamActive(AUDIO_STREAM_ALARM) ||
6674 hasStreamActive(AUDIO_STREAM_ENFORCED_AUDIBLE)) &&
6675 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc))) {
François Gaffiec005e562018-11-06 15:04:49 +01006676 // Retrieval of devices for voice DL is done on primary output profile, cannot
6677 // check the route (would force modifying configuration file for this profile)
6678 devices = mEngine->getOutputDevicesForAttributes(attr, nullptr, fromCache);
6679 break;
6680 }
Eric Laurente552edb2014-03-10 17:42:56 -07006681 }
François Gaffiec005e562018-11-06 15:04:49 +01006682 ALOGV("%s selected devices %s", __func__, devices.toString().c_str());
François Gaffie11d30102018-11-02 16:09:09 +01006683 return devices;
Eric Laurent1c333e22014-05-20 10:48:17 -07006684}
6685
François Gaffie11d30102018-11-02 16:09:09 +01006686sp<DeviceDescriptor> AudioPolicyManager::getNewInputDevice(
6687 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurent1c333e22014-05-20 10:48:17 -07006688{
François Gaffie11d30102018-11-02 16:09:09 +01006689 sp<DeviceDescriptor> device;
Eric Laurent6a94d692014-05-20 11:18:06 -07006690
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08006691 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07006692 if (index >= 0) {
6693 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006694 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01006695 ALOGV("getNewInputDevice() device %s forced by patch %d",
6696 inputDesc->getDevice()->toString().c_str(), inputDesc->getPatchHandle());
6697 return inputDesc->getDevice();
Eric Laurent6a94d692014-05-20 11:18:06 -07006698 }
6699 }
6700
Eric Laurent97ac8712018-07-27 18:59:02 -07006701 // Honor explicit routing requests only if no client using default routing is active on this
6702 // input: a specific app can not force routing for other apps by setting a preferred device.
6703 bool active;
François Gaffie11d30102018-11-02 16:09:09 +01006704 device = findPreferredDevice(inputDesc, AUDIO_SOURCE_DEFAULT, active, mAvailableInputDevices);
6705 if (device != nullptr) {
6706 return device;
Eric Laurent97ac8712018-07-27 18:59:02 -07006707 }
6708
Eric Laurentdc95a252018-04-12 12:46:56 -07006709 // If we are not in call and no client is active on this input, this methods returns
Andy Hungf024a9e2019-01-30 16:01:02 -08006710 // a null sp<>, causing the patch on the input stream to be released.
yuanjiahsu0735bf32021-03-18 08:12:54 +08006711 audio_attributes_t attributes;
6712 uid_t uid;
6713 sp<RecordClientDescriptor> topClient = inputDesc->getHighestPriorityClient();
6714 if (topClient != nullptr) {
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01006715 attributes = topClient->attributes();
6716 uid = topClient->uid();
yuanjiahsu0735bf32021-03-18 08:12:54 +08006717 } else {
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01006718 attributes = { .source = AUDIO_SOURCE_DEFAULT };
6719 uid = 0;
yuanjiahsu0735bf32021-03-18 08:12:54 +08006720 }
6721
Francois Gaffie716e1432019-01-14 16:58:59 +01006722 if (attributes.source == AUDIO_SOURCE_DEFAULT && isInCall()) {
6723 attributes.source = AUDIO_SOURCE_VOICE_COMMUNICATION;
Eric Laurentdc95a252018-04-12 12:46:56 -07006724 }
Francois Gaffie716e1432019-01-14 16:58:59 +01006725 if (attributes.source != AUDIO_SOURCE_DEFAULT) {
yuanjiahsu0735bf32021-03-18 08:12:54 +08006726 device = mEngine->getInputDeviceForAttributes(attributes, uid);
Eric Laurentfb66dd92016-01-28 18:32:03 -08006727 }
Eric Laurent1c333e22014-05-20 10:48:17 -07006728
Eric Laurente552edb2014-03-10 17:42:56 -07006729 return device;
6730}
6731
Eric Laurent794fde22016-03-11 09:50:45 -08006732bool AudioPolicyManager::streamsMatchForvolume(audio_stream_type_t stream1,
6733 audio_stream_type_t stream2) {
Jean-Michel Trivi99bb2f92016-11-23 15:52:07 -08006734 return (stream1 == stream2);
Eric Laurent28d09f02016-03-08 10:43:05 -08006735}
6736
Dorin Drimusf2196d82022-01-03 12:11:18 +01006737// TODO - consider MSD routes b/214971780
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08006738status_t AudioPolicyManager::getDevicesForAttributes(
Andy Hung6d23c0f2022-02-16 09:37:15 -08006739 const audio_attributes_t &attr, AudioDeviceTypeAddrVector *devices, bool forVolume) {
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08006740 if (devices == nullptr) {
6741 return BAD_VALUE;
6742 }
Andy Hung6d23c0f2022-02-16 09:37:15 -08006743
6744 // Devices are determined in the following precedence:
6745 //
6746 // 1) Devices associated with a dynamic policy matching the attributes. This is often
6747 // a remote submix from MIX_ROUTE_FLAG_LOOP_BACK.
6748 //
6749 // If no such dynamic policy then
6750 // 2) Devices containing an active client using setPreferredDevice
6751 // with same strategy as the attributes.
6752 // (from the default Engine::getOutputDevicesForAttributes() implementation).
6753 //
6754 // If no corresponding active client with setPreferredDevice then
6755 // 3) Devices associated with the strategy determined by the attributes
6756 // (from the default Engine::getOutputDevicesForAttributes() implementation).
6757 //
6758 // See related getOutputForAttrInt().
6759
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08006760 // check dynamic policies but only for primary descriptors (secondary not used for audible
6761 // audio routing, only used for duplication for playback capture)
Eric Laurentc529cf62020-04-17 18:19:10 -07006762 sp<AudioPolicyMix> policyMix;
Dean Wheatleyd082f472022-02-04 11:10:48 +11006763 status_t status = mPolicyMixes.getOutputForAttr(attr, AUDIO_CONFIG_BASE_INITIALIZER,
6764 0 /*uid unknown here*/, AUDIO_OUTPUT_FLAG_NONE, policyMix, nullptr);
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08006765 if (status != OK) {
6766 return status;
6767 }
Andy Hung6d23c0f2022-02-16 09:37:15 -08006768
6769 DeviceVector curDevices;
6770 if (policyMix != nullptr && policyMix->getOutput() != nullptr &&
6771 // For volume control, skip LOOPBACK mixes which use AUDIO_DEVICE_OUT_REMOTE_SUBMIX
6772 // as they are unaffected by device/stream volume
6773 // (per SwAudioOutputDescriptor::isFixedVolume()).
6774 (!forVolume || policyMix->mDeviceType != AUDIO_DEVICE_OUT_REMOTE_SUBMIX)
6775 ) {
6776 sp<DeviceDescriptor> deviceDesc = mAvailableOutputDevices.getDevice(
6777 policyMix->mDeviceType, policyMix->mDeviceAddress, AUDIO_FORMAT_DEFAULT);
6778 curDevices.add(deviceDesc);
6779 } else {
6780 // The default Engine::getOutputDevicesForAttributes() uses findPreferredDevice()
6781 // which selects setPreferredDevice if active. This means forVolume call
6782 // will take an active setPreferredDevice, if such exists.
6783
6784 curDevices = mEngine->getOutputDevicesForAttributes(
6785 attr, nullptr /* preferredDevice */, false /* fromCache */);
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08006786 }
Andy Hung6d23c0f2022-02-16 09:37:15 -08006787
6788 if (forVolume) {
6789 // We alias the device AUDIO_DEVICE_OUT_SPEAKER_SAFE to AUDIO_DEVICE_OUT_SPEAKER
6790 // for single volume control in AudioService (such relationship should exist if
6791 // SPEAKER_SAFE is present).
6792 //
6793 // (This is unrelated to a different device grouping as Volume::getDeviceCategory)
6794 DeviceVector speakerSafeDevices =
6795 curDevices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER_SAFE);
6796 if (!speakerSafeDevices.isEmpty()) {
6797 curDevices.merge(
6798 mAvailableOutputDevices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER));
6799 curDevices.remove(speakerSafeDevices);
6800 }
6801 }
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08006802 for (const auto& device : curDevices) {
6803 devices->push_back(device->getDeviceTypeAddr());
6804 }
6805 return NO_ERROR;
6806}
6807
Eric Laurente0720872014-03-11 09:30:41 -07006808void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07006809 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07006810 case AUDIO_STREAM_MUSIC:
François Gaffiec005e562018-11-06 15:04:49 +01006811 checkOutputForAttributes(attributes_initializer(AUDIO_USAGE_NOTIFICATION));
Eric Laurente552edb2014-03-10 17:42:56 -07006812 updateDevicesAndOutputs();
6813 break;
6814 default:
6815 break;
6816 }
6817}
6818
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006819uint32_t AudioPolicyManager::handleEventForBeacon(int event) {
Eric Laurent9459fb02015-08-12 18:36:32 -07006820
6821 // skip beacon mute management if a dedicated TTS output is available
6822 if (mTtsOutputAvailable) {
6823 return 0;
6824 }
6825
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006826 switch(event) {
6827 case STARTING_OUTPUT:
6828 mBeaconMuteRefCount++;
6829 break;
6830 case STOPPING_OUTPUT:
6831 if (mBeaconMuteRefCount > 0) {
6832 mBeaconMuteRefCount--;
6833 }
6834 break;
6835 case STARTING_BEACON:
6836 mBeaconPlayingRefCount++;
6837 break;
6838 case STOPPING_BEACON:
6839 if (mBeaconPlayingRefCount > 0) {
6840 mBeaconPlayingRefCount--;
6841 }
6842 break;
6843 }
6844
6845 if (mBeaconMuteRefCount > 0) {
6846 // any playback causes beacon to be muted
6847 return setBeaconMute(true);
6848 } else {
6849 // no other playback: unmute when beacon starts playing, mute when it stops
6850 return setBeaconMute(mBeaconPlayingRefCount == 0);
6851 }
6852}
6853
6854uint32_t AudioPolicyManager::setBeaconMute(bool mute) {
6855 ALOGV("setBeaconMute(%d) mBeaconMuteRefCount=%d mBeaconPlayingRefCount=%d",
6856 mute, mBeaconMuteRefCount, mBeaconPlayingRefCount);
6857 // keep track of muted state to avoid repeating mute/unmute operations
6858 if (mBeaconMuted != mute) {
6859 // mute/unmute AUDIO_STREAM_TTS on all outputs
6860 ALOGV("\t muting %d", mute);
6861 uint32_t maxLatency = 0;
Francois Gaffie4404ddb2021-02-04 17:03:38 +01006862 auto ttsVolumeSource = toVolumeSource(AUDIO_STREAM_TTS, false);
6863 if (ttsVolumeSource == VOLUME_SOURCE_NONE) {
6864 ALOGV("\t no tts volume source available");
6865 return 0;
6866 }
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006867 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07006868 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
jiabin9a3361e2019-10-01 09:38:30 -07006869 setVolumeSourceMute(ttsVolumeSource, mute/*on*/, desc, 0 /*delay*/, DeviceTypeSet());
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006870 const uint32_t latency = desc->latency() * 2;
Eric Laurentcdb2b352020-07-23 10:57:02 -07006871 if (desc->isActive(latency * 2) && latency > maxLatency) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006872 maxLatency = latency;
6873 }
6874 }
6875 mBeaconMuted = mute;
6876 return maxLatency;
6877 }
6878 return 0;
6879}
6880
Eric Laurente0720872014-03-11 09:30:41 -07006881void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07006882{
François Gaffiec005e562018-11-06 15:04:49 +01006883 mEngine->updateDeviceSelectionCache();
Eric Laurente552edb2014-03-10 17:42:56 -07006884 mPreviousOutputs = mOutputs;
6885}
6886
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07006887uint32_t AudioPolicyManager::checkDeviceMuteStrategies(const sp<AudioOutputDescriptor>& outputDesc,
François Gaffiec005e562018-11-06 15:04:49 +01006888 const DeviceVector &prevDevices,
Eric Laurente552edb2014-03-10 17:42:56 -07006889 uint32_t delayMs)
6890{
6891 // mute/unmute strategies using an incompatible device combination
6892 // if muting, wait for the audio in pcm buffer to be drained before proceeding
6893 // if unmuting, unmute only after the specified delay
6894 if (outputDesc->isDuplicated()) {
6895 return 0;
6896 }
6897
6898 uint32_t muteWaitMs = 0;
François Gaffiec005e562018-11-06 15:04:49 +01006899 DeviceVector devices = outputDesc->devices();
6900 bool shouldMute = outputDesc->isActive() && (devices.size() >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07006901
François Gaffiec005e562018-11-06 15:04:49 +01006902 auto productStrategies = mEngine->getOrderedProductStrategies();
6903 for (const auto &productStrategy : productStrategies) {
6904 auto attributes = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
6905 DeviceVector curDevices =
6906 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false/*fromCache*/);
6907 curDevices = curDevices.filter(outputDesc->supportedDevices());
6908 bool mute = shouldMute && curDevices.containsAtLeastOne(devices) && curDevices != devices;
Eric Laurente552edb2014-03-10 17:42:56 -07006909 bool doMute = false;
6910
François Gaffiec005e562018-11-06 15:04:49 +01006911 if (mute && !outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07006912 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01006913 outputDesc->setStrategyMutedByDevice(productStrategy, true);
6914 } else if (!mute && outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07006915 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01006916 outputDesc->setStrategyMutedByDevice(productStrategy, false);
Eric Laurente552edb2014-03-10 17:42:56 -07006917 }
Eric Laurent99401132014-05-07 19:48:15 -07006918 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07006919 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07006920 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07006921 // skip output if it does not share any device with current output
François Gaffie11d30102018-11-02 16:09:09 +01006922 if (!desc->supportedDevices().containsAtLeastOne(outputDesc->supportedDevices())) {
Eric Laurente552edb2014-03-10 17:42:56 -07006923 continue;
6924 }
François Gaffiec005e562018-11-06 15:04:49 +01006925 ALOGVV("%s() %s (curDevice %s)", __func__,
6926 mute ? "muting" : "unmuting", curDevices.toString().c_str());
6927 setStrategyMute(productStrategy, mute, desc, mute ? 0 : delayMs);
6928 if (desc->isStrategyActive(productStrategy)) {
Eric Laurent99401132014-05-07 19:48:15 -07006929 if (mute) {
6930 // FIXME: should not need to double latency if volume could be applied
6931 // immediately by the audioflinger mixer. We must account for the delay
6932 // between now and the next time the audioflinger thread for this output
6933 // will process a buffer (which corresponds to one buffer size,
6934 // usually 1/2 or 1/4 of the latency).
6935 if (muteWaitMs < desc->latency() * 2) {
6936 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07006937 }
6938 }
6939 }
6940 }
6941 }
6942 }
6943
Eric Laurent99401132014-05-07 19:48:15 -07006944 // temporary mute output if device selection changes to avoid volume bursts due to
6945 // different per device volumes
François Gaffiec005e562018-11-06 15:04:49 +01006946 if (outputDesc->isActive() && (devices != prevDevices)) {
Eric Laurentdc462862016-07-19 12:29:53 -07006947 uint32_t tempMuteWaitMs = outputDesc->latency() * 2;
Jasmine Chaf6074fe2021-08-17 13:44:31 +08006948
Eric Laurentdc462862016-07-19 12:29:53 -07006949 if (muteWaitMs < tempMuteWaitMs) {
6950 muteWaitMs = tempMuteWaitMs;
Eric Laurent99401132014-05-07 19:48:15 -07006951 }
Jasmine Chaf6074fe2021-08-17 13:44:31 +08006952
6953 // If recommended duration is defined, replace temporary mute duration to avoid
6954 // truncated notifications at beginning, which depends on duration of changing path in HAL.
6955 // Otherwise, temporary mute duration is conservatively set to 4 times the reported latency.
6956 uint32_t tempRecommendedMuteDuration = outputDesc->getRecommendedMuteDurationMs();
6957 uint32_t tempMuteDurationMs = tempRecommendedMuteDuration > 0 ?
6958 tempRecommendedMuteDuration : outputDesc->latency() * 4;
6959
François Gaffieaaac0fd2018-11-22 17:56:39 +01006960 for (const auto &activeVs : outputDesc->getActiveVolumeSources()) {
6961 // make sure that we do not start the temporary mute period too early in case of
6962 // delayed device change
6963 setVolumeSourceMute(activeVs, true, outputDesc, delayMs);
6964 setVolumeSourceMute(activeVs, false, outputDesc, delayMs + tempMuteDurationMs,
François Gaffiec005e562018-11-06 15:04:49 +01006965 devices.types());
Eric Laurent99401132014-05-07 19:48:15 -07006966 }
6967 }
6968
Eric Laurente552edb2014-03-10 17:42:56 -07006969 // wait for the PCM output buffers to empty before proceeding with the rest of the command
6970 if (muteWaitMs > delayMs) {
6971 muteWaitMs -= delayMs;
6972 usleep(muteWaitMs * 1000);
6973 return muteWaitMs;
6974 }
6975 return 0;
6976}
6977
François Gaffie11d30102018-11-02 16:09:09 +01006978uint32_t AudioPolicyManager::setOutputDevices(const sp<SwAudioOutputDescriptor>& outputDesc,
6979 const DeviceVector &devices,
6980 bool force,
6981 int delayMs,
6982 audio_patch_handle_t *patchHandle,
Francois Gaffie3523ab32021-06-22 13:24:34 +02006983 bool requiresMuteCheck, bool requiresVolumeCheck)
Eric Laurente552edb2014-03-10 17:42:56 -07006984{
François Gaffie11d30102018-11-02 16:09:09 +01006985 ALOGV("%s device %s delayMs %d", __func__, devices.toString().c_str(), delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07006986 uint32_t muteWaitMs;
6987
6988 if (outputDesc->isDuplicated()) {
François Gaffie11d30102018-11-02 16:09:09 +01006989 muteWaitMs = setOutputDevices(outputDesc->subOutput1(), devices, force, delayMs,
6990 nullptr /* patchHandle */, requiresMuteCheck);
6991 muteWaitMs += setOutputDevices(outputDesc->subOutput2(), devices, force, delayMs,
6992 nullptr /* patchHandle */, requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07006993 return muteWaitMs;
6994 }
Eric Laurente552edb2014-03-10 17:42:56 -07006995
6996 // filter devices according to output selected
Francois Gaffie716e1432019-01-14 16:58:59 +01006997 DeviceVector filteredDevices = outputDesc->filterSupportedDevices(devices);
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01006998 DeviceVector prevDevices = outputDesc->devices();
Francois Gaffie3523ab32021-06-22 13:24:34 +02006999 DeviceVector availPrevDevices = mAvailableOutputDevices.filter(prevDevices);
Eric Laurente552edb2014-03-10 17:42:56 -07007000
François Gaffie11d30102018-11-02 16:09:09 +01007001 ALOGV("setOutputDevices() prevDevice %s", prevDevices.toString().c_str());
7002
7003 if (!filteredDevices.isEmpty()) {
7004 outputDesc->setDevices(filteredDevices);
Eric Laurente552edb2014-03-10 17:42:56 -07007005 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00007006
7007 // if the outputs are not materially active, there is no need to mute.
7008 if (requiresMuteCheck) {
François Gaffiec005e562018-11-06 15:04:49 +01007009 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevices, delayMs);
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00007010 } else {
7011 ALOGV("%s: suppressing checkDeviceMuteStrategies", __func__);
7012 muteWaitMs = 0;
7013 }
Eric Laurente552edb2014-03-10 17:42:56 -07007014
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02007015 bool outputRouted = outputDesc->isRouted();
7016
Eric Laurent79ea9582020-06-11 18:49:24 -07007017 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
7018 // output profile or if new device is not supported AND previous device(s) is(are) still
7019 // available (otherwise reset device must be done on the output)
Francois Gaffie3523ab32021-06-22 13:24:34 +02007020 if (!devices.isEmpty() && filteredDevices.isEmpty() && !availPrevDevices.empty()) {
Eric Laurent79ea9582020-06-11 18:49:24 -07007021 ALOGV("%s: unsupported device %s for output", __func__, devices.toString().c_str());
7022 // restore previous device after evaluating strategy mute state
7023 outputDesc->setDevices(prevDevices);
7024 return muteWaitMs;
7025 }
7026
Eric Laurente552edb2014-03-10 17:42:56 -07007027 // Do not change the routing if:
Eric Laurentb80a2a82014-10-27 16:07:59 -07007028 // the requested device is AUDIO_DEVICE_NONE
7029 // OR the requested device is the same as current device
7030 // AND force is not specified
7031 // AND the output is connected by a valid audio patch.
François Gaffie11d30102018-11-02 16:09:09 +01007032 // Doing this check here allows the caller to call setOutputDevices() without conditions
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02007033 if ((filteredDevices.isEmpty() || filteredDevices == prevDevices) && !force && outputRouted) {
François Gaffie11d30102018-11-02 16:09:09 +01007034 ALOGV("%s setting same device %s or null device, force=%d, patch handle=%d", __func__,
7035 filteredDevices.toString().c_str(), force, outputDesc->getPatchHandle());
Francois Gaffie3523ab32021-06-22 13:24:34 +02007036 if (requiresVolumeCheck && !filteredDevices.isEmpty()) {
7037 ALOGV("%s setting same device on routed output, force apply volumes", __func__);
7038 applyStreamVolumes(outputDesc, filteredDevices.types(), delayMs, true /*force*/);
7039 }
Eric Laurente552edb2014-03-10 17:42:56 -07007040 return muteWaitMs;
7041 }
7042
François Gaffie11d30102018-11-02 16:09:09 +01007043 ALOGV("%s changing device to %s", __func__, filteredDevices.toString().c_str());
Eric Laurent1c333e22014-05-20 10:48:17 -07007044
Eric Laurente552edb2014-03-10 17:42:56 -07007045 // do the routing
Francois Gaffie3523ab32021-06-22 13:24:34 +02007046 if (filteredDevices.isEmpty() || mAvailableOutputDevices.filter(filteredDevices).empty()) {
Eric Laurentc75307b2015-03-17 15:29:32 -07007047 resetOutputDevice(outputDesc, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07007048 } else {
François Gaffie11d30102018-11-02 16:09:09 +01007049 PatchBuilder patchBuilder;
7050 patchBuilder.addSource(outputDesc);
7051 ALOG_ASSERT(filteredDevices.size() <= AUDIO_PATCH_PORTS_MAX, "Too many sink ports");
7052 for (const auto &filteredDevice : filteredDevices) {
7053 patchBuilder.addSink(filteredDevice);
Eric Laurentc40d9692016-04-13 19:14:13 -07007054 }
7055
Jasmine Cha7f82d1a2020-03-16 13:21:47 +08007056 // Add half reported latency to delayMs when muteWaitMs is null in order
7057 // to avoid disordered sequence of muting volume and changing devices.
7058 installPatch(__func__, patchHandle, outputDesc.get(), patchBuilder.patch(),
7059 muteWaitMs == 0 ? (delayMs + (outputDesc->latency() / 2)) : delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07007060 }
Eric Laurente552edb2014-03-10 17:42:56 -07007061
7062 // update stream volumes according to new device
François Gaffie11d30102018-11-02 16:09:09 +01007063 applyStreamVolumes(outputDesc, filteredDevices.types(), delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07007064
7065 return muteWaitMs;
7066}
7067
Eric Laurentc75307b2015-03-17 15:29:32 -07007068status_t AudioPolicyManager::resetOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurent6a94d692014-05-20 11:18:06 -07007069 int delayMs,
7070 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07007071{
Eric Laurent6a94d692014-05-20 11:18:06 -07007072 ssize_t index;
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02007073 if (patchHandle == nullptr && !outputDesc->isRouted()) {
7074 return INVALID_OPERATION;
7075 }
Eric Laurent6a94d692014-05-20 11:18:06 -07007076 if (patchHandle) {
7077 index = mAudioPatches.indexOfKey(*patchHandle);
7078 } else {
Jean-Michel Triviff155c62016-02-26 12:07:16 -08007079 index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007080 }
7081 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07007082 return INVALID_OPERATION;
7083 }
Eric Laurent6a94d692014-05-20 11:18:06 -07007084 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007085 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07007086 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07007087 outputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
François Gaffieafd4cea2019-11-18 15:50:22 +01007088 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007089 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07007090 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07007091 return status;
7092}
7093
7094status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
François Gaffie11d30102018-11-02 16:09:09 +01007095 const sp<DeviceDescriptor> &device,
Eric Laurent6a94d692014-05-20 11:18:06 -07007096 bool force,
7097 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07007098{
7099 status_t status = NO_ERROR;
7100
Eric Laurent1f2f2232014-06-02 12:01:23 -07007101 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
François Gaffie11d30102018-11-02 16:09:09 +01007102 if ((device != nullptr) && ((device != inputDesc->getDevice()) || force)) {
7103 inputDesc->setDevice(device);
Eric Laurent1c333e22014-05-20 10:48:17 -07007104
François Gaffie11d30102018-11-02 16:09:09 +01007105 if (mAvailableInputDevices.contains(device)) {
Mikhail Naganovdc769682018-05-04 15:34:08 -07007106 PatchBuilder patchBuilder;
7107 patchBuilder.addSink(inputDesc,
Eric Laurentdaf92cc2014-07-22 15:36:10 -07007108 // AUDIO_SOURCE_HOTWORD is for internal use only:
7109 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
Mikhail Naganovdc769682018-05-04 15:34:08 -07007110 [inputDesc](const PatchBuilder::mix_usecase_t& usecase) {
7111 auto result = usecase;
7112 if (result.source == AUDIO_SOURCE_HOTWORD && !inputDesc->isSoundTrigger()) {
7113 result.source = AUDIO_SOURCE_VOICE_RECOGNITION;
7114 }
7115 return result; }).
Eric Laurent1c333e22014-05-20 10:48:17 -07007116 //only one input device for now
François Gaffie11d30102018-11-02 16:09:09 +01007117 addSource(device);
Mikhail Naganovdc769682018-05-04 15:34:08 -07007118 status = installPatch(__func__, patchHandle, inputDesc.get(), patchBuilder.patch(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07007119 }
7120 }
7121 return status;
7122}
7123
Eric Laurent6a94d692014-05-20 11:18:06 -07007124status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
7125 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07007126{
Eric Laurent1f2f2232014-06-02 12:01:23 -07007127 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07007128 ssize_t index;
7129 if (patchHandle) {
7130 index = mAudioPatches.indexOfKey(*patchHandle);
7131 } else {
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08007132 index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007133 }
7134 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07007135 return INVALID_OPERATION;
7136 }
Eric Laurent6a94d692014-05-20 11:18:06 -07007137 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007138 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07007139 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07007140 inputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
François Gaffieafd4cea2019-11-18 15:50:22 +01007141 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007142 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07007143 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07007144 return status;
7145}
7146
François Gaffie11d30102018-11-02 16:09:09 +01007147sp<IOProfile> AudioPolicyManager::getInputProfile(const sp<DeviceDescriptor> &device,
François Gaffie53615e22015-03-19 09:24:12 +01007148 uint32_t& samplingRate,
Andy Hungf129b032015-04-07 13:45:50 -07007149 audio_format_t& format,
7150 audio_channel_mask_t& channelMask,
François Gaffie53615e22015-03-19 09:24:12 +01007151 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07007152{
7153 // Choose an input profile based on the requested capture parameters: select the first available
7154 // profile supporting all requested parameters.
Andy Hungf129b032015-04-07 13:45:50 -07007155 //
7156 // TODO: perhaps isCompatibleProfile should return a "matching" score so we can return
7157 // the best matching profile, not the first one.
Eric Laurente552edb2014-03-10 17:42:56 -07007158
Glenn Kasten730b9262018-03-29 15:01:26 -07007159 sp<IOProfile> firstInexact;
7160 uint32_t updatedSamplingRate = 0;
7161 audio_format_t updatedFormat = AUDIO_FORMAT_INVALID;
7162 audio_channel_mask_t updatedChannelMask = AUDIO_CHANNEL_INVALID;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08007163 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08007164 for (const auto& profile : hwModule->getInputProfiles()) {
Eric Laurentd4692962014-05-05 18:13:44 -07007165 // profile->log();
Glenn Kasten730b9262018-03-29 15:01:26 -07007166 //updatedFormat = format;
François Gaffie11d30102018-11-02 16:09:09 +01007167 if (profile->isCompatibleProfile(DeviceVector(device), samplingRate,
Glenn Kasten730b9262018-03-29 15:01:26 -07007168 &samplingRate /*updatedSamplingRate*/,
Andy Hungf129b032015-04-07 13:45:50 -07007169 format,
Glenn Kasten730b9262018-03-29 15:01:26 -07007170 &format, /*updatedFormat*/
Andy Hungf129b032015-04-07 13:45:50 -07007171 channelMask,
Glenn Kasten730b9262018-03-29 15:01:26 -07007172 &channelMask /*updatedChannelMask*/,
7173 // FIXME ugly cast
7174 (audio_output_flags_t) flags,
7175 true /*exactMatchRequiredForInputFlags*/)) {
Eric Laurente552edb2014-03-10 17:42:56 -07007176 return profile;
7177 }
François Gaffie11d30102018-11-02 16:09:09 +01007178 if (firstInexact == nullptr && profile->isCompatibleProfile(DeviceVector(device),
Glenn Kasten730b9262018-03-29 15:01:26 -07007179 samplingRate,
7180 &updatedSamplingRate,
7181 format,
7182 &updatedFormat,
7183 channelMask,
7184 &updatedChannelMask,
7185 // FIXME ugly cast
7186 (audio_output_flags_t) flags,
7187 false /*exactMatchRequiredForInputFlags*/)) {
7188 firstInexact = profile;
7189 }
7190
Eric Laurente552edb2014-03-10 17:42:56 -07007191 }
7192 }
Glenn Kasten730b9262018-03-29 15:01:26 -07007193 if (firstInexact != nullptr) {
7194 samplingRate = updatedSamplingRate;
7195 format = updatedFormat;
7196 channelMask = updatedChannelMask;
7197 return firstInexact;
7198 }
Eric Laurente552edb2014-03-10 17:42:56 -07007199 return NULL;
7200}
7201
François Gaffieaaac0fd2018-11-22 17:56:39 +01007202float AudioPolicyManager::computeVolume(IVolumeCurves &curves,
7203 VolumeSource volumeSource,
François Gaffied1ab2bd2015-12-02 18:20:06 +01007204 int index,
jiabin9a3361e2019-10-01 09:38:30 -07007205 const DeviceTypeSet& deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07007206{
jiabin9a3361e2019-10-01 09:38:30 -07007207 float volumeDb = curves.volIndexToDb(Volume::getDeviceCategory(deviceTypes), index);
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07007208
7209 // handle the case of accessibility active while a ringtone is playing: if the ringtone is much
7210 // louder than the accessibility prompt, the prompt cannot be heard, thus masking the touch
7211 // exploration of the dialer UI. In this situation, bring the accessibility volume closer to
7212 // the ringtone volume
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007213 const auto callVolumeSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL, false);
7214 const auto ringVolumeSrc = toVolumeSource(AUDIO_STREAM_RING, false);
7215 const auto musicVolumeSrc = toVolumeSource(AUDIO_STREAM_MUSIC, false);
7216 const auto alarmVolumeSrc = toVolumeSource(AUDIO_STREAM_ALARM, false);
7217 const auto a11yVolumeSrc = toVolumeSource(AUDIO_STREAM_ACCESSIBILITY, false);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007218
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07007219 if (volumeSource == a11yVolumeSrc
François Gaffieaaac0fd2018-11-22 17:56:39 +01007220 && (AUDIO_MODE_RINGTONE == mEngine->getPhoneState()) &&
7221 mOutputs.isActive(ringVolumeSrc, 0)) {
7222 auto &ringCurves = getVolumeCurves(AUDIO_STREAM_RING);
jiabin9a3361e2019-10-01 09:38:30 -07007223 const float ringVolumeDb = computeVolume(ringCurves, ringVolumeSrc, index, deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007224 return ringVolumeDb - 4 > volumeDb ? ringVolumeDb - 4 : volumeDb;
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07007225 }
7226
Eric Laurentdcd4ab12018-06-29 17:45:13 -07007227 // in-call: always cap volume by voice volume + some low headroom
François Gaffieaaac0fd2018-11-22 17:56:39 +01007228 if ((volumeSource != callVolumeSrc && (isInCall() ||
7229 mOutputs.isActiveLocally(callVolumeSrc))) &&
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007230 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM, false) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01007231 volumeSource == ringVolumeSrc || volumeSource == musicVolumeSrc ||
7232 volumeSource == alarmVolumeSrc ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007233 volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION, false) ||
7234 volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false) ||
7235 volumeSource == toVolumeSource(AUDIO_STREAM_DTMF, false) ||
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07007236 volumeSource == a11yVolumeSrc)) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007237 auto &voiceCurves = getVolumeCurves(callVolumeSrc);
jiabin9a3361e2019-10-01 09:38:30 -07007238 int voiceVolumeIndex = voiceCurves.getVolumeIndex(deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007239 const float maxVoiceVolDb =
jiabin9a3361e2019-10-01 09:38:30 -07007240 computeVolume(voiceCurves, callVolumeSrc, voiceVolumeIndex, deviceTypes)
Eric Laurent7731b5a2018-04-06 15:47:22 -07007241 + IN_CALL_EARPIECE_HEADROOM_DB;
Abhijith Shastry329ddab2019-04-23 11:53:26 -07007242 // FIXME: Workaround for call screening applications until a proper audio mode is defined
7243 // to support this scenario : Exempt the RING stream from the audio cap if the audio was
7244 // programmatically muted.
7245 // VOICE_CALL stream has minVolumeIndex > 0 : Users cannot set the volume of voice calls to
7246 // 0. We don't want to cap volume when the system has programmatically muted the voice call
7247 // stream. See setVolumeCurveIndex() for more information.
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07007248 bool exemptFromCapping =
7249 ((volumeSource == ringVolumeSrc) || (volumeSource == a11yVolumeSrc))
7250 && (voiceVolumeIndex == 0);
Abhijith Shastry329ddab2019-04-23 11:53:26 -07007251 ALOGV_IF(exemptFromCapping, "%s volume source %d at vol=%f not capped", __func__,
7252 volumeSource, volumeDb);
7253 if ((volumeDb > maxVoiceVolDb) && !exemptFromCapping) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007254 ALOGV("%s volume source %d at vol=%f overriden by volume group %d at vol=%f", __func__,
7255 volumeSource, volumeDb, callVolumeSrc, maxVoiceVolDb);
7256 volumeDb = maxVoiceVolDb;
Jean-Michel Trivi719a9872017-08-05 13:51:35 -07007257 }
7258 }
Eric Laurente552edb2014-03-10 17:42:56 -07007259 // if a headset is connected, apply the following rules to ring tones and notifications
7260 // to avoid sound level bursts in user's ears:
Eric Laurent6af1c1d2016-04-14 11:20:44 -07007261 // - always attenuate notifications volume by 6dB
7262 // - attenuate ring tones volume by 6dB unless music is not playing and
7263 // speaker is part of the select devices
Eric Laurente552edb2014-03-10 17:42:56 -07007264 // - if music is playing, always limit the volume to current music volume,
7265 // with a minimum threshold at -36dB so that notification is always perceived.
jiabin9a3361e2019-10-01 09:38:30 -07007266 if (!Intersection(deviceTypes,
7267 {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP, AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES,
7268 AUDIO_DEVICE_OUT_WIRED_HEADSET, AUDIO_DEVICE_OUT_WIRED_HEADPHONE,
Eric Laurentc42df452020-08-07 10:51:53 -07007269 AUDIO_DEVICE_OUT_USB_HEADSET, AUDIO_DEVICE_OUT_HEARING_AID,
7270 AUDIO_DEVICE_OUT_BLE_HEADSET}).empty() &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01007271 ((volumeSource == alarmVolumeSrc ||
7272 volumeSource == ringVolumeSrc) ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007273 (volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION, false)) ||
7274 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM, false)) ||
7275 ((volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false)) &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01007276 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) &&
7277 curves.canBeMuted()) {
7278
Eric Laurente552edb2014-03-10 17:42:56 -07007279 // when the phone is ringing we must consider that music could have been paused just before
7280 // by the music application and behave as if music was active if the last music track was
7281 // just stopped
Eric Laurent3b73df72014-03-11 09:06:29 -07007282 if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY) ||
Eric Laurente552edb2014-03-10 17:42:56 -07007283 mLimitRingtoneVolume) {
François Gaffie43c73442018-11-08 08:21:55 +01007284 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
jiabin9a3361e2019-10-01 09:38:30 -07007285 DeviceTypeSet musicDevice =
François Gaffiec005e562018-11-06 15:04:49 +01007286 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
7287 nullptr, true /*fromCache*/).types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01007288 auto &musicCurves = getVolumeCurves(AUDIO_STREAM_MUSIC);
jiabin9a3361e2019-10-01 09:38:30 -07007289 float musicVolDb = computeVolume(musicCurves,
7290 musicVolumeSrc,
7291 musicCurves.getVolumeIndex(musicDevice),
7292 musicDevice);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007293 float minVolDb = (musicVolDb > SONIFICATION_HEADSET_VOLUME_MIN_DB) ?
7294 musicVolDb : SONIFICATION_HEADSET_VOLUME_MIN_DB;
7295 if (volumeDb > minVolDb) {
7296 volumeDb = minVolDb;
7297 ALOGV("computeVolume limiting volume to %f musicVol %f", minVolDb, musicVolDb);
Eric Laurente552edb2014-03-10 17:42:56 -07007298 }
Eric Laurent7b6385c2021-05-12 17:55:36 +02007299 if (Volume::getDeviceForVolume(deviceTypes) != AUDIO_DEVICE_OUT_SPEAKER
7300 && !Intersection(deviceTypes, {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP,
7301 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES}).empty()) {
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07007302 // on A2DP, also ensure notification volume is not too low compared to media when
7303 // intended to be played
François Gaffie43c73442018-11-08 08:21:55 +01007304 if ((volumeDb > -96.0f) &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01007305 (musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB > volumeDb)) {
jiabin9a3361e2019-10-01 09:38:30 -07007306 ALOGV("%s increasing volume for volume source=%d device=%s from %f to %f",
7307 __func__, volumeSource, dumpDeviceTypes(deviceTypes).c_str(), volumeDb,
François Gaffieaaac0fd2018-11-22 17:56:39 +01007308 musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB);
7309 volumeDb = musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB;
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07007310 }
7311 }
jiabin9a3361e2019-10-01 09:38:30 -07007312 } else if ((Volume::getDeviceForVolume(deviceTypes) != AUDIO_DEVICE_OUT_SPEAKER) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01007313 (!(volumeSource == alarmVolumeSrc || volumeSource == ringVolumeSrc))) {
François Gaffie43c73442018-11-08 08:21:55 +01007314 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07007315 }
7316 }
7317
François Gaffie43c73442018-11-08 08:21:55 +01007318 return volumeDb;
Eric Laurente552edb2014-03-10 17:42:56 -07007319}
7320
Eric Laurent3839bc02018-07-10 18:33:34 -07007321int AudioPolicyManager::rescaleVolumeIndex(int srcIndex,
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01007322 VolumeSource fromVolumeSource,
7323 VolumeSource toVolumeSource)
Eric Laurent3839bc02018-07-10 18:33:34 -07007324{
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01007325 if (fromVolumeSource == toVolumeSource) {
Eric Laurent3839bc02018-07-10 18:33:34 -07007326 return srcIndex;
7327 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01007328 auto &srcCurves = getVolumeCurves(fromVolumeSource);
7329 auto &dstCurves = getVolumeCurves(toVolumeSource);
Eric Laurentf5aa58d2019-02-22 18:20:11 -08007330 float minSrc = (float)srcCurves.getVolumeIndexMin();
7331 float maxSrc = (float)srcCurves.getVolumeIndexMax();
7332 float minDst = (float)dstCurves.getVolumeIndexMin();
7333 float maxDst = (float)dstCurves.getVolumeIndexMax();
Eric Laurent3839bc02018-07-10 18:33:34 -07007334
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08007335 // preserve mute request or correct range
7336 if (srcIndex < minSrc) {
7337 if (srcIndex == 0) {
7338 return 0;
7339 }
7340 srcIndex = minSrc;
7341 } else if (srcIndex > maxSrc) {
7342 srcIndex = maxSrc;
7343 }
Eric Laurent3839bc02018-07-10 18:33:34 -07007344 return (int)(minDst + ((srcIndex - minSrc) * (maxDst - minDst)) / (maxSrc - minSrc));
7345}
7346
François Gaffieaaac0fd2018-11-22 17:56:39 +01007347status_t AudioPolicyManager::checkAndSetVolume(IVolumeCurves &curves,
7348 VolumeSource volumeSource,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08007349 int index,
7350 const sp<AudioOutputDescriptor>& outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07007351 DeviceTypeSet deviceTypes,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08007352 int delayMs,
7353 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07007354{
François Gaffieaaac0fd2018-11-22 17:56:39 +01007355 // do not change actual attributes volume if the attributes is muted
7356 if (outputDesc->isMuted(volumeSource)) {
7357 ALOGVV("%s: volume source %d muted count %d active=%d", __func__, volumeSource,
7358 outputDesc->getMuteCount(volumeSource), outputDesc->isActive(volumeSource));
Eric Laurente552edb2014-03-10 17:42:56 -07007359 return NO_ERROR;
7360 }
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007361 VolumeSource callVolSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL, false);
7362 VolumeSource btScoVolSrc = toVolumeSource(AUDIO_STREAM_BLUETOOTH_SCO, false);
7363 bool isVoiceVolSrc = (volumeSource != VOLUME_SOURCE_NONE) && (callVolSrc == volumeSource);
7364 bool isBtScoVolSrc = (volumeSource != VOLUME_SOURCE_NONE) && (btScoVolSrc == volumeSource);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007365
Eric Laurent2517af32020-11-25 15:31:27 +01007366 bool isScoRequested = isScoRequestedForComm();
Eric Laurent1a8b45f2022-04-13 16:01:47 +02007367 bool isHAUsed = isHearingAidUsedForComm();
7368
Eric Laurente552edb2014-03-10 17:42:56 -07007369 // do not change in call volume if bluetooth is connected and vice versa
François Gaffieaaac0fd2018-11-22 17:56:39 +01007370 // if sco and call follow same curves, bypass forceUseForComm
7371 if ((callVolSrc != btScoVolSrc) &&
Eric Laurent2517af32020-11-25 15:31:27 +01007372 ((isVoiceVolSrc && isScoRequested) ||
Beibeif660a512023-02-28 17:00:34 +08007373 (isBtScoVolSrc && !(isScoRequested || isHAUsed))) &&
7374 !isSingleDeviceType(deviceTypes, AUDIO_DEVICE_OUT_TELEPHONY_TX)) {
Eric Laurent2517af32020-11-25 15:31:27 +01007375 ALOGV("%s cannot set volume group %d volume when is%srequested for comm", __func__,
Eric Laurent1a8b45f2022-04-13 16:01:47 +02007376 volumeSource, isScoRequested ? " " : " not ");
Eric Laurent571ef962020-07-24 11:43:48 -07007377 // Do not return an error here as AudioService will always set both voice call
7378 // and bluetooth SCO volumes due to stream aliasing.
7379 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07007380 }
jiabin9a3361e2019-10-01 09:38:30 -07007381 if (deviceTypes.empty()) {
7382 deviceTypes = outputDesc->devices().types();
chenxin2080986da2023-07-17 11:45:21 +08007383 index = curves.getVolumeIndex(deviceTypes);
7384 ALOGD("%s if deviceTypes is change from none to device %s, need get index %d",
7385 __func__, dumpDeviceTypes(deviceTypes).c_str(), index);
Eric Laurentc75307b2015-03-17 15:29:32 -07007386 }
Eric Laurent275e8e92014-11-30 15:14:47 -08007387
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00007388 if (curves.getVolumeIndexMin() < 0 || curves.getVolumeIndexMax() < 0) {
7389 ALOGE("invalid volume index range");
7390 return BAD_VALUE;
7391 }
7392
jiabin9a3361e2019-10-01 09:38:30 -07007393 float volumeDb = computeVolume(curves, volumeSource, index, deviceTypes);
7394 if (outputDesc->isFixedVolume(deviceTypes) ||
Eric Laurent9698a4c2020-10-12 17:10:23 -07007395 // Force VoIP volume to max for bluetooth SCO device except if muted
7396 (index != 0 && (isVoiceVolSrc || isBtScoVolSrc) &&
jiabin9a3361e2019-10-01 09:38:30 -07007397 isSingleDeviceType(deviceTypes, audio_is_bluetooth_out_sco_device))) {
Eric Laurentffbc80f2015-03-18 18:30:19 -07007398 volumeDb = 0.0f;
Eric Laurent275e8e92014-11-30 15:14:47 -08007399 }
Francois Gaffie593634d2021-06-22 13:31:31 +02007400 const bool muted = (index == 0) && (volumeDb != 0.0f);
jiabin9a3361e2019-10-01 09:38:30 -07007401 outputDesc->setVolume(
Francois Gaffie593634d2021-06-22 13:31:31 +02007402 volumeDb, muted, volumeSource, curves.getStreamTypes(), deviceTypes, delayMs, force);
Eric Laurentc75307b2015-03-17 15:29:32 -07007403
Eric Laurente8f2c0f2021-08-17 11:17:19 +02007404 if (outputDesc == mPrimaryOutput && (isVoiceVolSrc || isBtScoVolSrc)) {
Eric Laurente552edb2014-03-10 17:42:56 -07007405 float voiceVolume;
Eric Laurentfad001d2019-06-11 19:17:57 -07007406 // Force voice volume to max or mute for Bluetooth SCO as other attenuations are managed by the headset
François Gaffieaaac0fd2018-11-22 17:56:39 +01007407 if (isVoiceVolSrc) {
7408 voiceVolume = (float)index/(float)curves.getVolumeIndexMax();
Eric Laurente552edb2014-03-10 17:42:56 -07007409 } else {
Eric Laurentfad001d2019-06-11 19:17:57 -07007410 voiceVolume = index == 0 ? 0.0 : 1.0;
Eric Laurente552edb2014-03-10 17:42:56 -07007411 }
Eric Laurent18fba842016-03-31 14:41:26 -07007412 if (voiceVolume != mLastVoiceVolume) {
Eric Laurente552edb2014-03-10 17:42:56 -07007413 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
7414 mLastVoiceVolume = voiceVolume;
7415 }
7416 }
Eric Laurente552edb2014-03-10 17:42:56 -07007417 return NO_ERROR;
7418}
7419
Eric Laurentc75307b2015-03-17 15:29:32 -07007420void AudioPolicyManager::applyStreamVolumes(const sp<AudioOutputDescriptor>& outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07007421 const DeviceTypeSet& deviceTypes,
7422 int delayMs,
7423 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07007424{
jiabincd510522020-01-22 09:40:55 -08007425 ALOGVV("applyStreamVolumes() for device %s", dumpDeviceTypes(deviceTypes).c_str());
François Gaffieaaac0fd2018-11-22 17:56:39 +01007426 for (const auto &volumeGroup : mEngine->getVolumeGroups()) {
7427 auto &curves = getVolumeCurves(toVolumeSource(volumeGroup));
7428 checkAndSetVolume(curves, toVolumeSource(volumeGroup),
jiabin9a3361e2019-10-01 09:38:30 -07007429 curves.getVolumeIndex(deviceTypes),
7430 outputDesc, deviceTypes, delayMs, force);
Eric Laurente552edb2014-03-10 17:42:56 -07007431 }
7432}
7433
François Gaffiec005e562018-11-06 15:04:49 +01007434void AudioPolicyManager::setStrategyMute(product_strategy_t strategy,
7435 bool on,
7436 const sp<AudioOutputDescriptor>& outputDesc,
7437 int delayMs,
jiabin9a3361e2019-10-01 09:38:30 -07007438 DeviceTypeSet deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07007439{
François Gaffieaaac0fd2018-11-22 17:56:39 +01007440 std::vector<VolumeSource> sourcesToMute;
7441 for (auto attributes: mEngine->getAllAttributesForProductStrategy(strategy)) {
7442 ALOGVV("%s() attributes %s, mute %d, output ID %d", __func__,
7443 toString(attributes).c_str(), on, outputDesc->getId());
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007444 VolumeSource source = toVolumeSource(attributes, false);
7445 if ((source != VOLUME_SOURCE_NONE) &&
7446 (std::find(begin(sourcesToMute), end(sourcesToMute), source)
7447 == end(sourcesToMute))) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007448 sourcesToMute.push_back(source);
7449 }
Eric Laurente552edb2014-03-10 17:42:56 -07007450 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01007451 for (auto source : sourcesToMute) {
jiabin9a3361e2019-10-01 09:38:30 -07007452 setVolumeSourceMute(source, on, outputDesc, delayMs, deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007453 }
7454
Eric Laurente552edb2014-03-10 17:42:56 -07007455}
7456
François Gaffieaaac0fd2018-11-22 17:56:39 +01007457void AudioPolicyManager::setVolumeSourceMute(VolumeSource volumeSource,
7458 bool on,
7459 const sp<AudioOutputDescriptor>& outputDesc,
7460 int delayMs,
jiabin9a3361e2019-10-01 09:38:30 -07007461 DeviceTypeSet deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07007462{
jiabin9a3361e2019-10-01 09:38:30 -07007463 if (deviceTypes.empty()) {
7464 deviceTypes = outputDesc->devices().types();
Eric Laurente552edb2014-03-10 17:42:56 -07007465 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01007466 auto &curves = getVolumeCurves(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07007467 if (on) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007468 if (!outputDesc->isMuted(volumeSource)) {
Eric Laurentf5aa58d2019-02-22 18:20:11 -08007469 if (curves.canBeMuted() &&
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007470 (volumeSource != toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01007471 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) ==
7472 AUDIO_POLICY_FORCE_NONE))) {
jiabin9a3361e2019-10-01 09:38:30 -07007473 checkAndSetVolume(curves, volumeSource, 0, outputDesc, deviceTypes, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07007474 }
7475 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01007476 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not
7477 // ignored
7478 outputDesc->incMuteCount(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07007479 } else {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007480 if (!outputDesc->isMuted(volumeSource)) {
7481 ALOGV("%s unmuting non muted attributes!", __func__);
Eric Laurente552edb2014-03-10 17:42:56 -07007482 return;
7483 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01007484 if (outputDesc->decMuteCount(volumeSource) == 0) {
7485 checkAndSetVolume(curves, volumeSource,
jiabin9a3361e2019-10-01 09:38:30 -07007486 curves.getVolumeIndex(deviceTypes),
Eric Laurentc75307b2015-03-17 15:29:32 -07007487 outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07007488 deviceTypes,
Eric Laurente552edb2014-03-10 17:42:56 -07007489 delayMs);
7490 }
7491 }
7492}
7493
François Gaffie53615e22015-03-19 09:24:12 +01007494bool AudioPolicyManager::isValidAttributes(const audio_attributes_t *paa)
7495{
François Gaffiec005e562018-11-06 15:04:49 +01007496 // has flags that map to a stream type?
Eric Laurente83b55d2014-11-14 10:06:21 -08007497 if ((paa->flags & (AUDIO_FLAG_AUDIBILITY_ENFORCED | AUDIO_FLAG_SCO | AUDIO_FLAG_BEACON)) != 0) {
7498 return true;
7499 }
7500
7501 // has known usage?
7502 switch (paa->usage) {
7503 case AUDIO_USAGE_UNKNOWN:
7504 case AUDIO_USAGE_MEDIA:
7505 case AUDIO_USAGE_VOICE_COMMUNICATION:
7506 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
7507 case AUDIO_USAGE_ALARM:
7508 case AUDIO_USAGE_NOTIFICATION:
7509 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
7510 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
7511 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
7512 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
7513 case AUDIO_USAGE_NOTIFICATION_EVENT:
7514 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
7515 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
7516 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
7517 case AUDIO_USAGE_GAME:
Eric Laurent275e8e92014-11-30 15:14:47 -08007518 case AUDIO_USAGE_VIRTUAL_SOURCE:
Jean-Michel Trivi36867762016-12-29 12:03:28 -08007519 case AUDIO_USAGE_ASSISTANT:
Eric Laurent21777f82019-12-06 18:12:06 -08007520 case AUDIO_USAGE_CALL_ASSISTANT:
Hayden Gomes524159d2019-12-23 14:41:47 -08007521 case AUDIO_USAGE_EMERGENCY:
7522 case AUDIO_USAGE_SAFETY:
7523 case AUDIO_USAGE_VEHICLE_STATUS:
7524 case AUDIO_USAGE_ANNOUNCEMENT:
Eric Laurente83b55d2014-11-14 10:06:21 -08007525 break;
7526 default:
7527 return false;
7528 }
7529 return true;
7530}
7531
François Gaffie2110e042015-03-24 08:41:51 +01007532audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
7533{
7534 return mEngine->getForceUse(usage);
7535}
7536
Eric Laurent96d1dda2022-03-14 17:14:19 +01007537bool AudioPolicyManager::isInCall() const {
François Gaffie2110e042015-03-24 08:41:51 +01007538 return isStateInCall(mEngine->getPhoneState());
7539}
7540
Eric Laurent96d1dda2022-03-14 17:14:19 +01007541bool AudioPolicyManager::isStateInCall(int state) const {
François Gaffie2110e042015-03-24 08:41:51 +01007542 return is_state_in_call(state);
7543}
7544
Eric Laurentf9cccec2022-11-16 19:12:00 +01007545bool AudioPolicyManager::isCallAudioAccessible() const {
Eric Laurent74b71512019-11-06 17:21:57 -08007546 audio_mode_t mode = mEngine->getPhoneState();
7547 return (mode == AUDIO_MODE_IN_CALL)
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01007548 || (mode == AUDIO_MODE_CALL_SCREEN)
7549 || (mode == AUDIO_MODE_CALL_REDIRECT);
Eric Laurent74b71512019-11-06 17:21:57 -08007550}
7551
Eric Laurentf9cccec2022-11-16 19:12:00 +01007552bool AudioPolicyManager::isInCallOrScreening() const {
7553 audio_mode_t mode = mEngine->getPhoneState();
7554 return isStateInCall(mode) || mode == AUDIO_MODE_CALL_SCREEN;
7555}
7556
Eric Laurentd60560a2015-04-10 11:31:20 -07007557void AudioPolicyManager::cleanUpForDevice(const sp<DeviceDescriptor>& deviceDesc)
7558{
7559 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07007560 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02007561 if (sourceDesc->isConnected() && (sourceDesc->srcDevice()->equals(deviceDesc) ||
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02007562 sourceDesc->sinkDevice()->equals(deviceDesc))
7563 && !isCallRxAudioSource(sourceDesc)) {
Francois Gaffiea0e5c992020-09-29 16:05:07 +02007564 disconnectAudioSource(sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07007565 }
7566 }
7567
7568 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
7569 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
7570 bool release = false;
7571 for (size_t j = 0; j < patchDesc->mPatch.num_sources && !release; j++) {
7572 const struct audio_port_config *source = &patchDesc->mPatch.sources[j];
7573 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
7574 source->ext.device.type == deviceDesc->type()) {
7575 release = true;
7576 }
7577 }
Francois Gaffiea0e5c992020-09-29 16:05:07 +02007578 const char *address = deviceDesc->address().c_str();
Eric Laurentd60560a2015-04-10 11:31:20 -07007579 for (size_t j = 0; j < patchDesc->mPatch.num_sinks && !release; j++) {
7580 const struct audio_port_config *sink = &patchDesc->mPatch.sinks[j];
7581 if (sink->type == AUDIO_PORT_TYPE_DEVICE &&
Francois Gaffiea0e5c992020-09-29 16:05:07 +02007582 sink->ext.device.type == deviceDesc->type() &&
7583 (strnlen(address, AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0
7584 || strncmp(sink->ext.device.address, address,
7585 AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0)) {
Eric Laurentd60560a2015-04-10 11:31:20 -07007586 release = true;
7587 }
7588 }
7589 if (release) {
François Gaffieafd4cea2019-11-18 15:50:22 +01007590 ALOGV("%s releasing patch %u", __FUNCTION__, patchDesc->getHandle());
7591 releaseAudioPatch(patchDesc->getHandle(), patchDesc->getUid());
Eric Laurentd60560a2015-04-10 11:31:20 -07007592 }
7593 }
Francois Gaffie716e1432019-01-14 16:58:59 +01007594
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01007595 mInputs.clearSessionRoutesForDevice(deviceDesc);
7596
Francois Gaffie716e1432019-01-14 16:58:59 +01007597 mHwModules.cleanUpForDevice(deviceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07007598}
7599
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007600void AudioPolicyManager::modifySurroundFormats(
7601 const sp<DeviceDescriptor>& devDesc, FormatVector *formatsPtr) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007602 std::unordered_set<audio_format_t> enforcedSurround(
7603 devDesc->encodedFormats().begin(), devDesc->encodedFormats().end());
Mikhail Naganov100f0122018-11-29 11:22:16 -08007604 std::unordered_set<audio_format_t> allSurround; // A flat set of all known surround formats
Mikhail Naganovb0fbc1b2023-04-28 13:06:32 -07007605 for (const auto& pair : mConfig->getSurroundFormats()) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08007606 allSurround.insert(pair.first);
7607 for (const auto& subformat : pair.second) allSurround.insert(subformat);
7608 }
Phil Burk09bc4612016-02-24 15:58:15 -08007609
7610 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
7611 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Phil Burk0709b0a2016-03-31 12:54:57 -07007612 ALOGD("%s: forced use = %d", __FUNCTION__, forceUse);
Mikhail Naganov100f0122018-11-29 11:22:16 -08007613 // This is the resulting set of formats depending on the surround mode:
7614 // 'all surround' = allSurround
7615 // 'enforced surround' = enforcedSurround [may include IEC69137 which isn't raw surround fmt]
7616 // 'non-surround' = not in 'all surround' and not in 'enforced surround'
7617 // 'manual surround' = mManualSurroundFormats
7618 // AUTO: formats v 'enforced surround'
7619 // ALWAYS: formats v 'all surround' v 'enforced surround'
7620 // NEVER: formats ^ 'non-surround'
7621 // MANUAL: formats ^ ('non-surround' v 'manual surround' v (IEC69137 ^ 'enforced surround'))
Phil Burk09bc4612016-02-24 15:58:15 -08007622
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007623 std::unordered_set<audio_format_t> formatSet;
7624 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL
7625 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08007626 // formatSet is (formats ^ 'non-surround')
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007627 for (auto formatIter = formatsPtr->begin(); formatIter != formatsPtr->end(); ++formatIter) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08007628 if (allSurround.count(*formatIter) == 0 && enforcedSurround.count(*formatIter) == 0) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007629 formatSet.insert(*formatIter);
7630 }
7631 }
7632 } else {
7633 formatSet.insert(formatsPtr->begin(), formatsPtr->end());
7634 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08007635 formatsPtr->clear(); // Re-filled from the formatSet at the end.
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007636
jiabin81772902018-04-02 17:52:27 -07007637 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08007638 formatSet.insert(mManualSurroundFormats.begin(), mManualSurroundFormats.end());
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007639 // Enable IEC61937 when in MANUAL mode if it's enforced for this device.
7640 if (enforcedSurround.count(AUDIO_FORMAT_IEC61937) != 0) {
7641 formatSet.insert(AUDIO_FORMAT_IEC61937);
Phil Burk09bc4612016-02-24 15:58:15 -08007642 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08007643 } else if (forceUse != AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) { // AUTO or ALWAYS
7644 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS) {
7645 formatSet.insert(allSurround.begin(), allSurround.end());
Phil Burk07ac1142016-03-25 13:39:29 -07007646 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08007647 formatSet.insert(enforcedSurround.begin(), enforcedSurround.end());
Phil Burk09bc4612016-02-24 15:58:15 -08007648 }
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007649 for (const auto& format : formatSet) {
jiabin06e4bab2019-07-29 10:13:34 -07007650 formatsPtr->push_back(format);
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007651 }
Phil Burk0709b0a2016-03-31 12:54:57 -07007652}
7653
jiabin06e4bab2019-07-29 10:13:34 -07007654void AudioPolicyManager::modifySurroundChannelMasks(ChannelMaskSet *channelMasksPtr) {
7655 ChannelMaskSet &channelMasks = *channelMasksPtr;
Phil Burk0709b0a2016-03-31 12:54:57 -07007656 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
7657 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
7658
7659 // If NEVER, then remove support for channelMasks > stereo.
7660 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
jiabin06e4bab2019-07-29 10:13:34 -07007661 for (auto it = channelMasks.begin(); it != channelMasks.end();) {
7662 audio_channel_mask_t channelMask = *it;
Phil Burk0709b0a2016-03-31 12:54:57 -07007663 if (channelMask & ~AUDIO_CHANNEL_OUT_STEREO) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01007664 ALOGV("%s: force NEVER, so remove channelMask 0x%08x", __FUNCTION__, channelMask);
jiabin06e4bab2019-07-29 10:13:34 -07007665 it = channelMasks.erase(it);
Phil Burk0709b0a2016-03-31 12:54:57 -07007666 } else {
jiabin06e4bab2019-07-29 10:13:34 -07007667 ++it;
Phil Burk0709b0a2016-03-31 12:54:57 -07007668 }
7669 }
jiabin81772902018-04-02 17:52:27 -07007670 // If ALWAYS or MANUAL, then make sure we at least support 5.1
7671 } else if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS
7672 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Phil Burk0709b0a2016-03-31 12:54:57 -07007673 bool supports5dot1 = false;
7674 // Are there any channel masks that can be considered "surround"?
Mikhail Naganovcf84e592017-12-07 11:25:11 -08007675 for (audio_channel_mask_t channelMask : channelMasks) {
Phil Burk0709b0a2016-03-31 12:54:57 -07007676 if ((channelMask & AUDIO_CHANNEL_OUT_5POINT1) == AUDIO_CHANNEL_OUT_5POINT1) {
7677 supports5dot1 = true;
7678 break;
7679 }
7680 }
7681 // If not then add 5.1 support.
7682 if (!supports5dot1) {
jiabin06e4bab2019-07-29 10:13:34 -07007683 channelMasks.insert(AUDIO_CHANNEL_OUT_5POINT1);
Eric Laurentfecbceb2021-02-09 14:46:43 +01007684 ALOGV("%s: force MANUAL or ALWAYS, so adding channelMask for 5.1 surround", __func__);
Phil Burk0709b0a2016-03-31 12:54:57 -07007685 }
Phil Burk09bc4612016-02-24 15:58:15 -08007686 }
7687}
7688
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007689void AudioPolicyManager::updateAudioProfiles(const sp<DeviceDescriptor>& devDesc,
Phil Burk00eeb322016-03-31 12:41:00 -07007690 audio_io_handle_t ioHandle,
François Gaffie112b0af2015-11-19 16:13:25 +01007691 AudioProfileVector &profiles)
7692{
7693 String8 reply;
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007694 audio_devices_t device = devDesc->type();
Phil Burk0709b0a2016-03-31 12:54:57 -07007695
François Gaffie112b0af2015-11-19 16:13:25 +01007696 // Format MUST be checked first to update the list of AudioProfile
7697 if (profiles.hasDynamicFormat()) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07007698 reply = mpClientInterface->getParameters(
7699 ioHandle, String8(AudioParameter::keyStreamSupportedFormats));
Tomasz Wasilczyk8f36f6e2023-08-15 20:59:35 +00007700 ALOGV("%s: supported formats %d, %s", __FUNCTION__, ioHandle, reply.c_str());
Eric Laurent62e4bc52016-02-02 18:37:28 -08007701 AudioParameter repliedParameters(reply);
jiabinf26596b2023-04-12 18:56:39 +00007702 FormatVector formats;
Eric Laurent62e4bc52016-02-02 18:37:28 -08007703 if (repliedParameters.get(
jiabinf26596b2023-04-12 18:56:39 +00007704 String8(AudioParameter::keyStreamSupportedFormats), reply) == NO_ERROR) {
Tomasz Wasilczyk8f36f6e2023-08-15 20:59:35 +00007705 formats = formatsFromString(reply.c_str());
jiabinf26596b2023-04-12 18:56:39 +00007706 } else if (devDesc->hasValidAudioProfile()) {
7707 ALOGD("%s: using the device profiles", __func__);
7708 formats = devDesc->getAudioProfiles().getSupportedFormats();
7709 } else {
7710 ALOGE("%s: failed to retrieve format, bailing out", __func__);
François Gaffie112b0af2015-11-19 16:13:25 +01007711 return;
7712 }
Kriti Dangef6be8f2020-11-05 11:58:19 +01007713 mReportedFormatsMap[devDesc] = formats;
Mikhail Naganov100f0122018-11-29 11:22:16 -08007714 if (device == AUDIO_DEVICE_OUT_HDMI
7715 || isDeviceOfModule(devDesc, AUDIO_HARDWARE_MODULE_ID_MSD)) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007716 modifySurroundFormats(devDesc, &formats);
Phil Burk00eeb322016-03-31 12:41:00 -07007717 }
jiabin3e277cc2019-09-10 14:27:34 -07007718 addProfilesForFormats(profiles, formats);
François Gaffie112b0af2015-11-19 16:13:25 +01007719 }
François Gaffie112b0af2015-11-19 16:13:25 +01007720
Mikhail Naganovcf84e592017-12-07 11:25:11 -08007721 for (audio_format_t format : profiles.getSupportedFormats()) {
jiabinf26596b2023-04-12 18:56:39 +00007722 std::optional<ChannelMaskSet> channelMasks;
jiabin06e4bab2019-07-29 10:13:34 -07007723 SampleRateSet samplingRates;
François Gaffie112b0af2015-11-19 16:13:25 +01007724 AudioParameter requestedParameters;
Mikhail Naganov388360c2016-10-17 17:09:41 -07007725 requestedParameters.addInt(String8(AudioParameter::keyFormat), format);
François Gaffie112b0af2015-11-19 16:13:25 +01007726
7727 if (profiles.hasDynamicRateFor(format)) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07007728 reply = mpClientInterface->getParameters(
7729 ioHandle,
7730 requestedParameters.toString() + ";" +
7731 AudioParameter::keyStreamSupportedSamplingRates);
Tomasz Wasilczyk8f36f6e2023-08-15 20:59:35 +00007732 ALOGV("%s: supported sampling rates %s", __FUNCTION__, reply.c_str());
Eric Laurent62e4bc52016-02-02 18:37:28 -08007733 AudioParameter repliedParameters(reply);
7734 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07007735 String8(AudioParameter::keyStreamSupportedSamplingRates), reply) == NO_ERROR) {
Tomasz Wasilczyk8f36f6e2023-08-15 20:59:35 +00007736 samplingRates = samplingRatesFromString(reply.c_str());
jiabinf26596b2023-04-12 18:56:39 +00007737 } else {
7738 samplingRates = devDesc->getAudioProfiles().getSampleRatesFor(format);
François Gaffie112b0af2015-11-19 16:13:25 +01007739 }
7740 }
7741 if (profiles.hasDynamicChannelsFor(format)) {
7742 reply = mpClientInterface->getParameters(ioHandle,
7743 requestedParameters.toString() + ";" +
Mikhail Naganov388360c2016-10-17 17:09:41 -07007744 AudioParameter::keyStreamSupportedChannels);
Tomasz Wasilczyk8f36f6e2023-08-15 20:59:35 +00007745 ALOGV("%s: supported channel masks %s", __FUNCTION__, reply.c_str());
Eric Laurent62e4bc52016-02-02 18:37:28 -08007746 AudioParameter repliedParameters(reply);
7747 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07007748 String8(AudioParameter::keyStreamSupportedChannels), reply) == NO_ERROR) {
Tomasz Wasilczyk8f36f6e2023-08-15 20:59:35 +00007749 channelMasks = channelMasksFromString(reply.c_str());
jiabinf26596b2023-04-12 18:56:39 +00007750 } else {
7751 channelMasks = devDesc->getAudioProfiles().getChannelMasksFor(format);
7752 }
7753 if (channelMasks.has_value() && (device == AUDIO_DEVICE_OUT_HDMI
7754 || isDeviceOfModule(devDesc, AUDIO_HARDWARE_MODULE_ID_MSD))) {
7755 modifySurroundChannelMasks(&channelMasks.value());
François Gaffie112b0af2015-11-19 16:13:25 +01007756 }
7757 }
jiabin3e277cc2019-09-10 14:27:34 -07007758 addDynamicAudioProfileAndSort(
jiabinf26596b2023-04-12 18:56:39 +00007759 profiles, new AudioProfile(
7760 format, channelMasks.value_or(ChannelMaskSet()), samplingRates));
François Gaffie112b0af2015-11-19 16:13:25 +01007761 }
7762}
Eric Laurentd60560a2015-04-10 11:31:20 -07007763
Mikhail Naganovdc769682018-05-04 15:34:08 -07007764status_t AudioPolicyManager::installPatch(const char *caller,
7765 audio_patch_handle_t *patchHandle,
7766 AudioIODescriptorInterface *ioDescriptor,
7767 const struct audio_patch *patch,
7768 int delayMs)
7769{
7770 ssize_t index = mAudioPatches.indexOfKey(
7771 patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE ?
7772 *patchHandle : ioDescriptor->getPatchHandle());
7773 sp<AudioPatch> patchDesc;
7774 status_t status = installPatch(
7775 caller, index, patchHandle, patch, delayMs, mUidCached, &patchDesc);
7776 if (status == NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01007777 ioDescriptor->setPatchHandle(patchDesc->getHandle());
Mikhail Naganovdc769682018-05-04 15:34:08 -07007778 }
7779 return status;
7780}
7781
7782status_t AudioPolicyManager::installPatch(const char *caller,
7783 ssize_t index,
7784 audio_patch_handle_t *patchHandle,
7785 const struct audio_patch *patch,
7786 int delayMs,
7787 uid_t uid,
7788 sp<AudioPatch> *patchDescPtr)
7789{
7790 sp<AudioPatch> patchDesc;
7791 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
7792 if (index >= 0) {
7793 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007794 afPatchHandle = patchDesc->getAfHandle();
Mikhail Naganovdc769682018-05-04 15:34:08 -07007795 }
7796
7797 status_t status = mpClientInterface->createAudioPatch(patch, &afPatchHandle, delayMs);
7798 ALOGV("%s() AF::createAudioPatch returned %d patchHandle %d num_sources %d num_sinks %d",
7799 caller, status, afPatchHandle, patch->num_sources, patch->num_sinks);
7800 if (status == NO_ERROR) {
7801 if (index < 0) {
7802 patchDesc = new AudioPatch(patch, uid);
François Gaffieafd4cea2019-11-18 15:50:22 +01007803 addAudioPatch(patchDesc->getHandle(), patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07007804 } else {
7805 patchDesc->mPatch = *patch;
7806 }
François Gaffieafd4cea2019-11-18 15:50:22 +01007807 patchDesc->setAfHandle(afPatchHandle);
Mikhail Naganovdc769682018-05-04 15:34:08 -07007808 if (patchHandle) {
François Gaffieafd4cea2019-11-18 15:50:22 +01007809 *patchHandle = patchDesc->getHandle();
Mikhail Naganovdc769682018-05-04 15:34:08 -07007810 }
7811 nextAudioPortGeneration();
7812 mpClientInterface->onAudioPatchListUpdate();
7813 }
7814 if (patchDescPtr) *patchDescPtr = patchDesc;
7815 return status;
7816}
7817
jiabinbce0c1d2020-10-05 11:20:18 -07007818bool AudioPolicyManager::areAllActiveTracksRerouted(const sp<SwAudioOutputDescriptor>& output)
7819{
7820 const TrackClientVector activeClients = output->getActiveClients();
7821 if (activeClients.empty()) {
7822 return true;
7823 }
7824 ssize_t index = mAudioPatches.indexOfKey(output->getPatchHandle());
7825 if (index < 0) {
7826 ALOGE("%s, no audio patch found while there are active clients on output %d",
7827 __func__, output->getId());
7828 return false;
7829 }
7830 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
7831 DeviceVector routedDevices;
7832 for (int i = 0; i < patchDesc->mPatch.num_sinks; ++i) {
7833 sp<DeviceDescriptor> device = mAvailableOutputDevices.getDeviceFromId(
7834 patchDesc->mPatch.sinks[i].id);
7835 if (device == nullptr) {
7836 ALOGE("%s, no audio device found with id(%d)",
7837 __func__, patchDesc->mPatch.sinks[i].id);
7838 return false;
7839 }
7840 routedDevices.add(device);
7841 }
7842 for (const auto& client : activeClients) {
jiabin49256852022-03-09 11:21:35 -08007843 if (client->isInvalid()) {
7844 // No need to take care about invalidated clients.
7845 continue;
7846 }
jiabinbce0c1d2020-10-05 11:20:18 -07007847 sp<DeviceDescriptor> preferredDevice =
7848 mAvailableOutputDevices.getDeviceFromId(client->preferredDeviceId());
7849 if (mEngine->getOutputDevicesForAttributes(
7850 client->attributes(), preferredDevice, false) == routedDevices) {
7851 return false;
7852 }
7853 }
7854 return true;
7855}
7856
7857sp<SwAudioOutputDescriptor> AudioPolicyManager::openOutputWithProfileAndDevice(
Eric Laurentb4f42a92022-01-17 17:37:31 +01007858 const sp<IOProfile>& profile, const DeviceVector& devices,
7859 const audio_config_base_t *mixerConfig)
jiabinbce0c1d2020-10-05 11:20:18 -07007860{
7861 for (const auto& device : devices) {
7862 // TODO: This should be checking if the profile supports the device combo.
7863 if (!profile->supportsDevice(device)) {
7864 return nullptr;
7865 }
7866 }
7867 sp<SwAudioOutputDescriptor> desc = new SwAudioOutputDescriptor(profile, mpClientInterface);
7868 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentb4f42a92022-01-17 17:37:31 +01007869 status_t status = desc->open(nullptr /* halConfig */, mixerConfig, devices,
jiabinbce0c1d2020-10-05 11:20:18 -07007870 AUDIO_STREAM_DEFAULT, AUDIO_OUTPUT_FLAG_NONE, &output);
7871 if (status != NO_ERROR) {
7872 return nullptr;
7873 }
7874
7875 // Here is where the out_set_parameters() for card & device gets called
7876 sp<DeviceDescriptor> device = devices.getDeviceForOpening();
7877 const audio_devices_t deviceType = device->type();
7878 const String8 &address = String8(device->address().c_str());
Tomasz Wasilczykfd9ffd12023-08-14 17:56:22 +00007879 if (!address.empty()) {
jiabinbce0c1d2020-10-05 11:20:18 -07007880 char *param = audio_device_address_to_parameter(deviceType, address.c_str());
7881 mpClientInterface->setParameters(output, String8(param));
7882 free(param);
7883 }
7884 updateAudioProfiles(device, output, profile->getAudioProfiles());
7885 if (!profile->hasValidAudioProfile()) {
7886 ALOGW("%s() missing param", __func__);
7887 desc->close();
7888 return nullptr;
7889 } else if (profile->hasDynamicAudioProfile()) {
7890 desc->close();
7891 output = AUDIO_IO_HANDLE_NONE;
7892 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
7893 profile->pickAudioProfile(
7894 config.sample_rate, config.channel_mask, config.format);
7895 config.offload_info.sample_rate = config.sample_rate;
7896 config.offload_info.channel_mask = config.channel_mask;
7897 config.offload_info.format = config.format;
7898
Eric Laurentb4f42a92022-01-17 17:37:31 +01007899 status = desc->open(&config, mixerConfig, devices,
jiabinbce0c1d2020-10-05 11:20:18 -07007900 AUDIO_STREAM_DEFAULT, AUDIO_OUTPUT_FLAG_NONE, &output);
7901 if (status != NO_ERROR) {
7902 return nullptr;
7903 }
7904 }
7905
7906 addOutput(output, desc);
Eric Laurentb4f42a92022-01-17 17:37:31 +01007907
baek.kim -61c20122022-07-27 10:05:32 +00007908 sp<DeviceDescriptor> speaker = mAvailableOutputDevices.getDevice(
7909 AUDIO_DEVICE_OUT_SPEAKER, String8(""), AUDIO_FORMAT_DEFAULT);
7910
jiabinbce0c1d2020-10-05 11:20:18 -07007911 if (audio_is_remote_submix_device(deviceType) && address != "0") {
7912 sp<AudioPolicyMix> policyMix;
7913 if (mPolicyMixes.getAudioPolicyMix(deviceType, address, policyMix) == NO_ERROR) {
7914 policyMix->setOutput(desc);
7915 desc->mPolicyMix = policyMix;
7916 } else {
7917 ALOGW("checkOutputsForDevice() cannot find policy for address %s",
Tomasz Wasilczyk8f36f6e2023-08-15 20:59:35 +00007918 address.c_str());
jiabinbce0c1d2020-10-05 11:20:18 -07007919 }
7920
baek.kim -61c20122022-07-27 10:05:32 +00007921 } else if (hasPrimaryOutput() && speaker != nullptr
7922 && mPrimaryOutput->supportsDevice(speaker) && !desc->supportsDevice(speaker)
Eric Laurentb4f42a92022-01-17 17:37:31 +01007923 && ((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0)) {
7924 // no duplicated output for:
7925 // - direct outputs
7926 // - outputs used by dynamic policy mixes
baek.kim -61c20122022-07-27 10:05:32 +00007927 // - outputs that supports SPEAKER while the primary output does not.
jiabinbce0c1d2020-10-05 11:20:18 -07007928 audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE;
7929
7930 //TODO: configure audio effect output stage here
7931
7932 // open a duplicating output thread for the new output and the primary output
7933 sp<SwAudioOutputDescriptor> dupOutputDesc =
7934 new SwAudioOutputDescriptor(nullptr, mpClientInterface);
7935 status = dupOutputDesc->openDuplicating(mPrimaryOutput, desc, &duplicatedOutput);
7936 if (status == NO_ERROR) {
7937 // add duplicated output descriptor
7938 addOutput(duplicatedOutput, dupOutputDesc);
7939 } else {
7940 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
7941 mPrimaryOutput->mIoHandle, output);
7942 desc->close();
7943 removeOutput(output);
7944 nextAudioPortGeneration();
7945 return nullptr;
7946 }
7947 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02007948 if (mPrimaryOutput == nullptr && profile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
7949 ALOGV("%s(): re-assigning mPrimaryOutput", __func__);
7950 mPrimaryOutput = desc;
7951 }
jiabinbce0c1d2020-10-05 11:20:18 -07007952 return desc;
7953}
7954
Mikhail Naganov1b2a7942017-12-08 10:18:09 -08007955} // namespace android