blob: b7abef9dd0ba4267d0b4ee76a81313fd467bd119 [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
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700276 && device->address() == policyMix->mDeviceAddress.string()) {
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);
Eric Laurent16c66dd2019-05-01 17:54:10 -07001091 const audio_io_handle_t output = selectOutput(outputs);
Eric Laurente552edb2014-03-10 17:42:56 -07001092
François Gaffie11d30102018-11-02 16:09:09 +01001093 ALOGV("getOutput() stream %d selected devices %s, output %d", stream,
1094 devices.toString().c_str(), output);
Eric Laurentf4e63452017-11-06 19:31:46 +00001095 return output;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001096}
1097
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001098status_t AudioPolicyManager::getAudioAttributes(audio_attributes_t *dstAttr,
1099 const audio_attributes_t *srcAttr,
1100 audio_stream_type_t srcStream)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001101{
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001102 if (srcAttr != NULL) {
1103 if (!isValidAttributes(srcAttr)) {
1104 ALOGE("%s invalid attributes: usage=%d content=%d flags=0x%x tags=[%s]",
1105 __func__,
1106 srcAttr->usage, srcAttr->content_type, srcAttr->flags,
1107 srcAttr->tags);
1108 return BAD_VALUE;
1109 }
1110 *dstAttr = *srcAttr;
1111 } else {
1112 if (srcStream < AUDIO_STREAM_MIN || srcStream >= AUDIO_STREAM_PUBLIC_CNT) {
1113 ALOGE("%s: invalid stream type", __func__);
1114 return BAD_VALUE;
1115 }
François Gaffiec005e562018-11-06 15:04:49 +01001116 *dstAttr = mEngine->getAttributesForStreamType(srcStream);
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001117 }
Eric Laurent22fcda22019-05-17 16:28:47 -07001118
1119 // Only honor audibility enforced when required. The client will be
1120 // forced to reconnect if the forced usage changes.
1121 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Mikhail Naganov55773032020-10-01 15:08:13 -07001122 dstAttr->flags = static_cast<audio_flags_mask_t>(
1123 dstAttr->flags & ~AUDIO_FLAG_AUDIBILITY_ENFORCED);
Eric Laurent22fcda22019-05-17 16:28:47 -07001124 }
1125
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001126 return NO_ERROR;
1127}
1128
Kevin Rocard153f92d2018-12-18 18:33:28 -08001129status_t AudioPolicyManager::getOutputForAttrInt(
1130 audio_attributes_t *resultAttr,
1131 audio_io_handle_t *output,
1132 audio_session_t session,
1133 const audio_attributes_t *attr,
1134 audio_stream_type_t *stream,
1135 uid_t uid,
1136 const audio_config_t *config,
1137 audio_output_flags_t *flags,
1138 audio_port_handle_t *selectedDeviceId,
1139 bool *isRequestedDeviceForExclusiveUse,
Eric Laurentc529cf62020-04-17 18:19:10 -07001140 std::vector<sp<AudioPolicyMix>> *secondaryMixes,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001141 output_type_t *outputType,
1142 bool *isSpatialized)
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001143{
François Gaffiec005e562018-11-06 15:04:49 +01001144 DeviceVector outputDevices;
Francois Gaffie716e1432019-01-14 16:58:59 +01001145 const audio_port_handle_t requestedPortId = *selectedDeviceId;
François Gaffie11d30102018-11-02 16:09:09 +01001146 DeviceVector msdDevices = getMsdAudioOutDevices();
François Gaffiec005e562018-11-06 15:04:49 +01001147 const sp<DeviceDescriptor> requestedDevice =
1148 mAvailableOutputDevices.getDeviceFromId(requestedPortId);
1149
Eric Laurent8a1095a2019-11-08 14:44:16 -08001150 *outputType = API_OUTPUT_INVALID;
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001151 *isSpatialized = false;
1152
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001153 status_t status = getAudioAttributes(resultAttr, attr, *stream);
1154 if (status != NO_ERROR) {
1155 return status;
Eric Laurent8f42ea12018-08-08 09:08:25 -07001156 }
Kevin Rocardb99cc752019-03-21 20:52:24 -07001157 if (auto it = mAllowedCapturePolicies.find(uid); it != end(mAllowedCapturePolicies)) {
Mikhail Naganov55773032020-10-01 15:08:13 -07001158 resultAttr->flags = static_cast<audio_flags_mask_t>(resultAttr->flags | it->second);
Kevin Rocardb99cc752019-03-21 20:52:24 -07001159 }
François Gaffiec005e562018-11-06 15:04:49 +01001160 *stream = mEngine->getStreamTypeForAttributes(*resultAttr);
Eric Laurent8f42ea12018-08-08 09:08:25 -07001161
François Gaffiec005e562018-11-06 15:04:49 +01001162 ALOGV("%s() attributes=%s stream=%s session %d selectedDeviceId %d", __func__,
1163 toString(*resultAttr).c_str(), toString(*stream).c_str(), session, requestedPortId);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001164
Kevin Rocard153f92d2018-12-18 18:33:28 -08001165 // The primary output is the explicit routing (eg. setPreferredDevice) if specified,
1166 // otherwise, fallback to the dynamic policies, if none match, query the engine.
1167 // Secondary outputs are always found by dynamic policies as the engine do not support them
Eric Laurentc529cf62020-04-17 18:19:10 -07001168 sp<AudioPolicyMix> primaryMix;
Dean Wheatleyd082f472022-02-04 11:10:48 +11001169 const audio_config_base_t clientConfig = {.sample_rate = config->sample_rate,
1170 .channel_mask = config->channel_mask,
1171 .format = config->format,
1172 };
1173 status = mPolicyMixes.getOutputForAttr(*resultAttr, clientConfig, uid, *flags, primaryMix,
1174 secondaryMixes);
Kevin Rocard94114a22019-04-01 19:38:23 -07001175 if (status != OK) {
1176 return status;
Kevin Rocard153f92d2018-12-18 18:33:28 -08001177 }
Kevin Rocard94114a22019-04-01 19:38:23 -07001178
Kevin Rocard153f92d2018-12-18 18:33:28 -08001179 // Explicit routing is higher priority then any dynamic policy primary output
Eric Laurentc529cf62020-04-17 18:19:10 -07001180 bool usePrimaryOutputFromPolicyMixes = requestedDevice == nullptr && primaryMix != nullptr;
Kevin Rocard153f92d2018-12-18 18:33:28 -08001181
1182 // FIXME: in case of RENDER policy, the output capabilities should be checked
Dean Wheatleyd082f472022-02-04 11:10:48 +11001183 if ((secondaryMixes != nullptr && !secondaryMixes->empty())
1184 && !audio_is_linear_pcm(config->format)) {
1185 ALOGD("%s: rejecting request as secondary mixes only support pcm", __func__);
Kevin Rocard153f92d2018-12-18 18:33:28 -08001186 return BAD_VALUE;
1187 }
1188 if (usePrimaryOutputFromPolicyMixes) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001189 sp<DeviceDescriptor> deviceDesc =
1190 mAvailableOutputDevices.getDevice(primaryMix->mDeviceType,
1191 primaryMix->mDeviceAddress,
1192 AUDIO_FORMAT_DEFAULT);
1193 sp<SwAudioOutputDescriptor> policyDesc = primaryMix->getOutput();
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001194 bool tryDirectForFlags = policyDesc == nullptr ||
1195 (policyDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT);
1196 // if a direct output can be opened to deliver the track's multi-channel content to the
1197 // output rather than being downmixed by the primary output, then use this direct
1198 // output by by-passing the primary mix if possible, otherwise fall-through to primary
1199 // mix.
1200 bool tryDirectForChannelMask = policyDesc != nullptr
1201 && (audio_channel_count_from_out_mask(policyDesc->getConfig().channel_mask) <
1202 audio_channel_count_from_out_mask(config->channel_mask));
1203 if (deviceDesc != nullptr && (tryDirectForFlags || tryDirectForChannelMask)) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001204 audio_io_handle_t newOutput;
1205 status = openDirectOutput(
1206 *stream, session, config,
1207 (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT),
1208 DeviceVector(deviceDesc), &newOutput);
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001209 if (status == NO_ERROR) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001210 policyDesc = mOutputs.valueFor(newOutput);
1211 primaryMix->setOutput(policyDesc);
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001212 } else if (tryDirectForFlags) {
1213 policyDesc = nullptr;
1214 } // otherwise use primary if available.
Eric Laurentc529cf62020-04-17 18:19:10 -07001215 }
1216 if (policyDesc != nullptr) {
1217 policyDesc->mPolicyMix = primaryMix;
1218 *output = policyDesc->mIoHandle;
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08001219 *selectedDeviceId = deviceDesc != 0 ? deviceDesc->getId() : AUDIO_PORT_HANDLE_NONE;
Eric Laurent8a1095a2019-11-08 14:44:16 -08001220
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08001221 ALOGV("getOutputForAttr() returns output %d", *output);
1222 if (resultAttr->usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
1223 *outputType = API_OUT_MIX_PLAYBACK;
1224 } else {
1225 *outputType = API_OUTPUT_LEGACY;
1226 }
1227 return NO_ERROR;
Eric Laurent8a1095a2019-11-08 14:44:16 -08001228 }
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001229 }
François Gaffiec005e562018-11-06 15:04:49 +01001230 // Virtual sources must always be dynamicaly or explicitly routed
1231 if (resultAttr->usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
1232 ALOGW("getOutputForAttr() no policy mix found for usage AUDIO_USAGE_VIRTUAL_SOURCE");
1233 return BAD_VALUE;
1234 }
1235 // explicit routing managed by getDeviceForStrategy in APM is now handled by engine
1236 // in order to let the choice of the order to future vendor engine
1237 outputDevices = mEngine->getOutputDevicesForAttributes(*resultAttr, requestedDevice, false);
Scott Randolph7b1fd232018-06-18 15:33:03 -07001238
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001239 if ((resultAttr->flags & AUDIO_FLAG_HW_AV_SYNC) != 0) {
Nadav Bar766fb022018-01-07 12:18:03 +02001240 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
Eric Laurent93c3d412014-08-01 14:48:35 -07001241 }
1242
Nadav Barb2f18162018-07-18 13:01:53 +03001243 // Set incall music only if device was explicitly set, and fallback to the device which is
1244 // chosen by the engine if not.
1245 // FIXME: provide a more generic approach which is not device specific and move this back
1246 // to getOutputForDevice.
Nadav Bar20919492018-11-20 10:20:51 +02001247 // TODO: Remove check of AUDIO_STREAM_MUSIC once migration is completed on the app side.
jiabin9a3361e2019-10-01 09:38:30 -07001248 if (outputDevices.onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_TELEPHONY_TX) &&
François Gaffiec005e562018-11-06 15:04:49 +01001249 (*stream == AUDIO_STREAM_MUSIC || resultAttr->usage == AUDIO_USAGE_VOICE_COMMUNICATION) &&
Nadav Barb2f18162018-07-18 13:01:53 +03001250 audio_is_linear_pcm(config->format) &&
Eric Laurent74b71512019-11-06 17:21:57 -08001251 isCallAudioAccessible()) {
Francois Gaffie716e1432019-01-14 16:58:59 +01001252 if (requestedPortId != AUDIO_PORT_HANDLE_NONE) {
Nadav Barb2f18162018-07-18 13:01:53 +03001253 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_INCALL_MUSIC;
François Gaffief579db52018-11-13 11:25:16 +01001254 *isRequestedDeviceForExclusiveUse = true;
Nadav Barb2f18162018-07-18 13:01:53 +03001255 }
1256 }
1257
François Gaffiec005e562018-11-06 15:04:49 +01001258 ALOGV("%s() device %s, sampling rate %d, format %#x, channel mask %#x, flags %#x stream %s",
1259 __func__, outputDevices.toString().c_str(), config->sample_rate, config->format,
1260 config->channel_mask, *flags, toString(*stream).c_str());
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001261
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001262 *output = AUDIO_IO_HANDLE_NONE;
François Gaffie11d30102018-11-02 16:09:09 +01001263 if (!msdDevices.isEmpty()) {
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001264 *output = getOutputForDevices(msdDevices, session, resultAttr, config, flags, isSpatialized);
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001265 if (*output != AUDIO_IO_HANDLE_NONE && setMsdOutputPatches(&outputDevices) == NO_ERROR) {
François Gaffiec005e562018-11-06 15:04:49 +01001266 ALOGV("%s() Using MSD devices %s instead of devices %s",
1267 __func__, msdDevices.toString().c_str(), outputDevices.toString().c_str());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001268 } else {
1269 *output = AUDIO_IO_HANDLE_NONE;
1270 }
1271 }
1272 if (*output == AUDIO_IO_HANDLE_NONE) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001273 *output = getOutputForDevices(outputDevices, session, resultAttr, config,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001274 flags, isSpatialized, resultAttr->flags & AUDIO_FLAG_MUTE_HAPTIC);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001275 }
Eric Laurente83b55d2014-11-14 10:06:21 -08001276 if (*output == AUDIO_IO_HANDLE_NONE) {
1277 return INVALID_OPERATION;
1278 }
Paul McLeanaa981192015-03-21 09:55:15 -07001279
François Gaffiec005e562018-11-06 15:04:49 +01001280 *selectedDeviceId = getFirstDeviceId(outputDevices);
Michael Chan6fb34492020-12-08 15:44:49 +11001281 for (auto &outputDevice : outputDevices) {
Mikhail Naganovb0fbc1b2023-04-28 13:06:32 -07001282 if (outputDevice->getId() == mConfig->getDefaultOutputDevice()->getId()) {
Michael Chan6fb34492020-12-08 15:44:49 +11001283 *selectedDeviceId = outputDevice->getId();
1284 break;
1285 }
1286 }
Eric Laurent2ac76942017-06-22 17:17:09 -07001287
Eric Laurent8a1095a2019-11-08 14:44:16 -08001288 if (outputDevices.onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_TELEPHONY_TX)) {
1289 *outputType = API_OUTPUT_TELEPHONY_TX;
1290 } else {
1291 *outputType = API_OUTPUT_LEGACY;
1292 }
1293
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001294 ALOGV("%s returns output %d selectedDeviceId %d", __func__, *output, *selectedDeviceId);
1295
1296 return NO_ERROR;
1297}
1298
1299status_t AudioPolicyManager::getOutputForAttr(const audio_attributes_t *attr,
1300 audio_io_handle_t *output,
1301 audio_session_t session,
1302 audio_stream_type_t *stream,
Svet Ganov3e5f14f2021-05-13 22:51:08 +00001303 const AttributionSourceState& attributionSource,
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001304 const audio_config_t *config,
1305 audio_output_flags_t *flags,
1306 audio_port_handle_t *selectedDeviceId,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001307 audio_port_handle_t *portId,
Eric Laurent8a1095a2019-11-08 14:44:16 -08001308 std::vector<audio_io_handle_t> *secondaryOutputs,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001309 output_type_t *outputType,
1310 bool *isSpatialized)
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001311{
1312 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
1313 if (*portId != AUDIO_PORT_HANDLE_NONE) {
1314 return INVALID_OPERATION;
1315 }
Philip P. Moltmannbda45752020-07-17 16:41:18 -07001316 const uid_t uid = VALUE_OR_RETURN_STATUS(
Svet Ganov3e5f14f2021-05-13 22:51:08 +00001317 aidl2legacy_int32_t_uid_t(attributionSource.uid));
Francois Gaffie716e1432019-01-14 16:58:59 +01001318 const audio_port_handle_t requestedPortId = *selectedDeviceId;
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001319 audio_attributes_t resultAttr;
François Gaffief579db52018-11-13 11:25:16 +01001320 bool isRequestedDeviceForExclusiveUse = false;
Eric Laurentc529cf62020-04-17 18:19:10 -07001321 std::vector<sp<AudioPolicyMix>> secondaryMixes;
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001322 const sp<DeviceDescriptor> requestedDevice =
1323 mAvailableOutputDevices.getDeviceFromId(requestedPortId);
1324
1325 // Prevent from storing invalid requested device id in clients
1326 const audio_port_handle_t sanitizedRequestedPortId =
1327 requestedDevice != nullptr ? requestedPortId : AUDIO_PORT_HANDLE_NONE;
1328 *selectedDeviceId = sanitizedRequestedPortId;
1329
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001330 status_t status = getOutputForAttrInt(&resultAttr, output, session, attr, stream, uid,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001331 config, flags, selectedDeviceId, &isRequestedDeviceForExclusiveUse,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001332 secondaryOutputs != nullptr ? &secondaryMixes : nullptr, outputType, isSpatialized);
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001333 if (status != NO_ERROR) {
1334 return status;
1335 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001336 std::vector<wp<SwAudioOutputDescriptor>> weakSecondaryOutputDescs;
Eric Laurentc529cf62020-04-17 18:19:10 -07001337 if (secondaryOutputs != nullptr) {
1338 for (auto &secondaryMix : secondaryMixes) {
1339 sp<SwAudioOutputDescriptor> outputDesc = secondaryMix->getOutput();
1340 if (outputDesc != nullptr &&
1341 outputDesc->mIoHandle != AUDIO_IO_HANDLE_NONE) {
1342 secondaryOutputs->push_back(outputDesc->mIoHandle);
1343 weakSecondaryOutputDescs.push_back(outputDesc);
1344 }
1345 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001346 }
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001347
Eric Laurent8fc147b2018-07-22 19:13:55 -07001348 audio_config_base_t clientConfig = {.sample_rate = config->sample_rate,
Nick Desaulniersa30e3202019-10-18 13:38:23 -07001349 .channel_mask = config->channel_mask,
Eric Laurent8fc147b2018-07-22 19:13:55 -07001350 .format = config->format,
Nick Desaulniersa30e3202019-10-18 13:38:23 -07001351 };
jiabin4ef93452019-09-10 14:29:54 -07001352 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurent8f42ea12018-08-08 09:08:25 -07001353
Eric Laurentc209fe42020-06-05 18:11:23 -07001354 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(*output);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001355 sp<TrackClientDescriptor> clientDesc =
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001356 new TrackClientDescriptor(*portId, uid, session, resultAttr, clientConfig,
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001357 sanitizedRequestedPortId, *stream,
François Gaffiec005e562018-11-06 15:04:49 +01001358 mEngine->getProductStrategyForAttributes(resultAttr),
François Gaffieaaac0fd2018-11-22 17:56:39 +01001359 toVolumeSource(resultAttr),
Kevin Rocard153f92d2018-12-18 18:33:28 -08001360 *flags, isRequestedDeviceForExclusiveUse,
Eric Laurentc209fe42020-06-05 18:11:23 -07001361 std::move(weakSecondaryOutputDescs),
1362 outputDesc->mPolicyMix);
Andy Hung39efb7a2018-09-26 15:39:28 -07001363 outputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001364
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001365 ALOGV("%s() returns output %d requestedPortId %d selectedDeviceId %d for port ID %d", __func__,
1366 *output, requestedPortId, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07001367
Eric Laurente83b55d2014-11-14 10:06:21 -08001368 return NO_ERROR;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001369}
1370
Eric Laurentc529cf62020-04-17 18:19:10 -07001371status_t AudioPolicyManager::openDirectOutput(audio_stream_type_t stream,
1372 audio_session_t session,
1373 const audio_config_t *config,
1374 audio_output_flags_t flags,
1375 const DeviceVector &devices,
1376 audio_io_handle_t *output) {
1377
1378 *output = AUDIO_IO_HANDLE_NONE;
1379
1380 // skip direct output selection if the request can obviously be attached to a mixed output
1381 // and not explicitly requested
1382 if (((flags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
1383 audio_is_linear_pcm(config->format) && config->sample_rate <= SAMPLE_RATE_HZ_MAX &&
1384 audio_channel_count_from_out_mask(config->channel_mask) <= 2) {
1385 return NAME_NOT_FOUND;
1386 }
1387
1388 // Do not allow offloading if one non offloadable effect is enabled or MasterMono is enabled.
1389 // This prevents creating an offloaded track and tearing it down immediately after start
1390 // when audioflinger detects there is an active non offloadable effect.
1391 // FIXME: We should check the audio session here but we do not have it in this context.
1392 // This may prevent offloading in rare situations where effects are left active by apps
1393 // in the background.
1394 sp<IOProfile> profile;
1395 if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) ||
1396 !(mEffects.isNonOffloadableEffectEnabled() || mMasterMono)) {
1397 profile = getProfileForOutput(
1398 devices, config->sample_rate, config->format, config->channel_mask,
1399 flags, true /* directOnly */);
1400 }
1401
1402 if (profile == nullptr) {
1403 return NAME_NOT_FOUND;
1404 }
1405
1406 // exclusive outputs for MMAP and Offload are enforced by different session ids.
1407 for (size_t i = 0; i < mOutputs.size(); i++) {
1408 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
1409 if (!desc->isDuplicated() && (profile == desc->mProfile)) {
1410 // reuse direct output if currently open by the same client
1411 // and configured with same parameters
1412 if ((config->sample_rate == desc->getSamplingRate()) &&
1413 (config->format == desc->getFormat()) &&
1414 (config->channel_mask == desc->getChannelMask()) &&
1415 (session == desc->mDirectClientSession)) {
1416 desc->mDirectOpenCount++;
Eric Laurentfecbceb2021-02-09 14:46:43 +01001417 ALOGV("%s reusing direct output %d for session %d", __func__,
Eric Laurentc529cf62020-04-17 18:19:10 -07001418 mOutputs.keyAt(i), session);
1419 *output = mOutputs.keyAt(i);
1420 return NO_ERROR;
1421 }
1422 }
1423 }
1424
1425 if (!profile->canOpenNewIo()) {
1426 return NAME_NOT_FOUND;
1427 }
1428
1429 sp<SwAudioOutputDescriptor> outputDesc =
1430 new SwAudioOutputDescriptor(profile, mpClientInterface);
1431
Michael Chan6fb34492020-12-08 15:44:49 +11001432 // An MSD patch may be using the only output stream that can service this request. Release
1433 // all MSD patches to prioritize this request over any active output on MSD.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001434 releaseMsdOutputPatches(devices);
Eric Laurentc529cf62020-04-17 18:19:10 -07001435
Eric Laurentf1f22e72021-07-13 14:04:14 +02001436 status_t status =
1437 outputDesc->open(config, nullptr /* mixerConfig */, devices, stream, flags, output);
Eric Laurentc529cf62020-04-17 18:19:10 -07001438
1439 // only accept an output with the requested parameters
1440 if (status != NO_ERROR ||
1441 (config->sample_rate != 0 && config->sample_rate != outputDesc->getSamplingRate()) ||
1442 (config->format != AUDIO_FORMAT_DEFAULT && config->format != outputDesc->getFormat()) ||
1443 (config->channel_mask != 0 && config->channel_mask != outputDesc->getChannelMask())) {
1444 ALOGV("%s failed opening direct output: output %d sample rate %d %d,"
1445 "format %d %d, channel mask %04x %04x", __func__, *output, config->sample_rate,
1446 outputDesc->getSamplingRate(), config->format, outputDesc->getFormat(),
1447 config->channel_mask, outputDesc->getChannelMask());
1448 if (*output != AUDIO_IO_HANDLE_NONE) {
1449 outputDesc->close();
1450 }
1451 // fall back to mixer output if possible when the direct output could not be open
1452 if (audio_is_linear_pcm(config->format) &&
1453 config->sample_rate <= SAMPLE_RATE_HZ_MAX) {
1454 return NAME_NOT_FOUND;
1455 }
1456 *output = AUDIO_IO_HANDLE_NONE;
1457 return BAD_VALUE;
1458 }
1459 outputDesc->mDirectOpenCount = 1;
1460 outputDesc->mDirectClientSession = session;
1461
1462 addOutput(*output, outputDesc);
1463 mPreviousOutputs = mOutputs;
1464 ALOGV("%s returns new direct output %d", __func__, *output);
1465 mpClientInterface->onAudioPortListUpdate();
1466 return NO_ERROR;
1467}
1468
François Gaffie11d30102018-11-02 16:09:09 +01001469audio_io_handle_t AudioPolicyManager::getOutputForDevices(
1470 const DeviceVector &devices,
Kevin Rocard169753c2017-03-06 14:18:23 -08001471 audio_session_t session,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001472 const audio_attributes_t *attr,
Eric Laurentfe231122017-11-17 17:48:06 -08001473 const audio_config_t *config,
jiabine375d412019-02-26 12:54:53 -08001474 audio_output_flags_t *flags,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001475 bool *isSpatialized,
jiabine375d412019-02-26 12:54:53 -08001476 bool forceMutingHaptic)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001477{
Andy Hungc88b0642018-04-27 15:42:35 -07001478 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001479
jiabine375d412019-02-26 12:54:53 -08001480 // Discard haptic channel mask when forcing muting haptic channels.
1481 audio_channel_mask_t channelMask = forceMutingHaptic
Mikhail Naganov55773032020-10-01 15:08:13 -07001482 ? static_cast<audio_channel_mask_t>(config->channel_mask & ~AUDIO_CHANNEL_HAPTIC_ALL)
1483 : config->channel_mask;
jiabine375d412019-02-26 12:54:53 -08001484
Eric Laurente552edb2014-03-10 17:42:56 -07001485 // open a direct output if required by specified parameters
1486 //force direct flag if offload flag is set: offloading implies a direct output stream
1487 // and all common behaviors are driven by checking only the direct flag
1488 // this should normally be set appropriately in the policy configuration file
Nadav Bar766fb022018-01-07 12:18:03 +02001489 if ((*flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1490 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurente552edb2014-03-10 17:42:56 -07001491 }
Nadav Bar766fb022018-01-07 12:18:03 +02001492 if ((*flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
1493 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent93c3d412014-08-01 14:48:35 -07001494 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001495
1496 audio_stream_type_t stream = mEngine->getStreamTypeForAttributes(*attr);
1497
Eric Laurente83b55d2014-11-14 10:06:21 -08001498 // only allow deep buffering for music stream type
1499 if (stream != AUDIO_STREAM_MUSIC) {
Nadav Bar766fb022018-01-07 12:18:03 +02001500 *flags = (audio_output_flags_t)(*flags &~AUDIO_OUTPUT_FLAG_DEEP_BUFFER);
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -07001501 } else if (/* stream == AUDIO_STREAM_MUSIC && */
Nadav Bar766fb022018-01-07 12:18:03 +02001502 *flags == AUDIO_OUTPUT_FLAG_NONE &&
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -07001503 property_get_bool("audio.deep_buffer.media", false /* default_value */)) {
1504 // use DEEP_BUFFER as default output for music stream type
Nadav Bar766fb022018-01-07 12:18:03 +02001505 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
Eric Laurente83b55d2014-11-14 10:06:21 -08001506 }
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -07001507 if (stream == AUDIO_STREAM_TTS) {
Nadav Bar766fb022018-01-07 12:18:03 +02001508 *flags = AUDIO_OUTPUT_FLAG_TTS;
Haynes Mathew George84c621e2017-04-25 11:41:50 -07001509 } else if (stream == AUDIO_STREAM_VOICE_CALL &&
Nadav Bar20919492018-11-20 10:20:51 +02001510 audio_is_linear_pcm(config->format) &&
1511 (*flags & AUDIO_OUTPUT_FLAG_INCALL_MUSIC) == 0) {
Nadav Bar766fb022018-01-07 12:18:03 +02001512 *flags = (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_VOIP_RX |
Haynes Mathew George84c621e2017-04-25 11:41:50 -07001513 AUDIO_OUTPUT_FLAG_DIRECT);
1514 ALOGV("Set VoIP and Direct output flags for PCM format");
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -07001515 }
Eric Laurente552edb2014-03-10 17:42:56 -07001516
Carter Hsua3abb402021-10-26 11:11:20 +08001517 // Attach the Ultrasound flag for the AUDIO_CONTENT_TYPE_ULTRASOUND
1518 if (attr->content_type == AUDIO_CONTENT_TYPE_ULTRASOUND) {
1519 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_ULTRASOUND);
1520 }
1521
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001522 *isSpatialized = false;
Eric Laurentfa0f6742021-08-17 18:39:44 +02001523 if (mSpatializerOutput != nullptr
Andy Hung9dd1a5b2022-05-10 15:39:39 -07001524 && canBeSpatializedInt(attr, config, devices.toTypeAddrVector())) {
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001525 *isSpatialized = true;
Eric Laurentfa0f6742021-08-17 18:39:44 +02001526 return mSpatializerOutput->mIoHandle;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001527 }
1528
Eric Laurentc529cf62020-04-17 18:19:10 -07001529 audio_config_t directConfig = *config;
1530 directConfig.channel_mask = channelMask;
1531 status_t status = openDirectOutput(stream, session, &directConfig, *flags, devices, &output);
1532 if (status != NAME_NOT_FOUND) {
Eric Laurente552edb2014-03-10 17:42:56 -07001533 return output;
1534 }
1535
Eric Laurent14cbfca2016-03-17 09:42:16 -07001536 // A request for HW A/V sync cannot fallback to a mixed output because time
1537 // stamps are embedded in audio data
Phil Burk2d059932018-02-15 15:55:11 -08001538 if ((*flags & (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ)) != 0) {
Eric Laurent14cbfca2016-03-17 09:42:16 -07001539 return AUDIO_IO_HANDLE_NONE;
1540 }
Pierre Couillaude73496b2023-03-06 16:19:05 +00001541 // A request for Tuner cannot fallback to a mixed output
1542 if ((directConfig.offload_info.content_id || directConfig.offload_info.sync_id)) {
1543 return AUDIO_IO_HANDLE_NONE;
1544 }
Eric Laurent14cbfca2016-03-17 09:42:16 -07001545
Eric Laurente552edb2014-03-10 17:42:56 -07001546 // ignoring channel mask due to downmix capability in mixer
1547
1548 // open a non direct output
1549
1550 // for non direct outputs, only PCM is supported
Eric Laurentfe231122017-11-17 17:48:06 -08001551 if (audio_is_linear_pcm(config->format)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001552 // get which output is suitable for the specified stream. The actual
1553 // routing change will happen when startOutput() will be called
François Gaffie11d30102018-11-02 16:09:09 +01001554 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07001555
Eric Laurent8838a382014-09-08 16:44:28 -07001556 // at this stage we should ignore the DIRECT flag as no direct output could be found earlier
Nadav Bar766fb022018-01-07 12:18:03 +02001557 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
jiabinebb6af42020-06-09 17:31:17 -07001558 output = selectOutput(
1559 outputs, *flags, config->format, channelMask, config->sample_rate, session);
Eric Laurente552edb2014-03-10 17:42:56 -07001560 }
François Gaffie11d30102018-11-02 16:09:09 +01001561 ALOGW_IF((output == 0), "getOutputForDevices() could not find output for stream %d, "
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001562 "sampling rate %d, format %#x, channels %#x, flags %#x",
jiabine375d412019-02-26 12:54:53 -08001563 stream, config->sample_rate, config->format, channelMask, *flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001564
Eric Laurente552edb2014-03-10 17:42:56 -07001565 return output;
1566}
1567
Mikhail Naganovf02f3672018-11-09 12:44:16 -08001568sp<DeviceDescriptor> AudioPolicyManager::getMsdAudioInDevice() const {
François Gaffie11d30102018-11-02 16:09:09 +01001569 auto msdInDevices = mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1570 mAvailableInputDevices);
1571 return msdInDevices.isEmpty()? nullptr : msdInDevices.itemAt(0);
1572}
1573
1574DeviceVector AudioPolicyManager::getMsdAudioOutDevices() const {
1575 return mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1576 mAvailableOutputDevices);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001577}
1578
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001579const AudioPatchCollection AudioPolicyManager::getMsdOutputPatches() const {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001580 AudioPatchCollection msdPatches;
Mikhail Naganov86112352018-10-04 09:02:49 -07001581 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1582 if (msdModule != 0) {
1583 for (size_t i = 0; i < mAudioPatches.size(); ++i) {
1584 sp<AudioPatch> patch = mAudioPatches.valueAt(i);
1585 for (size_t j = 0; j < patch->mPatch.num_sources; ++j) {
1586 const struct audio_port_config *source = &patch->mPatch.sources[j];
1587 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
1588 source->ext.device.hw_module == msdModule->getHandle()) {
François Gaffieafd4cea2019-11-18 15:50:22 +01001589 msdPatches.addAudioPatch(patch->getHandle(), patch);
Mikhail Naganov86112352018-10-04 09:02:49 -07001590 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001591 }
1592 }
1593 }
1594 return msdPatches;
1595}
1596
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02001597bool AudioPolicyManager::isMsdPatch(const audio_patch_handle_t &handle) const {
1598 ssize_t index = mAudioPatches.indexOfKey(handle);
1599 if (index < 0) {
1600 return false;
1601 }
1602 const sp<AudioPatch> patch = mAudioPatches.valueAt(index);
1603 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1604 if (msdModule == nullptr) {
1605 return false;
1606 }
1607 const struct audio_port_config *sink = &patch->mPatch.sinks[0];
1608 if (getMsdAudioOutDevices().contains(mAvailableOutputDevices.getDeviceFromId(sink->id))) {
1609 return true;
1610 }
1611 index = getMsdOutputPatches().indexOfKey(handle);
1612 if (index < 0) {
1613 return false;
1614 }
1615 return true;
1616}
1617
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001618status_t AudioPolicyManager::getMsdProfiles(bool hwAvSync,
1619 const InputProfileCollection &inputProfiles,
1620 const OutputProfileCollection &outputProfiles,
1621 const sp<DeviceDescriptor> &sourceDevice,
1622 const sp<DeviceDescriptor> &sinkDevice,
1623 AudioProfileVector& sourceProfiles,
1624 AudioProfileVector& sinkProfiles) const {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001625 if (inputProfiles.isEmpty()) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001626 ALOGE("%s() no input profiles for source module", __func__);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001627 return NO_INIT;
1628 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001629 if (outputProfiles.isEmpty()) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001630 ALOGE("%s() no output profiles for sink module", __func__);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001631 return NO_INIT;
1632 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001633 for (const auto &inProfile : inputProfiles) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001634 if (hwAvSync == ((inProfile->getFlags() & AUDIO_INPUT_FLAG_HW_AV_SYNC) != 0) &&
1635 inProfile->supportsDevice(sourceDevice)) {
1636 appendAudioProfiles(sourceProfiles, inProfile->getAudioProfiles());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001637 }
1638 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001639 for (const auto &outProfile : outputProfiles) {
Michael Chan6fb34492020-12-08 15:44:49 +11001640 if (hwAvSync == ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) &&
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001641 outProfile->supportsDevice(sinkDevice)) {
1642 appendAudioProfiles(sinkProfiles, outProfile->getAudioProfiles());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001643 }
1644 }
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001645 return NO_ERROR;
1646}
1647
1648status_t AudioPolicyManager::getBestMsdConfig(bool hwAvSync,
1649 const AudioProfileVector &sourceProfiles, const AudioProfileVector &sinkProfiles,
1650 audio_port_config *sourceConfig, audio_port_config *sinkConfig) const
1651{
Dean Wheatley16809da2022-12-09 14:55:46 +11001652 // Compressed formats for MSD module, ordered from most preferred to least preferred.
1653 static const std::vector<audio_format_t> formatsOrder = {{
1654 AUDIO_FORMAT_IEC60958, AUDIO_FORMAT_MAT_2_1, AUDIO_FORMAT_MAT_2_0, AUDIO_FORMAT_E_AC3,
1655 AUDIO_FORMAT_AC3, AUDIO_FORMAT_PCM_16_BIT }};
1656 static const std::vector<audio_channel_mask_t> channelMasksOrder = [](){
1657 // Channel position masks for MSD module, 3D > 2D > 1D ordering (most preferred to least
1658 // preferred).
1659 std::vector<audio_channel_mask_t> masks = {{
1660 AUDIO_CHANNEL_OUT_3POINT1POINT2, AUDIO_CHANNEL_OUT_3POINT0POINT2,
1661 AUDIO_CHANNEL_OUT_2POINT1POINT2, AUDIO_CHANNEL_OUT_2POINT0POINT2,
1662 AUDIO_CHANNEL_OUT_5POINT1, AUDIO_CHANNEL_OUT_STEREO }};
1663 // insert index masks (higher counts most preferred) as preferred over position masks
1664 for (int i = 1; i <= AUDIO_CHANNEL_COUNT_MAX; i++) {
1665 masks.insert(
1666 masks.begin(), audio_channel_mask_for_index_assignment_from_count(i));
1667 }
1668 return masks;
1669 }();
1670
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001671 struct audio_config_base bestSinkConfig;
Dean Wheatley16809da2022-12-09 14:55:46 +11001672 status_t result = findBestMatchingOutputConfig(sourceProfiles, sinkProfiles, formatsOrder,
1673 channelMasksOrder, true /*preferHigherSamplingRates*/, bestSinkConfig);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001674 if (result != NO_ERROR) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001675 ALOGD("%s() no matching config found for sink, hwAvSync: %d",
1676 __func__, hwAvSync);
Greg Kaiser83289652018-07-30 06:13:57 -07001677 return result;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001678 }
1679 sinkConfig->sample_rate = bestSinkConfig.sample_rate;
1680 sinkConfig->channel_mask = bestSinkConfig.channel_mask;
1681 sinkConfig->format = bestSinkConfig.format;
1682 // For encoded streams force direct flag to prevent downstream mixing.
1683 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1684 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_DIRECT);
Dean Wheatley5c9f0832019-11-21 13:39:31 +11001685 if (audio_is_iec61937_compatible(sinkConfig->format)) {
1686 // For formats compatible with IEC61937 encapsulation, assume that
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001687 // the input is IEC61937 framed (for proportional buffer sizing).
Dean Wheatley5c9f0832019-11-21 13:39:31 +11001688 // Add the AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO flag so downstream HAL can distinguish between
1689 // raw and IEC61937 framed streams.
1690 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1691 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO);
1692 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001693 sourceConfig->sample_rate = bestSinkConfig.sample_rate;
1694 // Specify exact channel mask to prevent guessing by bit count in PatchPanel.
Dean Wheatley16809da2022-12-09 14:55:46 +11001695 sourceConfig->channel_mask =
1696 audio_channel_mask_get_representation(bestSinkConfig.channel_mask)
1697 == AUDIO_CHANNEL_REPRESENTATION_INDEX ?
1698 bestSinkConfig.channel_mask : audio_channel_mask_out_to_in(bestSinkConfig.channel_mask);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001699 sourceConfig->format = bestSinkConfig.format;
1700 // Copy input stream directly without any processing (e.g. resampling).
1701 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1702 sourceConfig->flags.input | AUDIO_INPUT_FLAG_DIRECT);
1703 if (hwAvSync) {
1704 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1705 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
1706 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1707 sourceConfig->flags.input | AUDIO_INPUT_FLAG_HW_AV_SYNC);
1708 }
1709 const unsigned int config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE |
1710 AUDIO_PORT_CONFIG_CHANNEL_MASK | AUDIO_PORT_CONFIG_FORMAT | AUDIO_PORT_CONFIG_FLAGS;
1711 sinkConfig->config_mask |= config_mask;
1712 sourceConfig->config_mask |= config_mask;
1713 return NO_ERROR;
1714}
1715
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001716PatchBuilder AudioPolicyManager::buildMsdPatch(bool msdIsSource,
1717 const sp<DeviceDescriptor> &device) const
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001718{
1719 PatchBuilder patchBuilder;
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001720 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1721 ALOG_ASSERT(msdModule != nullptr, "MSD module not available");
1722 sp<HwModule> deviceModule = mHwModules.getModuleForDevice(device, AUDIO_FORMAT_DEFAULT);
1723 if (deviceModule == nullptr) {
1724 ALOGE("%s() unable to get module for %s", __func__, device->toString().c_str());
1725 return patchBuilder;
1726 }
1727 const InputProfileCollection inputProfiles = msdIsSource ?
1728 msdModule->getInputProfiles() : deviceModule->getInputProfiles();
1729 const OutputProfileCollection outputProfiles = msdIsSource ?
1730 deviceModule->getOutputProfiles() : msdModule->getOutputProfiles();
1731
1732 const sp<DeviceDescriptor> sourceDevice = msdIsSource ? getMsdAudioInDevice() : device;
1733 const sp<DeviceDescriptor> sinkDevice = msdIsSource ?
1734 device : getMsdAudioOutDevices().itemAt(0);
1735 patchBuilder.addSource(sourceDevice).addSink(sinkDevice);
1736
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001737 audio_port_config sourceConfig = patchBuilder.patch()->sources[0];
1738 audio_port_config sinkConfig = patchBuilder.patch()->sinks[0];
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001739 AudioProfileVector sourceProfiles;
1740 AudioProfileVector sinkProfiles;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001741 // TODO: Figure out whether MSD module has HW_AV_SYNC flag set in the AP config file.
1742 // For now, we just forcefully try with HwAvSync first.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001743 for (auto hwAvSync : { true, false }) {
1744 if (getMsdProfiles(hwAvSync, inputProfiles, outputProfiles, sourceDevice, sinkDevice,
1745 sourceProfiles, sinkProfiles) != NO_ERROR) {
1746 continue;
1747 }
1748 if (getBestMsdConfig(hwAvSync, sourceProfiles, sinkProfiles, &sourceConfig,
1749 &sinkConfig) == NO_ERROR) {
1750 // Found a matching config. Re-create PatchBuilder with this config.
1751 return (PatchBuilder()).addSource(sourceConfig).addSink(sinkConfig);
1752 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001753 }
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001754 ALOGV("%s() no matching config found. Fall through to default PCM patch"
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001755 " supporting PCM format conversion.", __func__);
1756 return patchBuilder;
1757}
1758
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001759status_t AudioPolicyManager::setMsdOutputPatches(const DeviceVector *outputDevices) {
Michael Chan6fb34492020-12-08 15:44:49 +11001760 DeviceVector devices;
1761 if (outputDevices != nullptr && outputDevices->size() > 0) {
1762 devices.add(*outputDevices);
1763 } else {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001764 // Use media strategy for unspecified output device. This should only
1765 // occur on checkForDeviceAndOutputChanges(). Device connection events may
1766 // therefore invalidate explicit routing requests.
Michael Chan6fb34492020-12-08 15:44:49 +11001767 devices = mEngine->getOutputDevicesForAttributes(
François Gaffiec005e562018-11-06 15:04:49 +01001768 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
Michael Chan6fb34492020-12-08 15:44:49 +11001769 LOG_ALWAYS_FATAL_IF(devices.isEmpty(), "no output device to set MSD patch");
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001770 }
Michael Chan6fb34492020-12-08 15:44:49 +11001771 std::vector<PatchBuilder> patchesToCreate;
1772 for (auto i = 0u; i < devices.size(); ++i) {
1773 ALOGV("%s() for device %s", __func__, devices[i]->toString().c_str());
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001774 patchesToCreate.push_back(buildMsdPatch(true /*msdIsSource*/, devices[i]));
Michael Chan6fb34492020-12-08 15:44:49 +11001775 }
1776 // Retain only the MSD patches associated with outputDevices request.
1777 // Tear down the others, and create new ones as needed.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001778 AudioPatchCollection patchesToRemove = getMsdOutputPatches();
Michael Chan6fb34492020-12-08 15:44:49 +11001779 for (auto it = patchesToCreate.begin(); it != patchesToCreate.end(); ) {
1780 auto retainedPatch = false;
1781 for (auto i = 0u; i < patchesToRemove.size(); ++i) {
1782 if (audio_patches_are_equal(it->patch(), &patchesToRemove[i]->mPatch)) {
1783 patchesToRemove.removeItemsAt(i);
1784 retainedPatch = true;
1785 break;
1786 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001787 }
Michael Chan6fb34492020-12-08 15:44:49 +11001788 if (retainedPatch) {
1789 it = patchesToCreate.erase(it);
1790 continue;
1791 }
1792 ++it;
1793 }
1794 if (patchesToCreate.size() == 0 && patchesToRemove.size() == 0) {
1795 return NO_ERROR;
1796 }
1797 for (auto i = 0u; i < patchesToRemove.size(); ++i) {
1798 auto &currentPatch = patchesToRemove.valueAt(i);
François Gaffieafd4cea2019-11-18 15:50:22 +01001799 releaseAudioPatch(currentPatch->getHandle(), mUidCached);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001800 }
Michael Chan6fb34492020-12-08 15:44:49 +11001801 status_t status = NO_ERROR;
1802 for (const auto &p : patchesToCreate) {
1803 auto currStatus = installPatch(__func__, -1 /*index*/, nullptr /*patchHandle*/,
1804 p.patch(), 0 /*delayMs*/, mUidCached, nullptr /*patchDescPtr*/);
1805 char message[256];
1806 snprintf(message, sizeof(message), "%s() %s: creating MSD patch from device:IN_BUS to "
1807 "device:%#x (format:%#x channels:%#x samplerate:%d)", __func__,
1808 currStatus == NO_ERROR ? "Success" : "Error",
1809 p.patch()->sinks[0].ext.device.type, p.patch()->sources[0].format,
1810 p.patch()->sources[0].channel_mask, p.patch()->sources[0].sample_rate);
1811 if (currStatus == NO_ERROR) {
1812 ALOGD("%s", message);
1813 } else {
1814 ALOGE("%s", message);
1815 if (status == NO_ERROR) {
1816 status = currStatus;
1817 }
1818 }
1819 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001820 return status;
1821}
1822
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001823void AudioPolicyManager::releaseMsdOutputPatches(const DeviceVector& devices) {
1824 AudioPatchCollection msdPatches = getMsdOutputPatches();
Michael Chan6fb34492020-12-08 15:44:49 +11001825 for (size_t i = 0; i < msdPatches.size(); i++) {
1826 const auto& patch = msdPatches[i];
1827 for (size_t j = 0; j < patch->mPatch.num_sinks; ++j) {
1828 const struct audio_port_config *sink = &patch->mPatch.sinks[j];
1829 if (sink->type == AUDIO_PORT_TYPE_DEVICE && devices.getDevice(sink->ext.device.type,
1830 String8(sink->ext.device.address), AUDIO_FORMAT_DEFAULT) != nullptr) {
1831 releaseAudioPatch(patch->getHandle(), mUidCached);
1832 break;
1833 }
1834 }
1835 }
1836}
1837
Dorin Drimus94d94412022-02-02 09:05:02 +01001838bool AudioPolicyManager::msdHasPatchesToAllDevices(const AudioDeviceTypeAddrVector& devices) {
Mikhail Naganovb0fbc1b2023-04-28 13:06:32 -07001839 DeviceVector devicesToCheck =
1840 mConfig->getOutputDevices().getDevicesFromDeviceTypeAddrVec(devices);
Dorin Drimus94d94412022-02-02 09:05:02 +01001841 AudioPatchCollection msdPatches = getMsdOutputPatches();
1842 for (size_t i = 0; i < msdPatches.size(); i++) {
1843 const auto& patch = msdPatches[i];
1844 for (size_t j = 0; j < patch->mPatch.num_sinks; ++j) {
1845 const struct audio_port_config *sink = &patch->mPatch.sinks[j];
1846 if (sink->type == AUDIO_PORT_TYPE_DEVICE) {
1847 const auto& foundDevice = devicesToCheck.getDevice(
1848 sink->ext.device.type, String8(sink->ext.device.address), AUDIO_FORMAT_DEFAULT);
1849 if (foundDevice != nullptr) {
1850 devicesToCheck.remove(foundDevice);
1851 if (devicesToCheck.isEmpty()) {
1852 return true;
1853 }
1854 }
1855 }
1856 }
1857 }
1858 return false;
1859}
1860
Eric Laurente0720872014-03-11 09:30:41 -07001861audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
jiabinebb6af42020-06-09 17:31:17 -07001862 audio_output_flags_t flags,
1863 audio_format_t format,
1864 audio_channel_mask_t channelMask,
1865 uint32_t samplingRate,
1866 audio_session_t sessionId)
Eric Laurente552edb2014-03-10 17:42:56 -07001867{
Eric Laurent16c66dd2019-05-01 17:54:10 -07001868 LOG_ALWAYS_FATAL_IF(!(format == AUDIO_FORMAT_INVALID || audio_is_linear_pcm(format)),
1869 "%s called with format %#x", __func__, format);
1870
jiabinebb6af42020-06-09 17:31:17 -07001871 // Return the output that haptic-generating attached to when 1) session id is specified,
1872 // 2) haptic-generating effect exists for given session id and 3) the output that
1873 // haptic-generating effect attached to is in given outputs.
1874 if (sessionId != AUDIO_SESSION_NONE) {
1875 audio_io_handle_t hapticGeneratingOutput = mEffects.getIoForSession(
1876 sessionId, FX_IID_HAPTICGENERATOR);
1877 if (outputs.indexOf(hapticGeneratingOutput) >= 0) {
1878 return hapticGeneratingOutput;
1879 }
1880 }
1881
Eric Laurent16c66dd2019-05-01 17:54:10 -07001882 // Flags disqualifying an output: the match must happen before calling selectOutput()
1883 static const audio_output_flags_t kExcludedFlags = (audio_output_flags_t)
1884 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ | AUDIO_OUTPUT_FLAG_DIRECT);
1885
1886 // Flags expressing a functional request: must be honored in priority over
1887 // other criteria
1888 static const audio_output_flags_t kFunctionalFlags = (audio_output_flags_t)
1889 (AUDIO_OUTPUT_FLAG_VOIP_RX | AUDIO_OUTPUT_FLAG_INCALL_MUSIC |
Eric Laurente28c66d2022-01-21 13:40:41 +01001890 AUDIO_OUTPUT_FLAG_TTS | AUDIO_OUTPUT_FLAG_DIRECT_PCM | AUDIO_OUTPUT_FLAG_ULTRASOUND |
1891 AUDIO_OUTPUT_FLAG_SPATIALIZER);
Eric Laurent16c66dd2019-05-01 17:54:10 -07001892 // Flags expressing a performance request: have lower priority than serving
1893 // requested sampling rate or channel mask
1894 static const audio_output_flags_t kPerformanceFlags = (audio_output_flags_t)
1895 (AUDIO_OUTPUT_FLAG_FAST | AUDIO_OUTPUT_FLAG_DEEP_BUFFER |
1896 AUDIO_OUTPUT_FLAG_RAW | AUDIO_OUTPUT_FLAG_SYNC);
1897
1898 const audio_output_flags_t functionalFlags =
1899 (audio_output_flags_t)(flags & kFunctionalFlags);
1900 const audio_output_flags_t performanceFlags =
1901 (audio_output_flags_t)(flags & kPerformanceFlags);
1902
1903 audio_io_handle_t bestOutput = (outputs.size() == 0) ? AUDIO_IO_HANDLE_NONE : outputs[0];
1904
Eric Laurente552edb2014-03-10 17:42:56 -07001905 // select one output among several that provide a path to a particular device or set of
François Gaffie11d30102018-11-02 16:09:09 +01001906 // devices (the list was previously build by getOutputsForDevices()).
Eric Laurente552edb2014-03-10 17:42:56 -07001907 // The priority is as follows:
jiabin40573322018-11-08 12:08:02 -08001908 // 1: the output supporting haptic playback when requesting haptic playback
Eric Laurent16c66dd2019-05-01 17:54:10 -07001909 // 2: the output with the highest number of requested functional flags
Carter Hsu199f1892021-10-15 15:47:29 +08001910 // with tiebreak preferring the minimum number of extra functional flags
1911 // (see b/200293124, the incorrect selection of AUDIO_OUTPUT_FLAG_VOIP_RX).
Eric Laurent16c66dd2019-05-01 17:54:10 -07001912 // 3: the output supporting the exact channel mask
1913 // 4: the output with a higher channel count than requested
jiabind1785f72022-06-03 20:48:18 +00001914 // 5: the output with the highest sampling rate if the requested sample rate is
1915 // greater than default sampling rate
Eric Laurent16c66dd2019-05-01 17:54:10 -07001916 // 6: the output with the highest number of requested performance flags
1917 // 7: the output with the bit depth the closest to the requested one
1918 // 8: the primary output
1919 // 9: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07001920
Eric Laurent16c66dd2019-05-01 17:54:10 -07001921 // matching criteria values in priority order for best matching output so far
1922 std::vector<uint32_t> bestMatchCriteria(8, 0);
Eric Laurente552edb2014-03-10 17:42:56 -07001923
Eric Laurent16c66dd2019-05-01 17:54:10 -07001924 const uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
1925 const uint32_t hapticChannelCount = audio_channel_count_from_out_mask(
1926 channelMask & AUDIO_CHANNEL_HAPTIC_ALL);
Eric Laurente78b6762018-12-19 16:29:01 -08001927
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001928 for (audio_io_handle_t output : outputs) {
1929 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent16c66dd2019-05-01 17:54:10 -07001930 // matching criteria values in priority order for current output
1931 std::vector<uint32_t> currentMatchCriteria(8, 0);
jiabin40573322018-11-08 12:08:02 -08001932
Eric Laurent16c66dd2019-05-01 17:54:10 -07001933 if (outputDesc->isDuplicated()) {
1934 continue;
1935 }
1936 if ((kExcludedFlags & outputDesc->mFlags) != 0) {
1937 continue;
1938 }
Eric Laurent8838a382014-09-08 16:44:28 -07001939
Eric Laurent16c66dd2019-05-01 17:54:10 -07001940 // If haptic channel is specified, use the haptic output if present.
1941 // When using haptic output, same audio format and sample rate are required.
1942 const uint32_t outputHapticChannelCount = audio_channel_count_from_out_mask(
jiabin5740f082019-08-19 15:08:30 -07001943 outputDesc->getChannelMask() & AUDIO_CHANNEL_HAPTIC_ALL);
Eric Laurent16c66dd2019-05-01 17:54:10 -07001944 if ((hapticChannelCount == 0) != (outputHapticChannelCount == 0)) {
1945 continue;
1946 }
1947 if (outputHapticChannelCount >= hapticChannelCount
jiabin5740f082019-08-19 15:08:30 -07001948 && format == outputDesc->getFormat()
1949 && samplingRate == outputDesc->getSamplingRate()) {
Eric Laurent16c66dd2019-05-01 17:54:10 -07001950 currentMatchCriteria[0] = outputHapticChannelCount;
1951 }
1952
1953 // functional flags match
Carter Hsu199f1892021-10-15 15:47:29 +08001954 const int matchingFunctionalFlags =
1955 __builtin_popcount(outputDesc->mFlags & functionalFlags);
1956 const int totalFunctionalFlags =
1957 __builtin_popcount(outputDesc->mFlags & kFunctionalFlags);
1958 // Prefer matching functional flags, but subtract unnecessary functional flags.
1959 currentMatchCriteria[1] = 100 * (matchingFunctionalFlags + 1) - totalFunctionalFlags;
Eric Laurent16c66dd2019-05-01 17:54:10 -07001960
1961 // channel mask and channel count match
jiabin5740f082019-08-19 15:08:30 -07001962 uint32_t outputChannelCount = audio_channel_count_from_out_mask(
1963 outputDesc->getChannelMask());
Eric Laurent16c66dd2019-05-01 17:54:10 -07001964 if (channelMask != AUDIO_CHANNEL_NONE && channelCount > 2 &&
1965 channelCount <= outputChannelCount) {
1966 if ((audio_channel_mask_get_representation(channelMask) ==
jiabin5740f082019-08-19 15:08:30 -07001967 audio_channel_mask_get_representation(outputDesc->getChannelMask())) &&
1968 ((channelMask & outputDesc->getChannelMask()) == channelMask)) {
Eric Laurent16c66dd2019-05-01 17:54:10 -07001969 currentMatchCriteria[2] = outputChannelCount;
Eric Laurente552edb2014-03-10 17:42:56 -07001970 }
Eric Laurent16c66dd2019-05-01 17:54:10 -07001971 currentMatchCriteria[3] = outputChannelCount;
1972 }
1973
1974 // sampling rate match
jiabind1785f72022-06-03 20:48:18 +00001975 if (samplingRate > SAMPLE_RATE_HZ_DEFAULT) {
jiabin5740f082019-08-19 15:08:30 -07001976 currentMatchCriteria[4] = outputDesc->getSamplingRate();
Eric Laurent16c66dd2019-05-01 17:54:10 -07001977 }
1978
1979 // performance flags match
1980 currentMatchCriteria[5] = popcount(outputDesc->mFlags & performanceFlags);
1981
1982 // format match
1983 if (format != AUDIO_FORMAT_INVALID) {
1984 currentMatchCriteria[6] =
jiabin4ef93452019-09-10 14:29:54 -07001985 PolicyAudioPort::kFormatDistanceMax -
1986 PolicyAudioPort::formatDistance(format, outputDesc->getFormat());
Eric Laurent16c66dd2019-05-01 17:54:10 -07001987 }
1988
1989 // primary output match
1990 currentMatchCriteria[7] = outputDesc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY;
1991
1992 // compare match criteria by priority then value
1993 if (std::lexicographical_compare(bestMatchCriteria.begin(), bestMatchCriteria.end(),
1994 currentMatchCriteria.begin(), currentMatchCriteria.end())) {
1995 bestMatchCriteria = currentMatchCriteria;
1996 bestOutput = output;
1997
1998 std::stringstream result;
1999 std::copy(bestMatchCriteria.begin(), bestMatchCriteria.end(),
2000 std::ostream_iterator<int>(result, " "));
2001 ALOGV("%s new bestOutput %d criteria %s",
2002 __func__, bestOutput, result.str().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07002003 }
2004 }
2005
Eric Laurent16c66dd2019-05-01 17:54:10 -07002006 return bestOutput;
Eric Laurente552edb2014-03-10 17:42:56 -07002007}
2008
Eric Laurent8fc147b2018-07-22 19:13:55 -07002009status_t AudioPolicyManager::startOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002010{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002011 ALOGV("%s portId %d", __FUNCTION__, portId);
2012
2013 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2014 if (outputDesc == 0) {
2015 ALOGW("startOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002016 return BAD_VALUE;
2017 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002018 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002019
Eric Laurent8fc147b2018-07-22 19:13:55 -07002020 ALOGV("startOutput() output %d, stream %d, session %d",
Eric Laurent97ac8712018-07-27 18:59:02 -07002021 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurentc75307b2015-03-17 15:29:32 -07002022
Eric Laurent733ce942017-12-07 12:18:25 -08002023 status_t status = outputDesc->start();
2024 if (status != NO_ERROR) {
2025 return status;
Eric Laurent3974e3b2017-12-07 17:58:43 -08002026 }
2027
Eric Laurent97ac8712018-07-27 18:59:02 -07002028 uint32_t delayMs;
2029 status = startSource(outputDesc, client, &delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07002030
2031 if (status != NO_ERROR) {
Eric Laurent733ce942017-12-07 12:18:25 -08002032 outputDesc->stop();
Eric Laurent8c7e6da2015-04-21 17:37:00 -07002033 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07002034 }
Eric Laurentc75307b2015-03-17 15:29:32 -07002035 if (delayMs != 0) {
2036 usleep(delayMs * 1000);
2037 }
2038
2039 return status;
2040}
2041
Eric Laurent96d1dda2022-03-14 17:14:19 +01002042bool AudioPolicyManager::isLeUnicastActive() const {
2043 if (isInCall()) {
2044 return true;
2045 }
2046 return isAnyDeviceTypeActive(getAudioDeviceOutLeAudioUnicastSet());
2047}
2048
2049bool AudioPolicyManager::isAnyDeviceTypeActive(const DeviceTypeSet& deviceTypes) const {
2050 if (mAvailableOutputDevices.getDevicesFromTypes(deviceTypes).isEmpty()) {
2051 return false;
2052 }
2053 bool active = mOutputs.isAnyDeviceTypeActive(deviceTypes);
2054 ALOGV("%s active %d", __func__, active);
2055 return active;
2056}
2057
Eric Laurent97ac8712018-07-27 18:59:02 -07002058status_t AudioPolicyManager::startSource(const sp<SwAudioOutputDescriptor>& outputDesc,
2059 const sp<TrackClientDescriptor>& client,
2060 uint32_t *delayMs)
Eric Laurentc75307b2015-03-17 15:29:32 -07002061{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002062 // cannot start playback of STREAM_TTS if any other output is being used
2063 uint32_t beaconMuteLatency = 0;
Eric Laurentc75307b2015-03-17 15:29:32 -07002064
2065 *delayMs = 0;
Eric Laurent97ac8712018-07-27 18:59:02 -07002066 audio_stream_type_t stream = client->stream();
François Gaffie1c878552018-11-22 16:53:21 +01002067 auto clientVolSrc = client->volumeSource();
François Gaffiec005e562018-11-06 15:04:49 +01002068 auto clientStrategy = client->strategy();
2069 auto clientAttr = client->attributes();
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002070 if (stream == AUDIO_STREAM_TTS) {
2071 ALOGV("\t found BEACON stream");
François Gaffie1c878552018-11-22 16:53:21 +01002072 if (!mTtsOutputAvailable && mOutputs.isAnyOutputActive(
Francois Gaffie4404ddb2021-02-04 17:03:38 +01002073 toVolumeSource(AUDIO_STREAM_TTS, false) /*sourceToIgnore*/)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002074 return INVALID_OPERATION;
2075 } else {
2076 beaconMuteLatency = handleEventForBeacon(STARTING_BEACON);
2077 }
2078 } else {
2079 // some playback other than beacon starts
2080 beaconMuteLatency = handleEventForBeacon(STARTING_OUTPUT);
2081 }
2082
Eric Laurent77305a62016-07-25 16:39:22 -07002083 // force device change if the output is inactive and no audio patch is already present.
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002084 // check active before incrementing usage count
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02002085 bool force = !outputDesc->isActive() && !outputDesc->isRouted();
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002086
François Gaffie11d30102018-11-02 16:09:09 +01002087 DeviceVector devices;
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002088 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
Eric Laurent97ac8712018-07-27 18:59:02 -07002089 const char *address = NULL;
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002090 if (policyMix != nullptr) {
François Gaffie11d30102018-11-02 16:09:09 +01002091 audio_devices_t newDeviceType;
Eric Laurent97ac8712018-07-27 18:59:02 -07002092 address = policyMix->mDeviceAddress.string();
Kevin Rocard153f92d2018-12-18 18:33:28 -08002093 if ((policyMix->mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie11d30102018-11-02 16:09:09 +01002094 newDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Kevin Rocard153f92d2018-12-18 18:33:28 -08002095 } else {
2096 newDeviceType = policyMix->mDeviceType;
Eric Laurent97ac8712018-07-27 18:59:02 -07002097 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08002098 sp device = mAvailableOutputDevices.getDevice(newDeviceType, String8(address),
2099 AUDIO_FORMAT_DEFAULT);
2100 ALOG_ASSERT(device, "%s: no device found t=%u, a=%s", __func__, newDeviceType, address);
2101 devices.add(device);
Eric Laurent97ac8712018-07-27 18:59:02 -07002102 }
2103
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002104 // requiresMuteCheck is false when we can bypass mute strategy.
2105 // It covers a common case when there is no materially active audio
2106 // and muting would result in unnecessary delay and dropped audio.
2107 const uint32_t outputLatencyMs = outputDesc->latency();
2108 bool requiresMuteCheck = outputDesc->isActive(outputLatencyMs * 2); // account for drain
Eric Laurent96d1dda2022-03-14 17:14:19 +01002109 bool wasLeUnicastActive = isLeUnicastActive();
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002110
Eric Laurente552edb2014-03-10 17:42:56 -07002111 // increment usage count for this stream on the requested output:
2112 // NOTE that the usage count is the same for duplicated output and hardware output which is
2113 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
Eric Laurent592dd7b2018-08-05 18:58:48 -07002114 outputDesc->setClientActive(client, true);
Eric Laurent97ac8712018-07-27 18:59:02 -07002115
2116 if (client->hasPreferredDevice(true)) {
François Gaffief96e5432019-04-09 17:13:56 +02002117 if (outputDesc->clientsList(true /*activeOnly*/).size() == 1 &&
2118 client->isPreferredDeviceForExclusiveUse()) {
2119 // Preferred device may be exclusive, use only if no other active clients on this output
2120 devices = DeviceVector(
2121 mAvailableOutputDevices.getDeviceFromId(client->preferredDeviceId()));
2122 } else {
2123 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
2124 }
François Gaffie11d30102018-11-02 16:09:09 +01002125 if (devices != outputDesc->devices()) {
François Gaffiec005e562018-11-06 15:04:49 +01002126 checkStrategyRoute(clientStrategy, outputDesc->mIoHandle);
Eric Laurent97ac8712018-07-27 18:59:02 -07002127 }
2128 }
Eric Laurente552edb2014-03-10 17:42:56 -07002129
François Gaffiec005e562018-11-06 15:04:49 +01002130 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07002131 selectOutputForMusicEffects();
2132 }
2133
François Gaffie1c878552018-11-22 16:53:21 +01002134 if (outputDesc->getActivityCount(clientVolSrc) == 1 || !devices.isEmpty()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08002135 // starting an output being rerouted?
François Gaffie11d30102018-11-02 16:09:09 +01002136 if (devices.isEmpty()) {
2137 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Eric Laurent275e8e92014-11-30 15:14:47 -08002138 }
François Gaffiec005e562018-11-06 15:04:49 +01002139 bool shouldWait =
2140 (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM)) ||
2141 followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_NOTIFICATION)) ||
2142 (beaconMuteLatency > 0));
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002143 uint32_t waitMs = beaconMuteLatency;
Eric Laurente552edb2014-03-10 17:42:56 -07002144 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01002145 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07002146 if (desc != outputDesc) {
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002147 // An output has a shared device if
2148 // - managed by the same hw module
2149 // - supports the currently selected device
2150 const bool sharedDevice = outputDesc->sharesHwModuleWith(desc)
François Gaffie11d30102018-11-02 16:09:09 +01002151 && (!desc->filterSupportedDevices(devices).isEmpty());
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002152
Eric Laurent77305a62016-07-25 16:39:22 -07002153 // force a device change if any other output is:
2154 // - managed by the same hw module
Jean-Michel Trivi4a5b4812018-02-08 17:22:32 +00002155 // - supports currently selected device
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002156 // - has a current device selection that differs from selected device.
Eric Laurent77305a62016-07-25 16:39:22 -07002157 // - has an active audio patch
Eric Laurente552edb2014-03-10 17:42:56 -07002158 // In this case, the audio HAL must receive the new device selection so that it can
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002159 // change the device currently selected by the other output.
2160 if (sharedDevice &&
François Gaffie11d30102018-11-02 16:09:09 +01002161 desc->devices() != devices &&
Eric Laurent77305a62016-07-25 16:39:22 -07002162 desc->getPatchHandle() != AUDIO_PATCH_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07002163 force = true;
2164 }
2165 // wait for audio on other active outputs to be presented when starting
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002166 // a notification so that audio focus effect can propagate, or that a mute/unmute
2167 // event occurred for beacon
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002168 const uint32_t latencyMs = desc->latency();
2169 const bool isActive = desc->isActive(latencyMs * 2); // account for drain
2170
2171 if (shouldWait && isActive && (waitMs < latencyMs)) {
2172 waitMs = latencyMs;
Eric Laurente552edb2014-03-10 17:42:56 -07002173 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002174
2175 // Require mute check if another output is on a shared device
2176 // and currently active to have proper drain and avoid pops.
2177 // Note restoring AudioTracks onto this output needs to invoke
2178 // a volume ramp if there is no mute.
2179 requiresMuteCheck |= sharedDevice && isActive;
Eric Laurente552edb2014-03-10 17:42:56 -07002180 }
2181 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002182
2183 const uint32_t muteWaitMs =
François Gaffie11d30102018-11-02 16:09:09 +01002184 setOutputDevices(outputDesc, devices, force, 0, NULL, requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07002185
Eric Laurente552edb2014-03-10 17:42:56 -07002186 // apply volume rules for current stream and device if necessary
François Gaffieaaac0fd2018-11-22 17:56:39 +01002187 auto &curves = getVolumeCurves(client->attributes());
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00002188 if (NO_ERROR != checkAndSetVolume(curves, client->volumeSource(),
François Gaffieaaac0fd2018-11-22 17:56:39 +01002189 curves.getVolumeIndex(outputDesc->devices().types()),
Eric Laurentc75307b2015-03-17 15:29:32 -07002190 outputDesc,
Francois Gaffied11442b2020-04-27 11:51:09 +02002191 outputDesc->devices().types(), 0 /*delay*/,
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00002192 outputDesc->useHwGain() /*force*/)) {
2193 // request AudioService to reinitialize the volume curves asynchronously
2194 ALOGE("checkAndSetVolume failed, requesting volume range init");
2195 mpClientInterface->onVolumeRangeInitRequest();
2196 };
Eric Laurente552edb2014-03-10 17:42:56 -07002197
2198 // update the outputs if starting an output with a stream that can affect notification
2199 // routing
2200 handleNotificationRoutingForStream(stream);
Eric Laurentc722f302014-12-10 11:21:49 -08002201
Eric Laurent2cbe89a2014-12-19 11:49:08 -08002202 // force reevaluating accessibility routing when ringtone or alarm starts
François Gaffiec005e562018-11-06 15:04:49 +01002203 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM))) {
Eric Laurent2cbe89a2014-12-19 11:49:08 -08002204 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
2205 }
Eric Laurentdc462862016-07-19 12:29:53 -07002206
2207 if (waitMs > muteWaitMs) {
2208 *delayMs = waitMs - muteWaitMs;
2209 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002210
2211 // FIXME: A device change (muteWaitMs > 0) likely introduces a volume change.
2212 // A volume change enacted by APM with 0 delay is not synchronous, as it goes
2213 // via AudioCommandThread to AudioFlinger. Hence it is possible that the volume
2214 // change occurs after the MixerThread starts and causes a stream volume
2215 // glitch.
2216 //
2217 // We do not introduce additional delay here.
Eric Laurente552edb2014-03-10 17:42:56 -07002218 }
Eric Laurentdc462862016-07-19 12:29:53 -07002219
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002220 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
jiabin9a3361e2019-10-01 09:38:30 -07002221 mEngine->getForceUse(
2222 AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
François Gaffiec005e562018-11-06 15:04:49 +01002223 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), true, outputDesc);
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002224 }
2225
Eric Laurent97ac8712018-07-27 18:59:02 -07002226 // Automatically enable the remote submix input when output is started on a re routing mix
2227 // of type MIX_TYPE_RECORDERS
jiabin9a3361e2019-10-01 09:38:30 -07002228 if (isSingleDeviceType(devices.types(), &audio_is_remote_submix_device) &&
2229 policyMix != NULL && policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002230 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2231 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2232 address,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002233 "remote-submix",
2234 AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07002235 }
2236
Eric Laurent96d1dda2022-03-14 17:14:19 +01002237 checkLeBroadcastRoutes(wasLeUnicastActive, outputDesc, *delayMs);
2238
Eric Laurente552edb2014-03-10 17:42:56 -07002239 return NO_ERROR;
2240}
2241
Eric Laurent96d1dda2022-03-14 17:14:19 +01002242void AudioPolicyManager::checkLeBroadcastRoutes(bool wasUnicastActive,
2243 sp<SwAudioOutputDescriptor> ignoredOutput, uint32_t delayMs) {
2244 bool isUnicastActive = isLeUnicastActive();
2245
2246 if (wasUnicastActive != isUnicastActive) {
2247 //reroute all outputs routed to LE broadcast if LE unicast activy changed on any output
2248 for (size_t i = 0; i < mOutputs.size(); i++) {
2249 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
2250 if (desc != ignoredOutput && desc->isActive()
2251 && ((isUnicastActive &&
2252 !desc->devices().
2253 getDevicesFromType(AUDIO_DEVICE_OUT_BLE_BROADCAST).isEmpty())
2254 || (wasUnicastActive &&
2255 !desc->devices().getDevicesFromTypes(
2256 getAudioDeviceOutLeAudioUnicastSet()).isEmpty()))) {
2257 DeviceVector newDevices = getNewOutputDevices(desc, false /*fromCache*/);
2258 bool force = desc->devices() != newDevices;
2259 setOutputDevices(desc, newDevices, force, delayMs);
2260 // re-apply device specific volume if not done by setOutputDevice()
2261 if (!force) {
2262 applyStreamVolumes(desc, newDevices.types(), delayMs);
2263 }
2264 }
2265 }
2266 }
2267}
2268
Eric Laurent8fc147b2018-07-22 19:13:55 -07002269status_t AudioPolicyManager::stopOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002270{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002271 ALOGV("%s portId %d", __FUNCTION__, portId);
2272
2273 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2274 if (outputDesc == 0) {
2275 ALOGW("stopOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002276 return BAD_VALUE;
2277 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002278 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002279
Eric Laurent97ac8712018-07-27 18:59:02 -07002280 ALOGV("stopOutput() output %d, stream %d, session %d",
2281 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurente552edb2014-03-10 17:42:56 -07002282
Eric Laurent97ac8712018-07-27 18:59:02 -07002283 status_t status = stopSource(outputDesc, client);
Eric Laurent3974e3b2017-12-07 17:58:43 -08002284
Eric Laurent733ce942017-12-07 12:18:25 -08002285 if (status == NO_ERROR ) {
2286 outputDesc->stop();
Eric Laurent3974e3b2017-12-07 17:58:43 -08002287 }
2288 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07002289}
2290
Eric Laurent97ac8712018-07-27 18:59:02 -07002291status_t AudioPolicyManager::stopSource(const sp<SwAudioOutputDescriptor>& outputDesc,
2292 const sp<TrackClientDescriptor>& client)
Eric Laurentc75307b2015-03-17 15:29:32 -07002293{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002294 // always handle stream stop, check which stream type is stopping
Eric Laurent97ac8712018-07-27 18:59:02 -07002295 audio_stream_type_t stream = client->stream();
François Gaffie1c878552018-11-22 16:53:21 +01002296 auto clientVolSrc = client->volumeSource();
Eric Laurent96d1dda2022-03-14 17:14:19 +01002297 bool wasLeUnicastActive = isLeUnicastActive();
Eric Laurent97ac8712018-07-27 18:59:02 -07002298
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002299 handleEventForBeacon(stream == AUDIO_STREAM_TTS ? STOPPING_BEACON : STOPPING_OUTPUT);
2300
François Gaffie1c878552018-11-22 16:53:21 +01002301 if (outputDesc->getActivityCount(clientVolSrc) > 0) {
2302 if (outputDesc->getActivityCount(clientVolSrc) == 1) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002303 // Automatically disable the remote submix input when output is stopped on a
2304 // re routing mix of type MIX_TYPE_RECORDERS
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002305 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
jiabin9a3361e2019-10-01 09:38:30 -07002306 if (isSingleDeviceType(
2307 outputDesc->devices().types(), &audio_is_remote_submix_device) &&
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002308 policyMix != nullptr &&
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002309 policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002310 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2311 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002312 policyMix->mDeviceAddress,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002313 "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07002314 }
2315 }
2316 bool forceDeviceUpdate = false;
2317 if (client->hasPreferredDevice(true)) {
François Gaffiec005e562018-11-06 15:04:49 +01002318 checkStrategyRoute(client->strategy(), AUDIO_IO_HANDLE_NONE);
Eric Laurent97ac8712018-07-27 18:59:02 -07002319 forceDeviceUpdate = true;
2320 }
2321
Eric Laurente552edb2014-03-10 17:42:56 -07002322 // decrement usage count of this stream on the output
Eric Laurent592dd7b2018-08-05 18:58:48 -07002323 outputDesc->setClientActive(client, false);
Paul McLeanaa981192015-03-21 09:55:15 -07002324
Eric Laurente552edb2014-03-10 17:42:56 -07002325 // store time at which the stream was stopped - see isStreamActive()
François Gaffie1c878552018-11-22 16:53:21 +01002326 if (outputDesc->getActivityCount(clientVolSrc) == 0 || forceDeviceUpdate) {
François Gaffiec005e562018-11-06 15:04:49 +01002327 outputDesc->setStopTime(client, systemTime());
François Gaffie11d30102018-11-02 16:09:09 +01002328 DeviceVector newDevices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Francois Gaffie3523ab32021-06-22 13:24:34 +02002329
2330 // If the routing does not change, if an output is routed on a device using HwGain
2331 // (aka setAudioPortConfig) and there are still active clients following different
2332 // volume group(s), force reapply volume
2333 bool requiresVolumeCheck = outputDesc->getActivityCount(clientVolSrc) == 0 &&
2334 outputDesc->useHwGain() && outputDesc->isAnyActive(VOLUME_SOURCE_NONE);
2335
Eric Laurente552edb2014-03-10 17:42:56 -07002336 // delay the device switch by twice the latency because stopOutput() is executed when
2337 // the track stop() command is received and at that time the audio track buffer can
2338 // still contain data that needs to be drained. The latency only covers the audio HAL
2339 // and kernel buffers. Also the latency does not always include additional delay in the
2340 // audio path (audio DSP, CODEC ...)
Francois Gaffie3523ab32021-06-22 13:24:34 +02002341 setOutputDevices(outputDesc, newDevices, false, outputDesc->latency()*2,
2342 nullptr, true /*requiresMuteCheck*/, requiresVolumeCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07002343
2344 // force restoring the device selection on other active outputs if it differs from the
2345 // one being selected for this output
Eric Laurent57de36c2016-09-28 16:59:11 -07002346 uint32_t delayMs = outputDesc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -07002347 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01002348 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07002349 if (desc != outputDesc &&
Eric Laurente552edb2014-03-10 17:42:56 -07002350 desc->isActive() &&
2351 outputDesc->sharesHwModuleWith(desc) &&
François Gaffie11d30102018-11-02 16:09:09 +01002352 (newDevices != desc->devices())) {
2353 DeviceVector newDevices2 = getNewOutputDevices(desc, false /*fromCache*/);
2354 bool force = desc->devices() != newDevices2;
Eric Laurentf3a5a602018-05-22 18:42:55 -07002355
François Gaffie11d30102018-11-02 16:09:09 +01002356 setOutputDevices(desc, newDevices2, force, delayMs);
2357
Eric Laurent57de36c2016-09-28 16:59:11 -07002358 // re-apply device specific volume if not done by setOutputDevice()
2359 if (!force) {
François Gaffie11d30102018-11-02 16:09:09 +01002360 applyStreamVolumes(desc, newDevices2.types(), delayMs);
Eric Laurent57de36c2016-09-28 16:59:11 -07002361 }
Eric Laurente552edb2014-03-10 17:42:56 -07002362 }
2363 }
2364 // update the outputs if stopping one with a stream that can affect notification routing
2365 handleNotificationRoutingForStream(stream);
2366 }
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002367
2368 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
2369 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Jean-Michel Trivi74e01fa2019-02-25 12:18:09 -08002370 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), false, outputDesc);
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002371 }
2372
François Gaffiec005e562018-11-06 15:04:49 +01002373 if (followsSameRouting(client->attributes(), attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07002374 selectOutputForMusicEffects();
2375 }
Eric Laurent96d1dda2022-03-14 17:14:19 +01002376
2377 checkLeBroadcastRoutes(wasLeUnicastActive, outputDesc, outputDesc->latency()*2);
2378
Eric Laurente552edb2014-03-10 17:42:56 -07002379 return NO_ERROR;
2380 } else {
Eric Laurentc75307b2015-03-17 15:29:32 -07002381 ALOGW("stopOutput() refcount is already 0");
Eric Laurente552edb2014-03-10 17:42:56 -07002382 return INVALID_OPERATION;
2383 }
2384}
2385
jiabinbce0c1d2020-10-05 11:20:18 -07002386bool AudioPolicyManager::releaseOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002387{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002388 ALOGV("%s portId %d", __FUNCTION__, portId);
2389
2390 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2391 if (outputDesc == 0) {
Andy Hung39efb7a2018-09-26 15:39:28 -07002392 // If an output descriptor is closed due to a device routing change,
2393 // then there are race conditions with releaseOutput from tracks
2394 // that may be destroyed (with no PlaybackThread) or a PlaybackThread
2395 // destroyed shortly thereafter.
2396 //
2397 // Here we just log a warning, instead of a fatal error.
Eric Laurent8fc147b2018-07-22 19:13:55 -07002398 ALOGW("releaseOutput() no output for client %d", portId);
jiabinbce0c1d2020-10-05 11:20:18 -07002399 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002400 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002401
2402 ALOGV("releaseOutput() %d", outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -07002403
Jaideep Sharma7bf382e2020-11-26 17:07:29 +05302404 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
2405 if (outputDesc->isClientActive(client)) {
2406 ALOGW("releaseOutput() inactivates portId %d in good faith", portId);
2407 stopOutput(portId);
2408 }
2409
Eric Laurent8fc147b2018-07-22 19:13:55 -07002410 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
2411 if (outputDesc->mDirectOpenCount <= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07002412 ALOGW("releaseOutput() invalid open count %d for output %d",
Eric Laurent8fc147b2018-07-22 19:13:55 -07002413 outputDesc->mDirectOpenCount, outputDesc->mIoHandle);
jiabinbce0c1d2020-10-05 11:20:18 -07002414 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002415 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002416 if (--outputDesc->mDirectOpenCount == 0) {
2417 closeOutput(outputDesc->mIoHandle);
Eric Laurentb52c1522014-05-20 11:27:36 -07002418 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07002419 }
2420 }
Jaideep Sharma7bf382e2020-11-26 17:07:29 +05302421
Andy Hung39efb7a2018-09-26 15:39:28 -07002422 outputDesc->removeClient(portId);
jiabinbce0c1d2020-10-05 11:20:18 -07002423 if (outputDesc->mPendingReopenToQueryProfiles && outputDesc->getClientCount() == 0) {
2424 // The output is pending reopened to query dynamic profiles and
2425 // there is no active clients
2426 closeOutput(outputDesc->mIoHandle);
2427 sp<SwAudioOutputDescriptor> newOutputDesc = openOutputWithProfileAndDevice(
2428 outputDesc->mProfile, mEngine->getActiveMediaDevices(mAvailableOutputDevices));
2429 if (newOutputDesc == nullptr) {
2430 ALOGE("%s failed to open output", __func__);
2431 }
2432 return true;
2433 }
2434 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002435}
2436
Eric Laurentcaf7f482014-11-25 17:50:47 -08002437status_t AudioPolicyManager::getInputForAttr(const audio_attributes_t *attr,
2438 audio_io_handle_t *input,
Mikhail Naganov2996f672019-04-18 12:29:59 -07002439 audio_unique_id_t riid,
Eric Laurentcaf7f482014-11-25 17:50:47 -08002440 audio_session_t session,
Svet Ganov3e5f14f2021-05-13 22:51:08 +00002441 const AttributionSourceState& attributionSource,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002442 const audio_config_base_t *config,
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002443 audio_input_flags_t flags,
Eric Laurent2ac76942017-06-22 17:17:09 -07002444 audio_port_handle_t *selectedDeviceId,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002445 input_type_t *inputType,
2446 audio_port_handle_t *portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002447{
François Gaffiec005e562018-11-06 15:04:49 +01002448 ALOGV("%s() source %d, sampling rate %d, format %#x, channel mask %#x, session %d, "
Eric Laurent2f2c1982021-06-02 14:03:11 +02002449 "flags %#x attributes=%s requested device ID %d",
2450 __func__, attr->source, config->sample_rate, config->format, config->channel_mask,
2451 session, flags, toString(*attr).c_str(), *selectedDeviceId);
Eric Laurente552edb2014-03-10 17:42:56 -07002452
Eric Laurentad2e7b92017-09-14 20:06:42 -07002453 status_t status = NO_ERROR;
Francois Gaffie716e1432019-01-14 16:58:59 +01002454 audio_attributes_t attributes = *attr;
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002455 sp<AudioPolicyMix> policyMix;
François Gaffie11d30102018-11-02 16:09:09 +01002456 sp<DeviceDescriptor> device;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002457 sp<AudioInputDescriptor> inputDesc;
2458 sp<RecordClientDescriptor> clientDesc;
2459 audio_port_handle_t requestedDeviceId = *selectedDeviceId;
Svet Ganov3e5f14f2021-05-13 22:51:08 +00002460 uid_t uid = VALUE_OR_RETURN_STATUS(aidl2legacy_int32_t_uid_t(attributionSource.uid));
Eric Laurent8f42ea12018-08-08 09:08:25 -07002461 bool isSoundTrigger;
Eric Laurent8f42ea12018-08-08 09:08:25 -07002462
2463 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
2464 if (*portId != AUDIO_PORT_HANDLE_NONE) {
2465 return INVALID_OPERATION;
2466 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08002467
Francois Gaffie716e1432019-01-14 16:58:59 +01002468 if (attr->source == AUDIO_SOURCE_DEFAULT) {
2469 attributes.source = AUDIO_SOURCE_MIC;
Eric Laurentfe231122017-11-17 17:48:06 -08002470 }
2471
Paul McLean466dc8e2015-04-17 13:15:36 -06002472 // Explicit routing?
Pattydd807582021-11-04 21:01:03 +08002473 sp<DeviceDescriptor> explicitRoutingDevice =
François Gaffie11d30102018-11-02 16:09:09 +01002474 mAvailableInputDevices.getDeviceFromId(*selectedDeviceId);
Paul McLean466dc8e2015-04-17 13:15:36 -06002475
Eric Laurentad2e7b92017-09-14 20:06:42 -07002476 // special case for mmap capture: if an input IO handle is specified, we reuse this input if
2477 // possible
2478 if ((flags & AUDIO_INPUT_FLAG_MMAP_NOIRQ) == AUDIO_INPUT_FLAG_MMAP_NOIRQ &&
2479 *input != AUDIO_IO_HANDLE_NONE) {
2480 ssize_t index = mInputs.indexOfKey(*input);
2481 if (index < 0) {
2482 ALOGW("getInputForAttr() unknown MMAP input %d", *input);
2483 status = BAD_VALUE;
2484 goto error;
2485 }
2486 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002487 RecordClientVector clients = inputDesc->getClientsForSession(session);
2488 if (clients.size() == 0) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07002489 ALOGW("getInputForAttr() unknown session %d on input %d", session, *input);
2490 status = BAD_VALUE;
2491 goto error;
2492 }
2493 // For MMAP mode, the first call to getInputForAttr() is made on behalf of audioflinger.
2494 // The second call is for the first active client and sets the UID. Any further call
Eric Laurent331679c2018-04-16 17:03:16 -07002495 // corresponds to a new client and is only permitted from the same UID.
2496 // If the first UID is silenced, allow a new UID connection and replace with new UID
Eric Laurent8f42ea12018-08-08 09:08:25 -07002497 if (clients.size() > 1) {
2498 for (const auto& client : clients) {
2499 // The client map is ordered by key values (portId) and portIds are allocated
2500 // incrementaly. So the first client in this list is the one opened by audio flinger
2501 // when the mmap stream is created and should be ignored as it does not correspond
2502 // to an actual client
2503 if (client == *clients.cbegin()) {
2504 continue;
2505 }
2506 if (uid != client->uid() && !client->isSilenced()) {
2507 ALOGW("getInputForAttr() bad uid %d for client %d uid %d",
2508 uid, client->portId(), client->uid());
2509 status = INVALID_OPERATION;
2510 goto error;
2511 }
Eric Laurent331679c2018-04-16 17:03:16 -07002512 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002513 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002514 *inputType = API_INPUT_LEGACY;
François Gaffie11d30102018-11-02 16:09:09 +01002515 device = inputDesc->getDevice();
Eric Laurentad2e7b92017-09-14 20:06:42 -07002516
Eric Laurentfecbceb2021-02-09 14:46:43 +01002517 ALOGV("%s reusing MMAP input %d for session %d", __FUNCTION__, *input, session);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002518 goto exit;
Eric Laurentad2e7b92017-09-14 20:06:42 -07002519 }
2520
2521 *input = AUDIO_IO_HANDLE_NONE;
2522 *inputType = API_INPUT_INVALID;
2523
Francois Gaffie716e1432019-01-14 16:58:59 +01002524 if (attributes.source == AUDIO_SOURCE_REMOTE_SUBMIX &&
2525 strncmp(attributes.tags, "addr=", strlen("addr=")) == 0) {
2526 status = mPolicyMixes.getInputMixForAttr(attributes, &policyMix);
Eric Laurentad2e7b92017-09-14 20:06:42 -07002527 if (status != NO_ERROR) {
jiabinc1de2df2019-05-07 14:26:40 -07002528 ALOGW("%s could not find input mix for attr %s",
2529 __func__, toString(attributes).c_str());
Eric Laurentad2e7b92017-09-14 20:06:42 -07002530 goto error;
François Gaffie036e1e92015-03-19 10:16:24 +01002531 }
jiabinc1de2df2019-05-07 14:26:40 -07002532 device = mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2533 String8(attr->tags + strlen("addr=")),
2534 AUDIO_FORMAT_DEFAULT);
2535 if (device == nullptr) {
Kevin Rocard04ed0462019-05-02 17:53:24 -07002536 ALOGW("%s could not find in Remote Submix device for source %d, tags %s",
jiabinc1de2df2019-05-07 14:26:40 -07002537 __func__, attributes.source, attributes.tags);
2538 status = BAD_VALUE;
2539 goto error;
2540 }
2541
Kevin Rocard25f9b052019-02-27 15:08:54 -08002542 if (is_mix_loopback_render(policyMix->mRouteFlags)) {
2543 *inputType = API_INPUT_MIX_PUBLIC_CAPTURE_PLAYBACK;
2544 } else {
2545 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
2546 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002547 } else {
François Gaffie11d30102018-11-02 16:09:09 +01002548 if (explicitRoutingDevice != nullptr) {
2549 device = explicitRoutingDevice;
Eric Laurent97ac8712018-07-27 18:59:02 -07002550 } else {
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01002551 // Prevent from storing invalid requested device id in clients
2552 requestedDeviceId = AUDIO_PORT_HANDLE_NONE;
yuanjiahsu0735bf32021-03-18 08:12:54 +08002553 device = mEngine->getInputDeviceForAttributes(attributes, uid, &policyMix);
yuanjiahsu4069d5d2021-04-19 07:54:27 +08002554 ALOGV_IF(device != nullptr, "%s found device type is 0x%X",
2555 __FUNCTION__, device->type());
Eric Laurent97ac8712018-07-27 18:59:02 -07002556 }
François Gaffie11d30102018-11-02 16:09:09 +01002557 if (device == nullptr) {
Francois Gaffie716e1432019-01-14 16:58:59 +01002558 ALOGW("getInputForAttr() could not find device for source %d", attributes.source);
Eric Laurentad2e7b92017-09-14 20:06:42 -07002559 status = BAD_VALUE;
2560 goto error;
Eric Laurent275e8e92014-11-30 15:14:47 -08002561 }
Alden DSouzab7d20782021-02-08 08:51:42 -08002562 if (device->type() == AUDIO_DEVICE_IN_ECHO_REFERENCE) {
2563 *inputType = API_INPUT_MIX_CAPTURE;
2564 } else if (policyMix) {
François Gaffie11d30102018-11-02 16:09:09 +01002565 ALOG_ASSERT(policyMix->mMixType == MIX_TYPE_RECORDERS, "Invalid Mix Type");
2566 // there is an external policy, but this input is attached to a mix of recorders,
2567 // meaning it receives audio injected into the framework, so the recorder doesn't
2568 // know about it and is therefore considered "legacy"
2569 *inputType = API_INPUT_LEGACY;
2570 } else if (audio_is_remote_submix_device(device->type())) {
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002571 *inputType = API_INPUT_MIX_CAPTURE;
François Gaffie11d30102018-11-02 16:09:09 +01002572 } else if (device->type() == AUDIO_DEVICE_IN_TELEPHONY_RX) {
Eric Laurent82db2692015-08-07 13:59:42 -07002573 *inputType = API_INPUT_TELEPHONY_RX;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002574 } else {
2575 *inputType = API_INPUT_LEGACY;
Eric Laurentc722f302014-12-10 11:21:49 -08002576 }
Ravi Kumar Alamandab367f5b2015-08-25 08:21:37 -07002577
Eric Laurent599c7582015-12-07 18:05:55 -08002578 }
2579
François Gaffiec005e562018-11-06 15:04:49 +01002580 *input = getInputForDevice(device, session, attributes, config, flags, policyMix);
Eric Laurent599c7582015-12-07 18:05:55 -08002581 if (*input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07002582 status = INVALID_OPERATION;
2583 goto error;
Eric Laurent599c7582015-12-07 18:05:55 -08002584 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08002585
Eric Laurent8f42ea12018-08-08 09:08:25 -07002586exit:
2587
François Gaffiec005e562018-11-06 15:04:49 +01002588 *selectedDeviceId = mAvailableInputDevices.contains(device) ?
2589 device->getId() : AUDIO_PORT_HANDLE_NONE;
Eric Laurent2ac76942017-06-22 17:17:09 -07002590
Francois Gaffie716e1432019-01-14 16:58:59 +01002591 isSoundTrigger = attributes.source == AUDIO_SOURCE_HOTWORD &&
Carter Hsud0cce2e2019-05-03 17:36:28 +08002592 mSoundTriggerSessions.indexOfKey(session) >= 0;
jiabin4ef93452019-09-10 14:29:54 -07002593 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002594
Mikhail Naganov2996f672019-04-18 12:29:59 -07002595 clientDesc = new RecordClientDescriptor(*portId, riid, uid, session, attributes, *config,
Francois Gaffie716e1432019-01-14 16:58:59 +01002596 requestedDeviceId, attributes.source, flags,
2597 isSoundTrigger);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002598 inputDesc = mInputs.valueFor(*input);
Andy Hung39efb7a2018-09-26 15:39:28 -07002599 inputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002600
2601 ALOGV("getInputForAttr() returns input %d type %d selectedDeviceId %d for port ID %d",
2602 *input, *inputType, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07002603
Eric Laurent599c7582015-12-07 18:05:55 -08002604 return NO_ERROR;
Eric Laurentad2e7b92017-09-14 20:06:42 -07002605
2606error:
Eric Laurentad2e7b92017-09-14 20:06:42 -07002607 return status;
Eric Laurent599c7582015-12-07 18:05:55 -08002608}
2609
2610
François Gaffie11d30102018-11-02 16:09:09 +01002611audio_io_handle_t AudioPolicyManager::getInputForDevice(const sp<DeviceDescriptor> &device,
Eric Laurent599c7582015-12-07 18:05:55 -08002612 audio_session_t session,
François Gaffiec005e562018-11-06 15:04:49 +01002613 const audio_attributes_t &attributes,
Eric Laurentfe231122017-11-17 17:48:06 -08002614 const audio_config_base_t *config,
Eric Laurent599c7582015-12-07 18:05:55 -08002615 audio_input_flags_t flags,
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002616 const sp<AudioPolicyMix> &policyMix)
Eric Laurent599c7582015-12-07 18:05:55 -08002617{
2618 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
François Gaffiec005e562018-11-06 15:04:49 +01002619 audio_source_t halInputSource = attributes.source;
Eric Laurent599c7582015-12-07 18:05:55 -08002620 bool isSoundTrigger = false;
2621
François Gaffiec005e562018-11-06 15:04:49 +01002622 if (attributes.source == AUDIO_SOURCE_HOTWORD) {
Eric Laurent599c7582015-12-07 18:05:55 -08002623 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
2624 if (index >= 0) {
2625 input = mSoundTriggerSessions.valueFor(session);
2626 isSoundTrigger = true;
2627 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_HW_HOTWORD);
2628 ALOGV("SoundTrigger capture on session %d input %d", session, input);
2629 } else {
2630 halInputSource = AUDIO_SOURCE_VOICE_RECOGNITION;
Eric Laurent5dbe4712014-09-19 19:04:57 -07002631 }
François Gaffiec005e562018-11-06 15:04:49 +01002632 } else if (attributes.source == AUDIO_SOURCE_VOICE_COMMUNICATION &&
Eric Laurentfe231122017-11-17 17:48:06 -08002633 audio_is_linear_pcm(config->format)) {
Haynes Mathew George851d3ff2017-06-19 20:01:57 -07002634 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_VOIP_TX);
Eric Laurent5dbe4712014-09-19 19:04:57 -07002635 }
2636
Carter Hsua3abb402021-10-26 11:11:20 +08002637 if (attributes.source == AUDIO_SOURCE_ULTRASOUND) {
2638 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_ULTRASOUND);
2639 }
2640
Andy Hungf129b032015-04-07 13:45:50 -07002641 // find a compatible input profile (not necessarily identical in parameters)
2642 sp<IOProfile> profile;
Eric Laurentfe231122017-11-17 17:48:06 -08002643 // sampling rate and flags may be updated by getInputProfile
2644 uint32_t profileSamplingRate = (config->sample_rate == 0) ?
2645 SAMPLE_RATE_HZ_DEFAULT : config->sample_rate;
Glenn Kasten730b9262018-03-29 15:01:26 -07002646 audio_format_t profileFormat;
Eric Laurentfe231122017-11-17 17:48:06 -08002647 audio_channel_mask_t profileChannelMask = config->channel_mask;
Andy Hungf129b032015-04-07 13:45:50 -07002648 audio_input_flags_t profileFlags = flags;
2649 for (;;) {
Glenn Kasten730b9262018-03-29 15:01:26 -07002650 profileFormat = config->format; // reset each time through loop, in case it is updated
François Gaffie11d30102018-11-02 16:09:09 +01002651 profile = getInputProfile(device, profileSamplingRate, profileFormat, profileChannelMask,
Andy Hungf129b032015-04-07 13:45:50 -07002652 profileFlags);
2653 if (profile != 0) {
2654 break; // success
Eric Laurent05067782016-06-01 18:27:28 -07002655 } else if (profileFlags & AUDIO_INPUT_FLAG_RAW) {
2656 profileFlags = (audio_input_flags_t) (profileFlags & ~AUDIO_INPUT_FLAG_RAW); // retry
Atneya Nair497fff12022-01-18 16:23:04 -05002657 } else if (profileFlags != AUDIO_INPUT_FLAG_NONE && audio_is_linear_pcm(config->format)) {
Andy Hungf129b032015-04-07 13:45:50 -07002658 profileFlags = AUDIO_INPUT_FLAG_NONE; // retry
2659 } else { // fail
François Gaffie11d30102018-11-02 16:09:09 +01002660 ALOGW("%s could not find profile for device %s, sampling rate %u, format %#x, "
Pattydd807582021-11-04 21:01:03 +08002661 "channel mask 0x%X, flags %#x", __func__, device->toString().c_str(),
François Gaffie11d30102018-11-02 16:09:09 +01002662 config->sample_rate, config->format, config->channel_mask, flags);
Eric Laurent599c7582015-12-07 18:05:55 -08002663 return input;
Eric Laurent5dbe4712014-09-19 19:04:57 -07002664 }
Eric Laurente552edb2014-03-10 17:42:56 -07002665 }
Glenn Kasten05ddca52016-02-11 08:17:12 -08002666 // Pick input sampling rate if not specified by client
Eric Laurentfe231122017-11-17 17:48:06 -08002667 uint32_t samplingRate = config->sample_rate;
Glenn Kasten05ddca52016-02-11 08:17:12 -08002668 if (samplingRate == 0) {
2669 samplingRate = profileSamplingRate;
2670 }
Eric Laurente552edb2014-03-10 17:42:56 -07002671
Eric Laurent322b4d22015-04-03 15:57:54 -07002672 if (profile->getModuleHandle() == 0) {
2673 ALOGE("getInputForAttr(): HW module %s not opened", profile->getModuleName());
Eric Laurent599c7582015-12-07 18:05:55 -08002674 return input;
Eric Laurentcf2c0212014-07-25 16:20:43 -07002675 }
2676
Eric Laurentec376dc2021-04-08 20:41:22 +02002677 // Reuse an already opened input if a client with the same session ID already exists
2678 // on that input
2679 for (size_t i = 0; i < mInputs.size(); i++) {
2680 sp <AudioInputDescriptor> desc = mInputs.valueAt(i);
2681 if (desc->mProfile != profile) {
2682 continue;
2683 }
2684 RecordClientVector clients = desc->clientsList();
2685 for (const auto &client : clients) {
2686 if (session == client->session()) {
2687 return desc->mIoHandle;
2688 }
2689 }
2690 }
2691
Eric Laurent3974e3b2017-12-07 17:58:43 -08002692 if (!profile->canOpenNewIo()) {
Eric Laurent4eb58f12018-12-07 16:41:02 -08002693 for (size_t i = 0; i < mInputs.size(); ) {
Eric Laurentc529cf62020-04-17 18:19:10 -07002694 sp<AudioInputDescriptor> desc = mInputs.valueAt(i);
Eric Laurent4eb58f12018-12-07 16:41:02 -08002695 if (desc->mProfile != profile) {
Carter Hsu9a645a92019-05-15 12:15:32 +08002696 i++;
Eric Laurent4eb58f12018-12-07 16:41:02 -08002697 continue;
2698 }
2699 // if sound trigger, reuse input if used by other sound trigger on same session
2700 // else
2701 // reuse input if active client app is not in IDLE state
2702 //
2703 RecordClientVector clients = desc->clientsList();
2704 bool doClose = false;
2705 for (const auto& client : clients) {
2706 if (isSoundTrigger != client->isSoundTrigger()) {
2707 continue;
2708 }
2709 if (client->isSoundTrigger()) {
2710 if (session == client->session()) {
2711 return desc->mIoHandle;
2712 }
2713 continue;
2714 }
2715 if (client->active() && client->appState() != APP_STATE_IDLE) {
2716 return desc->mIoHandle;
2717 }
2718 doClose = true;
2719 }
2720 if (doClose) {
2721 closeInput(desc->mIoHandle);
2722 } else {
2723 i++;
2724 }
2725 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002726 }
2727
Eric Laurentfe231122017-11-17 17:48:06 -08002728 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07002729
Eric Laurentfe231122017-11-17 17:48:06 -08002730 audio_config_t lConfig = AUDIO_CONFIG_INITIALIZER;
2731 lConfig.sample_rate = profileSamplingRate;
2732 lConfig.channel_mask = profileChannelMask;
2733 lConfig.format = profileFormat;
Eric Laurente3014102017-05-03 11:15:43 -07002734
François Gaffie11d30102018-11-02 16:09:09 +01002735 status_t status = inputDesc->open(&lConfig, device, halInputSource, profileFlags, &input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07002736
2737 // only accept input with the exact requested set of parameters
Eric Laurent599c7582015-12-07 18:05:55 -08002738 if (status != NO_ERROR || input == AUDIO_IO_HANDLE_NONE ||
Eric Laurentfe231122017-11-17 17:48:06 -08002739 (profileSamplingRate != lConfig.sample_rate) ||
2740 !audio_formats_match(profileFormat, lConfig.format) ||
2741 (profileChannelMask != lConfig.channel_mask)) {
2742 ALOGW("getInputForAttr() failed opening input: sampling rate %d"
Glenn Kasten49f36ba2017-12-06 13:02:02 -08002743 ", format %#x, channel mask %#x",
Eric Laurentfe231122017-11-17 17:48:06 -08002744 profileSamplingRate, profileFormat, profileChannelMask);
Eric Laurent599c7582015-12-07 18:05:55 -08002745 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfe231122017-11-17 17:48:06 -08002746 inputDesc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07002747 }
Eric Laurent599c7582015-12-07 18:05:55 -08002748 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07002749 }
2750
Eric Laurentc722f302014-12-10 11:21:49 -08002751 inputDesc->mPolicyMix = policyMix;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002752
Eric Laurent599c7582015-12-07 18:05:55 -08002753 addInput(input, inputDesc);
Eric Laurentb52c1522014-05-20 11:27:36 -07002754 mpClientInterface->onAudioPortListUpdate();
Paul McLean466dc8e2015-04-17 13:15:36 -06002755
Eric Laurent599c7582015-12-07 18:05:55 -08002756 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07002757}
2758
Eric Laurent4eb58f12018-12-07 16:41:02 -08002759status_t AudioPolicyManager::startInput(audio_port_handle_t portId)
Eric Laurentbb948092017-01-23 18:33:30 -08002760{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002761 ALOGV("%s portId %d", __FUNCTION__, portId);
2762
2763 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2764 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002765 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurentd52a28c2020-08-21 17:10:39 -07002766 return DEAD_OBJECT;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002767 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002768 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07002769 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002770 if (client->active()) {
2771 ALOGW("%s input %d client %d already started", __FUNCTION__, input, client->portId());
2772 return INVALID_OPERATION;
Eric Laurent4dc68062014-07-28 17:26:49 -07002773 }
2774
Eric Laurent8f42ea12018-08-08 09:08:25 -07002775 audio_session_t session = client->session();
2776
Eric Laurent4eb58f12018-12-07 16:41:02 -08002777 ALOGV("%s input:%d, session:%d)", __FUNCTION__, input, session);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002778
Eric Laurent4eb58f12018-12-07 16:41:02 -08002779 Vector<sp<AudioInputDescriptor>> activeInputs = mInputs.getActiveInputs();
Eric Laurent74708e72017-04-07 17:13:42 -07002780
Eric Laurent4eb58f12018-12-07 16:41:02 -08002781 status_t status = inputDesc->start();
2782 if (status != NO_ERROR) {
2783 return status;
Eric Laurent74708e72017-04-07 17:13:42 -07002784 }
Eric Laurente552edb2014-03-10 17:42:56 -07002785
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002786 // increment activity count before calling getNewInputDevice() below as only active sessions
Eric Laurent313d1e72016-01-29 09:56:57 -08002787 // are considered for device selection
Eric Laurent8f42ea12018-08-08 09:08:25 -07002788 inputDesc->setClientActive(client, true);
Eric Laurent313d1e72016-01-29 09:56:57 -08002789
Eric Laurent8f42ea12018-08-08 09:08:25 -07002790 // indicate active capture to sound trigger service if starting capture from a mic on
2791 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01002792 sp<DeviceDescriptor> device = getNewInputDevice(inputDesc);
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002793 if (device != nullptr) {
2794 status = setInputDevice(input, device, true /* force */);
2795 } else {
2796 ALOGW("%s no new input device can be found for descriptor %d",
2797 __FUNCTION__, inputDesc->getId());
2798 status = BAD_VALUE;
2799 }
Eric Laurente552edb2014-03-10 17:42:56 -07002800
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002801 if (status == NO_ERROR && inputDesc->activeCount() == 1) {
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002802 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002803 // if input maps to a dynamic policy with an activity listener, notify of state change
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002804 if ((policyMix != nullptr)
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002805 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
2806 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
Eric Laurent8f42ea12018-08-08 09:08:25 -07002807 MIX_STATE_MIXING);
Eric Laurent733ce942017-12-07 12:18:25 -08002808 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002809
François Gaffie11d30102018-11-02 16:09:09 +01002810 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
2811 if (primaryInputDevices.contains(device) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07002812 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 1) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07002813 mpClientInterface->setSoundTriggerCaptureState(true);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002814 }
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002815
Eric Laurent8f42ea12018-08-08 09:08:25 -07002816 // automatically enable the remote submix output when input is started if not
2817 // used by a policy mix of type MIX_TYPE_RECORDERS
2818 // For remote submix (a virtual device), we open only one input per capture request.
François Gaffie11d30102018-11-02 16:09:09 +01002819 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002820 String8 address = String8("");
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002821 if (policyMix == nullptr) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002822 address = String8("0");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002823 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
2824 address = policyMix->mDeviceAddress;
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002825 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07002826 if (address != "") {
2827 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2828 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002829 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurentc722f302014-12-10 11:21:49 -08002830 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07002831 }
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002832 } else if (status != NO_ERROR) {
2833 // Restore client activity state.
2834 inputDesc->setClientActive(client, false);
2835 inputDesc->stop();
Eric Laurente552edb2014-03-10 17:42:56 -07002836 }
2837
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002838 ALOGV("%s input %d source = %d status = %d exit",
2839 __FUNCTION__, input, client->source(), status);
Eric Laurente552edb2014-03-10 17:42:56 -07002840
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002841 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07002842}
2843
Eric Laurent8fc147b2018-07-22 19:13:55 -07002844status_t AudioPolicyManager::stopInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002845{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002846 ALOGV("%s portId %d", __FUNCTION__, portId);
2847
2848 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2849 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002850 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002851 return BAD_VALUE;
2852 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002853 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07002854 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002855 if (!client->active()) {
2856 ALOGW("%s input %d client %d already stopped", __FUNCTION__, input, client->portId());
Eric Laurente552edb2014-03-10 17:42:56 -07002857 return INVALID_OPERATION;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002858 }
Carter Hsue6139d52021-07-08 10:30:20 +08002859 auto old_source = inputDesc->source();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002860 inputDesc->setClientActive(client, false);
Paul McLean466dc8e2015-04-17 13:15:36 -06002861
Eric Laurent8f42ea12018-08-08 09:08:25 -07002862 inputDesc->stop();
2863 if (inputDesc->isActive()) {
Carter Hsue6139d52021-07-08 10:30:20 +08002864 auto current_source = inputDesc->source();
2865 setInputDevice(input, getNewInputDevice(inputDesc),
2866 old_source != current_source /* force */);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002867 } else {
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002868 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002869 // if input maps to a dynamic policy with an activity listener, notify of state change
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002870 if ((policyMix != nullptr)
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002871 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
2872 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
Eric Laurent8f42ea12018-08-08 09:08:25 -07002873 MIX_STATE_IDLE);
Eric Laurent84332aa2016-01-28 22:19:18 +00002874 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07002875
2876 // automatically disable the remote submix output when input is stopped if not
2877 // used by a policy mix of type MIX_TYPE_RECORDERS
François Gaffie11d30102018-11-02 16:09:09 +01002878 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002879 String8 address = String8("");
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002880 if (policyMix == nullptr) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002881 address = String8("0");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002882 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
2883 address = policyMix->mDeviceAddress;
Eric Laurent8f42ea12018-08-08 09:08:25 -07002884 }
2885 if (address != "") {
2886 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2887 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002888 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002889 }
2890 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07002891 resetInputDevice(input);
2892
2893 // indicate inactive capture to sound trigger service if stopping capture from a mic on
2894 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01002895 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
2896 if (primaryInputDevices.contains(inputDesc->getDevice()) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07002897 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07002898 mpClientInterface->setSoundTriggerCaptureState(false);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002899 }
2900 inputDesc->clearPreemptedSessions();
Eric Laurente552edb2014-03-10 17:42:56 -07002901 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002902 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07002903}
2904
Eric Laurent8fc147b2018-07-22 19:13:55 -07002905void AudioPolicyManager::releaseInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002906{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002907 ALOGV("%s portId %d", __FUNCTION__, portId);
2908
2909 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2910 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002911 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002912 return;
2913 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002914 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002915 audio_io_handle_t input = inputDesc->mIoHandle;
2916
Eric Laurent8f42ea12018-08-08 09:08:25 -07002917 ALOGV("%s %d", __FUNCTION__, input);
Paul McLean466dc8e2015-04-17 13:15:36 -06002918
Andy Hung39efb7a2018-09-26 15:39:28 -07002919 inputDesc->removeClient(portId);
Eric Laurent599c7582015-12-07 18:05:55 -08002920
Andy Hung39efb7a2018-09-26 15:39:28 -07002921 if (inputDesc->getClientCount() > 0) {
2922 ALOGV("%s(%d) %zu clients remaining", __func__, portId, inputDesc->getClientCount());
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002923 return;
2924 }
2925
Eric Laurent05b90f82014-08-27 15:32:29 -07002926 closeInput(input);
Eric Laurentb52c1522014-05-20 11:27:36 -07002927 mpClientInterface->onAudioPortListUpdate();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002928 ALOGV("%s exit", __FUNCTION__);
Eric Laurente552edb2014-03-10 17:42:56 -07002929}
2930
Eric Laurent8f42ea12018-08-08 09:08:25 -07002931void AudioPolicyManager::closeActiveClients(const sp<AudioInputDescriptor>& input)
Eric Laurent8fc147b2018-07-22 19:13:55 -07002932{
Eric Laurent8f42ea12018-08-08 09:08:25 -07002933 RecordClientVector clients = input->clientsList(true);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002934
2935 for (const auto& client : clients) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002936 closeClient(client->portId());
Eric Laurent8fc147b2018-07-22 19:13:55 -07002937 }
2938}
2939
Eric Laurent8f42ea12018-08-08 09:08:25 -07002940void AudioPolicyManager::closeClient(audio_port_handle_t portId)
2941{
2942 stopInput(portId);
2943 releaseInput(portId);
2944}
Eric Laurent8fc147b2018-07-22 19:13:55 -07002945
Eric Laurent0dd51852019-04-19 18:18:58 -07002946void AudioPolicyManager::checkCloseInputs() {
2947 // After connecting or disconnecting an input device, close input if:
2948 // - it has no client (was just opened to check profile) OR
2949 // - none of its supported devices are connected anymore OR
2950 // - one of its clients cannot be routed to one of its supported
2951 // devices anymore. Otherwise update device selection
2952 std::vector<audio_io_handle_t> inputsToClose;
2953 for (size_t i = 0; i < mInputs.size(); i++) {
2954 const sp<AudioInputDescriptor> input = mInputs.valueAt(i);
2955 if (input->clientsList().size() == 0
Eric Laurent85732f42020-03-19 11:31:10 -07002956 || !mAvailableInputDevices.containsAtLeastOne(input->supportedDevices())) {
Eric Laurent0dd51852019-04-19 18:18:58 -07002957 inputsToClose.push_back(mInputs.keyAt(i));
2958 } else {
2959 bool close = false;
2960 for (const auto& client : input->clientsList()) {
2961 sp<DeviceDescriptor> device =
yuanjiahsu0735bf32021-03-18 08:12:54 +08002962 mEngine->getInputDeviceForAttributes(client->attributes(), client->uid());
Eric Laurent0dd51852019-04-19 18:18:58 -07002963 if (!input->supportedDevices().contains(device)) {
2964 close = true;
2965 break;
2966 }
2967 }
2968 if (close) {
2969 inputsToClose.push_back(mInputs.keyAt(i));
2970 } else {
2971 setInputDevice(input->mIoHandle, getNewInputDevice(input));
2972 }
2973 }
2974 }
2975
2976 for (const audio_io_handle_t handle : inputsToClose) {
2977 ALOGV("%s closing input %d", __func__, handle);
2978 closeInput(handle);
Eric Laurent05b90f82014-08-27 15:32:29 -07002979 }
Eric Laurentd4692962014-05-05 18:13:44 -07002980}
2981
François Gaffie251c7f02018-11-07 10:41:08 +01002982void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream, int indexMin, int indexMax)
Eric Laurente552edb2014-03-10 17:42:56 -07002983{
2984 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08002985 if (indexMin < 0 || indexMax < 0) {
2986 ALOGE("%s for stream %d: invalid min %d or max %d", __func__, stream , indexMin, indexMax);
2987 return;
2988 }
Eric Laurentf5aa58d2019-02-22 18:20:11 -08002989 getVolumeCurves(stream).initVolume(indexMin, indexMax);
Eric Laurent28d09f02016-03-08 10:43:05 -08002990
2991 // initialize other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08002992 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
2993 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002994 continue;
2995 }
Eric Laurentf5aa58d2019-02-22 18:20:11 -08002996 getVolumeCurves((audio_stream_type_t)curStream).initVolume(indexMin, indexMax);
Eric Laurent223fd5c2014-11-11 13:43:36 -08002997 }
Eric Laurente552edb2014-03-10 17:42:56 -07002998}
2999
Eric Laurente0720872014-03-11 09:30:41 -07003000status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
François Gaffie53615e22015-03-19 09:24:12 +01003001 int index,
3002 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07003003{
François Gaffieaaac0fd2018-11-22 17:56:39 +01003004 auto attributes = mEngine->getAttributesForStreamType(stream);
Eric Laurent242a9f82020-03-23 15:57:04 -07003005 if (attributes == AUDIO_ATTRIBUTES_INITIALIZER) {
3006 ALOGW("%s: no group for stream %s, bailing out", __func__, toString(stream).c_str());
3007 return NO_ERROR;
3008 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01003009 ALOGV("%s: stream %s attributes=%s", __func__,
3010 toString(stream).c_str(), toString(attributes).c_str());
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003011 return setVolumeIndexForAttributes(attributes, index, device);
Eric Laurente552edb2014-03-10 17:42:56 -07003012}
3013
Eric Laurente0720872014-03-11 09:30:41 -07003014status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
François Gaffieaaac0fd2018-11-22 17:56:39 +01003015 int *index,
3016 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07003017{
François Gaffiec005e562018-11-06 15:04:49 +01003018 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
3019 // stream by the engine.
jiabin9a3361e2019-10-01 09:38:30 -07003020 DeviceTypeSet deviceTypes = {device};
Eric Laurent5a2b6292016-04-14 18:05:57 -07003021 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
jiabin9a3361e2019-10-01 09:38:30 -07003022 deviceTypes = mEngine->getOutputDevicesForStream(
3023 stream, true /*fromCache*/).types();
Eric Laurente552edb2014-03-10 17:42:56 -07003024 }
jiabin9a3361e2019-10-01 09:38:30 -07003025 return getVolumeIndex(getVolumeCurves(stream), *index, deviceTypes);
Eric Laurente552edb2014-03-10 17:42:56 -07003026}
3027
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003028status_t AudioPolicyManager::setVolumeIndexForAttributes(const audio_attributes_t &attributes,
François Gaffiecfe17322018-11-07 13:41:29 +01003029 int index,
3030 audio_devices_t device)
3031{
3032 // Get Volume group matching the Audio Attributes
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003033 auto group = mEngine->getVolumeGroupForAttributes(attributes);
3034 if (group == VOLUME_GROUP_NONE) {
3035 ALOGD("%s: no group matching with %s", __FUNCTION__, toString(attributes).c_str());
François Gaffiecfe17322018-11-07 13:41:29 +01003036 return BAD_VALUE;
3037 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003038 ALOGV("%s: group %d matching with %s", __FUNCTION__, group, toString(attributes).c_str());
François Gaffiecfe17322018-11-07 13:41:29 +01003039 status_t status = NO_ERROR;
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003040 IVolumeCurves &curves = getVolumeCurves(attributes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01003041 VolumeSource vs = toVolumeSource(group);
Eric Laurentf9cccec2022-11-16 19:12:00 +01003042 // AUDIO_STREAM_BLUETOOTH_SCO is only used for volume control so we remap
3043 // to AUDIO_STREAM_VOICE_CALL to match with relevant playback activity
3044 VolumeSource activityVs = (vs == toVolumeSource(AUDIO_STREAM_BLUETOOTH_SCO, false)) ?
3045 toVolumeSource(AUDIO_STREAM_VOICE_CALL, false) : vs;
François Gaffieaaac0fd2018-11-22 17:56:39 +01003046 product_strategy_t strategy = mEngine->getProductStrategyForAttributes(attributes);
3047
3048 status = setVolumeCurveIndex(index, device, curves);
3049 if (status != NO_ERROR) {
3050 ALOGE("%s failed to set curve index for group %d device 0x%X", __func__, group, device);
3051 return status;
3052 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003053
jiabin9a3361e2019-10-01 09:38:30 -07003054 DeviceTypeSet curSrcDevices;
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003055 auto curCurvAttrs = curves.getAttributes();
3056 if (!curCurvAttrs.empty() && curCurvAttrs.front() != defaultAttr) {
3057 auto attr = curCurvAttrs.front();
jiabin9a3361e2019-10-01 09:38:30 -07003058 curSrcDevices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false).types();
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003059 } else if (!curves.getStreamTypes().empty()) {
3060 auto stream = curves.getStreamTypes().front();
jiabin9a3361e2019-10-01 09:38:30 -07003061 curSrcDevices = mEngine->getOutputDevicesForStream(stream, false).types();
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003062 } else {
3063 ALOGE("%s: Invalid src %d: no valid attributes nor stream",__func__, vs);
3064 return BAD_VALUE;
3065 }
jiabin9a3361e2019-10-01 09:38:30 -07003066 audio_devices_t curSrcDevice = Volume::getDeviceForVolume(curSrcDevices);
3067 resetDeviceTypes(curSrcDevices, curSrcDevice);
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003068
François Gaffiecfe17322018-11-07 13:41:29 +01003069 // update volume on all outputs and streams matching the following:
3070 // - The requested stream (or a stream matching for volume control) is active on the output
3071 // - The device (or devices) selected by the engine for this stream includes
3072 // the requested device
3073 // - For non default requested device, currently selected device on the output is either the
3074 // requested device or one of the devices selected by the engine for this stream
3075 // - For default requested device (AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME), apply volume only if
3076 // no specific device volume value exists for currently selected device.
François Gaffieaaac0fd2018-11-22 17:56:39 +01003077 for (size_t i = 0; i < mOutputs.size(); i++) {
3078 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
jiabin9a3361e2019-10-01 09:38:30 -07003079 DeviceTypeSet curDevices = desc->devices().types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01003080
jiabin9a3361e2019-10-01 09:38:30 -07003081 if (curDevices.erase(AUDIO_DEVICE_OUT_SPEAKER_SAFE)) {
3082 curDevices.insert(AUDIO_DEVICE_OUT_SPEAKER);
Robert Lee5e66e792019-04-03 18:37:15 +08003083 }
Eric Laurentf9cccec2022-11-16 19:12:00 +01003084
3085 if (!(desc->isActive(activityVs) || isInCallOrScreening())) {
François Gaffieed91f582020-01-31 10:35:37 +01003086 continue;
3087 }
3088 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME &&
3089 curDevices.find(device) == curDevices.end()) {
3090 continue;
3091 }
3092 bool applyVolume = false;
3093 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
3094 curSrcDevices.insert(device);
3095 applyVolume = (curSrcDevices.find(
3096 Volume::getDeviceForVolume(curDevices)) != curSrcDevices.end());
3097 } else {
3098 applyVolume = !curves.hasVolumeIndexForDevice(curSrcDevice);
3099 }
3100 if (!applyVolume) {
3101 continue; // next output
3102 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01003103 // Inter / intra volume group priority management: Loop on strategies arranged by priority
3104 // If a higher priority strategy is active, and the output is routed to a device with a
3105 // HW Gain management, do not change the volume
François Gaffieaaac0fd2018-11-22 17:56:39 +01003106 if (desc->useHwGain()) {
François Gaffieed91f582020-01-31 10:35:37 +01003107 applyVolume = false;
Francois Gaffie593634d2021-06-22 13:31:31 +02003108 // If the volume source is active with higher priority source, ensure at least Sw Muted
3109 desc->setSwMute((index == 0), vs, curves.getStreamTypes(), curDevices, 0 /*delayMs*/);
François Gaffieaaac0fd2018-11-22 17:56:39 +01003110 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
3111 auto activeClients = desc->clientsList(true /*activeOnly*/, productStrategy,
3112 false /*preferredDevice*/);
3113 if (activeClients.empty()) {
3114 continue;
3115 }
3116 bool isPreempted = false;
3117 bool isHigherPriority = productStrategy < strategy;
3118 for (const auto &client : activeClients) {
Eric Laurentf9cccec2022-11-16 19:12:00 +01003119 if (isHigherPriority && (client->volumeSource() != activityVs)) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01003120 ALOGV("%s: Strategy=%d (\nrequester:\n"
3121 " group %d, volumeGroup=%d attributes=%s)\n"
3122 " higher priority source active:\n"
3123 " volumeGroup=%d attributes=%s) \n"
3124 " on output %zu, bailing out", __func__, productStrategy,
3125 group, group, toString(attributes).c_str(),
3126 client->volumeSource(), toString(client->attributes()).c_str(), i);
3127 applyVolume = false;
3128 isPreempted = true;
3129 break;
3130 }
3131 // However, continue for loop to ensure no higher prio clients running on output
Eric Laurentf9cccec2022-11-16 19:12:00 +01003132 if (client->volumeSource() == activityVs) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01003133 applyVolume = true;
3134 }
3135 }
3136 if (isPreempted || applyVolume) {
3137 break;
3138 }
3139 }
3140 if (!applyVolume) {
3141 continue; // next output
3142 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01003143 }
François Gaffieed91f582020-01-31 10:35:37 +01003144 //FIXME: workaround for truncated touch sounds
3145 // delayed volume change for system stream to be removed when the problem is
3146 // handled by system UI
3147 status_t volStatus = checkAndSetVolume(
3148 curves, vs, index, desc, curDevices,
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003149 ((vs == toVolumeSource(AUDIO_STREAM_SYSTEM, false))?
François Gaffieed91f582020-01-31 10:35:37 +01003150 TOUCH_SOUND_FIXED_DELAY_MS : 0));
3151 if (volStatus != NO_ERROR) {
3152 status = volStatus;
François Gaffieaaac0fd2018-11-22 17:56:39 +01003153 }
3154 }
François Gaffiecfe17322018-11-07 13:41:29 +01003155 mpClientInterface->onAudioVolumeGroupChanged(group, 0 /*flags*/);
3156 return status;
3157}
3158
François Gaffieaaac0fd2018-11-22 17:56:39 +01003159status_t AudioPolicyManager::setVolumeCurveIndex(int index,
François Gaffiecfe17322018-11-07 13:41:29 +01003160 audio_devices_t device,
3161 IVolumeCurves &volumeCurves)
3162{
3163 // VOICE_CALL stream has minVolumeIndex > 0 but can be muted directly by an
3164 // app that has MODIFY_PHONE_STATE permission.
François Gaffieaaac0fd2018-11-22 17:56:39 +01003165 bool hasVoice = hasVoiceStream(volumeCurves.getStreamTypes());
3166 if (((index < volumeCurves.getVolumeIndexMin()) && !(hasVoice && index == 0)) ||
François Gaffiecfe17322018-11-07 13:41:29 +01003167 (index > volumeCurves.getVolumeIndexMax())) {
3168 ALOGD("%s: wrong index %d min=%d max=%d", __FUNCTION__, index,
3169 volumeCurves.getVolumeIndexMin(), volumeCurves.getVolumeIndexMax());
3170 return BAD_VALUE;
3171 }
3172 if (!audio_is_output_device(device)) {
3173 return BAD_VALUE;
3174 }
3175
3176 // Force max volume if stream cannot be muted
3177 if (!volumeCurves.canBeMuted()) index = volumeCurves.getVolumeIndexMax();
3178
François Gaffieaaac0fd2018-11-22 17:56:39 +01003179 ALOGV("%s device %08x, index %d", __FUNCTION__ , device, index);
François Gaffiecfe17322018-11-07 13:41:29 +01003180 volumeCurves.addCurrentVolumeIndex(device, index);
3181 return NO_ERROR;
3182}
3183
3184status_t AudioPolicyManager::getVolumeIndexForAttributes(const audio_attributes_t &attr,
3185 int &index,
3186 audio_devices_t device)
3187{
3188 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
3189 // stream by the engine.
jiabin9a3361e2019-10-01 09:38:30 -07003190 DeviceTypeSet deviceTypes = {device};
François Gaffiecfe17322018-11-07 13:41:29 +01003191 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
Mikhail Naganovbb990f22022-06-15 00:46:43 +00003192 deviceTypes = mEngine->getOutputDevicesForAttributes(
jiabin9a3361e2019-10-01 09:38:30 -07003193 attr, nullptr, true /*fromCache*/).types();
François Gaffiecfe17322018-11-07 13:41:29 +01003194 }
jiabin9a3361e2019-10-01 09:38:30 -07003195 return getVolumeIndex(getVolumeCurves(attr), index, deviceTypes);
François Gaffiecfe17322018-11-07 13:41:29 +01003196}
3197
3198status_t AudioPolicyManager::getVolumeIndex(const IVolumeCurves &curves,
3199 int &index,
jiabin9a3361e2019-10-01 09:38:30 -07003200 const DeviceTypeSet& deviceTypes) const
François Gaffiecfe17322018-11-07 13:41:29 +01003201{
Mikhail Naganovbb990f22022-06-15 00:46:43 +00003202 if (!isSingleDeviceType(deviceTypes, audio_is_output_device)) {
François Gaffiecfe17322018-11-07 13:41:29 +01003203 return BAD_VALUE;
3204 }
jiabin9a3361e2019-10-01 09:38:30 -07003205 index = curves.getVolumeIndex(deviceTypes);
3206 ALOGV("%s: device %s index %d", __FUNCTION__, dumpDeviceTypes(deviceTypes).c_str(), index);
François Gaffiecfe17322018-11-07 13:41:29 +01003207 return NO_ERROR;
3208}
3209
3210status_t AudioPolicyManager::getMinVolumeIndexForAttributes(const audio_attributes_t &attr,
3211 int &index)
3212{
3213 index = getVolumeCurves(attr).getVolumeIndexMin();
3214 return NO_ERROR;
3215}
3216
3217status_t AudioPolicyManager::getMaxVolumeIndexForAttributes(const audio_attributes_t &attr,
3218 int &index)
3219{
3220 index = getVolumeCurves(attr).getVolumeIndexMax();
3221 return NO_ERROR;
3222}
3223
Eric Laurent36829f92017-04-07 19:04:42 -07003224audio_io_handle_t AudioPolicyManager::selectOutputForMusicEffects()
Eric Laurente552edb2014-03-10 17:42:56 -07003225{
3226 // select one output among several suitable for global effects.
3227 // The priority is as follows:
3228 // 1: An offloaded output. If the effect ends up not being offloadable,
3229 // AudioFlinger will invalidate the track and the offloaded output
3230 // will be closed causing the effect to be moved to a PCM output.
3231 // 2: A deep buffer output
Eric Laurent36829f92017-04-07 19:04:42 -07003232 // 3: The primary output
3233 // 4: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07003234
François Gaffiec005e562018-11-06 15:04:49 +01003235 DeviceVector devices = mEngine->getOutputDevicesForAttributes(
3236 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
François Gaffie11d30102018-11-02 16:09:09 +01003237 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07003238
Eric Laurent36829f92017-04-07 19:04:42 -07003239 if (outputs.size() == 0) {
3240 return AUDIO_IO_HANDLE_NONE;
3241 }
Eric Laurente552edb2014-03-10 17:42:56 -07003242
Eric Laurent36829f92017-04-07 19:04:42 -07003243 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
3244 bool activeOnly = true;
3245
3246 while (output == AUDIO_IO_HANDLE_NONE) {
3247 audio_io_handle_t outputOffloaded = AUDIO_IO_HANDLE_NONE;
3248 audio_io_handle_t outputDeepBuffer = AUDIO_IO_HANDLE_NONE;
3249 audio_io_handle_t outputPrimary = AUDIO_IO_HANDLE_NONE;
3250
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003251 for (audio_io_handle_t output : outputs) {
3252 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
Eric Laurent83d17c22019-04-02 17:10:01 -07003253 if (activeOnly && !desc->isActive(toVolumeSource(AUDIO_STREAM_MUSIC))) {
Eric Laurent36829f92017-04-07 19:04:42 -07003254 continue;
3255 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003256 ALOGV("selectOutputForMusicEffects activeOnly %d output %d flags 0x%08x",
3257 activeOnly, output, desc->mFlags);
Eric Laurent36829f92017-04-07 19:04:42 -07003258 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003259 outputOffloaded = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003260 }
3261 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003262 outputDeepBuffer = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003263 }
3264 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003265 outputPrimary = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003266 }
3267 }
3268 if (outputOffloaded != AUDIO_IO_HANDLE_NONE) {
3269 output = outputOffloaded;
3270 } else if (outputDeepBuffer != AUDIO_IO_HANDLE_NONE) {
3271 output = outputDeepBuffer;
3272 } else if (outputPrimary != AUDIO_IO_HANDLE_NONE) {
3273 output = outputPrimary;
3274 } else {
3275 output = outputs[0];
3276 }
3277 activeOnly = false;
3278 }
3279
3280 if (output != mMusicEffectOutput) {
Eric Laurent6c796322019-04-09 14:13:17 -07003281 mEffects.moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output);
Eric Laurent36829f92017-04-07 19:04:42 -07003282 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output);
3283 mMusicEffectOutput = output;
3284 }
3285
3286 ALOGV("selectOutputForMusicEffects selected output %d", output);
Eric Laurente552edb2014-03-10 17:42:56 -07003287 return output;
3288}
3289
Eric Laurent36829f92017-04-07 19:04:42 -07003290audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc __unused)
3291{
3292 return selectOutputForMusicEffects();
3293}
3294
Eric Laurente0720872014-03-11 09:30:41 -07003295status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07003296 audio_io_handle_t io,
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08003297 product_strategy_t strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07003298 int session,
3299 int id)
3300{
Eric Laurentb82e6b72019-11-22 17:25:04 -08003301 if (session != AUDIO_SESSION_DEVICE) {
3302 ssize_t index = mOutputs.indexOfKey(io);
Eric Laurente552edb2014-03-10 17:42:56 -07003303 if (index < 0) {
Eric Laurentb82e6b72019-11-22 17:25:04 -08003304 index = mInputs.indexOfKey(io);
3305 if (index < 0) {
3306 ALOGW("registerEffect() unknown io %d", io);
3307 return INVALID_OPERATION;
3308 }
Eric Laurente552edb2014-03-10 17:42:56 -07003309 }
3310 }
Eric Laurentbf8f69f2022-03-25 17:48:38 +01003311 bool isMusicEffect = (session != AUDIO_SESSION_OUTPUT_STAGE)
3312 && ((strategy == streamToStrategy(AUDIO_STREAM_MUSIC)
3313 || strategy == PRODUCT_STRATEGY_NONE));
3314 return mEffects.registerEffect(desc, io, session, id, isMusicEffect);
Eric Laurente552edb2014-03-10 17:42:56 -07003315}
3316
Eric Laurentc241b0d2018-11-28 09:08:49 -08003317status_t AudioPolicyManager::unregisterEffect(int id)
3318{
3319 if (mEffects.getEffect(id) == nullptr) {
3320 return INVALID_OPERATION;
3321 }
Eric Laurentc241b0d2018-11-28 09:08:49 -08003322 if (mEffects.isEffectEnabled(id)) {
3323 ALOGW("%s effect %d enabled", __FUNCTION__, id);
3324 setEffectEnabled(id, false);
3325 }
3326 return mEffects.unregisterEffect(id);
3327}
3328
3329status_t AudioPolicyManager::setEffectEnabled(int id, bool enabled)
3330{
3331 sp<EffectDescriptor> effect = mEffects.getEffect(id);
3332 if (effect == nullptr) {
3333 return INVALID_OPERATION;
3334 }
3335
3336 status_t status = mEffects.setEffectEnabled(id, enabled);
3337 if (status == NO_ERROR) {
3338 mInputs.trackEffectEnabled(effect, enabled);
3339 }
3340 return status;
3341}
3342
Eric Laurent6c796322019-04-09 14:13:17 -07003343
3344status_t AudioPolicyManager::moveEffectsToIo(const std::vector<int>& ids, audio_io_handle_t io)
3345{
3346 mEffects.moveEffects(ids, io);
3347 return NO_ERROR;
3348}
3349
Eric Laurentc75307b2015-03-17 15:29:32 -07003350bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
3351{
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003352 auto vs = toVolumeSource(stream, false);
3353 return vs != VOLUME_SOURCE_NONE ? mOutputs.isActive(vs, inPastMs) : false;
Eric Laurentc75307b2015-03-17 15:29:32 -07003354}
3355
3356bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream, uint32_t inPastMs) const
3357{
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003358 auto vs = toVolumeSource(stream, false);
3359 return vs != VOLUME_SOURCE_NONE ? mOutputs.isActiveRemotely(vs, inPastMs) : false;
Eric Laurentc75307b2015-03-17 15:29:32 -07003360}
3361
Eric Laurente0720872014-03-11 09:30:41 -07003362bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07003363{
3364 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003365 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08003366 if (inputDescriptor->isSourceActive(source)) {
Eric Laurente552edb2014-03-10 17:42:56 -07003367 return true;
3368 }
3369 }
3370 return false;
3371}
3372
Eric Laurent275e8e92014-11-30 15:14:47 -08003373// Register a list of custom mixes with their attributes and format.
3374// When a mix is registered, corresponding input and output profiles are
3375// added to the remote submix hw module. The profile contains only the
3376// parameters (sampling rate, format...) specified by the mix.
3377// The corresponding input remote submix device is also connected.
3378//
3379// When a remote submix device is connected, the address is checked to select the
3380// appropriate profile and the corresponding input or output stream is opened.
3381//
3382// When capture starts, getInputForAttr() will:
3383// - 1 look for a mix matching the address passed in attribtutes tags if any
3384// - 2 if none found, getDeviceForInputSource() will:
3385// - 2.1 look for a mix matching the attributes source
3386// - 2.2 if none found, default to device selection by policy rules
3387// At this time, the corresponding output remote submix device is also connected
3388// and active playback use cases can be transferred to this mix if needed when reconnecting
3389// after AudioTracks are invalidated
3390//
3391// When playback starts, getOutputForAttr() will:
3392// - 1 look for a mix matching the address passed in attribtutes tags if any
3393// - 2 if none found, look for a mix matching the attributes usage
3394// - 3 if none found, default to device and output selection by policy rules.
3395
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003396status_t AudioPolicyManager::registerPolicyMixes(const Vector<AudioMix>& mixes)
Eric Laurent275e8e92014-11-30 15:14:47 -08003397{
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003398 ALOGV("registerPolicyMixes() %zu mix(es)", mixes.size());
3399 status_t res = NO_ERROR;
Eric Laurentc209fe42020-06-05 18:11:23 -07003400 bool checkOutputs = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003401 sp<HwModule> rSubmixModule;
3402 // examine each mix's route type
3403 for (size_t i = 0; i < mixes.size(); i++) {
Eric Laurent97ac8712018-07-27 18:59:02 -07003404 AudioMix mix = mixes[i];
Kevin Rocard153f92d2018-12-18 18:33:28 -08003405 // Only capture of playback is allowed in LOOP_BACK & RENDER mode
3406 if (is_mix_loopback_render(mix.mRouteFlags) && mix.mMixType != MIX_TYPE_PLAYERS) {
3407 ALOGE("Unsupported Policy Mix %zu of %zu: "
3408 "Only capture of playback is allowed in LOOP_BACK & RENDER mode",
3409 i, mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003410 res = INVALID_OPERATION;
Eric Laurent275e8e92014-11-30 15:14:47 -08003411 break;
3412 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08003413 // LOOP_BACK and LOOP_BACK | RENDER have the same remote submix backend and are handled
3414 // in the same way.
Eric Laurent97ac8712018-07-27 18:59:02 -07003415 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003416 ALOGV("registerPolicyMixes() mix %zu of %zu is LOOP_BACK %d", i, mixes.size(),
3417 mix.mRouteFlags);
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003418 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003419 rSubmixModule = mHwModules.getModuleFromName(
3420 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
3421 if (rSubmixModule == 0) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003422 ALOGE("Unable to find audio module for submix, aborting mix %zu registration",
Mikhail Naganovd4120142017-12-06 15:49:22 -08003423 i);
3424 res = INVALID_OPERATION;
3425 break;
3426 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003427 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003428
Eric Laurent97ac8712018-07-27 18:59:02 -07003429 String8 address = mix.mDeviceAddress;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003430 audio_devices_t deviceTypeToMakeAvailable;
Eric Laurent97ac8712018-07-27 18:59:02 -07003431 if (mix.mMixType == MIX_TYPE_PLAYERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07003432 mix.mDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003433 deviceTypeToMakeAvailable = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
3434 } else {
3435 mix.mDeviceType = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
3436 deviceTypeToMakeAvailable = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Eric Laurent97ac8712018-07-27 18:59:02 -07003437 }
François Gaffie036e1e92015-03-19 10:16:24 +01003438
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003439 if (mPolicyMixes.registerMix(mix, 0 /*output desc*/) != NO_ERROR) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003440 ALOGE("Error registering mix %zu for address %s", i, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003441 res = INVALID_OPERATION;
3442 break;
3443 }
Eric Laurent97ac8712018-07-27 18:59:02 -07003444 audio_config_t outputConfig = mix.mFormat;
3445 audio_config_t inputConfig = mix.mFormat;
Eric Laurentc529cf62020-04-17 18:19:10 -07003446 // NOTE: audio flinger mixer does not support mono output: configure remote submix HAL
3447 // in stereo and let audio flinger do the channel conversion if needed.
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003448 outputConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
3449 inputConfig.channel_mask = AUDIO_CHANNEL_IN_STEREO;
jiabin5740f082019-08-19 15:08:30 -07003450 rSubmixModule->addOutputProfile(address.c_str(), &outputConfig,
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003451 AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address);
jiabin5740f082019-08-19 15:08:30 -07003452 rSubmixModule->addInputProfile(address.c_str(), &inputConfig,
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003453 AUDIO_DEVICE_IN_REMOTE_SUBMIX, address);
François Gaffie036e1e92015-03-19 10:16:24 +01003454
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003455 if ((res = setDeviceConnectionStateInt(deviceTypeToMakeAvailable,
jiabinc1de2df2019-05-07 14:26:40 -07003456 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
3457 address.string(), "remote-submix", AUDIO_FORMAT_DEFAULT)) != NO_ERROR) {
3458 ALOGE("Failed to set remote submix device available, type %u, address %s",
3459 mix.mDeviceType, address.string());
3460 break;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003461 }
Eric Laurent97ac8712018-07-27 18:59:02 -07003462 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
3463 String8 address = mix.mDeviceAddress;
Eric Laurent2c80be02019-01-23 18:06:37 -08003464 audio_devices_t type = mix.mDeviceType;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003465 ALOGV(" registerPolicyMixes() mix %zu of %zu is RENDER, dev=0x%X addr=%s",
Eric Laurent2c80be02019-01-23 18:06:37 -08003466 i, mixes.size(), type, address.string());
3467
3468 sp<DeviceDescriptor> device = mHwModules.getDeviceDescriptor(
3469 mix.mDeviceType, mix.mDeviceAddress,
3470 String8(), AUDIO_FORMAT_DEFAULT);
3471 if (device == nullptr) {
3472 res = INVALID_OPERATION;
3473 break;
3474 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003475
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003476 bool foundOutput = false;
Eric Laurentc529cf62020-04-17 18:19:10 -07003477 // First try to find an already opened output supporting the device
3478 for (size_t j = 0 ; j < mOutputs.size() && !foundOutput && res == NO_ERROR; j++) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003479 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurent2c80be02019-01-23 18:06:37 -08003480
Eric Laurentc529cf62020-04-17 18:19:10 -07003481 if (!desc->isDuplicated() && desc->supportedDevices().contains(device)) {
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003482 if (mPolicyMixes.registerMix(mix, desc) != NO_ERROR) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003483 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
3484 address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003485 res = INVALID_OPERATION;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003486 } else {
3487 foundOutput = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003488 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003489 }
3490 }
Eric Laurentc529cf62020-04-17 18:19:10 -07003491 // If no output found, try to find a direct output profile supporting the device
3492 for (size_t i = 0; i < mHwModules.size() && !foundOutput && res == NO_ERROR; i++) {
3493 sp<HwModule> module = mHwModules[i];
3494 for (size_t j = 0;
3495 j < module->getOutputProfiles().size() && !foundOutput && res == NO_ERROR;
3496 j++) {
3497 sp<IOProfile> profile = module->getOutputProfiles()[j];
3498 if (profile->isDirectOutput() && profile->supportsDevice(device)) {
3499 if (mPolicyMixes.registerMix(mix, nullptr) != NO_ERROR) {
3500 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
3501 address.string());
3502 res = INVALID_OPERATION;
3503 } else {
3504 foundOutput = true;
3505 }
3506 }
3507 }
3508 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003509 if (res != NO_ERROR) {
3510 ALOGE(" Error registering mix %zu for device 0x%X addr %s",
Eric Laurent2c80be02019-01-23 18:06:37 -08003511 i, type, address.string());
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003512 res = INVALID_OPERATION;
3513 break;
3514 } else if (!foundOutput) {
3515 ALOGE(" Output not found for mix %zu for device 0x%X addr %s",
Eric Laurent2c80be02019-01-23 18:06:37 -08003516 i, type, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003517 res = INVALID_OPERATION;
3518 break;
Eric Laurentc209fe42020-06-05 18:11:23 -07003519 } else {
3520 checkOutputs = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003521 }
Eric Laurentc722f302014-12-10 11:21:49 -08003522 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003523 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003524 if (res != NO_ERROR) {
3525 unregisterPolicyMixes(mixes);
Eric Laurentc209fe42020-06-05 18:11:23 -07003526 } else if (checkOutputs) {
3527 checkForDeviceAndOutputChanges();
3528 updateCallAndOutputRouting();
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003529 }
3530 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08003531}
3532
3533status_t AudioPolicyManager::unregisterPolicyMixes(Vector<AudioMix> mixes)
3534{
Eric Laurent7b279bb2015-12-14 10:18:23 -08003535 ALOGV("unregisterPolicyMixes() num mixes %zu", mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003536 status_t res = NO_ERROR;
Eric Laurentc209fe42020-06-05 18:11:23 -07003537 bool checkOutputs = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003538 sp<HwModule> rSubmixModule;
3539 // examine each mix's route type
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003540 for (const auto& mix : mixes) {
3541 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie036e1e92015-03-19 10:16:24 +01003542
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003543 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003544 rSubmixModule = mHwModules.getModuleFromName(
3545 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
3546 if (rSubmixModule == 0) {
3547 res = INVALID_OPERATION;
3548 continue;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003549 }
3550 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003551
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003552 String8 address = mix.mDeviceAddress;
Eric Laurent275e8e92014-11-30 15:14:47 -08003553
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003554 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003555 res = INVALID_OPERATION;
3556 continue;
3557 }
3558
Kevin Rocard04ed0462019-05-02 17:53:24 -07003559 for (auto device : {AUDIO_DEVICE_IN_REMOTE_SUBMIX, AUDIO_DEVICE_OUT_REMOTE_SUBMIX}) {
3560 if (getDeviceConnectionState(device, address.string()) ==
3561 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
3562 res = setDeviceConnectionStateInt(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
3563 address.string(), "remote-submix",
3564 AUDIO_FORMAT_DEFAULT);
3565 if (res != OK) {
3566 ALOGE("Error making RemoteSubmix device unavailable for mix "
3567 "with type %d, address %s", device, address.string());
3568 }
3569 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003570 }
jiabin5740f082019-08-19 15:08:30 -07003571 rSubmixModule->removeOutputProfile(address.c_str());
3572 rSubmixModule->removeInputProfile(address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003573
Kevin Rocard153f92d2018-12-18 18:33:28 -08003574 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003575 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003576 res = INVALID_OPERATION;
3577 continue;
Eric Laurentc209fe42020-06-05 18:11:23 -07003578 } else {
3579 checkOutputs = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003580 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003581 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003582 }
Eric Laurentc209fe42020-06-05 18:11:23 -07003583 if (res == NO_ERROR && checkOutputs) {
3584 checkForDeviceAndOutputChanges();
3585 updateCallAndOutputRouting();
3586 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003587 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08003588}
3589
Mikhail Naganov100f0122018-11-29 11:22:16 -08003590void AudioPolicyManager::dumpManualSurroundFormats(String8 *dst) const
3591{
3592 size_t i = 0;
3593 constexpr size_t audioFormatPrefixLen = sizeof("AUDIO_FORMAT_");
3594 for (const auto& fmt : mManualSurroundFormats) {
3595 if (i++ != 0) dst->append(", ");
3596 std::string sfmt;
3597 FormatConverter::toString(fmt, sfmt);
3598 dst->append(sfmt.size() >= audioFormatPrefixLen ?
3599 sfmt.c_str() + audioFormatPrefixLen - 1 : sfmt.c_str());
3600 }
3601}
3602
Eric Laurentc529cf62020-04-17 18:19:10 -07003603// Returns true if all devices types match the predicate and are supported by one HW module
3604bool AudioPolicyManager::areAllDevicesSupported(
jiabin6a02d532020-08-07 11:56:38 -07003605 const AudioDeviceTypeAddrVector& devices,
Eric Laurentc529cf62020-04-17 18:19:10 -07003606 std::function<bool(audio_devices_t)> predicate,
3607 const char *context) {
3608 for (size_t i = 0; i < devices.size(); i++) {
3609 sp<DeviceDescriptor> devDesc = mHwModules.getDeviceDescriptor(
jiabin0a488932020-08-07 17:32:40 -07003610 devices[i].mType, devices[i].getAddress(), String8(),
Eric Laurent0e26e3f2020-04-29 14:24:16 -07003611 AUDIO_FORMAT_DEFAULT, false /*allowToCreate*/, true /*matchAddress*/);
Eric Laurentc529cf62020-04-17 18:19:10 -07003612 if (devDesc == nullptr || (predicate != nullptr && !predicate(devices[i].mType))) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003613 ALOGE("%s: device type %#x address %s not supported or not match predicate",
jiabin0a488932020-08-07 17:32:40 -07003614 context, devices[i].mType, devices[i].getAddress());
Eric Laurentc529cf62020-04-17 18:19:10 -07003615 return false;
3616 }
3617 }
3618 return true;
3619}
3620
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003621status_t AudioPolicyManager::setUidDeviceAffinities(uid_t uid,
jiabin6a02d532020-08-07 11:56:38 -07003622 const AudioDeviceTypeAddrVector& devices) {
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003623 ALOGV("%s() uid=%d num devices %zu", __FUNCTION__, uid, devices.size());
Eric Laurentc529cf62020-04-17 18:19:10 -07003624 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
3625 return BAD_VALUE;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003626 }
3627 status_t res = mPolicyMixes.setUidDeviceAffinities(uid, devices);
Eric Laurentc529cf62020-04-17 18:19:10 -07003628 if (res != NO_ERROR) {
3629 ALOGE("%s() Could not set all device affinities for uid = %d", __FUNCTION__, uid);
3630 return res;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003631 }
Eric Laurentc529cf62020-04-17 18:19:10 -07003632
3633 checkForDeviceAndOutputChanges();
3634 updateCallAndOutputRouting();
3635
3636 return NO_ERROR;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003637}
3638
3639status_t AudioPolicyManager::removeUidDeviceAffinities(uid_t uid) {
3640 ALOGV("%s() uid=%d", __FUNCTION__, uid);
Oscar Azucena4b2a8212019-04-26 23:48:59 -07003641 status_t res = mPolicyMixes.removeUidDeviceAffinities(uid);
3642 if (res != NO_ERROR) {
Eric Laurentc529cf62020-04-17 18:19:10 -07003643 ALOGE("%s() Could not remove all device affinities for uid = %d",
Oscar Azucena4b2a8212019-04-26 23:48:59 -07003644 __FUNCTION__, uid);
3645 return INVALID_OPERATION;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003646 }
3647
Eric Laurentc529cf62020-04-17 18:19:10 -07003648 checkForDeviceAndOutputChanges();
3649 updateCallAndOutputRouting();
3650
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003651 return res;
3652}
3653
Eric Laurent2517af32020-11-25 15:31:27 +01003654
jiabin0a488932020-08-07 17:32:40 -07003655status_t AudioPolicyManager::setDevicesRoleForStrategy(product_strategy_t strategy,
3656 device_role_t role,
3657 const AudioDeviceTypeAddrVector &devices) {
3658 ALOGV("%s() strategy=%d role=%d %s", __func__, strategy, role,
3659 dumpAudioDeviceTypeAddrVector(devices).c_str());
Eric Laurentc529cf62020-04-17 18:19:10 -07003660
Eric Laurentc529cf62020-04-17 18:19:10 -07003661 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003662 return BAD_VALUE;
3663 }
jiabin0a488932020-08-07 17:32:40 -07003664 status_t status = mEngine->setDevicesRoleForStrategy(strategy, role, devices);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003665 if (status != NO_ERROR) {
jiabin0a488932020-08-07 17:32:40 -07003666 ALOGW("Engine could not set preferred devices %s for strategy %d role %d",
3667 dumpAudioDeviceTypeAddrVector(devices).c_str(), strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003668 return status;
3669 }
3670
3671 checkForDeviceAndOutputChanges();
Eric Laurent2517af32020-11-25 15:31:27 +01003672
3673 bool forceVolumeReeval = false;
3674 // FIXME: workaround for truncated touch sounds
3675 // to be removed when the problem is handled by system UI
3676 uint32_t delayMs = 0;
3677 if (strategy == mCommunnicationStrategy) {
3678 forceVolumeReeval = true;
3679 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
3680 updateInputRouting();
3681 }
3682 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003683
3684 return NO_ERROR;
3685}
3686
3687void AudioPolicyManager::updateCallAndOutputRouting(bool forceVolumeReeval, uint32_t delayMs)
3688{
3689 uint32_t waitMs = 0;
Eric Laurent96d1dda2022-03-14 17:14:19 +01003690 bool wasLeUnicastActive = isLeUnicastActive();
Francois Gaffie19fd6c52021-02-04 17:02:59 +01003691 if (updateCallRouting(true /*fromCache*/, delayMs, &waitMs) == NO_ERROR) {
Eric Laurentb36b4ac2020-08-21 12:50:41 -07003692 // Only apply special touch sound delay once
3693 delayMs = 0;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003694 }
3695 for (size_t i = 0; i < mOutputs.size(); i++) {
3696 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
3697 DeviceVector newDevices = getNewOutputDevices(outputDesc, true /*fromCache*/);
Francois Gaffie601801d2021-06-22 13:27:39 +02003698 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) ||
3699 (outputDesc != mPrimaryOutput && !isTelephonyRxOrTx(outputDesc))) {
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003700 // As done in setDeviceConnectionState, we could also fix default device issue by
3701 // preventing the force re-routing in case of default dev that distinguishes on address.
3702 // Let's give back to engine full device choice decision however.
Francois Gaffie601801d2021-06-22 13:27:39 +02003703 bool forceRouting = !newDevices.isEmpty();
3704 waitMs = setOutputDevices(outputDesc, newDevices, forceRouting, delayMs, nullptr,
3705 true /*requiresMuteCheck*/,
3706 !forceRouting /*requiresVolumeCheck*/);
Eric Laurentb36b4ac2020-08-21 12:50:41 -07003707 // Only apply special touch sound delay once
3708 delayMs = 0;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003709 }
3710 if (forceVolumeReeval && !newDevices.isEmpty()) {
3711 applyStreamVolumes(outputDesc, newDevices.types(), waitMs, true);
3712 }
3713 }
Eric Laurent96d1dda2022-03-14 17:14:19 +01003714 checkLeBroadcastRoutes(wasLeUnicastActive, nullptr, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003715}
3716
Eric Laurent2517af32020-11-25 15:31:27 +01003717void AudioPolicyManager::updateInputRouting() {
3718 for (const auto& activeDesc : mInputs.getActiveInputs()) {
Jaideep Sharma408349a2020-11-27 14:47:17 +05303719 // Skip for hotword recording as the input device switch
3720 // is handled within sound trigger HAL
3721 if (activeDesc->isSoundTrigger() && activeDesc->source() == AUDIO_SOURCE_HOTWORD) {
3722 continue;
3723 }
Eric Laurent2517af32020-11-25 15:31:27 +01003724 auto newDevice = getNewInputDevice(activeDesc);
3725 // Force new input selection if the new device can not be reached via current input
3726 if (activeDesc->mProfile->getSupportedDevices().contains(newDevice)) {
3727 setInputDevice(activeDesc->mIoHandle, newDevice);
3728 } else {
3729 closeInput(activeDesc->mIoHandle);
3730 }
3731 }
3732}
3733
jiabin0a488932020-08-07 17:32:40 -07003734status_t AudioPolicyManager::removeDevicesRoleForStrategy(product_strategy_t strategy,
3735 device_role_t role)
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003736{
Eric Laurentfecbceb2021-02-09 14:46:43 +01003737 ALOGV("%s() strategy=%d role=%d", __func__, strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003738
jiabin0a488932020-08-07 17:32:40 -07003739 status_t status = mEngine->removeDevicesRoleForStrategy(strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003740 if (status != NO_ERROR) {
Eric Laurent2517af32020-11-25 15:31:27 +01003741 ALOGV("Engine could not remove preferred device for strategy %d status %d",
3742 strategy, status);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003743 return status;
3744 }
3745
3746 checkForDeviceAndOutputChanges();
Eric Laurent2517af32020-11-25 15:31:27 +01003747
3748 bool forceVolumeReeval = false;
3749 // FIXME: workaround for truncated touch sounds
3750 // to be removed when the problem is handled by system UI
3751 uint32_t delayMs = 0;
3752 if (strategy == mCommunnicationStrategy) {
3753 forceVolumeReeval = true;
3754 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
3755 updateInputRouting();
3756 }
3757 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003758
3759 return NO_ERROR;
3760}
3761
jiabin0a488932020-08-07 17:32:40 -07003762status_t AudioPolicyManager::getDevicesForRoleAndStrategy(product_strategy_t strategy,
3763 device_role_t role,
3764 AudioDeviceTypeAddrVector &devices) {
3765 return mEngine->getDevicesForRoleAndStrategy(strategy, role, devices);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003766}
3767
Jiabin Huang3b98d322020-09-03 17:54:16 +00003768status_t AudioPolicyManager::setDevicesRoleForCapturePreset(
3769 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices) {
3770 ALOGV("%s() audioSource=%d role=%d %s", __func__, audioSource, role,
3771 dumpAudioDeviceTypeAddrVector(devices).c_str());
3772
Mikhail Naganov55773032020-10-01 15:08:13 -07003773 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003774 return BAD_VALUE;
3775 }
3776 status_t status = mEngine->setDevicesRoleForCapturePreset(audioSource, role, devices);
3777 ALOGW_IF(status != NO_ERROR,
3778 "Engine could not set preferred devices %s for audio source %d role %d",
3779 dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
3780
3781 return status;
3782}
3783
3784status_t AudioPolicyManager::addDevicesRoleForCapturePreset(
3785 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices) {
3786 ALOGV("%s() audioSource=%d role=%d %s", __func__, audioSource, role,
3787 dumpAudioDeviceTypeAddrVector(devices).c_str());
3788
Mikhail Naganov55773032020-10-01 15:08:13 -07003789 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003790 return BAD_VALUE;
3791 }
3792 status_t status = mEngine->addDevicesRoleForCapturePreset(audioSource, role, devices);
3793 ALOGW_IF(status != NO_ERROR,
3794 "Engine could not add preferred devices %s for audio source %d role %d",
3795 dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
3796
Eric Laurent2517af32020-11-25 15:31:27 +01003797 updateInputRouting();
Jiabin Huang3b98d322020-09-03 17:54:16 +00003798 return status;
3799}
3800
3801status_t AudioPolicyManager::removeDevicesRoleForCapturePreset(
3802 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector& devices)
3803{
3804 ALOGV("%s() audioSource=%d role=%d devices=%s", __func__, audioSource, role,
3805 dumpAudioDeviceTypeAddrVector(devices).c_str());
3806
Mikhail Naganov55773032020-10-01 15:08:13 -07003807 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003808 return BAD_VALUE;
3809 }
3810
3811 status_t status = mEngine->removeDevicesRoleForCapturePreset(
3812 audioSource, role, devices);
3813 ALOGW_IF(status != NO_ERROR,
3814 "Engine could not remove devices role (%d) for capture preset %d", role, audioSource);
3815
Eric Laurent2517af32020-11-25 15:31:27 +01003816 updateInputRouting();
Jiabin Huang3b98d322020-09-03 17:54:16 +00003817 return status;
3818}
3819
3820status_t AudioPolicyManager::clearDevicesRoleForCapturePreset(audio_source_t audioSource,
3821 device_role_t role) {
3822 ALOGV("%s() audioSource=%d role=%d", __func__, audioSource, role);
3823
3824 status_t status = mEngine->clearDevicesRoleForCapturePreset(audioSource, role);
3825 ALOGW_IF(status != NO_ERROR,
3826 "Engine could not clear devices role (%d) for capture preset %d", role, audioSource);
3827
Eric Laurent2517af32020-11-25 15:31:27 +01003828 updateInputRouting();
Jiabin Huang3b98d322020-09-03 17:54:16 +00003829 return status;
3830}
3831
3832status_t AudioPolicyManager::getDevicesForRoleAndCapturePreset(
3833 audio_source_t audioSource, device_role_t role, AudioDeviceTypeAddrVector &devices) {
3834 return mEngine->getDevicesForRoleAndCapturePreset(audioSource, role, devices);
3835}
3836
Oscar Azucena90e77632019-11-27 17:12:28 -08003837status_t AudioPolicyManager::setUserIdDeviceAffinities(int userId,
jiabin6a02d532020-08-07 11:56:38 -07003838 const AudioDeviceTypeAddrVector& devices) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01003839 ALOGV("%s() userId=%d num devices %zu", __func__, userId, devices.size());
Eric Laurentc529cf62020-04-17 18:19:10 -07003840 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
3841 return BAD_VALUE;
Oscar Azucena90e77632019-11-27 17:12:28 -08003842 }
Oscar Azucena90e77632019-11-27 17:12:28 -08003843 status_t status = mPolicyMixes.setUserIdDeviceAffinities(userId, devices);
3844 if (status != NO_ERROR) {
3845 ALOGE("%s() could not set device affinity for userId %d",
3846 __FUNCTION__, userId);
3847 return status;
3848 }
3849
3850 // reevaluate outputs for all devices
3851 checkForDeviceAndOutputChanges();
3852 updateCallAndOutputRouting();
3853
3854 return NO_ERROR;
3855}
3856
3857status_t AudioPolicyManager::removeUserIdDeviceAffinities(int userId) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01003858 ALOGV("%s() userId=%d", __FUNCTION__, userId);
Oscar Azucena90e77632019-11-27 17:12:28 -08003859 status_t status = mPolicyMixes.removeUserIdDeviceAffinities(userId);
3860 if (status != NO_ERROR) {
3861 ALOGE("%s() Could not remove all device affinities fo userId = %d",
3862 __FUNCTION__, userId);
3863 return status;
3864 }
3865
3866 // reevaluate outputs for all devices
3867 checkForDeviceAndOutputChanges();
3868 updateCallAndOutputRouting();
3869
3870 return NO_ERROR;
3871}
3872
Andy Hungc29d82b2018-10-05 12:23:17 -07003873void AudioPolicyManager::dump(String8 *dst) const
Eric Laurente552edb2014-03-10 17:42:56 -07003874{
Andy Hungc29d82b2018-10-05 12:23:17 -07003875 dst->appendFormat("\nAudioPolicyManager Dump: %p\n", this);
Mikhail Naganov0dbe87b2021-12-01 02:03:31 +00003876 dst->appendFormat(" Primary Output I/O handle: %d\n",
Eric Laurent87ffa392015-05-22 10:32:38 -07003877 hasPrimaryOutput() ? mPrimaryOutput->mIoHandle : AUDIO_IO_HANDLE_NONE);
Mikhail Naganov0d6a0332016-04-19 17:12:38 -07003878 std::string stateLiteral;
3879 AudioModeConverter::toString(mEngine->getPhoneState(), stateLiteral);
Andy Hungc29d82b2018-10-05 12:23:17 -07003880 dst->appendFormat(" Phone state: %s\n", stateLiteral.c_str());
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07003881 const char* forceUses[AUDIO_POLICY_FORCE_USE_CNT] = {
3882 "communications", "media", "record", "dock", "system",
3883 "HDMI system audio", "encoded surround output", "vibrate ringing" };
3884 for (audio_policy_force_use_t i = AUDIO_POLICY_FORCE_FOR_COMMUNICATION;
3885 i < AUDIO_POLICY_FORCE_USE_CNT; i = (audio_policy_force_use_t)((int)i + 1)) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08003886 audio_policy_forced_cfg_t forceUseValue = mEngine->getForceUse(i);
3887 dst->appendFormat(" Force use for %s: %d", forceUses[i], forceUseValue);
3888 if (i == AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND &&
3889 forceUseValue == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
3890 dst->append(" (MANUAL: ");
3891 dumpManualSurroundFormats(dst);
3892 dst->append(")");
3893 }
3894 dst->append("\n");
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07003895 }
Andy Hungc29d82b2018-10-05 12:23:17 -07003896 dst->appendFormat(" TTS output %savailable\n", mTtsOutputAvailable ? "" : "not ");
3897 dst->appendFormat(" Master mono: %s\n", mMasterMono ? "on" : "off");
Mikhail Naganovb3bcb4f2022-02-23 23:46:56 +00003898 dst->appendFormat(" Communication Strategy id: %d\n", mCommunnicationStrategy);
Mikhail Naganovb0fbc1b2023-04-28 13:06:32 -07003899 dst->appendFormat(" Config source: %s\n", mConfig->getSource().c_str());
Eric Laurent2517af32020-11-25 15:31:27 +01003900
Mikhail Naganov0f413b22021-12-02 05:29:27 +00003901 dst->append("\n");
3902 mAvailableOutputDevices.dump(dst, String8("Available output"), 1);
3903 dst->append("\n");
3904 mAvailableInputDevices.dump(dst, String8("Available input"), 1);
Mikhail Naganovb0fbc1b2023-04-28 13:06:32 -07003905 mHwModules.dump(dst);
Andy Hungc29d82b2018-10-05 12:23:17 -07003906 mOutputs.dump(dst);
3907 mInputs.dump(dst);
Mikhail Naganov0f413b22021-12-02 05:29:27 +00003908 mEffects.dump(dst, 1);
Andy Hungc29d82b2018-10-05 12:23:17 -07003909 mAudioPatches.dump(dst);
3910 mPolicyMixes.dump(dst);
3911 mAudioSources.dump(dst);
François Gaffiec005e562018-11-06 15:04:49 +01003912
Kevin Rocardb99cc752019-03-21 20:52:24 -07003913 dst->appendFormat(" AllowedCapturePolicies:\n");
3914 for (auto& policy : mAllowedCapturePolicies) {
3915 dst->appendFormat(" - uid=%d flag_mask=%#x\n", policy.first, policy.second);
3916 }
3917
François Gaffiec005e562018-11-06 15:04:49 +01003918 dst->appendFormat("\nPolicy Engine dump:\n");
3919 mEngine->dump(dst);
Andy Hungc29d82b2018-10-05 12:23:17 -07003920}
3921
3922status_t AudioPolicyManager::dump(int fd)
3923{
3924 String8 result;
3925 dump(&result);
Andy Hungbb54e202018-10-05 11:42:02 -07003926 write(fd, result.string(), result.size());
Eric Laurente552edb2014-03-10 17:42:56 -07003927 return NO_ERROR;
3928}
3929
Kevin Rocardb99cc752019-03-21 20:52:24 -07003930status_t AudioPolicyManager::setAllowedCapturePolicy(uid_t uid, audio_flags_mask_t capturePolicy)
3931{
3932 mAllowedCapturePolicies[uid] = capturePolicy;
3933 return NO_ERROR;
3934}
3935
Eric Laurente552edb2014-03-10 17:42:56 -07003936// This function checks for the parameters which can be offloaded.
3937// This can be enhanced depending on the capability of the DSP and policy
3938// of the system.
Eric Laurent90fe31c2020-11-26 20:06:35 +01003939audio_offload_mode_t AudioPolicyManager::getOffloadSupport(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07003940{
Eric Laurent90fe31c2020-11-26 20:06:35 +01003941 ALOGV("%s: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07003942 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurent90fe31c2020-11-26 20:06:35 +01003943 __func__, offloadInfo.sample_rate, offloadInfo.channel_mask,
Eric Laurente552edb2014-03-10 17:42:56 -07003944 offloadInfo.format,
3945 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
3946 offloadInfo.has_video);
3947
jiabin2b9d5a12021-12-10 01:06:29 +00003948 if (!isOffloadPossible(offloadInfo)) {
Eric Laurent90fe31c2020-11-26 20:06:35 +01003949 return AUDIO_OFFLOAD_NOT_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07003950 }
3951
3952 // See if there is a profile to support this.
3953 // AUDIO_DEVICE_NONE
François Gaffie11d30102018-11-02 16:09:09 +01003954 sp<IOProfile> profile = getProfileForOutput(DeviceVector() /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07003955 offloadInfo.sample_rate,
3956 offloadInfo.format,
3957 offloadInfo.channel_mask,
Michael Chana94fbb22018-04-24 14:31:19 +10003958 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD,
3959 true /* directOnly */);
Eric Laurent94365442021-01-08 18:36:05 +01003960 ALOGV("%s: profile %sfound%s", __func__, profile != nullptr ? "" : "NOT ",
3961 (profile != nullptr && (profile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD) != 0)
3962 ? ", supports gapless" : "");
Eric Laurent90fe31c2020-11-26 20:06:35 +01003963 if (profile == nullptr) {
3964 return AUDIO_OFFLOAD_NOT_SUPPORTED;
3965 }
3966 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD) != 0) {
3967 return AUDIO_OFFLOAD_GAPLESS_SUPPORTED;
3968 }
3969 return AUDIO_OFFLOAD_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07003970}
3971
Michael Chana94fbb22018-04-24 14:31:19 +10003972bool AudioPolicyManager::isDirectOutputSupported(const audio_config_base_t& config,
3973 const audio_attributes_t& attributes) {
3974 audio_output_flags_t output_flags = AUDIO_OUTPUT_FLAG_NONE;
François Gaffie58d4be52018-11-06 15:30:12 +01003975 audio_flags_to_audio_output_flags(attributes.flags, &output_flags);
Dorin Drimus9901eb02022-01-14 11:36:51 +00003976 DeviceVector outputDevices = mEngine->getOutputDevicesForAttributes(attributes);
3977 sp<IOProfile> profile = getProfileForOutput(outputDevices,
Michael Chana94fbb22018-04-24 14:31:19 +10003978 config.sample_rate,
3979 config.format,
3980 config.channel_mask,
3981 output_flags,
3982 true /* directOnly */);
3983 ALOGV("%s() profile %sfound with name: %s, "
3984 "sample rate: %u, format: 0x%x, channel_mask: 0x%x, output flags: 0x%x",
3985 __FUNCTION__, profile != 0 ? "" : "NOT ",
jiabin5740f082019-08-19 15:08:30 -07003986 (profile != 0 ? profile->getTagName().c_str() : "null"),
Michael Chana94fbb22018-04-24 14:31:19 +10003987 config.sample_rate, config.format, config.channel_mask, output_flags);
Dorin Drimusecc9f422022-03-09 17:57:40 +01003988
3989 // also try the MSD module if compatible profile not found
3990 if (profile == nullptr) {
3991 profile = getMsdProfileForOutput(outputDevices,
3992 config.sample_rate,
3993 config.format,
3994 config.channel_mask,
3995 output_flags,
3996 true /* directOnly */);
3997 ALOGV("%s() MSD 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 ",
4000 (profile != 0 ? profile->getTagName().c_str() : "null"),
4001 config.sample_rate, config.format, config.channel_mask, output_flags);
4002 }
4003 return (profile != nullptr);
Michael Chana94fbb22018-04-24 14:31:19 +10004004}
4005
jiabin2b9d5a12021-12-10 01:06:29 +00004006bool AudioPolicyManager::isOffloadPossible(const audio_offload_info_t &offloadInfo,
4007 bool durationIgnored) {
4008 if (mMasterMono) {
4009 return false; // no offloading if mono is set.
4010 }
4011
4012 // Check if offload has been disabled
4013 if (property_get_bool("audio.offload.disable", false /* default_value */)) {
4014 ALOGV("%s: offload disabled by audio.offload.disable", __func__);
4015 return false;
4016 }
4017
4018 // Check if stream type is music, then only allow offload as of now.
4019 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
4020 {
4021 ALOGV("%s: stream_type != MUSIC, returning false", __func__);
4022 return false;
4023 }
4024
4025 //TODO: enable audio offloading with video when ready
4026 const bool allowOffloadWithVideo =
4027 property_get_bool("audio.offload.video", false /* default_value */);
4028 if (offloadInfo.has_video && !allowOffloadWithVideo) {
4029 ALOGV("%s: has_video == true, returning false", __func__);
4030 return false;
4031 }
4032
4033 //If duration is less than minimum value defined in property, return false
4034 const int min_duration_secs = property_get_int32(
4035 "audio.offload.min.duration.secs", -1 /* default_value */);
4036 if (!durationIgnored) {
4037 if (min_duration_secs >= 0) {
4038 if (offloadInfo.duration_us < min_duration_secs * 1000000LL) {
4039 ALOGV("%s: Offload denied by duration < audio.offload.min.duration.secs(=%d)",
4040 __func__, min_duration_secs);
4041 return false;
4042 }
4043 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
4044 ALOGV("%s: Offload denied by duration < default min(=%u)",
4045 __func__, OFFLOAD_DEFAULT_MIN_DURATION_SECS);
4046 return false;
4047 }
4048 }
4049
4050 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
4051 // creating an offloaded track and tearing it down immediately after start when audioflinger
4052 // detects there is an active non offloadable effect.
4053 // FIXME: We should check the audio session here but we do not have it in this context.
4054 // This may prevent offloading in rare situations where effects are left active by apps
4055 // in the background.
4056 if (mEffects.isNonOffloadableEffectEnabled()) {
4057 return false;
4058 }
4059
4060 return true;
4061}
4062
4063audio_direct_mode_t AudioPolicyManager::getDirectPlaybackSupport(const audio_attributes_t *attr,
4064 const audio_config_t *config) {
4065 audio_offload_info_t offloadInfo = AUDIO_INFO_INITIALIZER;
4066 offloadInfo.format = config->format;
4067 offloadInfo.sample_rate = config->sample_rate;
4068 offloadInfo.channel_mask = config->channel_mask;
4069 offloadInfo.stream_type = mEngine->getStreamTypeForAttributes(*attr);
4070 offloadInfo.has_video = false;
4071 offloadInfo.is_streaming = false;
4072 const bool offloadPossible = isOffloadPossible(offloadInfo, true /*durationIgnored*/);
4073
4074 audio_direct_mode_t directMode = AUDIO_DIRECT_NOT_SUPPORTED;
4075 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
4076 audio_flags_to_audio_output_flags(attr->flags, &flags);
4077 // only retain flags that will drive compressed offload or passthrough
4078 uint32_t relevantFlags = AUDIO_OUTPUT_FLAG_HW_AV_SYNC;
4079 if (offloadPossible) {
4080 relevantFlags |= AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD;
4081 }
4082 flags = (audio_output_flags_t)((flags & relevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
4083
Dorin Drimusfae3c642022-03-17 18:36:30 +01004084 DeviceVector engineOutputDevices = mEngine->getOutputDevicesForAttributes(*attr);
jiabin2b9d5a12021-12-10 01:06:29 +00004085 for (const auto& hwModule : mHwModules) {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004086 DeviceVector outputDevices = engineOutputDevices;
4087 // the MSD module checks for different conditions and output devices
4088 if (strcmp(hwModule->getName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0) {
4089 if (!msdHasPatchesToAllDevices(engineOutputDevices.toTypeAddrVector())) {
4090 continue;
4091 }
4092 outputDevices = getMsdAudioOutDevices();
4093 }
jiabin2b9d5a12021-12-10 01:06:29 +00004094 for (const auto& curProfile : hwModule->getOutputProfiles()) {
jiabinc8f7dfc2022-01-06 18:42:08 +00004095 if (!curProfile->isCompatibleProfile(outputDevices,
jiabin2b9d5a12021-12-10 01:06:29 +00004096 config->sample_rate, nullptr /*updatedSamplingRate*/,
4097 config->format, nullptr /*updatedFormat*/,
4098 config->channel_mask, nullptr /*updatedChannelMask*/,
4099 flags)) {
4100 continue;
4101 }
4102 // reject profiles not corresponding to a device currently available
4103 if (!mAvailableOutputDevices.containsAtLeastOne(curProfile->getSupportedDevices())) {
4104 continue;
4105 }
4106 if ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)
4107 != AUDIO_OUTPUT_FLAG_NONE) {
jiabinc6132d62022-01-01 07:36:31 +00004108 if ((directMode & AUDIO_DIRECT_OFFLOAD_GAPLESS_SUPPORTED)
jiabin2b9d5a12021-12-10 01:06:29 +00004109 != AUDIO_DIRECT_NOT_SUPPORTED) {
4110 // Already reports offload gapless supported. No need to report offload support.
4111 continue;
4112 }
4113 if ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD)
4114 != AUDIO_OUTPUT_FLAG_NONE) {
4115 // If offload gapless is reported, no need to report offload support.
4116 directMode = (audio_direct_mode_t) ((directMode &
4117 ~AUDIO_DIRECT_OFFLOAD_SUPPORTED) |
4118 AUDIO_DIRECT_OFFLOAD_GAPLESS_SUPPORTED);
4119 } else {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004120 directMode = (audio_direct_mode_t)(directMode | AUDIO_DIRECT_OFFLOAD_SUPPORTED);
jiabin2b9d5a12021-12-10 01:06:29 +00004121 }
4122 } else {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004123 directMode = (audio_direct_mode_t) (directMode | AUDIO_DIRECT_BITSTREAM_SUPPORTED);
jiabin2b9d5a12021-12-10 01:06:29 +00004124 }
4125 }
4126 }
4127 return directMode;
4128}
4129
Dorin Drimusf2196d82022-01-03 12:11:18 +01004130status_t AudioPolicyManager::getDirectProfilesForAttributes(const audio_attributes_t* attr,
4131 AudioProfileVector& audioProfilesVector) {
Dorin Drimus76e69572022-09-23 15:28:51 +00004132 if (mEffects.isNonOffloadableEffectEnabled()) {
4133 return OK;
4134 }
Dorin Drimusf2196d82022-01-03 12:11:18 +01004135 AudioDeviceTypeAddrVector devices;
Andy Hung6d23c0f2022-02-16 09:37:15 -08004136 status_t status = getDevicesForAttributes(*attr, &devices, false /* forVolume */);
Dorin Drimusf2196d82022-01-03 12:11:18 +01004137 if (status != OK) {
4138 return status;
4139 }
4140 ALOGV("%s: found %zu output devices for attributes.", __func__, devices.size());
4141 if (devices.empty()) {
4142 return OK; // no output devices for the attributes
4143 }
4144
4145 for (const auto& hwModule : mHwModules) {
Dorin Drimus94d94412022-02-02 09:05:02 +01004146 // the MSD module checks for different conditions
4147 if (strcmp(hwModule->getName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0) {
4148 continue;
4149 }
4150 for (const auto& outputProfile : hwModule->getOutputProfiles()) {
4151 if (!outputProfile->asAudioPort()->isDirectOutput()) {
Dorin Drimusf2196d82022-01-03 12:11:18 +01004152 continue;
4153 }
Dorin Drimus94d94412022-02-02 09:05:02 +01004154 // allow only profiles that support all the available and routed devices
4155 if (outputProfile->getSupportedDevices().getDevicesFromDeviceTypeAddrVec(devices).size()
Dorin Drimusf2196d82022-01-03 12:11:18 +01004156 != devices.size()) {
4157 continue;
4158 }
Dorin Drimus94d94412022-02-02 09:05:02 +01004159 audioProfilesVector.addAllValidProfiles(
4160 outputProfile->asAudioPort()->getAudioProfiles());
Dorin Drimusf2196d82022-01-03 12:11:18 +01004161 }
4162 }
Dorin Drimus94d94412022-02-02 09:05:02 +01004163
4164 // add the direct profiles from MSD if present and has audio patches to all the output(s)
4165 const auto& msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
4166 if (msdModule != nullptr) {
4167 if (msdHasPatchesToAllDevices(devices)) {
4168 ALOGV("%s: MSD audio patches set to all output devices.", __func__);
4169 for (const auto& outputProfile : msdModule->getOutputProfiles()) {
4170 if (!outputProfile->asAudioPort()->isDirectOutput()) {
4171 continue;
4172 }
4173 audioProfilesVector.addAllValidProfiles(
4174 outputProfile->asAudioPort()->getAudioProfiles());
4175 }
4176 } else {
4177 ALOGV("%s: MSD audio patches NOT set to all output devices.", __func__);
4178 }
4179 }
4180
Dorin Drimusf2196d82022-01-03 12:11:18 +01004181 return NO_ERROR;
4182}
4183
Eric Laurent6a94d692014-05-20 11:18:06 -07004184status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
4185 audio_port_type_t type,
4186 unsigned int *num_ports,
jiabin19cdba52020-11-24 11:28:58 -08004187 struct audio_port_v7 *ports,
Eric Laurent6a94d692014-05-20 11:18:06 -07004188 unsigned int *generation)
4189{
jiabin19cdba52020-11-24 11:28:58 -08004190 if (num_ports == nullptr || (*num_ports != 0 && ports == nullptr) ||
4191 generation == nullptr) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004192 return BAD_VALUE;
4193 }
4194 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
jiabin19cdba52020-11-24 11:28:58 -08004195 if (ports == nullptr) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004196 *num_ports = 0;
4197 }
4198
4199 size_t portsWritten = 0;
4200 size_t portsMax = *num_ports;
4201 *num_ports = 0;
4202 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07004203 // do not report devices with type AUDIO_DEVICE_IN_STUB or AUDIO_DEVICE_OUT_STUB
4204 // as they are used by stub HALs by convention
Eric Laurent6a94d692014-05-20 11:18:06 -07004205 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004206 for (const auto& dev : mAvailableOutputDevices) {
4207 if (dev->type() == AUDIO_DEVICE_OUT_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07004208 continue;
4209 }
4210 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004211 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07004212 }
4213 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07004214 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004215 }
4216 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004217 for (const auto& dev : mAvailableInputDevices) {
4218 if (dev->type() == AUDIO_DEVICE_IN_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07004219 continue;
4220 }
4221 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004222 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07004223 }
4224 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07004225 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004226 }
4227 }
4228 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
4229 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
4230 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
4231 mInputs[i]->toAudioPort(&ports[portsWritten++]);
4232 }
4233 *num_ports += mInputs.size();
4234 }
4235 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent84c70242014-06-23 08:46:27 -07004236 size_t numOutputs = 0;
4237 for (size_t i = 0; i < mOutputs.size(); i++) {
4238 if (!mOutputs[i]->isDuplicated()) {
4239 numOutputs++;
4240 if (portsWritten < portsMax) {
4241 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
4242 }
4243 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004244 }
Eric Laurent84c70242014-06-23 08:46:27 -07004245 *num_ports += numOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07004246 }
4247 }
4248 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07004249 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
Eric Laurent6a94d692014-05-20 11:18:06 -07004250 return NO_ERROR;
4251}
4252
Mikhail Naganov15f46712023-03-23 14:52:15 -07004253status_t AudioPolicyManager::listDeclaredDevicePorts(media::AudioPortRole role,
4254 std::vector<media::AudioPortFw>* _aidl_return) {
4255 auto pushPort = [&](const sp<DeviceDescriptor>& dev) -> status_t {
4256 audio_port_v7 port;
4257 dev->toAudioPort(&port);
4258 auto aidlPort = VALUE_OR_RETURN_STATUS(legacy2aidl_audio_port_v7_AudioPortFw(port));
4259 _aidl_return->push_back(std::move(aidlPort));
4260 return OK;
4261 };
4262
Mikhail Naganovb0fbc1b2023-04-28 13:06:32 -07004263 for (const auto& module : mHwModules) {
Mikhail Naganov15f46712023-03-23 14:52:15 -07004264 for (const auto& dev : module->getDeclaredDevices()) {
4265 if (role == media::AudioPortRole::NONE ||
4266 ((role == media::AudioPortRole::SOURCE)
4267 == audio_is_input_device(dev->type()))) {
4268 RETURN_STATUS_IF_ERROR(pushPort(dev));
4269 }
4270 }
4271 }
4272 return OK;
4273}
4274
jiabin19cdba52020-11-24 11:28:58 -08004275status_t AudioPolicyManager::getAudioPort(struct audio_port_v7 *port)
Eric Laurent6a94d692014-05-20 11:18:06 -07004276{
Eric Laurent99fcae42018-05-17 16:59:18 -07004277 if (port == nullptr || port->id == AUDIO_PORT_HANDLE_NONE) {
4278 return BAD_VALUE;
4279 }
4280 sp<DeviceDescriptor> dev = mAvailableOutputDevices.getDeviceFromId(port->id);
4281 if (dev != 0) {
4282 dev->toAudioPort(port);
4283 return NO_ERROR;
4284 }
4285 dev = mAvailableInputDevices.getDeviceFromId(port->id);
4286 if (dev != 0) {
4287 dev->toAudioPort(port);
4288 return NO_ERROR;
4289 }
4290 sp<SwAudioOutputDescriptor> out = mOutputs.getOutputFromId(port->id);
4291 if (out != 0) {
4292 out->toAudioPort(port);
4293 return NO_ERROR;
4294 }
4295 sp<AudioInputDescriptor> in = mInputs.getInputFromId(port->id);
4296 if (in != 0) {
4297 in->toAudioPort(port);
4298 return NO_ERROR;
4299 }
4300 return BAD_VALUE;
Eric Laurent6a94d692014-05-20 11:18:06 -07004301}
4302
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004303status_t AudioPolicyManager::createAudioPatch(const struct audio_patch *patch,
4304 audio_patch_handle_t *handle,
4305 uid_t uid)
Eric Laurent6a94d692014-05-20 11:18:06 -07004306{
François Gaffieafd4cea2019-11-18 15:50:22 +01004307 ALOGV("%s", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004308 if (handle == NULL || patch == NULL) {
4309 return BAD_VALUE;
4310 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004311 ALOGV("%s num sources %d num sinks %d", __func__, patch->num_sources, patch->num_sinks);
Mikhail Naganovac9858b2018-06-15 13:12:37 -07004312 if (!audio_patch_is_valid(patch)) {
Eric Laurent874c42872014-08-08 15:13:39 -07004313 return BAD_VALUE;
4314 }
4315 // only one source per audio patch supported for now
4316 if (patch->num_sources > 1) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004317 return INVALID_OPERATION;
4318 }
Eric Laurent874c42872014-08-08 15:13:39 -07004319 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004320 return INVALID_OPERATION;
4321 }
Eric Laurent874c42872014-08-08 15:13:39 -07004322 for (size_t i = 0; i < patch->num_sinks; i++) {
4323 if (patch->sinks[i].role != AUDIO_PORT_ROLE_SINK) {
4324 return INVALID_OPERATION;
4325 }
4326 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004327
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004328 sp<DeviceDescriptor> srcDevice = mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
4329 sp<DeviceDescriptor> sinkDevice = mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id);
4330 if (srcDevice == nullptr || sinkDevice == nullptr) {
4331 ALOGW("%s could not create patch, invalid sink and/or source device(s)", __func__);
4332 return BAD_VALUE;
4333 }
4334 ALOGV("%s between source %s and sink %s", __func__,
4335 srcDevice->toString().c_str(), sinkDevice->toString().c_str());
4336 audio_port_handle_t portId = PolicyAudioPort::getNextUniqueId();
4337 // Default attributes, default volume priority, not to infer with non raw audio patches.
4338 audio_attributes_t attributes = attributes_initializer(AUDIO_USAGE_MEDIA);
4339 const struct audio_port_config *source = &patch->sources[0];
4340 sp<SourceClientDescriptor> sourceDesc =
4341 new InternalSourceClientDescriptor(
4342 portId, uid, attributes, *source, srcDevice, sinkDevice,
4343 mEngine->getProductStrategyForAttributes(attributes), toVolumeSource(attributes));
4344
4345 status_t status =
4346 connectAudioSourceToSink(sourceDesc, sinkDevice, patch, *handle, uid, 0 /* delayMs */);
4347
4348 if (status != NO_ERROR) {
4349 return INVALID_OPERATION;
4350 }
4351 mAudioSources.add(portId, sourceDesc);
4352 return NO_ERROR;
4353}
4354
4355status_t AudioPolicyManager::connectAudioSourceToSink(
4356 const sp<SourceClientDescriptor>& sourceDesc, const sp<DeviceDescriptor> &sinkDevice,
4357 const struct audio_patch *patch,
4358 audio_patch_handle_t &handle,
4359 uid_t uid, uint32_t delayMs)
4360{
4361 status_t status = createAudioPatchInternal(patch, &handle, uid, delayMs, sourceDesc);
4362 if (status != NO_ERROR || mAudioPatches.indexOfKey(handle) < 0) {
4363 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
4364 return INVALID_OPERATION;
4365 }
4366 sourceDesc->connect(handle, sinkDevice);
4367 if (isMsdPatch(handle)) {
4368 return NO_ERROR;
4369 }
4370 // SW Bridge? (@todo: HW bridge, keep track of HwOutput for device selection "reconsideration")
4371 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
4372 ALOG_ASSERT(swOutput != nullptr, "%s: a swOutput shall always be associated", __func__);
4373 if (swOutput->getClient(sourceDesc->portId()) != nullptr) {
4374 ALOGW("%s source portId has already been attached to outputDesc", __func__);
4375 goto FailurePatchAdded;
4376 }
4377 status = swOutput->start();
4378 if (status != NO_ERROR) {
4379 goto FailureSourceAdded;
4380 }
4381 swOutput->addClient(sourceDesc);
4382 status = startSource(swOutput, sourceDesc, &delayMs);
4383 if (status != NO_ERROR) {
4384 ALOGW("%s failed to start source, error %d", __FUNCTION__, status);
4385 goto FailureSourceActive;
4386 }
4387 if (delayMs != 0) {
4388 usleep(delayMs * 1000);
4389 }
4390 return NO_ERROR;
4391
4392FailureSourceActive:
4393 swOutput->stop();
4394 releaseOutput(sourceDesc->portId());
4395FailureSourceAdded:
4396 sourceDesc->setSwOutput(nullptr);
4397FailurePatchAdded:
4398 releaseAudioPatchInternal(handle);
4399 return INVALID_OPERATION;
4400}
4401
4402status_t AudioPolicyManager::createAudioPatchInternal(const struct audio_patch *patch,
4403 audio_patch_handle_t *handle,
4404 uid_t uid, uint32_t delayMs,
4405 const sp<SourceClientDescriptor>& sourceDesc)
4406{
4407 ALOGV("%s num sources %d num sinks %d", __func__, patch->num_sources, patch->num_sinks);
Eric Laurent6a94d692014-05-20 11:18:06 -07004408 sp<AudioPatch> patchDesc;
4409 ssize_t index = mAudioPatches.indexOfKey(*handle);
4410
François Gaffieafd4cea2019-11-18 15:50:22 +01004411 ALOGV("%s source id %d role %d type %d", __func__, patch->sources[0].id,
4412 patch->sources[0].role,
4413 patch->sources[0].type);
Eric Laurent874c42872014-08-08 15:13:39 -07004414#if LOG_NDEBUG == 0
4415 for (size_t i = 0; i < patch->num_sinks; i++) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004416 ALOGV("%s sink %zu: id %d role %d type %d", __func__ ,i, patch->sinks[i].id,
4417 patch->sinks[i].role,
4418 patch->sinks[i].type);
Eric Laurent874c42872014-08-08 15:13:39 -07004419 }
4420#endif
Eric Laurent6a94d692014-05-20 11:18:06 -07004421
4422 if (index >= 0) {
4423 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01004424 ALOGV("%s mUidCached %d patchDesc->mUid %d uid %d",
4425 __func__, mUidCached, patchDesc->getUid(), uid);
4426 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004427 return INVALID_OPERATION;
4428 }
4429 } else {
Glenn Kastena13cde92016-03-28 15:26:02 -07004430 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07004431 }
4432
4433 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004434 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004435 if (outputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004436 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004437 return BAD_VALUE;
4438 }
Eric Laurent84c70242014-06-23 08:46:27 -07004439 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
4440 outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004441 if (patchDesc != 0) {
4442 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004443 ALOGV("%s source id differs for patch current id %d new id %d",
4444 __func__, patchDesc->mPatch.sources[0].id, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004445 return BAD_VALUE;
4446 }
4447 }
Eric Laurent874c42872014-08-08 15:13:39 -07004448 DeviceVector devices;
4449 for (size_t i = 0; i < patch->num_sinks; i++) {
4450 // Only support mix to devices connection
4451 // TODO add support for mix to mix connection
4452 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004453 ALOGV("%s source mix but sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07004454 return INVALID_OPERATION;
4455 }
4456 sp<DeviceDescriptor> devDesc =
4457 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
4458 if (devDesc == 0) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004459 ALOGV("%s out device not found for id %d", __func__, patch->sinks[i].id);
Eric Laurent874c42872014-08-08 15:13:39 -07004460 return BAD_VALUE;
4461 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004462
François Gaffie11d30102018-11-02 16:09:09 +01004463 if (!outputDesc->mProfile->isCompatibleProfile(DeviceVector(devDesc),
Eric Laurent874c42872014-08-08 15:13:39 -07004464 patch->sources[0].sample_rate,
François Gaffie53615e22015-03-19 09:24:12 +01004465 NULL, // updatedSamplingRate
4466 patch->sources[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07004467 NULL, // updatedFormat
François Gaffie53615e22015-03-19 09:24:12 +01004468 patch->sources[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07004469 NULL, // updatedChannelMask
François Gaffie53615e22015-03-19 09:24:12 +01004470 AUDIO_OUTPUT_FLAG_NONE /*FIXME*/)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004471 ALOGV("%s profile not supported for device %08x", __func__, devDesc->type());
Eric Laurent874c42872014-08-08 15:13:39 -07004472 return INVALID_OPERATION;
4473 }
4474 devices.add(devDesc);
4475 }
4476 if (devices.size() == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004477 return INVALID_OPERATION;
4478 }
Eric Laurent874c42872014-08-08 15:13:39 -07004479
Eric Laurent6a94d692014-05-20 11:18:06 -07004480 // TODO: reconfigure output format and channels here
François Gaffieafd4cea2019-11-18 15:50:22 +01004481 ALOGV("%s setting device %s on output %d",
4482 __func__, dumpDeviceTypes(devices.types()).c_str(), outputDesc->mIoHandle);
François Gaffie11d30102018-11-02 16:09:09 +01004483 setOutputDevices(outputDesc, devices, true, 0, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004484 index = mAudioPatches.indexOfKey(*handle);
4485 if (index >= 0) {
4486 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004487 ALOGW("%s setOutputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004488 }
4489 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01004490 patchDesc->setUid(uid);
4491 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004492 } else {
François Gaffieafd4cea2019-11-18 15:50:22 +01004493 ALOGW("%s setOutputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004494 return INVALID_OPERATION;
4495 }
4496 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
4497 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
4498 // input device to input mix connection
Eric Laurent874c42872014-08-08 15:13:39 -07004499 // only one sink supported when connecting an input device to a mix
4500 if (patch->num_sinks > 1) {
4501 return INVALID_OPERATION;
4502 }
François Gaffie53615e22015-03-19 09:24:12 +01004503 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004504 if (inputDesc == NULL) {
4505 return BAD_VALUE;
4506 }
4507 if (patchDesc != 0) {
4508 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
4509 return BAD_VALUE;
4510 }
4511 }
François Gaffie11d30102018-11-02 16:09:09 +01004512 sp<DeviceDescriptor> device =
Eric Laurent6a94d692014-05-20 11:18:06 -07004513 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01004514 if (device == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004515 return BAD_VALUE;
4516 }
4517
François Gaffie11d30102018-11-02 16:09:09 +01004518 if (!inputDesc->mProfile->isCompatibleProfile(DeviceVector(device),
Eric Laurent275e8e92014-11-30 15:14:47 -08004519 patch->sinks[0].sample_rate,
4520 NULL, /*updatedSampleRate*/
4521 patch->sinks[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07004522 NULL, /*updatedFormat*/
Eric Laurent275e8e92014-11-30 15:14:47 -08004523 patch->sinks[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07004524 NULL, /*updatedChannelMask*/
Eric Laurent275e8e92014-11-30 15:14:47 -08004525 // FIXME for the parameter type,
4526 // and the NONE
4527 (audio_output_flags_t)
Glenn Kasten6a8ab052014-07-24 14:08:35 -07004528 AUDIO_INPUT_FLAG_NONE)) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004529 return INVALID_OPERATION;
4530 }
4531 // TODO: reconfigure output format and channels here
François Gaffieafd4cea2019-11-18 15:50:22 +01004532 ALOGV("%s setting device %s on output %d", __func__,
François Gaffie11d30102018-11-02 16:09:09 +01004533 device->toString().c_str(), inputDesc->mIoHandle);
4534 setInputDevice(inputDesc->mIoHandle, device, true, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004535 index = mAudioPatches.indexOfKey(*handle);
4536 if (index >= 0) {
4537 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004538 ALOGW("%s setInputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004539 }
4540 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01004541 patchDesc->setUid(uid);
4542 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004543 } else {
François Gaffieafd4cea2019-11-18 15:50:22 +01004544 ALOGW("%s setInputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004545 return INVALID_OPERATION;
4546 }
4547 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
4548 // device to device connection
4549 if (patchDesc != 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07004550 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004551 return BAD_VALUE;
4552 }
4553 }
François Gaffie11d30102018-11-02 16:09:09 +01004554 sp<DeviceDescriptor> srcDevice =
Eric Laurent6a94d692014-05-20 11:18:06 -07004555 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01004556 if (srcDevice == 0) {
Eric Laurent58f8eb72014-09-12 16:19:41 -07004557 return BAD_VALUE;
4558 }
Eric Laurent874c42872014-08-08 15:13:39 -07004559
Eric Laurent6a94d692014-05-20 11:18:06 -07004560 //update source and sink with our own data as the data passed in the patch may
4561 // be incomplete.
François Gaffieafd4cea2019-11-18 15:50:22 +01004562 PatchBuilder patchBuilder;
4563 audio_port_config sourcePortConfig = {};
Dean Wheatley8bee85a2021-02-10 16:02:23 +11004564
4565 // if first sink is to MSD, establish single MSD patch
4566 if (getMsdAudioOutDevices().contains(
4567 mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id))) {
4568 ALOGV("%s patching to MSD", __FUNCTION__);
4569 patchBuilder = buildMsdPatch(false /*msdIsSource*/, srcDevice);
4570 goto installPatch;
4571 }
4572
François Gaffieafd4cea2019-11-18 15:50:22 +01004573 srcDevice->toAudioPortConfig(&sourcePortConfig, &patch->sources[0]);
4574 patchBuilder.addSource(sourcePortConfig);
Eric Laurent6a94d692014-05-20 11:18:06 -07004575
Eric Laurent874c42872014-08-08 15:13:39 -07004576 for (size_t i = 0; i < patch->num_sinks; i++) {
4577 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004578 ALOGV("%s source device but one sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07004579 return INVALID_OPERATION;
4580 }
François Gaffie11d30102018-11-02 16:09:09 +01004581 sp<DeviceDescriptor> sinkDevice =
Eric Laurent874c42872014-08-08 15:13:39 -07004582 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
François Gaffie11d30102018-11-02 16:09:09 +01004583 if (sinkDevice == 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07004584 return BAD_VALUE;
4585 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004586 audio_port_config sinkPortConfig = {};
4587 sinkDevice->toAudioPortConfig(&sinkPortConfig, &patch->sinks[i]);
4588 patchBuilder.addSink(sinkPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07004589
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004590 // Whatever Sw or Hw bridge, we do attach an SwOutput to an Audio Source for
4591 // volume management purpose (tracking activity)
4592 // In case of Hw bridge, it is a Work Around. The mixPort used is the one declared
4593 // in config XML to reach the sink so that is can be declared as available.
4594 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurent78b07302022-10-07 16:20:34 +02004595 sp<SwAudioOutputDescriptor> outputDesc;
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004596 if (!sourceDesc->isInternal()) {
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004597 // take care of dynamic routing for SwOutput selection,
4598 audio_attributes_t attributes = sourceDesc->attributes();
4599 audio_stream_type_t stream = sourceDesc->stream();
4600 audio_attributes_t resultAttr;
4601 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
4602 config.sample_rate = sourceDesc->config().sample_rate;
4603 config.channel_mask = sourceDesc->config().channel_mask;
4604 config.format = sourceDesc->config().format;
4605 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
4606 audio_port_handle_t selectedDeviceId = AUDIO_PORT_HANDLE_NONE;
4607 bool isRequestedDeviceForExclusiveUse = false;
4608 output_type_t outputType;
Eric Laurentb0a7bc92022-04-05 15:06:08 +02004609 bool isSpatialized;
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004610 getOutputForAttrInt(&resultAttr, &output, AUDIO_SESSION_NONE, &attributes,
4611 &stream, sourceDesc->uid(), &config, &flags,
4612 &selectedDeviceId, &isRequestedDeviceForExclusiveUse,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02004613 nullptr, &outputType, &isSpatialized);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004614 if (output == AUDIO_IO_HANDLE_NONE) {
4615 ALOGV("%s no output for device %s",
4616 __FUNCTION__, sinkDevice->toString().c_str());
4617 return INVALID_OPERATION;
4618 }
4619 outputDesc = mOutputs.valueFor(output);
4620 if (outputDesc->isDuplicated()) {
4621 ALOGE("%s output is duplicated", __func__);
4622 return INVALID_OPERATION;
4623 }
François Gaffie1765c5b2022-04-26 12:48:49 +02004624 bool closeOutput = outputDesc->mDirectOpenCount != 0;
4625 sourceDesc->setSwOutput(outputDesc, closeOutput);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004626 } else {
4627 // Same for "raw patches" aka created from createAudioPatch API
4628 SortedVector<audio_io_handle_t> outputs =
4629 getOutputsForDevices(DeviceVector(sinkDevice), mOutputs);
4630 // if the sink device is reachable via an opened output stream, request to
4631 // go via this output stream by adding a second source to the patch
4632 // description
4633 output = selectOutput(outputs);
4634 if (output == AUDIO_IO_HANDLE_NONE) {
4635 ALOGE("%s no output available for internal patch sink", __func__);
4636 return INVALID_OPERATION;
4637 }
4638 outputDesc = mOutputs.valueFor(output);
4639 if (outputDesc->isDuplicated()) {
4640 ALOGV("%s output for device %s is duplicated",
4641 __func__, sinkDevice->toString().c_str());
4642 return INVALID_OPERATION;
4643 }
François Gaffie1765c5b2022-04-26 12:48:49 +02004644 sourceDesc->setSwOutput(outputDesc, /* closeOutput= */ false);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004645 }
Eric Laurent3bcf8592015-04-03 12:13:24 -07004646 // create a software bridge in PatchPanel if:
Scott Randolphf3172402018-01-23 17:06:53 -08004647 // - source and sink devices are on different HW modules OR
Eric Laurent3bcf8592015-04-03 12:13:24 -07004648 // - audio HAL version is < 3.0
Francois Gaffie99896da2018-04-09 11:05:33 +02004649 // - audio HAL version is >= 3.0 but no route has been declared between devices
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004650 // - called from startAudioSource (aka sourceDesc is not internal) and source device
4651 // does not have a gain controller
François Gaffie11d30102018-11-02 16:09:09 +01004652 if (!srcDevice->hasSameHwModuleAs(sinkDevice) ||
4653 (srcDevice->getModuleVersionMajor() < 3) ||
François Gaffieafd4cea2019-11-18 15:50:22 +01004654 !srcDevice->getModule()->supportsPatch(srcDevice, sinkDevice) ||
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004655 (!sourceDesc->isInternal() &&
François Gaffieafd4cea2019-11-18 15:50:22 +01004656 srcDevice->getAudioPort()->getGains().size() == 0)) {
Eric Laurent3bcf8592015-04-03 12:13:24 -07004657 // support only one sink device for now to simplify output selection logic
Eric Laurent874c42872014-08-08 15:13:39 -07004658 if (patch->num_sinks > 1) {
Eric Laurent83b88082014-06-20 18:31:16 -07004659 return INVALID_OPERATION;
4660 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004661 sourceDesc->setUseSwBridge();
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004662 if (outputDesc != nullptr) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004663 audio_port_config srcMixPortConfig = {};
Ytai Ben-Tsvic9d2a912021-11-22 16:43:09 -08004664 outputDesc->toAudioPortConfig(&srcMixPortConfig, nullptr);
François Gaffieafd4cea2019-11-18 15:50:22 +01004665 // for volume control, we may need a valid stream
Eric Laurent78b07302022-10-07 16:20:34 +02004666 srcMixPortConfig.ext.mix.usecase.stream =
4667 (!sourceDesc->isInternal() || isCallTxAudioSource(sourceDesc)) ?
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004668 mEngine->getStreamTypeForAttributes(sourceDesc->attributes()) :
4669 AUDIO_STREAM_PATCH;
François Gaffieafd4cea2019-11-18 15:50:22 +01004670 patchBuilder.addSource(srcMixPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07004671 }
Eric Laurent83b88082014-06-20 18:31:16 -07004672 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004673 }
4674 // TODO: check from routing capabilities in config file and other conflicting patches
4675
Dean Wheatley8bee85a2021-02-10 16:02:23 +11004676installPatch:
François Gaffieafd4cea2019-11-18 15:50:22 +01004677 status_t status = installPatch(
4678 __func__, index, handle, patchBuilder.patch(), delayMs, uid, &patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07004679 if (status != NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004680 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
Eric Laurent6a94d692014-05-20 11:18:06 -07004681 return INVALID_OPERATION;
4682 }
4683 } else {
4684 return BAD_VALUE;
4685 }
4686 } else {
4687 return BAD_VALUE;
4688 }
4689 return NO_ERROR;
4690}
4691
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004692status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle, uid_t uid)
Eric Laurent6a94d692014-05-20 11:18:06 -07004693{
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004694 ALOGV("%s patch %d", __func__, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004695 ssize_t index = mAudioPatches.indexOfKey(handle);
4696
4697 if (index < 0) {
4698 return BAD_VALUE;
4699 }
4700 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01004701 ALOGV("%s() mUidCached %d patchDesc->mUid %d uid %d",
4702 __func__, mUidCached, patchDesc->getUid(), uid);
4703 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004704 return INVALID_OPERATION;
4705 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004706 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
4707 for (size_t i = 0; i < mAudioSources.size(); i++) {
4708 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
4709 if (sourceDesc != nullptr && sourceDesc->getPatchHandle() == handle) {
4710 portId = sourceDesc->portId();
4711 break;
4712 }
4713 }
4714 return portId != AUDIO_PORT_HANDLE_NONE ?
4715 stopAudioSource(portId) : releaseAudioPatchInternal(handle);
François Gaffieafd4cea2019-11-18 15:50:22 +01004716}
Eric Laurent6a94d692014-05-20 11:18:06 -07004717
François Gaffieafd4cea2019-11-18 15:50:22 +01004718status_t AudioPolicyManager::releaseAudioPatchInternal(audio_patch_handle_t handle,
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004719 uint32_t delayMs,
4720 const sp<SourceClientDescriptor>& sourceDesc)
François Gaffieafd4cea2019-11-18 15:50:22 +01004721{
4722 ALOGV("%s patch %d", __func__, handle);
4723 if (mAudioPatches.indexOfKey(handle) < 0) {
4724 ALOGE("%s: no patch found with handle=%d", __func__, handle);
4725 return BAD_VALUE;
4726 }
4727 sp<AudioPatch> patchDesc = mAudioPatches.valueFor(handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004728 struct audio_patch *patch = &patchDesc->mPatch;
François Gaffieafd4cea2019-11-18 15:50:22 +01004729 patchDesc->setUid(mUidCached);
Eric Laurent6a94d692014-05-20 11:18:06 -07004730 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004731 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004732 if (outputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004733 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004734 return BAD_VALUE;
4735 }
4736
François Gaffie11d30102018-11-02 16:09:09 +01004737 setOutputDevices(outputDesc,
4738 getNewOutputDevices(outputDesc, true /*fromCache*/),
4739 true,
4740 0,
4741 NULL);
Eric Laurent6a94d692014-05-20 11:18:06 -07004742 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
4743 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
François Gaffie53615e22015-03-19 09:24:12 +01004744 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004745 if (inputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004746 ALOGV("%s input not found for id %d", __func__, patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004747 return BAD_VALUE;
4748 }
4749 setInputDevice(inputDesc->mIoHandle,
Eric Laurentfb66dd92016-01-28 18:32:03 -08004750 getNewInputDevice(inputDesc),
Eric Laurent6a94d692014-05-20 11:18:06 -07004751 true,
4752 NULL);
4753 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004754 status_t status =
4755 mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
4756 ALOGV("%s patch panel returned %d patchHandle %d",
4757 __func__, status, patchDesc->getAfHandle());
4758 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004759 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004760 mpClientInterface->onAudioPatchListUpdate();
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004761 // SW or HW Bridge
4762 sp<SwAudioOutputDescriptor> outputDesc = nullptr;
4763 audio_patch_handle_t patchHandle = AUDIO_PATCH_HANDLE_NONE;
Francois Gaffie7feb8542020-04-06 17:39:47 +02004764 if (patch->num_sources > 1 && patch->sources[1].type == AUDIO_PORT_TYPE_MIX) {
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004765 outputDesc = mOutputs.getOutputFromId(patch->sources[1].id);
4766 } else if (patch->num_sources == 1 && sourceDesc != nullptr) {
4767 outputDesc = sourceDesc->swOutput().promote();
4768 }
4769 if (outputDesc == nullptr) {
4770 ALOGW("%s no output for id %d", __func__, patch->sources[0].id);
4771 // releaseOutput has already called closeOutput in case of direct output
4772 return NO_ERROR;
4773 }
François Gaffie1765c5b2022-04-26 12:48:49 +02004774 patchHandle = outputDesc->getPatchHandle();
4775 // When a Sw bridge is released, the mixer used by this bridge will release its
4776 // patch at AudioFlinger side. Hence, the mixer audio patch must be recreated
4777 // Reuse patch handle to force audio flinger removing initial mixer patch removal
4778 // updating hal patch handle (prevent leaks).
4779 // While using a HwBridge, force reconsidering device only if not reusing an existing
4780 // output and no more activity on output (will force to close).
4781 bool force = sourceDesc->useSwBridge() ||
4782 (sourceDesc->canCloseOutput() && !outputDesc->isActive());
4783 // APM pattern is to have always outputs opened / patch realized for reachable devices.
4784 // Update device may result to NONE (empty), coupled with force, it releases the patch.
4785 // Reconsider device only for cases:
4786 // 1 / Active Output
4787 // 2 / Inactive Output previously hosting HwBridge
4788 // 3 / Inactive Output previously hosting SwBridge that can be closed.
4789 bool updateDevice = outputDesc->isActive() || !sourceDesc->useSwBridge() ||
4790 sourceDesc->canCloseOutput();
4791 setOutputDevices(outputDesc,
4792 updateDevice ? getNewOutputDevices(outputDesc, true /*fromCache*/) :
4793 outputDesc->devices(),
4794 force,
4795 0,
4796 patchHandle == AUDIO_PATCH_HANDLE_NONE ? nullptr : &patchHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004797 } else {
4798 return BAD_VALUE;
4799 }
4800 } else {
4801 return BAD_VALUE;
4802 }
4803 return NO_ERROR;
4804}
4805
4806status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
4807 struct audio_patch *patches,
4808 unsigned int *generation)
4809{
François Gaffie53615e22015-03-19 09:24:12 +01004810 if (generation == NULL) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004811 return BAD_VALUE;
4812 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004813 *generation = curAudioPortGeneration();
François Gaffie53615e22015-03-19 09:24:12 +01004814 return mAudioPatches.listAudioPatches(num_patches, patches);
Eric Laurent6a94d692014-05-20 11:18:06 -07004815}
4816
Eric Laurente1715a42014-05-20 11:30:42 -07004817status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07004818{
Eric Laurente1715a42014-05-20 11:30:42 -07004819 ALOGV("setAudioPortConfig()");
4820
4821 if (config == NULL) {
4822 return BAD_VALUE;
4823 }
4824 ALOGV("setAudioPortConfig() on port handle %d", config->id);
4825 // Only support gain configuration for now
Eric Laurenta121f902014-06-03 13:32:54 -07004826 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
4827 return INVALID_OPERATION;
Eric Laurente1715a42014-05-20 11:30:42 -07004828 }
4829
Eric Laurenta121f902014-06-03 13:32:54 -07004830 sp<AudioPortConfig> audioPortConfig;
Eric Laurente1715a42014-05-20 11:30:42 -07004831 if (config->type == AUDIO_PORT_TYPE_MIX) {
4832 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004833 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07004834 if (outputDesc == NULL) {
4835 return BAD_VALUE;
4836 }
Eric Laurent84c70242014-06-23 08:46:27 -07004837 ALOG_ASSERT(!outputDesc->isDuplicated(),
4838 "setAudioPortConfig() called on duplicated output %d",
4839 outputDesc->mIoHandle);
Eric Laurenta121f902014-06-03 13:32:54 -07004840 audioPortConfig = outputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07004841 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
François Gaffie53615e22015-03-19 09:24:12 +01004842 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07004843 if (inputDesc == NULL) {
4844 return BAD_VALUE;
4845 }
Eric Laurenta121f902014-06-03 13:32:54 -07004846 audioPortConfig = inputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07004847 } else {
4848 return BAD_VALUE;
4849 }
4850 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
4851 sp<DeviceDescriptor> deviceDesc;
4852 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
4853 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
4854 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
4855 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
4856 } else {
4857 return BAD_VALUE;
4858 }
4859 if (deviceDesc == NULL) {
4860 return BAD_VALUE;
4861 }
Eric Laurenta121f902014-06-03 13:32:54 -07004862 audioPortConfig = deviceDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07004863 } else {
4864 return BAD_VALUE;
4865 }
4866
Mikhail Naganov7be71d22018-05-23 16:51:46 -07004867 struct audio_port_config backupConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07004868 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
4869 if (status == NO_ERROR) {
Mikhail Naganov7be71d22018-05-23 16:51:46 -07004870 struct audio_port_config newConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07004871 audioPortConfig->toAudioPortConfig(&newConfig, config);
4872 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
Eric Laurente1715a42014-05-20 11:30:42 -07004873 }
Eric Laurenta121f902014-06-03 13:32:54 -07004874 if (status != NO_ERROR) {
4875 audioPortConfig->applyAudioPortConfig(&backupConfig);
Eric Laurente1715a42014-05-20 11:30:42 -07004876 }
Eric Laurente1715a42014-05-20 11:30:42 -07004877
4878 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07004879}
4880
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004881void AudioPolicyManager::releaseResourcesForUid(uid_t uid)
4882{
Eric Laurentd60560a2015-04-10 11:31:20 -07004883 clearAudioSources(uid);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004884 clearAudioPatches(uid);
4885 clearSessionRoutes(uid);
4886}
4887
Eric Laurent6a94d692014-05-20 11:18:06 -07004888void AudioPolicyManager::clearAudioPatches(uid_t uid)
4889{
Eric Laurent0add0fd2014-12-04 18:58:14 -08004890 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004891 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
François Gaffieafd4cea2019-11-18 15:50:22 +01004892 if (patchDesc->getUid() == uid) {
Eric Laurent0add0fd2014-12-04 18:58:14 -08004893 releaseAudioPatch(mAudioPatches.keyAt(i), uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07004894 }
4895 }
4896}
4897
François Gaffiec005e562018-11-06 15:04:49 +01004898void AudioPolicyManager::checkStrategyRoute(product_strategy_t ps, audio_io_handle_t ouptutToSkip)
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004899{
François Gaffiec005e562018-11-06 15:04:49 +01004900 // Take the first attributes following the product strategy as it is used to retrieve the routed
4901 // device. All attributes wihin a strategy follows the same "routing strategy"
4902 auto attributes = mEngine->getAllAttributesForProductStrategy(ps).front();
4903 DeviceVector devices = mEngine->getOutputDevicesForAttributes(attributes, nullptr, false);
François Gaffie11d30102018-11-02 16:09:09 +01004904 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004905 for (size_t j = 0; j < mOutputs.size(); j++) {
4906 if (mOutputs.keyAt(j) == ouptutToSkip) {
4907 continue;
4908 }
4909 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(j);
François Gaffiec005e562018-11-06 15:04:49 +01004910 if (!outputDesc->isStrategyActive(ps)) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004911 continue;
4912 }
4913 // If the default device for this strategy is on another output mix,
4914 // invalidate all tracks in this strategy to force re connection.
4915 // Otherwise select new device on the output mix.
4916 if (outputs.indexOf(mOutputs.keyAt(j)) < 0) {
François Gaffiec005e562018-11-06 15:04:49 +01004917 for (auto stream : mEngine->getStreamTypesForProductStrategy(ps)) {
4918 mpClientInterface->invalidateStream(stream);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004919 }
4920 } else {
François Gaffie11d30102018-11-02 16:09:09 +01004921 setOutputDevices(
4922 outputDesc, getNewOutputDevices(outputDesc, false /*fromCache*/), false);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004923 }
4924 }
4925}
4926
4927void AudioPolicyManager::clearSessionRoutes(uid_t uid)
4928{
4929 // remove output routes associated with this uid
François Gaffiec005e562018-11-06 15:04:49 +01004930 std::vector<product_strategy_t> affectedStrategies;
Eric Laurent97ac8712018-07-27 18:59:02 -07004931 for (size_t i = 0; i < mOutputs.size(); i++) {
4932 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07004933 for (const auto& client : outputDesc->getClientIterable()) {
4934 if (client->hasPreferredDevice() && client->uid() == uid) {
4935 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
François Gaffiec005e562018-11-06 15:04:49 +01004936 auto clientStrategy = client->strategy();
4937 if (std::find(begin(affectedStrategies), end(affectedStrategies), clientStrategy) !=
4938 end(affectedStrategies)) {
4939 continue;
4940 }
4941 affectedStrategies.push_back(client->strategy());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004942 }
4943 }
4944 }
4945 // reroute outputs if necessary
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004946 for (const auto& strategy : affectedStrategies) {
4947 checkStrategyRoute(strategy, AUDIO_IO_HANDLE_NONE);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004948 }
4949
4950 // remove input routes associated with this uid
4951 SortedVector<audio_source_t> affectedSources;
Eric Laurent97ac8712018-07-27 18:59:02 -07004952 for (size_t i = 0; i < mInputs.size(); i++) {
4953 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07004954 for (const auto& client : inputDesc->getClientIterable()) {
4955 if (client->hasPreferredDevice() && client->uid() == uid) {
4956 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
4957 affectedSources.add(client->source());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004958 }
4959 }
4960 }
4961 // reroute inputs if necessary
4962 SortedVector<audio_io_handle_t> inputsToClose;
4963 for (size_t i = 0; i < mInputs.size(); i++) {
4964 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Eric Laurent4eb58f12018-12-07 16:41:02 -08004965 if (affectedSources.indexOf(inputDesc->source()) >= 0) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004966 inputsToClose.add(inputDesc->mIoHandle);
4967 }
4968 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004969 for (const auto& input : inputsToClose) {
4970 closeInput(input);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004971 }
4972}
4973
Eric Laurentd60560a2015-04-10 11:31:20 -07004974void AudioPolicyManager::clearAudioSources(uid_t uid)
4975{
4976 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004977 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
4978 if (sourceDesc->uid() == uid) {
Eric Laurentd60560a2015-04-10 11:31:20 -07004979 stopAudioSource(mAudioSources.keyAt(i));
4980 }
4981 }
4982}
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004983
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07004984status_t AudioPolicyManager::acquireSoundTriggerSession(audio_session_t *session,
4985 audio_io_handle_t *ioHandle,
4986 audio_devices_t *device)
4987{
Glenn Kastenf0c6d7d2016-02-26 10:44:04 -08004988 *session = (audio_session_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
4989 *ioHandle = (audio_io_handle_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
Francois Gaffie716e1432019-01-14 16:58:59 +01004990 audio_attributes_t attr = { .source = AUDIO_SOURCE_HOTWORD };
François Gaffiec005e562018-11-06 15:04:49 +01004991 *device = mEngine->getInputDeviceForAttributes(attr)->type();
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07004992
François Gaffiedf372692015-03-19 10:43:27 +01004993 return mSoundTriggerSessions.acquireSession(*session, *ioHandle);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07004994}
4995
Eric Laurentd60560a2015-04-10 11:31:20 -07004996status_t AudioPolicyManager::startAudioSource(const struct audio_port_config *source,
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004997 const audio_attributes_t *attributes,
4998 audio_port_handle_t *portId,
4999 uid_t uid)
Eric Laurent554a2772015-04-10 11:29:24 -07005000{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005001 ALOGV("%s", __FUNCTION__);
5002 *portId = AUDIO_PORT_HANDLE_NONE;
5003
5004 if (source == NULL || attributes == NULL || portId == NULL) {
5005 ALOGW("%s invalid argument: source %p attributes %p handle %p",
5006 __FUNCTION__, source, attributes, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005007 return BAD_VALUE;
5008 }
5009
Eric Laurentd60560a2015-04-10 11:31:20 -07005010 if (source->role != AUDIO_PORT_ROLE_SOURCE ||
5011 source->type != AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005012 ALOGW("%s INVALID_OPERATION source->role %d source->type %d",
5013 __FUNCTION__, source->role, source->type);
Eric Laurentd60560a2015-04-10 11:31:20 -07005014 return INVALID_OPERATION;
5015 }
5016
François Gaffie11d30102018-11-02 16:09:09 +01005017 sp<DeviceDescriptor> srcDevice =
Eric Laurentd60560a2015-04-10 11:31:20 -07005018 mAvailableInputDevices.getDevice(source->ext.device.type,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005019 String8(source->ext.device.address),
5020 AUDIO_FORMAT_DEFAULT);
François Gaffie11d30102018-11-02 16:09:09 +01005021 if (srcDevice == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005022 ALOGW("%s source->ext.device.type %08x not found", __FUNCTION__, source->ext.device.type);
Eric Laurentd60560a2015-04-10 11:31:20 -07005023 return BAD_VALUE;
5024 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005025
jiabin4ef93452019-09-10 14:29:54 -07005026 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurentd60560a2015-04-10 11:31:20 -07005027
François Gaffieaaac0fd2018-11-22 17:56:39 +01005028 sp<SourceClientDescriptor> sourceDesc =
François Gaffieafd4cea2019-11-18 15:50:22 +01005029 new SourceClientDescriptor(*portId, uid, *attributes, *source, srcDevice,
François Gaffieaaac0fd2018-11-22 17:56:39 +01005030 mEngine->getStreamTypeForAttributes(*attributes),
5031 mEngine->getProductStrategyForAttributes(*attributes),
5032 toVolumeSource(*attributes));
Eric Laurentd60560a2015-04-10 11:31:20 -07005033
5034 status_t status = connectAudioSource(sourceDesc);
5035 if (status == NO_ERROR) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005036 mAudioSources.add(*portId, sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07005037 }
5038 return status;
5039}
5040
Francois Gaffie601801d2021-06-22 13:27:39 +02005041sp<SourceClientDescriptor> AudioPolicyManager::startAudioSourceInternal(
5042 const struct audio_port_config *source, const audio_attributes_t *attributes, uid_t uid)
5043{
5044 ALOGV("%s", __FUNCTION__);
5045 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
5046
5047 status_t status = startAudioSource(source, attributes, &portId, uid);
5048 ALOGE_IF(status != OK, "%s: failed to start audio source (%d)", __func__, status);
5049 return mAudioSources.valueFor(portId);
5050}
5051
5052
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005053status_t AudioPolicyManager::connectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07005054{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005055 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->portId());
Eric Laurentd60560a2015-04-10 11:31:20 -07005056
5057 // make sure we only have one patch per source.
5058 disconnectAudioSource(sourceDesc);
5059
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005060 audio_attributes_t attributes = sourceDesc->attributes();
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005061 // May the device (dynamic) have been disconnected/reconnected, id has changed.
5062 sp<DeviceDescriptor> srcDevice = mAvailableInputDevices.getDevice(
5063 sourceDesc->srcDevice()->type(),
5064 String8(sourceDesc->srcDevice()->address().c_str()),
5065 AUDIO_FORMAT_DEFAULT);
François Gaffiec005e562018-11-06 15:04:49 +01005066 DeviceVector sinkDevices =
Francois Gaffieff1eb522020-05-06 18:37:04 +02005067 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false /*fromCache*/);
François Gaffiec005e562018-11-06 15:04:49 +01005068 ALOG_ASSERT(!sinkDevices.isEmpty(), "connectAudioSource(): no device found for attributes");
François Gaffie11d30102018-11-02 16:09:09 +01005069 sp<DeviceDescriptor> sinkDevice = sinkDevices.itemAt(0);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005070 if (!mAvailableOutputDevices.contains(sinkDevice)) {
5071 ALOGE("%s Device %s not available", __func__, sinkDevice->toString().c_str());
5072 return INVALID_OPERATION;
5073 }
François Gaffieafd4cea2019-11-18 15:50:22 +01005074 PatchBuilder patchBuilder;
5075 patchBuilder.addSink(sinkDevice).addSource(srcDevice);
5076 audio_patch_handle_t handle = AUDIO_PATCH_HANDLE_NONE;
François Gaffieafd4cea2019-11-18 15:50:22 +01005077
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005078 return connectAudioSourceToSink(
5079 sourceDesc, sinkDevice, patchBuilder.patch(), handle, mUidCached, 0 /*delayMs*/);
Eric Laurent554a2772015-04-10 11:29:24 -07005080}
5081
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005082status_t AudioPolicyManager::stopAudioSource(audio_port_handle_t portId)
Eric Laurent554a2772015-04-10 11:29:24 -07005083{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005084 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueFor(portId);
5085 ALOGV("%s port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005086 if (sourceDesc == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005087 ALOGW("%s unknown source for port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005088 return BAD_VALUE;
5089 }
5090 status_t status = disconnectAudioSource(sourceDesc);
5091
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005092 mAudioSources.removeItem(portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005093 return status;
5094}
5095
Andy Hung2ddee192015-12-18 17:34:44 -08005096status_t AudioPolicyManager::setMasterMono(bool mono)
5097{
5098 if (mMasterMono == mono) {
5099 return NO_ERROR;
5100 }
5101 mMasterMono = mono;
5102 // if enabling mono we close all offloaded devices, which will invalidate the
5103 // corresponding AudioTrack. The AudioTrack client/MediaPlayer is responsible
5104 // for recreating the new AudioTrack as non-offloaded PCM.
5105 //
5106 // If disabling mono, we leave all tracks as is: we don't know which clients
5107 // and tracks are able to be recreated as offloaded. The next "song" should
5108 // play back offloaded.
5109 if (mMasterMono) {
5110 Vector<audio_io_handle_t> offloaded;
5111 for (size_t i = 0; i < mOutputs.size(); ++i) {
5112 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
5113 if (desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
5114 offloaded.push(desc->mIoHandle);
5115 }
5116 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005117 for (const auto& handle : offloaded) {
5118 closeOutput(handle);
Andy Hung2ddee192015-12-18 17:34:44 -08005119 }
5120 }
5121 // update master mono for all remaining outputs
5122 for (size_t i = 0; i < mOutputs.size(); ++i) {
5123 updateMono(mOutputs.keyAt(i));
5124 }
5125 return NO_ERROR;
5126}
5127
5128status_t AudioPolicyManager::getMasterMono(bool *mono)
5129{
5130 *mono = mMasterMono;
5131 return NO_ERROR;
5132}
5133
Eric Laurentac9cef52017-06-09 15:46:26 -07005134float AudioPolicyManager::getStreamVolumeDB(
5135 audio_stream_type_t stream, int index, audio_devices_t device)
5136{
jiabin9a3361e2019-10-01 09:38:30 -07005137 return computeVolume(getVolumeCurves(stream), toVolumeSource(stream), index, {device});
Eric Laurentac9cef52017-06-09 15:46:26 -07005138}
5139
jiabin81772902018-04-02 17:52:27 -07005140status_t AudioPolicyManager::getSurroundFormats(unsigned int *numSurroundFormats,
5141 audio_format_t *surroundFormats,
Kriti Dang6537def2021-03-02 13:46:59 +01005142 bool *surroundFormatsEnabled)
jiabin81772902018-04-02 17:52:27 -07005143{
Kriti Dang6537def2021-03-02 13:46:59 +01005144 if (numSurroundFormats == nullptr || (*numSurroundFormats != 0 &&
5145 (surroundFormats == nullptr || surroundFormatsEnabled == nullptr))) {
jiabin81772902018-04-02 17:52:27 -07005146 return BAD_VALUE;
5147 }
Kriti Dang6537def2021-03-02 13:46:59 +01005148 ALOGV("%s() numSurroundFormats %d surroundFormats %p surroundFormatsEnabled %p",
5149 __func__, *numSurroundFormats, surroundFormats, surroundFormatsEnabled);
jiabin81772902018-04-02 17:52:27 -07005150
5151 size_t formatsWritten = 0;
5152 size_t formatsMax = *numSurroundFormats;
Kriti Dangef6be8f2020-11-05 11:58:19 +01005153
Mikhail Naganovb0fbc1b2023-04-28 13:06:32 -07005154 *numSurroundFormats = mConfig->getSurroundFormats().size();
Mikhail Naganov100f0122018-11-29 11:22:16 -08005155 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
5156 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Mikhail Naganovb0fbc1b2023-04-28 13:06:32 -07005157 for (const auto& format: mConfig->getSurroundFormats()) {
jiabin81772902018-04-02 17:52:27 -07005158 if (formatsWritten < formatsMax) {
Kriti Dang6537def2021-03-02 13:46:59 +01005159 surroundFormats[formatsWritten] = format.first;
Mikhail Naganov100f0122018-11-29 11:22:16 -08005160 bool formatEnabled = true;
5161 switch (forceUse) {
5162 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL:
Kriti Dang6537def2021-03-02 13:46:59 +01005163 formatEnabled = mManualSurroundFormats.count(format.first) != 0;
Mikhail Naganov100f0122018-11-29 11:22:16 -08005164 break;
5165 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER:
5166 formatEnabled = false;
5167 break;
5168 default: // AUTO or ALWAYS => true
5169 break;
jiabin81772902018-04-02 17:52:27 -07005170 }
5171 surroundFormatsEnabled[formatsWritten++] = formatEnabled;
5172 }
jiabin81772902018-04-02 17:52:27 -07005173 }
5174 return NO_ERROR;
5175}
5176
Kriti Dang6537def2021-03-02 13:46:59 +01005177status_t AudioPolicyManager::getReportedSurroundFormats(unsigned int *numSurroundFormats,
5178 audio_format_t *surroundFormats) {
5179 if (numSurroundFormats == nullptr || (*numSurroundFormats != 0 && surroundFormats == nullptr)) {
5180 return BAD_VALUE;
5181 }
5182 ALOGV("%s() numSurroundFormats %d surroundFormats %p",
5183 __func__, *numSurroundFormats, surroundFormats);
5184
5185 size_t formatsWritten = 0;
5186 size_t formatsMax = *numSurroundFormats;
5187 std::unordered_set<audio_format_t> formats; // Uses primary surround formats only
5188
5189 // Return formats from all device profiles that have already been resolved by
5190 // checkOutputsForDevice().
5191 for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
5192 sp<DeviceDescriptor> device = mAvailableOutputDevices[i];
5193 audio_devices_t deviceType = device->type();
5194 // Enabling/disabling formats are applied to only HDMI devices. So, this function
5195 // returns formats reported by HDMI devices.
5196 if (deviceType != AUDIO_DEVICE_OUT_HDMI) {
5197 continue;
5198 }
5199 // Formats reported by sink devices
5200 std::unordered_set<audio_format_t> formatset;
5201 if (auto it = mReportedFormatsMap.find(device); it != mReportedFormatsMap.end()) {
5202 formatset.insert(it->second.begin(), it->second.end());
5203 }
5204
5205 // Formats hard-coded in the in policy configuration file (if any).
5206 FormatVector encodedFormats = device->encodedFormats();
5207 formatset.insert(encodedFormats.begin(), encodedFormats.end());
5208 // Filter the formats which are supported by the vendor hardware.
5209 for (auto it = formatset.begin(); it != formatset.end(); ++it) {
Mikhail Naganovb0fbc1b2023-04-28 13:06:32 -07005210 if (mConfig->getSurroundFormats().count(*it) != 0) {
Kriti Dang6537def2021-03-02 13:46:59 +01005211 formats.insert(*it);
5212 } else {
Mikhail Naganovb0fbc1b2023-04-28 13:06:32 -07005213 for (const auto& pair : mConfig->getSurroundFormats()) {
Kriti Dang6537def2021-03-02 13:46:59 +01005214 if (pair.second.count(*it) != 0) {
5215 formats.insert(pair.first);
5216 break;
5217 }
5218 }
5219 }
5220 }
5221 }
5222 *numSurroundFormats = formats.size();
5223 for (const auto& format: formats) {
5224 if (formatsWritten < formatsMax) {
5225 surroundFormats[formatsWritten++] = format;
5226 }
5227 }
5228 return NO_ERROR;
5229}
5230
jiabin81772902018-04-02 17:52:27 -07005231status_t AudioPolicyManager::setSurroundFormatEnabled(audio_format_t audioFormat, bool enabled)
5232{
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005233 ALOGV("%s() format 0x%X enabled %d", __func__, audioFormat, enabled);
Mikhail Naganovb0fbc1b2023-04-28 13:06:32 -07005234 const auto& formatIter = mConfig->getSurroundFormats().find(audioFormat);
5235 if (formatIter == mConfig->getSurroundFormats().end()) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005236 ALOGW("%s() format 0x%X is not a known surround format", __func__, audioFormat);
jiabin81772902018-04-02 17:52:27 -07005237 return BAD_VALUE;
5238 }
5239
Mikhail Naganov100f0122018-11-29 11:22:16 -08005240 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND) !=
5241 AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005242 ALOGW("%s() not in manual mode for surround sound format selection", __func__);
jiabin81772902018-04-02 17:52:27 -07005243 return INVALID_OPERATION;
5244 }
5245
Mikhail Naganov100f0122018-11-29 11:22:16 -08005246 if ((mManualSurroundFormats.count(audioFormat) != 0) == enabled) {
jiabin81772902018-04-02 17:52:27 -07005247 return NO_ERROR;
5248 }
5249
Mikhail Naganov100f0122018-11-29 11:22:16 -08005250 std::unordered_set<audio_format_t> surroundFormatsBackup(mManualSurroundFormats);
jiabin81772902018-04-02 17:52:27 -07005251 if (enabled) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005252 mManualSurroundFormats.insert(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07005253 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005254 mManualSurroundFormats.insert(subFormat);
jiabin81772902018-04-02 17:52:27 -07005255 }
5256 } else {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005257 mManualSurroundFormats.erase(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07005258 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005259 mManualSurroundFormats.erase(subFormat);
jiabin81772902018-04-02 17:52:27 -07005260 }
5261 }
5262
5263 sp<SwAudioOutputDescriptor> outputDesc;
5264 bool profileUpdated = false;
jiabin9a3361e2019-10-01 09:38:30 -07005265 DeviceVector hdmiOutputDevices = mAvailableOutputDevices.getDevicesFromType(
5266 AUDIO_DEVICE_OUT_HDMI);
jiabin81772902018-04-02 17:52:27 -07005267 for (size_t i = 0; i < hdmiOutputDevices.size(); i++) {
5268 // Simulate reconnection to update enabled surround sound formats.
jiabince9f20e2019-09-12 16:29:15 -07005269 String8 address = String8(hdmiOutputDevices[i]->address().c_str());
jiabin5740f082019-08-19 15:08:30 -07005270 std::string name = hdmiOutputDevices[i]->getName();
jiabin81772902018-04-02 17:52:27 -07005271 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
5272 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
5273 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005274 name.c_str(),
5275 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005276 if (status != NO_ERROR) {
5277 continue;
5278 }
5279 status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
5280 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
5281 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005282 name.c_str(),
5283 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005284 profileUpdated |= (status == NO_ERROR);
5285 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08005286 // FIXME: Why doing this for input HDMI devices if we don't augment their reported formats?
jiabin9a3361e2019-10-01 09:38:30 -07005287 DeviceVector hdmiInputDevices = mAvailableInputDevices.getDevicesFromType(
jiabin81772902018-04-02 17:52:27 -07005288 AUDIO_DEVICE_IN_HDMI);
5289 for (size_t i = 0; i < hdmiInputDevices.size(); i++) {
5290 // Simulate reconnection to update enabled surround sound formats.
jiabince9f20e2019-09-12 16:29:15 -07005291 String8 address = String8(hdmiInputDevices[i]->address().c_str());
jiabin5740f082019-08-19 15:08:30 -07005292 std::string name = hdmiInputDevices[i]->getName();
jiabin81772902018-04-02 17:52:27 -07005293 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
5294 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
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 if (status != NO_ERROR) {
5299 continue;
5300 }
5301 status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
5302 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
5303 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005304 name.c_str(),
5305 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005306 profileUpdated |= (status == NO_ERROR);
5307 }
5308
jiabin81772902018-04-02 17:52:27 -07005309 if (!profileUpdated) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005310 ALOGW("%s() no audio profiles updated, undoing surround formats change", __func__);
Mikhail Naganov100f0122018-11-29 11:22:16 -08005311 mManualSurroundFormats = std::move(surroundFormatsBackup);
jiabin81772902018-04-02 17:52:27 -07005312 }
5313
5314 return profileUpdated ? NO_ERROR : INVALID_OPERATION;
5315}
5316
Eric Laurent5ada82e2019-08-29 17:53:54 -07005317void AudioPolicyManager::setAppState(audio_port_handle_t portId, app_state_t state)
Svet Ganovf4ddfef2018-01-16 07:37:58 -08005318{
Eric Laurent5ada82e2019-08-29 17:53:54 -07005319 ALOGV("%s(portId:%d, state:%d)", __func__, portId, state);
Eric Laurenta9f86652018-11-28 17:23:11 -08005320 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent5ada82e2019-08-29 17:53:54 -07005321 mInputs.valueAt(i)->setAppState(portId, state);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08005322 }
5323}
5324
jiabin6012f912018-11-02 17:06:30 -07005325bool AudioPolicyManager::isHapticPlaybackSupported()
5326{
5327 for (const auto& hwModule : mHwModules) {
5328 const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
5329 for (const auto &outProfile : outputProfiles) {
5330 struct audio_port audioPort;
5331 outProfile->toAudioPort(&audioPort);
5332 for (size_t i = 0; i < audioPort.num_channel_masks; i++) {
5333 if (audioPort.channel_masks[i] & AUDIO_CHANNEL_HAPTIC_ALL) {
5334 return true;
5335 }
5336 }
5337 }
5338 }
5339 return false;
5340}
5341
Carter Hsu325a8eb2022-01-19 19:56:51 +08005342bool AudioPolicyManager::isUltrasoundSupported()
5343{
5344 bool hasUltrasoundOutput = false;
5345 bool hasUltrasoundInput = false;
5346 for (const auto& hwModule : mHwModules) {
5347 const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
5348 if (!hasUltrasoundOutput) {
5349 for (const auto &outProfile : outputProfiles) {
5350 if (outProfile->getFlags() & AUDIO_OUTPUT_FLAG_ULTRASOUND) {
5351 hasUltrasoundOutput = true;
5352 break;
5353 }
5354 }
5355 }
5356
5357 const InputProfileCollection &inputProfiles = hwModule->getInputProfiles();
5358 if (!hasUltrasoundInput) {
5359 for (const auto &inputProfile : inputProfiles) {
5360 if (inputProfile->getFlags() & AUDIO_INPUT_FLAG_ULTRASOUND) {
5361 hasUltrasoundInput = true;
5362 break;
5363 }
5364 }
5365 }
5366
5367 if (hasUltrasoundOutput && hasUltrasoundInput)
5368 return true;
5369 }
5370 return false;
5371}
5372
Eric Laurent8340e672019-11-06 11:01:08 -08005373bool AudioPolicyManager::isCallScreenModeSupported()
5374{
Mikhail Naganovb0fbc1b2023-04-28 13:06:32 -07005375 return mConfig->isCallScreenModeSupported();
Eric Laurent8340e672019-11-06 11:01:08 -08005376}
5377
5378
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005379status_t AudioPolicyManager::disconnectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07005380{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005381 ALOGV("%s port Id %d", __FUNCTION__, sourceDesc->portId());
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005382 if (!sourceDesc->isConnected()) {
5383 ALOGV("%s port Id %d already disconnected", __FUNCTION__, sourceDesc->portId());
5384 return NO_ERROR;
5385 }
François Gaffieafd4cea2019-11-18 15:50:22 +01005386 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
5387 if (swOutput != 0) {
5388 status_t status = stopSource(swOutput, sourceDesc);
Eric Laurent733ce942017-12-07 12:18:25 -08005389 if (status == NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005390 swOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08005391 }
jiabinbce0c1d2020-10-05 11:20:18 -07005392 if (releaseOutput(sourceDesc->portId())) {
5393 // The output descriptor is reopened to query dynamic profiles. In that case, there is
5394 // no need to release audio patch here but just return NO_ERROR.
5395 return NO_ERROR;
5396 }
Eric Laurentd60560a2015-04-10 11:31:20 -07005397 } else {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005398 sp<HwAudioOutputDescriptor> hwOutputDesc = sourceDesc->hwOutput().promote();
Eric Laurentd60560a2015-04-10 11:31:20 -07005399 if (hwOutputDesc != 0) {
Eric Laurentd60560a2015-04-10 11:31:20 -07005400 // close Hwoutput and remove from mHwOutputs
5401 } else {
5402 ALOGW("%s source has neither SW nor HW output", __FUNCTION__);
5403 }
5404 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005405 status_t status = releaseAudioPatchInternal(sourceDesc->getPatchHandle(), 0, sourceDesc);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005406 sourceDesc->disconnect();
5407 return status;
Eric Laurentd60560a2015-04-10 11:31:20 -07005408}
5409
François Gaffiec005e562018-11-06 15:04:49 +01005410sp<SourceClientDescriptor> AudioPolicyManager::getSourceForAttributesOnOutput(
5411 audio_io_handle_t output, const audio_attributes_t &attr)
Eric Laurentd60560a2015-04-10 11:31:20 -07005412{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005413 sp<SourceClientDescriptor> source;
Eric Laurentd60560a2015-04-10 11:31:20 -07005414 for (size_t i = 0; i < mAudioSources.size(); i++) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005415 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005416 sp<SwAudioOutputDescriptor> outputDesc = sourceDesc->swOutput().promote();
François Gaffiec005e562018-11-06 15:04:49 +01005417 if (followsSameRouting(attr, sourceDesc->attributes()) &&
5418 outputDesc != 0 && outputDesc->mIoHandle == output) {
Eric Laurentd60560a2015-04-10 11:31:20 -07005419 source = sourceDesc;
5420 break;
5421 }
5422 }
5423 return source;
Eric Laurent554a2772015-04-10 11:29:24 -07005424}
5425
Eric Laurentb4f42a92022-01-17 17:37:31 +01005426bool AudioPolicyManager::canBeSpatializedInt(const audio_attributes_t *attr,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005427 const audio_config_t *config,
Andy Hung9dd1a5b2022-05-10 15:39:39 -07005428 const AudioDeviceTypeAddrVector &devices) const
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005429{
5430 // The caller can have the audio attributes criteria ignored by either passing a null ptr or
5431 // the AUDIO_ATTRIBUTES_INITIALIZER value.
Eric Laurentfa0f6742021-08-17 18:39:44 +02005432 // If attributes are specified, current policy is to only allow spatialization for media
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005433 // and game usages.
Eric Laurent39095982021-08-24 18:29:27 +02005434 if (attr != nullptr && *attr != AUDIO_ATTRIBUTES_INITIALIZER) {
5435 if (attr->usage != AUDIO_USAGE_MEDIA && attr->usage != AUDIO_USAGE_GAME) {
5436 return false;
5437 }
5438 if ((attr->flags & (AUDIO_FLAG_CONTENT_SPATIALIZED | AUDIO_FLAG_NEVER_SPATIALIZE)) != 0) {
5439 return false;
5440 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005441 }
5442
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005443 sp<IOProfile> profile =
Eric Laurent39095982021-08-24 18:29:27 +02005444 getSpatializerOutputProfile(config, devices);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005445 if (profile == nullptr) {
5446 return false;
5447 }
5448
5449 // The caller can have the audio config criteria ignored by either passing a null ptr or
5450 // the AUDIO_CONFIG_INITIALIZER value.
Eric Laurentfa0f6742021-08-17 18:39:44 +02005451 // If an audio config is specified, current policy is to only allow spatialization for
Eric Laurent39095982021-08-24 18:29:27 +02005452 // some positional channel masks.
Eric Laurent39095982021-08-24 18:29:27 +02005453
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005454 if (config != nullptr && *config != AUDIO_CONFIG_INITIALIZER) {
Andy Hung9dd1a5b2022-05-10 15:39:39 -07005455 if (!audio_is_channel_mask_spatialized(config->channel_mask)) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005456 return false;
5457 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005458 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005459 return true;
5460}
5461
5462void AudioPolicyManager::checkVirtualizerClientRoutes() {
5463 std::set<audio_stream_type_t> streamsToInvalidate;
5464 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent39095982021-08-24 18:29:27 +02005465 const sp<SwAudioOutputDescriptor>& desc = mOutputs[i];
5466 for (const sp<TrackClientDescriptor>& client : desc->getClientIterable()) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005467 audio_attributes_t attr = client->attributes();
5468 DeviceVector devices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false);
5469 AudioDeviceTypeAddrVector devicesTypeAddress = devices.toTypeAddrVector();
5470 audio_config_base_t clientConfig = client->config();
5471 audio_config_t config = audio_config_initializer(&clientConfig);
Eric Laurent39095982021-08-24 18:29:27 +02005472 if (desc != mSpatializerOutput
Andy Hung9dd1a5b2022-05-10 15:39:39 -07005473 && canBeSpatializedInt(&attr, &config, devicesTypeAddress)) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005474 streamsToInvalidate.insert(client->stream());
5475 }
5476 }
5477 }
5478
5479 for (audio_stream_type_t stream : streamsToInvalidate) {
5480 mpClientInterface->invalidateStream(stream);
5481 }
5482}
5483
Eric Laurente191d1b2022-04-15 11:59:25 +02005484
5485bool AudioPolicyManager::isOutputOnlyAvailableRouteToSomeDevice(
5486 const sp<SwAudioOutputDescriptor>& outputDesc) {
5487 if (outputDesc->isDuplicated()) {
5488 return false;
5489 }
5490 DeviceVector devices = outputDesc->supportedDevices();
5491 for (size_t i = 0; i < mOutputs.size(); i++) {
5492 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
5493 if (desc == outputDesc || desc->isDuplicated()) {
5494 continue;
5495 }
5496 DeviceVector sharedDevices = desc->filterSupportedDevices(devices);
5497 if (!sharedDevices.isEmpty()
5498 && (desc->devicesSupportEncodedFormats(sharedDevices.types())
5499 == outputDesc->devicesSupportEncodedFormats(sharedDevices.types()))) {
5500 return false;
5501 }
5502 }
5503 return true;
5504}
5505
5506
Eric Laurentfa0f6742021-08-17 18:39:44 +02005507status_t AudioPolicyManager::getSpatializerOutput(const audio_config_base_t *mixerConfig,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005508 const audio_attributes_t *attr,
5509 audio_io_handle_t *output) {
5510 *output = AUDIO_IO_HANDLE_NONE;
5511
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005512 DeviceVector devices = mEngine->getOutputDevicesForAttributes(*attr, nullptr, false);
5513 AudioDeviceTypeAddrVector devicesTypeAddress = devices.toTypeAddrVector();
5514 audio_config_t *configPtr = nullptr;
5515 audio_config_t config;
5516 if (mixerConfig != nullptr) {
5517 config = audio_config_initializer(mixerConfig);
5518 configPtr = &config;
5519 }
Andy Hung9dd1a5b2022-05-10 15:39:39 -07005520 if (!canBeSpatializedInt(attr, configPtr, devicesTypeAddress)) {
Eric Laurente191d1b2022-04-15 11:59:25 +02005521 ALOGV("%s provided attributes or mixer config cannot be spatialized", __func__);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005522 return BAD_VALUE;
5523 }
5524
5525 sp<IOProfile> profile =
Eric Laurent39095982021-08-24 18:29:27 +02005526 getSpatializerOutputProfile(configPtr, devicesTypeAddress);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005527 if (profile == nullptr) {
Eric Laurente191d1b2022-04-15 11:59:25 +02005528 ALOGV("%s no suitable output profile for provided attributes or mixer config", __func__);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005529 return BAD_VALUE;
5530 }
5531
Eric Laurente191d1b2022-04-15 11:59:25 +02005532 std::vector<sp<SwAudioOutputDescriptor>> spatializerOutputs;
Eric Laurent39095982021-08-24 18:29:27 +02005533 for (size_t i = 0; i < mOutputs.size(); i++) {
5534 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente191d1b2022-04-15 11:59:25 +02005535 if (!desc->isDuplicated()
5536 && (desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0) {
5537 spatializerOutputs.push_back(desc);
5538 ALOGV("%s adding opened spatializer Output %d", __func__, desc->mIoHandle);
Eric Laurent39095982021-08-24 18:29:27 +02005539 }
5540 }
Eric Laurente191d1b2022-04-15 11:59:25 +02005541 mSpatializerOutput.clear();
5542 bool outputsChanged = false;
5543 for (const auto& desc : spatializerOutputs) {
5544 if (desc->mProfile == profile
5545 && (configPtr == nullptr
5546 || configPtr->channel_mask == desc->mMixerChannelMask)) {
5547 mSpatializerOutput = desc;
5548 ALOGV("%s reusing current spatializer output %d", __func__, desc->mIoHandle);
5549 } else {
5550 ALOGV("%s closing spatializerOutput output %d to match channel mask %#x"
5551 " and devices %s", __func__, desc->mIoHandle,
5552 configPtr != nullptr ? configPtr->channel_mask : 0,
5553 devices.toString().c_str());
5554 closeOutput(desc->mIoHandle);
5555 outputsChanged = true;
5556 }
Eric Laurent39095982021-08-24 18:29:27 +02005557 }
5558
Eric Laurente191d1b2022-04-15 11:59:25 +02005559 if (mSpatializerOutput == nullptr) {
Eric Laurentb4f42a92022-01-17 17:37:31 +01005560 sp<SwAudioOutputDescriptor> desc =
5561 openOutputWithProfileAndDevice(profile, devices, mixerConfig);
Eric Laurente191d1b2022-04-15 11:59:25 +02005562 if (desc != nullptr) {
5563 mSpatializerOutput = desc;
5564 outputsChanged = true;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005565 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005566 }
5567
5568 checkVirtualizerClientRoutes();
5569
Eric Laurente191d1b2022-04-15 11:59:25 +02005570 if (outputsChanged) {
5571 mPreviousOutputs = mOutputs;
5572 mpClientInterface->onAudioPortListUpdate();
5573 }
5574
5575 if (mSpatializerOutput == nullptr) {
5576 ALOGV("%s could not open spatializer output with requested config", __func__);
5577 return BAD_VALUE;
5578 }
Eric Laurent39095982021-08-24 18:29:27 +02005579 *output = mSpatializerOutput->mIoHandle;
Eric Laurente191d1b2022-04-15 11:59:25 +02005580 ALOGV("%s returning new spatializer output %d", __func__, *output);
5581 return OK;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005582}
5583
Eric Laurentfa0f6742021-08-17 18:39:44 +02005584status_t AudioPolicyManager::releaseSpatializerOutput(audio_io_handle_t output) {
5585 if (mSpatializerOutput == nullptr) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005586 return INVALID_OPERATION;
5587 }
Eric Laurentfa0f6742021-08-17 18:39:44 +02005588 if (mSpatializerOutput->mIoHandle != output) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005589 return BAD_VALUE;
5590 }
Eric Laurent39095982021-08-24 18:29:27 +02005591
Eric Laurente191d1b2022-04-15 11:59:25 +02005592 if (!isOutputOnlyAvailableRouteToSomeDevice(mSpatializerOutput)) {
5593 ALOGV("%s closing spatializer output %d", __func__, mSpatializerOutput->mIoHandle);
5594 closeOutput(mSpatializerOutput->mIoHandle);
5595 //from now on mSpatializerOutput is null
5596 checkVirtualizerClientRoutes();
5597 }
Eric Laurent39095982021-08-24 18:29:27 +02005598
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005599 return NO_ERROR;
5600}
5601
Eric Laurente552edb2014-03-10 17:42:56 -07005602// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07005603// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07005604// ----------------------------------------------------------------------------
Eric Laurent6a94d692014-05-20 11:18:06 -07005605uint32_t AudioPolicyManager::nextAudioPortGeneration()
5606{
Mikhail Naganov2773dd72017-12-08 10:12:11 -08005607 return mAudioPortGeneration++;
Eric Laurent6a94d692014-05-20 11:18:06 -07005608}
5609
Mikhail Naganovb0fbc1b2023-04-28 13:06:32 -07005610AudioPolicyManager::AudioPolicyManager(const sp<const AudioPolicyConfig>& config,
Mikhail Naganovabb04782023-05-02 13:56:01 -07005611 EngineInstance&& engine,
Mikhail Naganovb0fbc1b2023-04-28 13:06:32 -07005612 AudioPolicyClientInterface *clientInterface)
Eric Laurente552edb2014-03-10 17:42:56 -07005613 :
Andy Hung4ef19fa2018-05-15 19:35:29 -07005614 mUidCached(AID_AUDIOSERVER), // no need to call getuid(), there's only one of us running.
Mikhail Naganovb0fbc1b2023-04-28 13:06:32 -07005615 mConfig(config),
Mikhail Naganovabb04782023-05-02 13:56:01 -07005616 mEngine(std::move(engine)),
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005617 mpClientInterface(clientInterface),
Eric Laurente552edb2014-03-10 17:42:56 -07005618 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
Eric Laurent3a4311c2014-03-17 12:00:47 -07005619 mA2dpSuspended(false),
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005620 mAudioPortGeneration(1),
5621 mBeaconMuteRefCount(0),
5622 mBeaconPlayingRefCount(0),
Eric Laurent9459fb02015-08-12 18:36:32 -07005623 mBeaconMuted(false),
Andy Hung2ddee192015-12-18 17:34:44 -08005624 mTtsOutputAvailable(false),
Eric Laurent36829f92017-04-07 19:04:42 -07005625 mMasterMono(false),
Eric Laurent4eb58f12018-12-07 16:41:02 -08005626 mMusicEffectOutput(AUDIO_IO_HANDLE_NONE)
Eric Laurente552edb2014-03-10 17:42:56 -07005627{
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005628}
François Gaffied1ab2bd2015-12-02 18:20:06 +01005629
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005630status_t AudioPolicyManager::initialize() {
Mikhail Naganovabb04782023-05-02 13:56:01 -07005631 if (mEngine == nullptr) {
5632 return NO_INIT;
François Gaffie2110e042015-03-24 08:41:51 +01005633 }
5634 mEngine->setObserver(this);
5635 status_t status = mEngine->initCheck();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005636 if (status != NO_ERROR) {
5637 LOG_FATAL("Policy engine not initialized(err=%d)", status);
5638 return status;
5639 }
François Gaffie2110e042015-03-24 08:41:51 +01005640
jiabin76e829d2023-04-04 21:02:36 +00005641 // The actual device selection cache will be updated when calling `updateDevicesAndOutputs`
5642 // at the end of this function.
5643 mEngine->initializeDeviceSelectionCache();
Eric Laurent1d69c872021-01-11 18:53:01 +01005644 mCommunnicationStrategy = mEngine->getProductStrategyForAttributes(
5645 mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL));
5646
Mikhail Naganovb0fbc1b2023-04-28 13:06:32 -07005647 // after parsing the config, mConfig contain all known devices;
Eric Laurente552edb2014-03-10 17:42:56 -07005648 // open all output streams needed to access attached devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07005649 onNewAudioModulesAvailableInt(nullptr /*newDevices*/);
François Gaffie11d30102018-11-02 16:09:09 +01005650
Eric Laurent3a4311c2014-03-17 12:00:47 -07005651 // make sure default device is reachable
Mikhail Naganovb0fbc1b2023-04-28 13:06:32 -07005652 if (const auto defaultOutputDevice = mConfig->getDefaultOutputDevice();
5653 defaultOutputDevice == nullptr ||
5654 !mAvailableOutputDevices.contains(defaultOutputDevice)) {
5655 ALOGE_IF(defaultOutputDevice != nullptr, "Default device %s is unreachable",
5656 defaultOutputDevice->toString().c_str());
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005657 status = NO_INIT;
Eric Laurent3a4311c2014-03-17 12:00:47 -07005658 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02005659 ALOGW_IF(mPrimaryOutput == nullptr, "The policy configuration does not declare a primary output");
Eric Laurente552edb2014-03-10 17:42:56 -07005660
Tomoharu Kasahara71c90912018-10-31 09:10:12 +09005661 // Silence ALOGV statements
5662 property_set("log.tag." LOG_TAG, "D");
5663
Eric Laurente552edb2014-03-10 17:42:56 -07005664 updateDevicesAndOutputs();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005665 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07005666}
5667
Eric Laurente0720872014-03-11 09:30:41 -07005668AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07005669{
Eric Laurente552edb2014-03-10 17:42:56 -07005670 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08005671 mOutputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07005672 }
5673 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08005674 mInputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07005675 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07005676 mAvailableOutputDevices.clear();
5677 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07005678 mOutputs.clear();
5679 mInputs.clear();
5680 mHwModules.clear();
Mikhail Naganov100f0122018-11-29 11:22:16 -08005681 mManualSurroundFormats.clear();
Mikhail Naganovb0fbc1b2023-04-28 13:06:32 -07005682 mConfig.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07005683}
5684
Eric Laurente0720872014-03-11 09:30:41 -07005685status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07005686{
Eric Laurent87ffa392015-05-22 10:32:38 -07005687 return hasPrimaryOutput() ? NO_ERROR : NO_INIT;
Eric Laurente552edb2014-03-10 17:42:56 -07005688}
5689
Eric Laurente552edb2014-03-10 17:42:56 -07005690// ---
5691
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005692void AudioPolicyManager::onNewAudioModulesAvailable()
5693{
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07005694 DeviceVector newDevices;
5695 onNewAudioModulesAvailableInt(&newDevices);
5696 if (!newDevices.empty()) {
5697 nextAudioPortGeneration();
5698 mpClientInterface->onAudioPortListUpdate();
5699 }
5700}
5701
5702void AudioPolicyManager::onNewAudioModulesAvailableInt(DeviceVector *newDevices)
5703{
Mikhail Naganovb0fbc1b2023-04-28 13:06:32 -07005704 for (const auto& hwModule : mConfig->getHwModules()) {
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005705 if (std::find(mHwModules.begin(), mHwModules.end(), hwModule) != mHwModules.end()) {
5706 continue;
5707 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005708 if (hwModule->getHandle() == AUDIO_MODULE_HANDLE_NONE) {
Mikhail Naganov1fba38c2023-05-03 17:45:36 -07005709 if (audio_module_handle_t handle = mpClientInterface->loadHwModule(hwModule->getName());
5710 handle != AUDIO_MODULE_HANDLE_NONE) {
5711 hwModule->setHandle(handle);
5712 } else {
5713 ALOGW("could not load HW module %s", hwModule->getName());
5714 continue;
5715 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005716 }
5717 mHwModules.push_back(hwModule);
Dean Wheatley12a87132021-04-16 10:08:49 +10005718 // open all output streams needed to access attached devices.
5719 // direct outputs are closed immediately after checking the availability of attached devices
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005720 // This also validates mAvailableOutputDevices list
5721 for (const auto& outProfile : hwModule->getOutputProfiles()) {
5722 if (!outProfile->canOpenNewIo()) {
5723 ALOGE("Invalid Output profile max open count %u for profile %s",
5724 outProfile->maxOpenCount, outProfile->getTagName().c_str());
5725 continue;
5726 }
5727 if (!outProfile->hasSupportedDevices()) {
5728 ALOGW("Output profile contains no device on module %s", hwModule->getName());
5729 continue;
5730 }
Carter Hsu1a3364a2022-01-21 15:32:56 +08005731 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_TTS) != 0 ||
5732 (outProfile->getFlags() & AUDIO_OUTPUT_FLAG_ULTRASOUND) != 0) {
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005733 mTtsOutputAvailable = true;
5734 }
5735
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005736 const DeviceVector &supportedDevices = outProfile->getSupportedDevices();
Mikhail Naganovb0fbc1b2023-04-28 13:06:32 -07005737 DeviceVector availProfileDevices = supportedDevices.filter(mConfig->getOutputDevices());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005738 sp<DeviceDescriptor> supportedDevice = 0;
Mikhail Naganovb0fbc1b2023-04-28 13:06:32 -07005739 if (supportedDevices.contains(mConfig->getDefaultOutputDevice())) {
5740 supportedDevice = mConfig->getDefaultOutputDevice();
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005741 } else {
5742 // choose first device present in profile's SupportedDevices also part of
5743 // mAvailableOutputDevices.
5744 if (availProfileDevices.isEmpty()) {
5745 continue;
5746 }
5747 supportedDevice = availProfileDevices.itemAt(0);
5748 }
Mikhail Naganovb0fbc1b2023-04-28 13:06:32 -07005749 if (!mConfig->getOutputDevices().contains(supportedDevice)) {
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005750 continue;
5751 }
5752 sp<SwAudioOutputDescriptor> outputDesc = new SwAudioOutputDescriptor(outProfile,
5753 mpClientInterface);
5754 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentf1f22e72021-07-13 14:04:14 +02005755 status_t status = outputDesc->open(nullptr /* halConfig */, nullptr /* mixerConfig */,
5756 DeviceVector(supportedDevice),
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005757 AUDIO_STREAM_DEFAULT,
5758 AUDIO_OUTPUT_FLAG_NONE, &output);
5759 if (status != NO_ERROR) {
5760 ALOGW("Cannot open output stream for devices %s on hw module %s",
5761 supportedDevice->toString().c_str(), hwModule->getName());
5762 continue;
5763 }
5764 for (const auto &device : availProfileDevices) {
5765 // give a valid ID to an attached device once confirmed it is reachable
5766 if (!device->isAttached()) {
5767 device->attach(hwModule);
5768 mAvailableOutputDevices.add(device);
jiabin1c4794b2020-05-05 10:08:05 -07005769 device->setEncapsulationInfoFromHal(mpClientInterface);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07005770 if (newDevices) newDevices->add(device);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005771 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
5772 }
5773 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02005774 if (mPrimaryOutput == nullptr &&
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005775 outProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
5776 mPrimaryOutput = outputDesc;
5777 }
Eric Laurent39095982021-08-24 18:29:27 +02005778 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
Eric Laurentc529cf62020-04-17 18:19:10 -07005779 outputDesc->close();
5780 } else {
5781 addOutput(output, outputDesc);
5782 setOutputDevices(outputDesc,
5783 DeviceVector(supportedDevice),
5784 true,
5785 0,
5786 NULL);
5787 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005788 }
5789 // open input streams needed to access attached devices to validate
5790 // mAvailableInputDevices list
5791 for (const auto& inProfile : hwModule->getInputProfiles()) {
5792 if (!inProfile->canOpenNewIo()) {
5793 ALOGE("Invalid Input profile max open count %u for profile %s",
5794 inProfile->maxOpenCount, inProfile->getTagName().c_str());
5795 continue;
5796 }
5797 if (!inProfile->hasSupportedDevices()) {
5798 ALOGW("Input profile contains no device on module %s", hwModule->getName());
5799 continue;
5800 }
5801 // chose first device present in profile's SupportedDevices also part of
5802 // available input devices
5803 const DeviceVector &supportedDevices = inProfile->getSupportedDevices();
Mikhail Naganovb0fbc1b2023-04-28 13:06:32 -07005804 DeviceVector availProfileDevices = supportedDevices.filter(mConfig->getInputDevices());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005805 if (availProfileDevices.isEmpty()) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01005806 ALOGV("%s: Input device list is empty! for profile %s",
5807 __func__, inProfile->getTagName().c_str());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005808 continue;
5809 }
5810 sp<AudioInputDescriptor> inputDesc =
5811 new AudioInputDescriptor(inProfile, mpClientInterface);
5812
5813 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
5814 status_t status = inputDesc->open(nullptr,
5815 availProfileDevices.itemAt(0),
5816 AUDIO_SOURCE_MIC,
5817 AUDIO_INPUT_FLAG_NONE,
5818 &input);
5819 if (status != NO_ERROR) {
5820 ALOGW("Cannot open input stream for device %s on hw module %s",
5821 availProfileDevices.toString().c_str(),
5822 hwModule->getName());
5823 continue;
5824 }
5825 for (const auto &device : availProfileDevices) {
5826 // give a valid ID to an attached device once confirmed it is reachable
5827 if (!device->isAttached()) {
5828 device->attach(hwModule);
5829 device->importAudioPortAndPickAudioProfile(inProfile, true);
5830 mAvailableInputDevices.add(device);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07005831 if (newDevices) newDevices->add(device);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005832 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
5833 }
5834 }
5835 inputDesc->close();
5836 }
5837 }
Eric Laurente191d1b2022-04-15 11:59:25 +02005838
5839 // Check if spatializer outputs can be closed until used.
5840 // mOutputs vector never contains duplicated outputs at this point.
5841 std::vector<audio_io_handle_t> outputsClosed;
5842 for (size_t i = 0; i < mOutputs.size(); i++) {
5843 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
5844 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0
5845 && !isOutputOnlyAvailableRouteToSomeDevice(desc)) {
5846 outputsClosed.push_back(desc->mIoHandle);
5847 desc->close();
5848 }
5849 }
5850 for (auto output : outputsClosed) {
5851 removeOutput(output);
5852 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005853}
5854
Eric Laurent98e38192018-02-15 18:31:53 -08005855void AudioPolicyManager::addOutput(audio_io_handle_t output,
5856 const sp<SwAudioOutputDescriptor>& outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07005857{
Eric Laurent1c333e22014-05-20 10:48:17 -07005858 mOutputs.add(output, outputDesc);
jiabin9a3361e2019-10-01 09:38:30 -07005859 applyStreamVolumes(outputDesc, DeviceTypeSet(), 0 /* delayMs */, true /* force */);
Andy Hung2ddee192015-12-18 17:34:44 -08005860 updateMono(output); // update mono status when adding to output list
Eric Laurent36829f92017-04-07 19:04:42 -07005861 selectOutputForMusicEffects();
Eric Laurent6a94d692014-05-20 11:18:06 -07005862 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07005863}
5864
François Gaffie53615e22015-03-19 09:24:12 +01005865void AudioPolicyManager::removeOutput(audio_io_handle_t output)
5866{
Francois Gaffiebce7cd42020-10-14 16:13:20 +02005867 if (mPrimaryOutput != 0 && mPrimaryOutput == mOutputs.valueFor(output)) {
5868 ALOGV("%s: removing primary output", __func__);
5869 mPrimaryOutput = nullptr;
5870 }
François Gaffie53615e22015-03-19 09:24:12 +01005871 mOutputs.removeItem(output);
Eric Laurent36829f92017-04-07 19:04:42 -07005872 selectOutputForMusicEffects();
François Gaffie53615e22015-03-19 09:24:12 +01005873}
5874
Eric Laurent98e38192018-02-15 18:31:53 -08005875void AudioPolicyManager::addInput(audio_io_handle_t input,
5876 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07005877{
Eric Laurent1c333e22014-05-20 10:48:17 -07005878 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07005879 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07005880}
Eric Laurente552edb2014-03-10 17:42:56 -07005881
François Gaffie11d30102018-11-02 16:09:09 +01005882status_t AudioPolicyManager::checkOutputsForDevice(const sp<DeviceDescriptor>& device,
François Gaffie53615e22015-03-19 09:24:12 +01005883 audio_policy_dev_state_t state,
François Gaffie11d30102018-11-02 16:09:09 +01005884 SortedVector<audio_io_handle_t>& outputs)
Eric Laurente552edb2014-03-10 17:42:56 -07005885{
François Gaffie11d30102018-11-02 16:09:09 +01005886 audio_devices_t deviceType = device->type();
jiabince9f20e2019-09-12 16:29:15 -07005887 const String8 &address = String8(device->address().c_str());
Eric Laurentc75307b2015-03-17 15:29:32 -07005888 sp<SwAudioOutputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07005889
François Gaffie11d30102018-11-02 16:09:09 +01005890 if (audio_device_is_digital(deviceType)) {
Eric Laurentcc750d32015-06-25 11:48:20 -07005891 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01005892 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07005893 }
Eric Laurente552edb2014-03-10 17:42:56 -07005894
Eric Laurent3b73df72014-03-11 09:06:29 -07005895 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
jiabinb4fed192020-09-22 14:45:40 -07005896 // first call getAudioPort to get the supported attributes from the HAL
5897 struct audio_port_v7 port = {};
5898 device->toAudioPort(&port);
5899 status_t status = mpClientInterface->getAudioPort(&port);
5900 if (status == NO_ERROR) {
5901 device->importAudioPort(port);
5902 }
5903
5904 // then list already open outputs that can be routed to this device
Eric Laurente552edb2014-03-10 17:42:56 -07005905 for (size_t i = 0; i < mOutputs.size(); i++) {
5906 desc = mOutputs.valueAt(i);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005907 if (!desc->isDuplicated() && desc->supportsDevice(device)
jiabin9a3361e2019-10-01 09:38:30 -07005908 && desc->devicesSupportEncodedFormats({deviceType})) {
François Gaffie11d30102018-11-02 16:09:09 +01005909 ALOGV("checkOutputsForDevice(): adding opened output %d on device %s",
5910 mOutputs.keyAt(i), device->toString().c_str());
5911 outputs.add(mOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07005912 }
5913 }
5914 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07005915 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08005916 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005917 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
5918 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
François Gaffie11d30102018-11-02 16:09:09 +01005919 if (profile->supportsDevice(device)) {
5920 profiles.add(profile);
5921 ALOGV("checkOutputsForDevice(): adding profile %zu from module %s",
5922 j, hwModule->getName());
Eric Laurente552edb2014-03-10 17:42:56 -07005923 }
5924 }
5925 }
5926
Eric Laurent7b279bb2015-12-14 10:18:23 -08005927 ALOGV(" found %zu profiles, %zu outputs", profiles.size(), outputs.size());
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005928
Eric Laurente552edb2014-03-10 17:42:56 -07005929 if (profiles.isEmpty() && outputs.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01005930 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07005931 return BAD_VALUE;
5932 }
5933
5934 // open outputs for matching profiles if needed. Direct outputs are also opened to
5935 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
5936 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07005937 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07005938
5939 // nothing to do if one output is already opened for this profile
5940 size_t j;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005941 for (j = 0; j < outputs.size(); j++) {
5942 desc = mOutputs.valueFor(outputs.itemAt(j));
Eric Laurente552edb2014-03-10 17:42:56 -07005943 if (!desc->isDuplicated() && desc->mProfile == profile) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07005944 // matching profile: save the sample rates, format and channel masks supported
5945 // by the profile in our device descriptor
François Gaffie11d30102018-11-02 16:09:09 +01005946 if (audio_device_is_digital(deviceType)) {
jiabin4ef93452019-09-10 14:29:54 -07005947 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07005948 }
Eric Laurente552edb2014-03-10 17:42:56 -07005949 break;
5950 }
5951 }
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005952 if (j != outputs.size()) {
Eric Laurente552edb2014-03-10 17:42:56 -07005953 continue;
5954 }
5955
Eric Laurent3974e3b2017-12-07 17:58:43 -08005956 if (!profile->canOpenNewIo()) {
5957 ALOGW("Max Output number %u already opened for this profile %s",
5958 profile->maxOpenCount, profile->getTagName().c_str());
5959 continue;
5960 }
5961
Eric Laurent83efe1c2017-07-09 16:51:08 -07005962 ALOGV("opening output for device %08x with params %s profile %p name %s",
jiabin5740f082019-08-19 15:08:30 -07005963 deviceType, address.string(), profile.get(), profile->getName().c_str());
jiabinbce0c1d2020-10-05 11:20:18 -07005964 desc = openOutputWithProfileAndDevice(profile, DeviceVector(device));
5965 audio_io_handle_t output = desc == nullptr ? AUDIO_IO_HANDLE_NONE : desc->mIoHandle;
Eric Laurentcf2c0212014-07-25 16:20:43 -07005966 if (output == AUDIO_IO_HANDLE_NONE) {
François Gaffie11d30102018-11-02 16:09:09 +01005967 ALOGW("checkOutputsForDevice() could not open output for device %x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07005968 profiles.removeAt(profile_index);
5969 profile_index--;
5970 } else {
5971 outputs.add(output);
Paul McLean9080a4c2015-06-18 08:24:02 -07005972 // Load digital format info only for digital devices
François Gaffie11d30102018-11-02 16:09:09 +01005973 if (audio_device_is_digital(deviceType)) {
jiabinbce0c1d2020-10-05 11:20:18 -07005974 // TODO: when getAudioPort is ready, it may not be needed to import the audio
5975 // port but just pick audio profile
jiabin4ef93452019-09-10 14:29:54 -07005976 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07005977 }
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07005978
François Gaffie11d30102018-11-02 16:09:09 +01005979 if (device_distinguishes_on_address(deviceType)) {
5980 ALOGV("checkOutputsForDevice(): setOutputDevices %s",
5981 device->toString().c_str());
5982 setOutputDevices(desc, DeviceVector(device), true/*force*/, 0/*delay*/,
5983 NULL/*patch handle*/);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005984 }
Eric Laurente552edb2014-03-10 17:42:56 -07005985 ALOGV("checkOutputsForDevice(): adding output %d", output);
5986 }
5987 }
5988
5989 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01005990 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07005991 return BAD_VALUE;
5992 }
Eric Laurentd4692962014-05-05 18:13:44 -07005993 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07005994 // check if one opened output is not needed any more after disconnecting one device
5995 for (size_t i = 0; i < mOutputs.size(); i++) {
5996 desc = mOutputs.valueAt(i);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005997 if (!desc->isDuplicated()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08005998 // exact match on device
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005999 if (device_distinguishes_on_address(deviceType) && desc->supportsDevice(device)
Francois Gaffiec7d4c222021-12-02 11:12:52 +01006000 && desc->containsSingleDeviceSupportingEncodedFormats(device)) {
François Gaffie11d30102018-11-02 16:09:09 +01006001 outputs.add(mOutputs.keyAt(i));
Francois Gaffie716e1432019-01-14 16:58:59 +01006002 } else if (!mAvailableOutputDevices.containsAtLeastOne(desc->supportedDevices())) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006003 ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
6004 mOutputs.keyAt(i));
6005 outputs.add(mOutputs.keyAt(i));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006006 }
Eric Laurente552edb2014-03-10 17:42:56 -07006007 }
6008 }
Eric Laurentd4692962014-05-05 18:13:44 -07006009 // Clear any profiles associated with the disconnected device.
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006010 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006011 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
6012 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
jiabinbce0c1d2020-10-05 11:20:18 -07006013 if (!profile->supportsDevice(device)) {
6014 continue;
6015 }
6016 ALOGV("checkOutputsForDevice(): "
6017 "clearing direct output profile %zu on module %s",
6018 j, hwModule->getName());
6019 profile->clearAudioProfiles();
6020 if (!profile->hasDynamicAudioProfile()) {
6021 continue;
6022 }
6023 // When a device is disconnected, if there is an IOProfile that contains dynamic
6024 // profiles and supports the disconnected device, call getAudioPort to repopulate
6025 // the capabilities of the devices that is supported by the IOProfile.
6026 for (const auto& supportedDevice : profile->getSupportedDevices()) {
6027 if (supportedDevice == device ||
6028 !mAvailableOutputDevices.contains(supportedDevice)) {
6029 continue;
6030 }
6031 struct audio_port_v7 port;
6032 supportedDevice->toAudioPort(&port);
6033 status_t status = mpClientInterface->getAudioPort(&port);
6034 if (status == NO_ERROR) {
6035 supportedDevice->importAudioPort(port);
6036 }
Eric Laurente552edb2014-03-10 17:42:56 -07006037 }
6038 }
6039 }
6040 }
6041 return NO_ERROR;
6042}
6043
François Gaffie11d30102018-11-02 16:09:09 +01006044status_t AudioPolicyManager::checkInputsForDevice(const sp<DeviceDescriptor>& device,
Eric Laurent0dd51852019-04-19 18:18:58 -07006045 audio_policy_dev_state_t state)
Eric Laurentd4692962014-05-05 18:13:44 -07006046{
Eric Laurent1f2f2232014-06-02 12:01:23 -07006047 sp<AudioInputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07006048
François Gaffie11d30102018-11-02 16:09:09 +01006049 if (audio_device_is_digital(device->type())) {
Eric Laurentcc750d32015-06-25 11:48:20 -07006050 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01006051 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07006052 }
6053
Eric Laurentd4692962014-05-05 18:13:44 -07006054 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
jiabinbf5f4262023-04-12 21:48:34 +00006055 // first call getAudioPort to get the supported attributes from the HAL
6056 struct audio_port_v7 port = {};
6057 device->toAudioPort(&port);
6058 status_t status = mpClientInterface->getAudioPort(&port);
6059 if (status == NO_ERROR) {
6060 device->importAudioPort(port);
6061 }
6062
Eric Laurent0dd51852019-04-19 18:18:58 -07006063 // look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07006064 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006065 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07006066 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006067 profile_index < hwModule->getInputProfiles().size();
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006068 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006069 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Eric Laurent275e8e92014-11-30 15:14:47 -08006070
François Gaffie11d30102018-11-02 16:09:09 +01006071 if (profile->supportsDevice(device)) {
6072 profiles.add(profile);
6073 ALOGV("checkInputsForDevice(): adding profile %zu from module %s",
6074 profile_index, hwModule->getName());
Eric Laurentd4692962014-05-05 18:13:44 -07006075 }
6076 }
6077 }
6078
Eric Laurent0dd51852019-04-19 18:18:58 -07006079 if (profiles.isEmpty()) {
6080 ALOGW("%s: No input profile available for device %s",
6081 __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07006082 return BAD_VALUE;
6083 }
6084
6085 // open inputs for matching profiles if needed. Direct inputs are also opened to
6086 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
6087 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
6088
Eric Laurent1c333e22014-05-20 10:48:17 -07006089 sp<IOProfile> profile = profiles[profile_index];
Eric Laurent3974e3b2017-12-07 17:58:43 -08006090
Eric Laurentd4692962014-05-05 18:13:44 -07006091 // nothing to do if one input is already opened for this profile
6092 size_t input_index;
6093 for (input_index = 0; input_index < mInputs.size(); input_index++) {
6094 desc = mInputs.valueAt(input_index);
6095 if (desc->mProfile == profile) {
François Gaffie11d30102018-11-02 16:09:09 +01006096 if (audio_device_is_digital(device->type())) {
jiabin4ef93452019-09-10 14:29:54 -07006097 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006098 }
Eric Laurentd4692962014-05-05 18:13:44 -07006099 break;
6100 }
6101 }
6102 if (input_index != mInputs.size()) {
6103 continue;
6104 }
6105
Eric Laurent3974e3b2017-12-07 17:58:43 -08006106 if (!profile->canOpenNewIo()) {
6107 ALOGW("Max Input number %u already opened for this profile %s",
6108 profile->maxOpenCount, profile->getTagName().c_str());
6109 continue;
6110 }
6111
Eric Laurentfe231122017-11-17 17:48:06 -08006112 desc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentcf2c0212014-07-25 16:20:43 -07006113 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
jiabinbf5f4262023-04-12 21:48:34 +00006114 status = desc->open(nullptr, device, AUDIO_SOURCE_MIC, AUDIO_INPUT_FLAG_NONE, &input);
Eric Laurentd4692962014-05-05 18:13:44 -07006115
Eric Laurentcf2c0212014-07-25 16:20:43 -07006116 if (status == NO_ERROR) {
jiabince9f20e2019-09-12 16:29:15 -07006117 const String8& address = String8(device->address().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07006118 if (!address.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006119 char *param = audio_device_address_to_parameter(device->type(), address);
Eric Laurentcf2c0212014-07-25 16:20:43 -07006120 mpClientInterface->setParameters(input, String8(param));
6121 free(param);
Eric Laurentd4692962014-05-05 18:13:44 -07006122 }
François Gaffie11d30102018-11-02 16:09:09 +01006123 updateAudioProfiles(device, input, profile->getAudioProfiles());
François Gaffie112b0af2015-11-19 16:13:25 +01006124 if (!profile->hasValidAudioProfile()) {
Eric Laurentd4692962014-05-05 18:13:44 -07006125 ALOGW("checkInputsForDevice() direct input missing param");
Eric Laurentfe231122017-11-17 17:48:06 -08006126 desc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07006127 input = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07006128 }
6129
Eric Laurent0dd51852019-04-19 18:18:58 -07006130 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07006131 addInput(input, desc);
6132 }
6133 } // endif input != 0
6134
Eric Laurentcf2c0212014-07-25 16:20:43 -07006135 if (input == AUDIO_IO_HANDLE_NONE) {
Pattydd807582021-11-04 21:01:03 +08006136 ALOGW("%s could not open input for device %s", __func__,
François Gaffie11d30102018-11-02 16:09:09 +01006137 device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07006138 profiles.removeAt(profile_index);
6139 profile_index--;
6140 } else {
François Gaffie11d30102018-11-02 16:09:09 +01006141 if (audio_device_is_digital(device->type())) {
jiabin4ef93452019-09-10 14:29:54 -07006142 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006143 }
Eric Laurentd4692962014-05-05 18:13:44 -07006144 ALOGV("checkInputsForDevice(): adding input %d", input);
6145 }
6146 } // end scan profiles
6147
6148 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006149 ALOGW("%s: No input available for device %s", __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07006150 return BAD_VALUE;
6151 }
6152 } else {
6153 // Disconnect
Eric Laurentd4692962014-05-05 18:13:44 -07006154 // Clear any profiles associated with the disconnected device.
Mikhail Naganovd4120142017-12-06 15:49:22 -08006155 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07006156 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006157 profile_index < hwModule->getInputProfiles().size();
Eric Laurentd4692962014-05-05 18:13:44 -07006158 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006159 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Francois Gaffie716e1432019-01-14 16:58:59 +01006160 if (profile->supportsDevice(device)) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08006161 ALOGV("checkInputsForDevice(): clearing direct input profile %zu on module %s",
6162 profile_index, hwModule->getName());
François Gaffie112b0af2015-11-19 16:13:25 +01006163 profile->clearAudioProfiles();
Eric Laurentd4692962014-05-05 18:13:44 -07006164 }
6165 }
6166 }
6167 } // end disconnect
6168
6169 return NO_ERROR;
6170}
6171
6172
Eric Laurente0720872014-03-11 09:30:41 -07006173void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07006174{
6175 ALOGV("closeOutput(%d)", output);
6176
François Gaffie1c878552018-11-22 16:53:21 +01006177 sp<SwAudioOutputDescriptor> closingOutput = mOutputs.valueFor(output);
6178 if (closingOutput == NULL) {
Eric Laurente552edb2014-03-10 17:42:56 -07006179 ALOGW("closeOutput() unknown output %d", output);
6180 return;
6181 }
Mikhail Naganov32ebca32019-03-22 15:42:52 -07006182 const bool closingOutputWasActive = closingOutput->isActive();
François Gaffie1c878552018-11-22 16:53:21 +01006183 mPolicyMixes.closeOutput(closingOutput);
Eric Laurent275e8e92014-11-30 15:14:47 -08006184
Eric Laurente552edb2014-03-10 17:42:56 -07006185 // look for duplicated outputs connected to the output being removed.
6186 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie1c878552018-11-22 16:53:21 +01006187 sp<SwAudioOutputDescriptor> dupOutput = mOutputs.valueAt(i);
6188 if (dupOutput->isDuplicated() &&
6189 (dupOutput->mOutput1 == closingOutput || dupOutput->mOutput2 == closingOutput)) {
6190 sp<SwAudioOutputDescriptor> remainingOutput =
6191 dupOutput->mOutput1 == closingOutput ? dupOutput->mOutput2 : dupOutput->mOutput1;
Eric Laurente552edb2014-03-10 17:42:56 -07006192 // As all active tracks on duplicated output will be deleted,
6193 // and as they were also referenced on the other output, the reference
6194 // count for their stream type must be adjusted accordingly on
6195 // the other output.
François Gaffie1c878552018-11-22 16:53:21 +01006196 const bool wasActive = remainingOutput->isActive();
6197 // Note: no-op on the closing output where all clients has already been set inactive
6198 dupOutput->setAllClientsInactive();
Eric Laurent733ce942017-12-07 12:18:25 -08006199 // stop() will be a no op if the output is still active but is needed in case all
6200 // active streams refcounts where cleared above
6201 if (wasActive) {
François Gaffie1c878552018-11-22 16:53:21 +01006202 remainingOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08006203 }
Eric Laurente552edb2014-03-10 17:42:56 -07006204 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
6205 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
6206
6207 mpClientInterface->closeOutput(duplicatedOutput);
François Gaffie53615e22015-03-19 09:24:12 +01006208 removeOutput(duplicatedOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07006209 }
6210 }
6211
Eric Laurent05b90f82014-08-27 15:32:29 -07006212 nextAudioPortGeneration();
6213
François Gaffie1c878552018-11-22 16:53:21 +01006214 ssize_t index = mAudioPatches.indexOfKey(closingOutput->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07006215 if (index >= 0) {
6216 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006217 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
6218 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07006219 mAudioPatches.removeItemsAt(index);
6220 mpClientInterface->onAudioPatchListUpdate();
6221 }
6222
Mikhail Naganov32ebca32019-03-22 15:42:52 -07006223 if (closingOutputWasActive) {
6224 closingOutput->stop();
6225 }
François Gaffie1c878552018-11-22 16:53:21 +01006226 closingOutput->close();
Eric Laurente552edb2014-03-10 17:42:56 -07006227
François Gaffie53615e22015-03-19 09:24:12 +01006228 removeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07006229 mPreviousOutputs = mOutputs;
Eric Laurentb4f42a92022-01-17 17:37:31 +01006230 if (closingOutput == mSpatializerOutput) {
6231 mSpatializerOutput.clear();
6232 }
Dean Wheatley3023b382018-08-09 07:42:40 +10006233
6234 // MSD patches may have been released to support a non-MSD direct output. Reset MSD patch if
6235 // no direct outputs are open.
François Gaffie11d30102018-11-02 16:09:09 +01006236 if (!getMsdAudioOutDevices().isEmpty()) {
Dean Wheatley3023b382018-08-09 07:42:40 +10006237 bool directOutputOpen = false;
6238 for (size_t i = 0; i < mOutputs.size(); i++) {
6239 if (mOutputs[i]->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
6240 directOutputOpen = true;
6241 break;
6242 }
6243 }
6244 if (!directOutputOpen) {
Michael Chan6fb34492020-12-08 15:44:49 +11006245 ALOGV("no direct outputs open, reset MSD patches");
6246 // TODO: The MSD patches to be established here may differ to current MSD patches due to
6247 // how output devices for patching are resolved. Avoid by caching and reusing the
6248 // arguments to mEngine->getOutputDevicesForAttributes() when resolving which output
6249 // devices to patch to. This may be complicated by the fact that devices may become
6250 // unavailable.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11006251 setMsdOutputPatches();
Dean Wheatley3023b382018-08-09 07:42:40 +10006252 }
6253 }
Eric Laurent05b90f82014-08-27 15:32:29 -07006254}
6255
6256void AudioPolicyManager::closeInput(audio_io_handle_t input)
6257{
6258 ALOGV("closeInput(%d)", input);
6259
6260 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
6261 if (inputDesc == NULL) {
6262 ALOGW("closeInput() unknown input %d", input);
6263 return;
6264 }
6265
Eric Laurent6a94d692014-05-20 11:18:06 -07006266 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07006267
François Gaffie11d30102018-11-02 16:09:09 +01006268 sp<DeviceDescriptor> device = inputDesc->getDevice();
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08006269 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07006270 if (index >= 0) {
6271 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006272 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
6273 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07006274 mAudioPatches.removeItemsAt(index);
6275 mpClientInterface->onAudioPatchListUpdate();
6276 }
6277
Eric Laurentfe231122017-11-17 17:48:06 -08006278 inputDesc->close();
Eric Laurent05b90f82014-08-27 15:32:29 -07006279 mInputs.removeItem(input);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07006280
François Gaffie11d30102018-11-02 16:09:09 +01006281 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
6282 if (primaryInputDevices.contains(device) &&
Haynes Mathew George1d539d92018-03-16 11:40:49 -07006283 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07006284 mpClientInterface->setSoundTriggerCaptureState(false);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07006285 }
Eric Laurente552edb2014-03-10 17:42:56 -07006286}
6287
François Gaffie11d30102018-11-02 16:09:09 +01006288SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevices(
6289 const DeviceVector &devices,
6290 const SwAudioOutputCollection& openOutputs)
Eric Laurente552edb2014-03-10 17:42:56 -07006291{
6292 SortedVector<audio_io_handle_t> outputs;
6293
François Gaffie11d30102018-11-02 16:09:09 +01006294 ALOGVV("%s() devices %s", __func__, devices.toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07006295 for (size_t i = 0; i < openOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01006296 ALOGVV("output %zu isDuplicated=%d device=%s",
Eric Laurent8c7e6da2015-04-21 17:37:00 -07006297 i, openOutputs.valueAt(i)->isDuplicated(),
François Gaffie11d30102018-11-02 16:09:09 +01006298 openOutputs.valueAt(i)->supportedDevices().toString().c_str());
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006299 if (openOutputs.valueAt(i)->supportsAllDevices(devices)
jiabin9a3361e2019-10-01 09:38:30 -07006300 && openOutputs.valueAt(i)->devicesSupportEncodedFormats(devices.types())) {
François Gaffie11d30102018-11-02 16:09:09 +01006301 ALOGVV("%s() found output %d", __func__, openOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07006302 outputs.add(openOutputs.keyAt(i));
6303 }
6304 }
6305 return outputs;
6306}
6307
Mikhail Naganov37977152018-07-11 15:54:44 -07006308void AudioPolicyManager::checkForDeviceAndOutputChanges(std::function<bool()> onOutputsChecked)
6309{
6310 // checkA2dpSuspend must run before checkOutputForAllStrategies so that A2DP
6311 // output is suspended before any tracks are moved to it
6312 checkA2dpSuspend();
6313 checkOutputForAllStrategies();
Kevin Rocard153f92d2018-12-18 18:33:28 -08006314 checkSecondaryOutputs();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11006315 if (onOutputsChecked != nullptr && onOutputsChecked()) checkA2dpSuspend();
Mikhail Naganov37977152018-07-11 15:54:44 -07006316 updateDevicesAndOutputs();
Mikhail Naganov7bd9b8d2018-11-15 02:09:03 +00006317 if (mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD) != 0) {
Michael Chan6fb34492020-12-08 15:44:49 +11006318 // TODO: The MSD patches to be established here may differ to current MSD patches due to how
6319 // output devices for patching are resolved. Nevertheless, AudioTracks affected by device
6320 // configuration changes will ultimately be rerouted correctly. We can still avoid
6321 // unnecessary rerouting by caching and reusing the arguments to
6322 // mEngine->getOutputDevicesForAttributes() when resolving which output devices to patch to.
6323 // This may be complicated by the fact that devices may become unavailable.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11006324 setMsdOutputPatches();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11006325 }
Jean-Michel Trivi9a6b9ad2020-10-22 16:46:43 -07006326 // an event that changed routing likely occurred, inform upper layers
6327 mpClientInterface->onRoutingUpdated();
Mikhail Naganov37977152018-07-11 15:54:44 -07006328}
6329
François Gaffiec005e562018-11-06 15:04:49 +01006330bool AudioPolicyManager::followsSameRouting(const audio_attributes_t &lAttr,
6331 const audio_attributes_t &rAttr) const
Eric Laurente552edb2014-03-10 17:42:56 -07006332{
François Gaffiec005e562018-11-06 15:04:49 +01006333 return mEngine->getProductStrategyForAttributes(lAttr) ==
6334 mEngine->getProductStrategyForAttributes(rAttr);
6335}
6336
Francois Gaffieff1eb522020-05-06 18:37:04 +02006337void AudioPolicyManager::checkAudioSourceForAttributes(const audio_attributes_t &attr)
6338{
6339 for (size_t i = 0; i < mAudioSources.size(); i++) {
6340 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
6341 if (sourceDesc != nullptr && followsSameRouting(attr, sourceDesc->attributes())
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02006342 && sourceDesc->getPatchHandle() == AUDIO_PATCH_HANDLE_NONE
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02006343 && !isCallRxAudioSource(sourceDesc) && !sourceDesc->isInternal()) {
Francois Gaffieff1eb522020-05-06 18:37:04 +02006344 connectAudioSource(sourceDesc);
6345 }
6346 }
6347}
6348
6349void AudioPolicyManager::clearAudioSourcesForOutput(audio_io_handle_t output)
6350{
6351 for (size_t i = 0; i < mAudioSources.size(); i++) {
6352 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
6353 if (sourceDesc != nullptr && sourceDesc->swOutput().promote() != nullptr
6354 && sourceDesc->swOutput().promote()->mIoHandle == output) {
6355 disconnectAudioSource(sourceDesc);
6356 }
6357 }
6358}
6359
François Gaffiec005e562018-11-06 15:04:49 +01006360void AudioPolicyManager::checkOutputForAttributes(const audio_attributes_t &attr)
6361{
6362 auto psId = mEngine->getProductStrategyForAttributes(attr);
6363
6364 DeviceVector oldDevices = mEngine->getOutputDevicesForAttributes(attr, 0, true /*fromCache*/);
6365 DeviceVector newDevices = mEngine->getOutputDevicesForAttributes(attr, 0, false /*fromCache*/);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07006366
François Gaffie11d30102018-11-02 16:09:09 +01006367 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevices(oldDevices, mPreviousOutputs);
6368 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevices(newDevices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07006369
Eric Laurentc209fe42020-06-05 18:11:23 -07006370 uint32_t maxLatency = 0;
Eric Laurent56ed8842022-11-15 16:04:41 +01006371 std::vector<sp<SwAudioOutputDescriptor>> invalidatedOutputs;
Eric Laurentc209fe42020-06-05 18:11:23 -07006372 // take into account dynamic audio policies related changes: if a client is now associated
6373 // to a different policy mix than at creation time, invalidate corresponding stream
Eric Laurent56ed8842022-11-15 16:04:41 +01006374 for (size_t i = 0; i < mPreviousOutputs.size(); i++) {
Eric Laurentc209fe42020-06-05 18:11:23 -07006375 const sp<SwAudioOutputDescriptor>& desc = mPreviousOutputs.valueAt(i);
6376 if (desc->isDuplicated()) {
6377 continue;
Jean-Michel Trivife472e22014-12-16 14:23:13 -08006378 }
Eric Laurentc209fe42020-06-05 18:11:23 -07006379 for (const sp<TrackClientDescriptor>& client : desc->getClientIterable()) {
6380 if (mEngine->getProductStrategyForAttributes(client->attributes()) != psId) {
6381 continue;
6382 }
6383 sp<AudioPolicyMix> primaryMix;
Dean Wheatleyd082f472022-02-04 11:10:48 +11006384 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->config(),
6385 client->uid(), client->flags(), primaryMix, nullptr);
Eric Laurentc209fe42020-06-05 18:11:23 -07006386 if (status != OK) {
6387 continue;
6388 }
yucliuf4de36d2020-09-14 14:57:56 -07006389 if (client->getPrimaryMix() != primaryMix || client->hasLostPrimaryMix()) {
Eric Laurent56ed8842022-11-15 16:04:41 +01006390 if (desc->isStrategyActive(psId) && maxLatency < desc->latency()) {
Eric Laurentc209fe42020-06-05 18:11:23 -07006391 maxLatency = desc->latency();
6392 }
Eric Laurent56ed8842022-11-15 16:04:41 +01006393 invalidatedOutputs.push_back(desc);
Eric Laurentc209fe42020-06-05 18:11:23 -07006394 }
Jean-Michel Trivife472e22014-12-16 14:23:13 -08006395 }
6396 }
6397
Eric Laurent56ed8842022-11-15 16:04:41 +01006398 if (srcOutputs != dstOutputs || !invalidatedOutputs.empty()) {
Eric Laurentac3a6902018-05-11 16:39:10 -07006399 // get maximum latency of all source outputs to determine the minimum mute time guaranteeing
6400 // audio from invalidated tracks will be rendered when unmuting
Eric Laurentac3a6902018-05-11 16:39:10 -07006401 for (audio_io_handle_t srcOut : srcOutputs) {
6402 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
Eric Laurentaa02db82019-09-05 17:31:49 -07006403 if (desc == nullptr) continue;
6404
6405 if (desc->isStrategyActive(psId) && maxLatency < desc->latency()) {
Eric Laurentac3a6902018-05-11 16:39:10 -07006406 maxLatency = desc->latency();
6407 }
Eric Laurentaa02db82019-09-05 17:31:49 -07006408
Eric Laurent56ed8842022-11-15 16:04:41 +01006409 bool invalidate = false;
Eric Laurentaa02db82019-09-05 17:31:49 -07006410 for (auto client : desc->clientsList(false /*activeOnly*/)) {
Eric Laurent78aade82019-09-13 18:55:08 -07006411 if (desc->isDuplicated() || !desc->mProfile->isDirectOutput()) {
Eric Laurentaa02db82019-09-05 17:31:49 -07006412 // a client on a non direct outputs has necessarily a linear PCM format
6413 // so we can call selectOutput() safely
6414 const audio_io_handle_t newOutput = selectOutput(dstOutputs,
6415 client->flags(),
6416 client->config().format,
6417 client->config().channel_mask,
jiabinebb6af42020-06-09 17:31:17 -07006418 client->config().sample_rate,
6419 client->session());
Eric Laurentaa02db82019-09-05 17:31:49 -07006420 if (newOutput != srcOut) {
6421 invalidate = true;
6422 break;
6423 }
6424 } else {
6425 sp<IOProfile> profile = getProfileForOutput(newDevices,
6426 client->config().sample_rate,
6427 client->config().format,
6428 client->config().channel_mask,
6429 client->flags(),
6430 true /* directOnly */);
6431 if (profile != desc->mProfile) {
6432 invalidate = true;
6433 break;
6434 }
6435 }
6436 }
Eric Laurent56ed8842022-11-15 16:04:41 +01006437 // mute strategy while moving tracks from one output to another
6438 if (invalidate) {
6439 invalidatedOutputs.push_back(desc);
6440 if (desc->isStrategyActive(psId)) {
6441 setStrategyMute(psId, true, desc);
6442 setStrategyMute(psId, false, desc, maxLatency * LATENCY_MUTE_FACTOR,
6443 newDevices.types());
6444 }
Eric Laurente552edb2014-03-10 17:42:56 -07006445 }
François Gaffiec005e562018-11-06 15:04:49 +01006446 sp<SourceClientDescriptor> source = getSourceForAttributesOnOutput(srcOut, attr);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02006447 if (source != nullptr && !isCallRxAudioSource(source) && !source->isInternal()) {
Eric Laurentd60560a2015-04-10 11:31:20 -07006448 connectAudioSource(source);
6449 }
Eric Laurente552edb2014-03-10 17:42:56 -07006450 }
6451
Eric Laurent56ed8842022-11-15 16:04:41 +01006452 ALOGV_IF(!(srcOutputs.isEmpty() || dstOutputs.isEmpty()),
6453 "%s: strategy %d, moving from output %s to output %s", __func__, psId,
6454 std::to_string(srcOutputs[0]).c_str(),
6455 std::to_string(dstOutputs[0]).c_str());
6456
François Gaffiec005e562018-11-06 15:04:49 +01006457 // Move effects associated to this stream from previous output to new output
6458 if (followsSameRouting(attr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07006459 selectOutputForMusicEffects();
Eric Laurente552edb2014-03-10 17:42:56 -07006460 }
François Gaffiec005e562018-11-06 15:04:49 +01006461 // Move tracks associated to this stream (and linked) from previous output to new output
Eric Laurent56ed8842022-11-15 16:04:41 +01006462 if (!invalidatedOutputs.empty()) {
Eric Laurentaa02db82019-09-05 17:31:49 -07006463 for (auto stream : mEngine->getStreamTypesForProductStrategy(psId)) {
6464 mpClientInterface->invalidateStream(stream);
6465 }
Eric Laurent56ed8842022-11-15 16:04:41 +01006466 for (sp<SwAudioOutputDescriptor> desc : invalidatedOutputs) {
jiabin49256852022-03-09 11:21:35 -08006467 desc->setTracksInvalidatedStatusByStrategy(psId);
6468 }
Eric Laurente552edb2014-03-10 17:42:56 -07006469 }
6470 }
6471}
6472
Eric Laurente0720872014-03-11 09:30:41 -07006473void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07006474{
François Gaffiec005e562018-11-06 15:04:49 +01006475 for (const auto &strategy : mEngine->getOrderedProductStrategies()) {
6476 auto attributes = mEngine->getAllAttributesForProductStrategy(strategy).front();
6477 checkOutputForAttributes(attributes);
Francois Gaffieff1eb522020-05-06 18:37:04 +02006478 checkAudioSourceForAttributes(attributes);
François Gaffiec005e562018-11-06 15:04:49 +01006479 }
Eric Laurente552edb2014-03-10 17:42:56 -07006480}
6481
Kevin Rocard153f92d2018-12-18 18:33:28 -08006482void AudioPolicyManager::checkSecondaryOutputs() {
6483 std::set<audio_stream_type_t> streamsToInvalidate;
jiabin10a03f12021-05-07 23:46:28 +00006484 TrackSecondaryOutputsMap trackSecondaryOutputs;
Kevin Rocard153f92d2018-12-18 18:33:28 -08006485 for (size_t i = 0; i < mOutputs.size(); i++) {
6486 const sp<SwAudioOutputDescriptor>& outputDescriptor = mOutputs[i];
6487 for (const sp<TrackClientDescriptor>& client : outputDescriptor->getClientIterable()) {
Eric Laurentc529cf62020-04-17 18:19:10 -07006488 sp<AudioPolicyMix> primaryMix;
6489 std::vector<sp<AudioPolicyMix>> secondaryMixes;
Dean Wheatleyd082f472022-02-04 11:10:48 +11006490 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->config(),
6491 client->uid(), client->flags(), primaryMix, &secondaryMixes);
Eric Laurentc529cf62020-04-17 18:19:10 -07006492 std::vector<sp<SwAudioOutputDescriptor>> secondaryDescs;
6493 for (auto &secondaryMix : secondaryMixes) {
6494 sp<SwAudioOutputDescriptor> outputDesc = secondaryMix->getOutput();
6495 if (outputDesc != nullptr &&
6496 outputDesc->mIoHandle != AUDIO_IO_HANDLE_NONE) {
6497 secondaryDescs.push_back(outputDesc);
6498 }
6499 }
6500
jiabin10a03f12021-05-07 23:46:28 +00006501 if (status != OK) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08006502 streamsToInvalidate.insert(client->stream());
jiabin10a03f12021-05-07 23:46:28 +00006503 } else if (!std::equal(
6504 client->getSecondaryOutputs().begin(),
6505 client->getSecondaryOutputs().end(),
6506 secondaryDescs.begin(), secondaryDescs.end())) {
jiabina5281062021-11-23 00:10:23 +00006507 if (!audio_is_linear_pcm(client->config().format)) {
6508 // If the format is not PCM, the tracks should be invalidated to get correct
6509 // behavior when the secondary output is changed.
6510 streamsToInvalidate.insert(client->stream());
6511 } else {
6512 std::vector<wp<SwAudioOutputDescriptor>> weakSecondaryDescs;
6513 std::vector<audio_io_handle_t> secondaryOutputIds;
6514 for (const auto &secondaryDesc: secondaryDescs) {
6515 secondaryOutputIds.push_back(secondaryDesc->mIoHandle);
6516 weakSecondaryDescs.push_back(secondaryDesc);
6517 }
6518 trackSecondaryOutputs.emplace(client->portId(), secondaryOutputIds);
6519 client->setSecondaryOutputs(std::move(weakSecondaryDescs));
jiabin10a03f12021-05-07 23:46:28 +00006520 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08006521 }
6522 }
6523 }
jiabin10a03f12021-05-07 23:46:28 +00006524 if (!trackSecondaryOutputs.empty()) {
6525 mpClientInterface->updateSecondaryOutputs(trackSecondaryOutputs);
6526 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08006527 for (audio_stream_type_t stream : streamsToInvalidate) {
jiabin10a03f12021-05-07 23:46:28 +00006528 ALOGD("%s Invalidate stream %d due to fail getting output for attr", __func__, stream);
Kevin Rocard153f92d2018-12-18 18:33:28 -08006529 mpClientInterface->invalidateStream(stream);
6530 }
6531}
6532
Eric Laurent2517af32020-11-25 15:31:27 +01006533bool AudioPolicyManager::isScoRequestedForComm() const {
6534 AudioDeviceTypeAddrVector devices;
6535 mEngine->getDevicesForRoleAndStrategy(mCommunnicationStrategy, DEVICE_ROLE_PREFERRED, devices);
6536 for (const auto &device : devices) {
6537 if (audio_is_bluetooth_out_sco_device(device.mType)) {
6538 return true;
6539 }
6540 }
6541 return false;
6542}
6543
Eric Laurent1a8b45f2022-04-13 16:01:47 +02006544bool AudioPolicyManager::isHearingAidUsedForComm() const {
6545 DeviceVector devices = mEngine->getOutputDevicesForStream(AUDIO_STREAM_VOICE_CALL,
6546 true /*fromCache*/);
6547 for (const auto &device : devices) {
6548 if (device->type() == AUDIO_DEVICE_OUT_HEARING_AID) {
6549 return true;
6550 }
6551 }
6552 return false;
6553}
6554
6555
Eric Laurente0720872014-03-11 09:30:41 -07006556void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07006557{
François Gaffie53615e22015-03-19 09:24:12 +01006558 audio_io_handle_t a2dpOutput = mOutputs.getA2dpOutput();
Aniket Kumar Lataa8ee9962018-01-31 20:24:23 -08006559 if (a2dpOutput == 0 || mOutputs.isA2dpOffloadedOnPrimary()) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07006560 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07006561 return;
6562 }
6563
Eric Laurent3a4311c2014-03-17 12:00:47 -07006564 bool isScoConnected =
jiabin9a3361e2019-10-01 09:38:30 -07006565 (mAvailableInputDevices.types().count(AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) != 0 ||
6566 !Intersection(mAvailableOutputDevices.types(), getAudioDeviceOutAllScoSet()).empty());
Eric Laurent2517af32020-11-25 15:31:27 +01006567 bool isScoRequested = isScoRequestedForComm();
Eric Laurentf732e072016-08-03 19:30:28 -07006568
6569 // if suspended, restore A2DP output if:
6570 // ((SCO device is NOT connected) ||
Eric Laurent2517af32020-11-25 15:31:27 +01006571 // ((SCO is not requested) &&
Eric Laurentf732e072016-08-03 19:30:28 -07006572 // (phone state is NOT in call) && (phone state is NOT ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07006573 //
Eric Laurentf732e072016-08-03 19:30:28 -07006574 // if not suspended, suspend A2DP output if:
6575 // (SCO device is connected) &&
Eric Laurent2517af32020-11-25 15:31:27 +01006576 // ((SCO is requested) ||
Eric Laurentf732e072016-08-03 19:30:28 -07006577 // ((phone state is in call) || (phone state is ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07006578 //
6579 if (mA2dpSuspended) {
Eric Laurentf732e072016-08-03 19:30:28 -07006580 if (!isScoConnected ||
Eric Laurent2517af32020-11-25 15:31:27 +01006581 (!isScoRequested &&
Eric Laurentf732e072016-08-03 19:30:28 -07006582 (mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) &&
François Gaffie2110e042015-03-24 08:41:51 +01006583 (mEngine->getPhoneState() != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07006584
6585 mpClientInterface->restoreOutput(a2dpOutput);
6586 mA2dpSuspended = false;
6587 }
6588 } else {
Eric Laurentf732e072016-08-03 19:30:28 -07006589 if (isScoConnected &&
Eric Laurent2517af32020-11-25 15:31:27 +01006590 (isScoRequested ||
Eric Laurentf732e072016-08-03 19:30:28 -07006591 (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) ||
François Gaffie2110e042015-03-24 08:41:51 +01006592 (mEngine->getPhoneState() == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07006593
6594 mpClientInterface->suspendOutput(a2dpOutput);
6595 mA2dpSuspended = true;
6596 }
6597 }
6598}
6599
François Gaffie11d30102018-11-02 16:09:09 +01006600DeviceVector AudioPolicyManager::getNewOutputDevices(const sp<SwAudioOutputDescriptor>& outputDesc,
6601 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07006602{
François Gaffie11d30102018-11-02 16:09:09 +01006603 DeviceVector devices;
6604
Jean-Michel Triviff155c62016-02-26 12:07:16 -08006605 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07006606 if (index >= 0) {
6607 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006608 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01006609 ALOGV("%s device %s forced by patch %d", __func__,
6610 outputDesc->devices().toString().c_str(), outputDesc->getPatchHandle());
6611 return outputDesc->devices();
Eric Laurent6a94d692014-05-20 11:18:06 -07006612 }
6613 }
6614
Dean Wheatley514b4312020-06-17 21:45:00 +10006615 // Do not retrieve engine device for outputs through MSD
6616 // TODO: support explicit routing requests by resetting MSD patch to engine device.
6617 if (outputDesc->devices() == getMsdAudioOutDevices()) {
6618 return outputDesc->devices();
6619 }
6620
Eric Laurent97ac8712018-07-27 18:59:02 -07006621 // Honor explicit routing requests only if no client using default routing is active on this
6622 // input: a specific app can not force routing for other apps by setting a preferred device.
6623 bool active; // unused
François Gaffie11d30102018-11-02 16:09:09 +01006624 sp<DeviceDescriptor> device =
François Gaffiec005e562018-11-06 15:04:49 +01006625 findPreferredDevice(outputDesc, PRODUCT_STRATEGY_NONE, active, mAvailableOutputDevices);
François Gaffie11d30102018-11-02 16:09:09 +01006626 if (device != nullptr) {
6627 return DeviceVector(device);
Eric Laurentf3a5a602018-05-22 18:42:55 -07006628 }
6629
François Gaffiea807ef92018-11-05 10:44:33 +01006630 // Legacy Engine cannot take care of bus devices and mix, so we need to handle the conflict
6631 // of setForceUse / Default Bus device here
6632 device = mPolicyMixes.getDeviceAndMixForOutput(outputDesc, mAvailableOutputDevices);
6633 if (device != nullptr) {
6634 return DeviceVector(device);
6635 }
6636
François Gaffiec005e562018-11-06 15:04:49 +01006637 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
6638 StreamTypeVector streams = mEngine->getStreamTypesForProductStrategy(productStrategy);
6639 auto attr = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05306640 auto hasStreamActive = [&](auto stream) {
6641 return hasStream(streams, stream) && isStreamActive(stream, 0);
6642 };
Eric Laurent484e9272018-06-07 17:29:23 -07006643
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05306644 auto doGetOutputDevicesForVoice = [&]() {
6645 return hasVoiceStream(streams) && (outputDesc == mPrimaryOutput ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01006646 outputDesc->isActive(toVolumeSource(AUDIO_STREAM_VOICE_CALL, false))) &&
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05306647 (isInCall() ||
Henrik Backlund07c654a2021-10-14 15:57:10 +02006648 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc)) &&
6649 !isStreamActive(AUDIO_STREAM_ENFORCED_AUDIBLE, 0);
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05306650 };
6651
6652 // With low-latency playing on speaker, music on WFD, when the first low-latency
6653 // output is stopped, getNewOutputDevices checks for a product strategy
6654 // from the list, as STRATEGY_SONIFICATION comes prior to STRATEGY_MEDIA.
Carter Hsucc58a6b2021-07-20 08:44:50 +00006655 // If an ALARM or ENFORCED_AUDIBLE stream is supported by the product strategy,
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05306656 // devices are returned for STRATEGY_SONIFICATION without checking whether the
6657 // stream is associated to the output descriptor.
6658 if (doGetOutputDevicesForVoice() || outputDesc->isStrategyActive(productStrategy) ||
6659 ((hasStreamActive(AUDIO_STREAM_ALARM) ||
6660 hasStreamActive(AUDIO_STREAM_ENFORCED_AUDIBLE)) &&
6661 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc))) {
François Gaffiec005e562018-11-06 15:04:49 +01006662 // Retrieval of devices for voice DL is done on primary output profile, cannot
6663 // check the route (would force modifying configuration file for this profile)
6664 devices = mEngine->getOutputDevicesForAttributes(attr, nullptr, fromCache);
6665 break;
6666 }
Eric Laurente552edb2014-03-10 17:42:56 -07006667 }
François Gaffiec005e562018-11-06 15:04:49 +01006668 ALOGV("%s selected devices %s", __func__, devices.toString().c_str());
François Gaffie11d30102018-11-02 16:09:09 +01006669 return devices;
Eric Laurent1c333e22014-05-20 10:48:17 -07006670}
6671
François Gaffie11d30102018-11-02 16:09:09 +01006672sp<DeviceDescriptor> AudioPolicyManager::getNewInputDevice(
6673 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurent1c333e22014-05-20 10:48:17 -07006674{
François Gaffie11d30102018-11-02 16:09:09 +01006675 sp<DeviceDescriptor> device;
Eric Laurent6a94d692014-05-20 11:18:06 -07006676
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08006677 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07006678 if (index >= 0) {
6679 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006680 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01006681 ALOGV("getNewInputDevice() device %s forced by patch %d",
6682 inputDesc->getDevice()->toString().c_str(), inputDesc->getPatchHandle());
6683 return inputDesc->getDevice();
Eric Laurent6a94d692014-05-20 11:18:06 -07006684 }
6685 }
6686
Eric Laurent97ac8712018-07-27 18:59:02 -07006687 // Honor explicit routing requests only if no client using default routing is active on this
6688 // input: a specific app can not force routing for other apps by setting a preferred device.
6689 bool active;
François Gaffie11d30102018-11-02 16:09:09 +01006690 device = findPreferredDevice(inputDesc, AUDIO_SOURCE_DEFAULT, active, mAvailableInputDevices);
6691 if (device != nullptr) {
6692 return device;
Eric Laurent97ac8712018-07-27 18:59:02 -07006693 }
6694
Eric Laurentdc95a252018-04-12 12:46:56 -07006695 // If we are not in call and no client is active on this input, this methods returns
Andy Hungf024a9e2019-01-30 16:01:02 -08006696 // a null sp<>, causing the patch on the input stream to be released.
yuanjiahsu0735bf32021-03-18 08:12:54 +08006697 audio_attributes_t attributes;
6698 uid_t uid;
6699 sp<RecordClientDescriptor> topClient = inputDesc->getHighestPriorityClient();
6700 if (topClient != nullptr) {
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01006701 attributes = topClient->attributes();
6702 uid = topClient->uid();
yuanjiahsu0735bf32021-03-18 08:12:54 +08006703 } else {
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01006704 attributes = { .source = AUDIO_SOURCE_DEFAULT };
6705 uid = 0;
yuanjiahsu0735bf32021-03-18 08:12:54 +08006706 }
6707
Francois Gaffie716e1432019-01-14 16:58:59 +01006708 if (attributes.source == AUDIO_SOURCE_DEFAULT && isInCall()) {
6709 attributes.source = AUDIO_SOURCE_VOICE_COMMUNICATION;
Eric Laurentdc95a252018-04-12 12:46:56 -07006710 }
Francois Gaffie716e1432019-01-14 16:58:59 +01006711 if (attributes.source != AUDIO_SOURCE_DEFAULT) {
yuanjiahsu0735bf32021-03-18 08:12:54 +08006712 device = mEngine->getInputDeviceForAttributes(attributes, uid);
Eric Laurentfb66dd92016-01-28 18:32:03 -08006713 }
Eric Laurent1c333e22014-05-20 10:48:17 -07006714
Eric Laurente552edb2014-03-10 17:42:56 -07006715 return device;
6716}
6717
Eric Laurent794fde22016-03-11 09:50:45 -08006718bool AudioPolicyManager::streamsMatchForvolume(audio_stream_type_t stream1,
6719 audio_stream_type_t stream2) {
Jean-Michel Trivi99bb2f92016-11-23 15:52:07 -08006720 return (stream1 == stream2);
Eric Laurent28d09f02016-03-08 10:43:05 -08006721}
6722
Dorin Drimusf2196d82022-01-03 12:11:18 +01006723// TODO - consider MSD routes b/214971780
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08006724status_t AudioPolicyManager::getDevicesForAttributes(
Andy Hung6d23c0f2022-02-16 09:37:15 -08006725 const audio_attributes_t &attr, AudioDeviceTypeAddrVector *devices, bool forVolume) {
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08006726 if (devices == nullptr) {
6727 return BAD_VALUE;
6728 }
Andy Hung6d23c0f2022-02-16 09:37:15 -08006729
6730 // Devices are determined in the following precedence:
6731 //
6732 // 1) Devices associated with a dynamic policy matching the attributes. This is often
6733 // a remote submix from MIX_ROUTE_FLAG_LOOP_BACK.
6734 //
6735 // If no such dynamic policy then
6736 // 2) Devices containing an active client using setPreferredDevice
6737 // with same strategy as the attributes.
6738 // (from the default Engine::getOutputDevicesForAttributes() implementation).
6739 //
6740 // If no corresponding active client with setPreferredDevice then
6741 // 3) Devices associated with the strategy determined by the attributes
6742 // (from the default Engine::getOutputDevicesForAttributes() implementation).
6743 //
6744 // See related getOutputForAttrInt().
6745
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08006746 // check dynamic policies but only for primary descriptors (secondary not used for audible
6747 // audio routing, only used for duplication for playback capture)
Eric Laurentc529cf62020-04-17 18:19:10 -07006748 sp<AudioPolicyMix> policyMix;
Dean Wheatleyd082f472022-02-04 11:10:48 +11006749 status_t status = mPolicyMixes.getOutputForAttr(attr, AUDIO_CONFIG_BASE_INITIALIZER,
6750 0 /*uid unknown here*/, AUDIO_OUTPUT_FLAG_NONE, policyMix, nullptr);
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08006751 if (status != OK) {
6752 return status;
6753 }
Andy Hung6d23c0f2022-02-16 09:37:15 -08006754
6755 DeviceVector curDevices;
6756 if (policyMix != nullptr && policyMix->getOutput() != nullptr &&
6757 // For volume control, skip LOOPBACK mixes which use AUDIO_DEVICE_OUT_REMOTE_SUBMIX
6758 // as they are unaffected by device/stream volume
6759 // (per SwAudioOutputDescriptor::isFixedVolume()).
6760 (!forVolume || policyMix->mDeviceType != AUDIO_DEVICE_OUT_REMOTE_SUBMIX)
6761 ) {
6762 sp<DeviceDescriptor> deviceDesc = mAvailableOutputDevices.getDevice(
6763 policyMix->mDeviceType, policyMix->mDeviceAddress, AUDIO_FORMAT_DEFAULT);
6764 curDevices.add(deviceDesc);
6765 } else {
6766 // The default Engine::getOutputDevicesForAttributes() uses findPreferredDevice()
6767 // which selects setPreferredDevice if active. This means forVolume call
6768 // will take an active setPreferredDevice, if such exists.
6769
6770 curDevices = mEngine->getOutputDevicesForAttributes(
6771 attr, nullptr /* preferredDevice */, false /* fromCache */);
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08006772 }
Andy Hung6d23c0f2022-02-16 09:37:15 -08006773
6774 if (forVolume) {
6775 // We alias the device AUDIO_DEVICE_OUT_SPEAKER_SAFE to AUDIO_DEVICE_OUT_SPEAKER
6776 // for single volume control in AudioService (such relationship should exist if
6777 // SPEAKER_SAFE is present).
6778 //
6779 // (This is unrelated to a different device grouping as Volume::getDeviceCategory)
6780 DeviceVector speakerSafeDevices =
6781 curDevices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER_SAFE);
6782 if (!speakerSafeDevices.isEmpty()) {
6783 curDevices.merge(
6784 mAvailableOutputDevices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER));
6785 curDevices.remove(speakerSafeDevices);
6786 }
6787 }
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08006788 for (const auto& device : curDevices) {
6789 devices->push_back(device->getDeviceTypeAddr());
6790 }
6791 return NO_ERROR;
6792}
6793
Eric Laurente0720872014-03-11 09:30:41 -07006794void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07006795 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07006796 case AUDIO_STREAM_MUSIC:
François Gaffiec005e562018-11-06 15:04:49 +01006797 checkOutputForAttributes(attributes_initializer(AUDIO_USAGE_NOTIFICATION));
Eric Laurente552edb2014-03-10 17:42:56 -07006798 updateDevicesAndOutputs();
6799 break;
6800 default:
6801 break;
6802 }
6803}
6804
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006805uint32_t AudioPolicyManager::handleEventForBeacon(int event) {
Eric Laurent9459fb02015-08-12 18:36:32 -07006806
6807 // skip beacon mute management if a dedicated TTS output is available
6808 if (mTtsOutputAvailable) {
6809 return 0;
6810 }
6811
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006812 switch(event) {
6813 case STARTING_OUTPUT:
6814 mBeaconMuteRefCount++;
6815 break;
6816 case STOPPING_OUTPUT:
6817 if (mBeaconMuteRefCount > 0) {
6818 mBeaconMuteRefCount--;
6819 }
6820 break;
6821 case STARTING_BEACON:
6822 mBeaconPlayingRefCount++;
6823 break;
6824 case STOPPING_BEACON:
6825 if (mBeaconPlayingRefCount > 0) {
6826 mBeaconPlayingRefCount--;
6827 }
6828 break;
6829 }
6830
6831 if (mBeaconMuteRefCount > 0) {
6832 // any playback causes beacon to be muted
6833 return setBeaconMute(true);
6834 } else {
6835 // no other playback: unmute when beacon starts playing, mute when it stops
6836 return setBeaconMute(mBeaconPlayingRefCount == 0);
6837 }
6838}
6839
6840uint32_t AudioPolicyManager::setBeaconMute(bool mute) {
6841 ALOGV("setBeaconMute(%d) mBeaconMuteRefCount=%d mBeaconPlayingRefCount=%d",
6842 mute, mBeaconMuteRefCount, mBeaconPlayingRefCount);
6843 // keep track of muted state to avoid repeating mute/unmute operations
6844 if (mBeaconMuted != mute) {
6845 // mute/unmute AUDIO_STREAM_TTS on all outputs
6846 ALOGV("\t muting %d", mute);
6847 uint32_t maxLatency = 0;
Francois Gaffie4404ddb2021-02-04 17:03:38 +01006848 auto ttsVolumeSource = toVolumeSource(AUDIO_STREAM_TTS, false);
6849 if (ttsVolumeSource == VOLUME_SOURCE_NONE) {
6850 ALOGV("\t no tts volume source available");
6851 return 0;
6852 }
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006853 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07006854 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
jiabin9a3361e2019-10-01 09:38:30 -07006855 setVolumeSourceMute(ttsVolumeSource, mute/*on*/, desc, 0 /*delay*/, DeviceTypeSet());
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006856 const uint32_t latency = desc->latency() * 2;
Eric Laurentcdb2b352020-07-23 10:57:02 -07006857 if (desc->isActive(latency * 2) && latency > maxLatency) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006858 maxLatency = latency;
6859 }
6860 }
6861 mBeaconMuted = mute;
6862 return maxLatency;
6863 }
6864 return 0;
6865}
6866
Eric Laurente0720872014-03-11 09:30:41 -07006867void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07006868{
François Gaffiec005e562018-11-06 15:04:49 +01006869 mEngine->updateDeviceSelectionCache();
Eric Laurente552edb2014-03-10 17:42:56 -07006870 mPreviousOutputs = mOutputs;
6871}
6872
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07006873uint32_t AudioPolicyManager::checkDeviceMuteStrategies(const sp<AudioOutputDescriptor>& outputDesc,
François Gaffiec005e562018-11-06 15:04:49 +01006874 const DeviceVector &prevDevices,
Eric Laurente552edb2014-03-10 17:42:56 -07006875 uint32_t delayMs)
6876{
6877 // mute/unmute strategies using an incompatible device combination
6878 // if muting, wait for the audio in pcm buffer to be drained before proceeding
6879 // if unmuting, unmute only after the specified delay
6880 if (outputDesc->isDuplicated()) {
6881 return 0;
6882 }
6883
6884 uint32_t muteWaitMs = 0;
François Gaffiec005e562018-11-06 15:04:49 +01006885 DeviceVector devices = outputDesc->devices();
6886 bool shouldMute = outputDesc->isActive() && (devices.size() >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07006887
François Gaffiec005e562018-11-06 15:04:49 +01006888 auto productStrategies = mEngine->getOrderedProductStrategies();
6889 for (const auto &productStrategy : productStrategies) {
6890 auto attributes = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
6891 DeviceVector curDevices =
6892 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false/*fromCache*/);
6893 curDevices = curDevices.filter(outputDesc->supportedDevices());
6894 bool mute = shouldMute && curDevices.containsAtLeastOne(devices) && curDevices != devices;
Eric Laurente552edb2014-03-10 17:42:56 -07006895 bool doMute = false;
6896
François Gaffiec005e562018-11-06 15:04:49 +01006897 if (mute && !outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07006898 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01006899 outputDesc->setStrategyMutedByDevice(productStrategy, true);
6900 } else if (!mute && outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07006901 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01006902 outputDesc->setStrategyMutedByDevice(productStrategy, false);
Eric Laurente552edb2014-03-10 17:42:56 -07006903 }
Eric Laurent99401132014-05-07 19:48:15 -07006904 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07006905 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07006906 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07006907 // skip output if it does not share any device with current output
François Gaffie11d30102018-11-02 16:09:09 +01006908 if (!desc->supportedDevices().containsAtLeastOne(outputDesc->supportedDevices())) {
Eric Laurente552edb2014-03-10 17:42:56 -07006909 continue;
6910 }
François Gaffiec005e562018-11-06 15:04:49 +01006911 ALOGVV("%s() %s (curDevice %s)", __func__,
6912 mute ? "muting" : "unmuting", curDevices.toString().c_str());
6913 setStrategyMute(productStrategy, mute, desc, mute ? 0 : delayMs);
6914 if (desc->isStrategyActive(productStrategy)) {
Eric Laurent99401132014-05-07 19:48:15 -07006915 if (mute) {
6916 // FIXME: should not need to double latency if volume could be applied
6917 // immediately by the audioflinger mixer. We must account for the delay
6918 // between now and the next time the audioflinger thread for this output
6919 // will process a buffer (which corresponds to one buffer size,
6920 // usually 1/2 or 1/4 of the latency).
6921 if (muteWaitMs < desc->latency() * 2) {
6922 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07006923 }
6924 }
6925 }
6926 }
6927 }
6928 }
6929
Eric Laurent99401132014-05-07 19:48:15 -07006930 // temporary mute output if device selection changes to avoid volume bursts due to
6931 // different per device volumes
François Gaffiec005e562018-11-06 15:04:49 +01006932 if (outputDesc->isActive() && (devices != prevDevices)) {
Eric Laurentdc462862016-07-19 12:29:53 -07006933 uint32_t tempMuteWaitMs = outputDesc->latency() * 2;
Jasmine Chaf6074fe2021-08-17 13:44:31 +08006934
Eric Laurentdc462862016-07-19 12:29:53 -07006935 if (muteWaitMs < tempMuteWaitMs) {
6936 muteWaitMs = tempMuteWaitMs;
Eric Laurent99401132014-05-07 19:48:15 -07006937 }
Jasmine Chaf6074fe2021-08-17 13:44:31 +08006938
6939 // If recommended duration is defined, replace temporary mute duration to avoid
6940 // truncated notifications at beginning, which depends on duration of changing path in HAL.
6941 // Otherwise, temporary mute duration is conservatively set to 4 times the reported latency.
6942 uint32_t tempRecommendedMuteDuration = outputDesc->getRecommendedMuteDurationMs();
6943 uint32_t tempMuteDurationMs = tempRecommendedMuteDuration > 0 ?
6944 tempRecommendedMuteDuration : outputDesc->latency() * 4;
6945
François Gaffieaaac0fd2018-11-22 17:56:39 +01006946 for (const auto &activeVs : outputDesc->getActiveVolumeSources()) {
6947 // make sure that we do not start the temporary mute period too early in case of
6948 // delayed device change
6949 setVolumeSourceMute(activeVs, true, outputDesc, delayMs);
6950 setVolumeSourceMute(activeVs, false, outputDesc, delayMs + tempMuteDurationMs,
François Gaffiec005e562018-11-06 15:04:49 +01006951 devices.types());
Eric Laurent99401132014-05-07 19:48:15 -07006952 }
6953 }
6954
Eric Laurente552edb2014-03-10 17:42:56 -07006955 // wait for the PCM output buffers to empty before proceeding with the rest of the command
6956 if (muteWaitMs > delayMs) {
6957 muteWaitMs -= delayMs;
6958 usleep(muteWaitMs * 1000);
6959 return muteWaitMs;
6960 }
6961 return 0;
6962}
6963
François Gaffie11d30102018-11-02 16:09:09 +01006964uint32_t AudioPolicyManager::setOutputDevices(const sp<SwAudioOutputDescriptor>& outputDesc,
6965 const DeviceVector &devices,
6966 bool force,
6967 int delayMs,
6968 audio_patch_handle_t *patchHandle,
Francois Gaffie3523ab32021-06-22 13:24:34 +02006969 bool requiresMuteCheck, bool requiresVolumeCheck)
Eric Laurente552edb2014-03-10 17:42:56 -07006970{
François Gaffie11d30102018-11-02 16:09:09 +01006971 ALOGV("%s device %s delayMs %d", __func__, devices.toString().c_str(), delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07006972 uint32_t muteWaitMs;
6973
6974 if (outputDesc->isDuplicated()) {
François Gaffie11d30102018-11-02 16:09:09 +01006975 muteWaitMs = setOutputDevices(outputDesc->subOutput1(), devices, force, delayMs,
6976 nullptr /* patchHandle */, requiresMuteCheck);
6977 muteWaitMs += setOutputDevices(outputDesc->subOutput2(), devices, force, delayMs,
6978 nullptr /* patchHandle */, requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07006979 return muteWaitMs;
6980 }
Eric Laurente552edb2014-03-10 17:42:56 -07006981
6982 // filter devices according to output selected
Francois Gaffie716e1432019-01-14 16:58:59 +01006983 DeviceVector filteredDevices = outputDesc->filterSupportedDevices(devices);
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01006984 DeviceVector prevDevices = outputDesc->devices();
Francois Gaffie3523ab32021-06-22 13:24:34 +02006985 DeviceVector availPrevDevices = mAvailableOutputDevices.filter(prevDevices);
Eric Laurente552edb2014-03-10 17:42:56 -07006986
François Gaffie11d30102018-11-02 16:09:09 +01006987 ALOGV("setOutputDevices() prevDevice %s", prevDevices.toString().c_str());
6988
6989 if (!filteredDevices.isEmpty()) {
6990 outputDesc->setDevices(filteredDevices);
Eric Laurente552edb2014-03-10 17:42:56 -07006991 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00006992
6993 // if the outputs are not materially active, there is no need to mute.
6994 if (requiresMuteCheck) {
François Gaffiec005e562018-11-06 15:04:49 +01006995 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevices, delayMs);
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00006996 } else {
6997 ALOGV("%s: suppressing checkDeviceMuteStrategies", __func__);
6998 muteWaitMs = 0;
6999 }
Eric Laurente552edb2014-03-10 17:42:56 -07007000
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02007001 bool outputRouted = outputDesc->isRouted();
7002
Eric Laurent79ea9582020-06-11 18:49:24 -07007003 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
7004 // output profile or if new device is not supported AND previous device(s) is(are) still
7005 // available (otherwise reset device must be done on the output)
Francois Gaffie3523ab32021-06-22 13:24:34 +02007006 if (!devices.isEmpty() && filteredDevices.isEmpty() && !availPrevDevices.empty()) {
Eric Laurent79ea9582020-06-11 18:49:24 -07007007 ALOGV("%s: unsupported device %s for output", __func__, devices.toString().c_str());
7008 // restore previous device after evaluating strategy mute state
7009 outputDesc->setDevices(prevDevices);
7010 return muteWaitMs;
7011 }
7012
Eric Laurente552edb2014-03-10 17:42:56 -07007013 // Do not change the routing if:
Eric Laurentb80a2a82014-10-27 16:07:59 -07007014 // the requested device is AUDIO_DEVICE_NONE
7015 // OR the requested device is the same as current device
7016 // AND force is not specified
7017 // AND the output is connected by a valid audio patch.
François Gaffie11d30102018-11-02 16:09:09 +01007018 // Doing this check here allows the caller to call setOutputDevices() without conditions
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02007019 if ((filteredDevices.isEmpty() || filteredDevices == prevDevices) && !force && outputRouted) {
François Gaffie11d30102018-11-02 16:09:09 +01007020 ALOGV("%s setting same device %s or null device, force=%d, patch handle=%d", __func__,
7021 filteredDevices.toString().c_str(), force, outputDesc->getPatchHandle());
Francois Gaffie3523ab32021-06-22 13:24:34 +02007022 if (requiresVolumeCheck && !filteredDevices.isEmpty()) {
7023 ALOGV("%s setting same device on routed output, force apply volumes", __func__);
7024 applyStreamVolumes(outputDesc, filteredDevices.types(), delayMs, true /*force*/);
7025 }
Eric Laurente552edb2014-03-10 17:42:56 -07007026 return muteWaitMs;
7027 }
7028
François Gaffie11d30102018-11-02 16:09:09 +01007029 ALOGV("%s changing device to %s", __func__, filteredDevices.toString().c_str());
Eric Laurent1c333e22014-05-20 10:48:17 -07007030
Eric Laurente552edb2014-03-10 17:42:56 -07007031 // do the routing
Francois Gaffie3523ab32021-06-22 13:24:34 +02007032 if (filteredDevices.isEmpty() || mAvailableOutputDevices.filter(filteredDevices).empty()) {
Eric Laurentc75307b2015-03-17 15:29:32 -07007033 resetOutputDevice(outputDesc, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07007034 } else {
François Gaffie11d30102018-11-02 16:09:09 +01007035 PatchBuilder patchBuilder;
7036 patchBuilder.addSource(outputDesc);
7037 ALOG_ASSERT(filteredDevices.size() <= AUDIO_PATCH_PORTS_MAX, "Too many sink ports");
7038 for (const auto &filteredDevice : filteredDevices) {
7039 patchBuilder.addSink(filteredDevice);
Eric Laurentc40d9692016-04-13 19:14:13 -07007040 }
7041
Jasmine Cha7f82d1a2020-03-16 13:21:47 +08007042 // Add half reported latency to delayMs when muteWaitMs is null in order
7043 // to avoid disordered sequence of muting volume and changing devices.
7044 installPatch(__func__, patchHandle, outputDesc.get(), patchBuilder.patch(),
7045 muteWaitMs == 0 ? (delayMs + (outputDesc->latency() / 2)) : delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07007046 }
Eric Laurente552edb2014-03-10 17:42:56 -07007047
7048 // update stream volumes according to new device
François Gaffie11d30102018-11-02 16:09:09 +01007049 applyStreamVolumes(outputDesc, filteredDevices.types(), delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07007050
7051 return muteWaitMs;
7052}
7053
Eric Laurentc75307b2015-03-17 15:29:32 -07007054status_t AudioPolicyManager::resetOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurent6a94d692014-05-20 11:18:06 -07007055 int delayMs,
7056 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07007057{
Eric Laurent6a94d692014-05-20 11:18:06 -07007058 ssize_t index;
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02007059 if (patchHandle == nullptr && !outputDesc->isRouted()) {
7060 return INVALID_OPERATION;
7061 }
Eric Laurent6a94d692014-05-20 11:18:06 -07007062 if (patchHandle) {
7063 index = mAudioPatches.indexOfKey(*patchHandle);
7064 } else {
Jean-Michel Triviff155c62016-02-26 12:07:16 -08007065 index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007066 }
7067 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07007068 return INVALID_OPERATION;
7069 }
Eric Laurent6a94d692014-05-20 11:18:06 -07007070 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007071 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07007072 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07007073 outputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
François Gaffieafd4cea2019-11-18 15:50:22 +01007074 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007075 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07007076 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07007077 return status;
7078}
7079
7080status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
François Gaffie11d30102018-11-02 16:09:09 +01007081 const sp<DeviceDescriptor> &device,
Eric Laurent6a94d692014-05-20 11:18:06 -07007082 bool force,
7083 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07007084{
7085 status_t status = NO_ERROR;
7086
Eric Laurent1f2f2232014-06-02 12:01:23 -07007087 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
François Gaffie11d30102018-11-02 16:09:09 +01007088 if ((device != nullptr) && ((device != inputDesc->getDevice()) || force)) {
7089 inputDesc->setDevice(device);
Eric Laurent1c333e22014-05-20 10:48:17 -07007090
François Gaffie11d30102018-11-02 16:09:09 +01007091 if (mAvailableInputDevices.contains(device)) {
Mikhail Naganovdc769682018-05-04 15:34:08 -07007092 PatchBuilder patchBuilder;
7093 patchBuilder.addSink(inputDesc,
Eric Laurentdaf92cc2014-07-22 15:36:10 -07007094 // AUDIO_SOURCE_HOTWORD is for internal use only:
7095 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
Mikhail Naganovdc769682018-05-04 15:34:08 -07007096 [inputDesc](const PatchBuilder::mix_usecase_t& usecase) {
7097 auto result = usecase;
7098 if (result.source == AUDIO_SOURCE_HOTWORD && !inputDesc->isSoundTrigger()) {
7099 result.source = AUDIO_SOURCE_VOICE_RECOGNITION;
7100 }
7101 return result; }).
Eric Laurent1c333e22014-05-20 10:48:17 -07007102 //only one input device for now
François Gaffie11d30102018-11-02 16:09:09 +01007103 addSource(device);
Mikhail Naganovdc769682018-05-04 15:34:08 -07007104 status = installPatch(__func__, patchHandle, inputDesc.get(), patchBuilder.patch(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07007105 }
7106 }
7107 return status;
7108}
7109
Eric Laurent6a94d692014-05-20 11:18:06 -07007110status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
7111 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07007112{
Eric Laurent1f2f2232014-06-02 12:01:23 -07007113 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07007114 ssize_t index;
7115 if (patchHandle) {
7116 index = mAudioPatches.indexOfKey(*patchHandle);
7117 } else {
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08007118 index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007119 }
7120 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07007121 return INVALID_OPERATION;
7122 }
Eric Laurent6a94d692014-05-20 11:18:06 -07007123 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007124 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07007125 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07007126 inputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
François Gaffieafd4cea2019-11-18 15:50:22 +01007127 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007128 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07007129 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07007130 return status;
7131}
7132
François Gaffie11d30102018-11-02 16:09:09 +01007133sp<IOProfile> AudioPolicyManager::getInputProfile(const sp<DeviceDescriptor> &device,
François Gaffie53615e22015-03-19 09:24:12 +01007134 uint32_t& samplingRate,
Andy Hungf129b032015-04-07 13:45:50 -07007135 audio_format_t& format,
7136 audio_channel_mask_t& channelMask,
François Gaffie53615e22015-03-19 09:24:12 +01007137 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07007138{
7139 // Choose an input profile based on the requested capture parameters: select the first available
7140 // profile supporting all requested parameters.
Andy Hungf129b032015-04-07 13:45:50 -07007141 //
7142 // TODO: perhaps isCompatibleProfile should return a "matching" score so we can return
7143 // the best matching profile, not the first one.
Eric Laurente552edb2014-03-10 17:42:56 -07007144
Glenn Kasten730b9262018-03-29 15:01:26 -07007145 sp<IOProfile> firstInexact;
7146 uint32_t updatedSamplingRate = 0;
7147 audio_format_t updatedFormat = AUDIO_FORMAT_INVALID;
7148 audio_channel_mask_t updatedChannelMask = AUDIO_CHANNEL_INVALID;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08007149 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08007150 for (const auto& profile : hwModule->getInputProfiles()) {
Eric Laurentd4692962014-05-05 18:13:44 -07007151 // profile->log();
Glenn Kasten730b9262018-03-29 15:01:26 -07007152 //updatedFormat = format;
François Gaffie11d30102018-11-02 16:09:09 +01007153 if (profile->isCompatibleProfile(DeviceVector(device), samplingRate,
Glenn Kasten730b9262018-03-29 15:01:26 -07007154 &samplingRate /*updatedSamplingRate*/,
Andy Hungf129b032015-04-07 13:45:50 -07007155 format,
Glenn Kasten730b9262018-03-29 15:01:26 -07007156 &format, /*updatedFormat*/
Andy Hungf129b032015-04-07 13:45:50 -07007157 channelMask,
Glenn Kasten730b9262018-03-29 15:01:26 -07007158 &channelMask /*updatedChannelMask*/,
7159 // FIXME ugly cast
7160 (audio_output_flags_t) flags,
7161 true /*exactMatchRequiredForInputFlags*/)) {
Eric Laurente552edb2014-03-10 17:42:56 -07007162 return profile;
7163 }
François Gaffie11d30102018-11-02 16:09:09 +01007164 if (firstInexact == nullptr && profile->isCompatibleProfile(DeviceVector(device),
Glenn Kasten730b9262018-03-29 15:01:26 -07007165 samplingRate,
7166 &updatedSamplingRate,
7167 format,
7168 &updatedFormat,
7169 channelMask,
7170 &updatedChannelMask,
7171 // FIXME ugly cast
7172 (audio_output_flags_t) flags,
7173 false /*exactMatchRequiredForInputFlags*/)) {
7174 firstInexact = profile;
7175 }
7176
Eric Laurente552edb2014-03-10 17:42:56 -07007177 }
7178 }
Glenn Kasten730b9262018-03-29 15:01:26 -07007179 if (firstInexact != nullptr) {
7180 samplingRate = updatedSamplingRate;
7181 format = updatedFormat;
7182 channelMask = updatedChannelMask;
7183 return firstInexact;
7184 }
Eric Laurente552edb2014-03-10 17:42:56 -07007185 return NULL;
7186}
7187
François Gaffieaaac0fd2018-11-22 17:56:39 +01007188float AudioPolicyManager::computeVolume(IVolumeCurves &curves,
7189 VolumeSource volumeSource,
François Gaffied1ab2bd2015-12-02 18:20:06 +01007190 int index,
jiabin9a3361e2019-10-01 09:38:30 -07007191 const DeviceTypeSet& deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07007192{
jiabin9a3361e2019-10-01 09:38:30 -07007193 float volumeDb = curves.volIndexToDb(Volume::getDeviceCategory(deviceTypes), index);
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07007194
7195 // handle the case of accessibility active while a ringtone is playing: if the ringtone is much
7196 // louder than the accessibility prompt, the prompt cannot be heard, thus masking the touch
7197 // exploration of the dialer UI. In this situation, bring the accessibility volume closer to
7198 // the ringtone volume
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007199 const auto callVolumeSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL, false);
7200 const auto ringVolumeSrc = toVolumeSource(AUDIO_STREAM_RING, false);
7201 const auto musicVolumeSrc = toVolumeSource(AUDIO_STREAM_MUSIC, false);
7202 const auto alarmVolumeSrc = toVolumeSource(AUDIO_STREAM_ALARM, false);
7203 const auto a11yVolumeSrc = toVolumeSource(AUDIO_STREAM_ACCESSIBILITY, false);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007204
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07007205 if (volumeSource == a11yVolumeSrc
François Gaffieaaac0fd2018-11-22 17:56:39 +01007206 && (AUDIO_MODE_RINGTONE == mEngine->getPhoneState()) &&
7207 mOutputs.isActive(ringVolumeSrc, 0)) {
7208 auto &ringCurves = getVolumeCurves(AUDIO_STREAM_RING);
jiabin9a3361e2019-10-01 09:38:30 -07007209 const float ringVolumeDb = computeVolume(ringCurves, ringVolumeSrc, index, deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007210 return ringVolumeDb - 4 > volumeDb ? ringVolumeDb - 4 : volumeDb;
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07007211 }
7212
Eric Laurentdcd4ab12018-06-29 17:45:13 -07007213 // in-call: always cap volume by voice volume + some low headroom
François Gaffieaaac0fd2018-11-22 17:56:39 +01007214 if ((volumeSource != callVolumeSrc && (isInCall() ||
7215 mOutputs.isActiveLocally(callVolumeSrc))) &&
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007216 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM, false) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01007217 volumeSource == ringVolumeSrc || volumeSource == musicVolumeSrc ||
7218 volumeSource == alarmVolumeSrc ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007219 volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION, false) ||
7220 volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false) ||
7221 volumeSource == toVolumeSource(AUDIO_STREAM_DTMF, false) ||
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07007222 volumeSource == a11yVolumeSrc)) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007223 auto &voiceCurves = getVolumeCurves(callVolumeSrc);
jiabin9a3361e2019-10-01 09:38:30 -07007224 int voiceVolumeIndex = voiceCurves.getVolumeIndex(deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007225 const float maxVoiceVolDb =
jiabin9a3361e2019-10-01 09:38:30 -07007226 computeVolume(voiceCurves, callVolumeSrc, voiceVolumeIndex, deviceTypes)
Eric Laurent7731b5a2018-04-06 15:47:22 -07007227 + IN_CALL_EARPIECE_HEADROOM_DB;
Abhijith Shastry329ddab2019-04-23 11:53:26 -07007228 // FIXME: Workaround for call screening applications until a proper audio mode is defined
7229 // to support this scenario : Exempt the RING stream from the audio cap if the audio was
7230 // programmatically muted.
7231 // VOICE_CALL stream has minVolumeIndex > 0 : Users cannot set the volume of voice calls to
7232 // 0. We don't want to cap volume when the system has programmatically muted the voice call
7233 // stream. See setVolumeCurveIndex() for more information.
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07007234 bool exemptFromCapping =
7235 ((volumeSource == ringVolumeSrc) || (volumeSource == a11yVolumeSrc))
7236 && (voiceVolumeIndex == 0);
Abhijith Shastry329ddab2019-04-23 11:53:26 -07007237 ALOGV_IF(exemptFromCapping, "%s volume source %d at vol=%f not capped", __func__,
7238 volumeSource, volumeDb);
7239 if ((volumeDb > maxVoiceVolDb) && !exemptFromCapping) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007240 ALOGV("%s volume source %d at vol=%f overriden by volume group %d at vol=%f", __func__,
7241 volumeSource, volumeDb, callVolumeSrc, maxVoiceVolDb);
7242 volumeDb = maxVoiceVolDb;
Jean-Michel Trivi719a9872017-08-05 13:51:35 -07007243 }
7244 }
Eric Laurente552edb2014-03-10 17:42:56 -07007245 // if a headset is connected, apply the following rules to ring tones and notifications
7246 // to avoid sound level bursts in user's ears:
Eric Laurent6af1c1d2016-04-14 11:20:44 -07007247 // - always attenuate notifications volume by 6dB
7248 // - attenuate ring tones volume by 6dB unless music is not playing and
7249 // speaker is part of the select devices
Eric Laurente552edb2014-03-10 17:42:56 -07007250 // - if music is playing, always limit the volume to current music volume,
7251 // with a minimum threshold at -36dB so that notification is always perceived.
jiabin9a3361e2019-10-01 09:38:30 -07007252 if (!Intersection(deviceTypes,
7253 {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP, AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES,
7254 AUDIO_DEVICE_OUT_WIRED_HEADSET, AUDIO_DEVICE_OUT_WIRED_HEADPHONE,
Eric Laurentc42df452020-08-07 10:51:53 -07007255 AUDIO_DEVICE_OUT_USB_HEADSET, AUDIO_DEVICE_OUT_HEARING_AID,
7256 AUDIO_DEVICE_OUT_BLE_HEADSET}).empty() &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01007257 ((volumeSource == alarmVolumeSrc ||
7258 volumeSource == ringVolumeSrc) ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007259 (volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION, false)) ||
7260 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM, false)) ||
7261 ((volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false)) &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01007262 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) &&
7263 curves.canBeMuted()) {
7264
Eric Laurente552edb2014-03-10 17:42:56 -07007265 // when the phone is ringing we must consider that music could have been paused just before
7266 // by the music application and behave as if music was active if the last music track was
7267 // just stopped
Eric Laurent3b73df72014-03-11 09:06:29 -07007268 if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY) ||
Eric Laurente552edb2014-03-10 17:42:56 -07007269 mLimitRingtoneVolume) {
François Gaffie43c73442018-11-08 08:21:55 +01007270 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
jiabin9a3361e2019-10-01 09:38:30 -07007271 DeviceTypeSet musicDevice =
François Gaffiec005e562018-11-06 15:04:49 +01007272 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
7273 nullptr, true /*fromCache*/).types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01007274 auto &musicCurves = getVolumeCurves(AUDIO_STREAM_MUSIC);
jiabin9a3361e2019-10-01 09:38:30 -07007275 float musicVolDb = computeVolume(musicCurves,
7276 musicVolumeSrc,
7277 musicCurves.getVolumeIndex(musicDevice),
7278 musicDevice);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007279 float minVolDb = (musicVolDb > SONIFICATION_HEADSET_VOLUME_MIN_DB) ?
7280 musicVolDb : SONIFICATION_HEADSET_VOLUME_MIN_DB;
7281 if (volumeDb > minVolDb) {
7282 volumeDb = minVolDb;
7283 ALOGV("computeVolume limiting volume to %f musicVol %f", minVolDb, musicVolDb);
Eric Laurente552edb2014-03-10 17:42:56 -07007284 }
Eric Laurent7b6385c2021-05-12 17:55:36 +02007285 if (Volume::getDeviceForVolume(deviceTypes) != AUDIO_DEVICE_OUT_SPEAKER
7286 && !Intersection(deviceTypes, {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP,
7287 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES}).empty()) {
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07007288 // on A2DP, also ensure notification volume is not too low compared to media when
7289 // intended to be played
François Gaffie43c73442018-11-08 08:21:55 +01007290 if ((volumeDb > -96.0f) &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01007291 (musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB > volumeDb)) {
jiabin9a3361e2019-10-01 09:38:30 -07007292 ALOGV("%s increasing volume for volume source=%d device=%s from %f to %f",
7293 __func__, volumeSource, dumpDeviceTypes(deviceTypes).c_str(), volumeDb,
François Gaffieaaac0fd2018-11-22 17:56:39 +01007294 musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB);
7295 volumeDb = musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB;
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07007296 }
7297 }
jiabin9a3361e2019-10-01 09:38:30 -07007298 } else if ((Volume::getDeviceForVolume(deviceTypes) != AUDIO_DEVICE_OUT_SPEAKER) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01007299 (!(volumeSource == alarmVolumeSrc || volumeSource == ringVolumeSrc))) {
François Gaffie43c73442018-11-08 08:21:55 +01007300 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07007301 }
7302 }
7303
François Gaffie43c73442018-11-08 08:21:55 +01007304 return volumeDb;
Eric Laurente552edb2014-03-10 17:42:56 -07007305}
7306
Eric Laurent3839bc02018-07-10 18:33:34 -07007307int AudioPolicyManager::rescaleVolumeIndex(int srcIndex,
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01007308 VolumeSource fromVolumeSource,
7309 VolumeSource toVolumeSource)
Eric Laurent3839bc02018-07-10 18:33:34 -07007310{
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01007311 if (fromVolumeSource == toVolumeSource) {
Eric Laurent3839bc02018-07-10 18:33:34 -07007312 return srcIndex;
7313 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01007314 auto &srcCurves = getVolumeCurves(fromVolumeSource);
7315 auto &dstCurves = getVolumeCurves(toVolumeSource);
Eric Laurentf5aa58d2019-02-22 18:20:11 -08007316 float minSrc = (float)srcCurves.getVolumeIndexMin();
7317 float maxSrc = (float)srcCurves.getVolumeIndexMax();
7318 float minDst = (float)dstCurves.getVolumeIndexMin();
7319 float maxDst = (float)dstCurves.getVolumeIndexMax();
Eric Laurent3839bc02018-07-10 18:33:34 -07007320
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08007321 // preserve mute request or correct range
7322 if (srcIndex < minSrc) {
7323 if (srcIndex == 0) {
7324 return 0;
7325 }
7326 srcIndex = minSrc;
7327 } else if (srcIndex > maxSrc) {
7328 srcIndex = maxSrc;
7329 }
Eric Laurent3839bc02018-07-10 18:33:34 -07007330 return (int)(minDst + ((srcIndex - minSrc) * (maxDst - minDst)) / (maxSrc - minSrc));
7331}
7332
François Gaffieaaac0fd2018-11-22 17:56:39 +01007333status_t AudioPolicyManager::checkAndSetVolume(IVolumeCurves &curves,
7334 VolumeSource volumeSource,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08007335 int index,
7336 const sp<AudioOutputDescriptor>& outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07007337 DeviceTypeSet deviceTypes,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08007338 int delayMs,
7339 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07007340{
François Gaffieaaac0fd2018-11-22 17:56:39 +01007341 // do not change actual attributes volume if the attributes is muted
7342 if (outputDesc->isMuted(volumeSource)) {
7343 ALOGVV("%s: volume source %d muted count %d active=%d", __func__, volumeSource,
7344 outputDesc->getMuteCount(volumeSource), outputDesc->isActive(volumeSource));
Eric Laurente552edb2014-03-10 17:42:56 -07007345 return NO_ERROR;
7346 }
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007347 VolumeSource callVolSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL, false);
7348 VolumeSource btScoVolSrc = toVolumeSource(AUDIO_STREAM_BLUETOOTH_SCO, false);
7349 bool isVoiceVolSrc = (volumeSource != VOLUME_SOURCE_NONE) && (callVolSrc == volumeSource);
7350 bool isBtScoVolSrc = (volumeSource != VOLUME_SOURCE_NONE) && (btScoVolSrc == volumeSource);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007351
Eric Laurent2517af32020-11-25 15:31:27 +01007352 bool isScoRequested = isScoRequestedForComm();
Eric Laurent1a8b45f2022-04-13 16:01:47 +02007353 bool isHAUsed = isHearingAidUsedForComm();
7354
Eric Laurente552edb2014-03-10 17:42:56 -07007355 // do not change in call volume if bluetooth is connected and vice versa
François Gaffieaaac0fd2018-11-22 17:56:39 +01007356 // if sco and call follow same curves, bypass forceUseForComm
7357 if ((callVolSrc != btScoVolSrc) &&
Eric Laurent2517af32020-11-25 15:31:27 +01007358 ((isVoiceVolSrc && isScoRequested) ||
Beibeif660a512023-02-28 17:00:34 +08007359 (isBtScoVolSrc && !(isScoRequested || isHAUsed))) &&
7360 !isSingleDeviceType(deviceTypes, AUDIO_DEVICE_OUT_TELEPHONY_TX)) {
Eric Laurent2517af32020-11-25 15:31:27 +01007361 ALOGV("%s cannot set volume group %d volume when is%srequested for comm", __func__,
Eric Laurent1a8b45f2022-04-13 16:01:47 +02007362 volumeSource, isScoRequested ? " " : " not ");
Eric Laurent571ef962020-07-24 11:43:48 -07007363 // Do not return an error here as AudioService will always set both voice call
7364 // and bluetooth SCO volumes due to stream aliasing.
7365 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07007366 }
jiabin9a3361e2019-10-01 09:38:30 -07007367 if (deviceTypes.empty()) {
7368 deviceTypes = outputDesc->devices().types();
Eric Laurentc75307b2015-03-17 15:29:32 -07007369 }
Eric Laurent275e8e92014-11-30 15:14:47 -08007370
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00007371 if (curves.getVolumeIndexMin() < 0 || curves.getVolumeIndexMax() < 0) {
7372 ALOGE("invalid volume index range");
7373 return BAD_VALUE;
7374 }
7375
jiabin9a3361e2019-10-01 09:38:30 -07007376 float volumeDb = computeVolume(curves, volumeSource, index, deviceTypes);
7377 if (outputDesc->isFixedVolume(deviceTypes) ||
Eric Laurent9698a4c2020-10-12 17:10:23 -07007378 // Force VoIP volume to max for bluetooth SCO device except if muted
7379 (index != 0 && (isVoiceVolSrc || isBtScoVolSrc) &&
jiabin9a3361e2019-10-01 09:38:30 -07007380 isSingleDeviceType(deviceTypes, audio_is_bluetooth_out_sco_device))) {
Eric Laurentffbc80f2015-03-18 18:30:19 -07007381 volumeDb = 0.0f;
Eric Laurent275e8e92014-11-30 15:14:47 -08007382 }
Francois Gaffie593634d2021-06-22 13:31:31 +02007383 const bool muted = (index == 0) && (volumeDb != 0.0f);
jiabin9a3361e2019-10-01 09:38:30 -07007384 outputDesc->setVolume(
Francois Gaffie593634d2021-06-22 13:31:31 +02007385 volumeDb, muted, volumeSource, curves.getStreamTypes(), deviceTypes, delayMs, force);
Eric Laurentc75307b2015-03-17 15:29:32 -07007386
Eric Laurente8f2c0f2021-08-17 11:17:19 +02007387 if (outputDesc == mPrimaryOutput && (isVoiceVolSrc || isBtScoVolSrc)) {
Eric Laurente552edb2014-03-10 17:42:56 -07007388 float voiceVolume;
Eric Laurentfad001d2019-06-11 19:17:57 -07007389 // 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 +01007390 if (isVoiceVolSrc) {
7391 voiceVolume = (float)index/(float)curves.getVolumeIndexMax();
Eric Laurente552edb2014-03-10 17:42:56 -07007392 } else {
Eric Laurentfad001d2019-06-11 19:17:57 -07007393 voiceVolume = index == 0 ? 0.0 : 1.0;
Eric Laurente552edb2014-03-10 17:42:56 -07007394 }
Eric Laurent18fba842016-03-31 14:41:26 -07007395 if (voiceVolume != mLastVoiceVolume) {
Eric Laurente552edb2014-03-10 17:42:56 -07007396 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
7397 mLastVoiceVolume = voiceVolume;
7398 }
7399 }
Eric Laurente552edb2014-03-10 17:42:56 -07007400 return NO_ERROR;
7401}
7402
Eric Laurentc75307b2015-03-17 15:29:32 -07007403void AudioPolicyManager::applyStreamVolumes(const sp<AudioOutputDescriptor>& outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07007404 const DeviceTypeSet& deviceTypes,
7405 int delayMs,
7406 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07007407{
jiabincd510522020-01-22 09:40:55 -08007408 ALOGVV("applyStreamVolumes() for device %s", dumpDeviceTypes(deviceTypes).c_str());
François Gaffieaaac0fd2018-11-22 17:56:39 +01007409 for (const auto &volumeGroup : mEngine->getVolumeGroups()) {
7410 auto &curves = getVolumeCurves(toVolumeSource(volumeGroup));
7411 checkAndSetVolume(curves, toVolumeSource(volumeGroup),
jiabin9a3361e2019-10-01 09:38:30 -07007412 curves.getVolumeIndex(deviceTypes),
7413 outputDesc, deviceTypes, delayMs, force);
Eric Laurente552edb2014-03-10 17:42:56 -07007414 }
7415}
7416
François Gaffiec005e562018-11-06 15:04:49 +01007417void AudioPolicyManager::setStrategyMute(product_strategy_t strategy,
7418 bool on,
7419 const sp<AudioOutputDescriptor>& outputDesc,
7420 int delayMs,
jiabin9a3361e2019-10-01 09:38:30 -07007421 DeviceTypeSet deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07007422{
François Gaffieaaac0fd2018-11-22 17:56:39 +01007423 std::vector<VolumeSource> sourcesToMute;
7424 for (auto attributes: mEngine->getAllAttributesForProductStrategy(strategy)) {
7425 ALOGVV("%s() attributes %s, mute %d, output ID %d", __func__,
7426 toString(attributes).c_str(), on, outputDesc->getId());
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007427 VolumeSource source = toVolumeSource(attributes, false);
7428 if ((source != VOLUME_SOURCE_NONE) &&
7429 (std::find(begin(sourcesToMute), end(sourcesToMute), source)
7430 == end(sourcesToMute))) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007431 sourcesToMute.push_back(source);
7432 }
Eric Laurente552edb2014-03-10 17:42:56 -07007433 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01007434 for (auto source : sourcesToMute) {
jiabin9a3361e2019-10-01 09:38:30 -07007435 setVolumeSourceMute(source, on, outputDesc, delayMs, deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007436 }
7437
Eric Laurente552edb2014-03-10 17:42:56 -07007438}
7439
François Gaffieaaac0fd2018-11-22 17:56:39 +01007440void AudioPolicyManager::setVolumeSourceMute(VolumeSource volumeSource,
7441 bool on,
7442 const sp<AudioOutputDescriptor>& outputDesc,
7443 int delayMs,
jiabin9a3361e2019-10-01 09:38:30 -07007444 DeviceTypeSet deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07007445{
jiabin9a3361e2019-10-01 09:38:30 -07007446 if (deviceTypes.empty()) {
7447 deviceTypes = outputDesc->devices().types();
Eric Laurente552edb2014-03-10 17:42:56 -07007448 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01007449 auto &curves = getVolumeCurves(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07007450 if (on) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007451 if (!outputDesc->isMuted(volumeSource)) {
Eric Laurentf5aa58d2019-02-22 18:20:11 -08007452 if (curves.canBeMuted() &&
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007453 (volumeSource != toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01007454 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) ==
7455 AUDIO_POLICY_FORCE_NONE))) {
jiabin9a3361e2019-10-01 09:38:30 -07007456 checkAndSetVolume(curves, volumeSource, 0, outputDesc, deviceTypes, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07007457 }
7458 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01007459 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not
7460 // ignored
7461 outputDesc->incMuteCount(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07007462 } else {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007463 if (!outputDesc->isMuted(volumeSource)) {
7464 ALOGV("%s unmuting non muted attributes!", __func__);
Eric Laurente552edb2014-03-10 17:42:56 -07007465 return;
7466 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01007467 if (outputDesc->decMuteCount(volumeSource) == 0) {
7468 checkAndSetVolume(curves, volumeSource,
jiabin9a3361e2019-10-01 09:38:30 -07007469 curves.getVolumeIndex(deviceTypes),
Eric Laurentc75307b2015-03-17 15:29:32 -07007470 outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07007471 deviceTypes,
Eric Laurente552edb2014-03-10 17:42:56 -07007472 delayMs);
7473 }
7474 }
7475}
7476
François Gaffie53615e22015-03-19 09:24:12 +01007477bool AudioPolicyManager::isValidAttributes(const audio_attributes_t *paa)
7478{
François Gaffiec005e562018-11-06 15:04:49 +01007479 // has flags that map to a stream type?
Eric Laurente83b55d2014-11-14 10:06:21 -08007480 if ((paa->flags & (AUDIO_FLAG_AUDIBILITY_ENFORCED | AUDIO_FLAG_SCO | AUDIO_FLAG_BEACON)) != 0) {
7481 return true;
7482 }
7483
7484 // has known usage?
7485 switch (paa->usage) {
7486 case AUDIO_USAGE_UNKNOWN:
7487 case AUDIO_USAGE_MEDIA:
7488 case AUDIO_USAGE_VOICE_COMMUNICATION:
7489 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
7490 case AUDIO_USAGE_ALARM:
7491 case AUDIO_USAGE_NOTIFICATION:
7492 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
7493 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
7494 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
7495 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
7496 case AUDIO_USAGE_NOTIFICATION_EVENT:
7497 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
7498 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
7499 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
7500 case AUDIO_USAGE_GAME:
Eric Laurent275e8e92014-11-30 15:14:47 -08007501 case AUDIO_USAGE_VIRTUAL_SOURCE:
Jean-Michel Trivi36867762016-12-29 12:03:28 -08007502 case AUDIO_USAGE_ASSISTANT:
Eric Laurent21777f82019-12-06 18:12:06 -08007503 case AUDIO_USAGE_CALL_ASSISTANT:
Hayden Gomes524159d2019-12-23 14:41:47 -08007504 case AUDIO_USAGE_EMERGENCY:
7505 case AUDIO_USAGE_SAFETY:
7506 case AUDIO_USAGE_VEHICLE_STATUS:
7507 case AUDIO_USAGE_ANNOUNCEMENT:
Eric Laurente83b55d2014-11-14 10:06:21 -08007508 break;
7509 default:
7510 return false;
7511 }
7512 return true;
7513}
7514
François Gaffie2110e042015-03-24 08:41:51 +01007515audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
7516{
7517 return mEngine->getForceUse(usage);
7518}
7519
Eric Laurent96d1dda2022-03-14 17:14:19 +01007520bool AudioPolicyManager::isInCall() const {
François Gaffie2110e042015-03-24 08:41:51 +01007521 return isStateInCall(mEngine->getPhoneState());
7522}
7523
Eric Laurent96d1dda2022-03-14 17:14:19 +01007524bool AudioPolicyManager::isStateInCall(int state) const {
François Gaffie2110e042015-03-24 08:41:51 +01007525 return is_state_in_call(state);
7526}
7527
Eric Laurentf9cccec2022-11-16 19:12:00 +01007528bool AudioPolicyManager::isCallAudioAccessible() const {
Eric Laurent74b71512019-11-06 17:21:57 -08007529 audio_mode_t mode = mEngine->getPhoneState();
7530 return (mode == AUDIO_MODE_IN_CALL)
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01007531 || (mode == AUDIO_MODE_CALL_SCREEN)
7532 || (mode == AUDIO_MODE_CALL_REDIRECT);
Eric Laurent74b71512019-11-06 17:21:57 -08007533}
7534
Eric Laurentf9cccec2022-11-16 19:12:00 +01007535bool AudioPolicyManager::isInCallOrScreening() const {
7536 audio_mode_t mode = mEngine->getPhoneState();
7537 return isStateInCall(mode) || mode == AUDIO_MODE_CALL_SCREEN;
7538}
7539
Eric Laurentd60560a2015-04-10 11:31:20 -07007540void AudioPolicyManager::cleanUpForDevice(const sp<DeviceDescriptor>& deviceDesc)
7541{
7542 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07007543 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02007544 if (sourceDesc->isConnected() && (sourceDesc->srcDevice()->equals(deviceDesc) ||
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02007545 sourceDesc->sinkDevice()->equals(deviceDesc))
7546 && !isCallRxAudioSource(sourceDesc)) {
Francois Gaffiea0e5c992020-09-29 16:05:07 +02007547 disconnectAudioSource(sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07007548 }
7549 }
7550
7551 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
7552 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
7553 bool release = false;
7554 for (size_t j = 0; j < patchDesc->mPatch.num_sources && !release; j++) {
7555 const struct audio_port_config *source = &patchDesc->mPatch.sources[j];
7556 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
7557 source->ext.device.type == deviceDesc->type()) {
7558 release = true;
7559 }
7560 }
Francois Gaffiea0e5c992020-09-29 16:05:07 +02007561 const char *address = deviceDesc->address().c_str();
Eric Laurentd60560a2015-04-10 11:31:20 -07007562 for (size_t j = 0; j < patchDesc->mPatch.num_sinks && !release; j++) {
7563 const struct audio_port_config *sink = &patchDesc->mPatch.sinks[j];
7564 if (sink->type == AUDIO_PORT_TYPE_DEVICE &&
Francois Gaffiea0e5c992020-09-29 16:05:07 +02007565 sink->ext.device.type == deviceDesc->type() &&
7566 (strnlen(address, AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0
7567 || strncmp(sink->ext.device.address, address,
7568 AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0)) {
Eric Laurentd60560a2015-04-10 11:31:20 -07007569 release = true;
7570 }
7571 }
7572 if (release) {
François Gaffieafd4cea2019-11-18 15:50:22 +01007573 ALOGV("%s releasing patch %u", __FUNCTION__, patchDesc->getHandle());
7574 releaseAudioPatch(patchDesc->getHandle(), patchDesc->getUid());
Eric Laurentd60560a2015-04-10 11:31:20 -07007575 }
7576 }
Francois Gaffie716e1432019-01-14 16:58:59 +01007577
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01007578 mInputs.clearSessionRoutesForDevice(deviceDesc);
7579
Francois Gaffie716e1432019-01-14 16:58:59 +01007580 mHwModules.cleanUpForDevice(deviceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07007581}
7582
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007583void AudioPolicyManager::modifySurroundFormats(
7584 const sp<DeviceDescriptor>& devDesc, FormatVector *formatsPtr) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007585 std::unordered_set<audio_format_t> enforcedSurround(
7586 devDesc->encodedFormats().begin(), devDesc->encodedFormats().end());
Mikhail Naganov100f0122018-11-29 11:22:16 -08007587 std::unordered_set<audio_format_t> allSurround; // A flat set of all known surround formats
Mikhail Naganovb0fbc1b2023-04-28 13:06:32 -07007588 for (const auto& pair : mConfig->getSurroundFormats()) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08007589 allSurround.insert(pair.first);
7590 for (const auto& subformat : pair.second) allSurround.insert(subformat);
7591 }
Phil Burk09bc4612016-02-24 15:58:15 -08007592
7593 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
7594 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Phil Burk0709b0a2016-03-31 12:54:57 -07007595 ALOGD("%s: forced use = %d", __FUNCTION__, forceUse);
Mikhail Naganov100f0122018-11-29 11:22:16 -08007596 // This is the resulting set of formats depending on the surround mode:
7597 // 'all surround' = allSurround
7598 // 'enforced surround' = enforcedSurround [may include IEC69137 which isn't raw surround fmt]
7599 // 'non-surround' = not in 'all surround' and not in 'enforced surround'
7600 // 'manual surround' = mManualSurroundFormats
7601 // AUTO: formats v 'enforced surround'
7602 // ALWAYS: formats v 'all surround' v 'enforced surround'
7603 // NEVER: formats ^ 'non-surround'
7604 // MANUAL: formats ^ ('non-surround' v 'manual surround' v (IEC69137 ^ 'enforced surround'))
Phil Burk09bc4612016-02-24 15:58:15 -08007605
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007606 std::unordered_set<audio_format_t> formatSet;
7607 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL
7608 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08007609 // formatSet is (formats ^ 'non-surround')
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007610 for (auto formatIter = formatsPtr->begin(); formatIter != formatsPtr->end(); ++formatIter) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08007611 if (allSurround.count(*formatIter) == 0 && enforcedSurround.count(*formatIter) == 0) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007612 formatSet.insert(*formatIter);
7613 }
7614 }
7615 } else {
7616 formatSet.insert(formatsPtr->begin(), formatsPtr->end());
7617 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08007618 formatsPtr->clear(); // Re-filled from the formatSet at the end.
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007619
jiabin81772902018-04-02 17:52:27 -07007620 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08007621 formatSet.insert(mManualSurroundFormats.begin(), mManualSurroundFormats.end());
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007622 // Enable IEC61937 when in MANUAL mode if it's enforced for this device.
7623 if (enforcedSurround.count(AUDIO_FORMAT_IEC61937) != 0) {
7624 formatSet.insert(AUDIO_FORMAT_IEC61937);
Phil Burk09bc4612016-02-24 15:58:15 -08007625 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08007626 } else if (forceUse != AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) { // AUTO or ALWAYS
7627 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS) {
7628 formatSet.insert(allSurround.begin(), allSurround.end());
Phil Burk07ac1142016-03-25 13:39:29 -07007629 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08007630 formatSet.insert(enforcedSurround.begin(), enforcedSurround.end());
Phil Burk09bc4612016-02-24 15:58:15 -08007631 }
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007632 for (const auto& format : formatSet) {
jiabin06e4bab2019-07-29 10:13:34 -07007633 formatsPtr->push_back(format);
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007634 }
Phil Burk0709b0a2016-03-31 12:54:57 -07007635}
7636
jiabin06e4bab2019-07-29 10:13:34 -07007637void AudioPolicyManager::modifySurroundChannelMasks(ChannelMaskSet *channelMasksPtr) {
7638 ChannelMaskSet &channelMasks = *channelMasksPtr;
Phil Burk0709b0a2016-03-31 12:54:57 -07007639 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
7640 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
7641
7642 // If NEVER, then remove support for channelMasks > stereo.
7643 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
jiabin06e4bab2019-07-29 10:13:34 -07007644 for (auto it = channelMasks.begin(); it != channelMasks.end();) {
7645 audio_channel_mask_t channelMask = *it;
Phil Burk0709b0a2016-03-31 12:54:57 -07007646 if (channelMask & ~AUDIO_CHANNEL_OUT_STEREO) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01007647 ALOGV("%s: force NEVER, so remove channelMask 0x%08x", __FUNCTION__, channelMask);
jiabin06e4bab2019-07-29 10:13:34 -07007648 it = channelMasks.erase(it);
Phil Burk0709b0a2016-03-31 12:54:57 -07007649 } else {
jiabin06e4bab2019-07-29 10:13:34 -07007650 ++it;
Phil Burk0709b0a2016-03-31 12:54:57 -07007651 }
7652 }
jiabin81772902018-04-02 17:52:27 -07007653 // If ALWAYS or MANUAL, then make sure we at least support 5.1
7654 } else if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS
7655 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Phil Burk0709b0a2016-03-31 12:54:57 -07007656 bool supports5dot1 = false;
7657 // Are there any channel masks that can be considered "surround"?
Mikhail Naganovcf84e592017-12-07 11:25:11 -08007658 for (audio_channel_mask_t channelMask : channelMasks) {
Phil Burk0709b0a2016-03-31 12:54:57 -07007659 if ((channelMask & AUDIO_CHANNEL_OUT_5POINT1) == AUDIO_CHANNEL_OUT_5POINT1) {
7660 supports5dot1 = true;
7661 break;
7662 }
7663 }
7664 // If not then add 5.1 support.
7665 if (!supports5dot1) {
jiabin06e4bab2019-07-29 10:13:34 -07007666 channelMasks.insert(AUDIO_CHANNEL_OUT_5POINT1);
Eric Laurentfecbceb2021-02-09 14:46:43 +01007667 ALOGV("%s: force MANUAL or ALWAYS, so adding channelMask for 5.1 surround", __func__);
Phil Burk0709b0a2016-03-31 12:54:57 -07007668 }
Phil Burk09bc4612016-02-24 15:58:15 -08007669 }
7670}
7671
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007672void AudioPolicyManager::updateAudioProfiles(const sp<DeviceDescriptor>& devDesc,
Phil Burk00eeb322016-03-31 12:41:00 -07007673 audio_io_handle_t ioHandle,
François Gaffie112b0af2015-11-19 16:13:25 +01007674 AudioProfileVector &profiles)
7675{
7676 String8 reply;
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007677 audio_devices_t device = devDesc->type();
Phil Burk0709b0a2016-03-31 12:54:57 -07007678
François Gaffie112b0af2015-11-19 16:13:25 +01007679 // Format MUST be checked first to update the list of AudioProfile
7680 if (profiles.hasDynamicFormat()) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07007681 reply = mpClientInterface->getParameters(
7682 ioHandle, String8(AudioParameter::keyStreamSupportedFormats));
jiabin81772902018-04-02 17:52:27 -07007683 ALOGV("%s: supported formats %d, %s", __FUNCTION__, ioHandle, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08007684 AudioParameter repliedParameters(reply);
jiabinf26596b2023-04-12 18:56:39 +00007685 FormatVector formats;
Eric Laurent62e4bc52016-02-02 18:37:28 -08007686 if (repliedParameters.get(
jiabinf26596b2023-04-12 18:56:39 +00007687 String8(AudioParameter::keyStreamSupportedFormats), reply) == NO_ERROR) {
7688 formats = formatsFromString(reply.string());
7689 } else if (devDesc->hasValidAudioProfile()) {
7690 ALOGD("%s: using the device profiles", __func__);
7691 formats = devDesc->getAudioProfiles().getSupportedFormats();
7692 } else {
7693 ALOGE("%s: failed to retrieve format, bailing out", __func__);
François Gaffie112b0af2015-11-19 16:13:25 +01007694 return;
7695 }
Kriti Dangef6be8f2020-11-05 11:58:19 +01007696 mReportedFormatsMap[devDesc] = formats;
Mikhail Naganov100f0122018-11-29 11:22:16 -08007697 if (device == AUDIO_DEVICE_OUT_HDMI
7698 || isDeviceOfModule(devDesc, AUDIO_HARDWARE_MODULE_ID_MSD)) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007699 modifySurroundFormats(devDesc, &formats);
Phil Burk00eeb322016-03-31 12:41:00 -07007700 }
jiabin3e277cc2019-09-10 14:27:34 -07007701 addProfilesForFormats(profiles, formats);
François Gaffie112b0af2015-11-19 16:13:25 +01007702 }
François Gaffie112b0af2015-11-19 16:13:25 +01007703
Mikhail Naganovcf84e592017-12-07 11:25:11 -08007704 for (audio_format_t format : profiles.getSupportedFormats()) {
jiabinf26596b2023-04-12 18:56:39 +00007705 std::optional<ChannelMaskSet> channelMasks;
jiabin06e4bab2019-07-29 10:13:34 -07007706 SampleRateSet samplingRates;
François Gaffie112b0af2015-11-19 16:13:25 +01007707 AudioParameter requestedParameters;
Mikhail Naganov388360c2016-10-17 17:09:41 -07007708 requestedParameters.addInt(String8(AudioParameter::keyFormat), format);
François Gaffie112b0af2015-11-19 16:13:25 +01007709
7710 if (profiles.hasDynamicRateFor(format)) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07007711 reply = mpClientInterface->getParameters(
7712 ioHandle,
7713 requestedParameters.toString() + ";" +
7714 AudioParameter::keyStreamSupportedSamplingRates);
François Gaffie112b0af2015-11-19 16:13:25 +01007715 ALOGV("%s: supported sampling rates %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08007716 AudioParameter repliedParameters(reply);
7717 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07007718 String8(AudioParameter::keyStreamSupportedSamplingRates), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08007719 samplingRates = samplingRatesFromString(reply.string());
jiabinf26596b2023-04-12 18:56:39 +00007720 } else {
7721 samplingRates = devDesc->getAudioProfiles().getSampleRatesFor(format);
François Gaffie112b0af2015-11-19 16:13:25 +01007722 }
7723 }
7724 if (profiles.hasDynamicChannelsFor(format)) {
7725 reply = mpClientInterface->getParameters(ioHandle,
7726 requestedParameters.toString() + ";" +
Mikhail Naganov388360c2016-10-17 17:09:41 -07007727 AudioParameter::keyStreamSupportedChannels);
François Gaffie112b0af2015-11-19 16:13:25 +01007728 ALOGV("%s: supported channel masks %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08007729 AudioParameter repliedParameters(reply);
7730 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07007731 String8(AudioParameter::keyStreamSupportedChannels), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08007732 channelMasks = channelMasksFromString(reply.string());
jiabinf26596b2023-04-12 18:56:39 +00007733 } else {
7734 channelMasks = devDesc->getAudioProfiles().getChannelMasksFor(format);
7735 }
7736 if (channelMasks.has_value() && (device == AUDIO_DEVICE_OUT_HDMI
7737 || isDeviceOfModule(devDesc, AUDIO_HARDWARE_MODULE_ID_MSD))) {
7738 modifySurroundChannelMasks(&channelMasks.value());
François Gaffie112b0af2015-11-19 16:13:25 +01007739 }
7740 }
jiabin3e277cc2019-09-10 14:27:34 -07007741 addDynamicAudioProfileAndSort(
jiabinf26596b2023-04-12 18:56:39 +00007742 profiles, new AudioProfile(
7743 format, channelMasks.value_or(ChannelMaskSet()), samplingRates));
François Gaffie112b0af2015-11-19 16:13:25 +01007744 }
7745}
Eric Laurentd60560a2015-04-10 11:31:20 -07007746
Mikhail Naganovdc769682018-05-04 15:34:08 -07007747status_t AudioPolicyManager::installPatch(const char *caller,
7748 audio_patch_handle_t *patchHandle,
7749 AudioIODescriptorInterface *ioDescriptor,
7750 const struct audio_patch *patch,
7751 int delayMs)
7752{
7753 ssize_t index = mAudioPatches.indexOfKey(
7754 patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE ?
7755 *patchHandle : ioDescriptor->getPatchHandle());
7756 sp<AudioPatch> patchDesc;
7757 status_t status = installPatch(
7758 caller, index, patchHandle, patch, delayMs, mUidCached, &patchDesc);
7759 if (status == NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01007760 ioDescriptor->setPatchHandle(patchDesc->getHandle());
Mikhail Naganovdc769682018-05-04 15:34:08 -07007761 }
7762 return status;
7763}
7764
7765status_t AudioPolicyManager::installPatch(const char *caller,
7766 ssize_t index,
7767 audio_patch_handle_t *patchHandle,
7768 const struct audio_patch *patch,
7769 int delayMs,
7770 uid_t uid,
7771 sp<AudioPatch> *patchDescPtr)
7772{
7773 sp<AudioPatch> patchDesc;
7774 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
7775 if (index >= 0) {
7776 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007777 afPatchHandle = patchDesc->getAfHandle();
Mikhail Naganovdc769682018-05-04 15:34:08 -07007778 }
7779
7780 status_t status = mpClientInterface->createAudioPatch(patch, &afPatchHandle, delayMs);
7781 ALOGV("%s() AF::createAudioPatch returned %d patchHandle %d num_sources %d num_sinks %d",
7782 caller, status, afPatchHandle, patch->num_sources, patch->num_sinks);
7783 if (status == NO_ERROR) {
7784 if (index < 0) {
7785 patchDesc = new AudioPatch(patch, uid);
François Gaffieafd4cea2019-11-18 15:50:22 +01007786 addAudioPatch(patchDesc->getHandle(), patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07007787 } else {
7788 patchDesc->mPatch = *patch;
7789 }
François Gaffieafd4cea2019-11-18 15:50:22 +01007790 patchDesc->setAfHandle(afPatchHandle);
Mikhail Naganovdc769682018-05-04 15:34:08 -07007791 if (patchHandle) {
François Gaffieafd4cea2019-11-18 15:50:22 +01007792 *patchHandle = patchDesc->getHandle();
Mikhail Naganovdc769682018-05-04 15:34:08 -07007793 }
7794 nextAudioPortGeneration();
7795 mpClientInterface->onAudioPatchListUpdate();
7796 }
7797 if (patchDescPtr) *patchDescPtr = patchDesc;
7798 return status;
7799}
7800
jiabinbce0c1d2020-10-05 11:20:18 -07007801bool AudioPolicyManager::areAllActiveTracksRerouted(const sp<SwAudioOutputDescriptor>& output)
7802{
7803 const TrackClientVector activeClients = output->getActiveClients();
7804 if (activeClients.empty()) {
7805 return true;
7806 }
7807 ssize_t index = mAudioPatches.indexOfKey(output->getPatchHandle());
7808 if (index < 0) {
7809 ALOGE("%s, no audio patch found while there are active clients on output %d",
7810 __func__, output->getId());
7811 return false;
7812 }
7813 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
7814 DeviceVector routedDevices;
7815 for (int i = 0; i < patchDesc->mPatch.num_sinks; ++i) {
7816 sp<DeviceDescriptor> device = mAvailableOutputDevices.getDeviceFromId(
7817 patchDesc->mPatch.sinks[i].id);
7818 if (device == nullptr) {
7819 ALOGE("%s, no audio device found with id(%d)",
7820 __func__, patchDesc->mPatch.sinks[i].id);
7821 return false;
7822 }
7823 routedDevices.add(device);
7824 }
7825 for (const auto& client : activeClients) {
jiabin49256852022-03-09 11:21:35 -08007826 if (client->isInvalid()) {
7827 // No need to take care about invalidated clients.
7828 continue;
7829 }
jiabinbce0c1d2020-10-05 11:20:18 -07007830 sp<DeviceDescriptor> preferredDevice =
7831 mAvailableOutputDevices.getDeviceFromId(client->preferredDeviceId());
7832 if (mEngine->getOutputDevicesForAttributes(
7833 client->attributes(), preferredDevice, false) == routedDevices) {
7834 return false;
7835 }
7836 }
7837 return true;
7838}
7839
7840sp<SwAudioOutputDescriptor> AudioPolicyManager::openOutputWithProfileAndDevice(
Eric Laurentb4f42a92022-01-17 17:37:31 +01007841 const sp<IOProfile>& profile, const DeviceVector& devices,
7842 const audio_config_base_t *mixerConfig)
jiabinbce0c1d2020-10-05 11:20:18 -07007843{
7844 for (const auto& device : devices) {
7845 // TODO: This should be checking if the profile supports the device combo.
7846 if (!profile->supportsDevice(device)) {
7847 return nullptr;
7848 }
7849 }
7850 sp<SwAudioOutputDescriptor> desc = new SwAudioOutputDescriptor(profile, mpClientInterface);
7851 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentb4f42a92022-01-17 17:37:31 +01007852 status_t status = desc->open(nullptr /* halConfig */, mixerConfig, devices,
jiabinbce0c1d2020-10-05 11:20:18 -07007853 AUDIO_STREAM_DEFAULT, AUDIO_OUTPUT_FLAG_NONE, &output);
7854 if (status != NO_ERROR) {
7855 return nullptr;
7856 }
7857
7858 // Here is where the out_set_parameters() for card & device gets called
7859 sp<DeviceDescriptor> device = devices.getDeviceForOpening();
7860 const audio_devices_t deviceType = device->type();
7861 const String8 &address = String8(device->address().c_str());
7862 if (!address.isEmpty()) {
7863 char *param = audio_device_address_to_parameter(deviceType, address.c_str());
7864 mpClientInterface->setParameters(output, String8(param));
7865 free(param);
7866 }
7867 updateAudioProfiles(device, output, profile->getAudioProfiles());
7868 if (!profile->hasValidAudioProfile()) {
7869 ALOGW("%s() missing param", __func__);
7870 desc->close();
7871 return nullptr;
7872 } else if (profile->hasDynamicAudioProfile()) {
7873 desc->close();
7874 output = AUDIO_IO_HANDLE_NONE;
7875 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
7876 profile->pickAudioProfile(
7877 config.sample_rate, config.channel_mask, config.format);
7878 config.offload_info.sample_rate = config.sample_rate;
7879 config.offload_info.channel_mask = config.channel_mask;
7880 config.offload_info.format = config.format;
7881
Eric Laurentb4f42a92022-01-17 17:37:31 +01007882 status = desc->open(&config, mixerConfig, devices,
jiabinbce0c1d2020-10-05 11:20:18 -07007883 AUDIO_STREAM_DEFAULT, AUDIO_OUTPUT_FLAG_NONE, &output);
7884 if (status != NO_ERROR) {
7885 return nullptr;
7886 }
7887 }
7888
7889 addOutput(output, desc);
Eric Laurentb4f42a92022-01-17 17:37:31 +01007890
baek.kim -61c20122022-07-27 10:05:32 +00007891 sp<DeviceDescriptor> speaker = mAvailableOutputDevices.getDevice(
7892 AUDIO_DEVICE_OUT_SPEAKER, String8(""), AUDIO_FORMAT_DEFAULT);
7893
jiabinbce0c1d2020-10-05 11:20:18 -07007894 if (audio_is_remote_submix_device(deviceType) && address != "0") {
7895 sp<AudioPolicyMix> policyMix;
7896 if (mPolicyMixes.getAudioPolicyMix(deviceType, address, policyMix) == NO_ERROR) {
7897 policyMix->setOutput(desc);
7898 desc->mPolicyMix = policyMix;
7899 } else {
7900 ALOGW("checkOutputsForDevice() cannot find policy for address %s",
7901 address.string());
7902 }
7903
baek.kim -61c20122022-07-27 10:05:32 +00007904 } else if (hasPrimaryOutput() && speaker != nullptr
7905 && mPrimaryOutput->supportsDevice(speaker) && !desc->supportsDevice(speaker)
Eric Laurentb4f42a92022-01-17 17:37:31 +01007906 && ((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0)) {
7907 // no duplicated output for:
7908 // - direct outputs
7909 // - outputs used by dynamic policy mixes
baek.kim -61c20122022-07-27 10:05:32 +00007910 // - outputs that supports SPEAKER while the primary output does not.
jiabinbce0c1d2020-10-05 11:20:18 -07007911 audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE;
7912
7913 //TODO: configure audio effect output stage here
7914
7915 // open a duplicating output thread for the new output and the primary output
7916 sp<SwAudioOutputDescriptor> dupOutputDesc =
7917 new SwAudioOutputDescriptor(nullptr, mpClientInterface);
7918 status = dupOutputDesc->openDuplicating(mPrimaryOutput, desc, &duplicatedOutput);
7919 if (status == NO_ERROR) {
7920 // add duplicated output descriptor
7921 addOutput(duplicatedOutput, dupOutputDesc);
7922 } else {
7923 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
7924 mPrimaryOutput->mIoHandle, output);
7925 desc->close();
7926 removeOutput(output);
7927 nextAudioPortGeneration();
7928 return nullptr;
7929 }
7930 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02007931 if (mPrimaryOutput == nullptr && profile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
7932 ALOGV("%s(): re-assigning mPrimaryOutput", __func__);
7933 mPrimaryOutput = desc;
7934 }
jiabinbce0c1d2020-10-05 11:20:18 -07007935 return desc;
7936}
7937
Mikhail Naganov1b2a7942017-12-08 10:18:09 -08007938} // namespace android