blob: 4dd1a80d9e4eb56e3e02b39f4007a0119f6f06b8 [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);
Mingyu Shih75563d32023-05-24 04:47:40 +08001091 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
1092 if (stream == AUDIO_STREAM_MUSIC &&
1093 property_get_bool("audio.deep_buffer.media", false /* default_value */)) {
1094 flags = AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
1095 }
1096 const audio_io_handle_t output = selectOutput(outputs, flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001097
François Gaffie11d30102018-11-02 16:09:09 +01001098 ALOGV("getOutput() stream %d selected devices %s, output %d", stream,
1099 devices.toString().c_str(), output);
Eric Laurentf4e63452017-11-06 19:31:46 +00001100 return output;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001101}
1102
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001103status_t AudioPolicyManager::getAudioAttributes(audio_attributes_t *dstAttr,
1104 const audio_attributes_t *srcAttr,
1105 audio_stream_type_t srcStream)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001106{
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001107 if (srcAttr != NULL) {
1108 if (!isValidAttributes(srcAttr)) {
1109 ALOGE("%s invalid attributes: usage=%d content=%d flags=0x%x tags=[%s]",
1110 __func__,
1111 srcAttr->usage, srcAttr->content_type, srcAttr->flags,
1112 srcAttr->tags);
1113 return BAD_VALUE;
1114 }
1115 *dstAttr = *srcAttr;
1116 } else {
1117 if (srcStream < AUDIO_STREAM_MIN || srcStream >= AUDIO_STREAM_PUBLIC_CNT) {
1118 ALOGE("%s: invalid stream type", __func__);
1119 return BAD_VALUE;
1120 }
François Gaffiec005e562018-11-06 15:04:49 +01001121 *dstAttr = mEngine->getAttributesForStreamType(srcStream);
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001122 }
Eric Laurent22fcda22019-05-17 16:28:47 -07001123
1124 // Only honor audibility enforced when required. The client will be
1125 // forced to reconnect if the forced usage changes.
1126 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Mikhail Naganov55773032020-10-01 15:08:13 -07001127 dstAttr->flags = static_cast<audio_flags_mask_t>(
1128 dstAttr->flags & ~AUDIO_FLAG_AUDIBILITY_ENFORCED);
Eric Laurent22fcda22019-05-17 16:28:47 -07001129 }
1130
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001131 return NO_ERROR;
1132}
1133
Kevin Rocard153f92d2018-12-18 18:33:28 -08001134status_t AudioPolicyManager::getOutputForAttrInt(
1135 audio_attributes_t *resultAttr,
1136 audio_io_handle_t *output,
1137 audio_session_t session,
1138 const audio_attributes_t *attr,
1139 audio_stream_type_t *stream,
1140 uid_t uid,
1141 const audio_config_t *config,
1142 audio_output_flags_t *flags,
1143 audio_port_handle_t *selectedDeviceId,
1144 bool *isRequestedDeviceForExclusiveUse,
Eric Laurentc529cf62020-04-17 18:19:10 -07001145 std::vector<sp<AudioPolicyMix>> *secondaryMixes,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001146 output_type_t *outputType,
1147 bool *isSpatialized)
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001148{
François Gaffiec005e562018-11-06 15:04:49 +01001149 DeviceVector outputDevices;
Francois Gaffie716e1432019-01-14 16:58:59 +01001150 const audio_port_handle_t requestedPortId = *selectedDeviceId;
François Gaffie11d30102018-11-02 16:09:09 +01001151 DeviceVector msdDevices = getMsdAudioOutDevices();
François Gaffiec005e562018-11-06 15:04:49 +01001152 const sp<DeviceDescriptor> requestedDevice =
1153 mAvailableOutputDevices.getDeviceFromId(requestedPortId);
1154
Eric Laurent8a1095a2019-11-08 14:44:16 -08001155 *outputType = API_OUTPUT_INVALID;
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001156 *isSpatialized = false;
1157
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001158 status_t status = getAudioAttributes(resultAttr, attr, *stream);
1159 if (status != NO_ERROR) {
1160 return status;
Eric Laurent8f42ea12018-08-08 09:08:25 -07001161 }
Kevin Rocardb99cc752019-03-21 20:52:24 -07001162 if (auto it = mAllowedCapturePolicies.find(uid); it != end(mAllowedCapturePolicies)) {
Mikhail Naganov55773032020-10-01 15:08:13 -07001163 resultAttr->flags = static_cast<audio_flags_mask_t>(resultAttr->flags | it->second);
Kevin Rocardb99cc752019-03-21 20:52:24 -07001164 }
François Gaffiec005e562018-11-06 15:04:49 +01001165 *stream = mEngine->getStreamTypeForAttributes(*resultAttr);
Eric Laurent8f42ea12018-08-08 09:08:25 -07001166
François Gaffiec005e562018-11-06 15:04:49 +01001167 ALOGV("%s() attributes=%s stream=%s session %d selectedDeviceId %d", __func__,
1168 toString(*resultAttr).c_str(), toString(*stream).c_str(), session, requestedPortId);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001169
Kevin Rocard153f92d2018-12-18 18:33:28 -08001170 // The primary output is the explicit routing (eg. setPreferredDevice) if specified,
1171 // otherwise, fallback to the dynamic policies, if none match, query the engine.
1172 // Secondary outputs are always found by dynamic policies as the engine do not support them
Eric Laurentc529cf62020-04-17 18:19:10 -07001173 sp<AudioPolicyMix> primaryMix;
Dean Wheatleyd082f472022-02-04 11:10:48 +11001174 const audio_config_base_t clientConfig = {.sample_rate = config->sample_rate,
1175 .channel_mask = config->channel_mask,
1176 .format = config->format,
1177 };
1178 status = mPolicyMixes.getOutputForAttr(*resultAttr, clientConfig, uid, *flags, primaryMix,
1179 secondaryMixes);
Kevin Rocard94114a22019-04-01 19:38:23 -07001180 if (status != OK) {
1181 return status;
Kevin Rocard153f92d2018-12-18 18:33:28 -08001182 }
Kevin Rocard94114a22019-04-01 19:38:23 -07001183
Kevin Rocard153f92d2018-12-18 18:33:28 -08001184 // Explicit routing is higher priority then any dynamic policy primary output
Eric Laurentc529cf62020-04-17 18:19:10 -07001185 bool usePrimaryOutputFromPolicyMixes = requestedDevice == nullptr && primaryMix != nullptr;
Kevin Rocard153f92d2018-12-18 18:33:28 -08001186
1187 // FIXME: in case of RENDER policy, the output capabilities should be checked
Dean Wheatleyd082f472022-02-04 11:10:48 +11001188 if ((secondaryMixes != nullptr && !secondaryMixes->empty())
1189 && !audio_is_linear_pcm(config->format)) {
1190 ALOGD("%s: rejecting request as secondary mixes only support pcm", __func__);
Kevin Rocard153f92d2018-12-18 18:33:28 -08001191 return BAD_VALUE;
1192 }
1193 if (usePrimaryOutputFromPolicyMixes) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001194 sp<DeviceDescriptor> deviceDesc =
1195 mAvailableOutputDevices.getDevice(primaryMix->mDeviceType,
1196 primaryMix->mDeviceAddress,
1197 AUDIO_FORMAT_DEFAULT);
1198 sp<SwAudioOutputDescriptor> policyDesc = primaryMix->getOutput();
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001199 bool tryDirectForFlags = policyDesc == nullptr ||
1200 (policyDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT);
1201 // if a direct output can be opened to deliver the track's multi-channel content to the
1202 // output rather than being downmixed by the primary output, then use this direct
1203 // output by by-passing the primary mix if possible, otherwise fall-through to primary
1204 // mix.
1205 bool tryDirectForChannelMask = policyDesc != nullptr
1206 && (audio_channel_count_from_out_mask(policyDesc->getConfig().channel_mask) <
1207 audio_channel_count_from_out_mask(config->channel_mask));
1208 if (deviceDesc != nullptr && (tryDirectForFlags || tryDirectForChannelMask)) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001209 audio_io_handle_t newOutput;
1210 status = openDirectOutput(
1211 *stream, session, config,
1212 (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT),
1213 DeviceVector(deviceDesc), &newOutput);
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001214 if (status == NO_ERROR) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001215 policyDesc = mOutputs.valueFor(newOutput);
1216 primaryMix->setOutput(policyDesc);
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001217 } else if (tryDirectForFlags) {
1218 policyDesc = nullptr;
1219 } // otherwise use primary if available.
Eric Laurentc529cf62020-04-17 18:19:10 -07001220 }
1221 if (policyDesc != nullptr) {
1222 policyDesc->mPolicyMix = primaryMix;
1223 *output = policyDesc->mIoHandle;
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08001224 *selectedDeviceId = deviceDesc != 0 ? deviceDesc->getId() : AUDIO_PORT_HANDLE_NONE;
Eric Laurent8a1095a2019-11-08 14:44:16 -08001225
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08001226 ALOGV("getOutputForAttr() returns output %d", *output);
1227 if (resultAttr->usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
1228 *outputType = API_OUT_MIX_PLAYBACK;
1229 } else {
1230 *outputType = API_OUTPUT_LEGACY;
1231 }
1232 return NO_ERROR;
Eric Laurent8a1095a2019-11-08 14:44:16 -08001233 }
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001234 }
François Gaffiec005e562018-11-06 15:04:49 +01001235 // Virtual sources must always be dynamicaly or explicitly routed
1236 if (resultAttr->usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
1237 ALOGW("getOutputForAttr() no policy mix found for usage AUDIO_USAGE_VIRTUAL_SOURCE");
1238 return BAD_VALUE;
1239 }
1240 // explicit routing managed by getDeviceForStrategy in APM is now handled by engine
1241 // in order to let the choice of the order to future vendor engine
1242 outputDevices = mEngine->getOutputDevicesForAttributes(*resultAttr, requestedDevice, false);
Scott Randolph7b1fd232018-06-18 15:33:03 -07001243
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001244 if ((resultAttr->flags & AUDIO_FLAG_HW_AV_SYNC) != 0) {
Nadav Bar766fb022018-01-07 12:18:03 +02001245 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
Eric Laurent93c3d412014-08-01 14:48:35 -07001246 }
1247
Nadav Barb2f18162018-07-18 13:01:53 +03001248 // Set incall music only if device was explicitly set, and fallback to the device which is
1249 // chosen by the engine if not.
1250 // FIXME: provide a more generic approach which is not device specific and move this back
1251 // to getOutputForDevice.
Nadav Bar20919492018-11-20 10:20:51 +02001252 // TODO: Remove check of AUDIO_STREAM_MUSIC once migration is completed on the app side.
jiabin9a3361e2019-10-01 09:38:30 -07001253 if (outputDevices.onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_TELEPHONY_TX) &&
François Gaffiec005e562018-11-06 15:04:49 +01001254 (*stream == AUDIO_STREAM_MUSIC || resultAttr->usage == AUDIO_USAGE_VOICE_COMMUNICATION) &&
Nadav Barb2f18162018-07-18 13:01:53 +03001255 audio_is_linear_pcm(config->format) &&
Eric Laurent74b71512019-11-06 17:21:57 -08001256 isCallAudioAccessible()) {
Francois Gaffie716e1432019-01-14 16:58:59 +01001257 if (requestedPortId != AUDIO_PORT_HANDLE_NONE) {
Nadav Barb2f18162018-07-18 13:01:53 +03001258 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_INCALL_MUSIC;
François Gaffief579db52018-11-13 11:25:16 +01001259 *isRequestedDeviceForExclusiveUse = true;
Nadav Barb2f18162018-07-18 13:01:53 +03001260 }
1261 }
1262
François Gaffiec005e562018-11-06 15:04:49 +01001263 ALOGV("%s() device %s, sampling rate %d, format %#x, channel mask %#x, flags %#x stream %s",
1264 __func__, outputDevices.toString().c_str(), config->sample_rate, config->format,
1265 config->channel_mask, *flags, toString(*stream).c_str());
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001266
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001267 *output = AUDIO_IO_HANDLE_NONE;
François Gaffie11d30102018-11-02 16:09:09 +01001268 if (!msdDevices.isEmpty()) {
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001269 *output = getOutputForDevices(msdDevices, session, resultAttr, config, flags, isSpatialized);
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001270 if (*output != AUDIO_IO_HANDLE_NONE && setMsdOutputPatches(&outputDevices) == NO_ERROR) {
François Gaffiec005e562018-11-06 15:04:49 +01001271 ALOGV("%s() Using MSD devices %s instead of devices %s",
1272 __func__, msdDevices.toString().c_str(), outputDevices.toString().c_str());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001273 } else {
1274 *output = AUDIO_IO_HANDLE_NONE;
1275 }
1276 }
1277 if (*output == AUDIO_IO_HANDLE_NONE) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001278 *output = getOutputForDevices(outputDevices, session, resultAttr, config,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001279 flags, isSpatialized, resultAttr->flags & AUDIO_FLAG_MUTE_HAPTIC);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001280 }
Eric Laurente83b55d2014-11-14 10:06:21 -08001281 if (*output == AUDIO_IO_HANDLE_NONE) {
1282 return INVALID_OPERATION;
1283 }
Paul McLeanaa981192015-03-21 09:55:15 -07001284
François Gaffiec005e562018-11-06 15:04:49 +01001285 *selectedDeviceId = getFirstDeviceId(outputDevices);
Michael Chan6fb34492020-12-08 15:44:49 +11001286 for (auto &outputDevice : outputDevices) {
Mikhail Naganovb0fbc1b2023-04-28 13:06:32 -07001287 if (outputDevice->getId() == mConfig->getDefaultOutputDevice()->getId()) {
Michael Chan6fb34492020-12-08 15:44:49 +11001288 *selectedDeviceId = outputDevice->getId();
1289 break;
1290 }
1291 }
Eric Laurent2ac76942017-06-22 17:17:09 -07001292
Eric Laurent8a1095a2019-11-08 14:44:16 -08001293 if (outputDevices.onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_TELEPHONY_TX)) {
1294 *outputType = API_OUTPUT_TELEPHONY_TX;
1295 } else {
1296 *outputType = API_OUTPUT_LEGACY;
1297 }
1298
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001299 ALOGV("%s returns output %d selectedDeviceId %d", __func__, *output, *selectedDeviceId);
1300
1301 return NO_ERROR;
1302}
1303
1304status_t AudioPolicyManager::getOutputForAttr(const audio_attributes_t *attr,
1305 audio_io_handle_t *output,
1306 audio_session_t session,
1307 audio_stream_type_t *stream,
Svet Ganov3e5f14f2021-05-13 22:51:08 +00001308 const AttributionSourceState& attributionSource,
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001309 const audio_config_t *config,
1310 audio_output_flags_t *flags,
1311 audio_port_handle_t *selectedDeviceId,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001312 audio_port_handle_t *portId,
Eric Laurent8a1095a2019-11-08 14:44:16 -08001313 std::vector<audio_io_handle_t> *secondaryOutputs,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001314 output_type_t *outputType,
1315 bool *isSpatialized)
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001316{
1317 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
1318 if (*portId != AUDIO_PORT_HANDLE_NONE) {
1319 return INVALID_OPERATION;
1320 }
Philip P. Moltmannbda45752020-07-17 16:41:18 -07001321 const uid_t uid = VALUE_OR_RETURN_STATUS(
Svet Ganov3e5f14f2021-05-13 22:51:08 +00001322 aidl2legacy_int32_t_uid_t(attributionSource.uid));
Francois Gaffie716e1432019-01-14 16:58:59 +01001323 const audio_port_handle_t requestedPortId = *selectedDeviceId;
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001324 audio_attributes_t resultAttr;
François Gaffief579db52018-11-13 11:25:16 +01001325 bool isRequestedDeviceForExclusiveUse = false;
Eric Laurentc529cf62020-04-17 18:19:10 -07001326 std::vector<sp<AudioPolicyMix>> secondaryMixes;
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001327 const sp<DeviceDescriptor> requestedDevice =
1328 mAvailableOutputDevices.getDeviceFromId(requestedPortId);
1329
1330 // Prevent from storing invalid requested device id in clients
1331 const audio_port_handle_t sanitizedRequestedPortId =
1332 requestedDevice != nullptr ? requestedPortId : AUDIO_PORT_HANDLE_NONE;
1333 *selectedDeviceId = sanitizedRequestedPortId;
1334
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001335 status_t status = getOutputForAttrInt(&resultAttr, output, session, attr, stream, uid,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001336 config, flags, selectedDeviceId, &isRequestedDeviceForExclusiveUse,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001337 secondaryOutputs != nullptr ? &secondaryMixes : nullptr, outputType, isSpatialized);
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001338 if (status != NO_ERROR) {
1339 return status;
1340 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001341 std::vector<wp<SwAudioOutputDescriptor>> weakSecondaryOutputDescs;
Eric Laurentc529cf62020-04-17 18:19:10 -07001342 if (secondaryOutputs != nullptr) {
1343 for (auto &secondaryMix : secondaryMixes) {
1344 sp<SwAudioOutputDescriptor> outputDesc = secondaryMix->getOutput();
1345 if (outputDesc != nullptr &&
1346 outputDesc->mIoHandle != AUDIO_IO_HANDLE_NONE) {
1347 secondaryOutputs->push_back(outputDesc->mIoHandle);
1348 weakSecondaryOutputDescs.push_back(outputDesc);
1349 }
1350 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001351 }
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001352
Eric Laurent8fc147b2018-07-22 19:13:55 -07001353 audio_config_base_t clientConfig = {.sample_rate = config->sample_rate,
Nick Desaulniersa30e3202019-10-18 13:38:23 -07001354 .channel_mask = config->channel_mask,
Eric Laurent8fc147b2018-07-22 19:13:55 -07001355 .format = config->format,
Nick Desaulniersa30e3202019-10-18 13:38:23 -07001356 };
jiabin4ef93452019-09-10 14:29:54 -07001357 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurent8f42ea12018-08-08 09:08:25 -07001358
Eric Laurentc209fe42020-06-05 18:11:23 -07001359 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(*output);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001360 sp<TrackClientDescriptor> clientDesc =
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001361 new TrackClientDescriptor(*portId, uid, session, resultAttr, clientConfig,
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001362 sanitizedRequestedPortId, *stream,
François Gaffiec005e562018-11-06 15:04:49 +01001363 mEngine->getProductStrategyForAttributes(resultAttr),
François Gaffieaaac0fd2018-11-22 17:56:39 +01001364 toVolumeSource(resultAttr),
Kevin Rocard153f92d2018-12-18 18:33:28 -08001365 *flags, isRequestedDeviceForExclusiveUse,
Eric Laurentc209fe42020-06-05 18:11:23 -07001366 std::move(weakSecondaryOutputDescs),
1367 outputDesc->mPolicyMix);
Andy Hung39efb7a2018-09-26 15:39:28 -07001368 outputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001369
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001370 ALOGV("%s() returns output %d requestedPortId %d selectedDeviceId %d for port ID %d", __func__,
1371 *output, requestedPortId, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07001372
Eric Laurente83b55d2014-11-14 10:06:21 -08001373 return NO_ERROR;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001374}
1375
Eric Laurentc529cf62020-04-17 18:19:10 -07001376status_t AudioPolicyManager::openDirectOutput(audio_stream_type_t stream,
1377 audio_session_t session,
1378 const audio_config_t *config,
1379 audio_output_flags_t flags,
1380 const DeviceVector &devices,
1381 audio_io_handle_t *output) {
1382
1383 *output = AUDIO_IO_HANDLE_NONE;
1384
1385 // skip direct output selection if the request can obviously be attached to a mixed output
1386 // and not explicitly requested
1387 if (((flags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
1388 audio_is_linear_pcm(config->format) && config->sample_rate <= SAMPLE_RATE_HZ_MAX &&
1389 audio_channel_count_from_out_mask(config->channel_mask) <= 2) {
1390 return NAME_NOT_FOUND;
1391 }
1392
1393 // Do not allow offloading if one non offloadable effect is enabled or MasterMono is enabled.
1394 // This prevents creating an offloaded track and tearing it down immediately after start
1395 // when audioflinger detects there is an active non offloadable effect.
1396 // FIXME: We should check the audio session here but we do not have it in this context.
1397 // This may prevent offloading in rare situations where effects are left active by apps
1398 // in the background.
1399 sp<IOProfile> profile;
1400 if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) ||
1401 !(mEffects.isNonOffloadableEffectEnabled() || mMasterMono)) {
1402 profile = getProfileForOutput(
1403 devices, config->sample_rate, config->format, config->channel_mask,
1404 flags, true /* directOnly */);
1405 }
1406
1407 if (profile == nullptr) {
1408 return NAME_NOT_FOUND;
1409 }
1410
1411 // exclusive outputs for MMAP and Offload are enforced by different session ids.
1412 for (size_t i = 0; i < mOutputs.size(); i++) {
1413 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
1414 if (!desc->isDuplicated() && (profile == desc->mProfile)) {
1415 // reuse direct output if currently open by the same client
1416 // and configured with same parameters
1417 if ((config->sample_rate == desc->getSamplingRate()) &&
1418 (config->format == desc->getFormat()) &&
1419 (config->channel_mask == desc->getChannelMask()) &&
1420 (session == desc->mDirectClientSession)) {
1421 desc->mDirectOpenCount++;
Eric Laurentfecbceb2021-02-09 14:46:43 +01001422 ALOGV("%s reusing direct output %d for session %d", __func__,
Eric Laurentc529cf62020-04-17 18:19:10 -07001423 mOutputs.keyAt(i), session);
1424 *output = mOutputs.keyAt(i);
1425 return NO_ERROR;
1426 }
1427 }
1428 }
1429
1430 if (!profile->canOpenNewIo()) {
1431 return NAME_NOT_FOUND;
1432 }
1433
1434 sp<SwAudioOutputDescriptor> outputDesc =
1435 new SwAudioOutputDescriptor(profile, mpClientInterface);
1436
Michael Chan6fb34492020-12-08 15:44:49 +11001437 // An MSD patch may be using the only output stream that can service this request. Release
1438 // all MSD patches to prioritize this request over any active output on MSD.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001439 releaseMsdOutputPatches(devices);
Eric Laurentc529cf62020-04-17 18:19:10 -07001440
Eric Laurentf1f22e72021-07-13 14:04:14 +02001441 status_t status =
1442 outputDesc->open(config, nullptr /* mixerConfig */, devices, stream, flags, output);
Eric Laurentc529cf62020-04-17 18:19:10 -07001443
1444 // only accept an output with the requested parameters
1445 if (status != NO_ERROR ||
1446 (config->sample_rate != 0 && config->sample_rate != outputDesc->getSamplingRate()) ||
1447 (config->format != AUDIO_FORMAT_DEFAULT && config->format != outputDesc->getFormat()) ||
1448 (config->channel_mask != 0 && config->channel_mask != outputDesc->getChannelMask())) {
1449 ALOGV("%s failed opening direct output: output %d sample rate %d %d,"
1450 "format %d %d, channel mask %04x %04x", __func__, *output, config->sample_rate,
1451 outputDesc->getSamplingRate(), config->format, outputDesc->getFormat(),
1452 config->channel_mask, outputDesc->getChannelMask());
1453 if (*output != AUDIO_IO_HANDLE_NONE) {
1454 outputDesc->close();
1455 }
1456 // fall back to mixer output if possible when the direct output could not be open
1457 if (audio_is_linear_pcm(config->format) &&
1458 config->sample_rate <= SAMPLE_RATE_HZ_MAX) {
1459 return NAME_NOT_FOUND;
1460 }
1461 *output = AUDIO_IO_HANDLE_NONE;
1462 return BAD_VALUE;
1463 }
1464 outputDesc->mDirectOpenCount = 1;
1465 outputDesc->mDirectClientSession = session;
1466
1467 addOutput(*output, outputDesc);
1468 mPreviousOutputs = mOutputs;
1469 ALOGV("%s returns new direct output %d", __func__, *output);
1470 mpClientInterface->onAudioPortListUpdate();
1471 return NO_ERROR;
1472}
1473
François Gaffie11d30102018-11-02 16:09:09 +01001474audio_io_handle_t AudioPolicyManager::getOutputForDevices(
1475 const DeviceVector &devices,
Kevin Rocard169753c2017-03-06 14:18:23 -08001476 audio_session_t session,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001477 const audio_attributes_t *attr,
Eric Laurentfe231122017-11-17 17:48:06 -08001478 const audio_config_t *config,
jiabine375d412019-02-26 12:54:53 -08001479 audio_output_flags_t *flags,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001480 bool *isSpatialized,
jiabine375d412019-02-26 12:54:53 -08001481 bool forceMutingHaptic)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001482{
Andy Hungc88b0642018-04-27 15:42:35 -07001483 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001484
jiabine375d412019-02-26 12:54:53 -08001485 // Discard haptic channel mask when forcing muting haptic channels.
1486 audio_channel_mask_t channelMask = forceMutingHaptic
Mikhail Naganov55773032020-10-01 15:08:13 -07001487 ? static_cast<audio_channel_mask_t>(config->channel_mask & ~AUDIO_CHANNEL_HAPTIC_ALL)
1488 : config->channel_mask;
jiabine375d412019-02-26 12:54:53 -08001489
Eric Laurente552edb2014-03-10 17:42:56 -07001490 // open a direct output if required by specified parameters
1491 //force direct flag if offload flag is set: offloading implies a direct output stream
1492 // and all common behaviors are driven by checking only the direct flag
1493 // this should normally be set appropriately in the policy configuration file
Nadav Bar766fb022018-01-07 12:18:03 +02001494 if ((*flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1495 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurente552edb2014-03-10 17:42:56 -07001496 }
Nadav Bar766fb022018-01-07 12:18:03 +02001497 if ((*flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
1498 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent93c3d412014-08-01 14:48:35 -07001499 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001500
1501 audio_stream_type_t stream = mEngine->getStreamTypeForAttributes(*attr);
1502
Eric Laurente83b55d2014-11-14 10:06:21 -08001503 // only allow deep buffering for music stream type
1504 if (stream != AUDIO_STREAM_MUSIC) {
Nadav Bar766fb022018-01-07 12:18:03 +02001505 *flags = (audio_output_flags_t)(*flags &~AUDIO_OUTPUT_FLAG_DEEP_BUFFER);
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -07001506 } else if (/* stream == AUDIO_STREAM_MUSIC && */
Nadav Bar766fb022018-01-07 12:18:03 +02001507 *flags == AUDIO_OUTPUT_FLAG_NONE &&
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -07001508 property_get_bool("audio.deep_buffer.media", false /* default_value */)) {
1509 // use DEEP_BUFFER as default output for music stream type
Nadav Bar766fb022018-01-07 12:18:03 +02001510 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
Eric Laurente83b55d2014-11-14 10:06:21 -08001511 }
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -07001512 if (stream == AUDIO_STREAM_TTS) {
Nadav Bar766fb022018-01-07 12:18:03 +02001513 *flags = AUDIO_OUTPUT_FLAG_TTS;
Haynes Mathew George84c621e2017-04-25 11:41:50 -07001514 } else if (stream == AUDIO_STREAM_VOICE_CALL &&
Nadav Bar20919492018-11-20 10:20:51 +02001515 audio_is_linear_pcm(config->format) &&
1516 (*flags & AUDIO_OUTPUT_FLAG_INCALL_MUSIC) == 0) {
Nadav Bar766fb022018-01-07 12:18:03 +02001517 *flags = (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_VOIP_RX |
Haynes Mathew George84c621e2017-04-25 11:41:50 -07001518 AUDIO_OUTPUT_FLAG_DIRECT);
1519 ALOGV("Set VoIP and Direct output flags for PCM format");
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -07001520 }
Eric Laurente552edb2014-03-10 17:42:56 -07001521
Carter Hsua3abb402021-10-26 11:11:20 +08001522 // Attach the Ultrasound flag for the AUDIO_CONTENT_TYPE_ULTRASOUND
1523 if (attr->content_type == AUDIO_CONTENT_TYPE_ULTRASOUND) {
1524 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_ULTRASOUND);
1525 }
1526
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001527 *isSpatialized = false;
Eric Laurentfa0f6742021-08-17 18:39:44 +02001528 if (mSpatializerOutput != nullptr
Andy Hung9dd1a5b2022-05-10 15:39:39 -07001529 && canBeSpatializedInt(attr, config, devices.toTypeAddrVector())) {
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001530 *isSpatialized = true;
Eric Laurentfa0f6742021-08-17 18:39:44 +02001531 return mSpatializerOutput->mIoHandle;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001532 }
1533
Eric Laurentc529cf62020-04-17 18:19:10 -07001534 audio_config_t directConfig = *config;
1535 directConfig.channel_mask = channelMask;
1536 status_t status = openDirectOutput(stream, session, &directConfig, *flags, devices, &output);
1537 if (status != NAME_NOT_FOUND) {
Eric Laurente552edb2014-03-10 17:42:56 -07001538 return output;
1539 }
1540
Eric Laurent14cbfca2016-03-17 09:42:16 -07001541 // A request for HW A/V sync cannot fallback to a mixed output because time
1542 // stamps are embedded in audio data
Phil Burk2d059932018-02-15 15:55:11 -08001543 if ((*flags & (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ)) != 0) {
Eric Laurent14cbfca2016-03-17 09:42:16 -07001544 return AUDIO_IO_HANDLE_NONE;
1545 }
Pierre Couillaude73496b2023-03-06 16:19:05 +00001546 // A request for Tuner cannot fallback to a mixed output
1547 if ((directConfig.offload_info.content_id || directConfig.offload_info.sync_id)) {
1548 return AUDIO_IO_HANDLE_NONE;
1549 }
Eric Laurent14cbfca2016-03-17 09:42:16 -07001550
Eric Laurente552edb2014-03-10 17:42:56 -07001551 // ignoring channel mask due to downmix capability in mixer
1552
1553 // open a non direct output
1554
1555 // for non direct outputs, only PCM is supported
Eric Laurentfe231122017-11-17 17:48:06 -08001556 if (audio_is_linear_pcm(config->format)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001557 // get which output is suitable for the specified stream. The actual
1558 // routing change will happen when startOutput() will be called
François Gaffie11d30102018-11-02 16:09:09 +01001559 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07001560
Eric Laurent8838a382014-09-08 16:44:28 -07001561 // at this stage we should ignore the DIRECT flag as no direct output could be found earlier
Nadav Bar766fb022018-01-07 12:18:03 +02001562 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
jiabinebb6af42020-06-09 17:31:17 -07001563 output = selectOutput(
1564 outputs, *flags, config->format, channelMask, config->sample_rate, session);
Eric Laurente552edb2014-03-10 17:42:56 -07001565 }
François Gaffie11d30102018-11-02 16:09:09 +01001566 ALOGW_IF((output == 0), "getOutputForDevices() could not find output for stream %d, "
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001567 "sampling rate %d, format %#x, channels %#x, flags %#x",
jiabine375d412019-02-26 12:54:53 -08001568 stream, config->sample_rate, config->format, channelMask, *flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001569
Eric Laurente552edb2014-03-10 17:42:56 -07001570 return output;
1571}
1572
Mikhail Naganovf02f3672018-11-09 12:44:16 -08001573sp<DeviceDescriptor> AudioPolicyManager::getMsdAudioInDevice() const {
François Gaffie11d30102018-11-02 16:09:09 +01001574 auto msdInDevices = mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1575 mAvailableInputDevices);
1576 return msdInDevices.isEmpty()? nullptr : msdInDevices.itemAt(0);
1577}
1578
1579DeviceVector AudioPolicyManager::getMsdAudioOutDevices() const {
1580 return mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1581 mAvailableOutputDevices);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001582}
1583
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001584const AudioPatchCollection AudioPolicyManager::getMsdOutputPatches() const {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001585 AudioPatchCollection msdPatches;
Mikhail Naganov86112352018-10-04 09:02:49 -07001586 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1587 if (msdModule != 0) {
1588 for (size_t i = 0; i < mAudioPatches.size(); ++i) {
1589 sp<AudioPatch> patch = mAudioPatches.valueAt(i);
1590 for (size_t j = 0; j < patch->mPatch.num_sources; ++j) {
1591 const struct audio_port_config *source = &patch->mPatch.sources[j];
1592 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
1593 source->ext.device.hw_module == msdModule->getHandle()) {
François Gaffieafd4cea2019-11-18 15:50:22 +01001594 msdPatches.addAudioPatch(patch->getHandle(), patch);
Mikhail Naganov86112352018-10-04 09:02:49 -07001595 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001596 }
1597 }
1598 }
1599 return msdPatches;
1600}
1601
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02001602bool AudioPolicyManager::isMsdPatch(const audio_patch_handle_t &handle) const {
1603 ssize_t index = mAudioPatches.indexOfKey(handle);
1604 if (index < 0) {
1605 return false;
1606 }
1607 const sp<AudioPatch> patch = mAudioPatches.valueAt(index);
1608 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1609 if (msdModule == nullptr) {
1610 return false;
1611 }
1612 const struct audio_port_config *sink = &patch->mPatch.sinks[0];
1613 if (getMsdAudioOutDevices().contains(mAvailableOutputDevices.getDeviceFromId(sink->id))) {
1614 return true;
1615 }
1616 index = getMsdOutputPatches().indexOfKey(handle);
1617 if (index < 0) {
1618 return false;
1619 }
1620 return true;
1621}
1622
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001623status_t AudioPolicyManager::getMsdProfiles(bool hwAvSync,
1624 const InputProfileCollection &inputProfiles,
1625 const OutputProfileCollection &outputProfiles,
1626 const sp<DeviceDescriptor> &sourceDevice,
1627 const sp<DeviceDescriptor> &sinkDevice,
1628 AudioProfileVector& sourceProfiles,
1629 AudioProfileVector& sinkProfiles) const {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001630 if (inputProfiles.isEmpty()) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001631 ALOGE("%s() no input profiles for source module", __func__);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001632 return NO_INIT;
1633 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001634 if (outputProfiles.isEmpty()) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001635 ALOGE("%s() no output profiles for sink module", __func__);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001636 return NO_INIT;
1637 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001638 for (const auto &inProfile : inputProfiles) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001639 if (hwAvSync == ((inProfile->getFlags() & AUDIO_INPUT_FLAG_HW_AV_SYNC) != 0) &&
1640 inProfile->supportsDevice(sourceDevice)) {
1641 appendAudioProfiles(sourceProfiles, inProfile->getAudioProfiles());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001642 }
1643 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001644 for (const auto &outProfile : outputProfiles) {
Michael Chan6fb34492020-12-08 15:44:49 +11001645 if (hwAvSync == ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) &&
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001646 outProfile->supportsDevice(sinkDevice)) {
1647 appendAudioProfiles(sinkProfiles, outProfile->getAudioProfiles());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001648 }
1649 }
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001650 return NO_ERROR;
1651}
1652
1653status_t AudioPolicyManager::getBestMsdConfig(bool hwAvSync,
1654 const AudioProfileVector &sourceProfiles, const AudioProfileVector &sinkProfiles,
1655 audio_port_config *sourceConfig, audio_port_config *sinkConfig) const
1656{
Dean Wheatley16809da2022-12-09 14:55:46 +11001657 // Compressed formats for MSD module, ordered from most preferred to least preferred.
1658 static const std::vector<audio_format_t> formatsOrder = {{
1659 AUDIO_FORMAT_IEC60958, AUDIO_FORMAT_MAT_2_1, AUDIO_FORMAT_MAT_2_0, AUDIO_FORMAT_E_AC3,
Dean Wheatley0f27c602023-08-23 13:57:21 +10001660 AUDIO_FORMAT_AC3, AUDIO_FORMAT_PCM_FLOAT, AUDIO_FORMAT_PCM_32_BIT,
1661 AUDIO_FORMAT_PCM_8_24_BIT, AUDIO_FORMAT_PCM_24_BIT_PACKED, AUDIO_FORMAT_PCM_16_BIT }};
Dean Wheatley16809da2022-12-09 14:55:46 +11001662 static const std::vector<audio_channel_mask_t> channelMasksOrder = [](){
1663 // Channel position masks for MSD module, 3D > 2D > 1D ordering (most preferred to least
1664 // preferred).
1665 std::vector<audio_channel_mask_t> masks = {{
1666 AUDIO_CHANNEL_OUT_3POINT1POINT2, AUDIO_CHANNEL_OUT_3POINT0POINT2,
1667 AUDIO_CHANNEL_OUT_2POINT1POINT2, AUDIO_CHANNEL_OUT_2POINT0POINT2,
1668 AUDIO_CHANNEL_OUT_5POINT1, AUDIO_CHANNEL_OUT_STEREO }};
1669 // insert index masks (higher counts most preferred) as preferred over position masks
1670 for (int i = 1; i <= AUDIO_CHANNEL_COUNT_MAX; i++) {
1671 masks.insert(
1672 masks.begin(), audio_channel_mask_for_index_assignment_from_count(i));
1673 }
1674 return masks;
1675 }();
1676
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001677 struct audio_config_base bestSinkConfig;
Dean Wheatley16809da2022-12-09 14:55:46 +11001678 status_t result = findBestMatchingOutputConfig(sourceProfiles, sinkProfiles, formatsOrder,
1679 channelMasksOrder, true /*preferHigherSamplingRates*/, bestSinkConfig);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001680 if (result != NO_ERROR) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001681 ALOGD("%s() no matching config found for sink, hwAvSync: %d",
1682 __func__, hwAvSync);
Greg Kaiser83289652018-07-30 06:13:57 -07001683 return result;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001684 }
1685 sinkConfig->sample_rate = bestSinkConfig.sample_rate;
1686 sinkConfig->channel_mask = bestSinkConfig.channel_mask;
1687 sinkConfig->format = bestSinkConfig.format;
1688 // For encoded streams force direct flag to prevent downstream mixing.
1689 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1690 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_DIRECT);
Dean Wheatley5c9f0832019-11-21 13:39:31 +11001691 if (audio_is_iec61937_compatible(sinkConfig->format)) {
1692 // For formats compatible with IEC61937 encapsulation, assume that
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001693 // the input is IEC61937 framed (for proportional buffer sizing).
Dean Wheatley5c9f0832019-11-21 13:39:31 +11001694 // Add the AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO flag so downstream HAL can distinguish between
1695 // raw and IEC61937 framed streams.
1696 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1697 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO);
1698 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001699 sourceConfig->sample_rate = bestSinkConfig.sample_rate;
1700 // Specify exact channel mask to prevent guessing by bit count in PatchPanel.
Dean Wheatley16809da2022-12-09 14:55:46 +11001701 sourceConfig->channel_mask =
1702 audio_channel_mask_get_representation(bestSinkConfig.channel_mask)
1703 == AUDIO_CHANNEL_REPRESENTATION_INDEX ?
1704 bestSinkConfig.channel_mask : audio_channel_mask_out_to_in(bestSinkConfig.channel_mask);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001705 sourceConfig->format = bestSinkConfig.format;
1706 // Copy input stream directly without any processing (e.g. resampling).
1707 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1708 sourceConfig->flags.input | AUDIO_INPUT_FLAG_DIRECT);
1709 if (hwAvSync) {
1710 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1711 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
1712 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1713 sourceConfig->flags.input | AUDIO_INPUT_FLAG_HW_AV_SYNC);
1714 }
1715 const unsigned int config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE |
1716 AUDIO_PORT_CONFIG_CHANNEL_MASK | AUDIO_PORT_CONFIG_FORMAT | AUDIO_PORT_CONFIG_FLAGS;
1717 sinkConfig->config_mask |= config_mask;
1718 sourceConfig->config_mask |= config_mask;
1719 return NO_ERROR;
1720}
1721
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001722PatchBuilder AudioPolicyManager::buildMsdPatch(bool msdIsSource,
1723 const sp<DeviceDescriptor> &device) const
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001724{
1725 PatchBuilder patchBuilder;
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001726 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1727 ALOG_ASSERT(msdModule != nullptr, "MSD module not available");
1728 sp<HwModule> deviceModule = mHwModules.getModuleForDevice(device, AUDIO_FORMAT_DEFAULT);
1729 if (deviceModule == nullptr) {
1730 ALOGE("%s() unable to get module for %s", __func__, device->toString().c_str());
1731 return patchBuilder;
1732 }
1733 const InputProfileCollection inputProfiles = msdIsSource ?
1734 msdModule->getInputProfiles() : deviceModule->getInputProfiles();
1735 const OutputProfileCollection outputProfiles = msdIsSource ?
1736 deviceModule->getOutputProfiles() : msdModule->getOutputProfiles();
1737
1738 const sp<DeviceDescriptor> sourceDevice = msdIsSource ? getMsdAudioInDevice() : device;
1739 const sp<DeviceDescriptor> sinkDevice = msdIsSource ?
1740 device : getMsdAudioOutDevices().itemAt(0);
1741 patchBuilder.addSource(sourceDevice).addSink(sinkDevice);
1742
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001743 audio_port_config sourceConfig = patchBuilder.patch()->sources[0];
1744 audio_port_config sinkConfig = patchBuilder.patch()->sinks[0];
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001745 AudioProfileVector sourceProfiles;
1746 AudioProfileVector sinkProfiles;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001747 // TODO: Figure out whether MSD module has HW_AV_SYNC flag set in the AP config file.
1748 // For now, we just forcefully try with HwAvSync first.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001749 for (auto hwAvSync : { true, false }) {
1750 if (getMsdProfiles(hwAvSync, inputProfiles, outputProfiles, sourceDevice, sinkDevice,
1751 sourceProfiles, sinkProfiles) != NO_ERROR) {
1752 continue;
1753 }
1754 if (getBestMsdConfig(hwAvSync, sourceProfiles, sinkProfiles, &sourceConfig,
1755 &sinkConfig) == NO_ERROR) {
1756 // Found a matching config. Re-create PatchBuilder with this config.
1757 return (PatchBuilder()).addSource(sourceConfig).addSink(sinkConfig);
1758 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001759 }
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001760 ALOGV("%s() no matching config found. Fall through to default PCM patch"
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001761 " supporting PCM format conversion.", __func__);
1762 return patchBuilder;
1763}
1764
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001765status_t AudioPolicyManager::setMsdOutputPatches(const DeviceVector *outputDevices) {
Michael Chan6fb34492020-12-08 15:44:49 +11001766 DeviceVector devices;
1767 if (outputDevices != nullptr && outputDevices->size() > 0) {
1768 devices.add(*outputDevices);
1769 } else {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001770 // Use media strategy for unspecified output device. This should only
1771 // occur on checkForDeviceAndOutputChanges(). Device connection events may
1772 // therefore invalidate explicit routing requests.
Michael Chan6fb34492020-12-08 15:44:49 +11001773 devices = mEngine->getOutputDevicesForAttributes(
François Gaffiec005e562018-11-06 15:04:49 +01001774 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
Michael Chan6fb34492020-12-08 15:44:49 +11001775 LOG_ALWAYS_FATAL_IF(devices.isEmpty(), "no output device to set MSD patch");
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001776 }
Michael Chan6fb34492020-12-08 15:44:49 +11001777 std::vector<PatchBuilder> patchesToCreate;
1778 for (auto i = 0u; i < devices.size(); ++i) {
1779 ALOGV("%s() for device %s", __func__, devices[i]->toString().c_str());
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001780 patchesToCreate.push_back(buildMsdPatch(true /*msdIsSource*/, devices[i]));
Michael Chan6fb34492020-12-08 15:44:49 +11001781 }
1782 // Retain only the MSD patches associated with outputDevices request.
1783 // Tear down the others, and create new ones as needed.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001784 AudioPatchCollection patchesToRemove = getMsdOutputPatches();
Michael Chan6fb34492020-12-08 15:44:49 +11001785 for (auto it = patchesToCreate.begin(); it != patchesToCreate.end(); ) {
1786 auto retainedPatch = false;
1787 for (auto i = 0u; i < patchesToRemove.size(); ++i) {
1788 if (audio_patches_are_equal(it->patch(), &patchesToRemove[i]->mPatch)) {
1789 patchesToRemove.removeItemsAt(i);
1790 retainedPatch = true;
1791 break;
1792 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001793 }
Michael Chan6fb34492020-12-08 15:44:49 +11001794 if (retainedPatch) {
1795 it = patchesToCreate.erase(it);
1796 continue;
1797 }
1798 ++it;
1799 }
1800 if (patchesToCreate.size() == 0 && patchesToRemove.size() == 0) {
1801 return NO_ERROR;
1802 }
1803 for (auto i = 0u; i < patchesToRemove.size(); ++i) {
1804 auto &currentPatch = patchesToRemove.valueAt(i);
François Gaffieafd4cea2019-11-18 15:50:22 +01001805 releaseAudioPatch(currentPatch->getHandle(), mUidCached);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001806 }
Michael Chan6fb34492020-12-08 15:44:49 +11001807 status_t status = NO_ERROR;
1808 for (const auto &p : patchesToCreate) {
1809 auto currStatus = installPatch(__func__, -1 /*index*/, nullptr /*patchHandle*/,
1810 p.patch(), 0 /*delayMs*/, mUidCached, nullptr /*patchDescPtr*/);
1811 char message[256];
1812 snprintf(message, sizeof(message), "%s() %s: creating MSD patch from device:IN_BUS to "
1813 "device:%#x (format:%#x channels:%#x samplerate:%d)", __func__,
1814 currStatus == NO_ERROR ? "Success" : "Error",
1815 p.patch()->sinks[0].ext.device.type, p.patch()->sources[0].format,
1816 p.patch()->sources[0].channel_mask, p.patch()->sources[0].sample_rate);
1817 if (currStatus == NO_ERROR) {
1818 ALOGD("%s", message);
1819 } else {
1820 ALOGE("%s", message);
1821 if (status == NO_ERROR) {
1822 status = currStatus;
1823 }
1824 }
1825 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001826 return status;
1827}
1828
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001829void AudioPolicyManager::releaseMsdOutputPatches(const DeviceVector& devices) {
1830 AudioPatchCollection msdPatches = getMsdOutputPatches();
Michael Chan6fb34492020-12-08 15:44:49 +11001831 for (size_t i = 0; i < msdPatches.size(); i++) {
1832 const auto& patch = msdPatches[i];
1833 for (size_t j = 0; j < patch->mPatch.num_sinks; ++j) {
1834 const struct audio_port_config *sink = &patch->mPatch.sinks[j];
1835 if (sink->type == AUDIO_PORT_TYPE_DEVICE && devices.getDevice(sink->ext.device.type,
1836 String8(sink->ext.device.address), AUDIO_FORMAT_DEFAULT) != nullptr) {
1837 releaseAudioPatch(patch->getHandle(), mUidCached);
1838 break;
1839 }
1840 }
1841 }
1842}
1843
Dorin Drimus94d94412022-02-02 09:05:02 +01001844bool AudioPolicyManager::msdHasPatchesToAllDevices(const AudioDeviceTypeAddrVector& devices) {
Mikhail Naganovb0fbc1b2023-04-28 13:06:32 -07001845 DeviceVector devicesToCheck =
1846 mConfig->getOutputDevices().getDevicesFromDeviceTypeAddrVec(devices);
Dorin Drimus94d94412022-02-02 09:05:02 +01001847 AudioPatchCollection msdPatches = getMsdOutputPatches();
1848 for (size_t i = 0; i < msdPatches.size(); i++) {
1849 const auto& patch = msdPatches[i];
1850 for (size_t j = 0; j < patch->mPatch.num_sinks; ++j) {
1851 const struct audio_port_config *sink = &patch->mPatch.sinks[j];
1852 if (sink->type == AUDIO_PORT_TYPE_DEVICE) {
1853 const auto& foundDevice = devicesToCheck.getDevice(
1854 sink->ext.device.type, String8(sink->ext.device.address), AUDIO_FORMAT_DEFAULT);
1855 if (foundDevice != nullptr) {
1856 devicesToCheck.remove(foundDevice);
1857 if (devicesToCheck.isEmpty()) {
1858 return true;
1859 }
1860 }
1861 }
1862 }
1863 }
1864 return false;
1865}
1866
Eric Laurente0720872014-03-11 09:30:41 -07001867audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
jiabinebb6af42020-06-09 17:31:17 -07001868 audio_output_flags_t flags,
1869 audio_format_t format,
1870 audio_channel_mask_t channelMask,
1871 uint32_t samplingRate,
1872 audio_session_t sessionId)
Eric Laurente552edb2014-03-10 17:42:56 -07001873{
Eric Laurent16c66dd2019-05-01 17:54:10 -07001874 LOG_ALWAYS_FATAL_IF(!(format == AUDIO_FORMAT_INVALID || audio_is_linear_pcm(format)),
1875 "%s called with format %#x", __func__, format);
1876
jiabinebb6af42020-06-09 17:31:17 -07001877 // Return the output that haptic-generating attached to when 1) session id is specified,
1878 // 2) haptic-generating effect exists for given session id and 3) the output that
1879 // haptic-generating effect attached to is in given outputs.
1880 if (sessionId != AUDIO_SESSION_NONE) {
1881 audio_io_handle_t hapticGeneratingOutput = mEffects.getIoForSession(
1882 sessionId, FX_IID_HAPTICGENERATOR);
1883 if (outputs.indexOf(hapticGeneratingOutput) >= 0) {
1884 return hapticGeneratingOutput;
1885 }
1886 }
1887
Eric Laurent16c66dd2019-05-01 17:54:10 -07001888 // Flags disqualifying an output: the match must happen before calling selectOutput()
1889 static const audio_output_flags_t kExcludedFlags = (audio_output_flags_t)
1890 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ | AUDIO_OUTPUT_FLAG_DIRECT);
1891
1892 // Flags expressing a functional request: must be honored in priority over
1893 // other criteria
1894 static const audio_output_flags_t kFunctionalFlags = (audio_output_flags_t)
1895 (AUDIO_OUTPUT_FLAG_VOIP_RX | AUDIO_OUTPUT_FLAG_INCALL_MUSIC |
Eric Laurente28c66d2022-01-21 13:40:41 +01001896 AUDIO_OUTPUT_FLAG_TTS | AUDIO_OUTPUT_FLAG_DIRECT_PCM | AUDIO_OUTPUT_FLAG_ULTRASOUND |
1897 AUDIO_OUTPUT_FLAG_SPATIALIZER);
Eric Laurent16c66dd2019-05-01 17:54:10 -07001898 // Flags expressing a performance request: have lower priority than serving
1899 // requested sampling rate or channel mask
1900 static const audio_output_flags_t kPerformanceFlags = (audio_output_flags_t)
1901 (AUDIO_OUTPUT_FLAG_FAST | AUDIO_OUTPUT_FLAG_DEEP_BUFFER |
1902 AUDIO_OUTPUT_FLAG_RAW | AUDIO_OUTPUT_FLAG_SYNC);
1903
1904 const audio_output_flags_t functionalFlags =
1905 (audio_output_flags_t)(flags & kFunctionalFlags);
1906 const audio_output_flags_t performanceFlags =
1907 (audio_output_flags_t)(flags & kPerformanceFlags);
1908
1909 audio_io_handle_t bestOutput = (outputs.size() == 0) ? AUDIO_IO_HANDLE_NONE : outputs[0];
1910
Eric Laurente552edb2014-03-10 17:42:56 -07001911 // select one output among several that provide a path to a particular device or set of
François Gaffie11d30102018-11-02 16:09:09 +01001912 // devices (the list was previously build by getOutputsForDevices()).
Eric Laurente552edb2014-03-10 17:42:56 -07001913 // The priority is as follows:
jiabin40573322018-11-08 12:08:02 -08001914 // 1: the output supporting haptic playback when requesting haptic playback
Eric Laurent16c66dd2019-05-01 17:54:10 -07001915 // 2: the output with the highest number of requested functional flags
Carter Hsu199f1892021-10-15 15:47:29 +08001916 // with tiebreak preferring the minimum number of extra functional flags
1917 // (see b/200293124, the incorrect selection of AUDIO_OUTPUT_FLAG_VOIP_RX).
Eric Laurent16c66dd2019-05-01 17:54:10 -07001918 // 3: the output supporting the exact channel mask
1919 // 4: the output with a higher channel count than requested
jiabind1785f72022-06-03 20:48:18 +00001920 // 5: the output with the highest sampling rate if the requested sample rate is
1921 // greater than default sampling rate
Eric Laurent16c66dd2019-05-01 17:54:10 -07001922 // 6: the output with the highest number of requested performance flags
1923 // 7: the output with the bit depth the closest to the requested one
1924 // 8: the primary output
1925 // 9: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07001926
Eric Laurent16c66dd2019-05-01 17:54:10 -07001927 // matching criteria values in priority order for best matching output so far
1928 std::vector<uint32_t> bestMatchCriteria(8, 0);
Eric Laurente552edb2014-03-10 17:42:56 -07001929
Eric Laurent16c66dd2019-05-01 17:54:10 -07001930 const uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
1931 const uint32_t hapticChannelCount = audio_channel_count_from_out_mask(
1932 channelMask & AUDIO_CHANNEL_HAPTIC_ALL);
Eric Laurente78b6762018-12-19 16:29:01 -08001933
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001934 for (audio_io_handle_t output : outputs) {
1935 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent16c66dd2019-05-01 17:54:10 -07001936 // matching criteria values in priority order for current output
1937 std::vector<uint32_t> currentMatchCriteria(8, 0);
jiabin40573322018-11-08 12:08:02 -08001938
Eric Laurent16c66dd2019-05-01 17:54:10 -07001939 if (outputDesc->isDuplicated()) {
1940 continue;
1941 }
1942 if ((kExcludedFlags & outputDesc->mFlags) != 0) {
1943 continue;
1944 }
Eric Laurent8838a382014-09-08 16:44:28 -07001945
Eric Laurent16c66dd2019-05-01 17:54:10 -07001946 // If haptic channel is specified, use the haptic output if present.
1947 // When using haptic output, same audio format and sample rate are required.
1948 const uint32_t outputHapticChannelCount = audio_channel_count_from_out_mask(
jiabin5740f082019-08-19 15:08:30 -07001949 outputDesc->getChannelMask() & AUDIO_CHANNEL_HAPTIC_ALL);
Eric Laurent16c66dd2019-05-01 17:54:10 -07001950 if ((hapticChannelCount == 0) != (outputHapticChannelCount == 0)) {
1951 continue;
1952 }
1953 if (outputHapticChannelCount >= hapticChannelCount
jiabin5740f082019-08-19 15:08:30 -07001954 && format == outputDesc->getFormat()
1955 && samplingRate == outputDesc->getSamplingRate()) {
Eric Laurent16c66dd2019-05-01 17:54:10 -07001956 currentMatchCriteria[0] = outputHapticChannelCount;
1957 }
1958
1959 // functional flags match
Carter Hsu199f1892021-10-15 15:47:29 +08001960 const int matchingFunctionalFlags =
1961 __builtin_popcount(outputDesc->mFlags & functionalFlags);
1962 const int totalFunctionalFlags =
1963 __builtin_popcount(outputDesc->mFlags & kFunctionalFlags);
1964 // Prefer matching functional flags, but subtract unnecessary functional flags.
1965 currentMatchCriteria[1] = 100 * (matchingFunctionalFlags + 1) - totalFunctionalFlags;
Eric Laurent16c66dd2019-05-01 17:54:10 -07001966
1967 // channel mask and channel count match
jiabin5740f082019-08-19 15:08:30 -07001968 uint32_t outputChannelCount = audio_channel_count_from_out_mask(
1969 outputDesc->getChannelMask());
Eric Laurent16c66dd2019-05-01 17:54:10 -07001970 if (channelMask != AUDIO_CHANNEL_NONE && channelCount > 2 &&
1971 channelCount <= outputChannelCount) {
1972 if ((audio_channel_mask_get_representation(channelMask) ==
jiabin5740f082019-08-19 15:08:30 -07001973 audio_channel_mask_get_representation(outputDesc->getChannelMask())) &&
1974 ((channelMask & outputDesc->getChannelMask()) == channelMask)) {
Eric Laurent16c66dd2019-05-01 17:54:10 -07001975 currentMatchCriteria[2] = outputChannelCount;
Eric Laurente552edb2014-03-10 17:42:56 -07001976 }
Eric Laurent16c66dd2019-05-01 17:54:10 -07001977 currentMatchCriteria[3] = outputChannelCount;
1978 }
1979
1980 // sampling rate match
jiabind1785f72022-06-03 20:48:18 +00001981 if (samplingRate > SAMPLE_RATE_HZ_DEFAULT) {
jiabin5740f082019-08-19 15:08:30 -07001982 currentMatchCriteria[4] = outputDesc->getSamplingRate();
Eric Laurent16c66dd2019-05-01 17:54:10 -07001983 }
1984
1985 // performance flags match
1986 currentMatchCriteria[5] = popcount(outputDesc->mFlags & performanceFlags);
1987
1988 // format match
1989 if (format != AUDIO_FORMAT_INVALID) {
1990 currentMatchCriteria[6] =
jiabin4ef93452019-09-10 14:29:54 -07001991 PolicyAudioPort::kFormatDistanceMax -
1992 PolicyAudioPort::formatDistance(format, outputDesc->getFormat());
Eric Laurent16c66dd2019-05-01 17:54:10 -07001993 }
1994
1995 // primary output match
1996 currentMatchCriteria[7] = outputDesc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY;
1997
1998 // compare match criteria by priority then value
1999 if (std::lexicographical_compare(bestMatchCriteria.begin(), bestMatchCriteria.end(),
2000 currentMatchCriteria.begin(), currentMatchCriteria.end())) {
2001 bestMatchCriteria = currentMatchCriteria;
2002 bestOutput = output;
2003
2004 std::stringstream result;
2005 std::copy(bestMatchCriteria.begin(), bestMatchCriteria.end(),
2006 std::ostream_iterator<int>(result, " "));
2007 ALOGV("%s new bestOutput %d criteria %s",
2008 __func__, bestOutput, result.str().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07002009 }
2010 }
2011
Eric Laurent16c66dd2019-05-01 17:54:10 -07002012 return bestOutput;
Eric Laurente552edb2014-03-10 17:42:56 -07002013}
2014
Eric Laurent8fc147b2018-07-22 19:13:55 -07002015status_t AudioPolicyManager::startOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002016{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002017 ALOGV("%s portId %d", __FUNCTION__, portId);
2018
2019 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2020 if (outputDesc == 0) {
2021 ALOGW("startOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002022 return BAD_VALUE;
2023 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002024 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002025
Eric Laurent8fc147b2018-07-22 19:13:55 -07002026 ALOGV("startOutput() output %d, stream %d, session %d",
Eric Laurent97ac8712018-07-27 18:59:02 -07002027 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurentc75307b2015-03-17 15:29:32 -07002028
Eric Laurent733ce942017-12-07 12:18:25 -08002029 status_t status = outputDesc->start();
2030 if (status != NO_ERROR) {
2031 return status;
Eric Laurent3974e3b2017-12-07 17:58:43 -08002032 }
2033
Eric Laurent97ac8712018-07-27 18:59:02 -07002034 uint32_t delayMs;
2035 status = startSource(outputDesc, client, &delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07002036
2037 if (status != NO_ERROR) {
Eric Laurent733ce942017-12-07 12:18:25 -08002038 outputDesc->stop();
Eric Laurent8c7e6da2015-04-21 17:37:00 -07002039 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07002040 }
Jean-Michel Trivi32b7a102023-02-07 20:49:04 +00002041 if (client->hasPreferredDevice()) {
2042 // playback activity with preferred device impacts routing occurred, inform upper layers
2043 mpClientInterface->onRoutingUpdated();
2044 }
Eric Laurentc75307b2015-03-17 15:29:32 -07002045 if (delayMs != 0) {
2046 usleep(delayMs * 1000);
2047 }
2048
2049 return status;
2050}
2051
Eric Laurent96d1dda2022-03-14 17:14:19 +01002052bool AudioPolicyManager::isLeUnicastActive() const {
2053 if (isInCall()) {
2054 return true;
2055 }
2056 return isAnyDeviceTypeActive(getAudioDeviceOutLeAudioUnicastSet());
2057}
2058
2059bool AudioPolicyManager::isAnyDeviceTypeActive(const DeviceTypeSet& deviceTypes) const {
2060 if (mAvailableOutputDevices.getDevicesFromTypes(deviceTypes).isEmpty()) {
2061 return false;
2062 }
2063 bool active = mOutputs.isAnyDeviceTypeActive(deviceTypes);
2064 ALOGV("%s active %d", __func__, active);
2065 return active;
2066}
2067
Eric Laurent97ac8712018-07-27 18:59:02 -07002068status_t AudioPolicyManager::startSource(const sp<SwAudioOutputDescriptor>& outputDesc,
2069 const sp<TrackClientDescriptor>& client,
2070 uint32_t *delayMs)
Eric Laurentc75307b2015-03-17 15:29:32 -07002071{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002072 // cannot start playback of STREAM_TTS if any other output is being used
2073 uint32_t beaconMuteLatency = 0;
Eric Laurentc75307b2015-03-17 15:29:32 -07002074
2075 *delayMs = 0;
Eric Laurent97ac8712018-07-27 18:59:02 -07002076 audio_stream_type_t stream = client->stream();
François Gaffie1c878552018-11-22 16:53:21 +01002077 auto clientVolSrc = client->volumeSource();
François Gaffiec005e562018-11-06 15:04:49 +01002078 auto clientStrategy = client->strategy();
2079 auto clientAttr = client->attributes();
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002080 if (stream == AUDIO_STREAM_TTS) {
2081 ALOGV("\t found BEACON stream");
François Gaffie1c878552018-11-22 16:53:21 +01002082 if (!mTtsOutputAvailable && mOutputs.isAnyOutputActive(
Francois Gaffie4404ddb2021-02-04 17:03:38 +01002083 toVolumeSource(AUDIO_STREAM_TTS, false) /*sourceToIgnore*/)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002084 return INVALID_OPERATION;
2085 } else {
2086 beaconMuteLatency = handleEventForBeacon(STARTING_BEACON);
2087 }
2088 } else {
2089 // some playback other than beacon starts
2090 beaconMuteLatency = handleEventForBeacon(STARTING_OUTPUT);
2091 }
2092
Eric Laurent77305a62016-07-25 16:39:22 -07002093 // force device change if the output is inactive and no audio patch is already present.
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002094 // check active before incrementing usage count
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02002095 bool force = !outputDesc->isActive() && !outputDesc->isRouted();
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002096
François Gaffie11d30102018-11-02 16:09:09 +01002097 DeviceVector devices;
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002098 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
Eric Laurent97ac8712018-07-27 18:59:02 -07002099 const char *address = NULL;
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002100 if (policyMix != nullptr) {
François Gaffie11d30102018-11-02 16:09:09 +01002101 audio_devices_t newDeviceType;
Eric Laurent97ac8712018-07-27 18:59:02 -07002102 address = policyMix->mDeviceAddress.string();
Kevin Rocard153f92d2018-12-18 18:33:28 -08002103 if ((policyMix->mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie11d30102018-11-02 16:09:09 +01002104 newDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Kevin Rocard153f92d2018-12-18 18:33:28 -08002105 } else {
2106 newDeviceType = policyMix->mDeviceType;
Eric Laurent97ac8712018-07-27 18:59:02 -07002107 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08002108 sp device = mAvailableOutputDevices.getDevice(newDeviceType, String8(address),
2109 AUDIO_FORMAT_DEFAULT);
2110 ALOG_ASSERT(device, "%s: no device found t=%u, a=%s", __func__, newDeviceType, address);
2111 devices.add(device);
Eric Laurent97ac8712018-07-27 18:59:02 -07002112 }
2113
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002114 // requiresMuteCheck is false when we can bypass mute strategy.
2115 // It covers a common case when there is no materially active audio
2116 // and muting would result in unnecessary delay and dropped audio.
2117 const uint32_t outputLatencyMs = outputDesc->latency();
2118 bool requiresMuteCheck = outputDesc->isActive(outputLatencyMs * 2); // account for drain
Eric Laurent96d1dda2022-03-14 17:14:19 +01002119 bool wasLeUnicastActive = isLeUnicastActive();
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002120
Eric Laurente552edb2014-03-10 17:42:56 -07002121 // increment usage count for this stream on the requested output:
2122 // NOTE that the usage count is the same for duplicated output and hardware output which is
2123 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
Eric Laurent592dd7b2018-08-05 18:58:48 -07002124 outputDesc->setClientActive(client, true);
Eric Laurent97ac8712018-07-27 18:59:02 -07002125
2126 if (client->hasPreferredDevice(true)) {
Eric Laurent72af8012023-03-15 17:36:22 +01002127 if (outputDesc->sameExclusivePreferredDevicesCount() > 0) {
François Gaffief96e5432019-04-09 17:13:56 +02002128 // Preferred device may be exclusive, use only if no other active clients on this output
2129 devices = DeviceVector(
2130 mAvailableOutputDevices.getDeviceFromId(client->preferredDeviceId()));
2131 } else {
2132 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
2133 }
François Gaffie11d30102018-11-02 16:09:09 +01002134 if (devices != outputDesc->devices()) {
François Gaffiec005e562018-11-06 15:04:49 +01002135 checkStrategyRoute(clientStrategy, outputDesc->mIoHandle);
Eric Laurent97ac8712018-07-27 18:59:02 -07002136 }
2137 }
Eric Laurente552edb2014-03-10 17:42:56 -07002138
François Gaffiec005e562018-11-06 15:04:49 +01002139 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07002140 selectOutputForMusicEffects();
2141 }
2142
François Gaffie1c878552018-11-22 16:53:21 +01002143 if (outputDesc->getActivityCount(clientVolSrc) == 1 || !devices.isEmpty()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08002144 // starting an output being rerouted?
François Gaffie11d30102018-11-02 16:09:09 +01002145 if (devices.isEmpty()) {
2146 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Eric Laurent275e8e92014-11-30 15:14:47 -08002147 }
François Gaffiec005e562018-11-06 15:04:49 +01002148 bool shouldWait =
2149 (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM)) ||
2150 followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_NOTIFICATION)) ||
2151 (beaconMuteLatency > 0));
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002152 uint32_t waitMs = beaconMuteLatency;
Eric Laurente552edb2014-03-10 17:42:56 -07002153 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01002154 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07002155 if (desc != outputDesc) {
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002156 // An output has a shared device if
2157 // - managed by the same hw module
2158 // - supports the currently selected device
2159 const bool sharedDevice = outputDesc->sharesHwModuleWith(desc)
François Gaffie11d30102018-11-02 16:09:09 +01002160 && (!desc->filterSupportedDevices(devices).isEmpty());
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002161
Eric Laurent77305a62016-07-25 16:39:22 -07002162 // force a device change if any other output is:
2163 // - managed by the same hw module
Jean-Michel Trivi4a5b4812018-02-08 17:22:32 +00002164 // - supports currently selected device
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002165 // - has a current device selection that differs from selected device.
Eric Laurent77305a62016-07-25 16:39:22 -07002166 // - has an active audio patch
Eric Laurente552edb2014-03-10 17:42:56 -07002167 // In this case, the audio HAL must receive the new device selection so that it can
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002168 // change the device currently selected by the other output.
2169 if (sharedDevice &&
François Gaffie11d30102018-11-02 16:09:09 +01002170 desc->devices() != devices &&
Eric Laurent77305a62016-07-25 16:39:22 -07002171 desc->getPatchHandle() != AUDIO_PATCH_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07002172 force = true;
2173 }
2174 // wait for audio on other active outputs to be presented when starting
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002175 // a notification so that audio focus effect can propagate, or that a mute/unmute
2176 // event occurred for beacon
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002177 const uint32_t latencyMs = desc->latency();
2178 const bool isActive = desc->isActive(latencyMs * 2); // account for drain
2179
2180 if (shouldWait && isActive && (waitMs < latencyMs)) {
2181 waitMs = latencyMs;
Eric Laurente552edb2014-03-10 17:42:56 -07002182 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002183
2184 // Require mute check if another output is on a shared device
2185 // and currently active to have proper drain and avoid pops.
2186 // Note restoring AudioTracks onto this output needs to invoke
2187 // a volume ramp if there is no mute.
2188 requiresMuteCheck |= sharedDevice && isActive;
Eric Laurente552edb2014-03-10 17:42:56 -07002189 }
2190 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002191
2192 const uint32_t muteWaitMs =
François Gaffie11d30102018-11-02 16:09:09 +01002193 setOutputDevices(outputDesc, devices, force, 0, NULL, requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07002194
Eric Laurente552edb2014-03-10 17:42:56 -07002195 // apply volume rules for current stream and device if necessary
François Gaffieaaac0fd2018-11-22 17:56:39 +01002196 auto &curves = getVolumeCurves(client->attributes());
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00002197 if (NO_ERROR != checkAndSetVolume(curves, client->volumeSource(),
François Gaffieaaac0fd2018-11-22 17:56:39 +01002198 curves.getVolumeIndex(outputDesc->devices().types()),
Eric Laurentc75307b2015-03-17 15:29:32 -07002199 outputDesc,
Francois Gaffied11442b2020-04-27 11:51:09 +02002200 outputDesc->devices().types(), 0 /*delay*/,
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00002201 outputDesc->useHwGain() /*force*/)) {
2202 // request AudioService to reinitialize the volume curves asynchronously
2203 ALOGE("checkAndSetVolume failed, requesting volume range init");
2204 mpClientInterface->onVolumeRangeInitRequest();
2205 };
Eric Laurente552edb2014-03-10 17:42:56 -07002206
2207 // update the outputs if starting an output with a stream that can affect notification
2208 // routing
2209 handleNotificationRoutingForStream(stream);
Eric Laurentc722f302014-12-10 11:21:49 -08002210
Eric Laurent2cbe89a2014-12-19 11:49:08 -08002211 // force reevaluating accessibility routing when ringtone or alarm starts
François Gaffiec005e562018-11-06 15:04:49 +01002212 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM))) {
Eric Laurent2cbe89a2014-12-19 11:49:08 -08002213 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
2214 }
Eric Laurentdc462862016-07-19 12:29:53 -07002215
2216 if (waitMs > muteWaitMs) {
2217 *delayMs = waitMs - muteWaitMs;
2218 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002219
2220 // FIXME: A device change (muteWaitMs > 0) likely introduces a volume change.
2221 // A volume change enacted by APM with 0 delay is not synchronous, as it goes
2222 // via AudioCommandThread to AudioFlinger. Hence it is possible that the volume
2223 // change occurs after the MixerThread starts and causes a stream volume
2224 // glitch.
2225 //
2226 // We do not introduce additional delay here.
Eric Laurente552edb2014-03-10 17:42:56 -07002227 }
Eric Laurentdc462862016-07-19 12:29:53 -07002228
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002229 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
jiabin9a3361e2019-10-01 09:38:30 -07002230 mEngine->getForceUse(
2231 AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
François Gaffiec005e562018-11-06 15:04:49 +01002232 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), true, outputDesc);
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002233 }
2234
Eric Laurent97ac8712018-07-27 18:59:02 -07002235 // Automatically enable the remote submix input when output is started on a re routing mix
2236 // of type MIX_TYPE_RECORDERS
jiabin9a3361e2019-10-01 09:38:30 -07002237 if (isSingleDeviceType(devices.types(), &audio_is_remote_submix_device) &&
2238 policyMix != NULL && policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002239 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2240 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2241 address,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002242 "remote-submix",
2243 AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07002244 }
2245
Eric Laurent96d1dda2022-03-14 17:14:19 +01002246 checkLeBroadcastRoutes(wasLeUnicastActive, outputDesc, *delayMs);
2247
Eric Laurente552edb2014-03-10 17:42:56 -07002248 return NO_ERROR;
2249}
2250
Eric Laurent96d1dda2022-03-14 17:14:19 +01002251void AudioPolicyManager::checkLeBroadcastRoutes(bool wasUnicastActive,
2252 sp<SwAudioOutputDescriptor> ignoredOutput, uint32_t delayMs) {
2253 bool isUnicastActive = isLeUnicastActive();
2254
2255 if (wasUnicastActive != isUnicastActive) {
2256 //reroute all outputs routed to LE broadcast if LE unicast activy changed on any output
2257 for (size_t i = 0; i < mOutputs.size(); i++) {
2258 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
2259 if (desc != ignoredOutput && desc->isActive()
2260 && ((isUnicastActive &&
2261 !desc->devices().
2262 getDevicesFromType(AUDIO_DEVICE_OUT_BLE_BROADCAST).isEmpty())
2263 || (wasUnicastActive &&
2264 !desc->devices().getDevicesFromTypes(
2265 getAudioDeviceOutLeAudioUnicastSet()).isEmpty()))) {
2266 DeviceVector newDevices = getNewOutputDevices(desc, false /*fromCache*/);
2267 bool force = desc->devices() != newDevices;
2268 setOutputDevices(desc, newDevices, force, delayMs);
2269 // re-apply device specific volume if not done by setOutputDevice()
2270 if (!force) {
2271 applyStreamVolumes(desc, newDevices.types(), delayMs);
2272 }
2273 }
2274 }
2275 }
2276}
2277
Eric Laurent8fc147b2018-07-22 19:13:55 -07002278status_t AudioPolicyManager::stopOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002279{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002280 ALOGV("%s portId %d", __FUNCTION__, portId);
2281
2282 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2283 if (outputDesc == 0) {
2284 ALOGW("stopOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002285 return BAD_VALUE;
2286 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002287 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002288
Jean-Michel Trivi32b7a102023-02-07 20:49:04 +00002289 if (client->hasPreferredDevice(true)) {
2290 // playback activity with preferred device impacts routing occurred, inform upper layers
2291 mpClientInterface->onRoutingUpdated();
2292 }
2293
Eric Laurent97ac8712018-07-27 18:59:02 -07002294 ALOGV("stopOutput() output %d, stream %d, session %d",
2295 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurente552edb2014-03-10 17:42:56 -07002296
Eric Laurent97ac8712018-07-27 18:59:02 -07002297 status_t status = stopSource(outputDesc, client);
Eric Laurent3974e3b2017-12-07 17:58:43 -08002298
Eric Laurent733ce942017-12-07 12:18:25 -08002299 if (status == NO_ERROR ) {
2300 outputDesc->stop();
Eric Laurent3974e3b2017-12-07 17:58:43 -08002301 }
2302 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07002303}
2304
Eric Laurent97ac8712018-07-27 18:59:02 -07002305status_t AudioPolicyManager::stopSource(const sp<SwAudioOutputDescriptor>& outputDesc,
2306 const sp<TrackClientDescriptor>& client)
Eric Laurentc75307b2015-03-17 15:29:32 -07002307{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002308 // always handle stream stop, check which stream type is stopping
Eric Laurent97ac8712018-07-27 18:59:02 -07002309 audio_stream_type_t stream = client->stream();
François Gaffie1c878552018-11-22 16:53:21 +01002310 auto clientVolSrc = client->volumeSource();
Eric Laurent96d1dda2022-03-14 17:14:19 +01002311 bool wasLeUnicastActive = isLeUnicastActive();
Eric Laurent97ac8712018-07-27 18:59:02 -07002312
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002313 handleEventForBeacon(stream == AUDIO_STREAM_TTS ? STOPPING_BEACON : STOPPING_OUTPUT);
2314
François Gaffie1c878552018-11-22 16:53:21 +01002315 if (outputDesc->getActivityCount(clientVolSrc) > 0) {
2316 if (outputDesc->getActivityCount(clientVolSrc) == 1) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002317 // Automatically disable the remote submix input when output is stopped on a
2318 // re routing mix of type MIX_TYPE_RECORDERS
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002319 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
jiabin9a3361e2019-10-01 09:38:30 -07002320 if (isSingleDeviceType(
2321 outputDesc->devices().types(), &audio_is_remote_submix_device) &&
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002322 policyMix != nullptr &&
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002323 policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002324 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2325 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002326 policyMix->mDeviceAddress,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002327 "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07002328 }
2329 }
2330 bool forceDeviceUpdate = false;
Eric Laurent72af8012023-03-15 17:36:22 +01002331 if (client->hasPreferredDevice(true) &&
2332 outputDesc->sameExclusivePreferredDevicesCount() < 2) {
François Gaffiec005e562018-11-06 15:04:49 +01002333 checkStrategyRoute(client->strategy(), AUDIO_IO_HANDLE_NONE);
Eric Laurent97ac8712018-07-27 18:59:02 -07002334 forceDeviceUpdate = true;
2335 }
2336
Eric Laurente552edb2014-03-10 17:42:56 -07002337 // decrement usage count of this stream on the output
Eric Laurent592dd7b2018-08-05 18:58:48 -07002338 outputDesc->setClientActive(client, false);
Paul McLeanaa981192015-03-21 09:55:15 -07002339
Eric Laurente552edb2014-03-10 17:42:56 -07002340 // store time at which the stream was stopped - see isStreamActive()
François Gaffie1c878552018-11-22 16:53:21 +01002341 if (outputDesc->getActivityCount(clientVolSrc) == 0 || forceDeviceUpdate) {
François Gaffiec005e562018-11-06 15:04:49 +01002342 outputDesc->setStopTime(client, systemTime());
François Gaffie11d30102018-11-02 16:09:09 +01002343 DeviceVector newDevices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Francois Gaffie3523ab32021-06-22 13:24:34 +02002344
2345 // If the routing does not change, if an output is routed on a device using HwGain
2346 // (aka setAudioPortConfig) and there are still active clients following different
2347 // volume group(s), force reapply volume
2348 bool requiresVolumeCheck = outputDesc->getActivityCount(clientVolSrc) == 0 &&
2349 outputDesc->useHwGain() && outputDesc->isAnyActive(VOLUME_SOURCE_NONE);
2350
Eric Laurente552edb2014-03-10 17:42:56 -07002351 // delay the device switch by twice the latency because stopOutput() is executed when
2352 // the track stop() command is received and at that time the audio track buffer can
2353 // still contain data that needs to be drained. The latency only covers the audio HAL
2354 // and kernel buffers. Also the latency does not always include additional delay in the
2355 // audio path (audio DSP, CODEC ...)
Francois Gaffie3523ab32021-06-22 13:24:34 +02002356 setOutputDevices(outputDesc, newDevices, false, outputDesc->latency()*2,
2357 nullptr, true /*requiresMuteCheck*/, requiresVolumeCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07002358
2359 // force restoring the device selection on other active outputs if it differs from the
2360 // one being selected for this output
Eric Laurent57de36c2016-09-28 16:59:11 -07002361 uint32_t delayMs = outputDesc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -07002362 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01002363 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07002364 if (desc != outputDesc &&
Eric Laurente552edb2014-03-10 17:42:56 -07002365 desc->isActive() &&
2366 outputDesc->sharesHwModuleWith(desc) &&
François Gaffie11d30102018-11-02 16:09:09 +01002367 (newDevices != desc->devices())) {
2368 DeviceVector newDevices2 = getNewOutputDevices(desc, false /*fromCache*/);
2369 bool force = desc->devices() != newDevices2;
Eric Laurentf3a5a602018-05-22 18:42:55 -07002370
François Gaffie11d30102018-11-02 16:09:09 +01002371 setOutputDevices(desc, newDevices2, force, delayMs);
2372
Eric Laurent57de36c2016-09-28 16:59:11 -07002373 // re-apply device specific volume if not done by setOutputDevice()
2374 if (!force) {
François Gaffie11d30102018-11-02 16:09:09 +01002375 applyStreamVolumes(desc, newDevices2.types(), delayMs);
Eric Laurent57de36c2016-09-28 16:59:11 -07002376 }
Eric Laurente552edb2014-03-10 17:42:56 -07002377 }
2378 }
2379 // update the outputs if stopping one with a stream that can affect notification routing
2380 handleNotificationRoutingForStream(stream);
2381 }
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002382
2383 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
2384 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Jean-Michel Trivi74e01fa2019-02-25 12:18:09 -08002385 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), false, outputDesc);
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002386 }
2387
François Gaffiec005e562018-11-06 15:04:49 +01002388 if (followsSameRouting(client->attributes(), attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07002389 selectOutputForMusicEffects();
2390 }
Eric Laurent96d1dda2022-03-14 17:14:19 +01002391
2392 checkLeBroadcastRoutes(wasLeUnicastActive, outputDesc, outputDesc->latency()*2);
2393
Eric Laurente552edb2014-03-10 17:42:56 -07002394 return NO_ERROR;
2395 } else {
Eric Laurentc75307b2015-03-17 15:29:32 -07002396 ALOGW("stopOutput() refcount is already 0");
Eric Laurente552edb2014-03-10 17:42:56 -07002397 return INVALID_OPERATION;
2398 }
2399}
2400
jiabinbce0c1d2020-10-05 11:20:18 -07002401bool AudioPolicyManager::releaseOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002402{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002403 ALOGV("%s portId %d", __FUNCTION__, portId);
2404
2405 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2406 if (outputDesc == 0) {
Andy Hung39efb7a2018-09-26 15:39:28 -07002407 // If an output descriptor is closed due to a device routing change,
2408 // then there are race conditions with releaseOutput from tracks
2409 // that may be destroyed (with no PlaybackThread) or a PlaybackThread
2410 // destroyed shortly thereafter.
2411 //
2412 // Here we just log a warning, instead of a fatal error.
Eric Laurent8fc147b2018-07-22 19:13:55 -07002413 ALOGW("releaseOutput() no output for client %d", portId);
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
2417 ALOGV("releaseOutput() %d", outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -07002418
Jaideep Sharma7bf382e2020-11-26 17:07:29 +05302419 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
2420 if (outputDesc->isClientActive(client)) {
2421 ALOGW("releaseOutput() inactivates portId %d in good faith", portId);
2422 stopOutput(portId);
2423 }
2424
Eric Laurent8fc147b2018-07-22 19:13:55 -07002425 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
2426 if (outputDesc->mDirectOpenCount <= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07002427 ALOGW("releaseOutput() invalid open count %d for output %d",
Eric Laurent8fc147b2018-07-22 19:13:55 -07002428 outputDesc->mDirectOpenCount, outputDesc->mIoHandle);
jiabinbce0c1d2020-10-05 11:20:18 -07002429 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002430 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002431 if (--outputDesc->mDirectOpenCount == 0) {
2432 closeOutput(outputDesc->mIoHandle);
Eric Laurentb52c1522014-05-20 11:27:36 -07002433 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07002434 }
2435 }
Jaideep Sharma7bf382e2020-11-26 17:07:29 +05302436
Andy Hung39efb7a2018-09-26 15:39:28 -07002437 outputDesc->removeClient(portId);
jiabinbce0c1d2020-10-05 11:20:18 -07002438 if (outputDesc->mPendingReopenToQueryProfiles && outputDesc->getClientCount() == 0) {
2439 // The output is pending reopened to query dynamic profiles and
2440 // there is no active clients
2441 closeOutput(outputDesc->mIoHandle);
2442 sp<SwAudioOutputDescriptor> newOutputDesc = openOutputWithProfileAndDevice(
2443 outputDesc->mProfile, mEngine->getActiveMediaDevices(mAvailableOutputDevices));
2444 if (newOutputDesc == nullptr) {
2445 ALOGE("%s failed to open output", __func__);
2446 }
2447 return true;
2448 }
2449 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002450}
2451
Eric Laurentcaf7f482014-11-25 17:50:47 -08002452status_t AudioPolicyManager::getInputForAttr(const audio_attributes_t *attr,
2453 audio_io_handle_t *input,
Mikhail Naganov2996f672019-04-18 12:29:59 -07002454 audio_unique_id_t riid,
Eric Laurentcaf7f482014-11-25 17:50:47 -08002455 audio_session_t session,
Svet Ganov3e5f14f2021-05-13 22:51:08 +00002456 const AttributionSourceState& attributionSource,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002457 const audio_config_base_t *config,
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002458 audio_input_flags_t flags,
Eric Laurent2ac76942017-06-22 17:17:09 -07002459 audio_port_handle_t *selectedDeviceId,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002460 input_type_t *inputType,
2461 audio_port_handle_t *portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002462{
François Gaffiec005e562018-11-06 15:04:49 +01002463 ALOGV("%s() source %d, sampling rate %d, format %#x, channel mask %#x, session %d, "
Eric Laurent2f2c1982021-06-02 14:03:11 +02002464 "flags %#x attributes=%s requested device ID %d",
2465 __func__, attr->source, config->sample_rate, config->format, config->channel_mask,
2466 session, flags, toString(*attr).c_str(), *selectedDeviceId);
Eric Laurente552edb2014-03-10 17:42:56 -07002467
Eric Laurentad2e7b92017-09-14 20:06:42 -07002468 status_t status = NO_ERROR;
Francois Gaffie716e1432019-01-14 16:58:59 +01002469 audio_attributes_t attributes = *attr;
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002470 sp<AudioPolicyMix> policyMix;
François Gaffie11d30102018-11-02 16:09:09 +01002471 sp<DeviceDescriptor> device;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002472 sp<AudioInputDescriptor> inputDesc;
2473 sp<RecordClientDescriptor> clientDesc;
2474 audio_port_handle_t requestedDeviceId = *selectedDeviceId;
Svet Ganov3e5f14f2021-05-13 22:51:08 +00002475 uid_t uid = VALUE_OR_RETURN_STATUS(aidl2legacy_int32_t_uid_t(attributionSource.uid));
Eric Laurent8f42ea12018-08-08 09:08:25 -07002476 bool isSoundTrigger;
Eric Laurent8f42ea12018-08-08 09:08:25 -07002477
2478 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
2479 if (*portId != AUDIO_PORT_HANDLE_NONE) {
2480 return INVALID_OPERATION;
2481 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08002482
Francois Gaffie716e1432019-01-14 16:58:59 +01002483 if (attr->source == AUDIO_SOURCE_DEFAULT) {
2484 attributes.source = AUDIO_SOURCE_MIC;
Eric Laurentfe231122017-11-17 17:48:06 -08002485 }
2486
Paul McLean466dc8e2015-04-17 13:15:36 -06002487 // Explicit routing?
Pattydd807582021-11-04 21:01:03 +08002488 sp<DeviceDescriptor> explicitRoutingDevice =
François Gaffie11d30102018-11-02 16:09:09 +01002489 mAvailableInputDevices.getDeviceFromId(*selectedDeviceId);
Paul McLean466dc8e2015-04-17 13:15:36 -06002490
Eric Laurentad2e7b92017-09-14 20:06:42 -07002491 // special case for mmap capture: if an input IO handle is specified, we reuse this input if
2492 // possible
2493 if ((flags & AUDIO_INPUT_FLAG_MMAP_NOIRQ) == AUDIO_INPUT_FLAG_MMAP_NOIRQ &&
2494 *input != AUDIO_IO_HANDLE_NONE) {
2495 ssize_t index = mInputs.indexOfKey(*input);
2496 if (index < 0) {
2497 ALOGW("getInputForAttr() unknown MMAP input %d", *input);
2498 status = BAD_VALUE;
2499 goto error;
2500 }
2501 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002502 RecordClientVector clients = inputDesc->getClientsForSession(session);
2503 if (clients.size() == 0) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07002504 ALOGW("getInputForAttr() unknown session %d on input %d", session, *input);
2505 status = BAD_VALUE;
2506 goto error;
2507 }
2508 // For MMAP mode, the first call to getInputForAttr() is made on behalf of audioflinger.
2509 // The second call is for the first active client and sets the UID. Any further call
Eric Laurent331679c2018-04-16 17:03:16 -07002510 // corresponds to a new client and is only permitted from the same UID.
2511 // If the first UID is silenced, allow a new UID connection and replace with new UID
Eric Laurent8f42ea12018-08-08 09:08:25 -07002512 if (clients.size() > 1) {
2513 for (const auto& client : clients) {
2514 // The client map is ordered by key values (portId) and portIds are allocated
2515 // incrementaly. So the first client in this list is the one opened by audio flinger
2516 // when the mmap stream is created and should be ignored as it does not correspond
2517 // to an actual client
2518 if (client == *clients.cbegin()) {
2519 continue;
2520 }
2521 if (uid != client->uid() && !client->isSilenced()) {
2522 ALOGW("getInputForAttr() bad uid %d for client %d uid %d",
2523 uid, client->portId(), client->uid());
2524 status = INVALID_OPERATION;
2525 goto error;
2526 }
Eric Laurent331679c2018-04-16 17:03:16 -07002527 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002528 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002529 *inputType = API_INPUT_LEGACY;
François Gaffie11d30102018-11-02 16:09:09 +01002530 device = inputDesc->getDevice();
Eric Laurentad2e7b92017-09-14 20:06:42 -07002531
Eric Laurentfecbceb2021-02-09 14:46:43 +01002532 ALOGV("%s reusing MMAP input %d for session %d", __FUNCTION__, *input, session);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002533 goto exit;
Eric Laurentad2e7b92017-09-14 20:06:42 -07002534 }
2535
2536 *input = AUDIO_IO_HANDLE_NONE;
2537 *inputType = API_INPUT_INVALID;
2538
Francois Gaffie716e1432019-01-14 16:58:59 +01002539 if (attributes.source == AUDIO_SOURCE_REMOTE_SUBMIX &&
2540 strncmp(attributes.tags, "addr=", strlen("addr=")) == 0) {
2541 status = mPolicyMixes.getInputMixForAttr(attributes, &policyMix);
Eric Laurentad2e7b92017-09-14 20:06:42 -07002542 if (status != NO_ERROR) {
jiabinc1de2df2019-05-07 14:26:40 -07002543 ALOGW("%s could not find input mix for attr %s",
2544 __func__, toString(attributes).c_str());
Eric Laurentad2e7b92017-09-14 20:06:42 -07002545 goto error;
François Gaffie036e1e92015-03-19 10:16:24 +01002546 }
jiabinc1de2df2019-05-07 14:26:40 -07002547 device = mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2548 String8(attr->tags + strlen("addr=")),
2549 AUDIO_FORMAT_DEFAULT);
2550 if (device == nullptr) {
Kevin Rocard04ed0462019-05-02 17:53:24 -07002551 ALOGW("%s could not find in Remote Submix device for source %d, tags %s",
jiabinc1de2df2019-05-07 14:26:40 -07002552 __func__, attributes.source, attributes.tags);
2553 status = BAD_VALUE;
2554 goto error;
2555 }
2556
Kevin Rocard25f9b052019-02-27 15:08:54 -08002557 if (is_mix_loopback_render(policyMix->mRouteFlags)) {
2558 *inputType = API_INPUT_MIX_PUBLIC_CAPTURE_PLAYBACK;
2559 } else {
2560 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
2561 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002562 } else {
François Gaffie11d30102018-11-02 16:09:09 +01002563 if (explicitRoutingDevice != nullptr) {
2564 device = explicitRoutingDevice;
Eric Laurent97ac8712018-07-27 18:59:02 -07002565 } else {
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01002566 // Prevent from storing invalid requested device id in clients
2567 requestedDeviceId = AUDIO_PORT_HANDLE_NONE;
yuanjiahsu0735bf32021-03-18 08:12:54 +08002568 device = mEngine->getInputDeviceForAttributes(attributes, uid, &policyMix);
yuanjiahsu4069d5d2021-04-19 07:54:27 +08002569 ALOGV_IF(device != nullptr, "%s found device type is 0x%X",
2570 __FUNCTION__, device->type());
Eric Laurent97ac8712018-07-27 18:59:02 -07002571 }
François Gaffie11d30102018-11-02 16:09:09 +01002572 if (device == nullptr) {
Francois Gaffie716e1432019-01-14 16:58:59 +01002573 ALOGW("getInputForAttr() could not find device for source %d", attributes.source);
Eric Laurentad2e7b92017-09-14 20:06:42 -07002574 status = BAD_VALUE;
2575 goto error;
Eric Laurent275e8e92014-11-30 15:14:47 -08002576 }
Alden DSouzab7d20782021-02-08 08:51:42 -08002577 if (device->type() == AUDIO_DEVICE_IN_ECHO_REFERENCE) {
2578 *inputType = API_INPUT_MIX_CAPTURE;
2579 } else if (policyMix) {
François Gaffie11d30102018-11-02 16:09:09 +01002580 ALOG_ASSERT(policyMix->mMixType == MIX_TYPE_RECORDERS, "Invalid Mix Type");
2581 // there is an external policy, but this input is attached to a mix of recorders,
2582 // meaning it receives audio injected into the framework, so the recorder doesn't
2583 // know about it and is therefore considered "legacy"
2584 *inputType = API_INPUT_LEGACY;
2585 } else if (audio_is_remote_submix_device(device->type())) {
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002586 *inputType = API_INPUT_MIX_CAPTURE;
François Gaffie11d30102018-11-02 16:09:09 +01002587 } else if (device->type() == AUDIO_DEVICE_IN_TELEPHONY_RX) {
Eric Laurent82db2692015-08-07 13:59:42 -07002588 *inputType = API_INPUT_TELEPHONY_RX;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002589 } else {
2590 *inputType = API_INPUT_LEGACY;
Eric Laurentc722f302014-12-10 11:21:49 -08002591 }
Ravi Kumar Alamandab367f5b2015-08-25 08:21:37 -07002592
Eric Laurent599c7582015-12-07 18:05:55 -08002593 }
2594
François Gaffiec005e562018-11-06 15:04:49 +01002595 *input = getInputForDevice(device, session, attributes, config, flags, policyMix);
Eric Laurent599c7582015-12-07 18:05:55 -08002596 if (*input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07002597 status = INVALID_OPERATION;
2598 goto error;
Eric Laurent599c7582015-12-07 18:05:55 -08002599 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08002600
Eric Laurent8f42ea12018-08-08 09:08:25 -07002601exit:
2602
François Gaffiec005e562018-11-06 15:04:49 +01002603 *selectedDeviceId = mAvailableInputDevices.contains(device) ?
2604 device->getId() : AUDIO_PORT_HANDLE_NONE;
Eric Laurent2ac76942017-06-22 17:17:09 -07002605
Francois Gaffie716e1432019-01-14 16:58:59 +01002606 isSoundTrigger = attributes.source == AUDIO_SOURCE_HOTWORD &&
Carter Hsud0cce2e2019-05-03 17:36:28 +08002607 mSoundTriggerSessions.indexOfKey(session) >= 0;
jiabin4ef93452019-09-10 14:29:54 -07002608 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002609
Mikhail Naganov2996f672019-04-18 12:29:59 -07002610 clientDesc = new RecordClientDescriptor(*portId, riid, uid, session, attributes, *config,
Francois Gaffie716e1432019-01-14 16:58:59 +01002611 requestedDeviceId, attributes.source, flags,
2612 isSoundTrigger);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002613 inputDesc = mInputs.valueFor(*input);
Andy Hung39efb7a2018-09-26 15:39:28 -07002614 inputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002615
2616 ALOGV("getInputForAttr() returns input %d type %d selectedDeviceId %d for port ID %d",
2617 *input, *inputType, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07002618
Eric Laurent599c7582015-12-07 18:05:55 -08002619 return NO_ERROR;
Eric Laurentad2e7b92017-09-14 20:06:42 -07002620
2621error:
Eric Laurentad2e7b92017-09-14 20:06:42 -07002622 return status;
Eric Laurent599c7582015-12-07 18:05:55 -08002623}
2624
2625
François Gaffie11d30102018-11-02 16:09:09 +01002626audio_io_handle_t AudioPolicyManager::getInputForDevice(const sp<DeviceDescriptor> &device,
Eric Laurent599c7582015-12-07 18:05:55 -08002627 audio_session_t session,
François Gaffiec005e562018-11-06 15:04:49 +01002628 const audio_attributes_t &attributes,
Eric Laurentfe231122017-11-17 17:48:06 -08002629 const audio_config_base_t *config,
Eric Laurent599c7582015-12-07 18:05:55 -08002630 audio_input_flags_t flags,
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002631 const sp<AudioPolicyMix> &policyMix)
Eric Laurent599c7582015-12-07 18:05:55 -08002632{
2633 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
François Gaffiec005e562018-11-06 15:04:49 +01002634 audio_source_t halInputSource = attributes.source;
Eric Laurent599c7582015-12-07 18:05:55 -08002635 bool isSoundTrigger = false;
2636
François Gaffiec005e562018-11-06 15:04:49 +01002637 if (attributes.source == AUDIO_SOURCE_HOTWORD) {
Eric Laurent599c7582015-12-07 18:05:55 -08002638 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
2639 if (index >= 0) {
2640 input = mSoundTriggerSessions.valueFor(session);
2641 isSoundTrigger = true;
2642 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_HW_HOTWORD);
2643 ALOGV("SoundTrigger capture on session %d input %d", session, input);
2644 } else {
2645 halInputSource = AUDIO_SOURCE_VOICE_RECOGNITION;
Eric Laurent5dbe4712014-09-19 19:04:57 -07002646 }
François Gaffiec005e562018-11-06 15:04:49 +01002647 } else if (attributes.source == AUDIO_SOURCE_VOICE_COMMUNICATION &&
Eric Laurentfe231122017-11-17 17:48:06 -08002648 audio_is_linear_pcm(config->format)) {
Haynes Mathew George851d3ff2017-06-19 20:01:57 -07002649 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_VOIP_TX);
Eric Laurent5dbe4712014-09-19 19:04:57 -07002650 }
2651
Carter Hsua3abb402021-10-26 11:11:20 +08002652 if (attributes.source == AUDIO_SOURCE_ULTRASOUND) {
2653 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_ULTRASOUND);
2654 }
2655
Andy Hungf129b032015-04-07 13:45:50 -07002656 // find a compatible input profile (not necessarily identical in parameters)
2657 sp<IOProfile> profile;
Eric Laurentfe231122017-11-17 17:48:06 -08002658 // sampling rate and flags may be updated by getInputProfile
2659 uint32_t profileSamplingRate = (config->sample_rate == 0) ?
2660 SAMPLE_RATE_HZ_DEFAULT : config->sample_rate;
Glenn Kasten730b9262018-03-29 15:01:26 -07002661 audio_format_t profileFormat;
Eric Laurentfe231122017-11-17 17:48:06 -08002662 audio_channel_mask_t profileChannelMask = config->channel_mask;
Andy Hungf129b032015-04-07 13:45:50 -07002663 audio_input_flags_t profileFlags = flags;
2664 for (;;) {
Glenn Kasten730b9262018-03-29 15:01:26 -07002665 profileFormat = config->format; // reset each time through loop, in case it is updated
François Gaffie11d30102018-11-02 16:09:09 +01002666 profile = getInputProfile(device, profileSamplingRate, profileFormat, profileChannelMask,
Andy Hungf129b032015-04-07 13:45:50 -07002667 profileFlags);
2668 if (profile != 0) {
2669 break; // success
Eric Laurent05067782016-06-01 18:27:28 -07002670 } else if (profileFlags & AUDIO_INPUT_FLAG_RAW) {
2671 profileFlags = (audio_input_flags_t) (profileFlags & ~AUDIO_INPUT_FLAG_RAW); // retry
Atneya Nair497fff12022-01-18 16:23:04 -05002672 } else if (profileFlags != AUDIO_INPUT_FLAG_NONE && audio_is_linear_pcm(config->format)) {
Andy Hungf129b032015-04-07 13:45:50 -07002673 profileFlags = AUDIO_INPUT_FLAG_NONE; // retry
2674 } else { // fail
François Gaffie11d30102018-11-02 16:09:09 +01002675 ALOGW("%s could not find profile for device %s, sampling rate %u, format %#x, "
Pattydd807582021-11-04 21:01:03 +08002676 "channel mask 0x%X, flags %#x", __func__, device->toString().c_str(),
François Gaffie11d30102018-11-02 16:09:09 +01002677 config->sample_rate, config->format, config->channel_mask, flags);
Eric Laurent599c7582015-12-07 18:05:55 -08002678 return input;
Eric Laurent5dbe4712014-09-19 19:04:57 -07002679 }
Eric Laurente552edb2014-03-10 17:42:56 -07002680 }
Glenn Kasten05ddca52016-02-11 08:17:12 -08002681 // Pick input sampling rate if not specified by client
Eric Laurentfe231122017-11-17 17:48:06 -08002682 uint32_t samplingRate = config->sample_rate;
Glenn Kasten05ddca52016-02-11 08:17:12 -08002683 if (samplingRate == 0) {
2684 samplingRate = profileSamplingRate;
2685 }
Eric Laurente552edb2014-03-10 17:42:56 -07002686
Eric Laurent322b4d22015-04-03 15:57:54 -07002687 if (profile->getModuleHandle() == 0) {
2688 ALOGE("getInputForAttr(): HW module %s not opened", profile->getModuleName());
Eric Laurent599c7582015-12-07 18:05:55 -08002689 return input;
Eric Laurentcf2c0212014-07-25 16:20:43 -07002690 }
2691
Eric Laurentec376dc2021-04-08 20:41:22 +02002692 // Reuse an already opened input if a client with the same session ID already exists
2693 // on that input
2694 for (size_t i = 0; i < mInputs.size(); i++) {
2695 sp <AudioInputDescriptor> desc = mInputs.valueAt(i);
2696 if (desc->mProfile != profile) {
2697 continue;
2698 }
2699 RecordClientVector clients = desc->clientsList();
2700 for (const auto &client : clients) {
2701 if (session == client->session()) {
2702 return desc->mIoHandle;
2703 }
2704 }
2705 }
2706
Eric Laurent3974e3b2017-12-07 17:58:43 -08002707 if (!profile->canOpenNewIo()) {
Eric Laurent4eb58f12018-12-07 16:41:02 -08002708 for (size_t i = 0; i < mInputs.size(); ) {
Eric Laurentc529cf62020-04-17 18:19:10 -07002709 sp<AudioInputDescriptor> desc = mInputs.valueAt(i);
Eric Laurent4eb58f12018-12-07 16:41:02 -08002710 if (desc->mProfile != profile) {
Carter Hsu9a645a92019-05-15 12:15:32 +08002711 i++;
Eric Laurent4eb58f12018-12-07 16:41:02 -08002712 continue;
2713 }
2714 // if sound trigger, reuse input if used by other sound trigger on same session
2715 // else
2716 // reuse input if active client app is not in IDLE state
2717 //
2718 RecordClientVector clients = desc->clientsList();
2719 bool doClose = false;
2720 for (const auto& client : clients) {
2721 if (isSoundTrigger != client->isSoundTrigger()) {
2722 continue;
2723 }
2724 if (client->isSoundTrigger()) {
2725 if (session == client->session()) {
2726 return desc->mIoHandle;
2727 }
2728 continue;
2729 }
2730 if (client->active() && client->appState() != APP_STATE_IDLE) {
2731 return desc->mIoHandle;
2732 }
2733 doClose = true;
2734 }
2735 if (doClose) {
2736 closeInput(desc->mIoHandle);
2737 } else {
2738 i++;
2739 }
2740 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002741 }
2742
Eric Laurentfe231122017-11-17 17:48:06 -08002743 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07002744
Eric Laurentfe231122017-11-17 17:48:06 -08002745 audio_config_t lConfig = AUDIO_CONFIG_INITIALIZER;
2746 lConfig.sample_rate = profileSamplingRate;
2747 lConfig.channel_mask = profileChannelMask;
2748 lConfig.format = profileFormat;
Eric Laurente3014102017-05-03 11:15:43 -07002749
François Gaffie11d30102018-11-02 16:09:09 +01002750 status_t status = inputDesc->open(&lConfig, device, halInputSource, profileFlags, &input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07002751
2752 // only accept input with the exact requested set of parameters
Eric Laurent599c7582015-12-07 18:05:55 -08002753 if (status != NO_ERROR || input == AUDIO_IO_HANDLE_NONE ||
Eric Laurentfe231122017-11-17 17:48:06 -08002754 (profileSamplingRate != lConfig.sample_rate) ||
2755 !audio_formats_match(profileFormat, lConfig.format) ||
2756 (profileChannelMask != lConfig.channel_mask)) {
2757 ALOGW("getInputForAttr() failed opening input: sampling rate %d"
Glenn Kasten49f36ba2017-12-06 13:02:02 -08002758 ", format %#x, channel mask %#x",
Eric Laurentfe231122017-11-17 17:48:06 -08002759 profileSamplingRate, profileFormat, profileChannelMask);
Eric Laurent599c7582015-12-07 18:05:55 -08002760 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfe231122017-11-17 17:48:06 -08002761 inputDesc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07002762 }
Eric Laurent599c7582015-12-07 18:05:55 -08002763 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07002764 }
2765
Eric Laurentc722f302014-12-10 11:21:49 -08002766 inputDesc->mPolicyMix = policyMix;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002767
Eric Laurent599c7582015-12-07 18:05:55 -08002768 addInput(input, inputDesc);
Eric Laurentb52c1522014-05-20 11:27:36 -07002769 mpClientInterface->onAudioPortListUpdate();
Paul McLean466dc8e2015-04-17 13:15:36 -06002770
Eric Laurent599c7582015-12-07 18:05:55 -08002771 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07002772}
2773
Eric Laurent4eb58f12018-12-07 16:41:02 -08002774status_t AudioPolicyManager::startInput(audio_port_handle_t portId)
Eric Laurentbb948092017-01-23 18:33:30 -08002775{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002776 ALOGV("%s portId %d", __FUNCTION__, portId);
2777
2778 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2779 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002780 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurentd52a28c2020-08-21 17:10:39 -07002781 return DEAD_OBJECT;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002782 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002783 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07002784 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002785 if (client->active()) {
2786 ALOGW("%s input %d client %d already started", __FUNCTION__, input, client->portId());
2787 return INVALID_OPERATION;
Eric Laurent4dc68062014-07-28 17:26:49 -07002788 }
2789
Eric Laurent8f42ea12018-08-08 09:08:25 -07002790 audio_session_t session = client->session();
2791
Eric Laurent4eb58f12018-12-07 16:41:02 -08002792 ALOGV("%s input:%d, session:%d)", __FUNCTION__, input, session);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002793
Eric Laurent4eb58f12018-12-07 16:41:02 -08002794 Vector<sp<AudioInputDescriptor>> activeInputs = mInputs.getActiveInputs();
Eric Laurent74708e72017-04-07 17:13:42 -07002795
Eric Laurent4eb58f12018-12-07 16:41:02 -08002796 status_t status = inputDesc->start();
2797 if (status != NO_ERROR) {
2798 return status;
Eric Laurent74708e72017-04-07 17:13:42 -07002799 }
Eric Laurente552edb2014-03-10 17:42:56 -07002800
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002801 // increment activity count before calling getNewInputDevice() below as only active sessions
Eric Laurent313d1e72016-01-29 09:56:57 -08002802 // are considered for device selection
Eric Laurent8f42ea12018-08-08 09:08:25 -07002803 inputDesc->setClientActive(client, true);
Eric Laurent313d1e72016-01-29 09:56:57 -08002804
Eric Laurent8f42ea12018-08-08 09:08:25 -07002805 // indicate active capture to sound trigger service if starting capture from a mic on
2806 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01002807 sp<DeviceDescriptor> device = getNewInputDevice(inputDesc);
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002808 if (device != nullptr) {
2809 status = setInputDevice(input, device, true /* force */);
2810 } else {
2811 ALOGW("%s no new input device can be found for descriptor %d",
2812 __FUNCTION__, inputDesc->getId());
2813 status = BAD_VALUE;
2814 }
Eric Laurente552edb2014-03-10 17:42:56 -07002815
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002816 if (status == NO_ERROR && inputDesc->activeCount() == 1) {
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002817 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002818 // if input maps to a dynamic policy with an activity listener, notify of state change
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002819 if ((policyMix != nullptr)
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002820 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
2821 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
Eric Laurent8f42ea12018-08-08 09:08:25 -07002822 MIX_STATE_MIXING);
Eric Laurent733ce942017-12-07 12:18:25 -08002823 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002824
François Gaffie11d30102018-11-02 16:09:09 +01002825 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
2826 if (primaryInputDevices.contains(device) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07002827 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 1) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07002828 mpClientInterface->setSoundTriggerCaptureState(true);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002829 }
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002830
Eric Laurent8f42ea12018-08-08 09:08:25 -07002831 // automatically enable the remote submix output when input is started if not
2832 // used by a policy mix of type MIX_TYPE_RECORDERS
2833 // For remote submix (a virtual device), we open only one input per capture request.
François Gaffie11d30102018-11-02 16:09:09 +01002834 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002835 String8 address = String8("");
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002836 if (policyMix == nullptr) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002837 address = String8("0");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002838 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
2839 address = policyMix->mDeviceAddress;
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002840 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07002841 if (address != "") {
2842 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2843 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002844 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurentc722f302014-12-10 11:21:49 -08002845 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07002846 }
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002847 } else if (status != NO_ERROR) {
2848 // Restore client activity state.
2849 inputDesc->setClientActive(client, false);
2850 inputDesc->stop();
Eric Laurente552edb2014-03-10 17:42:56 -07002851 }
2852
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002853 ALOGV("%s input %d source = %d status = %d exit",
2854 __FUNCTION__, input, client->source(), status);
Eric Laurente552edb2014-03-10 17:42:56 -07002855
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002856 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07002857}
2858
Eric Laurent8fc147b2018-07-22 19:13:55 -07002859status_t AudioPolicyManager::stopInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002860{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002861 ALOGV("%s portId %d", __FUNCTION__, portId);
2862
2863 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2864 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002865 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002866 return BAD_VALUE;
2867 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002868 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07002869 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002870 if (!client->active()) {
2871 ALOGW("%s input %d client %d already stopped", __FUNCTION__, input, client->portId());
Eric Laurente552edb2014-03-10 17:42:56 -07002872 return INVALID_OPERATION;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002873 }
Carter Hsue6139d52021-07-08 10:30:20 +08002874 auto old_source = inputDesc->source();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002875 inputDesc->setClientActive(client, false);
Paul McLean466dc8e2015-04-17 13:15:36 -06002876
Eric Laurent8f42ea12018-08-08 09:08:25 -07002877 inputDesc->stop();
2878 if (inputDesc->isActive()) {
Carter Hsue6139d52021-07-08 10:30:20 +08002879 auto current_source = inputDesc->source();
2880 setInputDevice(input, getNewInputDevice(inputDesc),
2881 old_source != current_source /* force */);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002882 } else {
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002883 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002884 // if input maps to a dynamic policy with an activity listener, notify of state change
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002885 if ((policyMix != nullptr)
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002886 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
2887 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
Eric Laurent8f42ea12018-08-08 09:08:25 -07002888 MIX_STATE_IDLE);
Eric Laurent84332aa2016-01-28 22:19:18 +00002889 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07002890
2891 // automatically disable the remote submix output when input is stopped if not
2892 // used by a policy mix of type MIX_TYPE_RECORDERS
François Gaffie11d30102018-11-02 16:09:09 +01002893 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002894 String8 address = String8("");
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002895 if (policyMix == nullptr) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002896 address = String8("0");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002897 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
2898 address = policyMix->mDeviceAddress;
Eric Laurent8f42ea12018-08-08 09:08:25 -07002899 }
2900 if (address != "") {
2901 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2902 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002903 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002904 }
2905 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07002906 resetInputDevice(input);
2907
2908 // indicate inactive capture to sound trigger service if stopping capture from a mic on
2909 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01002910 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
2911 if (primaryInputDevices.contains(inputDesc->getDevice()) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07002912 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07002913 mpClientInterface->setSoundTriggerCaptureState(false);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002914 }
2915 inputDesc->clearPreemptedSessions();
Eric Laurente552edb2014-03-10 17:42:56 -07002916 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002917 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07002918}
2919
Eric Laurent8fc147b2018-07-22 19:13:55 -07002920void AudioPolicyManager::releaseInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002921{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002922 ALOGV("%s portId %d", __FUNCTION__, portId);
2923
2924 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2925 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002926 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002927 return;
2928 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002929 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002930 audio_io_handle_t input = inputDesc->mIoHandle;
2931
Eric Laurent8f42ea12018-08-08 09:08:25 -07002932 ALOGV("%s %d", __FUNCTION__, input);
Paul McLean466dc8e2015-04-17 13:15:36 -06002933
Andy Hung39efb7a2018-09-26 15:39:28 -07002934 inputDesc->removeClient(portId);
Eric Laurent599c7582015-12-07 18:05:55 -08002935
Andy Hung39efb7a2018-09-26 15:39:28 -07002936 if (inputDesc->getClientCount() > 0) {
2937 ALOGV("%s(%d) %zu clients remaining", __func__, portId, inputDesc->getClientCount());
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002938 return;
2939 }
2940
Eric Laurent05b90f82014-08-27 15:32:29 -07002941 closeInput(input);
Eric Laurentb52c1522014-05-20 11:27:36 -07002942 mpClientInterface->onAudioPortListUpdate();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002943 ALOGV("%s exit", __FUNCTION__);
Eric Laurente552edb2014-03-10 17:42:56 -07002944}
2945
Eric Laurent8f42ea12018-08-08 09:08:25 -07002946void AudioPolicyManager::closeActiveClients(const sp<AudioInputDescriptor>& input)
Eric Laurent8fc147b2018-07-22 19:13:55 -07002947{
Eric Laurent8f42ea12018-08-08 09:08:25 -07002948 RecordClientVector clients = input->clientsList(true);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002949
2950 for (const auto& client : clients) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002951 closeClient(client->portId());
Eric Laurent8fc147b2018-07-22 19:13:55 -07002952 }
2953}
2954
Eric Laurent8f42ea12018-08-08 09:08:25 -07002955void AudioPolicyManager::closeClient(audio_port_handle_t portId)
2956{
2957 stopInput(portId);
2958 releaseInput(portId);
2959}
Eric Laurent8fc147b2018-07-22 19:13:55 -07002960
Eric Laurent0dd51852019-04-19 18:18:58 -07002961void AudioPolicyManager::checkCloseInputs() {
2962 // After connecting or disconnecting an input device, close input if:
2963 // - it has no client (was just opened to check profile) OR
2964 // - none of its supported devices are connected anymore OR
2965 // - one of its clients cannot be routed to one of its supported
2966 // devices anymore. Otherwise update device selection
2967 std::vector<audio_io_handle_t> inputsToClose;
2968 for (size_t i = 0; i < mInputs.size(); i++) {
2969 const sp<AudioInputDescriptor> input = mInputs.valueAt(i);
2970 if (input->clientsList().size() == 0
Eric Laurent85732f42020-03-19 11:31:10 -07002971 || !mAvailableInputDevices.containsAtLeastOne(input->supportedDevices())) {
Eric Laurent0dd51852019-04-19 18:18:58 -07002972 inputsToClose.push_back(mInputs.keyAt(i));
2973 } else {
2974 bool close = false;
2975 for (const auto& client : input->clientsList()) {
2976 sp<DeviceDescriptor> device =
yuanjiahsu0735bf32021-03-18 08:12:54 +08002977 mEngine->getInputDeviceForAttributes(client->attributes(), client->uid());
Eric Laurent0dd51852019-04-19 18:18:58 -07002978 if (!input->supportedDevices().contains(device)) {
2979 close = true;
2980 break;
2981 }
2982 }
2983 if (close) {
2984 inputsToClose.push_back(mInputs.keyAt(i));
2985 } else {
2986 setInputDevice(input->mIoHandle, getNewInputDevice(input));
2987 }
2988 }
2989 }
2990
2991 for (const audio_io_handle_t handle : inputsToClose) {
2992 ALOGV("%s closing input %d", __func__, handle);
2993 closeInput(handle);
Eric Laurent05b90f82014-08-27 15:32:29 -07002994 }
Eric Laurentd4692962014-05-05 18:13:44 -07002995}
2996
François Gaffie251c7f02018-11-07 10:41:08 +01002997void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream, int indexMin, int indexMax)
Eric Laurente552edb2014-03-10 17:42:56 -07002998{
2999 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08003000 if (indexMin < 0 || indexMax < 0) {
3001 ALOGE("%s for stream %d: invalid min %d or max %d", __func__, stream , indexMin, indexMax);
3002 return;
3003 }
Eric Laurentf5aa58d2019-02-22 18:20:11 -08003004 getVolumeCurves(stream).initVolume(indexMin, indexMax);
Eric Laurent28d09f02016-03-08 10:43:05 -08003005
3006 // initialize other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08003007 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
3008 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08003009 continue;
3010 }
Eric Laurentf5aa58d2019-02-22 18:20:11 -08003011 getVolumeCurves((audio_stream_type_t)curStream).initVolume(indexMin, indexMax);
Eric Laurent223fd5c2014-11-11 13:43:36 -08003012 }
Eric Laurente552edb2014-03-10 17:42:56 -07003013}
3014
Eric Laurente0720872014-03-11 09:30:41 -07003015status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
François Gaffie53615e22015-03-19 09:24:12 +01003016 int index,
3017 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07003018{
François Gaffieaaac0fd2018-11-22 17:56:39 +01003019 auto attributes = mEngine->getAttributesForStreamType(stream);
Eric Laurent242a9f82020-03-23 15:57:04 -07003020 if (attributes == AUDIO_ATTRIBUTES_INITIALIZER) {
3021 ALOGW("%s: no group for stream %s, bailing out", __func__, toString(stream).c_str());
3022 return NO_ERROR;
3023 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01003024 ALOGV("%s: stream %s attributes=%s", __func__,
3025 toString(stream).c_str(), toString(attributes).c_str());
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003026 return setVolumeIndexForAttributes(attributes, index, device);
Eric Laurente552edb2014-03-10 17:42:56 -07003027}
3028
Eric Laurente0720872014-03-11 09:30:41 -07003029status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
François Gaffieaaac0fd2018-11-22 17:56:39 +01003030 int *index,
3031 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07003032{
François Gaffiec005e562018-11-06 15:04:49 +01003033 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
3034 // stream by the engine.
jiabin9a3361e2019-10-01 09:38:30 -07003035 DeviceTypeSet deviceTypes = {device};
Eric Laurent5a2b6292016-04-14 18:05:57 -07003036 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
jiabin9a3361e2019-10-01 09:38:30 -07003037 deviceTypes = mEngine->getOutputDevicesForStream(
3038 stream, true /*fromCache*/).types();
Eric Laurente552edb2014-03-10 17:42:56 -07003039 }
jiabin9a3361e2019-10-01 09:38:30 -07003040 return getVolumeIndex(getVolumeCurves(stream), *index, deviceTypes);
Eric Laurente552edb2014-03-10 17:42:56 -07003041}
3042
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003043status_t AudioPolicyManager::setVolumeIndexForAttributes(const audio_attributes_t &attributes,
François Gaffiecfe17322018-11-07 13:41:29 +01003044 int index,
3045 audio_devices_t device)
3046{
3047 // Get Volume group matching the Audio Attributes
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003048 auto group = mEngine->getVolumeGroupForAttributes(attributes);
3049 if (group == VOLUME_GROUP_NONE) {
3050 ALOGD("%s: no group matching with %s", __FUNCTION__, toString(attributes).c_str());
François Gaffiecfe17322018-11-07 13:41:29 +01003051 return BAD_VALUE;
3052 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003053 ALOGV("%s: group %d matching with %s", __FUNCTION__, group, toString(attributes).c_str());
François Gaffiecfe17322018-11-07 13:41:29 +01003054 status_t status = NO_ERROR;
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003055 IVolumeCurves &curves = getVolumeCurves(attributes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01003056 VolumeSource vs = toVolumeSource(group);
Eric Laurentf9cccec2022-11-16 19:12:00 +01003057 // AUDIO_STREAM_BLUETOOTH_SCO is only used for volume control so we remap
3058 // to AUDIO_STREAM_VOICE_CALL to match with relevant playback activity
3059 VolumeSource activityVs = (vs == toVolumeSource(AUDIO_STREAM_BLUETOOTH_SCO, false)) ?
3060 toVolumeSource(AUDIO_STREAM_VOICE_CALL, false) : vs;
François Gaffieaaac0fd2018-11-22 17:56:39 +01003061 product_strategy_t strategy = mEngine->getProductStrategyForAttributes(attributes);
3062
3063 status = setVolumeCurveIndex(index, device, curves);
3064 if (status != NO_ERROR) {
3065 ALOGE("%s failed to set curve index for group %d device 0x%X", __func__, group, device);
3066 return status;
3067 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003068
jiabin9a3361e2019-10-01 09:38:30 -07003069 DeviceTypeSet curSrcDevices;
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003070 auto curCurvAttrs = curves.getAttributes();
3071 if (!curCurvAttrs.empty() && curCurvAttrs.front() != defaultAttr) {
3072 auto attr = curCurvAttrs.front();
jiabin9a3361e2019-10-01 09:38:30 -07003073 curSrcDevices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false).types();
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003074 } else if (!curves.getStreamTypes().empty()) {
3075 auto stream = curves.getStreamTypes().front();
jiabin9a3361e2019-10-01 09:38:30 -07003076 curSrcDevices = mEngine->getOutputDevicesForStream(stream, false).types();
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003077 } else {
3078 ALOGE("%s: Invalid src %d: no valid attributes nor stream",__func__, vs);
3079 return BAD_VALUE;
3080 }
jiabin9a3361e2019-10-01 09:38:30 -07003081 audio_devices_t curSrcDevice = Volume::getDeviceForVolume(curSrcDevices);
3082 resetDeviceTypes(curSrcDevices, curSrcDevice);
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003083
François Gaffiecfe17322018-11-07 13:41:29 +01003084 // update volume on all outputs and streams matching the following:
3085 // - The requested stream (or a stream matching for volume control) is active on the output
3086 // - The device (or devices) selected by the engine for this stream includes
3087 // the requested device
3088 // - For non default requested device, currently selected device on the output is either the
3089 // requested device or one of the devices selected by the engine for this stream
3090 // - For default requested device (AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME), apply volume only if
3091 // no specific device volume value exists for currently selected device.
François Gaffieaaac0fd2018-11-22 17:56:39 +01003092 for (size_t i = 0; i < mOutputs.size(); i++) {
3093 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
jiabin9a3361e2019-10-01 09:38:30 -07003094 DeviceTypeSet curDevices = desc->devices().types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01003095
jiabin9a3361e2019-10-01 09:38:30 -07003096 if (curDevices.erase(AUDIO_DEVICE_OUT_SPEAKER_SAFE)) {
3097 curDevices.insert(AUDIO_DEVICE_OUT_SPEAKER);
Robert Lee5e66e792019-04-03 18:37:15 +08003098 }
Eric Laurentf9cccec2022-11-16 19:12:00 +01003099
3100 if (!(desc->isActive(activityVs) || isInCallOrScreening())) {
François Gaffieed91f582020-01-31 10:35:37 +01003101 continue;
3102 }
3103 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME &&
3104 curDevices.find(device) == curDevices.end()) {
3105 continue;
3106 }
3107 bool applyVolume = false;
3108 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
3109 curSrcDevices.insert(device);
3110 applyVolume = (curSrcDevices.find(
3111 Volume::getDeviceForVolume(curDevices)) != curSrcDevices.end());
3112 } else {
3113 applyVolume = !curves.hasVolumeIndexForDevice(curSrcDevice);
3114 }
3115 if (!applyVolume) {
3116 continue; // next output
3117 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01003118 // Inter / intra volume group priority management: Loop on strategies arranged by priority
3119 // If a higher priority strategy is active, and the output is routed to a device with a
3120 // HW Gain management, do not change the volume
François Gaffieaaac0fd2018-11-22 17:56:39 +01003121 if (desc->useHwGain()) {
François Gaffieed91f582020-01-31 10:35:37 +01003122 applyVolume = false;
Francois Gaffie593634d2021-06-22 13:31:31 +02003123 // If the volume source is active with higher priority source, ensure at least Sw Muted
3124 desc->setSwMute((index == 0), vs, curves.getStreamTypes(), curDevices, 0 /*delayMs*/);
François Gaffieaaac0fd2018-11-22 17:56:39 +01003125 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
3126 auto activeClients = desc->clientsList(true /*activeOnly*/, productStrategy,
3127 false /*preferredDevice*/);
3128 if (activeClients.empty()) {
3129 continue;
3130 }
3131 bool isPreempted = false;
3132 bool isHigherPriority = productStrategy < strategy;
3133 for (const auto &client : activeClients) {
Eric Laurentf9cccec2022-11-16 19:12:00 +01003134 if (isHigherPriority && (client->volumeSource() != activityVs)) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01003135 ALOGV("%s: Strategy=%d (\nrequester:\n"
3136 " group %d, volumeGroup=%d attributes=%s)\n"
3137 " higher priority source active:\n"
3138 " volumeGroup=%d attributes=%s) \n"
3139 " on output %zu, bailing out", __func__, productStrategy,
3140 group, group, toString(attributes).c_str(),
3141 client->volumeSource(), toString(client->attributes()).c_str(), i);
3142 applyVolume = false;
3143 isPreempted = true;
3144 break;
3145 }
3146 // However, continue for loop to ensure no higher prio clients running on output
Eric Laurentf9cccec2022-11-16 19:12:00 +01003147 if (client->volumeSource() == activityVs) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01003148 applyVolume = true;
3149 }
3150 }
3151 if (isPreempted || applyVolume) {
3152 break;
3153 }
3154 }
3155 if (!applyVolume) {
3156 continue; // next output
3157 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01003158 }
François Gaffieed91f582020-01-31 10:35:37 +01003159 //FIXME: workaround for truncated touch sounds
3160 // delayed volume change for system stream to be removed when the problem is
3161 // handled by system UI
3162 status_t volStatus = checkAndSetVolume(
3163 curves, vs, index, desc, curDevices,
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003164 ((vs == toVolumeSource(AUDIO_STREAM_SYSTEM, false))?
François Gaffieed91f582020-01-31 10:35:37 +01003165 TOUCH_SOUND_FIXED_DELAY_MS : 0));
3166 if (volStatus != NO_ERROR) {
3167 status = volStatus;
François Gaffieaaac0fd2018-11-22 17:56:39 +01003168 }
3169 }
François Gaffiecfe17322018-11-07 13:41:29 +01003170 mpClientInterface->onAudioVolumeGroupChanged(group, 0 /*flags*/);
3171 return status;
3172}
3173
François Gaffieaaac0fd2018-11-22 17:56:39 +01003174status_t AudioPolicyManager::setVolumeCurveIndex(int index,
François Gaffiecfe17322018-11-07 13:41:29 +01003175 audio_devices_t device,
3176 IVolumeCurves &volumeCurves)
3177{
3178 // VOICE_CALL stream has minVolumeIndex > 0 but can be muted directly by an
3179 // app that has MODIFY_PHONE_STATE permission.
François Gaffieaaac0fd2018-11-22 17:56:39 +01003180 bool hasVoice = hasVoiceStream(volumeCurves.getStreamTypes());
3181 if (((index < volumeCurves.getVolumeIndexMin()) && !(hasVoice && index == 0)) ||
François Gaffiecfe17322018-11-07 13:41:29 +01003182 (index > volumeCurves.getVolumeIndexMax())) {
3183 ALOGD("%s: wrong index %d min=%d max=%d", __FUNCTION__, index,
3184 volumeCurves.getVolumeIndexMin(), volumeCurves.getVolumeIndexMax());
3185 return BAD_VALUE;
3186 }
3187 if (!audio_is_output_device(device)) {
3188 return BAD_VALUE;
3189 }
3190
3191 // Force max volume if stream cannot be muted
3192 if (!volumeCurves.canBeMuted()) index = volumeCurves.getVolumeIndexMax();
3193
François Gaffieaaac0fd2018-11-22 17:56:39 +01003194 ALOGV("%s device %08x, index %d", __FUNCTION__ , device, index);
François Gaffiecfe17322018-11-07 13:41:29 +01003195 volumeCurves.addCurrentVolumeIndex(device, index);
3196 return NO_ERROR;
3197}
3198
3199status_t AudioPolicyManager::getVolumeIndexForAttributes(const audio_attributes_t &attr,
3200 int &index,
3201 audio_devices_t device)
3202{
3203 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
3204 // stream by the engine.
jiabin9a3361e2019-10-01 09:38:30 -07003205 DeviceTypeSet deviceTypes = {device};
François Gaffiecfe17322018-11-07 13:41:29 +01003206 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
Mikhail Naganovbb990f22022-06-15 00:46:43 +00003207 deviceTypes = mEngine->getOutputDevicesForAttributes(
jiabin9a3361e2019-10-01 09:38:30 -07003208 attr, nullptr, true /*fromCache*/).types();
François Gaffiecfe17322018-11-07 13:41:29 +01003209 }
jiabin9a3361e2019-10-01 09:38:30 -07003210 return getVolumeIndex(getVolumeCurves(attr), index, deviceTypes);
François Gaffiecfe17322018-11-07 13:41:29 +01003211}
3212
3213status_t AudioPolicyManager::getVolumeIndex(const IVolumeCurves &curves,
3214 int &index,
jiabin9a3361e2019-10-01 09:38:30 -07003215 const DeviceTypeSet& deviceTypes) const
François Gaffiecfe17322018-11-07 13:41:29 +01003216{
Mikhail Naganovbb990f22022-06-15 00:46:43 +00003217 if (!isSingleDeviceType(deviceTypes, audio_is_output_device)) {
François Gaffiecfe17322018-11-07 13:41:29 +01003218 return BAD_VALUE;
3219 }
jiabin9a3361e2019-10-01 09:38:30 -07003220 index = curves.getVolumeIndex(deviceTypes);
3221 ALOGV("%s: device %s index %d", __FUNCTION__, dumpDeviceTypes(deviceTypes).c_str(), index);
François Gaffiecfe17322018-11-07 13:41:29 +01003222 return NO_ERROR;
3223}
3224
3225status_t AudioPolicyManager::getMinVolumeIndexForAttributes(const audio_attributes_t &attr,
3226 int &index)
3227{
3228 index = getVolumeCurves(attr).getVolumeIndexMin();
3229 return NO_ERROR;
3230}
3231
3232status_t AudioPolicyManager::getMaxVolumeIndexForAttributes(const audio_attributes_t &attr,
3233 int &index)
3234{
3235 index = getVolumeCurves(attr).getVolumeIndexMax();
3236 return NO_ERROR;
3237}
3238
Eric Laurent36829f92017-04-07 19:04:42 -07003239audio_io_handle_t AudioPolicyManager::selectOutputForMusicEffects()
Eric Laurente552edb2014-03-10 17:42:56 -07003240{
3241 // select one output among several suitable for global effects.
3242 // The priority is as follows:
3243 // 1: An offloaded output. If the effect ends up not being offloadable,
3244 // AudioFlinger will invalidate the track and the offloaded output
3245 // will be closed causing the effect to be moved to a PCM output.
3246 // 2: A deep buffer output
Eric Laurent36829f92017-04-07 19:04:42 -07003247 // 3: The primary output
3248 // 4: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07003249
François Gaffiec005e562018-11-06 15:04:49 +01003250 DeviceVector devices = mEngine->getOutputDevicesForAttributes(
3251 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
François Gaffie11d30102018-11-02 16:09:09 +01003252 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07003253
Eric Laurent36829f92017-04-07 19:04:42 -07003254 if (outputs.size() == 0) {
3255 return AUDIO_IO_HANDLE_NONE;
3256 }
Eric Laurente552edb2014-03-10 17:42:56 -07003257
Eric Laurent36829f92017-04-07 19:04:42 -07003258 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
3259 bool activeOnly = true;
3260
3261 while (output == AUDIO_IO_HANDLE_NONE) {
3262 audio_io_handle_t outputOffloaded = AUDIO_IO_HANDLE_NONE;
3263 audio_io_handle_t outputDeepBuffer = AUDIO_IO_HANDLE_NONE;
3264 audio_io_handle_t outputPrimary = AUDIO_IO_HANDLE_NONE;
3265
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003266 for (audio_io_handle_t output : outputs) {
3267 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
Eric Laurent83d17c22019-04-02 17:10:01 -07003268 if (activeOnly && !desc->isActive(toVolumeSource(AUDIO_STREAM_MUSIC))) {
Eric Laurent36829f92017-04-07 19:04:42 -07003269 continue;
3270 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003271 ALOGV("selectOutputForMusicEffects activeOnly %d output %d flags 0x%08x",
3272 activeOnly, output, desc->mFlags);
Eric Laurent36829f92017-04-07 19:04:42 -07003273 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003274 outputOffloaded = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003275 }
3276 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003277 outputDeepBuffer = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003278 }
3279 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003280 outputPrimary = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003281 }
3282 }
3283 if (outputOffloaded != AUDIO_IO_HANDLE_NONE) {
3284 output = outputOffloaded;
3285 } else if (outputDeepBuffer != AUDIO_IO_HANDLE_NONE) {
3286 output = outputDeepBuffer;
3287 } else if (outputPrimary != AUDIO_IO_HANDLE_NONE) {
3288 output = outputPrimary;
3289 } else {
3290 output = outputs[0];
3291 }
3292 activeOnly = false;
3293 }
3294
3295 if (output != mMusicEffectOutput) {
Eric Laurent6c796322019-04-09 14:13:17 -07003296 mEffects.moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output);
Eric Laurent36829f92017-04-07 19:04:42 -07003297 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output);
3298 mMusicEffectOutput = output;
3299 }
3300
3301 ALOGV("selectOutputForMusicEffects selected output %d", output);
Eric Laurente552edb2014-03-10 17:42:56 -07003302 return output;
3303}
3304
Eric Laurent36829f92017-04-07 19:04:42 -07003305audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc __unused)
3306{
3307 return selectOutputForMusicEffects();
3308}
3309
Eric Laurente0720872014-03-11 09:30:41 -07003310status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07003311 audio_io_handle_t io,
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08003312 product_strategy_t strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07003313 int session,
3314 int id)
3315{
Eric Laurentb82e6b72019-11-22 17:25:04 -08003316 if (session != AUDIO_SESSION_DEVICE) {
3317 ssize_t index = mOutputs.indexOfKey(io);
Eric Laurente552edb2014-03-10 17:42:56 -07003318 if (index < 0) {
Eric Laurentb82e6b72019-11-22 17:25:04 -08003319 index = mInputs.indexOfKey(io);
3320 if (index < 0) {
3321 ALOGW("registerEffect() unknown io %d", io);
3322 return INVALID_OPERATION;
3323 }
Eric Laurente552edb2014-03-10 17:42:56 -07003324 }
3325 }
Eric Laurentbf8f69f2022-03-25 17:48:38 +01003326 bool isMusicEffect = (session != AUDIO_SESSION_OUTPUT_STAGE)
3327 && ((strategy == streamToStrategy(AUDIO_STREAM_MUSIC)
3328 || strategy == PRODUCT_STRATEGY_NONE));
3329 return mEffects.registerEffect(desc, io, session, id, isMusicEffect);
Eric Laurente552edb2014-03-10 17:42:56 -07003330}
3331
Eric Laurentc241b0d2018-11-28 09:08:49 -08003332status_t AudioPolicyManager::unregisterEffect(int id)
3333{
3334 if (mEffects.getEffect(id) == nullptr) {
3335 return INVALID_OPERATION;
3336 }
Eric Laurentc241b0d2018-11-28 09:08:49 -08003337 if (mEffects.isEffectEnabled(id)) {
3338 ALOGW("%s effect %d enabled", __FUNCTION__, id);
3339 setEffectEnabled(id, false);
3340 }
3341 return mEffects.unregisterEffect(id);
3342}
3343
3344status_t AudioPolicyManager::setEffectEnabled(int id, bool enabled)
3345{
3346 sp<EffectDescriptor> effect = mEffects.getEffect(id);
3347 if (effect == nullptr) {
3348 return INVALID_OPERATION;
3349 }
3350
3351 status_t status = mEffects.setEffectEnabled(id, enabled);
3352 if (status == NO_ERROR) {
3353 mInputs.trackEffectEnabled(effect, enabled);
3354 }
3355 return status;
3356}
3357
Eric Laurent6c796322019-04-09 14:13:17 -07003358
3359status_t AudioPolicyManager::moveEffectsToIo(const std::vector<int>& ids, audio_io_handle_t io)
3360{
3361 mEffects.moveEffects(ids, io);
3362 return NO_ERROR;
3363}
3364
Eric Laurentc75307b2015-03-17 15:29:32 -07003365bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
3366{
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003367 auto vs = toVolumeSource(stream, false);
3368 return vs != VOLUME_SOURCE_NONE ? mOutputs.isActive(vs, inPastMs) : false;
Eric Laurentc75307b2015-03-17 15:29:32 -07003369}
3370
3371bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream, uint32_t inPastMs) const
3372{
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003373 auto vs = toVolumeSource(stream, false);
3374 return vs != VOLUME_SOURCE_NONE ? mOutputs.isActiveRemotely(vs, inPastMs) : false;
Eric Laurentc75307b2015-03-17 15:29:32 -07003375}
3376
Eric Laurente0720872014-03-11 09:30:41 -07003377bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07003378{
3379 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003380 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08003381 if (inputDescriptor->isSourceActive(source)) {
Eric Laurente552edb2014-03-10 17:42:56 -07003382 return true;
3383 }
3384 }
3385 return false;
3386}
3387
Eric Laurent275e8e92014-11-30 15:14:47 -08003388// Register a list of custom mixes with their attributes and format.
3389// When a mix is registered, corresponding input and output profiles are
3390// added to the remote submix hw module. The profile contains only the
3391// parameters (sampling rate, format...) specified by the mix.
3392// The corresponding input remote submix device is also connected.
3393//
3394// When a remote submix device is connected, the address is checked to select the
3395// appropriate profile and the corresponding input or output stream is opened.
3396//
3397// When capture starts, getInputForAttr() will:
3398// - 1 look for a mix matching the address passed in attribtutes tags if any
3399// - 2 if none found, getDeviceForInputSource() will:
3400// - 2.1 look for a mix matching the attributes source
3401// - 2.2 if none found, default to device selection by policy rules
3402// At this time, the corresponding output remote submix device is also connected
3403// and active playback use cases can be transferred to this mix if needed when reconnecting
3404// after AudioTracks are invalidated
3405//
3406// When playback starts, getOutputForAttr() will:
3407// - 1 look for a mix matching the address passed in attribtutes tags if any
3408// - 2 if none found, look for a mix matching the attributes usage
3409// - 3 if none found, default to device and output selection by policy rules.
3410
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003411status_t AudioPolicyManager::registerPolicyMixes(const Vector<AudioMix>& mixes)
Eric Laurent275e8e92014-11-30 15:14:47 -08003412{
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003413 ALOGV("registerPolicyMixes() %zu mix(es)", mixes.size());
3414 status_t res = NO_ERROR;
Eric Laurentc209fe42020-06-05 18:11:23 -07003415 bool checkOutputs = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003416 sp<HwModule> rSubmixModule;
3417 // examine each mix's route type
3418 for (size_t i = 0; i < mixes.size(); i++) {
Eric Laurent97ac8712018-07-27 18:59:02 -07003419 AudioMix mix = mixes[i];
Kevin Rocard153f92d2018-12-18 18:33:28 -08003420 // Only capture of playback is allowed in LOOP_BACK & RENDER mode
3421 if (is_mix_loopback_render(mix.mRouteFlags) && mix.mMixType != MIX_TYPE_PLAYERS) {
3422 ALOGE("Unsupported Policy Mix %zu of %zu: "
3423 "Only capture of playback is allowed in LOOP_BACK & RENDER mode",
3424 i, mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003425 res = INVALID_OPERATION;
Eric Laurent275e8e92014-11-30 15:14:47 -08003426 break;
3427 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08003428 // LOOP_BACK and LOOP_BACK | RENDER have the same remote submix backend and are handled
3429 // in the same way.
Eric Laurent97ac8712018-07-27 18:59:02 -07003430 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003431 ALOGV("registerPolicyMixes() mix %zu of %zu is LOOP_BACK %d", i, mixes.size(),
3432 mix.mRouteFlags);
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003433 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003434 rSubmixModule = mHwModules.getModuleFromName(
3435 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
3436 if (rSubmixModule == 0) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003437 ALOGE("Unable to find audio module for submix, aborting mix %zu registration",
Mikhail Naganovd4120142017-12-06 15:49:22 -08003438 i);
3439 res = INVALID_OPERATION;
3440 break;
3441 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003442 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003443
Eric Laurent97ac8712018-07-27 18:59:02 -07003444 String8 address = mix.mDeviceAddress;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003445 audio_devices_t deviceTypeToMakeAvailable;
Eric Laurent97ac8712018-07-27 18:59:02 -07003446 if (mix.mMixType == MIX_TYPE_PLAYERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07003447 mix.mDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003448 deviceTypeToMakeAvailable = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
3449 } else {
3450 mix.mDeviceType = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
3451 deviceTypeToMakeAvailable = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Eric Laurent97ac8712018-07-27 18:59:02 -07003452 }
François Gaffie036e1e92015-03-19 10:16:24 +01003453
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003454 if (mPolicyMixes.registerMix(mix, 0 /*output desc*/) != NO_ERROR) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003455 ALOGE("Error registering mix %zu for address %s", i, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003456 res = INVALID_OPERATION;
3457 break;
3458 }
Eric Laurent97ac8712018-07-27 18:59:02 -07003459 audio_config_t outputConfig = mix.mFormat;
3460 audio_config_t inputConfig = mix.mFormat;
Eric Laurentc529cf62020-04-17 18:19:10 -07003461 // NOTE: audio flinger mixer does not support mono output: configure remote submix HAL
3462 // in stereo and let audio flinger do the channel conversion if needed.
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003463 outputConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
3464 inputConfig.channel_mask = AUDIO_CHANNEL_IN_STEREO;
jiabin5740f082019-08-19 15:08:30 -07003465 rSubmixModule->addOutputProfile(address.c_str(), &outputConfig,
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003466 AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address);
jiabin5740f082019-08-19 15:08:30 -07003467 rSubmixModule->addInputProfile(address.c_str(), &inputConfig,
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003468 AUDIO_DEVICE_IN_REMOTE_SUBMIX, address);
François Gaffie036e1e92015-03-19 10:16:24 +01003469
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003470 if ((res = setDeviceConnectionStateInt(deviceTypeToMakeAvailable,
jiabinc1de2df2019-05-07 14:26:40 -07003471 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
3472 address.string(), "remote-submix", AUDIO_FORMAT_DEFAULT)) != NO_ERROR) {
3473 ALOGE("Failed to set remote submix device available, type %u, address %s",
3474 mix.mDeviceType, address.string());
3475 break;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003476 }
Eric Laurent97ac8712018-07-27 18:59:02 -07003477 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
3478 String8 address = mix.mDeviceAddress;
Eric Laurent2c80be02019-01-23 18:06:37 -08003479 audio_devices_t type = mix.mDeviceType;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003480 ALOGV(" registerPolicyMixes() mix %zu of %zu is RENDER, dev=0x%X addr=%s",
Eric Laurent2c80be02019-01-23 18:06:37 -08003481 i, mixes.size(), type, address.string());
3482
3483 sp<DeviceDescriptor> device = mHwModules.getDeviceDescriptor(
3484 mix.mDeviceType, mix.mDeviceAddress,
3485 String8(), AUDIO_FORMAT_DEFAULT);
3486 if (device == nullptr) {
3487 res = INVALID_OPERATION;
3488 break;
3489 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003490
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003491 bool foundOutput = false;
Eric Laurentc529cf62020-04-17 18:19:10 -07003492 // First try to find an already opened output supporting the device
3493 for (size_t j = 0 ; j < mOutputs.size() && !foundOutput && res == NO_ERROR; j++) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003494 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurent2c80be02019-01-23 18:06:37 -08003495
Eric Laurentc529cf62020-04-17 18:19:10 -07003496 if (!desc->isDuplicated() && desc->supportedDevices().contains(device)) {
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003497 if (mPolicyMixes.registerMix(mix, desc) != NO_ERROR) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003498 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
3499 address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003500 res = INVALID_OPERATION;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003501 } else {
3502 foundOutput = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003503 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003504 }
3505 }
Eric Laurentc529cf62020-04-17 18:19:10 -07003506 // If no output found, try to find a direct output profile supporting the device
3507 for (size_t i = 0; i < mHwModules.size() && !foundOutput && res == NO_ERROR; i++) {
3508 sp<HwModule> module = mHwModules[i];
3509 for (size_t j = 0;
3510 j < module->getOutputProfiles().size() && !foundOutput && res == NO_ERROR;
3511 j++) {
3512 sp<IOProfile> profile = module->getOutputProfiles()[j];
3513 if (profile->isDirectOutput() && profile->supportsDevice(device)) {
3514 if (mPolicyMixes.registerMix(mix, nullptr) != NO_ERROR) {
3515 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
3516 address.string());
3517 res = INVALID_OPERATION;
3518 } else {
3519 foundOutput = true;
3520 }
3521 }
3522 }
3523 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003524 if (res != NO_ERROR) {
3525 ALOGE(" Error registering mix %zu for device 0x%X addr %s",
Eric Laurent2c80be02019-01-23 18:06:37 -08003526 i, type, address.string());
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003527 res = INVALID_OPERATION;
3528 break;
3529 } else if (!foundOutput) {
3530 ALOGE(" Output not found for mix %zu for device 0x%X addr %s",
Eric Laurent2c80be02019-01-23 18:06:37 -08003531 i, type, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003532 res = INVALID_OPERATION;
3533 break;
Eric Laurentc209fe42020-06-05 18:11:23 -07003534 } else {
3535 checkOutputs = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003536 }
Eric Laurentc722f302014-12-10 11:21:49 -08003537 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003538 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003539 if (res != NO_ERROR) {
3540 unregisterPolicyMixes(mixes);
Eric Laurentc209fe42020-06-05 18:11:23 -07003541 } else if (checkOutputs) {
3542 checkForDeviceAndOutputChanges();
3543 updateCallAndOutputRouting();
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003544 }
3545 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08003546}
3547
3548status_t AudioPolicyManager::unregisterPolicyMixes(Vector<AudioMix> mixes)
3549{
Eric Laurent7b279bb2015-12-14 10:18:23 -08003550 ALOGV("unregisterPolicyMixes() num mixes %zu", mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003551 status_t res = NO_ERROR;
Eric Laurentc209fe42020-06-05 18:11:23 -07003552 bool checkOutputs = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003553 sp<HwModule> rSubmixModule;
3554 // examine each mix's route type
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003555 for (const auto& mix : mixes) {
3556 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie036e1e92015-03-19 10:16:24 +01003557
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003558 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003559 rSubmixModule = mHwModules.getModuleFromName(
3560 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
3561 if (rSubmixModule == 0) {
3562 res = INVALID_OPERATION;
3563 continue;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003564 }
3565 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003566
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003567 String8 address = mix.mDeviceAddress;
Eric Laurent275e8e92014-11-30 15:14:47 -08003568
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003569 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003570 res = INVALID_OPERATION;
3571 continue;
3572 }
3573
Kevin Rocard04ed0462019-05-02 17:53:24 -07003574 for (auto device : {AUDIO_DEVICE_IN_REMOTE_SUBMIX, AUDIO_DEVICE_OUT_REMOTE_SUBMIX}) {
3575 if (getDeviceConnectionState(device, address.string()) ==
3576 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
3577 res = setDeviceConnectionStateInt(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
3578 address.string(), "remote-submix",
3579 AUDIO_FORMAT_DEFAULT);
3580 if (res != OK) {
3581 ALOGE("Error making RemoteSubmix device unavailable for mix "
3582 "with type %d, address %s", device, address.string());
3583 }
3584 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003585 }
jiabin5740f082019-08-19 15:08:30 -07003586 rSubmixModule->removeOutputProfile(address.c_str());
3587 rSubmixModule->removeInputProfile(address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003588
Kevin Rocard153f92d2018-12-18 18:33:28 -08003589 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003590 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003591 res = INVALID_OPERATION;
3592 continue;
Eric Laurentc209fe42020-06-05 18:11:23 -07003593 } else {
3594 checkOutputs = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003595 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003596 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003597 }
Eric Laurentc209fe42020-06-05 18:11:23 -07003598 if (res == NO_ERROR && checkOutputs) {
3599 checkForDeviceAndOutputChanges();
3600 updateCallAndOutputRouting();
3601 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003602 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08003603}
3604
Mikhail Naganov100f0122018-11-29 11:22:16 -08003605void AudioPolicyManager::dumpManualSurroundFormats(String8 *dst) const
3606{
3607 size_t i = 0;
3608 constexpr size_t audioFormatPrefixLen = sizeof("AUDIO_FORMAT_");
3609 for (const auto& fmt : mManualSurroundFormats) {
3610 if (i++ != 0) dst->append(", ");
3611 std::string sfmt;
3612 FormatConverter::toString(fmt, sfmt);
3613 dst->append(sfmt.size() >= audioFormatPrefixLen ?
3614 sfmt.c_str() + audioFormatPrefixLen - 1 : sfmt.c_str());
3615 }
3616}
3617
Eric Laurentc529cf62020-04-17 18:19:10 -07003618// Returns true if all devices types match the predicate and are supported by one HW module
3619bool AudioPolicyManager::areAllDevicesSupported(
jiabin6a02d532020-08-07 11:56:38 -07003620 const AudioDeviceTypeAddrVector& devices,
Eric Laurentc529cf62020-04-17 18:19:10 -07003621 std::function<bool(audio_devices_t)> predicate,
3622 const char *context) {
3623 for (size_t i = 0; i < devices.size(); i++) {
3624 sp<DeviceDescriptor> devDesc = mHwModules.getDeviceDescriptor(
jiabin0a488932020-08-07 17:32:40 -07003625 devices[i].mType, devices[i].getAddress(), String8(),
Eric Laurent0e26e3f2020-04-29 14:24:16 -07003626 AUDIO_FORMAT_DEFAULT, false /*allowToCreate*/, true /*matchAddress*/);
Eric Laurentc529cf62020-04-17 18:19:10 -07003627 if (devDesc == nullptr || (predicate != nullptr && !predicate(devices[i].mType))) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003628 ALOGE("%s: device type %#x address %s not supported or not match predicate",
jiabin0a488932020-08-07 17:32:40 -07003629 context, devices[i].mType, devices[i].getAddress());
Eric Laurentc529cf62020-04-17 18:19:10 -07003630 return false;
3631 }
3632 }
3633 return true;
3634}
3635
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003636status_t AudioPolicyManager::setUidDeviceAffinities(uid_t uid,
jiabin6a02d532020-08-07 11:56:38 -07003637 const AudioDeviceTypeAddrVector& devices) {
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003638 ALOGV("%s() uid=%d num devices %zu", __FUNCTION__, uid, devices.size());
Eric Laurentc529cf62020-04-17 18:19:10 -07003639 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
3640 return BAD_VALUE;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003641 }
3642 status_t res = mPolicyMixes.setUidDeviceAffinities(uid, devices);
Eric Laurentc529cf62020-04-17 18:19:10 -07003643 if (res != NO_ERROR) {
3644 ALOGE("%s() Could not set all device affinities for uid = %d", __FUNCTION__, uid);
3645 return res;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003646 }
Eric Laurentc529cf62020-04-17 18:19:10 -07003647
3648 checkForDeviceAndOutputChanges();
3649 updateCallAndOutputRouting();
3650
3651 return NO_ERROR;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003652}
3653
3654status_t AudioPolicyManager::removeUidDeviceAffinities(uid_t uid) {
3655 ALOGV("%s() uid=%d", __FUNCTION__, uid);
Oscar Azucena4b2a8212019-04-26 23:48:59 -07003656 status_t res = mPolicyMixes.removeUidDeviceAffinities(uid);
3657 if (res != NO_ERROR) {
Eric Laurentc529cf62020-04-17 18:19:10 -07003658 ALOGE("%s() Could not remove all device affinities for uid = %d",
Oscar Azucena4b2a8212019-04-26 23:48:59 -07003659 __FUNCTION__, uid);
3660 return INVALID_OPERATION;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003661 }
3662
Eric Laurentc529cf62020-04-17 18:19:10 -07003663 checkForDeviceAndOutputChanges();
3664 updateCallAndOutputRouting();
3665
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003666 return res;
3667}
3668
Eric Laurent2517af32020-11-25 15:31:27 +01003669
jiabin0a488932020-08-07 17:32:40 -07003670status_t AudioPolicyManager::setDevicesRoleForStrategy(product_strategy_t strategy,
3671 device_role_t role,
3672 const AudioDeviceTypeAddrVector &devices) {
3673 ALOGV("%s() strategy=%d role=%d %s", __func__, strategy, role,
3674 dumpAudioDeviceTypeAddrVector(devices).c_str());
Eric Laurentc529cf62020-04-17 18:19:10 -07003675
Eric Laurentc529cf62020-04-17 18:19:10 -07003676 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003677 return BAD_VALUE;
3678 }
jiabin0a488932020-08-07 17:32:40 -07003679 status_t status = mEngine->setDevicesRoleForStrategy(strategy, role, devices);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003680 if (status != NO_ERROR) {
jiabin0a488932020-08-07 17:32:40 -07003681 ALOGW("Engine could not set preferred devices %s for strategy %d role %d",
3682 dumpAudioDeviceTypeAddrVector(devices).c_str(), strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003683 return status;
3684 }
3685
3686 checkForDeviceAndOutputChanges();
Eric Laurent2517af32020-11-25 15:31:27 +01003687
3688 bool forceVolumeReeval = false;
3689 // FIXME: workaround for truncated touch sounds
3690 // to be removed when the problem is handled by system UI
3691 uint32_t delayMs = 0;
3692 if (strategy == mCommunnicationStrategy) {
3693 forceVolumeReeval = true;
3694 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
3695 updateInputRouting();
3696 }
3697 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003698
3699 return NO_ERROR;
3700}
3701
3702void AudioPolicyManager::updateCallAndOutputRouting(bool forceVolumeReeval, uint32_t delayMs)
3703{
3704 uint32_t waitMs = 0;
Eric Laurent96d1dda2022-03-14 17:14:19 +01003705 bool wasLeUnicastActive = isLeUnicastActive();
Francois Gaffie19fd6c52021-02-04 17:02:59 +01003706 if (updateCallRouting(true /*fromCache*/, delayMs, &waitMs) == NO_ERROR) {
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 for (size_t i = 0; i < mOutputs.size(); i++) {
3711 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
3712 DeviceVector newDevices = getNewOutputDevices(outputDesc, true /*fromCache*/);
Francois Gaffie601801d2021-06-22 13:27:39 +02003713 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) ||
3714 (outputDesc != mPrimaryOutput && !isTelephonyRxOrTx(outputDesc))) {
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003715 // As done in setDeviceConnectionState, we could also fix default device issue by
3716 // preventing the force re-routing in case of default dev that distinguishes on address.
3717 // Let's give back to engine full device choice decision however.
Francois Gaffie601801d2021-06-22 13:27:39 +02003718 bool forceRouting = !newDevices.isEmpty();
3719 waitMs = setOutputDevices(outputDesc, newDevices, forceRouting, delayMs, nullptr,
3720 true /*requiresMuteCheck*/,
3721 !forceRouting /*requiresVolumeCheck*/);
Eric Laurentb36b4ac2020-08-21 12:50:41 -07003722 // Only apply special touch sound delay once
3723 delayMs = 0;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003724 }
3725 if (forceVolumeReeval && !newDevices.isEmpty()) {
3726 applyStreamVolumes(outputDesc, newDevices.types(), waitMs, true);
3727 }
3728 }
Eric Laurent96d1dda2022-03-14 17:14:19 +01003729 checkLeBroadcastRoutes(wasLeUnicastActive, nullptr, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003730}
3731
Eric Laurent2517af32020-11-25 15:31:27 +01003732void AudioPolicyManager::updateInputRouting() {
3733 for (const auto& activeDesc : mInputs.getActiveInputs()) {
Jaideep Sharma408349a2020-11-27 14:47:17 +05303734 // Skip for hotword recording as the input device switch
3735 // is handled within sound trigger HAL
3736 if (activeDesc->isSoundTrigger() && activeDesc->source() == AUDIO_SOURCE_HOTWORD) {
3737 continue;
3738 }
Eric Laurent2517af32020-11-25 15:31:27 +01003739 auto newDevice = getNewInputDevice(activeDesc);
3740 // Force new input selection if the new device can not be reached via current input
3741 if (activeDesc->mProfile->getSupportedDevices().contains(newDevice)) {
3742 setInputDevice(activeDesc->mIoHandle, newDevice);
3743 } else {
3744 closeInput(activeDesc->mIoHandle);
3745 }
3746 }
3747}
3748
jiabin0a488932020-08-07 17:32:40 -07003749status_t AudioPolicyManager::removeDevicesRoleForStrategy(product_strategy_t strategy,
3750 device_role_t role)
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003751{
Eric Laurentfecbceb2021-02-09 14:46:43 +01003752 ALOGV("%s() strategy=%d role=%d", __func__, strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003753
jiabin0a488932020-08-07 17:32:40 -07003754 status_t status = mEngine->removeDevicesRoleForStrategy(strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003755 if (status != NO_ERROR) {
Eric Laurent2517af32020-11-25 15:31:27 +01003756 ALOGV("Engine could not remove preferred device for strategy %d status %d",
3757 strategy, status);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003758 return status;
3759 }
3760
3761 checkForDeviceAndOutputChanges();
Eric Laurent2517af32020-11-25 15:31:27 +01003762
3763 bool forceVolumeReeval = false;
3764 // FIXME: workaround for truncated touch sounds
3765 // to be removed when the problem is handled by system UI
3766 uint32_t delayMs = 0;
3767 if (strategy == mCommunnicationStrategy) {
3768 forceVolumeReeval = true;
3769 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
3770 updateInputRouting();
3771 }
3772 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003773
3774 return NO_ERROR;
3775}
3776
jiabin0a488932020-08-07 17:32:40 -07003777status_t AudioPolicyManager::getDevicesForRoleAndStrategy(product_strategy_t strategy,
3778 device_role_t role,
3779 AudioDeviceTypeAddrVector &devices) {
3780 return mEngine->getDevicesForRoleAndStrategy(strategy, role, devices);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003781}
3782
Jiabin Huang3b98d322020-09-03 17:54:16 +00003783status_t AudioPolicyManager::setDevicesRoleForCapturePreset(
3784 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices) {
3785 ALOGV("%s() audioSource=%d role=%d %s", __func__, audioSource, role,
3786 dumpAudioDeviceTypeAddrVector(devices).c_str());
3787
Mikhail Naganov55773032020-10-01 15:08:13 -07003788 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003789 return BAD_VALUE;
3790 }
3791 status_t status = mEngine->setDevicesRoleForCapturePreset(audioSource, role, devices);
3792 ALOGW_IF(status != NO_ERROR,
3793 "Engine could not set preferred devices %s for audio source %d role %d",
3794 dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
3795
3796 return status;
3797}
3798
3799status_t AudioPolicyManager::addDevicesRoleForCapturePreset(
3800 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices) {
3801 ALOGV("%s() audioSource=%d role=%d %s", __func__, audioSource, role,
3802 dumpAudioDeviceTypeAddrVector(devices).c_str());
3803
Mikhail Naganov55773032020-10-01 15:08:13 -07003804 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003805 return BAD_VALUE;
3806 }
3807 status_t status = mEngine->addDevicesRoleForCapturePreset(audioSource, role, devices);
3808 ALOGW_IF(status != NO_ERROR,
3809 "Engine could not add preferred devices %s for audio source %d role %d",
3810 dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
3811
Eric Laurent2517af32020-11-25 15:31:27 +01003812 updateInputRouting();
Jiabin Huang3b98d322020-09-03 17:54:16 +00003813 return status;
3814}
3815
3816status_t AudioPolicyManager::removeDevicesRoleForCapturePreset(
3817 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector& devices)
3818{
3819 ALOGV("%s() audioSource=%d role=%d devices=%s", __func__, audioSource, role,
3820 dumpAudioDeviceTypeAddrVector(devices).c_str());
3821
Mikhail Naganov55773032020-10-01 15:08:13 -07003822 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003823 return BAD_VALUE;
3824 }
3825
3826 status_t status = mEngine->removeDevicesRoleForCapturePreset(
3827 audioSource, role, devices);
3828 ALOGW_IF(status != NO_ERROR,
3829 "Engine could not remove devices role (%d) for capture preset %d", role, audioSource);
3830
Eric Laurent2517af32020-11-25 15:31:27 +01003831 updateInputRouting();
Jiabin Huang3b98d322020-09-03 17:54:16 +00003832 return status;
3833}
3834
3835status_t AudioPolicyManager::clearDevicesRoleForCapturePreset(audio_source_t audioSource,
3836 device_role_t role) {
3837 ALOGV("%s() audioSource=%d role=%d", __func__, audioSource, role);
3838
3839 status_t status = mEngine->clearDevicesRoleForCapturePreset(audioSource, role);
3840 ALOGW_IF(status != NO_ERROR,
3841 "Engine could not clear devices role (%d) for capture preset %d", role, audioSource);
3842
Eric Laurent2517af32020-11-25 15:31:27 +01003843 updateInputRouting();
Jiabin Huang3b98d322020-09-03 17:54:16 +00003844 return status;
3845}
3846
3847status_t AudioPolicyManager::getDevicesForRoleAndCapturePreset(
3848 audio_source_t audioSource, device_role_t role, AudioDeviceTypeAddrVector &devices) {
3849 return mEngine->getDevicesForRoleAndCapturePreset(audioSource, role, devices);
3850}
3851
Oscar Azucena90e77632019-11-27 17:12:28 -08003852status_t AudioPolicyManager::setUserIdDeviceAffinities(int userId,
jiabin6a02d532020-08-07 11:56:38 -07003853 const AudioDeviceTypeAddrVector& devices) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01003854 ALOGV("%s() userId=%d num devices %zu", __func__, userId, devices.size());
Eric Laurentc529cf62020-04-17 18:19:10 -07003855 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
3856 return BAD_VALUE;
Oscar Azucena90e77632019-11-27 17:12:28 -08003857 }
Oscar Azucena90e77632019-11-27 17:12:28 -08003858 status_t status = mPolicyMixes.setUserIdDeviceAffinities(userId, devices);
3859 if (status != NO_ERROR) {
3860 ALOGE("%s() could not set device affinity for userId %d",
3861 __FUNCTION__, userId);
3862 return status;
3863 }
3864
3865 // reevaluate outputs for all devices
3866 checkForDeviceAndOutputChanges();
3867 updateCallAndOutputRouting();
3868
3869 return NO_ERROR;
3870}
3871
3872status_t AudioPolicyManager::removeUserIdDeviceAffinities(int userId) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01003873 ALOGV("%s() userId=%d", __FUNCTION__, userId);
Oscar Azucena90e77632019-11-27 17:12:28 -08003874 status_t status = mPolicyMixes.removeUserIdDeviceAffinities(userId);
3875 if (status != NO_ERROR) {
3876 ALOGE("%s() Could not remove all device affinities fo userId = %d",
3877 __FUNCTION__, userId);
3878 return status;
3879 }
3880
3881 // reevaluate outputs for all devices
3882 checkForDeviceAndOutputChanges();
3883 updateCallAndOutputRouting();
3884
3885 return NO_ERROR;
3886}
3887
Andy Hungc29d82b2018-10-05 12:23:17 -07003888void AudioPolicyManager::dump(String8 *dst) const
Eric Laurente552edb2014-03-10 17:42:56 -07003889{
Andy Hungc29d82b2018-10-05 12:23:17 -07003890 dst->appendFormat("\nAudioPolicyManager Dump: %p\n", this);
Mikhail Naganov0dbe87b2021-12-01 02:03:31 +00003891 dst->appendFormat(" Primary Output I/O handle: %d\n",
Eric Laurent87ffa392015-05-22 10:32:38 -07003892 hasPrimaryOutput() ? mPrimaryOutput->mIoHandle : AUDIO_IO_HANDLE_NONE);
Mikhail Naganov0d6a0332016-04-19 17:12:38 -07003893 std::string stateLiteral;
3894 AudioModeConverter::toString(mEngine->getPhoneState(), stateLiteral);
Andy Hungc29d82b2018-10-05 12:23:17 -07003895 dst->appendFormat(" Phone state: %s\n", stateLiteral.c_str());
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07003896 const char* forceUses[AUDIO_POLICY_FORCE_USE_CNT] = {
3897 "communications", "media", "record", "dock", "system",
3898 "HDMI system audio", "encoded surround output", "vibrate ringing" };
3899 for (audio_policy_force_use_t i = AUDIO_POLICY_FORCE_FOR_COMMUNICATION;
3900 i < AUDIO_POLICY_FORCE_USE_CNT; i = (audio_policy_force_use_t)((int)i + 1)) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08003901 audio_policy_forced_cfg_t forceUseValue = mEngine->getForceUse(i);
3902 dst->appendFormat(" Force use for %s: %d", forceUses[i], forceUseValue);
3903 if (i == AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND &&
3904 forceUseValue == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
3905 dst->append(" (MANUAL: ");
3906 dumpManualSurroundFormats(dst);
3907 dst->append(")");
3908 }
3909 dst->append("\n");
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07003910 }
Andy Hungc29d82b2018-10-05 12:23:17 -07003911 dst->appendFormat(" TTS output %savailable\n", mTtsOutputAvailable ? "" : "not ");
3912 dst->appendFormat(" Master mono: %s\n", mMasterMono ? "on" : "off");
Mikhail Naganovb3bcb4f2022-02-23 23:46:56 +00003913 dst->appendFormat(" Communication Strategy id: %d\n", mCommunnicationStrategy);
Mikhail Naganovb0fbc1b2023-04-28 13:06:32 -07003914 dst->appendFormat(" Config source: %s\n", mConfig->getSource().c_str());
Eric Laurent2517af32020-11-25 15:31:27 +01003915
Mikhail Naganov0f413b22021-12-02 05:29:27 +00003916 dst->append("\n");
3917 mAvailableOutputDevices.dump(dst, String8("Available output"), 1);
3918 dst->append("\n");
3919 mAvailableInputDevices.dump(dst, String8("Available input"), 1);
Mikhail Naganovb0fbc1b2023-04-28 13:06:32 -07003920 mHwModules.dump(dst);
Andy Hungc29d82b2018-10-05 12:23:17 -07003921 mOutputs.dump(dst);
3922 mInputs.dump(dst);
Mikhail Naganov0f413b22021-12-02 05:29:27 +00003923 mEffects.dump(dst, 1);
Andy Hungc29d82b2018-10-05 12:23:17 -07003924 mAudioPatches.dump(dst);
3925 mPolicyMixes.dump(dst);
3926 mAudioSources.dump(dst);
François Gaffiec005e562018-11-06 15:04:49 +01003927
Kevin Rocardb99cc752019-03-21 20:52:24 -07003928 dst->appendFormat(" AllowedCapturePolicies:\n");
3929 for (auto& policy : mAllowedCapturePolicies) {
3930 dst->appendFormat(" - uid=%d flag_mask=%#x\n", policy.first, policy.second);
3931 }
3932
François Gaffiec005e562018-11-06 15:04:49 +01003933 dst->appendFormat("\nPolicy Engine dump:\n");
3934 mEngine->dump(dst);
Andy Hungc29d82b2018-10-05 12:23:17 -07003935}
3936
3937status_t AudioPolicyManager::dump(int fd)
3938{
3939 String8 result;
3940 dump(&result);
Andy Hungbb54e202018-10-05 11:42:02 -07003941 write(fd, result.string(), result.size());
Eric Laurente552edb2014-03-10 17:42:56 -07003942 return NO_ERROR;
3943}
3944
Kevin Rocardb99cc752019-03-21 20:52:24 -07003945status_t AudioPolicyManager::setAllowedCapturePolicy(uid_t uid, audio_flags_mask_t capturePolicy)
3946{
3947 mAllowedCapturePolicies[uid] = capturePolicy;
3948 return NO_ERROR;
3949}
3950
Eric Laurente552edb2014-03-10 17:42:56 -07003951// This function checks for the parameters which can be offloaded.
3952// This can be enhanced depending on the capability of the DSP and policy
3953// of the system.
Eric Laurent90fe31c2020-11-26 20:06:35 +01003954audio_offload_mode_t AudioPolicyManager::getOffloadSupport(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07003955{
Eric Laurent90fe31c2020-11-26 20:06:35 +01003956 ALOGV("%s: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07003957 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurent90fe31c2020-11-26 20:06:35 +01003958 __func__, offloadInfo.sample_rate, offloadInfo.channel_mask,
Eric Laurente552edb2014-03-10 17:42:56 -07003959 offloadInfo.format,
3960 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
3961 offloadInfo.has_video);
3962
jiabin2b9d5a12021-12-10 01:06:29 +00003963 if (!isOffloadPossible(offloadInfo)) {
Eric Laurent90fe31c2020-11-26 20:06:35 +01003964 return AUDIO_OFFLOAD_NOT_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07003965 }
3966
3967 // See if there is a profile to support this.
3968 // AUDIO_DEVICE_NONE
François Gaffie11d30102018-11-02 16:09:09 +01003969 sp<IOProfile> profile = getProfileForOutput(DeviceVector() /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07003970 offloadInfo.sample_rate,
3971 offloadInfo.format,
3972 offloadInfo.channel_mask,
Michael Chana94fbb22018-04-24 14:31:19 +10003973 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD,
3974 true /* directOnly */);
Eric Laurent94365442021-01-08 18:36:05 +01003975 ALOGV("%s: profile %sfound%s", __func__, profile != nullptr ? "" : "NOT ",
3976 (profile != nullptr && (profile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD) != 0)
3977 ? ", supports gapless" : "");
Eric Laurent90fe31c2020-11-26 20:06:35 +01003978 if (profile == nullptr) {
3979 return AUDIO_OFFLOAD_NOT_SUPPORTED;
3980 }
3981 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD) != 0) {
3982 return AUDIO_OFFLOAD_GAPLESS_SUPPORTED;
3983 }
3984 return AUDIO_OFFLOAD_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07003985}
3986
Michael Chana94fbb22018-04-24 14:31:19 +10003987bool AudioPolicyManager::isDirectOutputSupported(const audio_config_base_t& config,
3988 const audio_attributes_t& attributes) {
3989 audio_output_flags_t output_flags = AUDIO_OUTPUT_FLAG_NONE;
François Gaffie58d4be52018-11-06 15:30:12 +01003990 audio_flags_to_audio_output_flags(attributes.flags, &output_flags);
Dorin Drimus9901eb02022-01-14 11:36:51 +00003991 DeviceVector outputDevices = mEngine->getOutputDevicesForAttributes(attributes);
3992 sp<IOProfile> profile = getProfileForOutput(outputDevices,
Michael Chana94fbb22018-04-24 14:31:19 +10003993 config.sample_rate,
3994 config.format,
3995 config.channel_mask,
3996 output_flags,
3997 true /* directOnly */);
3998 ALOGV("%s() profile %sfound with name: %s, "
3999 "sample rate: %u, format: 0x%x, channel_mask: 0x%x, output flags: 0x%x",
4000 __FUNCTION__, profile != 0 ? "" : "NOT ",
jiabin5740f082019-08-19 15:08:30 -07004001 (profile != 0 ? profile->getTagName().c_str() : "null"),
Michael Chana94fbb22018-04-24 14:31:19 +10004002 config.sample_rate, config.format, config.channel_mask, output_flags);
Dorin Drimusecc9f422022-03-09 17:57:40 +01004003
4004 // also try the MSD module if compatible profile not found
4005 if (profile == nullptr) {
4006 profile = getMsdProfileForOutput(outputDevices,
4007 config.sample_rate,
4008 config.format,
4009 config.channel_mask,
4010 output_flags,
4011 true /* directOnly */);
4012 ALOGV("%s() MSD profile %sfound with name: %s, "
4013 "sample rate: %u, format: 0x%x, channel_mask: 0x%x, output flags: 0x%x",
4014 __FUNCTION__, profile != 0 ? "" : "NOT ",
4015 (profile != 0 ? profile->getTagName().c_str() : "null"),
4016 config.sample_rate, config.format, config.channel_mask, output_flags);
4017 }
4018 return (profile != nullptr);
Michael Chana94fbb22018-04-24 14:31:19 +10004019}
4020
jiabin2b9d5a12021-12-10 01:06:29 +00004021bool AudioPolicyManager::isOffloadPossible(const audio_offload_info_t &offloadInfo,
4022 bool durationIgnored) {
4023 if (mMasterMono) {
4024 return false; // no offloading if mono is set.
4025 }
4026
4027 // Check if offload has been disabled
4028 if (property_get_bool("audio.offload.disable", false /* default_value */)) {
4029 ALOGV("%s: offload disabled by audio.offload.disable", __func__);
4030 return false;
4031 }
4032
4033 // Check if stream type is music, then only allow offload as of now.
4034 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
4035 {
4036 ALOGV("%s: stream_type != MUSIC, returning false", __func__);
4037 return false;
4038 }
4039
4040 //TODO: enable audio offloading with video when ready
4041 const bool allowOffloadWithVideo =
4042 property_get_bool("audio.offload.video", false /* default_value */);
4043 if (offloadInfo.has_video && !allowOffloadWithVideo) {
4044 ALOGV("%s: has_video == true, returning false", __func__);
4045 return false;
4046 }
4047
4048 //If duration is less than minimum value defined in property, return false
4049 const int min_duration_secs = property_get_int32(
4050 "audio.offload.min.duration.secs", -1 /* default_value */);
4051 if (!durationIgnored) {
4052 if (min_duration_secs >= 0) {
4053 if (offloadInfo.duration_us < min_duration_secs * 1000000LL) {
4054 ALOGV("%s: Offload denied by duration < audio.offload.min.duration.secs(=%d)",
4055 __func__, min_duration_secs);
4056 return false;
4057 }
4058 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
4059 ALOGV("%s: Offload denied by duration < default min(=%u)",
4060 __func__, OFFLOAD_DEFAULT_MIN_DURATION_SECS);
4061 return false;
4062 }
4063 }
4064
4065 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
4066 // creating an offloaded track and tearing it down immediately after start when audioflinger
4067 // detects there is an active non offloadable effect.
4068 // FIXME: We should check the audio session here but we do not have it in this context.
4069 // This may prevent offloading in rare situations where effects are left active by apps
4070 // in the background.
4071 if (mEffects.isNonOffloadableEffectEnabled()) {
4072 return false;
4073 }
4074
4075 return true;
4076}
4077
4078audio_direct_mode_t AudioPolicyManager::getDirectPlaybackSupport(const audio_attributes_t *attr,
4079 const audio_config_t *config) {
4080 audio_offload_info_t offloadInfo = AUDIO_INFO_INITIALIZER;
4081 offloadInfo.format = config->format;
4082 offloadInfo.sample_rate = config->sample_rate;
4083 offloadInfo.channel_mask = config->channel_mask;
4084 offloadInfo.stream_type = mEngine->getStreamTypeForAttributes(*attr);
4085 offloadInfo.has_video = false;
4086 offloadInfo.is_streaming = false;
4087 const bool offloadPossible = isOffloadPossible(offloadInfo, true /*durationIgnored*/);
4088
4089 audio_direct_mode_t directMode = AUDIO_DIRECT_NOT_SUPPORTED;
4090 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
4091 audio_flags_to_audio_output_flags(attr->flags, &flags);
4092 // only retain flags that will drive compressed offload or passthrough
4093 uint32_t relevantFlags = AUDIO_OUTPUT_FLAG_HW_AV_SYNC;
4094 if (offloadPossible) {
4095 relevantFlags |= AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD;
4096 }
4097 flags = (audio_output_flags_t)((flags & relevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
4098
Dorin Drimusfae3c642022-03-17 18:36:30 +01004099 DeviceVector engineOutputDevices = mEngine->getOutputDevicesForAttributes(*attr);
jiabin2b9d5a12021-12-10 01:06:29 +00004100 for (const auto& hwModule : mHwModules) {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004101 DeviceVector outputDevices = engineOutputDevices;
4102 // the MSD module checks for different conditions and output devices
4103 if (strcmp(hwModule->getName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0) {
4104 if (!msdHasPatchesToAllDevices(engineOutputDevices.toTypeAddrVector())) {
4105 continue;
4106 }
4107 outputDevices = getMsdAudioOutDevices();
4108 }
jiabin2b9d5a12021-12-10 01:06:29 +00004109 for (const auto& curProfile : hwModule->getOutputProfiles()) {
jiabinc8f7dfc2022-01-06 18:42:08 +00004110 if (!curProfile->isCompatibleProfile(outputDevices,
jiabin2b9d5a12021-12-10 01:06:29 +00004111 config->sample_rate, nullptr /*updatedSamplingRate*/,
4112 config->format, nullptr /*updatedFormat*/,
4113 config->channel_mask, nullptr /*updatedChannelMask*/,
4114 flags)) {
4115 continue;
4116 }
4117 // reject profiles not corresponding to a device currently available
4118 if (!mAvailableOutputDevices.containsAtLeastOne(curProfile->getSupportedDevices())) {
4119 continue;
4120 }
4121 if ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)
4122 != AUDIO_OUTPUT_FLAG_NONE) {
jiabinc6132d62022-01-01 07:36:31 +00004123 if ((directMode & AUDIO_DIRECT_OFFLOAD_GAPLESS_SUPPORTED)
jiabin2b9d5a12021-12-10 01:06:29 +00004124 != AUDIO_DIRECT_NOT_SUPPORTED) {
4125 // Already reports offload gapless supported. No need to report offload support.
4126 continue;
4127 }
4128 if ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD)
4129 != AUDIO_OUTPUT_FLAG_NONE) {
4130 // If offload gapless is reported, no need to report offload support.
4131 directMode = (audio_direct_mode_t) ((directMode &
4132 ~AUDIO_DIRECT_OFFLOAD_SUPPORTED) |
4133 AUDIO_DIRECT_OFFLOAD_GAPLESS_SUPPORTED);
4134 } else {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004135 directMode = (audio_direct_mode_t)(directMode | AUDIO_DIRECT_OFFLOAD_SUPPORTED);
jiabin2b9d5a12021-12-10 01:06:29 +00004136 }
4137 } else {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004138 directMode = (audio_direct_mode_t) (directMode | AUDIO_DIRECT_BITSTREAM_SUPPORTED);
jiabin2b9d5a12021-12-10 01:06:29 +00004139 }
4140 }
4141 }
4142 return directMode;
4143}
4144
Dorin Drimusf2196d82022-01-03 12:11:18 +01004145status_t AudioPolicyManager::getDirectProfilesForAttributes(const audio_attributes_t* attr,
4146 AudioProfileVector& audioProfilesVector) {
Dorin Drimus76e69572022-09-23 15:28:51 +00004147 if (mEffects.isNonOffloadableEffectEnabled()) {
4148 return OK;
4149 }
Dorin Drimusf2196d82022-01-03 12:11:18 +01004150 AudioDeviceTypeAddrVector devices;
Andy Hung6d23c0f2022-02-16 09:37:15 -08004151 status_t status = getDevicesForAttributes(*attr, &devices, false /* forVolume */);
Dorin Drimusf2196d82022-01-03 12:11:18 +01004152 if (status != OK) {
4153 return status;
4154 }
4155 ALOGV("%s: found %zu output devices for attributes.", __func__, devices.size());
4156 if (devices.empty()) {
4157 return OK; // no output devices for the attributes
4158 }
4159
4160 for (const auto& hwModule : mHwModules) {
Dorin Drimus94d94412022-02-02 09:05:02 +01004161 // the MSD module checks for different conditions
4162 if (strcmp(hwModule->getName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0) {
4163 continue;
4164 }
4165 for (const auto& outputProfile : hwModule->getOutputProfiles()) {
4166 if (!outputProfile->asAudioPort()->isDirectOutput()) {
Dorin Drimusf2196d82022-01-03 12:11:18 +01004167 continue;
4168 }
Dorin Drimus94d94412022-02-02 09:05:02 +01004169 // allow only profiles that support all the available and routed devices
4170 if (outputProfile->getSupportedDevices().getDevicesFromDeviceTypeAddrVec(devices).size()
Dorin Drimusf2196d82022-01-03 12:11:18 +01004171 != devices.size()) {
4172 continue;
4173 }
Dorin Drimus94d94412022-02-02 09:05:02 +01004174 audioProfilesVector.addAllValidProfiles(
4175 outputProfile->asAudioPort()->getAudioProfiles());
Dorin Drimusf2196d82022-01-03 12:11:18 +01004176 }
4177 }
Dorin Drimus94d94412022-02-02 09:05:02 +01004178
4179 // add the direct profiles from MSD if present and has audio patches to all the output(s)
4180 const auto& msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
4181 if (msdModule != nullptr) {
4182 if (msdHasPatchesToAllDevices(devices)) {
4183 ALOGV("%s: MSD audio patches set to all output devices.", __func__);
4184 for (const auto& outputProfile : msdModule->getOutputProfiles()) {
4185 if (!outputProfile->asAudioPort()->isDirectOutput()) {
4186 continue;
4187 }
4188 audioProfilesVector.addAllValidProfiles(
4189 outputProfile->asAudioPort()->getAudioProfiles());
4190 }
4191 } else {
4192 ALOGV("%s: MSD audio patches NOT set to all output devices.", __func__);
4193 }
4194 }
4195
Dorin Drimusf2196d82022-01-03 12:11:18 +01004196 return NO_ERROR;
4197}
4198
Eric Laurent6a94d692014-05-20 11:18:06 -07004199status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
4200 audio_port_type_t type,
4201 unsigned int *num_ports,
jiabin19cdba52020-11-24 11:28:58 -08004202 struct audio_port_v7 *ports,
Eric Laurent6a94d692014-05-20 11:18:06 -07004203 unsigned int *generation)
4204{
jiabin19cdba52020-11-24 11:28:58 -08004205 if (num_ports == nullptr || (*num_ports != 0 && ports == nullptr) ||
4206 generation == nullptr) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004207 return BAD_VALUE;
4208 }
4209 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
jiabin19cdba52020-11-24 11:28:58 -08004210 if (ports == nullptr) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004211 *num_ports = 0;
4212 }
4213
4214 size_t portsWritten = 0;
4215 size_t portsMax = *num_ports;
4216 *num_ports = 0;
4217 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07004218 // do not report devices with type AUDIO_DEVICE_IN_STUB or AUDIO_DEVICE_OUT_STUB
4219 // as they are used by stub HALs by convention
Eric Laurent6a94d692014-05-20 11:18:06 -07004220 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004221 for (const auto& dev : mAvailableOutputDevices) {
4222 if (dev->type() == AUDIO_DEVICE_OUT_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07004223 continue;
4224 }
4225 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004226 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07004227 }
4228 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07004229 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004230 }
4231 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004232 for (const auto& dev : mAvailableInputDevices) {
4233 if (dev->type() == AUDIO_DEVICE_IN_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07004234 continue;
4235 }
4236 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004237 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07004238 }
4239 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07004240 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004241 }
4242 }
4243 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
4244 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
4245 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
4246 mInputs[i]->toAudioPort(&ports[portsWritten++]);
4247 }
4248 *num_ports += mInputs.size();
4249 }
4250 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent84c70242014-06-23 08:46:27 -07004251 size_t numOutputs = 0;
4252 for (size_t i = 0; i < mOutputs.size(); i++) {
4253 if (!mOutputs[i]->isDuplicated()) {
4254 numOutputs++;
4255 if (portsWritten < portsMax) {
4256 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
4257 }
4258 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004259 }
Eric Laurent84c70242014-06-23 08:46:27 -07004260 *num_ports += numOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07004261 }
4262 }
4263 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07004264 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
Eric Laurent6a94d692014-05-20 11:18:06 -07004265 return NO_ERROR;
4266}
4267
Mikhail Naganov15f46712023-03-23 14:52:15 -07004268status_t AudioPolicyManager::listDeclaredDevicePorts(media::AudioPortRole role,
4269 std::vector<media::AudioPortFw>* _aidl_return) {
4270 auto pushPort = [&](const sp<DeviceDescriptor>& dev) -> status_t {
4271 audio_port_v7 port;
4272 dev->toAudioPort(&port);
4273 auto aidlPort = VALUE_OR_RETURN_STATUS(legacy2aidl_audio_port_v7_AudioPortFw(port));
4274 _aidl_return->push_back(std::move(aidlPort));
4275 return OK;
4276 };
4277
Mikhail Naganovb0fbc1b2023-04-28 13:06:32 -07004278 for (const auto& module : mHwModules) {
Mikhail Naganov15f46712023-03-23 14:52:15 -07004279 for (const auto& dev : module->getDeclaredDevices()) {
4280 if (role == media::AudioPortRole::NONE ||
4281 ((role == media::AudioPortRole::SOURCE)
4282 == audio_is_input_device(dev->type()))) {
4283 RETURN_STATUS_IF_ERROR(pushPort(dev));
4284 }
4285 }
4286 }
4287 return OK;
4288}
4289
jiabin19cdba52020-11-24 11:28:58 -08004290status_t AudioPolicyManager::getAudioPort(struct audio_port_v7 *port)
Eric Laurent6a94d692014-05-20 11:18:06 -07004291{
Eric Laurent99fcae42018-05-17 16:59:18 -07004292 if (port == nullptr || port->id == AUDIO_PORT_HANDLE_NONE) {
4293 return BAD_VALUE;
4294 }
4295 sp<DeviceDescriptor> dev = mAvailableOutputDevices.getDeviceFromId(port->id);
4296 if (dev != 0) {
4297 dev->toAudioPort(port);
4298 return NO_ERROR;
4299 }
4300 dev = mAvailableInputDevices.getDeviceFromId(port->id);
4301 if (dev != 0) {
4302 dev->toAudioPort(port);
4303 return NO_ERROR;
4304 }
4305 sp<SwAudioOutputDescriptor> out = mOutputs.getOutputFromId(port->id);
4306 if (out != 0) {
4307 out->toAudioPort(port);
4308 return NO_ERROR;
4309 }
4310 sp<AudioInputDescriptor> in = mInputs.getInputFromId(port->id);
4311 if (in != 0) {
4312 in->toAudioPort(port);
4313 return NO_ERROR;
4314 }
4315 return BAD_VALUE;
Eric Laurent6a94d692014-05-20 11:18:06 -07004316}
4317
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004318status_t AudioPolicyManager::createAudioPatch(const struct audio_patch *patch,
4319 audio_patch_handle_t *handle,
4320 uid_t uid)
Eric Laurent6a94d692014-05-20 11:18:06 -07004321{
François Gaffieafd4cea2019-11-18 15:50:22 +01004322 ALOGV("%s", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004323 if (handle == NULL || patch == NULL) {
4324 return BAD_VALUE;
4325 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004326 ALOGV("%s num sources %d num sinks %d", __func__, patch->num_sources, patch->num_sinks);
Mikhail Naganovac9858b2018-06-15 13:12:37 -07004327 if (!audio_patch_is_valid(patch)) {
Eric Laurent874c42872014-08-08 15:13:39 -07004328 return BAD_VALUE;
4329 }
4330 // only one source per audio patch supported for now
4331 if (patch->num_sources > 1) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004332 return INVALID_OPERATION;
4333 }
Eric Laurent874c42872014-08-08 15:13:39 -07004334 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004335 return INVALID_OPERATION;
4336 }
Eric Laurent874c42872014-08-08 15:13:39 -07004337 for (size_t i = 0; i < patch->num_sinks; i++) {
4338 if (patch->sinks[i].role != AUDIO_PORT_ROLE_SINK) {
4339 return INVALID_OPERATION;
4340 }
4341 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004342
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004343 sp<DeviceDescriptor> srcDevice = mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
4344 sp<DeviceDescriptor> sinkDevice = mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id);
4345 if (srcDevice == nullptr || sinkDevice == nullptr) {
4346 ALOGW("%s could not create patch, invalid sink and/or source device(s)", __func__);
4347 return BAD_VALUE;
4348 }
4349 ALOGV("%s between source %s and sink %s", __func__,
4350 srcDevice->toString().c_str(), sinkDevice->toString().c_str());
4351 audio_port_handle_t portId = PolicyAudioPort::getNextUniqueId();
4352 // Default attributes, default volume priority, not to infer with non raw audio patches.
4353 audio_attributes_t attributes = attributes_initializer(AUDIO_USAGE_MEDIA);
4354 const struct audio_port_config *source = &patch->sources[0];
4355 sp<SourceClientDescriptor> sourceDesc =
4356 new InternalSourceClientDescriptor(
4357 portId, uid, attributes, *source, srcDevice, sinkDevice,
4358 mEngine->getProductStrategyForAttributes(attributes), toVolumeSource(attributes));
4359
4360 status_t status =
4361 connectAudioSourceToSink(sourceDesc, sinkDevice, patch, *handle, uid, 0 /* delayMs */);
4362
4363 if (status != NO_ERROR) {
4364 return INVALID_OPERATION;
4365 }
4366 mAudioSources.add(portId, sourceDesc);
4367 return NO_ERROR;
4368}
4369
4370status_t AudioPolicyManager::connectAudioSourceToSink(
4371 const sp<SourceClientDescriptor>& sourceDesc, const sp<DeviceDescriptor> &sinkDevice,
4372 const struct audio_patch *patch,
4373 audio_patch_handle_t &handle,
4374 uid_t uid, uint32_t delayMs)
4375{
4376 status_t status = createAudioPatchInternal(patch, &handle, uid, delayMs, sourceDesc);
4377 if (status != NO_ERROR || mAudioPatches.indexOfKey(handle) < 0) {
4378 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
4379 return INVALID_OPERATION;
4380 }
4381 sourceDesc->connect(handle, sinkDevice);
4382 if (isMsdPatch(handle)) {
4383 return NO_ERROR;
4384 }
4385 // SW Bridge? (@todo: HW bridge, keep track of HwOutput for device selection "reconsideration")
4386 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
4387 ALOG_ASSERT(swOutput != nullptr, "%s: a swOutput shall always be associated", __func__);
4388 if (swOutput->getClient(sourceDesc->portId()) != nullptr) {
4389 ALOGW("%s source portId has already been attached to outputDesc", __func__);
4390 goto FailurePatchAdded;
4391 }
4392 status = swOutput->start();
4393 if (status != NO_ERROR) {
4394 goto FailureSourceAdded;
4395 }
4396 swOutput->addClient(sourceDesc);
4397 status = startSource(swOutput, sourceDesc, &delayMs);
4398 if (status != NO_ERROR) {
4399 ALOGW("%s failed to start source, error %d", __FUNCTION__, status);
4400 goto FailureSourceActive;
4401 }
4402 if (delayMs != 0) {
4403 usleep(delayMs * 1000);
4404 }
4405 return NO_ERROR;
4406
4407FailureSourceActive:
4408 swOutput->stop();
4409 releaseOutput(sourceDesc->portId());
4410FailureSourceAdded:
4411 sourceDesc->setSwOutput(nullptr);
4412FailurePatchAdded:
4413 releaseAudioPatchInternal(handle);
4414 return INVALID_OPERATION;
4415}
4416
4417status_t AudioPolicyManager::createAudioPatchInternal(const struct audio_patch *patch,
4418 audio_patch_handle_t *handle,
4419 uid_t uid, uint32_t delayMs,
4420 const sp<SourceClientDescriptor>& sourceDesc)
4421{
4422 ALOGV("%s num sources %d num sinks %d", __func__, patch->num_sources, patch->num_sinks);
Eric Laurent6a94d692014-05-20 11:18:06 -07004423 sp<AudioPatch> patchDesc;
4424 ssize_t index = mAudioPatches.indexOfKey(*handle);
4425
François Gaffieafd4cea2019-11-18 15:50:22 +01004426 ALOGV("%s source id %d role %d type %d", __func__, patch->sources[0].id,
4427 patch->sources[0].role,
4428 patch->sources[0].type);
Eric Laurent874c42872014-08-08 15:13:39 -07004429#if LOG_NDEBUG == 0
4430 for (size_t i = 0; i < patch->num_sinks; i++) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004431 ALOGV("%s sink %zu: id %d role %d type %d", __func__ ,i, patch->sinks[i].id,
4432 patch->sinks[i].role,
4433 patch->sinks[i].type);
Eric Laurent874c42872014-08-08 15:13:39 -07004434 }
4435#endif
Eric Laurent6a94d692014-05-20 11:18:06 -07004436
4437 if (index >= 0) {
4438 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01004439 ALOGV("%s mUidCached %d patchDesc->mUid %d uid %d",
4440 __func__, mUidCached, patchDesc->getUid(), uid);
4441 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004442 return INVALID_OPERATION;
4443 }
4444 } else {
Glenn Kastena13cde92016-03-28 15:26:02 -07004445 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07004446 }
4447
4448 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004449 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004450 if (outputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004451 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004452 return BAD_VALUE;
4453 }
Eric Laurent84c70242014-06-23 08:46:27 -07004454 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
4455 outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004456 if (patchDesc != 0) {
4457 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004458 ALOGV("%s source id differs for patch current id %d new id %d",
4459 __func__, patchDesc->mPatch.sources[0].id, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004460 return BAD_VALUE;
4461 }
4462 }
Eric Laurent874c42872014-08-08 15:13:39 -07004463 DeviceVector devices;
4464 for (size_t i = 0; i < patch->num_sinks; i++) {
4465 // Only support mix to devices connection
4466 // TODO add support for mix to mix connection
4467 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004468 ALOGV("%s source mix but sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07004469 return INVALID_OPERATION;
4470 }
4471 sp<DeviceDescriptor> devDesc =
4472 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
4473 if (devDesc == 0) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004474 ALOGV("%s out device not found for id %d", __func__, patch->sinks[i].id);
Eric Laurent874c42872014-08-08 15:13:39 -07004475 return BAD_VALUE;
4476 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004477
François Gaffie11d30102018-11-02 16:09:09 +01004478 if (!outputDesc->mProfile->isCompatibleProfile(DeviceVector(devDesc),
Eric Laurent874c42872014-08-08 15:13:39 -07004479 patch->sources[0].sample_rate,
François Gaffie53615e22015-03-19 09:24:12 +01004480 NULL, // updatedSamplingRate
4481 patch->sources[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07004482 NULL, // updatedFormat
François Gaffie53615e22015-03-19 09:24:12 +01004483 patch->sources[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07004484 NULL, // updatedChannelMask
François Gaffie53615e22015-03-19 09:24:12 +01004485 AUDIO_OUTPUT_FLAG_NONE /*FIXME*/)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004486 ALOGV("%s profile not supported for device %08x", __func__, devDesc->type());
Eric Laurent874c42872014-08-08 15:13:39 -07004487 return INVALID_OPERATION;
4488 }
4489 devices.add(devDesc);
4490 }
4491 if (devices.size() == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004492 return INVALID_OPERATION;
4493 }
Eric Laurent874c42872014-08-08 15:13:39 -07004494
Eric Laurent6a94d692014-05-20 11:18:06 -07004495 // TODO: reconfigure output format and channels here
François Gaffieafd4cea2019-11-18 15:50:22 +01004496 ALOGV("%s setting device %s on output %d",
4497 __func__, dumpDeviceTypes(devices.types()).c_str(), outputDesc->mIoHandle);
François Gaffie11d30102018-11-02 16:09:09 +01004498 setOutputDevices(outputDesc, devices, true, 0, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004499 index = mAudioPatches.indexOfKey(*handle);
4500 if (index >= 0) {
4501 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004502 ALOGW("%s setOutputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004503 }
4504 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01004505 patchDesc->setUid(uid);
4506 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004507 } else {
François Gaffieafd4cea2019-11-18 15:50:22 +01004508 ALOGW("%s setOutputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004509 return INVALID_OPERATION;
4510 }
4511 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
4512 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
4513 // input device to input mix connection
Eric Laurent874c42872014-08-08 15:13:39 -07004514 // only one sink supported when connecting an input device to a mix
4515 if (patch->num_sinks > 1) {
4516 return INVALID_OPERATION;
4517 }
François Gaffie53615e22015-03-19 09:24:12 +01004518 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004519 if (inputDesc == NULL) {
4520 return BAD_VALUE;
4521 }
4522 if (patchDesc != 0) {
4523 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
4524 return BAD_VALUE;
4525 }
4526 }
François Gaffie11d30102018-11-02 16:09:09 +01004527 sp<DeviceDescriptor> device =
Eric Laurent6a94d692014-05-20 11:18:06 -07004528 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01004529 if (device == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004530 return BAD_VALUE;
4531 }
4532
François Gaffie11d30102018-11-02 16:09:09 +01004533 if (!inputDesc->mProfile->isCompatibleProfile(DeviceVector(device),
Eric Laurent275e8e92014-11-30 15:14:47 -08004534 patch->sinks[0].sample_rate,
4535 NULL, /*updatedSampleRate*/
4536 patch->sinks[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07004537 NULL, /*updatedFormat*/
Eric Laurent275e8e92014-11-30 15:14:47 -08004538 patch->sinks[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07004539 NULL, /*updatedChannelMask*/
Eric Laurent275e8e92014-11-30 15:14:47 -08004540 // FIXME for the parameter type,
4541 // and the NONE
4542 (audio_output_flags_t)
Glenn Kasten6a8ab052014-07-24 14:08:35 -07004543 AUDIO_INPUT_FLAG_NONE)) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004544 return INVALID_OPERATION;
4545 }
4546 // TODO: reconfigure output format and channels here
François Gaffieafd4cea2019-11-18 15:50:22 +01004547 ALOGV("%s setting device %s on output %d", __func__,
François Gaffie11d30102018-11-02 16:09:09 +01004548 device->toString().c_str(), inputDesc->mIoHandle);
4549 setInputDevice(inputDesc->mIoHandle, device, true, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004550 index = mAudioPatches.indexOfKey(*handle);
4551 if (index >= 0) {
4552 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004553 ALOGW("%s setInputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004554 }
4555 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01004556 patchDesc->setUid(uid);
4557 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004558 } else {
François Gaffieafd4cea2019-11-18 15:50:22 +01004559 ALOGW("%s setInputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004560 return INVALID_OPERATION;
4561 }
4562 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
4563 // device to device connection
4564 if (patchDesc != 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07004565 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004566 return BAD_VALUE;
4567 }
4568 }
François Gaffie11d30102018-11-02 16:09:09 +01004569 sp<DeviceDescriptor> srcDevice =
Eric Laurent6a94d692014-05-20 11:18:06 -07004570 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01004571 if (srcDevice == 0) {
Eric Laurent58f8eb72014-09-12 16:19:41 -07004572 return BAD_VALUE;
4573 }
Eric Laurent874c42872014-08-08 15:13:39 -07004574
Eric Laurent6a94d692014-05-20 11:18:06 -07004575 //update source and sink with our own data as the data passed in the patch may
4576 // be incomplete.
François Gaffieafd4cea2019-11-18 15:50:22 +01004577 PatchBuilder patchBuilder;
4578 audio_port_config sourcePortConfig = {};
Dean Wheatley8bee85a2021-02-10 16:02:23 +11004579
4580 // if first sink is to MSD, establish single MSD patch
4581 if (getMsdAudioOutDevices().contains(
4582 mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id))) {
4583 ALOGV("%s patching to MSD", __FUNCTION__);
4584 patchBuilder = buildMsdPatch(false /*msdIsSource*/, srcDevice);
4585 goto installPatch;
4586 }
4587
François Gaffieafd4cea2019-11-18 15:50:22 +01004588 srcDevice->toAudioPortConfig(&sourcePortConfig, &patch->sources[0]);
4589 patchBuilder.addSource(sourcePortConfig);
Eric Laurent6a94d692014-05-20 11:18:06 -07004590
Eric Laurent874c42872014-08-08 15:13:39 -07004591 for (size_t i = 0; i < patch->num_sinks; i++) {
4592 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004593 ALOGV("%s source device but one sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07004594 return INVALID_OPERATION;
4595 }
François Gaffie11d30102018-11-02 16:09:09 +01004596 sp<DeviceDescriptor> sinkDevice =
Eric Laurent874c42872014-08-08 15:13:39 -07004597 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
François Gaffie11d30102018-11-02 16:09:09 +01004598 if (sinkDevice == 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07004599 return BAD_VALUE;
4600 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004601 audio_port_config sinkPortConfig = {};
4602 sinkDevice->toAudioPortConfig(&sinkPortConfig, &patch->sinks[i]);
4603 patchBuilder.addSink(sinkPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07004604
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004605 // Whatever Sw or Hw bridge, we do attach an SwOutput to an Audio Source for
4606 // volume management purpose (tracking activity)
4607 // In case of Hw bridge, it is a Work Around. The mixPort used is the one declared
4608 // in config XML to reach the sink so that is can be declared as available.
4609 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurent78b07302022-10-07 16:20:34 +02004610 sp<SwAudioOutputDescriptor> outputDesc;
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004611 if (!sourceDesc->isInternal()) {
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004612 // take care of dynamic routing for SwOutput selection,
4613 audio_attributes_t attributes = sourceDesc->attributes();
4614 audio_stream_type_t stream = sourceDesc->stream();
4615 audio_attributes_t resultAttr;
4616 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
4617 config.sample_rate = sourceDesc->config().sample_rate;
4618 config.channel_mask = sourceDesc->config().channel_mask;
4619 config.format = sourceDesc->config().format;
4620 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
4621 audio_port_handle_t selectedDeviceId = AUDIO_PORT_HANDLE_NONE;
4622 bool isRequestedDeviceForExclusiveUse = false;
4623 output_type_t outputType;
Eric Laurentb0a7bc92022-04-05 15:06:08 +02004624 bool isSpatialized;
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004625 getOutputForAttrInt(&resultAttr, &output, AUDIO_SESSION_NONE, &attributes,
4626 &stream, sourceDesc->uid(), &config, &flags,
4627 &selectedDeviceId, &isRequestedDeviceForExclusiveUse,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02004628 nullptr, &outputType, &isSpatialized);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004629 if (output == AUDIO_IO_HANDLE_NONE) {
4630 ALOGV("%s no output for device %s",
4631 __FUNCTION__, sinkDevice->toString().c_str());
4632 return INVALID_OPERATION;
4633 }
4634 outputDesc = mOutputs.valueFor(output);
4635 if (outputDesc->isDuplicated()) {
4636 ALOGE("%s output is duplicated", __func__);
4637 return INVALID_OPERATION;
4638 }
François Gaffie1765c5b2022-04-26 12:48:49 +02004639 bool closeOutput = outputDesc->mDirectOpenCount != 0;
4640 sourceDesc->setSwOutput(outputDesc, closeOutput);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004641 } else {
4642 // Same for "raw patches" aka created from createAudioPatch API
4643 SortedVector<audio_io_handle_t> outputs =
4644 getOutputsForDevices(DeviceVector(sinkDevice), mOutputs);
4645 // if the sink device is reachable via an opened output stream, request to
4646 // go via this output stream by adding a second source to the patch
4647 // description
4648 output = selectOutput(outputs);
4649 if (output == AUDIO_IO_HANDLE_NONE) {
4650 ALOGE("%s no output available for internal patch sink", __func__);
4651 return INVALID_OPERATION;
4652 }
4653 outputDesc = mOutputs.valueFor(output);
4654 if (outputDesc->isDuplicated()) {
4655 ALOGV("%s output for device %s is duplicated",
4656 __func__, sinkDevice->toString().c_str());
4657 return INVALID_OPERATION;
4658 }
François Gaffie1765c5b2022-04-26 12:48:49 +02004659 sourceDesc->setSwOutput(outputDesc, /* closeOutput= */ false);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004660 }
Eric Laurent3bcf8592015-04-03 12:13:24 -07004661 // create a software bridge in PatchPanel if:
Scott Randolphf3172402018-01-23 17:06:53 -08004662 // - source and sink devices are on different HW modules OR
Eric Laurent3bcf8592015-04-03 12:13:24 -07004663 // - audio HAL version is < 3.0
Francois Gaffie99896da2018-04-09 11:05:33 +02004664 // - audio HAL version is >= 3.0 but no route has been declared between devices
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004665 // - called from startAudioSource (aka sourceDesc is not internal) and source device
4666 // does not have a gain controller
François Gaffie11d30102018-11-02 16:09:09 +01004667 if (!srcDevice->hasSameHwModuleAs(sinkDevice) ||
4668 (srcDevice->getModuleVersionMajor() < 3) ||
François Gaffieafd4cea2019-11-18 15:50:22 +01004669 !srcDevice->getModule()->supportsPatch(srcDevice, sinkDevice) ||
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004670 (!sourceDesc->isInternal() &&
François Gaffieafd4cea2019-11-18 15:50:22 +01004671 srcDevice->getAudioPort()->getGains().size() == 0)) {
Eric Laurent3bcf8592015-04-03 12:13:24 -07004672 // support only one sink device for now to simplify output selection logic
Eric Laurent874c42872014-08-08 15:13:39 -07004673 if (patch->num_sinks > 1) {
Eric Laurent83b88082014-06-20 18:31:16 -07004674 return INVALID_OPERATION;
4675 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004676 sourceDesc->setUseSwBridge();
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004677 if (outputDesc != nullptr) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004678 audio_port_config srcMixPortConfig = {};
Ytai Ben-Tsvic9d2a912021-11-22 16:43:09 -08004679 outputDesc->toAudioPortConfig(&srcMixPortConfig, nullptr);
François Gaffieafd4cea2019-11-18 15:50:22 +01004680 // for volume control, we may need a valid stream
Eric Laurent78b07302022-10-07 16:20:34 +02004681 srcMixPortConfig.ext.mix.usecase.stream =
4682 (!sourceDesc->isInternal() || isCallTxAudioSource(sourceDesc)) ?
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004683 mEngine->getStreamTypeForAttributes(sourceDesc->attributes()) :
4684 AUDIO_STREAM_PATCH;
François Gaffieafd4cea2019-11-18 15:50:22 +01004685 patchBuilder.addSource(srcMixPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07004686 }
Eric Laurent83b88082014-06-20 18:31:16 -07004687 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004688 }
4689 // TODO: check from routing capabilities in config file and other conflicting patches
4690
Dean Wheatley8bee85a2021-02-10 16:02:23 +11004691installPatch:
François Gaffieafd4cea2019-11-18 15:50:22 +01004692 status_t status = installPatch(
4693 __func__, index, handle, patchBuilder.patch(), delayMs, uid, &patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07004694 if (status != NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004695 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
Eric Laurent6a94d692014-05-20 11:18:06 -07004696 return INVALID_OPERATION;
4697 }
4698 } else {
4699 return BAD_VALUE;
4700 }
4701 } else {
4702 return BAD_VALUE;
4703 }
4704 return NO_ERROR;
4705}
4706
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004707status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle, uid_t uid)
Eric Laurent6a94d692014-05-20 11:18:06 -07004708{
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004709 ALOGV("%s patch %d", __func__, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004710 ssize_t index = mAudioPatches.indexOfKey(handle);
4711
4712 if (index < 0) {
4713 return BAD_VALUE;
4714 }
4715 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01004716 ALOGV("%s() mUidCached %d patchDesc->mUid %d uid %d",
4717 __func__, mUidCached, patchDesc->getUid(), uid);
4718 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004719 return INVALID_OPERATION;
4720 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004721 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
4722 for (size_t i = 0; i < mAudioSources.size(); i++) {
4723 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
4724 if (sourceDesc != nullptr && sourceDesc->getPatchHandle() == handle) {
4725 portId = sourceDesc->portId();
4726 break;
4727 }
4728 }
4729 return portId != AUDIO_PORT_HANDLE_NONE ?
4730 stopAudioSource(portId) : releaseAudioPatchInternal(handle);
François Gaffieafd4cea2019-11-18 15:50:22 +01004731}
Eric Laurent6a94d692014-05-20 11:18:06 -07004732
François Gaffieafd4cea2019-11-18 15:50:22 +01004733status_t AudioPolicyManager::releaseAudioPatchInternal(audio_patch_handle_t handle,
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004734 uint32_t delayMs,
4735 const sp<SourceClientDescriptor>& sourceDesc)
François Gaffieafd4cea2019-11-18 15:50:22 +01004736{
4737 ALOGV("%s patch %d", __func__, handle);
4738 if (mAudioPatches.indexOfKey(handle) < 0) {
4739 ALOGE("%s: no patch found with handle=%d", __func__, handle);
4740 return BAD_VALUE;
4741 }
4742 sp<AudioPatch> patchDesc = mAudioPatches.valueFor(handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004743 struct audio_patch *patch = &patchDesc->mPatch;
François Gaffieafd4cea2019-11-18 15:50:22 +01004744 patchDesc->setUid(mUidCached);
Eric Laurent6a94d692014-05-20 11:18:06 -07004745 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004746 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004747 if (outputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004748 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004749 return BAD_VALUE;
4750 }
4751
François Gaffie11d30102018-11-02 16:09:09 +01004752 setOutputDevices(outputDesc,
4753 getNewOutputDevices(outputDesc, true /*fromCache*/),
4754 true,
4755 0,
4756 NULL);
Eric Laurent6a94d692014-05-20 11:18:06 -07004757 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
4758 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
François Gaffie53615e22015-03-19 09:24:12 +01004759 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004760 if (inputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004761 ALOGV("%s input not found for id %d", __func__, patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004762 return BAD_VALUE;
4763 }
4764 setInputDevice(inputDesc->mIoHandle,
Eric Laurentfb66dd92016-01-28 18:32:03 -08004765 getNewInputDevice(inputDesc),
Eric Laurent6a94d692014-05-20 11:18:06 -07004766 true,
4767 NULL);
4768 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004769 status_t status =
4770 mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
4771 ALOGV("%s patch panel returned %d patchHandle %d",
4772 __func__, status, patchDesc->getAfHandle());
4773 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004774 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004775 mpClientInterface->onAudioPatchListUpdate();
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004776 // SW or HW Bridge
4777 sp<SwAudioOutputDescriptor> outputDesc = nullptr;
4778 audio_patch_handle_t patchHandle = AUDIO_PATCH_HANDLE_NONE;
Francois Gaffie7feb8542020-04-06 17:39:47 +02004779 if (patch->num_sources > 1 && patch->sources[1].type == AUDIO_PORT_TYPE_MIX) {
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004780 outputDesc = mOutputs.getOutputFromId(patch->sources[1].id);
4781 } else if (patch->num_sources == 1 && sourceDesc != nullptr) {
4782 outputDesc = sourceDesc->swOutput().promote();
4783 }
4784 if (outputDesc == nullptr) {
4785 ALOGW("%s no output for id %d", __func__, patch->sources[0].id);
4786 // releaseOutput has already called closeOutput in case of direct output
4787 return NO_ERROR;
4788 }
François Gaffie1765c5b2022-04-26 12:48:49 +02004789 patchHandle = outputDesc->getPatchHandle();
4790 // When a Sw bridge is released, the mixer used by this bridge will release its
4791 // patch at AudioFlinger side. Hence, the mixer audio patch must be recreated
4792 // Reuse patch handle to force audio flinger removing initial mixer patch removal
4793 // updating hal patch handle (prevent leaks).
4794 // While using a HwBridge, force reconsidering device only if not reusing an existing
4795 // output and no more activity on output (will force to close).
4796 bool force = sourceDesc->useSwBridge() ||
4797 (sourceDesc->canCloseOutput() && !outputDesc->isActive());
4798 // APM pattern is to have always outputs opened / patch realized for reachable devices.
4799 // Update device may result to NONE (empty), coupled with force, it releases the patch.
4800 // Reconsider device only for cases:
4801 // 1 / Active Output
4802 // 2 / Inactive Output previously hosting HwBridge
4803 // 3 / Inactive Output previously hosting SwBridge that can be closed.
4804 bool updateDevice = outputDesc->isActive() || !sourceDesc->useSwBridge() ||
4805 sourceDesc->canCloseOutput();
4806 setOutputDevices(outputDesc,
4807 updateDevice ? getNewOutputDevices(outputDesc, true /*fromCache*/) :
4808 outputDesc->devices(),
4809 force,
4810 0,
4811 patchHandle == AUDIO_PATCH_HANDLE_NONE ? nullptr : &patchHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004812 } else {
4813 return BAD_VALUE;
4814 }
4815 } else {
4816 return BAD_VALUE;
4817 }
4818 return NO_ERROR;
4819}
4820
4821status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
4822 struct audio_patch *patches,
4823 unsigned int *generation)
4824{
François Gaffie53615e22015-03-19 09:24:12 +01004825 if (generation == NULL) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004826 return BAD_VALUE;
4827 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004828 *generation = curAudioPortGeneration();
François Gaffie53615e22015-03-19 09:24:12 +01004829 return mAudioPatches.listAudioPatches(num_patches, patches);
Eric Laurent6a94d692014-05-20 11:18:06 -07004830}
4831
Eric Laurente1715a42014-05-20 11:30:42 -07004832status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07004833{
Eric Laurente1715a42014-05-20 11:30:42 -07004834 ALOGV("setAudioPortConfig()");
4835
4836 if (config == NULL) {
4837 return BAD_VALUE;
4838 }
4839 ALOGV("setAudioPortConfig() on port handle %d", config->id);
4840 // Only support gain configuration for now
Eric Laurenta121f902014-06-03 13:32:54 -07004841 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
4842 return INVALID_OPERATION;
Eric Laurente1715a42014-05-20 11:30:42 -07004843 }
4844
Eric Laurenta121f902014-06-03 13:32:54 -07004845 sp<AudioPortConfig> audioPortConfig;
Eric Laurente1715a42014-05-20 11:30:42 -07004846 if (config->type == AUDIO_PORT_TYPE_MIX) {
4847 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004848 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07004849 if (outputDesc == NULL) {
4850 return BAD_VALUE;
4851 }
Eric Laurent84c70242014-06-23 08:46:27 -07004852 ALOG_ASSERT(!outputDesc->isDuplicated(),
4853 "setAudioPortConfig() called on duplicated output %d",
4854 outputDesc->mIoHandle);
Eric Laurenta121f902014-06-03 13:32:54 -07004855 audioPortConfig = outputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07004856 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
François Gaffie53615e22015-03-19 09:24:12 +01004857 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07004858 if (inputDesc == NULL) {
4859 return BAD_VALUE;
4860 }
Eric Laurenta121f902014-06-03 13:32:54 -07004861 audioPortConfig = inputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07004862 } else {
4863 return BAD_VALUE;
4864 }
4865 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
4866 sp<DeviceDescriptor> deviceDesc;
4867 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
4868 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
4869 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
4870 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
4871 } else {
4872 return BAD_VALUE;
4873 }
4874 if (deviceDesc == NULL) {
4875 return BAD_VALUE;
4876 }
Eric Laurenta121f902014-06-03 13:32:54 -07004877 audioPortConfig = deviceDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07004878 } else {
4879 return BAD_VALUE;
4880 }
4881
Mikhail Naganov7be71d22018-05-23 16:51:46 -07004882 struct audio_port_config backupConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07004883 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
4884 if (status == NO_ERROR) {
Mikhail Naganov7be71d22018-05-23 16:51:46 -07004885 struct audio_port_config newConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07004886 audioPortConfig->toAudioPortConfig(&newConfig, config);
4887 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
Eric Laurente1715a42014-05-20 11:30:42 -07004888 }
Eric Laurenta121f902014-06-03 13:32:54 -07004889 if (status != NO_ERROR) {
4890 audioPortConfig->applyAudioPortConfig(&backupConfig);
Eric Laurente1715a42014-05-20 11:30:42 -07004891 }
Eric Laurente1715a42014-05-20 11:30:42 -07004892
4893 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07004894}
4895
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004896void AudioPolicyManager::releaseResourcesForUid(uid_t uid)
4897{
Eric Laurentd60560a2015-04-10 11:31:20 -07004898 clearAudioSources(uid);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004899 clearAudioPatches(uid);
4900 clearSessionRoutes(uid);
4901}
4902
Eric Laurent6a94d692014-05-20 11:18:06 -07004903void AudioPolicyManager::clearAudioPatches(uid_t uid)
4904{
Eric Laurent0add0fd2014-12-04 18:58:14 -08004905 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004906 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
François Gaffieafd4cea2019-11-18 15:50:22 +01004907 if (patchDesc->getUid() == uid) {
Eric Laurent0add0fd2014-12-04 18:58:14 -08004908 releaseAudioPatch(mAudioPatches.keyAt(i), uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07004909 }
4910 }
4911}
4912
François Gaffiec005e562018-11-06 15:04:49 +01004913void AudioPolicyManager::checkStrategyRoute(product_strategy_t ps, audio_io_handle_t ouptutToSkip)
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004914{
François Gaffiec005e562018-11-06 15:04:49 +01004915 // Take the first attributes following the product strategy as it is used to retrieve the routed
4916 // device. All attributes wihin a strategy follows the same "routing strategy"
4917 auto attributes = mEngine->getAllAttributesForProductStrategy(ps).front();
4918 DeviceVector devices = mEngine->getOutputDevicesForAttributes(attributes, nullptr, false);
François Gaffie11d30102018-11-02 16:09:09 +01004919 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004920 for (size_t j = 0; j < mOutputs.size(); j++) {
4921 if (mOutputs.keyAt(j) == ouptutToSkip) {
4922 continue;
4923 }
4924 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(j);
François Gaffiec005e562018-11-06 15:04:49 +01004925 if (!outputDesc->isStrategyActive(ps)) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004926 continue;
4927 }
4928 // If the default device for this strategy is on another output mix,
4929 // invalidate all tracks in this strategy to force re connection.
4930 // Otherwise select new device on the output mix.
4931 if (outputs.indexOf(mOutputs.keyAt(j)) < 0) {
François Gaffiec005e562018-11-06 15:04:49 +01004932 for (auto stream : mEngine->getStreamTypesForProductStrategy(ps)) {
4933 mpClientInterface->invalidateStream(stream);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004934 }
4935 } else {
François Gaffie11d30102018-11-02 16:09:09 +01004936 setOutputDevices(
4937 outputDesc, getNewOutputDevices(outputDesc, false /*fromCache*/), false);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004938 }
4939 }
4940}
4941
4942void AudioPolicyManager::clearSessionRoutes(uid_t uid)
4943{
4944 // remove output routes associated with this uid
François Gaffiec005e562018-11-06 15:04:49 +01004945 std::vector<product_strategy_t> affectedStrategies;
Eric Laurent97ac8712018-07-27 18:59:02 -07004946 for (size_t i = 0; i < mOutputs.size(); i++) {
4947 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07004948 for (const auto& client : outputDesc->getClientIterable()) {
4949 if (client->hasPreferredDevice() && client->uid() == uid) {
4950 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
François Gaffiec005e562018-11-06 15:04:49 +01004951 auto clientStrategy = client->strategy();
4952 if (std::find(begin(affectedStrategies), end(affectedStrategies), clientStrategy) !=
4953 end(affectedStrategies)) {
4954 continue;
4955 }
4956 affectedStrategies.push_back(client->strategy());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004957 }
4958 }
4959 }
4960 // reroute outputs if necessary
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004961 for (const auto& strategy : affectedStrategies) {
4962 checkStrategyRoute(strategy, AUDIO_IO_HANDLE_NONE);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004963 }
4964
4965 // remove input routes associated with this uid
4966 SortedVector<audio_source_t> affectedSources;
Eric Laurent97ac8712018-07-27 18:59:02 -07004967 for (size_t i = 0; i < mInputs.size(); i++) {
4968 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07004969 for (const auto& client : inputDesc->getClientIterable()) {
4970 if (client->hasPreferredDevice() && client->uid() == uid) {
4971 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
4972 affectedSources.add(client->source());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004973 }
4974 }
4975 }
4976 // reroute inputs if necessary
4977 SortedVector<audio_io_handle_t> inputsToClose;
4978 for (size_t i = 0; i < mInputs.size(); i++) {
4979 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Eric Laurent4eb58f12018-12-07 16:41:02 -08004980 if (affectedSources.indexOf(inputDesc->source()) >= 0) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004981 inputsToClose.add(inputDesc->mIoHandle);
4982 }
4983 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004984 for (const auto& input : inputsToClose) {
4985 closeInput(input);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004986 }
4987}
4988
Eric Laurentd60560a2015-04-10 11:31:20 -07004989void AudioPolicyManager::clearAudioSources(uid_t uid)
4990{
4991 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004992 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
4993 if (sourceDesc->uid() == uid) {
Eric Laurentd60560a2015-04-10 11:31:20 -07004994 stopAudioSource(mAudioSources.keyAt(i));
4995 }
4996 }
4997}
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004998
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07004999status_t AudioPolicyManager::acquireSoundTriggerSession(audio_session_t *session,
5000 audio_io_handle_t *ioHandle,
5001 audio_devices_t *device)
5002{
Glenn Kastenf0c6d7d2016-02-26 10:44:04 -08005003 *session = (audio_session_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
5004 *ioHandle = (audio_io_handle_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
Francois Gaffie716e1432019-01-14 16:58:59 +01005005 audio_attributes_t attr = { .source = AUDIO_SOURCE_HOTWORD };
François Gaffiec005e562018-11-06 15:04:49 +01005006 *device = mEngine->getInputDeviceForAttributes(attr)->type();
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005007
François Gaffiedf372692015-03-19 10:43:27 +01005008 return mSoundTriggerSessions.acquireSession(*session, *ioHandle);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005009}
5010
Eric Laurentd60560a2015-04-10 11:31:20 -07005011status_t AudioPolicyManager::startAudioSource(const struct audio_port_config *source,
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005012 const audio_attributes_t *attributes,
5013 audio_port_handle_t *portId,
5014 uid_t uid)
Eric Laurent554a2772015-04-10 11:29:24 -07005015{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005016 ALOGV("%s", __FUNCTION__);
5017 *portId = AUDIO_PORT_HANDLE_NONE;
5018
5019 if (source == NULL || attributes == NULL || portId == NULL) {
5020 ALOGW("%s invalid argument: source %p attributes %p handle %p",
5021 __FUNCTION__, source, attributes, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005022 return BAD_VALUE;
5023 }
5024
Eric Laurentd60560a2015-04-10 11:31:20 -07005025 if (source->role != AUDIO_PORT_ROLE_SOURCE ||
5026 source->type != AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005027 ALOGW("%s INVALID_OPERATION source->role %d source->type %d",
5028 __FUNCTION__, source->role, source->type);
Eric Laurentd60560a2015-04-10 11:31:20 -07005029 return INVALID_OPERATION;
5030 }
5031
François Gaffie11d30102018-11-02 16:09:09 +01005032 sp<DeviceDescriptor> srcDevice =
Eric Laurentd60560a2015-04-10 11:31:20 -07005033 mAvailableInputDevices.getDevice(source->ext.device.type,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005034 String8(source->ext.device.address),
5035 AUDIO_FORMAT_DEFAULT);
François Gaffie11d30102018-11-02 16:09:09 +01005036 if (srcDevice == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005037 ALOGW("%s source->ext.device.type %08x not found", __FUNCTION__, source->ext.device.type);
Eric Laurentd60560a2015-04-10 11:31:20 -07005038 return BAD_VALUE;
5039 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005040
jiabin4ef93452019-09-10 14:29:54 -07005041 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurentd60560a2015-04-10 11:31:20 -07005042
François Gaffieaaac0fd2018-11-22 17:56:39 +01005043 sp<SourceClientDescriptor> sourceDesc =
François Gaffieafd4cea2019-11-18 15:50:22 +01005044 new SourceClientDescriptor(*portId, uid, *attributes, *source, srcDevice,
François Gaffieaaac0fd2018-11-22 17:56:39 +01005045 mEngine->getStreamTypeForAttributes(*attributes),
5046 mEngine->getProductStrategyForAttributes(*attributes),
5047 toVolumeSource(*attributes));
Eric Laurentd60560a2015-04-10 11:31:20 -07005048
5049 status_t status = connectAudioSource(sourceDesc);
5050 if (status == NO_ERROR) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005051 mAudioSources.add(*portId, sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07005052 }
5053 return status;
5054}
5055
Francois Gaffie601801d2021-06-22 13:27:39 +02005056sp<SourceClientDescriptor> AudioPolicyManager::startAudioSourceInternal(
5057 const struct audio_port_config *source, const audio_attributes_t *attributes, uid_t uid)
5058{
5059 ALOGV("%s", __FUNCTION__);
5060 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
5061
5062 status_t status = startAudioSource(source, attributes, &portId, uid);
5063 ALOGE_IF(status != OK, "%s: failed to start audio source (%d)", __func__, status);
5064 return mAudioSources.valueFor(portId);
5065}
5066
5067
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005068status_t AudioPolicyManager::connectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07005069{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005070 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->portId());
Eric Laurentd60560a2015-04-10 11:31:20 -07005071
5072 // make sure we only have one patch per source.
5073 disconnectAudioSource(sourceDesc);
5074
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005075 audio_attributes_t attributes = sourceDesc->attributes();
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005076 // May the device (dynamic) have been disconnected/reconnected, id has changed.
5077 sp<DeviceDescriptor> srcDevice = mAvailableInputDevices.getDevice(
5078 sourceDesc->srcDevice()->type(),
5079 String8(sourceDesc->srcDevice()->address().c_str()),
5080 AUDIO_FORMAT_DEFAULT);
François Gaffiec005e562018-11-06 15:04:49 +01005081 DeviceVector sinkDevices =
Francois Gaffieff1eb522020-05-06 18:37:04 +02005082 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false /*fromCache*/);
François Gaffiec005e562018-11-06 15:04:49 +01005083 ALOG_ASSERT(!sinkDevices.isEmpty(), "connectAudioSource(): no device found for attributes");
François Gaffie11d30102018-11-02 16:09:09 +01005084 sp<DeviceDescriptor> sinkDevice = sinkDevices.itemAt(0);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005085 if (!mAvailableOutputDevices.contains(sinkDevice)) {
5086 ALOGE("%s Device %s not available", __func__, sinkDevice->toString().c_str());
5087 return INVALID_OPERATION;
5088 }
François Gaffieafd4cea2019-11-18 15:50:22 +01005089 PatchBuilder patchBuilder;
5090 patchBuilder.addSink(sinkDevice).addSource(srcDevice);
5091 audio_patch_handle_t handle = AUDIO_PATCH_HANDLE_NONE;
François Gaffieafd4cea2019-11-18 15:50:22 +01005092
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005093 return connectAudioSourceToSink(
5094 sourceDesc, sinkDevice, patchBuilder.patch(), handle, mUidCached, 0 /*delayMs*/);
Eric Laurent554a2772015-04-10 11:29:24 -07005095}
5096
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005097status_t AudioPolicyManager::stopAudioSource(audio_port_handle_t portId)
Eric Laurent554a2772015-04-10 11:29:24 -07005098{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005099 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueFor(portId);
5100 ALOGV("%s port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005101 if (sourceDesc == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005102 ALOGW("%s unknown source for port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005103 return BAD_VALUE;
5104 }
5105 status_t status = disconnectAudioSource(sourceDesc);
5106
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005107 mAudioSources.removeItem(portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005108 return status;
5109}
5110
Andy Hung2ddee192015-12-18 17:34:44 -08005111status_t AudioPolicyManager::setMasterMono(bool mono)
5112{
5113 if (mMasterMono == mono) {
5114 return NO_ERROR;
5115 }
5116 mMasterMono = mono;
5117 // if enabling mono we close all offloaded devices, which will invalidate the
5118 // corresponding AudioTrack. The AudioTrack client/MediaPlayer is responsible
5119 // for recreating the new AudioTrack as non-offloaded PCM.
5120 //
5121 // If disabling mono, we leave all tracks as is: we don't know which clients
5122 // and tracks are able to be recreated as offloaded. The next "song" should
5123 // play back offloaded.
5124 if (mMasterMono) {
5125 Vector<audio_io_handle_t> offloaded;
5126 for (size_t i = 0; i < mOutputs.size(); ++i) {
5127 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
5128 if (desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
5129 offloaded.push(desc->mIoHandle);
5130 }
5131 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005132 for (const auto& handle : offloaded) {
5133 closeOutput(handle);
Andy Hung2ddee192015-12-18 17:34:44 -08005134 }
5135 }
5136 // update master mono for all remaining outputs
5137 for (size_t i = 0; i < mOutputs.size(); ++i) {
5138 updateMono(mOutputs.keyAt(i));
5139 }
5140 return NO_ERROR;
5141}
5142
5143status_t AudioPolicyManager::getMasterMono(bool *mono)
5144{
5145 *mono = mMasterMono;
5146 return NO_ERROR;
5147}
5148
Eric Laurentac9cef52017-06-09 15:46:26 -07005149float AudioPolicyManager::getStreamVolumeDB(
5150 audio_stream_type_t stream, int index, audio_devices_t device)
5151{
jiabin9a3361e2019-10-01 09:38:30 -07005152 return computeVolume(getVolumeCurves(stream), toVolumeSource(stream), index, {device});
Eric Laurentac9cef52017-06-09 15:46:26 -07005153}
5154
jiabin81772902018-04-02 17:52:27 -07005155status_t AudioPolicyManager::getSurroundFormats(unsigned int *numSurroundFormats,
5156 audio_format_t *surroundFormats,
Kriti Dang6537def2021-03-02 13:46:59 +01005157 bool *surroundFormatsEnabled)
jiabin81772902018-04-02 17:52:27 -07005158{
Kriti Dang6537def2021-03-02 13:46:59 +01005159 if (numSurroundFormats == nullptr || (*numSurroundFormats != 0 &&
5160 (surroundFormats == nullptr || surroundFormatsEnabled == nullptr))) {
jiabin81772902018-04-02 17:52:27 -07005161 return BAD_VALUE;
5162 }
Kriti Dang6537def2021-03-02 13:46:59 +01005163 ALOGV("%s() numSurroundFormats %d surroundFormats %p surroundFormatsEnabled %p",
5164 __func__, *numSurroundFormats, surroundFormats, surroundFormatsEnabled);
jiabin81772902018-04-02 17:52:27 -07005165
5166 size_t formatsWritten = 0;
5167 size_t formatsMax = *numSurroundFormats;
Kriti Dangef6be8f2020-11-05 11:58:19 +01005168
Mikhail Naganovb0fbc1b2023-04-28 13:06:32 -07005169 *numSurroundFormats = mConfig->getSurroundFormats().size();
Mikhail Naganov100f0122018-11-29 11:22:16 -08005170 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
5171 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Mikhail Naganovb0fbc1b2023-04-28 13:06:32 -07005172 for (const auto& format: mConfig->getSurroundFormats()) {
jiabin81772902018-04-02 17:52:27 -07005173 if (formatsWritten < formatsMax) {
Kriti Dang6537def2021-03-02 13:46:59 +01005174 surroundFormats[formatsWritten] = format.first;
Mikhail Naganov100f0122018-11-29 11:22:16 -08005175 bool formatEnabled = true;
5176 switch (forceUse) {
5177 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL:
Kriti Dang6537def2021-03-02 13:46:59 +01005178 formatEnabled = mManualSurroundFormats.count(format.first) != 0;
Mikhail Naganov100f0122018-11-29 11:22:16 -08005179 break;
5180 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER:
5181 formatEnabled = false;
5182 break;
5183 default: // AUTO or ALWAYS => true
5184 break;
jiabin81772902018-04-02 17:52:27 -07005185 }
5186 surroundFormatsEnabled[formatsWritten++] = formatEnabled;
5187 }
jiabin81772902018-04-02 17:52:27 -07005188 }
5189 return NO_ERROR;
5190}
5191
Kriti Dang6537def2021-03-02 13:46:59 +01005192status_t AudioPolicyManager::getReportedSurroundFormats(unsigned int *numSurroundFormats,
5193 audio_format_t *surroundFormats) {
5194 if (numSurroundFormats == nullptr || (*numSurroundFormats != 0 && surroundFormats == nullptr)) {
5195 return BAD_VALUE;
5196 }
5197 ALOGV("%s() numSurroundFormats %d surroundFormats %p",
5198 __func__, *numSurroundFormats, surroundFormats);
5199
5200 size_t formatsWritten = 0;
5201 size_t formatsMax = *numSurroundFormats;
5202 std::unordered_set<audio_format_t> formats; // Uses primary surround formats only
5203
5204 // Return formats from all device profiles that have already been resolved by
5205 // checkOutputsForDevice().
5206 for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
5207 sp<DeviceDescriptor> device = mAvailableOutputDevices[i];
5208 audio_devices_t deviceType = device->type();
5209 // Enabling/disabling formats are applied to only HDMI devices. So, this function
5210 // returns formats reported by HDMI devices.
5211 if (deviceType != AUDIO_DEVICE_OUT_HDMI) {
5212 continue;
5213 }
5214 // Formats reported by sink devices
5215 std::unordered_set<audio_format_t> formatset;
5216 if (auto it = mReportedFormatsMap.find(device); it != mReportedFormatsMap.end()) {
5217 formatset.insert(it->second.begin(), it->second.end());
5218 }
5219
5220 // Formats hard-coded in the in policy configuration file (if any).
5221 FormatVector encodedFormats = device->encodedFormats();
5222 formatset.insert(encodedFormats.begin(), encodedFormats.end());
5223 // Filter the formats which are supported by the vendor hardware.
5224 for (auto it = formatset.begin(); it != formatset.end(); ++it) {
Mikhail Naganovb0fbc1b2023-04-28 13:06:32 -07005225 if (mConfig->getSurroundFormats().count(*it) != 0) {
Kriti Dang6537def2021-03-02 13:46:59 +01005226 formats.insert(*it);
5227 } else {
Mikhail Naganovb0fbc1b2023-04-28 13:06:32 -07005228 for (const auto& pair : mConfig->getSurroundFormats()) {
Kriti Dang6537def2021-03-02 13:46:59 +01005229 if (pair.second.count(*it) != 0) {
5230 formats.insert(pair.first);
5231 break;
5232 }
5233 }
5234 }
5235 }
5236 }
5237 *numSurroundFormats = formats.size();
5238 for (const auto& format: formats) {
5239 if (formatsWritten < formatsMax) {
5240 surroundFormats[formatsWritten++] = format;
5241 }
5242 }
5243 return NO_ERROR;
5244}
5245
jiabin81772902018-04-02 17:52:27 -07005246status_t AudioPolicyManager::setSurroundFormatEnabled(audio_format_t audioFormat, bool enabled)
5247{
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005248 ALOGV("%s() format 0x%X enabled %d", __func__, audioFormat, enabled);
Mikhail Naganovb0fbc1b2023-04-28 13:06:32 -07005249 const auto& formatIter = mConfig->getSurroundFormats().find(audioFormat);
5250 if (formatIter == mConfig->getSurroundFormats().end()) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005251 ALOGW("%s() format 0x%X is not a known surround format", __func__, audioFormat);
jiabin81772902018-04-02 17:52:27 -07005252 return BAD_VALUE;
5253 }
5254
Mikhail Naganov100f0122018-11-29 11:22:16 -08005255 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND) !=
5256 AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005257 ALOGW("%s() not in manual mode for surround sound format selection", __func__);
jiabin81772902018-04-02 17:52:27 -07005258 return INVALID_OPERATION;
5259 }
5260
Mikhail Naganov100f0122018-11-29 11:22:16 -08005261 if ((mManualSurroundFormats.count(audioFormat) != 0) == enabled) {
jiabin81772902018-04-02 17:52:27 -07005262 return NO_ERROR;
5263 }
5264
Mikhail Naganov100f0122018-11-29 11:22:16 -08005265 std::unordered_set<audio_format_t> surroundFormatsBackup(mManualSurroundFormats);
jiabin81772902018-04-02 17:52:27 -07005266 if (enabled) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005267 mManualSurroundFormats.insert(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07005268 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005269 mManualSurroundFormats.insert(subFormat);
jiabin81772902018-04-02 17:52:27 -07005270 }
5271 } else {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005272 mManualSurroundFormats.erase(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07005273 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005274 mManualSurroundFormats.erase(subFormat);
jiabin81772902018-04-02 17:52:27 -07005275 }
5276 }
5277
5278 sp<SwAudioOutputDescriptor> outputDesc;
5279 bool profileUpdated = false;
jiabin9a3361e2019-10-01 09:38:30 -07005280 DeviceVector hdmiOutputDevices = mAvailableOutputDevices.getDevicesFromType(
5281 AUDIO_DEVICE_OUT_HDMI);
jiabin81772902018-04-02 17:52:27 -07005282 for (size_t i = 0; i < hdmiOutputDevices.size(); i++) {
5283 // Simulate reconnection to update enabled surround sound formats.
jiabince9f20e2019-09-12 16:29:15 -07005284 String8 address = String8(hdmiOutputDevices[i]->address().c_str());
jiabin5740f082019-08-19 15:08:30 -07005285 std::string name = hdmiOutputDevices[i]->getName();
jiabin81772902018-04-02 17:52:27 -07005286 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
5287 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
5288 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005289 name.c_str(),
5290 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005291 if (status != NO_ERROR) {
5292 continue;
5293 }
5294 status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
5295 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
5296 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005297 name.c_str(),
5298 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005299 profileUpdated |= (status == NO_ERROR);
5300 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08005301 // FIXME: Why doing this for input HDMI devices if we don't augment their reported formats?
jiabin9a3361e2019-10-01 09:38:30 -07005302 DeviceVector hdmiInputDevices = mAvailableInputDevices.getDevicesFromType(
jiabin81772902018-04-02 17:52:27 -07005303 AUDIO_DEVICE_IN_HDMI);
5304 for (size_t i = 0; i < hdmiInputDevices.size(); i++) {
5305 // Simulate reconnection to update enabled surround sound formats.
jiabince9f20e2019-09-12 16:29:15 -07005306 String8 address = String8(hdmiInputDevices[i]->address().c_str());
jiabin5740f082019-08-19 15:08:30 -07005307 std::string name = hdmiInputDevices[i]->getName();
jiabin81772902018-04-02 17:52:27 -07005308 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
5309 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
5310 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005311 name.c_str(),
5312 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005313 if (status != NO_ERROR) {
5314 continue;
5315 }
5316 status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
5317 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
5318 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005319 name.c_str(),
5320 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005321 profileUpdated |= (status == NO_ERROR);
5322 }
5323
jiabin81772902018-04-02 17:52:27 -07005324 if (!profileUpdated) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005325 ALOGW("%s() no audio profiles updated, undoing surround formats change", __func__);
Mikhail Naganov100f0122018-11-29 11:22:16 -08005326 mManualSurroundFormats = std::move(surroundFormatsBackup);
jiabin81772902018-04-02 17:52:27 -07005327 }
5328
5329 return profileUpdated ? NO_ERROR : INVALID_OPERATION;
5330}
5331
Eric Laurent5ada82e2019-08-29 17:53:54 -07005332void AudioPolicyManager::setAppState(audio_port_handle_t portId, app_state_t state)
Svet Ganovf4ddfef2018-01-16 07:37:58 -08005333{
Eric Laurent5ada82e2019-08-29 17:53:54 -07005334 ALOGV("%s(portId:%d, state:%d)", __func__, portId, state);
Eric Laurenta9f86652018-11-28 17:23:11 -08005335 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent5ada82e2019-08-29 17:53:54 -07005336 mInputs.valueAt(i)->setAppState(portId, state);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08005337 }
5338}
5339
jiabin6012f912018-11-02 17:06:30 -07005340bool AudioPolicyManager::isHapticPlaybackSupported()
5341{
5342 for (const auto& hwModule : mHwModules) {
5343 const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
5344 for (const auto &outProfile : outputProfiles) {
5345 struct audio_port audioPort;
5346 outProfile->toAudioPort(&audioPort);
5347 for (size_t i = 0; i < audioPort.num_channel_masks; i++) {
5348 if (audioPort.channel_masks[i] & AUDIO_CHANNEL_HAPTIC_ALL) {
5349 return true;
5350 }
5351 }
5352 }
5353 }
5354 return false;
5355}
5356
Carter Hsu325a8eb2022-01-19 19:56:51 +08005357bool AudioPolicyManager::isUltrasoundSupported()
5358{
5359 bool hasUltrasoundOutput = false;
5360 bool hasUltrasoundInput = false;
5361 for (const auto& hwModule : mHwModules) {
5362 const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
5363 if (!hasUltrasoundOutput) {
5364 for (const auto &outProfile : outputProfiles) {
5365 if (outProfile->getFlags() & AUDIO_OUTPUT_FLAG_ULTRASOUND) {
5366 hasUltrasoundOutput = true;
5367 break;
5368 }
5369 }
5370 }
5371
5372 const InputProfileCollection &inputProfiles = hwModule->getInputProfiles();
5373 if (!hasUltrasoundInput) {
5374 for (const auto &inputProfile : inputProfiles) {
5375 if (inputProfile->getFlags() & AUDIO_INPUT_FLAG_ULTRASOUND) {
5376 hasUltrasoundInput = true;
5377 break;
5378 }
5379 }
5380 }
5381
5382 if (hasUltrasoundOutput && hasUltrasoundInput)
5383 return true;
5384 }
5385 return false;
5386}
5387
Eric Laurent8340e672019-11-06 11:01:08 -08005388bool AudioPolicyManager::isCallScreenModeSupported()
5389{
Mikhail Naganovb0fbc1b2023-04-28 13:06:32 -07005390 return mConfig->isCallScreenModeSupported();
Eric Laurent8340e672019-11-06 11:01:08 -08005391}
5392
5393
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005394status_t AudioPolicyManager::disconnectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07005395{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005396 ALOGV("%s port Id %d", __FUNCTION__, sourceDesc->portId());
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005397 if (!sourceDesc->isConnected()) {
5398 ALOGV("%s port Id %d already disconnected", __FUNCTION__, sourceDesc->portId());
5399 return NO_ERROR;
5400 }
François Gaffieafd4cea2019-11-18 15:50:22 +01005401 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
5402 if (swOutput != 0) {
5403 status_t status = stopSource(swOutput, sourceDesc);
Eric Laurent733ce942017-12-07 12:18:25 -08005404 if (status == NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005405 swOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08005406 }
jiabinbce0c1d2020-10-05 11:20:18 -07005407 if (releaseOutput(sourceDesc->portId())) {
5408 // The output descriptor is reopened to query dynamic profiles. In that case, there is
5409 // no need to release audio patch here but just return NO_ERROR.
5410 return NO_ERROR;
5411 }
Eric Laurentd60560a2015-04-10 11:31:20 -07005412 } else {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005413 sp<HwAudioOutputDescriptor> hwOutputDesc = sourceDesc->hwOutput().promote();
Eric Laurentd60560a2015-04-10 11:31:20 -07005414 if (hwOutputDesc != 0) {
Eric Laurentd60560a2015-04-10 11:31:20 -07005415 // close Hwoutput and remove from mHwOutputs
5416 } else {
5417 ALOGW("%s source has neither SW nor HW output", __FUNCTION__);
5418 }
5419 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005420 status_t status = releaseAudioPatchInternal(sourceDesc->getPatchHandle(), 0, sourceDesc);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005421 sourceDesc->disconnect();
5422 return status;
Eric Laurentd60560a2015-04-10 11:31:20 -07005423}
5424
François Gaffiec005e562018-11-06 15:04:49 +01005425sp<SourceClientDescriptor> AudioPolicyManager::getSourceForAttributesOnOutput(
5426 audio_io_handle_t output, const audio_attributes_t &attr)
Eric Laurentd60560a2015-04-10 11:31:20 -07005427{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005428 sp<SourceClientDescriptor> source;
Eric Laurentd60560a2015-04-10 11:31:20 -07005429 for (size_t i = 0; i < mAudioSources.size(); i++) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005430 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005431 sp<SwAudioOutputDescriptor> outputDesc = sourceDesc->swOutput().promote();
François Gaffiec005e562018-11-06 15:04:49 +01005432 if (followsSameRouting(attr, sourceDesc->attributes()) &&
5433 outputDesc != 0 && outputDesc->mIoHandle == output) {
Eric Laurentd60560a2015-04-10 11:31:20 -07005434 source = sourceDesc;
5435 break;
5436 }
5437 }
5438 return source;
Eric Laurent554a2772015-04-10 11:29:24 -07005439}
5440
Eric Laurentb4f42a92022-01-17 17:37:31 +01005441bool AudioPolicyManager::canBeSpatializedInt(const audio_attributes_t *attr,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005442 const audio_config_t *config,
Andy Hung9dd1a5b2022-05-10 15:39:39 -07005443 const AudioDeviceTypeAddrVector &devices) const
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005444{
5445 // The caller can have the audio attributes criteria ignored by either passing a null ptr or
5446 // the AUDIO_ATTRIBUTES_INITIALIZER value.
Eric Laurentfa0f6742021-08-17 18:39:44 +02005447 // If attributes are specified, current policy is to only allow spatialization for media
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005448 // and game usages.
Eric Laurent39095982021-08-24 18:29:27 +02005449 if (attr != nullptr && *attr != AUDIO_ATTRIBUTES_INITIALIZER) {
5450 if (attr->usage != AUDIO_USAGE_MEDIA && attr->usage != AUDIO_USAGE_GAME) {
5451 return false;
5452 }
5453 if ((attr->flags & (AUDIO_FLAG_CONTENT_SPATIALIZED | AUDIO_FLAG_NEVER_SPATIALIZE)) != 0) {
5454 return false;
5455 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005456 }
5457
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005458 sp<IOProfile> profile =
Eric Laurent39095982021-08-24 18:29:27 +02005459 getSpatializerOutputProfile(config, devices);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005460 if (profile == nullptr) {
5461 return false;
5462 }
5463
5464 // The caller can have the audio config criteria ignored by either passing a null ptr or
5465 // the AUDIO_CONFIG_INITIALIZER value.
Eric Laurentfa0f6742021-08-17 18:39:44 +02005466 // If an audio config is specified, current policy is to only allow spatialization for
Eric Laurent39095982021-08-24 18:29:27 +02005467 // some positional channel masks.
Eric Laurent39095982021-08-24 18:29:27 +02005468
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005469 if (config != nullptr && *config != AUDIO_CONFIG_INITIALIZER) {
Andy Hung9dd1a5b2022-05-10 15:39:39 -07005470 if (!audio_is_channel_mask_spatialized(config->channel_mask)) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005471 return false;
5472 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005473 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005474 return true;
5475}
5476
5477void AudioPolicyManager::checkVirtualizerClientRoutes() {
5478 std::set<audio_stream_type_t> streamsToInvalidate;
5479 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent39095982021-08-24 18:29:27 +02005480 const sp<SwAudioOutputDescriptor>& desc = mOutputs[i];
5481 for (const sp<TrackClientDescriptor>& client : desc->getClientIterable()) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005482 audio_attributes_t attr = client->attributes();
5483 DeviceVector devices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false);
5484 AudioDeviceTypeAddrVector devicesTypeAddress = devices.toTypeAddrVector();
5485 audio_config_base_t clientConfig = client->config();
5486 audio_config_t config = audio_config_initializer(&clientConfig);
Eric Laurent39095982021-08-24 18:29:27 +02005487 if (desc != mSpatializerOutput
Andy Hung9dd1a5b2022-05-10 15:39:39 -07005488 && canBeSpatializedInt(&attr, &config, devicesTypeAddress)) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005489 streamsToInvalidate.insert(client->stream());
5490 }
5491 }
5492 }
5493
5494 for (audio_stream_type_t stream : streamsToInvalidate) {
5495 mpClientInterface->invalidateStream(stream);
5496 }
5497}
5498
Eric Laurente191d1b2022-04-15 11:59:25 +02005499
5500bool AudioPolicyManager::isOutputOnlyAvailableRouteToSomeDevice(
5501 const sp<SwAudioOutputDescriptor>& outputDesc) {
5502 if (outputDesc->isDuplicated()) {
5503 return false;
5504 }
5505 DeviceVector devices = outputDesc->supportedDevices();
5506 for (size_t i = 0; i < mOutputs.size(); i++) {
5507 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
5508 if (desc == outputDesc || desc->isDuplicated()) {
5509 continue;
5510 }
5511 DeviceVector sharedDevices = desc->filterSupportedDevices(devices);
5512 if (!sharedDevices.isEmpty()
5513 && (desc->devicesSupportEncodedFormats(sharedDevices.types())
5514 == outputDesc->devicesSupportEncodedFormats(sharedDevices.types()))) {
5515 return false;
5516 }
5517 }
5518 return true;
5519}
5520
5521
Eric Laurentfa0f6742021-08-17 18:39:44 +02005522status_t AudioPolicyManager::getSpatializerOutput(const audio_config_base_t *mixerConfig,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005523 const audio_attributes_t *attr,
5524 audio_io_handle_t *output) {
5525 *output = AUDIO_IO_HANDLE_NONE;
5526
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005527 DeviceVector devices = mEngine->getOutputDevicesForAttributes(*attr, nullptr, false);
5528 AudioDeviceTypeAddrVector devicesTypeAddress = devices.toTypeAddrVector();
5529 audio_config_t *configPtr = nullptr;
5530 audio_config_t config;
5531 if (mixerConfig != nullptr) {
5532 config = audio_config_initializer(mixerConfig);
5533 configPtr = &config;
5534 }
Andy Hung9dd1a5b2022-05-10 15:39:39 -07005535 if (!canBeSpatializedInt(attr, configPtr, devicesTypeAddress)) {
Eric Laurente191d1b2022-04-15 11:59:25 +02005536 ALOGV("%s provided attributes or mixer config cannot be spatialized", __func__);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005537 return BAD_VALUE;
5538 }
5539
5540 sp<IOProfile> profile =
Eric Laurent39095982021-08-24 18:29:27 +02005541 getSpatializerOutputProfile(configPtr, devicesTypeAddress);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005542 if (profile == nullptr) {
Eric Laurente191d1b2022-04-15 11:59:25 +02005543 ALOGV("%s no suitable output profile for provided attributes or mixer config", __func__);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005544 return BAD_VALUE;
5545 }
5546
Eric Laurente191d1b2022-04-15 11:59:25 +02005547 std::vector<sp<SwAudioOutputDescriptor>> spatializerOutputs;
Eric Laurent39095982021-08-24 18:29:27 +02005548 for (size_t i = 0; i < mOutputs.size(); i++) {
5549 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente191d1b2022-04-15 11:59:25 +02005550 if (!desc->isDuplicated()
5551 && (desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0) {
5552 spatializerOutputs.push_back(desc);
5553 ALOGV("%s adding opened spatializer Output %d", __func__, desc->mIoHandle);
Eric Laurent39095982021-08-24 18:29:27 +02005554 }
5555 }
Eric Laurente191d1b2022-04-15 11:59:25 +02005556 mSpatializerOutput.clear();
5557 bool outputsChanged = false;
5558 for (const auto& desc : spatializerOutputs) {
5559 if (desc->mProfile == profile
5560 && (configPtr == nullptr
5561 || configPtr->channel_mask == desc->mMixerChannelMask)) {
5562 mSpatializerOutput = desc;
5563 ALOGV("%s reusing current spatializer output %d", __func__, desc->mIoHandle);
5564 } else {
5565 ALOGV("%s closing spatializerOutput output %d to match channel mask %#x"
5566 " and devices %s", __func__, desc->mIoHandle,
5567 configPtr != nullptr ? configPtr->channel_mask : 0,
5568 devices.toString().c_str());
5569 closeOutput(desc->mIoHandle);
5570 outputsChanged = true;
5571 }
Eric Laurent39095982021-08-24 18:29:27 +02005572 }
5573
Eric Laurente191d1b2022-04-15 11:59:25 +02005574 if (mSpatializerOutput == nullptr) {
Eric Laurentb4f42a92022-01-17 17:37:31 +01005575 sp<SwAudioOutputDescriptor> desc =
5576 openOutputWithProfileAndDevice(profile, devices, mixerConfig);
Eric Laurente191d1b2022-04-15 11:59:25 +02005577 if (desc != nullptr) {
5578 mSpatializerOutput = desc;
5579 outputsChanged = true;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005580 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005581 }
5582
5583 checkVirtualizerClientRoutes();
5584
Eric Laurente191d1b2022-04-15 11:59:25 +02005585 if (outputsChanged) {
5586 mPreviousOutputs = mOutputs;
5587 mpClientInterface->onAudioPortListUpdate();
5588 }
5589
5590 if (mSpatializerOutput == nullptr) {
5591 ALOGV("%s could not open spatializer output with requested config", __func__);
5592 return BAD_VALUE;
5593 }
Eric Laurent39095982021-08-24 18:29:27 +02005594 *output = mSpatializerOutput->mIoHandle;
Eric Laurente191d1b2022-04-15 11:59:25 +02005595 ALOGV("%s returning new spatializer output %d", __func__, *output);
5596 return OK;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005597}
5598
Eric Laurentfa0f6742021-08-17 18:39:44 +02005599status_t AudioPolicyManager::releaseSpatializerOutput(audio_io_handle_t output) {
5600 if (mSpatializerOutput == nullptr) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005601 return INVALID_OPERATION;
5602 }
Eric Laurentfa0f6742021-08-17 18:39:44 +02005603 if (mSpatializerOutput->mIoHandle != output) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005604 return BAD_VALUE;
5605 }
Eric Laurent39095982021-08-24 18:29:27 +02005606
Eric Laurente191d1b2022-04-15 11:59:25 +02005607 if (!isOutputOnlyAvailableRouteToSomeDevice(mSpatializerOutput)) {
5608 ALOGV("%s closing spatializer output %d", __func__, mSpatializerOutput->mIoHandle);
5609 closeOutput(mSpatializerOutput->mIoHandle);
5610 //from now on mSpatializerOutput is null
5611 checkVirtualizerClientRoutes();
5612 }
Eric Laurent39095982021-08-24 18:29:27 +02005613
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005614 return NO_ERROR;
5615}
5616
Eric Laurente552edb2014-03-10 17:42:56 -07005617// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07005618// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07005619// ----------------------------------------------------------------------------
Eric Laurent6a94d692014-05-20 11:18:06 -07005620uint32_t AudioPolicyManager::nextAudioPortGeneration()
5621{
Mikhail Naganov2773dd72017-12-08 10:12:11 -08005622 return mAudioPortGeneration++;
Eric Laurent6a94d692014-05-20 11:18:06 -07005623}
5624
Mikhail Naganovb0fbc1b2023-04-28 13:06:32 -07005625AudioPolicyManager::AudioPolicyManager(const sp<const AudioPolicyConfig>& config,
Mikhail Naganovabb04782023-05-02 13:56:01 -07005626 EngineInstance&& engine,
Mikhail Naganovb0fbc1b2023-04-28 13:06:32 -07005627 AudioPolicyClientInterface *clientInterface)
Eric Laurente552edb2014-03-10 17:42:56 -07005628 :
Andy Hung4ef19fa2018-05-15 19:35:29 -07005629 mUidCached(AID_AUDIOSERVER), // no need to call getuid(), there's only one of us running.
Mikhail Naganovb0fbc1b2023-04-28 13:06:32 -07005630 mConfig(config),
Mikhail Naganovabb04782023-05-02 13:56:01 -07005631 mEngine(std::move(engine)),
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005632 mpClientInterface(clientInterface),
Eric Laurente552edb2014-03-10 17:42:56 -07005633 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
Eric Laurent3a4311c2014-03-17 12:00:47 -07005634 mA2dpSuspended(false),
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005635 mAudioPortGeneration(1),
5636 mBeaconMuteRefCount(0),
5637 mBeaconPlayingRefCount(0),
Eric Laurent9459fb02015-08-12 18:36:32 -07005638 mBeaconMuted(false),
Andy Hung2ddee192015-12-18 17:34:44 -08005639 mTtsOutputAvailable(false),
Eric Laurent36829f92017-04-07 19:04:42 -07005640 mMasterMono(false),
Eric Laurent4eb58f12018-12-07 16:41:02 -08005641 mMusicEffectOutput(AUDIO_IO_HANDLE_NONE)
Eric Laurente552edb2014-03-10 17:42:56 -07005642{
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005643}
François Gaffied1ab2bd2015-12-02 18:20:06 +01005644
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005645status_t AudioPolicyManager::initialize() {
Mikhail Naganovabb04782023-05-02 13:56:01 -07005646 if (mEngine == nullptr) {
5647 return NO_INIT;
François Gaffie2110e042015-03-24 08:41:51 +01005648 }
5649 mEngine->setObserver(this);
5650 status_t status = mEngine->initCheck();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005651 if (status != NO_ERROR) {
5652 LOG_FATAL("Policy engine not initialized(err=%d)", status);
5653 return status;
5654 }
François Gaffie2110e042015-03-24 08:41:51 +01005655
jiabin76e829d2023-04-04 21:02:36 +00005656 // The actual device selection cache will be updated when calling `updateDevicesAndOutputs`
5657 // at the end of this function.
5658 mEngine->initializeDeviceSelectionCache();
Eric Laurent1d69c872021-01-11 18:53:01 +01005659 mCommunnicationStrategy = mEngine->getProductStrategyForAttributes(
5660 mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL));
5661
Mikhail Naganovb0fbc1b2023-04-28 13:06:32 -07005662 // after parsing the config, mConfig contain all known devices;
Eric Laurente552edb2014-03-10 17:42:56 -07005663 // open all output streams needed to access attached devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07005664 onNewAudioModulesAvailableInt(nullptr /*newDevices*/);
François Gaffie11d30102018-11-02 16:09:09 +01005665
Eric Laurent3a4311c2014-03-17 12:00:47 -07005666 // make sure default device is reachable
Mikhail Naganovb0fbc1b2023-04-28 13:06:32 -07005667 if (const auto defaultOutputDevice = mConfig->getDefaultOutputDevice();
5668 defaultOutputDevice == nullptr ||
5669 !mAvailableOutputDevices.contains(defaultOutputDevice)) {
5670 ALOGE_IF(defaultOutputDevice != nullptr, "Default device %s is unreachable",
5671 defaultOutputDevice->toString().c_str());
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005672 status = NO_INIT;
Eric Laurent3a4311c2014-03-17 12:00:47 -07005673 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02005674 ALOGW_IF(mPrimaryOutput == nullptr, "The policy configuration does not declare a primary output");
Eric Laurente552edb2014-03-10 17:42:56 -07005675
Tomoharu Kasahara71c90912018-10-31 09:10:12 +09005676 // Silence ALOGV statements
5677 property_set("log.tag." LOG_TAG, "D");
5678
Eric Laurente552edb2014-03-10 17:42:56 -07005679 updateDevicesAndOutputs();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005680 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07005681}
5682
Eric Laurente0720872014-03-11 09:30:41 -07005683AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07005684{
Eric Laurente552edb2014-03-10 17:42:56 -07005685 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08005686 mOutputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07005687 }
5688 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08005689 mInputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07005690 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07005691 mAvailableOutputDevices.clear();
5692 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07005693 mOutputs.clear();
5694 mInputs.clear();
5695 mHwModules.clear();
Mikhail Naganov100f0122018-11-29 11:22:16 -08005696 mManualSurroundFormats.clear();
Mikhail Naganovb0fbc1b2023-04-28 13:06:32 -07005697 mConfig.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07005698}
5699
Eric Laurente0720872014-03-11 09:30:41 -07005700status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07005701{
Eric Laurent87ffa392015-05-22 10:32:38 -07005702 return hasPrimaryOutput() ? NO_ERROR : NO_INIT;
Eric Laurente552edb2014-03-10 17:42:56 -07005703}
5704
Eric Laurente552edb2014-03-10 17:42:56 -07005705// ---
5706
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005707void AudioPolicyManager::onNewAudioModulesAvailable()
5708{
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07005709 DeviceVector newDevices;
5710 onNewAudioModulesAvailableInt(&newDevices);
5711 if (!newDevices.empty()) {
5712 nextAudioPortGeneration();
5713 mpClientInterface->onAudioPortListUpdate();
5714 }
5715}
5716
5717void AudioPolicyManager::onNewAudioModulesAvailableInt(DeviceVector *newDevices)
5718{
Mikhail Naganovb0fbc1b2023-04-28 13:06:32 -07005719 for (const auto& hwModule : mConfig->getHwModules()) {
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005720 if (std::find(mHwModules.begin(), mHwModules.end(), hwModule) != mHwModules.end()) {
5721 continue;
5722 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005723 if (hwModule->getHandle() == AUDIO_MODULE_HANDLE_NONE) {
Mikhail Naganov1fba38c2023-05-03 17:45:36 -07005724 if (audio_module_handle_t handle = mpClientInterface->loadHwModule(hwModule->getName());
5725 handle != AUDIO_MODULE_HANDLE_NONE) {
5726 hwModule->setHandle(handle);
5727 } else {
5728 ALOGW("could not load HW module %s", hwModule->getName());
5729 continue;
5730 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005731 }
5732 mHwModules.push_back(hwModule);
Dean Wheatley12a87132021-04-16 10:08:49 +10005733 // open all output streams needed to access attached devices.
5734 // direct outputs are closed immediately after checking the availability of attached devices
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005735 // This also validates mAvailableOutputDevices list
5736 for (const auto& outProfile : hwModule->getOutputProfiles()) {
5737 if (!outProfile->canOpenNewIo()) {
5738 ALOGE("Invalid Output profile max open count %u for profile %s",
5739 outProfile->maxOpenCount, outProfile->getTagName().c_str());
5740 continue;
5741 }
5742 if (!outProfile->hasSupportedDevices()) {
5743 ALOGW("Output profile contains no device on module %s", hwModule->getName());
5744 continue;
5745 }
Carter Hsu1a3364a2022-01-21 15:32:56 +08005746 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_TTS) != 0 ||
5747 (outProfile->getFlags() & AUDIO_OUTPUT_FLAG_ULTRASOUND) != 0) {
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005748 mTtsOutputAvailable = true;
5749 }
5750
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005751 const DeviceVector &supportedDevices = outProfile->getSupportedDevices();
Mikhail Naganovb0fbc1b2023-04-28 13:06:32 -07005752 DeviceVector availProfileDevices = supportedDevices.filter(mConfig->getOutputDevices());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005753 sp<DeviceDescriptor> supportedDevice = 0;
Mikhail Naganovb0fbc1b2023-04-28 13:06:32 -07005754 if (supportedDevices.contains(mConfig->getDefaultOutputDevice())) {
5755 supportedDevice = mConfig->getDefaultOutputDevice();
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005756 } else {
5757 // choose first device present in profile's SupportedDevices also part of
5758 // mAvailableOutputDevices.
5759 if (availProfileDevices.isEmpty()) {
5760 continue;
5761 }
5762 supportedDevice = availProfileDevices.itemAt(0);
5763 }
Mikhail Naganovb0fbc1b2023-04-28 13:06:32 -07005764 if (!mConfig->getOutputDevices().contains(supportedDevice)) {
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005765 continue;
5766 }
5767 sp<SwAudioOutputDescriptor> outputDesc = new SwAudioOutputDescriptor(outProfile,
5768 mpClientInterface);
5769 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentf1f22e72021-07-13 14:04:14 +02005770 status_t status = outputDesc->open(nullptr /* halConfig */, nullptr /* mixerConfig */,
5771 DeviceVector(supportedDevice),
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005772 AUDIO_STREAM_DEFAULT,
5773 AUDIO_OUTPUT_FLAG_NONE, &output);
5774 if (status != NO_ERROR) {
5775 ALOGW("Cannot open output stream for devices %s on hw module %s",
5776 supportedDevice->toString().c_str(), hwModule->getName());
5777 continue;
5778 }
5779 for (const auto &device : availProfileDevices) {
5780 // give a valid ID to an attached device once confirmed it is reachable
5781 if (!device->isAttached()) {
5782 device->attach(hwModule);
5783 mAvailableOutputDevices.add(device);
jiabin1c4794b2020-05-05 10:08:05 -07005784 device->setEncapsulationInfoFromHal(mpClientInterface);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07005785 if (newDevices) newDevices->add(device);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005786 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
5787 }
5788 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02005789 if (mPrimaryOutput == nullptr &&
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005790 outProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
5791 mPrimaryOutput = outputDesc;
5792 }
Eric Laurent39095982021-08-24 18:29:27 +02005793 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
Eric Laurentc529cf62020-04-17 18:19:10 -07005794 outputDesc->close();
5795 } else {
5796 addOutput(output, outputDesc);
5797 setOutputDevices(outputDesc,
5798 DeviceVector(supportedDevice),
5799 true,
5800 0,
5801 NULL);
5802 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005803 }
5804 // open input streams needed to access attached devices to validate
5805 // mAvailableInputDevices list
5806 for (const auto& inProfile : hwModule->getInputProfiles()) {
5807 if (!inProfile->canOpenNewIo()) {
5808 ALOGE("Invalid Input profile max open count %u for profile %s",
5809 inProfile->maxOpenCount, inProfile->getTagName().c_str());
5810 continue;
5811 }
5812 if (!inProfile->hasSupportedDevices()) {
5813 ALOGW("Input profile contains no device on module %s", hwModule->getName());
5814 continue;
5815 }
5816 // chose first device present in profile's SupportedDevices also part of
5817 // available input devices
5818 const DeviceVector &supportedDevices = inProfile->getSupportedDevices();
Mikhail Naganovb0fbc1b2023-04-28 13:06:32 -07005819 DeviceVector availProfileDevices = supportedDevices.filter(mConfig->getInputDevices());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005820 if (availProfileDevices.isEmpty()) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01005821 ALOGV("%s: Input device list is empty! for profile %s",
5822 __func__, inProfile->getTagName().c_str());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005823 continue;
5824 }
5825 sp<AudioInputDescriptor> inputDesc =
5826 new AudioInputDescriptor(inProfile, mpClientInterface);
5827
5828 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
5829 status_t status = inputDesc->open(nullptr,
5830 availProfileDevices.itemAt(0),
5831 AUDIO_SOURCE_MIC,
5832 AUDIO_INPUT_FLAG_NONE,
5833 &input);
5834 if (status != NO_ERROR) {
5835 ALOGW("Cannot open input stream for device %s on hw module %s",
5836 availProfileDevices.toString().c_str(),
5837 hwModule->getName());
5838 continue;
5839 }
5840 for (const auto &device : availProfileDevices) {
5841 // give a valid ID to an attached device once confirmed it is reachable
5842 if (!device->isAttached()) {
5843 device->attach(hwModule);
5844 device->importAudioPortAndPickAudioProfile(inProfile, true);
5845 mAvailableInputDevices.add(device);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07005846 if (newDevices) newDevices->add(device);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005847 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
5848 }
5849 }
5850 inputDesc->close();
5851 }
5852 }
Eric Laurente191d1b2022-04-15 11:59:25 +02005853
5854 // Check if spatializer outputs can be closed until used.
5855 // mOutputs vector never contains duplicated outputs at this point.
5856 std::vector<audio_io_handle_t> outputsClosed;
5857 for (size_t i = 0; i < mOutputs.size(); i++) {
5858 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
5859 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0
5860 && !isOutputOnlyAvailableRouteToSomeDevice(desc)) {
5861 outputsClosed.push_back(desc->mIoHandle);
5862 desc->close();
5863 }
5864 }
5865 for (auto output : outputsClosed) {
5866 removeOutput(output);
5867 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005868}
5869
Eric Laurent98e38192018-02-15 18:31:53 -08005870void AudioPolicyManager::addOutput(audio_io_handle_t output,
5871 const sp<SwAudioOutputDescriptor>& outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07005872{
Eric Laurent1c333e22014-05-20 10:48:17 -07005873 mOutputs.add(output, outputDesc);
jiabin9a3361e2019-10-01 09:38:30 -07005874 applyStreamVolumes(outputDesc, DeviceTypeSet(), 0 /* delayMs */, true /* force */);
Andy Hung2ddee192015-12-18 17:34:44 -08005875 updateMono(output); // update mono status when adding to output list
Eric Laurent36829f92017-04-07 19:04:42 -07005876 selectOutputForMusicEffects();
Eric Laurent6a94d692014-05-20 11:18:06 -07005877 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07005878}
5879
François Gaffie53615e22015-03-19 09:24:12 +01005880void AudioPolicyManager::removeOutput(audio_io_handle_t output)
5881{
Francois Gaffiebce7cd42020-10-14 16:13:20 +02005882 if (mPrimaryOutput != 0 && mPrimaryOutput == mOutputs.valueFor(output)) {
5883 ALOGV("%s: removing primary output", __func__);
5884 mPrimaryOutput = nullptr;
5885 }
François Gaffie53615e22015-03-19 09:24:12 +01005886 mOutputs.removeItem(output);
Eric Laurent36829f92017-04-07 19:04:42 -07005887 selectOutputForMusicEffects();
François Gaffie53615e22015-03-19 09:24:12 +01005888}
5889
Eric Laurent98e38192018-02-15 18:31:53 -08005890void AudioPolicyManager::addInput(audio_io_handle_t input,
5891 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07005892{
Eric Laurent1c333e22014-05-20 10:48:17 -07005893 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07005894 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07005895}
Eric Laurente552edb2014-03-10 17:42:56 -07005896
François Gaffie11d30102018-11-02 16:09:09 +01005897status_t AudioPolicyManager::checkOutputsForDevice(const sp<DeviceDescriptor>& device,
François Gaffie53615e22015-03-19 09:24:12 +01005898 audio_policy_dev_state_t state,
François Gaffie11d30102018-11-02 16:09:09 +01005899 SortedVector<audio_io_handle_t>& outputs)
Eric Laurente552edb2014-03-10 17:42:56 -07005900{
François Gaffie11d30102018-11-02 16:09:09 +01005901 audio_devices_t deviceType = device->type();
jiabince9f20e2019-09-12 16:29:15 -07005902 const String8 &address = String8(device->address().c_str());
Eric Laurentc75307b2015-03-17 15:29:32 -07005903 sp<SwAudioOutputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07005904
François Gaffie11d30102018-11-02 16:09:09 +01005905 if (audio_device_is_digital(deviceType)) {
Eric Laurentcc750d32015-06-25 11:48:20 -07005906 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01005907 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07005908 }
Eric Laurente552edb2014-03-10 17:42:56 -07005909
Eric Laurent3b73df72014-03-11 09:06:29 -07005910 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
jiabinb4fed192020-09-22 14:45:40 -07005911 // first call getAudioPort to get the supported attributes from the HAL
5912 struct audio_port_v7 port = {};
5913 device->toAudioPort(&port);
5914 status_t status = mpClientInterface->getAudioPort(&port);
5915 if (status == NO_ERROR) {
5916 device->importAudioPort(port);
5917 }
5918
5919 // then list already open outputs that can be routed to this device
Eric Laurente552edb2014-03-10 17:42:56 -07005920 for (size_t i = 0; i < mOutputs.size(); i++) {
5921 desc = mOutputs.valueAt(i);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005922 if (!desc->isDuplicated() && desc->supportsDevice(device)
jiabin9a3361e2019-10-01 09:38:30 -07005923 && desc->devicesSupportEncodedFormats({deviceType})) {
François Gaffie11d30102018-11-02 16:09:09 +01005924 ALOGV("checkOutputsForDevice(): adding opened output %d on device %s",
5925 mOutputs.keyAt(i), device->toString().c_str());
5926 outputs.add(mOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07005927 }
5928 }
5929 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07005930 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08005931 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005932 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
5933 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
François Gaffie11d30102018-11-02 16:09:09 +01005934 if (profile->supportsDevice(device)) {
5935 profiles.add(profile);
5936 ALOGV("checkOutputsForDevice(): adding profile %zu from module %s",
5937 j, hwModule->getName());
Eric Laurente552edb2014-03-10 17:42:56 -07005938 }
5939 }
5940 }
5941
Eric Laurent7b279bb2015-12-14 10:18:23 -08005942 ALOGV(" found %zu profiles, %zu outputs", profiles.size(), outputs.size());
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005943
Eric Laurente552edb2014-03-10 17:42:56 -07005944 if (profiles.isEmpty() && outputs.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01005945 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07005946 return BAD_VALUE;
5947 }
5948
5949 // open outputs for matching profiles if needed. Direct outputs are also opened to
5950 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
5951 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07005952 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07005953
5954 // nothing to do if one output is already opened for this profile
5955 size_t j;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005956 for (j = 0; j < outputs.size(); j++) {
5957 desc = mOutputs.valueFor(outputs.itemAt(j));
Eric Laurente552edb2014-03-10 17:42:56 -07005958 if (!desc->isDuplicated() && desc->mProfile == profile) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07005959 // matching profile: save the sample rates, format and channel masks supported
5960 // by the profile in our device descriptor
François Gaffie11d30102018-11-02 16:09:09 +01005961 if (audio_device_is_digital(deviceType)) {
jiabin4ef93452019-09-10 14:29:54 -07005962 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07005963 }
Eric Laurente552edb2014-03-10 17:42:56 -07005964 break;
5965 }
5966 }
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005967 if (j != outputs.size()) {
Eric Laurente552edb2014-03-10 17:42:56 -07005968 continue;
5969 }
5970
Eric Laurent3974e3b2017-12-07 17:58:43 -08005971 if (!profile->canOpenNewIo()) {
5972 ALOGW("Max Output number %u already opened for this profile %s",
5973 profile->maxOpenCount, profile->getTagName().c_str());
5974 continue;
5975 }
5976
Eric Laurent83efe1c2017-07-09 16:51:08 -07005977 ALOGV("opening output for device %08x with params %s profile %p name %s",
jiabin5740f082019-08-19 15:08:30 -07005978 deviceType, address.string(), profile.get(), profile->getName().c_str());
jiabinbce0c1d2020-10-05 11:20:18 -07005979 desc = openOutputWithProfileAndDevice(profile, DeviceVector(device));
5980 audio_io_handle_t output = desc == nullptr ? AUDIO_IO_HANDLE_NONE : desc->mIoHandle;
Eric Laurentcf2c0212014-07-25 16:20:43 -07005981 if (output == AUDIO_IO_HANDLE_NONE) {
François Gaffie11d30102018-11-02 16:09:09 +01005982 ALOGW("checkOutputsForDevice() could not open output for device %x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07005983 profiles.removeAt(profile_index);
5984 profile_index--;
5985 } else {
5986 outputs.add(output);
Paul McLean9080a4c2015-06-18 08:24:02 -07005987 // Load digital format info only for digital devices
François Gaffie11d30102018-11-02 16:09:09 +01005988 if (audio_device_is_digital(deviceType)) {
jiabinbce0c1d2020-10-05 11:20:18 -07005989 // TODO: when getAudioPort is ready, it may not be needed to import the audio
5990 // port but just pick audio profile
jiabin4ef93452019-09-10 14:29:54 -07005991 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07005992 }
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07005993
François Gaffie11d30102018-11-02 16:09:09 +01005994 if (device_distinguishes_on_address(deviceType)) {
5995 ALOGV("checkOutputsForDevice(): setOutputDevices %s",
5996 device->toString().c_str());
5997 setOutputDevices(desc, DeviceVector(device), true/*force*/, 0/*delay*/,
5998 NULL/*patch handle*/);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005999 }
Eric Laurente552edb2014-03-10 17:42:56 -07006000 ALOGV("checkOutputsForDevice(): adding output %d", output);
6001 }
6002 }
6003
6004 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006005 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07006006 return BAD_VALUE;
6007 }
Eric Laurentd4692962014-05-05 18:13:44 -07006008 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07006009 // check if one opened output is not needed any more after disconnecting one device
6010 for (size_t i = 0; i < mOutputs.size(); i++) {
6011 desc = mOutputs.valueAt(i);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006012 if (!desc->isDuplicated()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08006013 // exact match on device
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006014 if (device_distinguishes_on_address(deviceType) && desc->supportsDevice(device)
Francois Gaffiec7d4c222021-12-02 11:12:52 +01006015 && desc->containsSingleDeviceSupportingEncodedFormats(device)) {
François Gaffie11d30102018-11-02 16:09:09 +01006016 outputs.add(mOutputs.keyAt(i));
Francois Gaffie716e1432019-01-14 16:58:59 +01006017 } else if (!mAvailableOutputDevices.containsAtLeastOne(desc->supportedDevices())) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006018 ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
6019 mOutputs.keyAt(i));
6020 outputs.add(mOutputs.keyAt(i));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006021 }
Eric Laurente552edb2014-03-10 17:42:56 -07006022 }
6023 }
Eric Laurentd4692962014-05-05 18:13:44 -07006024 // Clear any profiles associated with the disconnected device.
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006025 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006026 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
6027 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
jiabinbce0c1d2020-10-05 11:20:18 -07006028 if (!profile->supportsDevice(device)) {
6029 continue;
6030 }
6031 ALOGV("checkOutputsForDevice(): "
6032 "clearing direct output profile %zu on module %s",
6033 j, hwModule->getName());
6034 profile->clearAudioProfiles();
6035 if (!profile->hasDynamicAudioProfile()) {
6036 continue;
6037 }
6038 // When a device is disconnected, if there is an IOProfile that contains dynamic
6039 // profiles and supports the disconnected device, call getAudioPort to repopulate
6040 // the capabilities of the devices that is supported by the IOProfile.
6041 for (const auto& supportedDevice : profile->getSupportedDevices()) {
6042 if (supportedDevice == device ||
6043 !mAvailableOutputDevices.contains(supportedDevice)) {
6044 continue;
6045 }
6046 struct audio_port_v7 port;
6047 supportedDevice->toAudioPort(&port);
6048 status_t status = mpClientInterface->getAudioPort(&port);
6049 if (status == NO_ERROR) {
6050 supportedDevice->importAudioPort(port);
6051 }
Eric Laurente552edb2014-03-10 17:42:56 -07006052 }
6053 }
6054 }
6055 }
6056 return NO_ERROR;
6057}
6058
François Gaffie11d30102018-11-02 16:09:09 +01006059status_t AudioPolicyManager::checkInputsForDevice(const sp<DeviceDescriptor>& device,
Eric Laurent0dd51852019-04-19 18:18:58 -07006060 audio_policy_dev_state_t state)
Eric Laurentd4692962014-05-05 18:13:44 -07006061{
Eric Laurent1f2f2232014-06-02 12:01:23 -07006062 sp<AudioInputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07006063
François Gaffie11d30102018-11-02 16:09:09 +01006064 if (audio_device_is_digital(device->type())) {
Eric Laurentcc750d32015-06-25 11:48:20 -07006065 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01006066 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07006067 }
6068
Eric Laurentd4692962014-05-05 18:13:44 -07006069 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
jiabinbf5f4262023-04-12 21:48:34 +00006070 // first call getAudioPort to get the supported attributes from the HAL
6071 struct audio_port_v7 port = {};
6072 device->toAudioPort(&port);
6073 status_t status = mpClientInterface->getAudioPort(&port);
6074 if (status == NO_ERROR) {
6075 device->importAudioPort(port);
6076 }
6077
Eric Laurent0dd51852019-04-19 18:18:58 -07006078 // look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07006079 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006080 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07006081 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006082 profile_index < hwModule->getInputProfiles().size();
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006083 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006084 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Eric Laurent275e8e92014-11-30 15:14:47 -08006085
François Gaffie11d30102018-11-02 16:09:09 +01006086 if (profile->supportsDevice(device)) {
6087 profiles.add(profile);
6088 ALOGV("checkInputsForDevice(): adding profile %zu from module %s",
6089 profile_index, hwModule->getName());
Eric Laurentd4692962014-05-05 18:13:44 -07006090 }
6091 }
6092 }
6093
Eric Laurent0dd51852019-04-19 18:18:58 -07006094 if (profiles.isEmpty()) {
6095 ALOGW("%s: No input profile available for device %s",
6096 __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07006097 return BAD_VALUE;
6098 }
6099
6100 // open inputs for matching profiles if needed. Direct inputs are also opened to
6101 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
6102 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
6103
Eric Laurent1c333e22014-05-20 10:48:17 -07006104 sp<IOProfile> profile = profiles[profile_index];
Eric Laurent3974e3b2017-12-07 17:58:43 -08006105
Eric Laurentd4692962014-05-05 18:13:44 -07006106 // nothing to do if one input is already opened for this profile
6107 size_t input_index;
6108 for (input_index = 0; input_index < mInputs.size(); input_index++) {
6109 desc = mInputs.valueAt(input_index);
6110 if (desc->mProfile == profile) {
François Gaffie11d30102018-11-02 16:09:09 +01006111 if (audio_device_is_digital(device->type())) {
jiabin4ef93452019-09-10 14:29:54 -07006112 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006113 }
Eric Laurentd4692962014-05-05 18:13:44 -07006114 break;
6115 }
6116 }
6117 if (input_index != mInputs.size()) {
6118 continue;
6119 }
6120
Eric Laurent3974e3b2017-12-07 17:58:43 -08006121 if (!profile->canOpenNewIo()) {
6122 ALOGW("Max Input number %u already opened for this profile %s",
6123 profile->maxOpenCount, profile->getTagName().c_str());
6124 continue;
6125 }
6126
Eric Laurentfe231122017-11-17 17:48:06 -08006127 desc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentcf2c0212014-07-25 16:20:43 -07006128 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
jiabinbf5f4262023-04-12 21:48:34 +00006129 status = desc->open(nullptr, device, AUDIO_SOURCE_MIC, AUDIO_INPUT_FLAG_NONE, &input);
Eric Laurentd4692962014-05-05 18:13:44 -07006130
Eric Laurentcf2c0212014-07-25 16:20:43 -07006131 if (status == NO_ERROR) {
jiabince9f20e2019-09-12 16:29:15 -07006132 const String8& address = String8(device->address().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07006133 if (!address.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006134 char *param = audio_device_address_to_parameter(device->type(), address);
Eric Laurentcf2c0212014-07-25 16:20:43 -07006135 mpClientInterface->setParameters(input, String8(param));
6136 free(param);
Eric Laurentd4692962014-05-05 18:13:44 -07006137 }
François Gaffie11d30102018-11-02 16:09:09 +01006138 updateAudioProfiles(device, input, profile->getAudioProfiles());
François Gaffie112b0af2015-11-19 16:13:25 +01006139 if (!profile->hasValidAudioProfile()) {
Eric Laurentd4692962014-05-05 18:13:44 -07006140 ALOGW("checkInputsForDevice() direct input missing param");
Eric Laurentfe231122017-11-17 17:48:06 -08006141 desc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07006142 input = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07006143 }
6144
Eric Laurent0dd51852019-04-19 18:18:58 -07006145 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07006146 addInput(input, desc);
6147 }
6148 } // endif input != 0
6149
Eric Laurentcf2c0212014-07-25 16:20:43 -07006150 if (input == AUDIO_IO_HANDLE_NONE) {
Pattydd807582021-11-04 21:01:03 +08006151 ALOGW("%s could not open input for device %s", __func__,
François Gaffie11d30102018-11-02 16:09:09 +01006152 device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07006153 profiles.removeAt(profile_index);
6154 profile_index--;
6155 } else {
François Gaffie11d30102018-11-02 16:09:09 +01006156 if (audio_device_is_digital(device->type())) {
jiabin4ef93452019-09-10 14:29:54 -07006157 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006158 }
Eric Laurentd4692962014-05-05 18:13:44 -07006159 ALOGV("checkInputsForDevice(): adding input %d", input);
6160 }
6161 } // end scan profiles
6162
6163 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006164 ALOGW("%s: No input available for device %s", __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07006165 return BAD_VALUE;
6166 }
6167 } else {
6168 // Disconnect
Eric Laurentd4692962014-05-05 18:13:44 -07006169 // Clear any profiles associated with the disconnected device.
Mikhail Naganovd4120142017-12-06 15:49:22 -08006170 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07006171 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006172 profile_index < hwModule->getInputProfiles().size();
Eric Laurentd4692962014-05-05 18:13:44 -07006173 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006174 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Francois Gaffie716e1432019-01-14 16:58:59 +01006175 if (profile->supportsDevice(device)) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08006176 ALOGV("checkInputsForDevice(): clearing direct input profile %zu on module %s",
6177 profile_index, hwModule->getName());
François Gaffie112b0af2015-11-19 16:13:25 +01006178 profile->clearAudioProfiles();
Eric Laurentd4692962014-05-05 18:13:44 -07006179 }
6180 }
6181 }
6182 } // end disconnect
6183
6184 return NO_ERROR;
6185}
6186
6187
Eric Laurente0720872014-03-11 09:30:41 -07006188void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07006189{
6190 ALOGV("closeOutput(%d)", output);
6191
François Gaffie1c878552018-11-22 16:53:21 +01006192 sp<SwAudioOutputDescriptor> closingOutput = mOutputs.valueFor(output);
6193 if (closingOutput == NULL) {
Eric Laurente552edb2014-03-10 17:42:56 -07006194 ALOGW("closeOutput() unknown output %d", output);
6195 return;
6196 }
Mikhail Naganov32ebca32019-03-22 15:42:52 -07006197 const bool closingOutputWasActive = closingOutput->isActive();
François Gaffie1c878552018-11-22 16:53:21 +01006198 mPolicyMixes.closeOutput(closingOutput);
Eric Laurent275e8e92014-11-30 15:14:47 -08006199
Eric Laurente552edb2014-03-10 17:42:56 -07006200 // look for duplicated outputs connected to the output being removed.
6201 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie1c878552018-11-22 16:53:21 +01006202 sp<SwAudioOutputDescriptor> dupOutput = mOutputs.valueAt(i);
6203 if (dupOutput->isDuplicated() &&
6204 (dupOutput->mOutput1 == closingOutput || dupOutput->mOutput2 == closingOutput)) {
6205 sp<SwAudioOutputDescriptor> remainingOutput =
6206 dupOutput->mOutput1 == closingOutput ? dupOutput->mOutput2 : dupOutput->mOutput1;
Eric Laurente552edb2014-03-10 17:42:56 -07006207 // As all active tracks on duplicated output will be deleted,
6208 // and as they were also referenced on the other output, the reference
6209 // count for their stream type must be adjusted accordingly on
6210 // the other output.
François Gaffie1c878552018-11-22 16:53:21 +01006211 const bool wasActive = remainingOutput->isActive();
6212 // Note: no-op on the closing output where all clients has already been set inactive
6213 dupOutput->setAllClientsInactive();
Eric Laurent733ce942017-12-07 12:18:25 -08006214 // stop() will be a no op if the output is still active but is needed in case all
6215 // active streams refcounts where cleared above
6216 if (wasActive) {
François Gaffie1c878552018-11-22 16:53:21 +01006217 remainingOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08006218 }
Eric Laurente552edb2014-03-10 17:42:56 -07006219 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
6220 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
6221
6222 mpClientInterface->closeOutput(duplicatedOutput);
François Gaffie53615e22015-03-19 09:24:12 +01006223 removeOutput(duplicatedOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07006224 }
6225 }
6226
Eric Laurent05b90f82014-08-27 15:32:29 -07006227 nextAudioPortGeneration();
6228
François Gaffie1c878552018-11-22 16:53:21 +01006229 ssize_t index = mAudioPatches.indexOfKey(closingOutput->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07006230 if (index >= 0) {
6231 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006232 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
6233 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07006234 mAudioPatches.removeItemsAt(index);
6235 mpClientInterface->onAudioPatchListUpdate();
6236 }
6237
Mikhail Naganov32ebca32019-03-22 15:42:52 -07006238 if (closingOutputWasActive) {
6239 closingOutput->stop();
6240 }
François Gaffie1c878552018-11-22 16:53:21 +01006241 closingOutput->close();
Eric Laurente552edb2014-03-10 17:42:56 -07006242
François Gaffie53615e22015-03-19 09:24:12 +01006243 removeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07006244 mPreviousOutputs = mOutputs;
Eric Laurentb4f42a92022-01-17 17:37:31 +01006245 if (closingOutput == mSpatializerOutput) {
6246 mSpatializerOutput.clear();
6247 }
Dean Wheatley3023b382018-08-09 07:42:40 +10006248
6249 // MSD patches may have been released to support a non-MSD direct output. Reset MSD patch if
6250 // no direct outputs are open.
François Gaffie11d30102018-11-02 16:09:09 +01006251 if (!getMsdAudioOutDevices().isEmpty()) {
Dean Wheatley3023b382018-08-09 07:42:40 +10006252 bool directOutputOpen = false;
6253 for (size_t i = 0; i < mOutputs.size(); i++) {
6254 if (mOutputs[i]->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
6255 directOutputOpen = true;
6256 break;
6257 }
6258 }
6259 if (!directOutputOpen) {
Michael Chan6fb34492020-12-08 15:44:49 +11006260 ALOGV("no direct outputs open, reset MSD patches");
6261 // TODO: The MSD patches to be established here may differ to current MSD patches due to
6262 // how output devices for patching are resolved. Avoid by caching and reusing the
6263 // arguments to mEngine->getOutputDevicesForAttributes() when resolving which output
6264 // devices to patch to. This may be complicated by the fact that devices may become
6265 // unavailable.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11006266 setMsdOutputPatches();
Dean Wheatley3023b382018-08-09 07:42:40 +10006267 }
6268 }
Eric Laurent05b90f82014-08-27 15:32:29 -07006269}
6270
6271void AudioPolicyManager::closeInput(audio_io_handle_t input)
6272{
6273 ALOGV("closeInput(%d)", input);
6274
6275 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
6276 if (inputDesc == NULL) {
6277 ALOGW("closeInput() unknown input %d", input);
6278 return;
6279 }
6280
Eric Laurent6a94d692014-05-20 11:18:06 -07006281 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07006282
François Gaffie11d30102018-11-02 16:09:09 +01006283 sp<DeviceDescriptor> device = inputDesc->getDevice();
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08006284 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07006285 if (index >= 0) {
6286 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006287 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
6288 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07006289 mAudioPatches.removeItemsAt(index);
6290 mpClientInterface->onAudioPatchListUpdate();
6291 }
6292
Eric Laurentfe231122017-11-17 17:48:06 -08006293 inputDesc->close();
Eric Laurent05b90f82014-08-27 15:32:29 -07006294 mInputs.removeItem(input);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07006295
François Gaffie11d30102018-11-02 16:09:09 +01006296 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
6297 if (primaryInputDevices.contains(device) &&
Haynes Mathew George1d539d92018-03-16 11:40:49 -07006298 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07006299 mpClientInterface->setSoundTriggerCaptureState(false);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07006300 }
Eric Laurente552edb2014-03-10 17:42:56 -07006301}
6302
François Gaffie11d30102018-11-02 16:09:09 +01006303SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevices(
6304 const DeviceVector &devices,
6305 const SwAudioOutputCollection& openOutputs)
Eric Laurente552edb2014-03-10 17:42:56 -07006306{
6307 SortedVector<audio_io_handle_t> outputs;
6308
François Gaffie11d30102018-11-02 16:09:09 +01006309 ALOGVV("%s() devices %s", __func__, devices.toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07006310 for (size_t i = 0; i < openOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01006311 ALOGVV("output %zu isDuplicated=%d device=%s",
Eric Laurent8c7e6da2015-04-21 17:37:00 -07006312 i, openOutputs.valueAt(i)->isDuplicated(),
François Gaffie11d30102018-11-02 16:09:09 +01006313 openOutputs.valueAt(i)->supportedDevices().toString().c_str());
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006314 if (openOutputs.valueAt(i)->supportsAllDevices(devices)
jiabin9a3361e2019-10-01 09:38:30 -07006315 && openOutputs.valueAt(i)->devicesSupportEncodedFormats(devices.types())) {
François Gaffie11d30102018-11-02 16:09:09 +01006316 ALOGVV("%s() found output %d", __func__, openOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07006317 outputs.add(openOutputs.keyAt(i));
6318 }
6319 }
6320 return outputs;
6321}
6322
Mikhail Naganov37977152018-07-11 15:54:44 -07006323void AudioPolicyManager::checkForDeviceAndOutputChanges(std::function<bool()> onOutputsChecked)
6324{
6325 // checkA2dpSuspend must run before checkOutputForAllStrategies so that A2DP
6326 // output is suspended before any tracks are moved to it
6327 checkA2dpSuspend();
6328 checkOutputForAllStrategies();
Kevin Rocard153f92d2018-12-18 18:33:28 -08006329 checkSecondaryOutputs();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11006330 if (onOutputsChecked != nullptr && onOutputsChecked()) checkA2dpSuspend();
Mikhail Naganov37977152018-07-11 15:54:44 -07006331 updateDevicesAndOutputs();
Mikhail Naganov7bd9b8d2018-11-15 02:09:03 +00006332 if (mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD) != 0) {
Michael Chan6fb34492020-12-08 15:44:49 +11006333 // TODO: The MSD patches to be established here may differ to current MSD patches due to how
6334 // output devices for patching are resolved. Nevertheless, AudioTracks affected by device
6335 // configuration changes will ultimately be rerouted correctly. We can still avoid
6336 // unnecessary rerouting by caching and reusing the arguments to
6337 // mEngine->getOutputDevicesForAttributes() when resolving which output devices to patch to.
6338 // This may be complicated by the fact that devices may become unavailable.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11006339 setMsdOutputPatches();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11006340 }
Jean-Michel Trivi9a6b9ad2020-10-22 16:46:43 -07006341 // an event that changed routing likely occurred, inform upper layers
6342 mpClientInterface->onRoutingUpdated();
Mikhail Naganov37977152018-07-11 15:54:44 -07006343}
6344
François Gaffiec005e562018-11-06 15:04:49 +01006345bool AudioPolicyManager::followsSameRouting(const audio_attributes_t &lAttr,
6346 const audio_attributes_t &rAttr) const
Eric Laurente552edb2014-03-10 17:42:56 -07006347{
François Gaffiec005e562018-11-06 15:04:49 +01006348 return mEngine->getProductStrategyForAttributes(lAttr) ==
6349 mEngine->getProductStrategyForAttributes(rAttr);
6350}
6351
Francois Gaffieff1eb522020-05-06 18:37:04 +02006352void AudioPolicyManager::checkAudioSourceForAttributes(const audio_attributes_t &attr)
6353{
6354 for (size_t i = 0; i < mAudioSources.size(); i++) {
6355 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
6356 if (sourceDesc != nullptr && followsSameRouting(attr, sourceDesc->attributes())
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02006357 && sourceDesc->getPatchHandle() == AUDIO_PATCH_HANDLE_NONE
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02006358 && !isCallRxAudioSource(sourceDesc) && !sourceDesc->isInternal()) {
Francois Gaffieff1eb522020-05-06 18:37:04 +02006359 connectAudioSource(sourceDesc);
6360 }
6361 }
6362}
6363
6364void AudioPolicyManager::clearAudioSourcesForOutput(audio_io_handle_t output)
6365{
6366 for (size_t i = 0; i < mAudioSources.size(); i++) {
6367 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
6368 if (sourceDesc != nullptr && sourceDesc->swOutput().promote() != nullptr
6369 && sourceDesc->swOutput().promote()->mIoHandle == output) {
6370 disconnectAudioSource(sourceDesc);
6371 }
6372 }
6373}
6374
François Gaffiec005e562018-11-06 15:04:49 +01006375void AudioPolicyManager::checkOutputForAttributes(const audio_attributes_t &attr)
6376{
6377 auto psId = mEngine->getProductStrategyForAttributes(attr);
6378
6379 DeviceVector oldDevices = mEngine->getOutputDevicesForAttributes(attr, 0, true /*fromCache*/);
6380 DeviceVector newDevices = mEngine->getOutputDevicesForAttributes(attr, 0, false /*fromCache*/);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07006381
François Gaffie11d30102018-11-02 16:09:09 +01006382 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevices(oldDevices, mPreviousOutputs);
6383 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevices(newDevices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07006384
Eric Laurentc209fe42020-06-05 18:11:23 -07006385 uint32_t maxLatency = 0;
Eric Laurent56ed8842022-11-15 16:04:41 +01006386 std::vector<sp<SwAudioOutputDescriptor>> invalidatedOutputs;
Eric Laurentc209fe42020-06-05 18:11:23 -07006387 // take into account dynamic audio policies related changes: if a client is now associated
6388 // to a different policy mix than at creation time, invalidate corresponding stream
Eric Laurent56ed8842022-11-15 16:04:41 +01006389 for (size_t i = 0; i < mPreviousOutputs.size(); i++) {
Eric Laurentc209fe42020-06-05 18:11:23 -07006390 const sp<SwAudioOutputDescriptor>& desc = mPreviousOutputs.valueAt(i);
6391 if (desc->isDuplicated()) {
6392 continue;
Jean-Michel Trivife472e22014-12-16 14:23:13 -08006393 }
Eric Laurentc209fe42020-06-05 18:11:23 -07006394 for (const sp<TrackClientDescriptor>& client : desc->getClientIterable()) {
6395 if (mEngine->getProductStrategyForAttributes(client->attributes()) != psId) {
6396 continue;
6397 }
6398 sp<AudioPolicyMix> primaryMix;
Dean Wheatleyd082f472022-02-04 11:10:48 +11006399 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->config(),
6400 client->uid(), client->flags(), primaryMix, nullptr);
Eric Laurentc209fe42020-06-05 18:11:23 -07006401 if (status != OK) {
6402 continue;
6403 }
yucliuf4de36d2020-09-14 14:57:56 -07006404 if (client->getPrimaryMix() != primaryMix || client->hasLostPrimaryMix()) {
Eric Laurent56ed8842022-11-15 16:04:41 +01006405 if (desc->isStrategyActive(psId) && maxLatency < desc->latency()) {
Eric Laurentc209fe42020-06-05 18:11:23 -07006406 maxLatency = desc->latency();
6407 }
Eric Laurent56ed8842022-11-15 16:04:41 +01006408 invalidatedOutputs.push_back(desc);
Eric Laurentc209fe42020-06-05 18:11:23 -07006409 }
Jean-Michel Trivife472e22014-12-16 14:23:13 -08006410 }
6411 }
6412
Eric Laurent56ed8842022-11-15 16:04:41 +01006413 if (srcOutputs != dstOutputs || !invalidatedOutputs.empty()) {
Eric Laurentac3a6902018-05-11 16:39:10 -07006414 // get maximum latency of all source outputs to determine the minimum mute time guaranteeing
6415 // audio from invalidated tracks will be rendered when unmuting
Eric Laurentac3a6902018-05-11 16:39:10 -07006416 for (audio_io_handle_t srcOut : srcOutputs) {
6417 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
Eric Laurentaa02db82019-09-05 17:31:49 -07006418 if (desc == nullptr) continue;
6419
6420 if (desc->isStrategyActive(psId) && maxLatency < desc->latency()) {
Eric Laurentac3a6902018-05-11 16:39:10 -07006421 maxLatency = desc->latency();
6422 }
Eric Laurentaa02db82019-09-05 17:31:49 -07006423
Eric Laurent56ed8842022-11-15 16:04:41 +01006424 bool invalidate = false;
Eric Laurentaa02db82019-09-05 17:31:49 -07006425 for (auto client : desc->clientsList(false /*activeOnly*/)) {
Eric Laurent78aade82019-09-13 18:55:08 -07006426 if (desc->isDuplicated() || !desc->mProfile->isDirectOutput()) {
Eric Laurentaa02db82019-09-05 17:31:49 -07006427 // a client on a non direct outputs has necessarily a linear PCM format
6428 // so we can call selectOutput() safely
6429 const audio_io_handle_t newOutput = selectOutput(dstOutputs,
6430 client->flags(),
6431 client->config().format,
6432 client->config().channel_mask,
jiabinebb6af42020-06-09 17:31:17 -07006433 client->config().sample_rate,
6434 client->session());
Eric Laurentaa02db82019-09-05 17:31:49 -07006435 if (newOutput != srcOut) {
6436 invalidate = true;
6437 break;
6438 }
6439 } else {
6440 sp<IOProfile> profile = getProfileForOutput(newDevices,
6441 client->config().sample_rate,
6442 client->config().format,
6443 client->config().channel_mask,
6444 client->flags(),
6445 true /* directOnly */);
6446 if (profile != desc->mProfile) {
6447 invalidate = true;
6448 break;
6449 }
6450 }
6451 }
Eric Laurent56ed8842022-11-15 16:04:41 +01006452 // mute strategy while moving tracks from one output to another
6453 if (invalidate) {
6454 invalidatedOutputs.push_back(desc);
6455 if (desc->isStrategyActive(psId)) {
6456 setStrategyMute(psId, true, desc);
6457 setStrategyMute(psId, false, desc, maxLatency * LATENCY_MUTE_FACTOR,
6458 newDevices.types());
6459 }
Eric Laurente552edb2014-03-10 17:42:56 -07006460 }
François Gaffiec005e562018-11-06 15:04:49 +01006461 sp<SourceClientDescriptor> source = getSourceForAttributesOnOutput(srcOut, attr);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02006462 if (source != nullptr && !isCallRxAudioSource(source) && !source->isInternal()) {
Eric Laurentd60560a2015-04-10 11:31:20 -07006463 connectAudioSource(source);
6464 }
Eric Laurente552edb2014-03-10 17:42:56 -07006465 }
6466
Eric Laurent56ed8842022-11-15 16:04:41 +01006467 ALOGV_IF(!(srcOutputs.isEmpty() || dstOutputs.isEmpty()),
6468 "%s: strategy %d, moving from output %s to output %s", __func__, psId,
6469 std::to_string(srcOutputs[0]).c_str(),
6470 std::to_string(dstOutputs[0]).c_str());
6471
François Gaffiec005e562018-11-06 15:04:49 +01006472 // Move effects associated to this stream from previous output to new output
6473 if (followsSameRouting(attr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07006474 selectOutputForMusicEffects();
Eric Laurente552edb2014-03-10 17:42:56 -07006475 }
François Gaffiec005e562018-11-06 15:04:49 +01006476 // Move tracks associated to this stream (and linked) from previous output to new output
Eric Laurent56ed8842022-11-15 16:04:41 +01006477 if (!invalidatedOutputs.empty()) {
Eric Laurentaa02db82019-09-05 17:31:49 -07006478 for (auto stream : mEngine->getStreamTypesForProductStrategy(psId)) {
6479 mpClientInterface->invalidateStream(stream);
6480 }
Eric Laurent56ed8842022-11-15 16:04:41 +01006481 for (sp<SwAudioOutputDescriptor> desc : invalidatedOutputs) {
jiabin49256852022-03-09 11:21:35 -08006482 desc->setTracksInvalidatedStatusByStrategy(psId);
6483 }
Eric Laurente552edb2014-03-10 17:42:56 -07006484 }
6485 }
6486}
6487
Eric Laurente0720872014-03-11 09:30:41 -07006488void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07006489{
François Gaffiec005e562018-11-06 15:04:49 +01006490 for (const auto &strategy : mEngine->getOrderedProductStrategies()) {
6491 auto attributes = mEngine->getAllAttributesForProductStrategy(strategy).front();
6492 checkOutputForAttributes(attributes);
Francois Gaffieff1eb522020-05-06 18:37:04 +02006493 checkAudioSourceForAttributes(attributes);
François Gaffiec005e562018-11-06 15:04:49 +01006494 }
Eric Laurente552edb2014-03-10 17:42:56 -07006495}
6496
Kevin Rocard153f92d2018-12-18 18:33:28 -08006497void AudioPolicyManager::checkSecondaryOutputs() {
6498 std::set<audio_stream_type_t> streamsToInvalidate;
jiabin10a03f12021-05-07 23:46:28 +00006499 TrackSecondaryOutputsMap trackSecondaryOutputs;
Kevin Rocard153f92d2018-12-18 18:33:28 -08006500 for (size_t i = 0; i < mOutputs.size(); i++) {
6501 const sp<SwAudioOutputDescriptor>& outputDescriptor = mOutputs[i];
6502 for (const sp<TrackClientDescriptor>& client : outputDescriptor->getClientIterable()) {
Eric Laurentc529cf62020-04-17 18:19:10 -07006503 sp<AudioPolicyMix> primaryMix;
6504 std::vector<sp<AudioPolicyMix>> secondaryMixes;
Dean Wheatleyd082f472022-02-04 11:10:48 +11006505 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->config(),
6506 client->uid(), client->flags(), primaryMix, &secondaryMixes);
Eric Laurentc529cf62020-04-17 18:19:10 -07006507 std::vector<sp<SwAudioOutputDescriptor>> secondaryDescs;
6508 for (auto &secondaryMix : secondaryMixes) {
6509 sp<SwAudioOutputDescriptor> outputDesc = secondaryMix->getOutput();
6510 if (outputDesc != nullptr &&
6511 outputDesc->mIoHandle != AUDIO_IO_HANDLE_NONE) {
6512 secondaryDescs.push_back(outputDesc);
6513 }
6514 }
6515
jiabin10a03f12021-05-07 23:46:28 +00006516 if (status != OK) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08006517 streamsToInvalidate.insert(client->stream());
jiabin10a03f12021-05-07 23:46:28 +00006518 } else if (!std::equal(
6519 client->getSecondaryOutputs().begin(),
6520 client->getSecondaryOutputs().end(),
6521 secondaryDescs.begin(), secondaryDescs.end())) {
jiabina5281062021-11-23 00:10:23 +00006522 if (!audio_is_linear_pcm(client->config().format)) {
6523 // If the format is not PCM, the tracks should be invalidated to get correct
6524 // behavior when the secondary output is changed.
6525 streamsToInvalidate.insert(client->stream());
6526 } else {
6527 std::vector<wp<SwAudioOutputDescriptor>> weakSecondaryDescs;
6528 std::vector<audio_io_handle_t> secondaryOutputIds;
6529 for (const auto &secondaryDesc: secondaryDescs) {
6530 secondaryOutputIds.push_back(secondaryDesc->mIoHandle);
6531 weakSecondaryDescs.push_back(secondaryDesc);
6532 }
6533 trackSecondaryOutputs.emplace(client->portId(), secondaryOutputIds);
6534 client->setSecondaryOutputs(std::move(weakSecondaryDescs));
jiabin10a03f12021-05-07 23:46:28 +00006535 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08006536 }
6537 }
6538 }
jiabin10a03f12021-05-07 23:46:28 +00006539 if (!trackSecondaryOutputs.empty()) {
6540 mpClientInterface->updateSecondaryOutputs(trackSecondaryOutputs);
6541 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08006542 for (audio_stream_type_t stream : streamsToInvalidate) {
jiabin10a03f12021-05-07 23:46:28 +00006543 ALOGD("%s Invalidate stream %d due to fail getting output for attr", __func__, stream);
Kevin Rocard153f92d2018-12-18 18:33:28 -08006544 mpClientInterface->invalidateStream(stream);
6545 }
6546}
6547
Eric Laurent2517af32020-11-25 15:31:27 +01006548bool AudioPolicyManager::isScoRequestedForComm() const {
6549 AudioDeviceTypeAddrVector devices;
6550 mEngine->getDevicesForRoleAndStrategy(mCommunnicationStrategy, DEVICE_ROLE_PREFERRED, devices);
6551 for (const auto &device : devices) {
6552 if (audio_is_bluetooth_out_sco_device(device.mType)) {
6553 return true;
6554 }
6555 }
6556 return false;
6557}
6558
Eric Laurent1a8b45f2022-04-13 16:01:47 +02006559bool AudioPolicyManager::isHearingAidUsedForComm() const {
6560 DeviceVector devices = mEngine->getOutputDevicesForStream(AUDIO_STREAM_VOICE_CALL,
6561 true /*fromCache*/);
6562 for (const auto &device : devices) {
6563 if (device->type() == AUDIO_DEVICE_OUT_HEARING_AID) {
6564 return true;
6565 }
6566 }
6567 return false;
6568}
6569
6570
Eric Laurente0720872014-03-11 09:30:41 -07006571void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07006572{
François Gaffie53615e22015-03-19 09:24:12 +01006573 audio_io_handle_t a2dpOutput = mOutputs.getA2dpOutput();
Aniket Kumar Lataa8ee9962018-01-31 20:24:23 -08006574 if (a2dpOutput == 0 || mOutputs.isA2dpOffloadedOnPrimary()) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07006575 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07006576 return;
6577 }
6578
Eric Laurent3a4311c2014-03-17 12:00:47 -07006579 bool isScoConnected =
jiabin9a3361e2019-10-01 09:38:30 -07006580 (mAvailableInputDevices.types().count(AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) != 0 ||
6581 !Intersection(mAvailableOutputDevices.types(), getAudioDeviceOutAllScoSet()).empty());
Eric Laurent2517af32020-11-25 15:31:27 +01006582 bool isScoRequested = isScoRequestedForComm();
Eric Laurentf732e072016-08-03 19:30:28 -07006583
6584 // if suspended, restore A2DP output if:
6585 // ((SCO device is NOT connected) ||
Eric Laurent2517af32020-11-25 15:31:27 +01006586 // ((SCO is not requested) &&
Eric Laurentf732e072016-08-03 19:30:28 -07006587 // (phone state is NOT in call) && (phone state is NOT ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07006588 //
Eric Laurentf732e072016-08-03 19:30:28 -07006589 // if not suspended, suspend A2DP output if:
6590 // (SCO device is connected) &&
Eric Laurent2517af32020-11-25 15:31:27 +01006591 // ((SCO is requested) ||
Eric Laurentf732e072016-08-03 19:30:28 -07006592 // ((phone state is in call) || (phone state is ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07006593 //
6594 if (mA2dpSuspended) {
Eric Laurentf732e072016-08-03 19:30:28 -07006595 if (!isScoConnected ||
Eric Laurent2517af32020-11-25 15:31:27 +01006596 (!isScoRequested &&
Eric Laurentf732e072016-08-03 19:30:28 -07006597 (mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) &&
François Gaffie2110e042015-03-24 08:41:51 +01006598 (mEngine->getPhoneState() != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07006599
6600 mpClientInterface->restoreOutput(a2dpOutput);
6601 mA2dpSuspended = false;
6602 }
6603 } else {
Eric Laurentf732e072016-08-03 19:30:28 -07006604 if (isScoConnected &&
Eric Laurent2517af32020-11-25 15:31:27 +01006605 (isScoRequested ||
Eric Laurentf732e072016-08-03 19:30:28 -07006606 (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) ||
François Gaffie2110e042015-03-24 08:41:51 +01006607 (mEngine->getPhoneState() == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07006608
6609 mpClientInterface->suspendOutput(a2dpOutput);
6610 mA2dpSuspended = true;
6611 }
6612 }
6613}
6614
François Gaffie11d30102018-11-02 16:09:09 +01006615DeviceVector AudioPolicyManager::getNewOutputDevices(const sp<SwAudioOutputDescriptor>& outputDesc,
6616 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07006617{
François Gaffie11d30102018-11-02 16:09:09 +01006618 DeviceVector devices;
6619
Jean-Michel Triviff155c62016-02-26 12:07:16 -08006620 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07006621 if (index >= 0) {
6622 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006623 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01006624 ALOGV("%s device %s forced by patch %d", __func__,
6625 outputDesc->devices().toString().c_str(), outputDesc->getPatchHandle());
6626 return outputDesc->devices();
Eric Laurent6a94d692014-05-20 11:18:06 -07006627 }
6628 }
6629
Dean Wheatley514b4312020-06-17 21:45:00 +10006630 // Do not retrieve engine device for outputs through MSD
6631 // TODO: support explicit routing requests by resetting MSD patch to engine device.
6632 if (outputDesc->devices() == getMsdAudioOutDevices()) {
6633 return outputDesc->devices();
6634 }
6635
Eric Laurent97ac8712018-07-27 18:59:02 -07006636 // Honor explicit routing requests only if no client using default routing is active on this
6637 // input: a specific app can not force routing for other apps by setting a preferred device.
6638 bool active; // unused
François Gaffie11d30102018-11-02 16:09:09 +01006639 sp<DeviceDescriptor> device =
François Gaffiec005e562018-11-06 15:04:49 +01006640 findPreferredDevice(outputDesc, PRODUCT_STRATEGY_NONE, active, mAvailableOutputDevices);
François Gaffie11d30102018-11-02 16:09:09 +01006641 if (device != nullptr) {
6642 return DeviceVector(device);
Eric Laurentf3a5a602018-05-22 18:42:55 -07006643 }
6644
François Gaffiea807ef92018-11-05 10:44:33 +01006645 // Legacy Engine cannot take care of bus devices and mix, so we need to handle the conflict
6646 // of setForceUse / Default Bus device here
6647 device = mPolicyMixes.getDeviceAndMixForOutput(outputDesc, mAvailableOutputDevices);
6648 if (device != nullptr) {
6649 return DeviceVector(device);
6650 }
6651
François Gaffiec005e562018-11-06 15:04:49 +01006652 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
6653 StreamTypeVector streams = mEngine->getStreamTypesForProductStrategy(productStrategy);
6654 auto attr = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05306655 auto hasStreamActive = [&](auto stream) {
6656 return hasStream(streams, stream) && isStreamActive(stream, 0);
6657 };
Eric Laurent484e9272018-06-07 17:29:23 -07006658
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05306659 auto doGetOutputDevicesForVoice = [&]() {
6660 return hasVoiceStream(streams) && (outputDesc == mPrimaryOutput ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01006661 outputDesc->isActive(toVolumeSource(AUDIO_STREAM_VOICE_CALL, false))) &&
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05306662 (isInCall() ||
Henrik Backlund07c654a2021-10-14 15:57:10 +02006663 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc)) &&
6664 !isStreamActive(AUDIO_STREAM_ENFORCED_AUDIBLE, 0);
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05306665 };
6666
6667 // With low-latency playing on speaker, music on WFD, when the first low-latency
6668 // output is stopped, getNewOutputDevices checks for a product strategy
6669 // from the list, as STRATEGY_SONIFICATION comes prior to STRATEGY_MEDIA.
Carter Hsucc58a6b2021-07-20 08:44:50 +00006670 // If an ALARM or ENFORCED_AUDIBLE stream is supported by the product strategy,
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05306671 // devices are returned for STRATEGY_SONIFICATION without checking whether the
6672 // stream is associated to the output descriptor.
6673 if (doGetOutputDevicesForVoice() || outputDesc->isStrategyActive(productStrategy) ||
6674 ((hasStreamActive(AUDIO_STREAM_ALARM) ||
6675 hasStreamActive(AUDIO_STREAM_ENFORCED_AUDIBLE)) &&
6676 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc))) {
François Gaffiec005e562018-11-06 15:04:49 +01006677 // Retrieval of devices for voice DL is done on primary output profile, cannot
6678 // check the route (would force modifying configuration file for this profile)
6679 devices = mEngine->getOutputDevicesForAttributes(attr, nullptr, fromCache);
6680 break;
6681 }
Eric Laurente552edb2014-03-10 17:42:56 -07006682 }
François Gaffiec005e562018-11-06 15:04:49 +01006683 ALOGV("%s selected devices %s", __func__, devices.toString().c_str());
François Gaffie11d30102018-11-02 16:09:09 +01006684 return devices;
Eric Laurent1c333e22014-05-20 10:48:17 -07006685}
6686
François Gaffie11d30102018-11-02 16:09:09 +01006687sp<DeviceDescriptor> AudioPolicyManager::getNewInputDevice(
6688 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurent1c333e22014-05-20 10:48:17 -07006689{
François Gaffie11d30102018-11-02 16:09:09 +01006690 sp<DeviceDescriptor> device;
Eric Laurent6a94d692014-05-20 11:18:06 -07006691
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08006692 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07006693 if (index >= 0) {
6694 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006695 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01006696 ALOGV("getNewInputDevice() device %s forced by patch %d",
6697 inputDesc->getDevice()->toString().c_str(), inputDesc->getPatchHandle());
6698 return inputDesc->getDevice();
Eric Laurent6a94d692014-05-20 11:18:06 -07006699 }
6700 }
6701
Eric Laurent97ac8712018-07-27 18:59:02 -07006702 // Honor explicit routing requests only if no client using default routing is active on this
6703 // input: a specific app can not force routing for other apps by setting a preferred device.
6704 bool active;
François Gaffie11d30102018-11-02 16:09:09 +01006705 device = findPreferredDevice(inputDesc, AUDIO_SOURCE_DEFAULT, active, mAvailableInputDevices);
6706 if (device != nullptr) {
6707 return device;
Eric Laurent97ac8712018-07-27 18:59:02 -07006708 }
6709
Eric Laurentdc95a252018-04-12 12:46:56 -07006710 // If we are not in call and no client is active on this input, this methods returns
Andy Hungf024a9e2019-01-30 16:01:02 -08006711 // a null sp<>, causing the patch on the input stream to be released.
yuanjiahsu0735bf32021-03-18 08:12:54 +08006712 audio_attributes_t attributes;
6713 uid_t uid;
6714 sp<RecordClientDescriptor> topClient = inputDesc->getHighestPriorityClient();
6715 if (topClient != nullptr) {
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01006716 attributes = topClient->attributes();
6717 uid = topClient->uid();
yuanjiahsu0735bf32021-03-18 08:12:54 +08006718 } else {
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01006719 attributes = { .source = AUDIO_SOURCE_DEFAULT };
6720 uid = 0;
yuanjiahsu0735bf32021-03-18 08:12:54 +08006721 }
6722
Francois Gaffie716e1432019-01-14 16:58:59 +01006723 if (attributes.source == AUDIO_SOURCE_DEFAULT && isInCall()) {
6724 attributes.source = AUDIO_SOURCE_VOICE_COMMUNICATION;
Eric Laurentdc95a252018-04-12 12:46:56 -07006725 }
Francois Gaffie716e1432019-01-14 16:58:59 +01006726 if (attributes.source != AUDIO_SOURCE_DEFAULT) {
yuanjiahsu0735bf32021-03-18 08:12:54 +08006727 device = mEngine->getInputDeviceForAttributes(attributes, uid);
Eric Laurentfb66dd92016-01-28 18:32:03 -08006728 }
Eric Laurent1c333e22014-05-20 10:48:17 -07006729
Eric Laurente552edb2014-03-10 17:42:56 -07006730 return device;
6731}
6732
Eric Laurent794fde22016-03-11 09:50:45 -08006733bool AudioPolicyManager::streamsMatchForvolume(audio_stream_type_t stream1,
6734 audio_stream_type_t stream2) {
Jean-Michel Trivi99bb2f92016-11-23 15:52:07 -08006735 return (stream1 == stream2);
Eric Laurent28d09f02016-03-08 10:43:05 -08006736}
6737
Dorin Drimusf2196d82022-01-03 12:11:18 +01006738// TODO - consider MSD routes b/214971780
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08006739status_t AudioPolicyManager::getDevicesForAttributes(
Andy Hung6d23c0f2022-02-16 09:37:15 -08006740 const audio_attributes_t &attr, AudioDeviceTypeAddrVector *devices, bool forVolume) {
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08006741 if (devices == nullptr) {
6742 return BAD_VALUE;
6743 }
Andy Hung6d23c0f2022-02-16 09:37:15 -08006744
6745 // Devices are determined in the following precedence:
6746 //
6747 // 1) Devices associated with a dynamic policy matching the attributes. This is often
6748 // a remote submix from MIX_ROUTE_FLAG_LOOP_BACK.
6749 //
6750 // If no such dynamic policy then
6751 // 2) Devices containing an active client using setPreferredDevice
6752 // with same strategy as the attributes.
6753 // (from the default Engine::getOutputDevicesForAttributes() implementation).
6754 //
6755 // If no corresponding active client with setPreferredDevice then
6756 // 3) Devices associated with the strategy determined by the attributes
6757 // (from the default Engine::getOutputDevicesForAttributes() implementation).
6758 //
6759 // See related getOutputForAttrInt().
6760
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08006761 // check dynamic policies but only for primary descriptors (secondary not used for audible
6762 // audio routing, only used for duplication for playback capture)
Eric Laurentc529cf62020-04-17 18:19:10 -07006763 sp<AudioPolicyMix> policyMix;
Dean Wheatleyd082f472022-02-04 11:10:48 +11006764 status_t status = mPolicyMixes.getOutputForAttr(attr, AUDIO_CONFIG_BASE_INITIALIZER,
6765 0 /*uid unknown here*/, AUDIO_OUTPUT_FLAG_NONE, policyMix, nullptr);
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08006766 if (status != OK) {
6767 return status;
6768 }
Andy Hung6d23c0f2022-02-16 09:37:15 -08006769
6770 DeviceVector curDevices;
6771 if (policyMix != nullptr && policyMix->getOutput() != nullptr &&
6772 // For volume control, skip LOOPBACK mixes which use AUDIO_DEVICE_OUT_REMOTE_SUBMIX
6773 // as they are unaffected by device/stream volume
6774 // (per SwAudioOutputDescriptor::isFixedVolume()).
6775 (!forVolume || policyMix->mDeviceType != AUDIO_DEVICE_OUT_REMOTE_SUBMIX)
6776 ) {
6777 sp<DeviceDescriptor> deviceDesc = mAvailableOutputDevices.getDevice(
6778 policyMix->mDeviceType, policyMix->mDeviceAddress, AUDIO_FORMAT_DEFAULT);
6779 curDevices.add(deviceDesc);
6780 } else {
6781 // The default Engine::getOutputDevicesForAttributes() uses findPreferredDevice()
6782 // which selects setPreferredDevice if active. This means forVolume call
6783 // will take an active setPreferredDevice, if such exists.
6784
6785 curDevices = mEngine->getOutputDevicesForAttributes(
6786 attr, nullptr /* preferredDevice */, false /* fromCache */);
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08006787 }
Andy Hung6d23c0f2022-02-16 09:37:15 -08006788
6789 if (forVolume) {
6790 // We alias the device AUDIO_DEVICE_OUT_SPEAKER_SAFE to AUDIO_DEVICE_OUT_SPEAKER
6791 // for single volume control in AudioService (such relationship should exist if
6792 // SPEAKER_SAFE is present).
6793 //
6794 // (This is unrelated to a different device grouping as Volume::getDeviceCategory)
6795 DeviceVector speakerSafeDevices =
6796 curDevices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER_SAFE);
6797 if (!speakerSafeDevices.isEmpty()) {
6798 curDevices.merge(
6799 mAvailableOutputDevices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER));
6800 curDevices.remove(speakerSafeDevices);
6801 }
6802 }
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08006803 for (const auto& device : curDevices) {
6804 devices->push_back(device->getDeviceTypeAddr());
6805 }
6806 return NO_ERROR;
6807}
6808
Eric Laurente0720872014-03-11 09:30:41 -07006809void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07006810 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07006811 case AUDIO_STREAM_MUSIC:
François Gaffiec005e562018-11-06 15:04:49 +01006812 checkOutputForAttributes(attributes_initializer(AUDIO_USAGE_NOTIFICATION));
Eric Laurente552edb2014-03-10 17:42:56 -07006813 updateDevicesAndOutputs();
6814 break;
6815 default:
6816 break;
6817 }
6818}
6819
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006820uint32_t AudioPolicyManager::handleEventForBeacon(int event) {
Eric Laurent9459fb02015-08-12 18:36:32 -07006821
6822 // skip beacon mute management if a dedicated TTS output is available
6823 if (mTtsOutputAvailable) {
6824 return 0;
6825 }
6826
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006827 switch(event) {
6828 case STARTING_OUTPUT:
6829 mBeaconMuteRefCount++;
6830 break;
6831 case STOPPING_OUTPUT:
6832 if (mBeaconMuteRefCount > 0) {
6833 mBeaconMuteRefCount--;
6834 }
6835 break;
6836 case STARTING_BEACON:
6837 mBeaconPlayingRefCount++;
6838 break;
6839 case STOPPING_BEACON:
6840 if (mBeaconPlayingRefCount > 0) {
6841 mBeaconPlayingRefCount--;
6842 }
6843 break;
6844 }
6845
6846 if (mBeaconMuteRefCount > 0) {
6847 // any playback causes beacon to be muted
6848 return setBeaconMute(true);
6849 } else {
6850 // no other playback: unmute when beacon starts playing, mute when it stops
6851 return setBeaconMute(mBeaconPlayingRefCount == 0);
6852 }
6853}
6854
6855uint32_t AudioPolicyManager::setBeaconMute(bool mute) {
6856 ALOGV("setBeaconMute(%d) mBeaconMuteRefCount=%d mBeaconPlayingRefCount=%d",
6857 mute, mBeaconMuteRefCount, mBeaconPlayingRefCount);
6858 // keep track of muted state to avoid repeating mute/unmute operations
6859 if (mBeaconMuted != mute) {
6860 // mute/unmute AUDIO_STREAM_TTS on all outputs
6861 ALOGV("\t muting %d", mute);
6862 uint32_t maxLatency = 0;
Francois Gaffie4404ddb2021-02-04 17:03:38 +01006863 auto ttsVolumeSource = toVolumeSource(AUDIO_STREAM_TTS, false);
6864 if (ttsVolumeSource == VOLUME_SOURCE_NONE) {
6865 ALOGV("\t no tts volume source available");
6866 return 0;
6867 }
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006868 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07006869 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
jiabin9a3361e2019-10-01 09:38:30 -07006870 setVolumeSourceMute(ttsVolumeSource, mute/*on*/, desc, 0 /*delay*/, DeviceTypeSet());
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006871 const uint32_t latency = desc->latency() * 2;
Eric Laurentcdb2b352020-07-23 10:57:02 -07006872 if (desc->isActive(latency * 2) && latency > maxLatency) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006873 maxLatency = latency;
6874 }
6875 }
6876 mBeaconMuted = mute;
6877 return maxLatency;
6878 }
6879 return 0;
6880}
6881
Eric Laurente0720872014-03-11 09:30:41 -07006882void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07006883{
François Gaffiec005e562018-11-06 15:04:49 +01006884 mEngine->updateDeviceSelectionCache();
Eric Laurente552edb2014-03-10 17:42:56 -07006885 mPreviousOutputs = mOutputs;
6886}
6887
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07006888uint32_t AudioPolicyManager::checkDeviceMuteStrategies(const sp<AudioOutputDescriptor>& outputDesc,
François Gaffiec005e562018-11-06 15:04:49 +01006889 const DeviceVector &prevDevices,
Eric Laurente552edb2014-03-10 17:42:56 -07006890 uint32_t delayMs)
6891{
6892 // mute/unmute strategies using an incompatible device combination
6893 // if muting, wait for the audio in pcm buffer to be drained before proceeding
6894 // if unmuting, unmute only after the specified delay
6895 if (outputDesc->isDuplicated()) {
6896 return 0;
6897 }
6898
6899 uint32_t muteWaitMs = 0;
François Gaffiec005e562018-11-06 15:04:49 +01006900 DeviceVector devices = outputDesc->devices();
6901 bool shouldMute = outputDesc->isActive() && (devices.size() >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07006902
François Gaffiec005e562018-11-06 15:04:49 +01006903 auto productStrategies = mEngine->getOrderedProductStrategies();
6904 for (const auto &productStrategy : productStrategies) {
6905 auto attributes = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
6906 DeviceVector curDevices =
6907 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false/*fromCache*/);
6908 curDevices = curDevices.filter(outputDesc->supportedDevices());
6909 bool mute = shouldMute && curDevices.containsAtLeastOne(devices) && curDevices != devices;
Eric Laurente552edb2014-03-10 17:42:56 -07006910 bool doMute = false;
6911
François Gaffiec005e562018-11-06 15:04:49 +01006912 if (mute && !outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07006913 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01006914 outputDesc->setStrategyMutedByDevice(productStrategy, true);
6915 } else if (!mute && outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07006916 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01006917 outputDesc->setStrategyMutedByDevice(productStrategy, false);
Eric Laurente552edb2014-03-10 17:42:56 -07006918 }
Eric Laurent99401132014-05-07 19:48:15 -07006919 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07006920 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07006921 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07006922 // skip output if it does not share any device with current output
François Gaffie11d30102018-11-02 16:09:09 +01006923 if (!desc->supportedDevices().containsAtLeastOne(outputDesc->supportedDevices())) {
Eric Laurente552edb2014-03-10 17:42:56 -07006924 continue;
6925 }
François Gaffiec005e562018-11-06 15:04:49 +01006926 ALOGVV("%s() %s (curDevice %s)", __func__,
6927 mute ? "muting" : "unmuting", curDevices.toString().c_str());
6928 setStrategyMute(productStrategy, mute, desc, mute ? 0 : delayMs);
6929 if (desc->isStrategyActive(productStrategy)) {
Eric Laurent99401132014-05-07 19:48:15 -07006930 if (mute) {
6931 // FIXME: should not need to double latency if volume could be applied
6932 // immediately by the audioflinger mixer. We must account for the delay
6933 // between now and the next time the audioflinger thread for this output
6934 // will process a buffer (which corresponds to one buffer size,
6935 // usually 1/2 or 1/4 of the latency).
6936 if (muteWaitMs < desc->latency() * 2) {
6937 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07006938 }
6939 }
6940 }
6941 }
6942 }
6943 }
6944
Eric Laurent99401132014-05-07 19:48:15 -07006945 // temporary mute output if device selection changes to avoid volume bursts due to
6946 // different per device volumes
François Gaffiec005e562018-11-06 15:04:49 +01006947 if (outputDesc->isActive() && (devices != prevDevices)) {
Eric Laurentdc462862016-07-19 12:29:53 -07006948 uint32_t tempMuteWaitMs = outputDesc->latency() * 2;
Jasmine Chaf6074fe2021-08-17 13:44:31 +08006949
Eric Laurentdc462862016-07-19 12:29:53 -07006950 if (muteWaitMs < tempMuteWaitMs) {
6951 muteWaitMs = tempMuteWaitMs;
Eric Laurent99401132014-05-07 19:48:15 -07006952 }
Jasmine Chaf6074fe2021-08-17 13:44:31 +08006953
6954 // If recommended duration is defined, replace temporary mute duration to avoid
6955 // truncated notifications at beginning, which depends on duration of changing path in HAL.
6956 // Otherwise, temporary mute duration is conservatively set to 4 times the reported latency.
6957 uint32_t tempRecommendedMuteDuration = outputDesc->getRecommendedMuteDurationMs();
6958 uint32_t tempMuteDurationMs = tempRecommendedMuteDuration > 0 ?
6959 tempRecommendedMuteDuration : outputDesc->latency() * 4;
6960
François Gaffieaaac0fd2018-11-22 17:56:39 +01006961 for (const auto &activeVs : outputDesc->getActiveVolumeSources()) {
6962 // make sure that we do not start the temporary mute period too early in case of
6963 // delayed device change
6964 setVolumeSourceMute(activeVs, true, outputDesc, delayMs);
6965 setVolumeSourceMute(activeVs, false, outputDesc, delayMs + tempMuteDurationMs,
François Gaffiec005e562018-11-06 15:04:49 +01006966 devices.types());
Eric Laurent99401132014-05-07 19:48:15 -07006967 }
6968 }
6969
Eric Laurente552edb2014-03-10 17:42:56 -07006970 // wait for the PCM output buffers to empty before proceeding with the rest of the command
6971 if (muteWaitMs > delayMs) {
6972 muteWaitMs -= delayMs;
6973 usleep(muteWaitMs * 1000);
6974 return muteWaitMs;
6975 }
6976 return 0;
6977}
6978
François Gaffie11d30102018-11-02 16:09:09 +01006979uint32_t AudioPolicyManager::setOutputDevices(const sp<SwAudioOutputDescriptor>& outputDesc,
6980 const DeviceVector &devices,
6981 bool force,
6982 int delayMs,
6983 audio_patch_handle_t *patchHandle,
Francois Gaffie3523ab32021-06-22 13:24:34 +02006984 bool requiresMuteCheck, bool requiresVolumeCheck)
Eric Laurente552edb2014-03-10 17:42:56 -07006985{
François Gaffie11d30102018-11-02 16:09:09 +01006986 ALOGV("%s device %s delayMs %d", __func__, devices.toString().c_str(), delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07006987 uint32_t muteWaitMs;
6988
6989 if (outputDesc->isDuplicated()) {
François Gaffie11d30102018-11-02 16:09:09 +01006990 muteWaitMs = setOutputDevices(outputDesc->subOutput1(), devices, force, delayMs,
6991 nullptr /* patchHandle */, requiresMuteCheck);
6992 muteWaitMs += setOutputDevices(outputDesc->subOutput2(), devices, force, delayMs,
6993 nullptr /* patchHandle */, requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07006994 return muteWaitMs;
6995 }
Eric Laurente552edb2014-03-10 17:42:56 -07006996
6997 // filter devices according to output selected
Francois Gaffie716e1432019-01-14 16:58:59 +01006998 DeviceVector filteredDevices = outputDesc->filterSupportedDevices(devices);
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01006999 DeviceVector prevDevices = outputDesc->devices();
Francois Gaffie3523ab32021-06-22 13:24:34 +02007000 DeviceVector availPrevDevices = mAvailableOutputDevices.filter(prevDevices);
Eric Laurente552edb2014-03-10 17:42:56 -07007001
François Gaffie11d30102018-11-02 16:09:09 +01007002 ALOGV("setOutputDevices() prevDevice %s", prevDevices.toString().c_str());
7003
7004 if (!filteredDevices.isEmpty()) {
7005 outputDesc->setDevices(filteredDevices);
Eric Laurente552edb2014-03-10 17:42:56 -07007006 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00007007
7008 // if the outputs are not materially active, there is no need to mute.
7009 if (requiresMuteCheck) {
François Gaffiec005e562018-11-06 15:04:49 +01007010 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevices, delayMs);
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00007011 } else {
7012 ALOGV("%s: suppressing checkDeviceMuteStrategies", __func__);
7013 muteWaitMs = 0;
7014 }
Eric Laurente552edb2014-03-10 17:42:56 -07007015
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02007016 bool outputRouted = outputDesc->isRouted();
7017
Eric Laurent79ea9582020-06-11 18:49:24 -07007018 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
7019 // output profile or if new device is not supported AND previous device(s) is(are) still
7020 // available (otherwise reset device must be done on the output)
Francois Gaffie3523ab32021-06-22 13:24:34 +02007021 if (!devices.isEmpty() && filteredDevices.isEmpty() && !availPrevDevices.empty()) {
Eric Laurent79ea9582020-06-11 18:49:24 -07007022 ALOGV("%s: unsupported device %s for output", __func__, devices.toString().c_str());
7023 // restore previous device after evaluating strategy mute state
7024 outputDesc->setDevices(prevDevices);
7025 return muteWaitMs;
7026 }
7027
Eric Laurente552edb2014-03-10 17:42:56 -07007028 // Do not change the routing if:
Eric Laurentb80a2a82014-10-27 16:07:59 -07007029 // the requested device is AUDIO_DEVICE_NONE
7030 // OR the requested device is the same as current device
7031 // AND force is not specified
7032 // AND the output is connected by a valid audio patch.
François Gaffie11d30102018-11-02 16:09:09 +01007033 // Doing this check here allows the caller to call setOutputDevices() without conditions
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02007034 if ((filteredDevices.isEmpty() || filteredDevices == prevDevices) && !force && outputRouted) {
François Gaffie11d30102018-11-02 16:09:09 +01007035 ALOGV("%s setting same device %s or null device, force=%d, patch handle=%d", __func__,
7036 filteredDevices.toString().c_str(), force, outputDesc->getPatchHandle());
Francois Gaffie3523ab32021-06-22 13:24:34 +02007037 if (requiresVolumeCheck && !filteredDevices.isEmpty()) {
7038 ALOGV("%s setting same device on routed output, force apply volumes", __func__);
7039 applyStreamVolumes(outputDesc, filteredDevices.types(), delayMs, true /*force*/);
7040 }
Eric Laurente552edb2014-03-10 17:42:56 -07007041 return muteWaitMs;
7042 }
7043
François Gaffie11d30102018-11-02 16:09:09 +01007044 ALOGV("%s changing device to %s", __func__, filteredDevices.toString().c_str());
Eric Laurent1c333e22014-05-20 10:48:17 -07007045
Eric Laurente552edb2014-03-10 17:42:56 -07007046 // do the routing
Francois Gaffie3523ab32021-06-22 13:24:34 +02007047 if (filteredDevices.isEmpty() || mAvailableOutputDevices.filter(filteredDevices).empty()) {
Eric Laurentc75307b2015-03-17 15:29:32 -07007048 resetOutputDevice(outputDesc, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07007049 } else {
François Gaffie11d30102018-11-02 16:09:09 +01007050 PatchBuilder patchBuilder;
7051 patchBuilder.addSource(outputDesc);
7052 ALOG_ASSERT(filteredDevices.size() <= AUDIO_PATCH_PORTS_MAX, "Too many sink ports");
7053 for (const auto &filteredDevice : filteredDevices) {
7054 patchBuilder.addSink(filteredDevice);
Eric Laurentc40d9692016-04-13 19:14:13 -07007055 }
7056
Jasmine Cha7f82d1a2020-03-16 13:21:47 +08007057 // Add half reported latency to delayMs when muteWaitMs is null in order
7058 // to avoid disordered sequence of muting volume and changing devices.
7059 installPatch(__func__, patchHandle, outputDesc.get(), patchBuilder.patch(),
7060 muteWaitMs == 0 ? (delayMs + (outputDesc->latency() / 2)) : delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07007061 }
Eric Laurente552edb2014-03-10 17:42:56 -07007062
7063 // update stream volumes according to new device
François Gaffie11d30102018-11-02 16:09:09 +01007064 applyStreamVolumes(outputDesc, filteredDevices.types(), delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07007065
7066 return muteWaitMs;
7067}
7068
Eric Laurentc75307b2015-03-17 15:29:32 -07007069status_t AudioPolicyManager::resetOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurent6a94d692014-05-20 11:18:06 -07007070 int delayMs,
7071 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07007072{
Eric Laurent6a94d692014-05-20 11:18:06 -07007073 ssize_t index;
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02007074 if (patchHandle == nullptr && !outputDesc->isRouted()) {
7075 return INVALID_OPERATION;
7076 }
Eric Laurent6a94d692014-05-20 11:18:06 -07007077 if (patchHandle) {
7078 index = mAudioPatches.indexOfKey(*patchHandle);
7079 } else {
Jean-Michel Triviff155c62016-02-26 12:07:16 -08007080 index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007081 }
7082 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07007083 return INVALID_OPERATION;
7084 }
Eric Laurent6a94d692014-05-20 11:18:06 -07007085 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007086 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07007087 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07007088 outputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
François Gaffieafd4cea2019-11-18 15:50:22 +01007089 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007090 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07007091 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07007092 return status;
7093}
7094
7095status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
François Gaffie11d30102018-11-02 16:09:09 +01007096 const sp<DeviceDescriptor> &device,
Eric Laurent6a94d692014-05-20 11:18:06 -07007097 bool force,
7098 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07007099{
7100 status_t status = NO_ERROR;
7101
Eric Laurent1f2f2232014-06-02 12:01:23 -07007102 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
François Gaffie11d30102018-11-02 16:09:09 +01007103 if ((device != nullptr) && ((device != inputDesc->getDevice()) || force)) {
7104 inputDesc->setDevice(device);
Eric Laurent1c333e22014-05-20 10:48:17 -07007105
François Gaffie11d30102018-11-02 16:09:09 +01007106 if (mAvailableInputDevices.contains(device)) {
Mikhail Naganovdc769682018-05-04 15:34:08 -07007107 PatchBuilder patchBuilder;
7108 patchBuilder.addSink(inputDesc,
Eric Laurentdaf92cc2014-07-22 15:36:10 -07007109 // AUDIO_SOURCE_HOTWORD is for internal use only:
7110 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
Mikhail Naganovdc769682018-05-04 15:34:08 -07007111 [inputDesc](const PatchBuilder::mix_usecase_t& usecase) {
7112 auto result = usecase;
7113 if (result.source == AUDIO_SOURCE_HOTWORD && !inputDesc->isSoundTrigger()) {
7114 result.source = AUDIO_SOURCE_VOICE_RECOGNITION;
7115 }
7116 return result; }).
Eric Laurent1c333e22014-05-20 10:48:17 -07007117 //only one input device for now
François Gaffie11d30102018-11-02 16:09:09 +01007118 addSource(device);
Mikhail Naganovdc769682018-05-04 15:34:08 -07007119 status = installPatch(__func__, patchHandle, inputDesc.get(), patchBuilder.patch(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07007120 }
7121 }
7122 return status;
7123}
7124
Eric Laurent6a94d692014-05-20 11:18:06 -07007125status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
7126 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07007127{
Eric Laurent1f2f2232014-06-02 12:01:23 -07007128 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07007129 ssize_t index;
7130 if (patchHandle) {
7131 index = mAudioPatches.indexOfKey(*patchHandle);
7132 } else {
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08007133 index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007134 }
7135 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07007136 return INVALID_OPERATION;
7137 }
Eric Laurent6a94d692014-05-20 11:18:06 -07007138 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007139 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07007140 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07007141 inputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
François Gaffieafd4cea2019-11-18 15:50:22 +01007142 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007143 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07007144 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07007145 return status;
7146}
7147
François Gaffie11d30102018-11-02 16:09:09 +01007148sp<IOProfile> AudioPolicyManager::getInputProfile(const sp<DeviceDescriptor> &device,
François Gaffie53615e22015-03-19 09:24:12 +01007149 uint32_t& samplingRate,
Andy Hungf129b032015-04-07 13:45:50 -07007150 audio_format_t& format,
7151 audio_channel_mask_t& channelMask,
François Gaffie53615e22015-03-19 09:24:12 +01007152 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07007153{
7154 // Choose an input profile based on the requested capture parameters: select the first available
7155 // profile supporting all requested parameters.
Andy Hungf129b032015-04-07 13:45:50 -07007156 //
7157 // TODO: perhaps isCompatibleProfile should return a "matching" score so we can return
7158 // the best matching profile, not the first one.
Eric Laurente552edb2014-03-10 17:42:56 -07007159
Glenn Kasten730b9262018-03-29 15:01:26 -07007160 sp<IOProfile> firstInexact;
7161 uint32_t updatedSamplingRate = 0;
7162 audio_format_t updatedFormat = AUDIO_FORMAT_INVALID;
7163 audio_channel_mask_t updatedChannelMask = AUDIO_CHANNEL_INVALID;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08007164 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08007165 for (const auto& profile : hwModule->getInputProfiles()) {
Eric Laurentd4692962014-05-05 18:13:44 -07007166 // profile->log();
Glenn Kasten730b9262018-03-29 15:01:26 -07007167 //updatedFormat = format;
François Gaffie11d30102018-11-02 16:09:09 +01007168 if (profile->isCompatibleProfile(DeviceVector(device), samplingRate,
Glenn Kasten730b9262018-03-29 15:01:26 -07007169 &samplingRate /*updatedSamplingRate*/,
Andy Hungf129b032015-04-07 13:45:50 -07007170 format,
Glenn Kasten730b9262018-03-29 15:01:26 -07007171 &format, /*updatedFormat*/
Andy Hungf129b032015-04-07 13:45:50 -07007172 channelMask,
Glenn Kasten730b9262018-03-29 15:01:26 -07007173 &channelMask /*updatedChannelMask*/,
7174 // FIXME ugly cast
7175 (audio_output_flags_t) flags,
7176 true /*exactMatchRequiredForInputFlags*/)) {
Eric Laurente552edb2014-03-10 17:42:56 -07007177 return profile;
7178 }
François Gaffie11d30102018-11-02 16:09:09 +01007179 if (firstInexact == nullptr && profile->isCompatibleProfile(DeviceVector(device),
Glenn Kasten730b9262018-03-29 15:01:26 -07007180 samplingRate,
7181 &updatedSamplingRate,
7182 format,
7183 &updatedFormat,
7184 channelMask,
7185 &updatedChannelMask,
7186 // FIXME ugly cast
7187 (audio_output_flags_t) flags,
7188 false /*exactMatchRequiredForInputFlags*/)) {
7189 firstInexact = profile;
7190 }
7191
Eric Laurente552edb2014-03-10 17:42:56 -07007192 }
7193 }
Glenn Kasten730b9262018-03-29 15:01:26 -07007194 if (firstInexact != nullptr) {
7195 samplingRate = updatedSamplingRate;
7196 format = updatedFormat;
7197 channelMask = updatedChannelMask;
7198 return firstInexact;
7199 }
Eric Laurente552edb2014-03-10 17:42:56 -07007200 return NULL;
7201}
7202
François Gaffieaaac0fd2018-11-22 17:56:39 +01007203float AudioPolicyManager::computeVolume(IVolumeCurves &curves,
7204 VolumeSource volumeSource,
François Gaffied1ab2bd2015-12-02 18:20:06 +01007205 int index,
jiabin9a3361e2019-10-01 09:38:30 -07007206 const DeviceTypeSet& deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07007207{
jiabin9a3361e2019-10-01 09:38:30 -07007208 float volumeDb = curves.volIndexToDb(Volume::getDeviceCategory(deviceTypes), index);
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07007209
7210 // handle the case of accessibility active while a ringtone is playing: if the ringtone is much
7211 // louder than the accessibility prompt, the prompt cannot be heard, thus masking the touch
7212 // exploration of the dialer UI. In this situation, bring the accessibility volume closer to
7213 // the ringtone volume
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007214 const auto callVolumeSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL, false);
7215 const auto ringVolumeSrc = toVolumeSource(AUDIO_STREAM_RING, false);
7216 const auto musicVolumeSrc = toVolumeSource(AUDIO_STREAM_MUSIC, false);
7217 const auto alarmVolumeSrc = toVolumeSource(AUDIO_STREAM_ALARM, false);
7218 const auto a11yVolumeSrc = toVolumeSource(AUDIO_STREAM_ACCESSIBILITY, false);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007219
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07007220 if (volumeSource == a11yVolumeSrc
François Gaffieaaac0fd2018-11-22 17:56:39 +01007221 && (AUDIO_MODE_RINGTONE == mEngine->getPhoneState()) &&
7222 mOutputs.isActive(ringVolumeSrc, 0)) {
7223 auto &ringCurves = getVolumeCurves(AUDIO_STREAM_RING);
jiabin9a3361e2019-10-01 09:38:30 -07007224 const float ringVolumeDb = computeVolume(ringCurves, ringVolumeSrc, index, deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007225 return ringVolumeDb - 4 > volumeDb ? ringVolumeDb - 4 : volumeDb;
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07007226 }
7227
Eric Laurentdcd4ab12018-06-29 17:45:13 -07007228 // in-call: always cap volume by voice volume + some low headroom
François Gaffieaaac0fd2018-11-22 17:56:39 +01007229 if ((volumeSource != callVolumeSrc && (isInCall() ||
7230 mOutputs.isActiveLocally(callVolumeSrc))) &&
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007231 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM, false) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01007232 volumeSource == ringVolumeSrc || volumeSource == musicVolumeSrc ||
7233 volumeSource == alarmVolumeSrc ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007234 volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION, false) ||
7235 volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false) ||
7236 volumeSource == toVolumeSource(AUDIO_STREAM_DTMF, false) ||
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07007237 volumeSource == a11yVolumeSrc)) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007238 auto &voiceCurves = getVolumeCurves(callVolumeSrc);
jiabin9a3361e2019-10-01 09:38:30 -07007239 int voiceVolumeIndex = voiceCurves.getVolumeIndex(deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007240 const float maxVoiceVolDb =
jiabin9a3361e2019-10-01 09:38:30 -07007241 computeVolume(voiceCurves, callVolumeSrc, voiceVolumeIndex, deviceTypes)
Eric Laurent7731b5a2018-04-06 15:47:22 -07007242 + IN_CALL_EARPIECE_HEADROOM_DB;
Abhijith Shastry329ddab2019-04-23 11:53:26 -07007243 // FIXME: Workaround for call screening applications until a proper audio mode is defined
7244 // to support this scenario : Exempt the RING stream from the audio cap if the audio was
7245 // programmatically muted.
7246 // VOICE_CALL stream has minVolumeIndex > 0 : Users cannot set the volume of voice calls to
7247 // 0. We don't want to cap volume when the system has programmatically muted the voice call
7248 // stream. See setVolumeCurveIndex() for more information.
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07007249 bool exemptFromCapping =
7250 ((volumeSource == ringVolumeSrc) || (volumeSource == a11yVolumeSrc))
7251 && (voiceVolumeIndex == 0);
Abhijith Shastry329ddab2019-04-23 11:53:26 -07007252 ALOGV_IF(exemptFromCapping, "%s volume source %d at vol=%f not capped", __func__,
7253 volumeSource, volumeDb);
7254 if ((volumeDb > maxVoiceVolDb) && !exemptFromCapping) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007255 ALOGV("%s volume source %d at vol=%f overriden by volume group %d at vol=%f", __func__,
7256 volumeSource, volumeDb, callVolumeSrc, maxVoiceVolDb);
7257 volumeDb = maxVoiceVolDb;
Jean-Michel Trivi719a9872017-08-05 13:51:35 -07007258 }
7259 }
Eric Laurente552edb2014-03-10 17:42:56 -07007260 // if a headset is connected, apply the following rules to ring tones and notifications
7261 // to avoid sound level bursts in user's ears:
Eric Laurent6af1c1d2016-04-14 11:20:44 -07007262 // - always attenuate notifications volume by 6dB
7263 // - attenuate ring tones volume by 6dB unless music is not playing and
7264 // speaker is part of the select devices
Eric Laurente552edb2014-03-10 17:42:56 -07007265 // - if music is playing, always limit the volume to current music volume,
7266 // with a minimum threshold at -36dB so that notification is always perceived.
jiabin9a3361e2019-10-01 09:38:30 -07007267 if (!Intersection(deviceTypes,
7268 {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP, AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES,
7269 AUDIO_DEVICE_OUT_WIRED_HEADSET, AUDIO_DEVICE_OUT_WIRED_HEADPHONE,
Eric Laurentc42df452020-08-07 10:51:53 -07007270 AUDIO_DEVICE_OUT_USB_HEADSET, AUDIO_DEVICE_OUT_HEARING_AID,
7271 AUDIO_DEVICE_OUT_BLE_HEADSET}).empty() &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01007272 ((volumeSource == alarmVolumeSrc ||
7273 volumeSource == ringVolumeSrc) ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007274 (volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION, false)) ||
7275 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM, false)) ||
7276 ((volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false)) &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01007277 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) &&
7278 curves.canBeMuted()) {
7279
Eric Laurente552edb2014-03-10 17:42:56 -07007280 // when the phone is ringing we must consider that music could have been paused just before
7281 // by the music application and behave as if music was active if the last music track was
7282 // just stopped
Eric Laurent3b73df72014-03-11 09:06:29 -07007283 if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY) ||
Eric Laurente552edb2014-03-10 17:42:56 -07007284 mLimitRingtoneVolume) {
François Gaffie43c73442018-11-08 08:21:55 +01007285 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
jiabin9a3361e2019-10-01 09:38:30 -07007286 DeviceTypeSet musicDevice =
François Gaffiec005e562018-11-06 15:04:49 +01007287 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
7288 nullptr, true /*fromCache*/).types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01007289 auto &musicCurves = getVolumeCurves(AUDIO_STREAM_MUSIC);
jiabin9a3361e2019-10-01 09:38:30 -07007290 float musicVolDb = computeVolume(musicCurves,
7291 musicVolumeSrc,
7292 musicCurves.getVolumeIndex(musicDevice),
7293 musicDevice);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007294 float minVolDb = (musicVolDb > SONIFICATION_HEADSET_VOLUME_MIN_DB) ?
7295 musicVolDb : SONIFICATION_HEADSET_VOLUME_MIN_DB;
7296 if (volumeDb > minVolDb) {
7297 volumeDb = minVolDb;
7298 ALOGV("computeVolume limiting volume to %f musicVol %f", minVolDb, musicVolDb);
Eric Laurente552edb2014-03-10 17:42:56 -07007299 }
Eric Laurent7b6385c2021-05-12 17:55:36 +02007300 if (Volume::getDeviceForVolume(deviceTypes) != AUDIO_DEVICE_OUT_SPEAKER
7301 && !Intersection(deviceTypes, {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP,
7302 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES}).empty()) {
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07007303 // on A2DP, also ensure notification volume is not too low compared to media when
7304 // intended to be played
François Gaffie43c73442018-11-08 08:21:55 +01007305 if ((volumeDb > -96.0f) &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01007306 (musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB > volumeDb)) {
jiabin9a3361e2019-10-01 09:38:30 -07007307 ALOGV("%s increasing volume for volume source=%d device=%s from %f to %f",
7308 __func__, volumeSource, dumpDeviceTypes(deviceTypes).c_str(), volumeDb,
François Gaffieaaac0fd2018-11-22 17:56:39 +01007309 musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB);
7310 volumeDb = musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB;
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07007311 }
7312 }
jiabin9a3361e2019-10-01 09:38:30 -07007313 } else if ((Volume::getDeviceForVolume(deviceTypes) != AUDIO_DEVICE_OUT_SPEAKER) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01007314 (!(volumeSource == alarmVolumeSrc || volumeSource == ringVolumeSrc))) {
François Gaffie43c73442018-11-08 08:21:55 +01007315 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07007316 }
7317 }
7318
François Gaffie43c73442018-11-08 08:21:55 +01007319 return volumeDb;
Eric Laurente552edb2014-03-10 17:42:56 -07007320}
7321
Eric Laurent3839bc02018-07-10 18:33:34 -07007322int AudioPolicyManager::rescaleVolumeIndex(int srcIndex,
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01007323 VolumeSource fromVolumeSource,
7324 VolumeSource toVolumeSource)
Eric Laurent3839bc02018-07-10 18:33:34 -07007325{
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01007326 if (fromVolumeSource == toVolumeSource) {
Eric Laurent3839bc02018-07-10 18:33:34 -07007327 return srcIndex;
7328 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01007329 auto &srcCurves = getVolumeCurves(fromVolumeSource);
7330 auto &dstCurves = getVolumeCurves(toVolumeSource);
Eric Laurentf5aa58d2019-02-22 18:20:11 -08007331 float minSrc = (float)srcCurves.getVolumeIndexMin();
7332 float maxSrc = (float)srcCurves.getVolumeIndexMax();
7333 float minDst = (float)dstCurves.getVolumeIndexMin();
7334 float maxDst = (float)dstCurves.getVolumeIndexMax();
Eric Laurent3839bc02018-07-10 18:33:34 -07007335
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08007336 // preserve mute request or correct range
7337 if (srcIndex < minSrc) {
7338 if (srcIndex == 0) {
7339 return 0;
7340 }
7341 srcIndex = minSrc;
7342 } else if (srcIndex > maxSrc) {
7343 srcIndex = maxSrc;
7344 }
Eric Laurent3839bc02018-07-10 18:33:34 -07007345 return (int)(minDst + ((srcIndex - minSrc) * (maxDst - minDst)) / (maxSrc - minSrc));
7346}
7347
François Gaffieaaac0fd2018-11-22 17:56:39 +01007348status_t AudioPolicyManager::checkAndSetVolume(IVolumeCurves &curves,
7349 VolumeSource volumeSource,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08007350 int index,
7351 const sp<AudioOutputDescriptor>& outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07007352 DeviceTypeSet deviceTypes,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08007353 int delayMs,
7354 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07007355{
François Gaffieaaac0fd2018-11-22 17:56:39 +01007356 // do not change actual attributes volume if the attributes is muted
7357 if (outputDesc->isMuted(volumeSource)) {
7358 ALOGVV("%s: volume source %d muted count %d active=%d", __func__, volumeSource,
7359 outputDesc->getMuteCount(volumeSource), outputDesc->isActive(volumeSource));
Eric Laurente552edb2014-03-10 17:42:56 -07007360 return NO_ERROR;
7361 }
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007362 VolumeSource callVolSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL, false);
7363 VolumeSource btScoVolSrc = toVolumeSource(AUDIO_STREAM_BLUETOOTH_SCO, false);
7364 bool isVoiceVolSrc = (volumeSource != VOLUME_SOURCE_NONE) && (callVolSrc == volumeSource);
7365 bool isBtScoVolSrc = (volumeSource != VOLUME_SOURCE_NONE) && (btScoVolSrc == volumeSource);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007366
Eric Laurent2517af32020-11-25 15:31:27 +01007367 bool isScoRequested = isScoRequestedForComm();
Eric Laurent1a8b45f2022-04-13 16:01:47 +02007368 bool isHAUsed = isHearingAidUsedForComm();
7369
Eric Laurente552edb2014-03-10 17:42:56 -07007370 // do not change in call volume if bluetooth is connected and vice versa
François Gaffieaaac0fd2018-11-22 17:56:39 +01007371 // if sco and call follow same curves, bypass forceUseForComm
7372 if ((callVolSrc != btScoVolSrc) &&
Eric Laurent2517af32020-11-25 15:31:27 +01007373 ((isVoiceVolSrc && isScoRequested) ||
Beibeif660a512023-02-28 17:00:34 +08007374 (isBtScoVolSrc && !(isScoRequested || isHAUsed))) &&
7375 !isSingleDeviceType(deviceTypes, AUDIO_DEVICE_OUT_TELEPHONY_TX)) {
Eric Laurent2517af32020-11-25 15:31:27 +01007376 ALOGV("%s cannot set volume group %d volume when is%srequested for comm", __func__,
Eric Laurent1a8b45f2022-04-13 16:01:47 +02007377 volumeSource, isScoRequested ? " " : " not ");
Eric Laurent571ef962020-07-24 11:43:48 -07007378 // Do not return an error here as AudioService will always set both voice call
7379 // and bluetooth SCO volumes due to stream aliasing.
7380 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07007381 }
jiabin9a3361e2019-10-01 09:38:30 -07007382 if (deviceTypes.empty()) {
7383 deviceTypes = outputDesc->devices().types();
chenxin2080986da2023-07-17 11:45:21 +08007384 index = curves.getVolumeIndex(deviceTypes);
7385 ALOGD("%s if deviceTypes is change from none to device %s, need get index %d",
7386 __func__, dumpDeviceTypes(deviceTypes).c_str(), index);
Eric Laurentc75307b2015-03-17 15:29:32 -07007387 }
Eric Laurent275e8e92014-11-30 15:14:47 -08007388
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00007389 if (curves.getVolumeIndexMin() < 0 || curves.getVolumeIndexMax() < 0) {
7390 ALOGE("invalid volume index range");
7391 return BAD_VALUE;
7392 }
7393
jiabin9a3361e2019-10-01 09:38:30 -07007394 float volumeDb = computeVolume(curves, volumeSource, index, deviceTypes);
7395 if (outputDesc->isFixedVolume(deviceTypes) ||
Eric Laurent9698a4c2020-10-12 17:10:23 -07007396 // Force VoIP volume to max for bluetooth SCO device except if muted
7397 (index != 0 && (isVoiceVolSrc || isBtScoVolSrc) &&
jiabin9a3361e2019-10-01 09:38:30 -07007398 isSingleDeviceType(deviceTypes, audio_is_bluetooth_out_sco_device))) {
Eric Laurentffbc80f2015-03-18 18:30:19 -07007399 volumeDb = 0.0f;
Eric Laurent275e8e92014-11-30 15:14:47 -08007400 }
Francois Gaffie593634d2021-06-22 13:31:31 +02007401 const bool muted = (index == 0) && (volumeDb != 0.0f);
jiabin9a3361e2019-10-01 09:38:30 -07007402 outputDesc->setVolume(
Francois Gaffie593634d2021-06-22 13:31:31 +02007403 volumeDb, muted, volumeSource, curves.getStreamTypes(), deviceTypes, delayMs, force);
Eric Laurentc75307b2015-03-17 15:29:32 -07007404
Eric Laurente8f2c0f2021-08-17 11:17:19 +02007405 if (outputDesc == mPrimaryOutput && (isVoiceVolSrc || isBtScoVolSrc)) {
Eric Laurente552edb2014-03-10 17:42:56 -07007406 float voiceVolume;
Eric Laurentfad001d2019-06-11 19:17:57 -07007407 // 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 +01007408 if (isVoiceVolSrc) {
7409 voiceVolume = (float)index/(float)curves.getVolumeIndexMax();
Eric Laurente552edb2014-03-10 17:42:56 -07007410 } else {
Eric Laurentfad001d2019-06-11 19:17:57 -07007411 voiceVolume = index == 0 ? 0.0 : 1.0;
Eric Laurente552edb2014-03-10 17:42:56 -07007412 }
Eric Laurent18fba842016-03-31 14:41:26 -07007413 if (voiceVolume != mLastVoiceVolume) {
Eric Laurente552edb2014-03-10 17:42:56 -07007414 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
7415 mLastVoiceVolume = voiceVolume;
7416 }
7417 }
Eric Laurente552edb2014-03-10 17:42:56 -07007418 return NO_ERROR;
7419}
7420
Eric Laurentc75307b2015-03-17 15:29:32 -07007421void AudioPolicyManager::applyStreamVolumes(const sp<AudioOutputDescriptor>& outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07007422 const DeviceTypeSet& deviceTypes,
7423 int delayMs,
7424 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07007425{
jiabincd510522020-01-22 09:40:55 -08007426 ALOGVV("applyStreamVolumes() for device %s", dumpDeviceTypes(deviceTypes).c_str());
François Gaffieaaac0fd2018-11-22 17:56:39 +01007427 for (const auto &volumeGroup : mEngine->getVolumeGroups()) {
7428 auto &curves = getVolumeCurves(toVolumeSource(volumeGroup));
7429 checkAndSetVolume(curves, toVolumeSource(volumeGroup),
jiabin9a3361e2019-10-01 09:38:30 -07007430 curves.getVolumeIndex(deviceTypes),
7431 outputDesc, deviceTypes, delayMs, force);
Eric Laurente552edb2014-03-10 17:42:56 -07007432 }
7433}
7434
François Gaffiec005e562018-11-06 15:04:49 +01007435void AudioPolicyManager::setStrategyMute(product_strategy_t strategy,
7436 bool on,
7437 const sp<AudioOutputDescriptor>& outputDesc,
7438 int delayMs,
jiabin9a3361e2019-10-01 09:38:30 -07007439 DeviceTypeSet deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07007440{
François Gaffieaaac0fd2018-11-22 17:56:39 +01007441 std::vector<VolumeSource> sourcesToMute;
7442 for (auto attributes: mEngine->getAllAttributesForProductStrategy(strategy)) {
7443 ALOGVV("%s() attributes %s, mute %d, output ID %d", __func__,
7444 toString(attributes).c_str(), on, outputDesc->getId());
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007445 VolumeSource source = toVolumeSource(attributes, false);
7446 if ((source != VOLUME_SOURCE_NONE) &&
7447 (std::find(begin(sourcesToMute), end(sourcesToMute), source)
7448 == end(sourcesToMute))) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007449 sourcesToMute.push_back(source);
7450 }
Eric Laurente552edb2014-03-10 17:42:56 -07007451 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01007452 for (auto source : sourcesToMute) {
jiabin9a3361e2019-10-01 09:38:30 -07007453 setVolumeSourceMute(source, on, outputDesc, delayMs, deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007454 }
7455
Eric Laurente552edb2014-03-10 17:42:56 -07007456}
7457
François Gaffieaaac0fd2018-11-22 17:56:39 +01007458void AudioPolicyManager::setVolumeSourceMute(VolumeSource volumeSource,
7459 bool on,
7460 const sp<AudioOutputDescriptor>& outputDesc,
7461 int delayMs,
jiabin9a3361e2019-10-01 09:38:30 -07007462 DeviceTypeSet deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07007463{
jiabin9a3361e2019-10-01 09:38:30 -07007464 if (deviceTypes.empty()) {
7465 deviceTypes = outputDesc->devices().types();
Eric Laurente552edb2014-03-10 17:42:56 -07007466 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01007467 auto &curves = getVolumeCurves(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07007468 if (on) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007469 if (!outputDesc->isMuted(volumeSource)) {
Eric Laurentf5aa58d2019-02-22 18:20:11 -08007470 if (curves.canBeMuted() &&
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007471 (volumeSource != toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01007472 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) ==
7473 AUDIO_POLICY_FORCE_NONE))) {
jiabin9a3361e2019-10-01 09:38:30 -07007474 checkAndSetVolume(curves, volumeSource, 0, outputDesc, deviceTypes, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07007475 }
7476 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01007477 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not
7478 // ignored
7479 outputDesc->incMuteCount(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07007480 } else {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007481 if (!outputDesc->isMuted(volumeSource)) {
7482 ALOGV("%s unmuting non muted attributes!", __func__);
Eric Laurente552edb2014-03-10 17:42:56 -07007483 return;
7484 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01007485 if (outputDesc->decMuteCount(volumeSource) == 0) {
7486 checkAndSetVolume(curves, volumeSource,
jiabin9a3361e2019-10-01 09:38:30 -07007487 curves.getVolumeIndex(deviceTypes),
Eric Laurentc75307b2015-03-17 15:29:32 -07007488 outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07007489 deviceTypes,
Eric Laurente552edb2014-03-10 17:42:56 -07007490 delayMs);
7491 }
7492 }
7493}
7494
François Gaffie53615e22015-03-19 09:24:12 +01007495bool AudioPolicyManager::isValidAttributes(const audio_attributes_t *paa)
7496{
François Gaffiec005e562018-11-06 15:04:49 +01007497 // has flags that map to a stream type?
Eric Laurente83b55d2014-11-14 10:06:21 -08007498 if ((paa->flags & (AUDIO_FLAG_AUDIBILITY_ENFORCED | AUDIO_FLAG_SCO | AUDIO_FLAG_BEACON)) != 0) {
7499 return true;
7500 }
7501
7502 // has known usage?
7503 switch (paa->usage) {
7504 case AUDIO_USAGE_UNKNOWN:
7505 case AUDIO_USAGE_MEDIA:
7506 case AUDIO_USAGE_VOICE_COMMUNICATION:
7507 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
7508 case AUDIO_USAGE_ALARM:
7509 case AUDIO_USAGE_NOTIFICATION:
7510 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
7511 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
7512 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
7513 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
7514 case AUDIO_USAGE_NOTIFICATION_EVENT:
7515 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
7516 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
7517 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
7518 case AUDIO_USAGE_GAME:
Eric Laurent275e8e92014-11-30 15:14:47 -08007519 case AUDIO_USAGE_VIRTUAL_SOURCE:
Jean-Michel Trivi36867762016-12-29 12:03:28 -08007520 case AUDIO_USAGE_ASSISTANT:
Eric Laurent21777f82019-12-06 18:12:06 -08007521 case AUDIO_USAGE_CALL_ASSISTANT:
Hayden Gomes524159d2019-12-23 14:41:47 -08007522 case AUDIO_USAGE_EMERGENCY:
7523 case AUDIO_USAGE_SAFETY:
7524 case AUDIO_USAGE_VEHICLE_STATUS:
7525 case AUDIO_USAGE_ANNOUNCEMENT:
Eric Laurente83b55d2014-11-14 10:06:21 -08007526 break;
7527 default:
7528 return false;
7529 }
7530 return true;
7531}
7532
François Gaffie2110e042015-03-24 08:41:51 +01007533audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
7534{
7535 return mEngine->getForceUse(usage);
7536}
7537
Eric Laurent96d1dda2022-03-14 17:14:19 +01007538bool AudioPolicyManager::isInCall() const {
François Gaffie2110e042015-03-24 08:41:51 +01007539 return isStateInCall(mEngine->getPhoneState());
7540}
7541
Eric Laurent96d1dda2022-03-14 17:14:19 +01007542bool AudioPolicyManager::isStateInCall(int state) const {
François Gaffie2110e042015-03-24 08:41:51 +01007543 return is_state_in_call(state);
7544}
7545
Eric Laurentf9cccec2022-11-16 19:12:00 +01007546bool AudioPolicyManager::isCallAudioAccessible() const {
Eric Laurent74b71512019-11-06 17:21:57 -08007547 audio_mode_t mode = mEngine->getPhoneState();
7548 return (mode == AUDIO_MODE_IN_CALL)
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01007549 || (mode == AUDIO_MODE_CALL_SCREEN)
7550 || (mode == AUDIO_MODE_CALL_REDIRECT);
Eric Laurent74b71512019-11-06 17:21:57 -08007551}
7552
Eric Laurentf9cccec2022-11-16 19:12:00 +01007553bool AudioPolicyManager::isInCallOrScreening() const {
7554 audio_mode_t mode = mEngine->getPhoneState();
7555 return isStateInCall(mode) || mode == AUDIO_MODE_CALL_SCREEN;
7556}
7557
Eric Laurentd60560a2015-04-10 11:31:20 -07007558void AudioPolicyManager::cleanUpForDevice(const sp<DeviceDescriptor>& deviceDesc)
7559{
7560 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07007561 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02007562 if (sourceDesc->isConnected() && (sourceDesc->srcDevice()->equals(deviceDesc) ||
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02007563 sourceDesc->sinkDevice()->equals(deviceDesc))
7564 && !isCallRxAudioSource(sourceDesc)) {
Francois Gaffiea0e5c992020-09-29 16:05:07 +02007565 disconnectAudioSource(sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07007566 }
7567 }
7568
7569 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
7570 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
7571 bool release = false;
7572 for (size_t j = 0; j < patchDesc->mPatch.num_sources && !release; j++) {
7573 const struct audio_port_config *source = &patchDesc->mPatch.sources[j];
7574 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
7575 source->ext.device.type == deviceDesc->type()) {
7576 release = true;
7577 }
7578 }
Francois Gaffiea0e5c992020-09-29 16:05:07 +02007579 const char *address = deviceDesc->address().c_str();
Eric Laurentd60560a2015-04-10 11:31:20 -07007580 for (size_t j = 0; j < patchDesc->mPatch.num_sinks && !release; j++) {
7581 const struct audio_port_config *sink = &patchDesc->mPatch.sinks[j];
7582 if (sink->type == AUDIO_PORT_TYPE_DEVICE &&
Francois Gaffiea0e5c992020-09-29 16:05:07 +02007583 sink->ext.device.type == deviceDesc->type() &&
7584 (strnlen(address, AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0
7585 || strncmp(sink->ext.device.address, address,
7586 AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0)) {
Eric Laurentd60560a2015-04-10 11:31:20 -07007587 release = true;
7588 }
7589 }
7590 if (release) {
François Gaffieafd4cea2019-11-18 15:50:22 +01007591 ALOGV("%s releasing patch %u", __FUNCTION__, patchDesc->getHandle());
7592 releaseAudioPatch(patchDesc->getHandle(), patchDesc->getUid());
Eric Laurentd60560a2015-04-10 11:31:20 -07007593 }
7594 }
Francois Gaffie716e1432019-01-14 16:58:59 +01007595
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01007596 mInputs.clearSessionRoutesForDevice(deviceDesc);
7597
Francois Gaffie716e1432019-01-14 16:58:59 +01007598 mHwModules.cleanUpForDevice(deviceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07007599}
7600
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007601void AudioPolicyManager::modifySurroundFormats(
7602 const sp<DeviceDescriptor>& devDesc, FormatVector *formatsPtr) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007603 std::unordered_set<audio_format_t> enforcedSurround(
7604 devDesc->encodedFormats().begin(), devDesc->encodedFormats().end());
Mikhail Naganov100f0122018-11-29 11:22:16 -08007605 std::unordered_set<audio_format_t> allSurround; // A flat set of all known surround formats
Mikhail Naganovb0fbc1b2023-04-28 13:06:32 -07007606 for (const auto& pair : mConfig->getSurroundFormats()) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08007607 allSurround.insert(pair.first);
7608 for (const auto& subformat : pair.second) allSurround.insert(subformat);
7609 }
Phil Burk09bc4612016-02-24 15:58:15 -08007610
7611 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
7612 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Phil Burk0709b0a2016-03-31 12:54:57 -07007613 ALOGD("%s: forced use = %d", __FUNCTION__, forceUse);
Mikhail Naganov100f0122018-11-29 11:22:16 -08007614 // This is the resulting set of formats depending on the surround mode:
7615 // 'all surround' = allSurround
7616 // 'enforced surround' = enforcedSurround [may include IEC69137 which isn't raw surround fmt]
7617 // 'non-surround' = not in 'all surround' and not in 'enforced surround'
7618 // 'manual surround' = mManualSurroundFormats
7619 // AUTO: formats v 'enforced surround'
7620 // ALWAYS: formats v 'all surround' v 'enforced surround'
7621 // NEVER: formats ^ 'non-surround'
7622 // MANUAL: formats ^ ('non-surround' v 'manual surround' v (IEC69137 ^ 'enforced surround'))
Phil Burk09bc4612016-02-24 15:58:15 -08007623
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007624 std::unordered_set<audio_format_t> formatSet;
7625 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL
7626 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08007627 // formatSet is (formats ^ 'non-surround')
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007628 for (auto formatIter = formatsPtr->begin(); formatIter != formatsPtr->end(); ++formatIter) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08007629 if (allSurround.count(*formatIter) == 0 && enforcedSurround.count(*formatIter) == 0) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007630 formatSet.insert(*formatIter);
7631 }
7632 }
7633 } else {
7634 formatSet.insert(formatsPtr->begin(), formatsPtr->end());
7635 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08007636 formatsPtr->clear(); // Re-filled from the formatSet at the end.
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007637
jiabin81772902018-04-02 17:52:27 -07007638 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08007639 formatSet.insert(mManualSurroundFormats.begin(), mManualSurroundFormats.end());
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007640 // Enable IEC61937 when in MANUAL mode if it's enforced for this device.
7641 if (enforcedSurround.count(AUDIO_FORMAT_IEC61937) != 0) {
7642 formatSet.insert(AUDIO_FORMAT_IEC61937);
Phil Burk09bc4612016-02-24 15:58:15 -08007643 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08007644 } else if (forceUse != AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) { // AUTO or ALWAYS
7645 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS) {
7646 formatSet.insert(allSurround.begin(), allSurround.end());
Phil Burk07ac1142016-03-25 13:39:29 -07007647 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08007648 formatSet.insert(enforcedSurround.begin(), enforcedSurround.end());
Phil Burk09bc4612016-02-24 15:58:15 -08007649 }
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007650 for (const auto& format : formatSet) {
jiabin06e4bab2019-07-29 10:13:34 -07007651 formatsPtr->push_back(format);
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007652 }
Phil Burk0709b0a2016-03-31 12:54:57 -07007653}
7654
jiabin06e4bab2019-07-29 10:13:34 -07007655void AudioPolicyManager::modifySurroundChannelMasks(ChannelMaskSet *channelMasksPtr) {
7656 ChannelMaskSet &channelMasks = *channelMasksPtr;
Phil Burk0709b0a2016-03-31 12:54:57 -07007657 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
7658 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
7659
7660 // If NEVER, then remove support for channelMasks > stereo.
7661 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
jiabin06e4bab2019-07-29 10:13:34 -07007662 for (auto it = channelMasks.begin(); it != channelMasks.end();) {
7663 audio_channel_mask_t channelMask = *it;
Phil Burk0709b0a2016-03-31 12:54:57 -07007664 if (channelMask & ~AUDIO_CHANNEL_OUT_STEREO) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01007665 ALOGV("%s: force NEVER, so remove channelMask 0x%08x", __FUNCTION__, channelMask);
jiabin06e4bab2019-07-29 10:13:34 -07007666 it = channelMasks.erase(it);
Phil Burk0709b0a2016-03-31 12:54:57 -07007667 } else {
jiabin06e4bab2019-07-29 10:13:34 -07007668 ++it;
Phil Burk0709b0a2016-03-31 12:54:57 -07007669 }
7670 }
jiabin81772902018-04-02 17:52:27 -07007671 // If ALWAYS or MANUAL, then make sure we at least support 5.1
7672 } else if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS
7673 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Phil Burk0709b0a2016-03-31 12:54:57 -07007674 bool supports5dot1 = false;
7675 // Are there any channel masks that can be considered "surround"?
Mikhail Naganovcf84e592017-12-07 11:25:11 -08007676 for (audio_channel_mask_t channelMask : channelMasks) {
Phil Burk0709b0a2016-03-31 12:54:57 -07007677 if ((channelMask & AUDIO_CHANNEL_OUT_5POINT1) == AUDIO_CHANNEL_OUT_5POINT1) {
7678 supports5dot1 = true;
7679 break;
7680 }
7681 }
7682 // If not then add 5.1 support.
7683 if (!supports5dot1) {
jiabin06e4bab2019-07-29 10:13:34 -07007684 channelMasks.insert(AUDIO_CHANNEL_OUT_5POINT1);
Eric Laurentfecbceb2021-02-09 14:46:43 +01007685 ALOGV("%s: force MANUAL or ALWAYS, so adding channelMask for 5.1 surround", __func__);
Phil Burk0709b0a2016-03-31 12:54:57 -07007686 }
Phil Burk09bc4612016-02-24 15:58:15 -08007687 }
7688}
7689
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007690void AudioPolicyManager::updateAudioProfiles(const sp<DeviceDescriptor>& devDesc,
Phil Burk00eeb322016-03-31 12:41:00 -07007691 audio_io_handle_t ioHandle,
François Gaffie112b0af2015-11-19 16:13:25 +01007692 AudioProfileVector &profiles)
7693{
7694 String8 reply;
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007695 audio_devices_t device = devDesc->type();
Phil Burk0709b0a2016-03-31 12:54:57 -07007696
François Gaffie112b0af2015-11-19 16:13:25 +01007697 // Format MUST be checked first to update the list of AudioProfile
7698 if (profiles.hasDynamicFormat()) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07007699 reply = mpClientInterface->getParameters(
7700 ioHandle, String8(AudioParameter::keyStreamSupportedFormats));
jiabin81772902018-04-02 17:52:27 -07007701 ALOGV("%s: supported formats %d, %s", __FUNCTION__, ioHandle, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08007702 AudioParameter repliedParameters(reply);
jiabinf26596b2023-04-12 18:56:39 +00007703 FormatVector formats;
Eric Laurent62e4bc52016-02-02 18:37:28 -08007704 if (repliedParameters.get(
jiabinf26596b2023-04-12 18:56:39 +00007705 String8(AudioParameter::keyStreamSupportedFormats), reply) == NO_ERROR) {
7706 formats = formatsFromString(reply.string());
7707 } else if (devDesc->hasValidAudioProfile()) {
7708 ALOGD("%s: using the device profiles", __func__);
7709 formats = devDesc->getAudioProfiles().getSupportedFormats();
7710 } else {
7711 ALOGE("%s: failed to retrieve format, bailing out", __func__);
François Gaffie112b0af2015-11-19 16:13:25 +01007712 return;
7713 }
Kriti Dangef6be8f2020-11-05 11:58:19 +01007714 mReportedFormatsMap[devDesc] = formats;
Mikhail Naganov100f0122018-11-29 11:22:16 -08007715 if (device == AUDIO_DEVICE_OUT_HDMI
7716 || isDeviceOfModule(devDesc, AUDIO_HARDWARE_MODULE_ID_MSD)) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007717 modifySurroundFormats(devDesc, &formats);
Phil Burk00eeb322016-03-31 12:41:00 -07007718 }
jiabin3e277cc2019-09-10 14:27:34 -07007719 addProfilesForFormats(profiles, formats);
François Gaffie112b0af2015-11-19 16:13:25 +01007720 }
François Gaffie112b0af2015-11-19 16:13:25 +01007721
Mikhail Naganovcf84e592017-12-07 11:25:11 -08007722 for (audio_format_t format : profiles.getSupportedFormats()) {
jiabinf26596b2023-04-12 18:56:39 +00007723 std::optional<ChannelMaskSet> channelMasks;
jiabin06e4bab2019-07-29 10:13:34 -07007724 SampleRateSet samplingRates;
François Gaffie112b0af2015-11-19 16:13:25 +01007725 AudioParameter requestedParameters;
Mikhail Naganov388360c2016-10-17 17:09:41 -07007726 requestedParameters.addInt(String8(AudioParameter::keyFormat), format);
François Gaffie112b0af2015-11-19 16:13:25 +01007727
7728 if (profiles.hasDynamicRateFor(format)) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07007729 reply = mpClientInterface->getParameters(
7730 ioHandle,
7731 requestedParameters.toString() + ";" +
7732 AudioParameter::keyStreamSupportedSamplingRates);
François Gaffie112b0af2015-11-19 16:13:25 +01007733 ALOGV("%s: supported sampling rates %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08007734 AudioParameter repliedParameters(reply);
7735 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07007736 String8(AudioParameter::keyStreamSupportedSamplingRates), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08007737 samplingRates = samplingRatesFromString(reply.string());
jiabinf26596b2023-04-12 18:56:39 +00007738 } else {
7739 samplingRates = devDesc->getAudioProfiles().getSampleRatesFor(format);
François Gaffie112b0af2015-11-19 16:13:25 +01007740 }
7741 }
7742 if (profiles.hasDynamicChannelsFor(format)) {
7743 reply = mpClientInterface->getParameters(ioHandle,
7744 requestedParameters.toString() + ";" +
Mikhail Naganov388360c2016-10-17 17:09:41 -07007745 AudioParameter::keyStreamSupportedChannels);
François Gaffie112b0af2015-11-19 16:13:25 +01007746 ALOGV("%s: supported channel masks %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08007747 AudioParameter repliedParameters(reply);
7748 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07007749 String8(AudioParameter::keyStreamSupportedChannels), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08007750 channelMasks = channelMasksFromString(reply.string());
jiabinf26596b2023-04-12 18:56:39 +00007751 } else {
7752 channelMasks = devDesc->getAudioProfiles().getChannelMasksFor(format);
7753 }
7754 if (channelMasks.has_value() && (device == AUDIO_DEVICE_OUT_HDMI
7755 || isDeviceOfModule(devDesc, AUDIO_HARDWARE_MODULE_ID_MSD))) {
7756 modifySurroundChannelMasks(&channelMasks.value());
François Gaffie112b0af2015-11-19 16:13:25 +01007757 }
7758 }
jiabin3e277cc2019-09-10 14:27:34 -07007759 addDynamicAudioProfileAndSort(
jiabinf26596b2023-04-12 18:56:39 +00007760 profiles, new AudioProfile(
7761 format, channelMasks.value_or(ChannelMaskSet()), samplingRates));
François Gaffie112b0af2015-11-19 16:13:25 +01007762 }
7763}
Eric Laurentd60560a2015-04-10 11:31:20 -07007764
Mikhail Naganovdc769682018-05-04 15:34:08 -07007765status_t AudioPolicyManager::installPatch(const char *caller,
7766 audio_patch_handle_t *patchHandle,
7767 AudioIODescriptorInterface *ioDescriptor,
7768 const struct audio_patch *patch,
7769 int delayMs)
7770{
7771 ssize_t index = mAudioPatches.indexOfKey(
7772 patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE ?
7773 *patchHandle : ioDescriptor->getPatchHandle());
7774 sp<AudioPatch> patchDesc;
7775 status_t status = installPatch(
7776 caller, index, patchHandle, patch, delayMs, mUidCached, &patchDesc);
7777 if (status == NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01007778 ioDescriptor->setPatchHandle(patchDesc->getHandle());
Mikhail Naganovdc769682018-05-04 15:34:08 -07007779 }
7780 return status;
7781}
7782
7783status_t AudioPolicyManager::installPatch(const char *caller,
7784 ssize_t index,
7785 audio_patch_handle_t *patchHandle,
7786 const struct audio_patch *patch,
7787 int delayMs,
7788 uid_t uid,
7789 sp<AudioPatch> *patchDescPtr)
7790{
7791 sp<AudioPatch> patchDesc;
7792 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
7793 if (index >= 0) {
7794 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007795 afPatchHandle = patchDesc->getAfHandle();
Mikhail Naganovdc769682018-05-04 15:34:08 -07007796 }
7797
7798 status_t status = mpClientInterface->createAudioPatch(patch, &afPatchHandle, delayMs);
7799 ALOGV("%s() AF::createAudioPatch returned %d patchHandle %d num_sources %d num_sinks %d",
7800 caller, status, afPatchHandle, patch->num_sources, patch->num_sinks);
7801 if (status == NO_ERROR) {
7802 if (index < 0) {
7803 patchDesc = new AudioPatch(patch, uid);
François Gaffieafd4cea2019-11-18 15:50:22 +01007804 addAudioPatch(patchDesc->getHandle(), patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07007805 } else {
7806 patchDesc->mPatch = *patch;
7807 }
François Gaffieafd4cea2019-11-18 15:50:22 +01007808 patchDesc->setAfHandle(afPatchHandle);
Mikhail Naganovdc769682018-05-04 15:34:08 -07007809 if (patchHandle) {
François Gaffieafd4cea2019-11-18 15:50:22 +01007810 *patchHandle = patchDesc->getHandle();
Mikhail Naganovdc769682018-05-04 15:34:08 -07007811 }
7812 nextAudioPortGeneration();
7813 mpClientInterface->onAudioPatchListUpdate();
7814 }
7815 if (patchDescPtr) *patchDescPtr = patchDesc;
7816 return status;
7817}
7818
jiabinbce0c1d2020-10-05 11:20:18 -07007819bool AudioPolicyManager::areAllActiveTracksRerouted(const sp<SwAudioOutputDescriptor>& output)
7820{
7821 const TrackClientVector activeClients = output->getActiveClients();
7822 if (activeClients.empty()) {
7823 return true;
7824 }
7825 ssize_t index = mAudioPatches.indexOfKey(output->getPatchHandle());
7826 if (index < 0) {
7827 ALOGE("%s, no audio patch found while there are active clients on output %d",
7828 __func__, output->getId());
7829 return false;
7830 }
7831 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
7832 DeviceVector routedDevices;
7833 for (int i = 0; i < patchDesc->mPatch.num_sinks; ++i) {
7834 sp<DeviceDescriptor> device = mAvailableOutputDevices.getDeviceFromId(
7835 patchDesc->mPatch.sinks[i].id);
7836 if (device == nullptr) {
7837 ALOGE("%s, no audio device found with id(%d)",
7838 __func__, patchDesc->mPatch.sinks[i].id);
7839 return false;
7840 }
7841 routedDevices.add(device);
7842 }
7843 for (const auto& client : activeClients) {
jiabin49256852022-03-09 11:21:35 -08007844 if (client->isInvalid()) {
7845 // No need to take care about invalidated clients.
7846 continue;
7847 }
jiabinbce0c1d2020-10-05 11:20:18 -07007848 sp<DeviceDescriptor> preferredDevice =
7849 mAvailableOutputDevices.getDeviceFromId(client->preferredDeviceId());
7850 if (mEngine->getOutputDevicesForAttributes(
7851 client->attributes(), preferredDevice, false) == routedDevices) {
7852 return false;
7853 }
7854 }
7855 return true;
7856}
7857
7858sp<SwAudioOutputDescriptor> AudioPolicyManager::openOutputWithProfileAndDevice(
Eric Laurentb4f42a92022-01-17 17:37:31 +01007859 const sp<IOProfile>& profile, const DeviceVector& devices,
7860 const audio_config_base_t *mixerConfig)
jiabinbce0c1d2020-10-05 11:20:18 -07007861{
7862 for (const auto& device : devices) {
7863 // TODO: This should be checking if the profile supports the device combo.
7864 if (!profile->supportsDevice(device)) {
7865 return nullptr;
7866 }
7867 }
7868 sp<SwAudioOutputDescriptor> desc = new SwAudioOutputDescriptor(profile, mpClientInterface);
7869 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentb4f42a92022-01-17 17:37:31 +01007870 status_t status = desc->open(nullptr /* halConfig */, mixerConfig, devices,
jiabinbce0c1d2020-10-05 11:20:18 -07007871 AUDIO_STREAM_DEFAULT, AUDIO_OUTPUT_FLAG_NONE, &output);
7872 if (status != NO_ERROR) {
7873 return nullptr;
7874 }
7875
7876 // Here is where the out_set_parameters() for card & device gets called
7877 sp<DeviceDescriptor> device = devices.getDeviceForOpening();
7878 const audio_devices_t deviceType = device->type();
7879 const String8 &address = String8(device->address().c_str());
7880 if (!address.isEmpty()) {
7881 char *param = audio_device_address_to_parameter(deviceType, address.c_str());
7882 mpClientInterface->setParameters(output, String8(param));
7883 free(param);
7884 }
7885 updateAudioProfiles(device, output, profile->getAudioProfiles());
7886 if (!profile->hasValidAudioProfile()) {
7887 ALOGW("%s() missing param", __func__);
7888 desc->close();
7889 return nullptr;
7890 } else if (profile->hasDynamicAudioProfile()) {
7891 desc->close();
7892 output = AUDIO_IO_HANDLE_NONE;
7893 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
7894 profile->pickAudioProfile(
7895 config.sample_rate, config.channel_mask, config.format);
7896 config.offload_info.sample_rate = config.sample_rate;
7897 config.offload_info.channel_mask = config.channel_mask;
7898 config.offload_info.format = config.format;
7899
Eric Laurentb4f42a92022-01-17 17:37:31 +01007900 status = desc->open(&config, mixerConfig, devices,
jiabinbce0c1d2020-10-05 11:20:18 -07007901 AUDIO_STREAM_DEFAULT, AUDIO_OUTPUT_FLAG_NONE, &output);
7902 if (status != NO_ERROR) {
7903 return nullptr;
7904 }
7905 }
7906
7907 addOutput(output, desc);
Eric Laurentb4f42a92022-01-17 17:37:31 +01007908
baek.kim -61c20122022-07-27 10:05:32 +00007909 sp<DeviceDescriptor> speaker = mAvailableOutputDevices.getDevice(
7910 AUDIO_DEVICE_OUT_SPEAKER, String8(""), AUDIO_FORMAT_DEFAULT);
7911
jiabinbce0c1d2020-10-05 11:20:18 -07007912 if (audio_is_remote_submix_device(deviceType) && address != "0") {
7913 sp<AudioPolicyMix> policyMix;
7914 if (mPolicyMixes.getAudioPolicyMix(deviceType, address, policyMix) == NO_ERROR) {
7915 policyMix->setOutput(desc);
7916 desc->mPolicyMix = policyMix;
7917 } else {
7918 ALOGW("checkOutputsForDevice() cannot find policy for address %s",
7919 address.string());
7920 }
7921
baek.kim -61c20122022-07-27 10:05:32 +00007922 } else if (hasPrimaryOutput() && speaker != nullptr
7923 && mPrimaryOutput->supportsDevice(speaker) && !desc->supportsDevice(speaker)
Eric Laurentb4f42a92022-01-17 17:37:31 +01007924 && ((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0)) {
7925 // no duplicated output for:
7926 // - direct outputs
7927 // - outputs used by dynamic policy mixes
baek.kim -61c20122022-07-27 10:05:32 +00007928 // - outputs that supports SPEAKER while the primary output does not.
jiabinbce0c1d2020-10-05 11:20:18 -07007929 audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE;
7930
7931 //TODO: configure audio effect output stage here
7932
7933 // open a duplicating output thread for the new output and the primary output
7934 sp<SwAudioOutputDescriptor> dupOutputDesc =
7935 new SwAudioOutputDescriptor(nullptr, mpClientInterface);
7936 status = dupOutputDesc->openDuplicating(mPrimaryOutput, desc, &duplicatedOutput);
7937 if (status == NO_ERROR) {
7938 // add duplicated output descriptor
7939 addOutput(duplicatedOutput, dupOutputDesc);
7940 } else {
7941 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
7942 mPrimaryOutput->mIoHandle, output);
7943 desc->close();
7944 removeOutput(output);
7945 nextAudioPortGeneration();
7946 return nullptr;
7947 }
7948 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02007949 if (mPrimaryOutput == nullptr && profile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
7950 ALOGV("%s(): re-assigning mPrimaryOutput", __func__);
7951 mPrimaryOutput = desc;
7952 }
jiabinbce0c1d2020-10-05 11:20:18 -07007953 return desc;
7954}
7955
Mikhail Naganov1b2a7942017-12-08 10:18:09 -08007956} // namespace android