blob: 23d4b33a2393c033036bb8575f5e49b1947622c6 [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,
1660 AUDIO_FORMAT_AC3, AUDIO_FORMAT_PCM_16_BIT }};
1661 static const std::vector<audio_channel_mask_t> channelMasksOrder = [](){
1662 // Channel position masks for MSD module, 3D > 2D > 1D ordering (most preferred to least
1663 // preferred).
1664 std::vector<audio_channel_mask_t> masks = {{
1665 AUDIO_CHANNEL_OUT_3POINT1POINT2, AUDIO_CHANNEL_OUT_3POINT0POINT2,
1666 AUDIO_CHANNEL_OUT_2POINT1POINT2, AUDIO_CHANNEL_OUT_2POINT0POINT2,
1667 AUDIO_CHANNEL_OUT_5POINT1, AUDIO_CHANNEL_OUT_STEREO }};
1668 // insert index masks (higher counts most preferred) as preferred over position masks
1669 for (int i = 1; i <= AUDIO_CHANNEL_COUNT_MAX; i++) {
1670 masks.insert(
1671 masks.begin(), audio_channel_mask_for_index_assignment_from_count(i));
1672 }
1673 return masks;
1674 }();
1675
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001676 struct audio_config_base bestSinkConfig;
Dean Wheatley16809da2022-12-09 14:55:46 +11001677 status_t result = findBestMatchingOutputConfig(sourceProfiles, sinkProfiles, formatsOrder,
1678 channelMasksOrder, true /*preferHigherSamplingRates*/, bestSinkConfig);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001679 if (result != NO_ERROR) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001680 ALOGD("%s() no matching config found for sink, hwAvSync: %d",
1681 __func__, hwAvSync);
Greg Kaiser83289652018-07-30 06:13:57 -07001682 return result;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001683 }
1684 sinkConfig->sample_rate = bestSinkConfig.sample_rate;
1685 sinkConfig->channel_mask = bestSinkConfig.channel_mask;
1686 sinkConfig->format = bestSinkConfig.format;
1687 // For encoded streams force direct flag to prevent downstream mixing.
1688 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1689 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_DIRECT);
Dean Wheatley5c9f0832019-11-21 13:39:31 +11001690 if (audio_is_iec61937_compatible(sinkConfig->format)) {
1691 // For formats compatible with IEC61937 encapsulation, assume that
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001692 // the input is IEC61937 framed (for proportional buffer sizing).
Dean Wheatley5c9f0832019-11-21 13:39:31 +11001693 // Add the AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO flag so downstream HAL can distinguish between
1694 // raw and IEC61937 framed streams.
1695 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1696 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO);
1697 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001698 sourceConfig->sample_rate = bestSinkConfig.sample_rate;
1699 // Specify exact channel mask to prevent guessing by bit count in PatchPanel.
Dean Wheatley16809da2022-12-09 14:55:46 +11001700 sourceConfig->channel_mask =
1701 audio_channel_mask_get_representation(bestSinkConfig.channel_mask)
1702 == AUDIO_CHANNEL_REPRESENTATION_INDEX ?
1703 bestSinkConfig.channel_mask : audio_channel_mask_out_to_in(bestSinkConfig.channel_mask);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001704 sourceConfig->format = bestSinkConfig.format;
1705 // Copy input stream directly without any processing (e.g. resampling).
1706 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1707 sourceConfig->flags.input | AUDIO_INPUT_FLAG_DIRECT);
1708 if (hwAvSync) {
1709 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1710 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
1711 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1712 sourceConfig->flags.input | AUDIO_INPUT_FLAG_HW_AV_SYNC);
1713 }
1714 const unsigned int config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE |
1715 AUDIO_PORT_CONFIG_CHANNEL_MASK | AUDIO_PORT_CONFIG_FORMAT | AUDIO_PORT_CONFIG_FLAGS;
1716 sinkConfig->config_mask |= config_mask;
1717 sourceConfig->config_mask |= config_mask;
1718 return NO_ERROR;
1719}
1720
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001721PatchBuilder AudioPolicyManager::buildMsdPatch(bool msdIsSource,
1722 const sp<DeviceDescriptor> &device) const
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001723{
1724 PatchBuilder patchBuilder;
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001725 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1726 ALOG_ASSERT(msdModule != nullptr, "MSD module not available");
1727 sp<HwModule> deviceModule = mHwModules.getModuleForDevice(device, AUDIO_FORMAT_DEFAULT);
1728 if (deviceModule == nullptr) {
1729 ALOGE("%s() unable to get module for %s", __func__, device->toString().c_str());
1730 return patchBuilder;
1731 }
1732 const InputProfileCollection inputProfiles = msdIsSource ?
1733 msdModule->getInputProfiles() : deviceModule->getInputProfiles();
1734 const OutputProfileCollection outputProfiles = msdIsSource ?
1735 deviceModule->getOutputProfiles() : msdModule->getOutputProfiles();
1736
1737 const sp<DeviceDescriptor> sourceDevice = msdIsSource ? getMsdAudioInDevice() : device;
1738 const sp<DeviceDescriptor> sinkDevice = msdIsSource ?
1739 device : getMsdAudioOutDevices().itemAt(0);
1740 patchBuilder.addSource(sourceDevice).addSink(sinkDevice);
1741
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001742 audio_port_config sourceConfig = patchBuilder.patch()->sources[0];
1743 audio_port_config sinkConfig = patchBuilder.patch()->sinks[0];
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001744 AudioProfileVector sourceProfiles;
1745 AudioProfileVector sinkProfiles;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001746 // TODO: Figure out whether MSD module has HW_AV_SYNC flag set in the AP config file.
1747 // For now, we just forcefully try with HwAvSync first.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001748 for (auto hwAvSync : { true, false }) {
1749 if (getMsdProfiles(hwAvSync, inputProfiles, outputProfiles, sourceDevice, sinkDevice,
1750 sourceProfiles, sinkProfiles) != NO_ERROR) {
1751 continue;
1752 }
1753 if (getBestMsdConfig(hwAvSync, sourceProfiles, sinkProfiles, &sourceConfig,
1754 &sinkConfig) == NO_ERROR) {
1755 // Found a matching config. Re-create PatchBuilder with this config.
1756 return (PatchBuilder()).addSource(sourceConfig).addSink(sinkConfig);
1757 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001758 }
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001759 ALOGV("%s() no matching config found. Fall through to default PCM patch"
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001760 " supporting PCM format conversion.", __func__);
1761 return patchBuilder;
1762}
1763
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001764status_t AudioPolicyManager::setMsdOutputPatches(const DeviceVector *outputDevices) {
Michael Chan6fb34492020-12-08 15:44:49 +11001765 DeviceVector devices;
1766 if (outputDevices != nullptr && outputDevices->size() > 0) {
1767 devices.add(*outputDevices);
1768 } else {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001769 // Use media strategy for unspecified output device. This should only
1770 // occur on checkForDeviceAndOutputChanges(). Device connection events may
1771 // therefore invalidate explicit routing requests.
Michael Chan6fb34492020-12-08 15:44:49 +11001772 devices = mEngine->getOutputDevicesForAttributes(
François Gaffiec005e562018-11-06 15:04:49 +01001773 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
Michael Chan6fb34492020-12-08 15:44:49 +11001774 LOG_ALWAYS_FATAL_IF(devices.isEmpty(), "no output device to set MSD patch");
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001775 }
Michael Chan6fb34492020-12-08 15:44:49 +11001776 std::vector<PatchBuilder> patchesToCreate;
1777 for (auto i = 0u; i < devices.size(); ++i) {
1778 ALOGV("%s() for device %s", __func__, devices[i]->toString().c_str());
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001779 patchesToCreate.push_back(buildMsdPatch(true /*msdIsSource*/, devices[i]));
Michael Chan6fb34492020-12-08 15:44:49 +11001780 }
1781 // Retain only the MSD patches associated with outputDevices request.
1782 // Tear down the others, and create new ones as needed.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001783 AudioPatchCollection patchesToRemove = getMsdOutputPatches();
Michael Chan6fb34492020-12-08 15:44:49 +11001784 for (auto it = patchesToCreate.begin(); it != patchesToCreate.end(); ) {
1785 auto retainedPatch = false;
1786 for (auto i = 0u; i < patchesToRemove.size(); ++i) {
1787 if (audio_patches_are_equal(it->patch(), &patchesToRemove[i]->mPatch)) {
1788 patchesToRemove.removeItemsAt(i);
1789 retainedPatch = true;
1790 break;
1791 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001792 }
Michael Chan6fb34492020-12-08 15:44:49 +11001793 if (retainedPatch) {
1794 it = patchesToCreate.erase(it);
1795 continue;
1796 }
1797 ++it;
1798 }
1799 if (patchesToCreate.size() == 0 && patchesToRemove.size() == 0) {
1800 return NO_ERROR;
1801 }
1802 for (auto i = 0u; i < patchesToRemove.size(); ++i) {
1803 auto &currentPatch = patchesToRemove.valueAt(i);
François Gaffieafd4cea2019-11-18 15:50:22 +01001804 releaseAudioPatch(currentPatch->getHandle(), mUidCached);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001805 }
Michael Chan6fb34492020-12-08 15:44:49 +11001806 status_t status = NO_ERROR;
1807 for (const auto &p : patchesToCreate) {
1808 auto currStatus = installPatch(__func__, -1 /*index*/, nullptr /*patchHandle*/,
1809 p.patch(), 0 /*delayMs*/, mUidCached, nullptr /*patchDescPtr*/);
1810 char message[256];
1811 snprintf(message, sizeof(message), "%s() %s: creating MSD patch from device:IN_BUS to "
1812 "device:%#x (format:%#x channels:%#x samplerate:%d)", __func__,
1813 currStatus == NO_ERROR ? "Success" : "Error",
1814 p.patch()->sinks[0].ext.device.type, p.patch()->sources[0].format,
1815 p.patch()->sources[0].channel_mask, p.patch()->sources[0].sample_rate);
1816 if (currStatus == NO_ERROR) {
1817 ALOGD("%s", message);
1818 } else {
1819 ALOGE("%s", message);
1820 if (status == NO_ERROR) {
1821 status = currStatus;
1822 }
1823 }
1824 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001825 return status;
1826}
1827
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001828void AudioPolicyManager::releaseMsdOutputPatches(const DeviceVector& devices) {
1829 AudioPatchCollection msdPatches = getMsdOutputPatches();
Michael Chan6fb34492020-12-08 15:44:49 +11001830 for (size_t i = 0; i < msdPatches.size(); i++) {
1831 const auto& patch = msdPatches[i];
1832 for (size_t j = 0; j < patch->mPatch.num_sinks; ++j) {
1833 const struct audio_port_config *sink = &patch->mPatch.sinks[j];
1834 if (sink->type == AUDIO_PORT_TYPE_DEVICE && devices.getDevice(sink->ext.device.type,
1835 String8(sink->ext.device.address), AUDIO_FORMAT_DEFAULT) != nullptr) {
1836 releaseAudioPatch(patch->getHandle(), mUidCached);
1837 break;
1838 }
1839 }
1840 }
1841}
1842
Dorin Drimus94d94412022-02-02 09:05:02 +01001843bool AudioPolicyManager::msdHasPatchesToAllDevices(const AudioDeviceTypeAddrVector& devices) {
Mikhail Naganovb0fbc1b2023-04-28 13:06:32 -07001844 DeviceVector devicesToCheck =
1845 mConfig->getOutputDevices().getDevicesFromDeviceTypeAddrVec(devices);
Dorin Drimus94d94412022-02-02 09:05:02 +01001846 AudioPatchCollection msdPatches = getMsdOutputPatches();
1847 for (size_t i = 0; i < msdPatches.size(); i++) {
1848 const auto& patch = msdPatches[i];
1849 for (size_t j = 0; j < patch->mPatch.num_sinks; ++j) {
1850 const struct audio_port_config *sink = &patch->mPatch.sinks[j];
1851 if (sink->type == AUDIO_PORT_TYPE_DEVICE) {
1852 const auto& foundDevice = devicesToCheck.getDevice(
1853 sink->ext.device.type, String8(sink->ext.device.address), AUDIO_FORMAT_DEFAULT);
1854 if (foundDevice != nullptr) {
1855 devicesToCheck.remove(foundDevice);
1856 if (devicesToCheck.isEmpty()) {
1857 return true;
1858 }
1859 }
1860 }
1861 }
1862 }
1863 return false;
1864}
1865
Eric Laurente0720872014-03-11 09:30:41 -07001866audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
jiabinebb6af42020-06-09 17:31:17 -07001867 audio_output_flags_t flags,
1868 audio_format_t format,
1869 audio_channel_mask_t channelMask,
1870 uint32_t samplingRate,
1871 audio_session_t sessionId)
Eric Laurente552edb2014-03-10 17:42:56 -07001872{
Eric Laurent16c66dd2019-05-01 17:54:10 -07001873 LOG_ALWAYS_FATAL_IF(!(format == AUDIO_FORMAT_INVALID || audio_is_linear_pcm(format)),
1874 "%s called with format %#x", __func__, format);
1875
jiabinebb6af42020-06-09 17:31:17 -07001876 // Return the output that haptic-generating attached to when 1) session id is specified,
1877 // 2) haptic-generating effect exists for given session id and 3) the output that
1878 // haptic-generating effect attached to is in given outputs.
1879 if (sessionId != AUDIO_SESSION_NONE) {
1880 audio_io_handle_t hapticGeneratingOutput = mEffects.getIoForSession(
1881 sessionId, FX_IID_HAPTICGENERATOR);
1882 if (outputs.indexOf(hapticGeneratingOutput) >= 0) {
1883 return hapticGeneratingOutput;
1884 }
1885 }
1886
Eric Laurent16c66dd2019-05-01 17:54:10 -07001887 // Flags disqualifying an output: the match must happen before calling selectOutput()
1888 static const audio_output_flags_t kExcludedFlags = (audio_output_flags_t)
1889 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ | AUDIO_OUTPUT_FLAG_DIRECT);
1890
1891 // Flags expressing a functional request: must be honored in priority over
1892 // other criteria
1893 static const audio_output_flags_t kFunctionalFlags = (audio_output_flags_t)
1894 (AUDIO_OUTPUT_FLAG_VOIP_RX | AUDIO_OUTPUT_FLAG_INCALL_MUSIC |
Eric Laurente28c66d2022-01-21 13:40:41 +01001895 AUDIO_OUTPUT_FLAG_TTS | AUDIO_OUTPUT_FLAG_DIRECT_PCM | AUDIO_OUTPUT_FLAG_ULTRASOUND |
1896 AUDIO_OUTPUT_FLAG_SPATIALIZER);
Eric Laurent16c66dd2019-05-01 17:54:10 -07001897 // Flags expressing a performance request: have lower priority than serving
1898 // requested sampling rate or channel mask
1899 static const audio_output_flags_t kPerformanceFlags = (audio_output_flags_t)
1900 (AUDIO_OUTPUT_FLAG_FAST | AUDIO_OUTPUT_FLAG_DEEP_BUFFER |
1901 AUDIO_OUTPUT_FLAG_RAW | AUDIO_OUTPUT_FLAG_SYNC);
1902
1903 const audio_output_flags_t functionalFlags =
1904 (audio_output_flags_t)(flags & kFunctionalFlags);
1905 const audio_output_flags_t performanceFlags =
1906 (audio_output_flags_t)(flags & kPerformanceFlags);
1907
1908 audio_io_handle_t bestOutput = (outputs.size() == 0) ? AUDIO_IO_HANDLE_NONE : outputs[0];
1909
Eric Laurente552edb2014-03-10 17:42:56 -07001910 // select one output among several that provide a path to a particular device or set of
François Gaffie11d30102018-11-02 16:09:09 +01001911 // devices (the list was previously build by getOutputsForDevices()).
Eric Laurente552edb2014-03-10 17:42:56 -07001912 // The priority is as follows:
jiabin40573322018-11-08 12:08:02 -08001913 // 1: the output supporting haptic playback when requesting haptic playback
Eric Laurent16c66dd2019-05-01 17:54:10 -07001914 // 2: the output with the highest number of requested functional flags
Carter Hsu199f1892021-10-15 15:47:29 +08001915 // with tiebreak preferring the minimum number of extra functional flags
1916 // (see b/200293124, the incorrect selection of AUDIO_OUTPUT_FLAG_VOIP_RX).
Eric Laurent16c66dd2019-05-01 17:54:10 -07001917 // 3: the output supporting the exact channel mask
1918 // 4: the output with a higher channel count than requested
jiabind1785f72022-06-03 20:48:18 +00001919 // 5: the output with the highest sampling rate if the requested sample rate is
1920 // greater than default sampling rate
Eric Laurent16c66dd2019-05-01 17:54:10 -07001921 // 6: the output with the highest number of requested performance flags
1922 // 7: the output with the bit depth the closest to the requested one
1923 // 8: the primary output
1924 // 9: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07001925
Eric Laurent16c66dd2019-05-01 17:54:10 -07001926 // matching criteria values in priority order for best matching output so far
1927 std::vector<uint32_t> bestMatchCriteria(8, 0);
Eric Laurente552edb2014-03-10 17:42:56 -07001928
Eric Laurent16c66dd2019-05-01 17:54:10 -07001929 const uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
1930 const uint32_t hapticChannelCount = audio_channel_count_from_out_mask(
1931 channelMask & AUDIO_CHANNEL_HAPTIC_ALL);
Eric Laurente78b6762018-12-19 16:29:01 -08001932
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001933 for (audio_io_handle_t output : outputs) {
1934 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent16c66dd2019-05-01 17:54:10 -07001935 // matching criteria values in priority order for current output
1936 std::vector<uint32_t> currentMatchCriteria(8, 0);
jiabin40573322018-11-08 12:08:02 -08001937
Eric Laurent16c66dd2019-05-01 17:54:10 -07001938 if (outputDesc->isDuplicated()) {
1939 continue;
1940 }
1941 if ((kExcludedFlags & outputDesc->mFlags) != 0) {
1942 continue;
1943 }
Eric Laurent8838a382014-09-08 16:44:28 -07001944
Eric Laurent16c66dd2019-05-01 17:54:10 -07001945 // If haptic channel is specified, use the haptic output if present.
1946 // When using haptic output, same audio format and sample rate are required.
1947 const uint32_t outputHapticChannelCount = audio_channel_count_from_out_mask(
jiabin5740f082019-08-19 15:08:30 -07001948 outputDesc->getChannelMask() & AUDIO_CHANNEL_HAPTIC_ALL);
Eric Laurent16c66dd2019-05-01 17:54:10 -07001949 if ((hapticChannelCount == 0) != (outputHapticChannelCount == 0)) {
1950 continue;
1951 }
1952 if (outputHapticChannelCount >= hapticChannelCount
jiabin5740f082019-08-19 15:08:30 -07001953 && format == outputDesc->getFormat()
1954 && samplingRate == outputDesc->getSamplingRate()) {
Eric Laurent16c66dd2019-05-01 17:54:10 -07001955 currentMatchCriteria[0] = outputHapticChannelCount;
1956 }
1957
1958 // functional flags match
Carter Hsu199f1892021-10-15 15:47:29 +08001959 const int matchingFunctionalFlags =
1960 __builtin_popcount(outputDesc->mFlags & functionalFlags);
1961 const int totalFunctionalFlags =
1962 __builtin_popcount(outputDesc->mFlags & kFunctionalFlags);
1963 // Prefer matching functional flags, but subtract unnecessary functional flags.
1964 currentMatchCriteria[1] = 100 * (matchingFunctionalFlags + 1) - totalFunctionalFlags;
Eric Laurent16c66dd2019-05-01 17:54:10 -07001965
1966 // channel mask and channel count match
jiabin5740f082019-08-19 15:08:30 -07001967 uint32_t outputChannelCount = audio_channel_count_from_out_mask(
1968 outputDesc->getChannelMask());
Eric Laurent16c66dd2019-05-01 17:54:10 -07001969 if (channelMask != AUDIO_CHANNEL_NONE && channelCount > 2 &&
1970 channelCount <= outputChannelCount) {
1971 if ((audio_channel_mask_get_representation(channelMask) ==
jiabin5740f082019-08-19 15:08:30 -07001972 audio_channel_mask_get_representation(outputDesc->getChannelMask())) &&
1973 ((channelMask & outputDesc->getChannelMask()) == channelMask)) {
Eric Laurent16c66dd2019-05-01 17:54:10 -07001974 currentMatchCriteria[2] = outputChannelCount;
Eric Laurente552edb2014-03-10 17:42:56 -07001975 }
Eric Laurent16c66dd2019-05-01 17:54:10 -07001976 currentMatchCriteria[3] = outputChannelCount;
1977 }
1978
1979 // sampling rate match
jiabind1785f72022-06-03 20:48:18 +00001980 if (samplingRate > SAMPLE_RATE_HZ_DEFAULT) {
jiabin5740f082019-08-19 15:08:30 -07001981 currentMatchCriteria[4] = outputDesc->getSamplingRate();
Eric Laurent16c66dd2019-05-01 17:54:10 -07001982 }
1983
1984 // performance flags match
1985 currentMatchCriteria[5] = popcount(outputDesc->mFlags & performanceFlags);
1986
1987 // format match
1988 if (format != AUDIO_FORMAT_INVALID) {
1989 currentMatchCriteria[6] =
jiabin4ef93452019-09-10 14:29:54 -07001990 PolicyAudioPort::kFormatDistanceMax -
1991 PolicyAudioPort::formatDistance(format, outputDesc->getFormat());
Eric Laurent16c66dd2019-05-01 17:54:10 -07001992 }
1993
1994 // primary output match
1995 currentMatchCriteria[7] = outputDesc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY;
1996
1997 // compare match criteria by priority then value
1998 if (std::lexicographical_compare(bestMatchCriteria.begin(), bestMatchCriteria.end(),
1999 currentMatchCriteria.begin(), currentMatchCriteria.end())) {
2000 bestMatchCriteria = currentMatchCriteria;
2001 bestOutput = output;
2002
2003 std::stringstream result;
2004 std::copy(bestMatchCriteria.begin(), bestMatchCriteria.end(),
2005 std::ostream_iterator<int>(result, " "));
2006 ALOGV("%s new bestOutput %d criteria %s",
2007 __func__, bestOutput, result.str().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07002008 }
2009 }
2010
Eric Laurent16c66dd2019-05-01 17:54:10 -07002011 return bestOutput;
Eric Laurente552edb2014-03-10 17:42:56 -07002012}
2013
Eric Laurent8fc147b2018-07-22 19:13:55 -07002014status_t AudioPolicyManager::startOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002015{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002016 ALOGV("%s portId %d", __FUNCTION__, portId);
2017
2018 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2019 if (outputDesc == 0) {
2020 ALOGW("startOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002021 return BAD_VALUE;
2022 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002023 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002024
Eric Laurent8fc147b2018-07-22 19:13:55 -07002025 ALOGV("startOutput() output %d, stream %d, session %d",
Eric Laurent97ac8712018-07-27 18:59:02 -07002026 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurentc75307b2015-03-17 15:29:32 -07002027
Eric Laurent733ce942017-12-07 12:18:25 -08002028 status_t status = outputDesc->start();
2029 if (status != NO_ERROR) {
2030 return status;
Eric Laurent3974e3b2017-12-07 17:58:43 -08002031 }
2032
Eric Laurent97ac8712018-07-27 18:59:02 -07002033 uint32_t delayMs;
2034 status = startSource(outputDesc, client, &delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07002035
2036 if (status != NO_ERROR) {
Eric Laurent733ce942017-12-07 12:18:25 -08002037 outputDesc->stop();
Eric Laurent8c7e6da2015-04-21 17:37:00 -07002038 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07002039 }
Eric Laurentc75307b2015-03-17 15:29:32 -07002040 if (delayMs != 0) {
2041 usleep(delayMs * 1000);
2042 }
2043
2044 return status;
2045}
2046
Eric Laurent96d1dda2022-03-14 17:14:19 +01002047bool AudioPolicyManager::isLeUnicastActive() const {
2048 if (isInCall()) {
2049 return true;
2050 }
2051 return isAnyDeviceTypeActive(getAudioDeviceOutLeAudioUnicastSet());
2052}
2053
2054bool AudioPolicyManager::isAnyDeviceTypeActive(const DeviceTypeSet& deviceTypes) const {
2055 if (mAvailableOutputDevices.getDevicesFromTypes(deviceTypes).isEmpty()) {
2056 return false;
2057 }
2058 bool active = mOutputs.isAnyDeviceTypeActive(deviceTypes);
2059 ALOGV("%s active %d", __func__, active);
2060 return active;
2061}
2062
Eric Laurent97ac8712018-07-27 18:59:02 -07002063status_t AudioPolicyManager::startSource(const sp<SwAudioOutputDescriptor>& outputDesc,
2064 const sp<TrackClientDescriptor>& client,
2065 uint32_t *delayMs)
Eric Laurentc75307b2015-03-17 15:29:32 -07002066{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002067 // cannot start playback of STREAM_TTS if any other output is being used
2068 uint32_t beaconMuteLatency = 0;
Eric Laurentc75307b2015-03-17 15:29:32 -07002069
2070 *delayMs = 0;
Eric Laurent97ac8712018-07-27 18:59:02 -07002071 audio_stream_type_t stream = client->stream();
François Gaffie1c878552018-11-22 16:53:21 +01002072 auto clientVolSrc = client->volumeSource();
François Gaffiec005e562018-11-06 15:04:49 +01002073 auto clientStrategy = client->strategy();
2074 auto clientAttr = client->attributes();
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002075 if (stream == AUDIO_STREAM_TTS) {
2076 ALOGV("\t found BEACON stream");
François Gaffie1c878552018-11-22 16:53:21 +01002077 if (!mTtsOutputAvailable && mOutputs.isAnyOutputActive(
Francois Gaffie4404ddb2021-02-04 17:03:38 +01002078 toVolumeSource(AUDIO_STREAM_TTS, false) /*sourceToIgnore*/)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002079 return INVALID_OPERATION;
2080 } else {
2081 beaconMuteLatency = handleEventForBeacon(STARTING_BEACON);
2082 }
2083 } else {
2084 // some playback other than beacon starts
2085 beaconMuteLatency = handleEventForBeacon(STARTING_OUTPUT);
2086 }
2087
Eric Laurent77305a62016-07-25 16:39:22 -07002088 // force device change if the output is inactive and no audio patch is already present.
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002089 // check active before incrementing usage count
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02002090 bool force = !outputDesc->isActive() && !outputDesc->isRouted();
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002091
François Gaffie11d30102018-11-02 16:09:09 +01002092 DeviceVector devices;
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002093 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
Eric Laurent97ac8712018-07-27 18:59:02 -07002094 const char *address = NULL;
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002095 if (policyMix != nullptr) {
François Gaffie11d30102018-11-02 16:09:09 +01002096 audio_devices_t newDeviceType;
Eric Laurent97ac8712018-07-27 18:59:02 -07002097 address = policyMix->mDeviceAddress.string();
Kevin Rocard153f92d2018-12-18 18:33:28 -08002098 if ((policyMix->mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie11d30102018-11-02 16:09:09 +01002099 newDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Kevin Rocard153f92d2018-12-18 18:33:28 -08002100 } else {
2101 newDeviceType = policyMix->mDeviceType;
Eric Laurent97ac8712018-07-27 18:59:02 -07002102 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08002103 sp device = mAvailableOutputDevices.getDevice(newDeviceType, String8(address),
2104 AUDIO_FORMAT_DEFAULT);
2105 ALOG_ASSERT(device, "%s: no device found t=%u, a=%s", __func__, newDeviceType, address);
2106 devices.add(device);
Eric Laurent97ac8712018-07-27 18:59:02 -07002107 }
2108
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002109 // requiresMuteCheck is false when we can bypass mute strategy.
2110 // It covers a common case when there is no materially active audio
2111 // and muting would result in unnecessary delay and dropped audio.
2112 const uint32_t outputLatencyMs = outputDesc->latency();
2113 bool requiresMuteCheck = outputDesc->isActive(outputLatencyMs * 2); // account for drain
Eric Laurent96d1dda2022-03-14 17:14:19 +01002114 bool wasLeUnicastActive = isLeUnicastActive();
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002115
Eric Laurente552edb2014-03-10 17:42:56 -07002116 // increment usage count for this stream on the requested output:
2117 // NOTE that the usage count is the same for duplicated output and hardware output which is
2118 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
Eric Laurent592dd7b2018-08-05 18:58:48 -07002119 outputDesc->setClientActive(client, true);
Eric Laurent97ac8712018-07-27 18:59:02 -07002120
2121 if (client->hasPreferredDevice(true)) {
François Gaffief96e5432019-04-09 17:13:56 +02002122 if (outputDesc->clientsList(true /*activeOnly*/).size() == 1 &&
2123 client->isPreferredDeviceForExclusiveUse()) {
2124 // Preferred device may be exclusive, use only if no other active clients on this output
2125 devices = DeviceVector(
2126 mAvailableOutputDevices.getDeviceFromId(client->preferredDeviceId()));
2127 } else {
2128 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
2129 }
François Gaffie11d30102018-11-02 16:09:09 +01002130 if (devices != outputDesc->devices()) {
François Gaffiec005e562018-11-06 15:04:49 +01002131 checkStrategyRoute(clientStrategy, outputDesc->mIoHandle);
Eric Laurent97ac8712018-07-27 18:59:02 -07002132 }
2133 }
Eric Laurente552edb2014-03-10 17:42:56 -07002134
François Gaffiec005e562018-11-06 15:04:49 +01002135 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07002136 selectOutputForMusicEffects();
2137 }
2138
François Gaffie1c878552018-11-22 16:53:21 +01002139 if (outputDesc->getActivityCount(clientVolSrc) == 1 || !devices.isEmpty()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08002140 // starting an output being rerouted?
François Gaffie11d30102018-11-02 16:09:09 +01002141 if (devices.isEmpty()) {
2142 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Eric Laurent275e8e92014-11-30 15:14:47 -08002143 }
François Gaffiec005e562018-11-06 15:04:49 +01002144 bool shouldWait =
2145 (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM)) ||
2146 followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_NOTIFICATION)) ||
2147 (beaconMuteLatency > 0));
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002148 uint32_t waitMs = beaconMuteLatency;
Eric Laurente552edb2014-03-10 17:42:56 -07002149 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01002150 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07002151 if (desc != outputDesc) {
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002152 // An output has a shared device if
2153 // - managed by the same hw module
2154 // - supports the currently selected device
2155 const bool sharedDevice = outputDesc->sharesHwModuleWith(desc)
François Gaffie11d30102018-11-02 16:09:09 +01002156 && (!desc->filterSupportedDevices(devices).isEmpty());
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002157
Eric Laurent77305a62016-07-25 16:39:22 -07002158 // force a device change if any other output is:
2159 // - managed by the same hw module
Jean-Michel Trivi4a5b4812018-02-08 17:22:32 +00002160 // - supports currently selected device
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002161 // - has a current device selection that differs from selected device.
Eric Laurent77305a62016-07-25 16:39:22 -07002162 // - has an active audio patch
Eric Laurente552edb2014-03-10 17:42:56 -07002163 // In this case, the audio HAL must receive the new device selection so that it can
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002164 // change the device currently selected by the other output.
2165 if (sharedDevice &&
François Gaffie11d30102018-11-02 16:09:09 +01002166 desc->devices() != devices &&
Eric Laurent77305a62016-07-25 16:39:22 -07002167 desc->getPatchHandle() != AUDIO_PATCH_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07002168 force = true;
2169 }
2170 // wait for audio on other active outputs to be presented when starting
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002171 // a notification so that audio focus effect can propagate, or that a mute/unmute
2172 // event occurred for beacon
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002173 const uint32_t latencyMs = desc->latency();
2174 const bool isActive = desc->isActive(latencyMs * 2); // account for drain
2175
2176 if (shouldWait && isActive && (waitMs < latencyMs)) {
2177 waitMs = latencyMs;
Eric Laurente552edb2014-03-10 17:42:56 -07002178 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002179
2180 // Require mute check if another output is on a shared device
2181 // and currently active to have proper drain and avoid pops.
2182 // Note restoring AudioTracks onto this output needs to invoke
2183 // a volume ramp if there is no mute.
2184 requiresMuteCheck |= sharedDevice && isActive;
Eric Laurente552edb2014-03-10 17:42:56 -07002185 }
2186 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002187
2188 const uint32_t muteWaitMs =
François Gaffie11d30102018-11-02 16:09:09 +01002189 setOutputDevices(outputDesc, devices, force, 0, NULL, requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07002190
Eric Laurente552edb2014-03-10 17:42:56 -07002191 // apply volume rules for current stream and device if necessary
François Gaffieaaac0fd2018-11-22 17:56:39 +01002192 auto &curves = getVolumeCurves(client->attributes());
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00002193 if (NO_ERROR != checkAndSetVolume(curves, client->volumeSource(),
François Gaffieaaac0fd2018-11-22 17:56:39 +01002194 curves.getVolumeIndex(outputDesc->devices().types()),
Eric Laurentc75307b2015-03-17 15:29:32 -07002195 outputDesc,
Francois Gaffied11442b2020-04-27 11:51:09 +02002196 outputDesc->devices().types(), 0 /*delay*/,
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00002197 outputDesc->useHwGain() /*force*/)) {
2198 // request AudioService to reinitialize the volume curves asynchronously
2199 ALOGE("checkAndSetVolume failed, requesting volume range init");
2200 mpClientInterface->onVolumeRangeInitRequest();
2201 };
Eric Laurente552edb2014-03-10 17:42:56 -07002202
2203 // update the outputs if starting an output with a stream that can affect notification
2204 // routing
2205 handleNotificationRoutingForStream(stream);
Eric Laurentc722f302014-12-10 11:21:49 -08002206
Eric Laurent2cbe89a2014-12-19 11:49:08 -08002207 // force reevaluating accessibility routing when ringtone or alarm starts
François Gaffiec005e562018-11-06 15:04:49 +01002208 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM))) {
Eric Laurent2cbe89a2014-12-19 11:49:08 -08002209 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
2210 }
Eric Laurentdc462862016-07-19 12:29:53 -07002211
2212 if (waitMs > muteWaitMs) {
2213 *delayMs = waitMs - muteWaitMs;
2214 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002215
2216 // FIXME: A device change (muteWaitMs > 0) likely introduces a volume change.
2217 // A volume change enacted by APM with 0 delay is not synchronous, as it goes
2218 // via AudioCommandThread to AudioFlinger. Hence it is possible that the volume
2219 // change occurs after the MixerThread starts and causes a stream volume
2220 // glitch.
2221 //
2222 // We do not introduce additional delay here.
Eric Laurente552edb2014-03-10 17:42:56 -07002223 }
Eric Laurentdc462862016-07-19 12:29:53 -07002224
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002225 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
jiabin9a3361e2019-10-01 09:38:30 -07002226 mEngine->getForceUse(
2227 AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
François Gaffiec005e562018-11-06 15:04:49 +01002228 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), true, outputDesc);
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002229 }
2230
Eric Laurent97ac8712018-07-27 18:59:02 -07002231 // Automatically enable the remote submix input when output is started on a re routing mix
2232 // of type MIX_TYPE_RECORDERS
jiabin9a3361e2019-10-01 09:38:30 -07002233 if (isSingleDeviceType(devices.types(), &audio_is_remote_submix_device) &&
2234 policyMix != NULL && policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002235 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2236 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2237 address,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002238 "remote-submix",
2239 AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07002240 }
2241
Eric Laurent96d1dda2022-03-14 17:14:19 +01002242 checkLeBroadcastRoutes(wasLeUnicastActive, outputDesc, *delayMs);
2243
Eric Laurente552edb2014-03-10 17:42:56 -07002244 return NO_ERROR;
2245}
2246
Eric Laurent96d1dda2022-03-14 17:14:19 +01002247void AudioPolicyManager::checkLeBroadcastRoutes(bool wasUnicastActive,
2248 sp<SwAudioOutputDescriptor> ignoredOutput, uint32_t delayMs) {
2249 bool isUnicastActive = isLeUnicastActive();
2250
2251 if (wasUnicastActive != isUnicastActive) {
2252 //reroute all outputs routed to LE broadcast if LE unicast activy changed on any output
2253 for (size_t i = 0; i < mOutputs.size(); i++) {
2254 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
2255 if (desc != ignoredOutput && desc->isActive()
2256 && ((isUnicastActive &&
2257 !desc->devices().
2258 getDevicesFromType(AUDIO_DEVICE_OUT_BLE_BROADCAST).isEmpty())
2259 || (wasUnicastActive &&
2260 !desc->devices().getDevicesFromTypes(
2261 getAudioDeviceOutLeAudioUnicastSet()).isEmpty()))) {
2262 DeviceVector newDevices = getNewOutputDevices(desc, false /*fromCache*/);
2263 bool force = desc->devices() != newDevices;
2264 setOutputDevices(desc, newDevices, force, delayMs);
2265 // re-apply device specific volume if not done by setOutputDevice()
2266 if (!force) {
2267 applyStreamVolumes(desc, newDevices.types(), delayMs);
2268 }
2269 }
2270 }
2271 }
2272}
2273
Eric Laurent8fc147b2018-07-22 19:13:55 -07002274status_t AudioPolicyManager::stopOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002275{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002276 ALOGV("%s portId %d", __FUNCTION__, portId);
2277
2278 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2279 if (outputDesc == 0) {
2280 ALOGW("stopOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002281 return BAD_VALUE;
2282 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002283 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002284
Eric Laurent97ac8712018-07-27 18:59:02 -07002285 ALOGV("stopOutput() output %d, stream %d, session %d",
2286 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurente552edb2014-03-10 17:42:56 -07002287
Eric Laurent97ac8712018-07-27 18:59:02 -07002288 status_t status = stopSource(outputDesc, client);
Eric Laurent3974e3b2017-12-07 17:58:43 -08002289
Eric Laurent733ce942017-12-07 12:18:25 -08002290 if (status == NO_ERROR ) {
2291 outputDesc->stop();
Eric Laurent3974e3b2017-12-07 17:58:43 -08002292 }
2293 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07002294}
2295
Eric Laurent97ac8712018-07-27 18:59:02 -07002296status_t AudioPolicyManager::stopSource(const sp<SwAudioOutputDescriptor>& outputDesc,
2297 const sp<TrackClientDescriptor>& client)
Eric Laurentc75307b2015-03-17 15:29:32 -07002298{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002299 // always handle stream stop, check which stream type is stopping
Eric Laurent97ac8712018-07-27 18:59:02 -07002300 audio_stream_type_t stream = client->stream();
François Gaffie1c878552018-11-22 16:53:21 +01002301 auto clientVolSrc = client->volumeSource();
Eric Laurent96d1dda2022-03-14 17:14:19 +01002302 bool wasLeUnicastActive = isLeUnicastActive();
Eric Laurent97ac8712018-07-27 18:59:02 -07002303
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002304 handleEventForBeacon(stream == AUDIO_STREAM_TTS ? STOPPING_BEACON : STOPPING_OUTPUT);
2305
François Gaffie1c878552018-11-22 16:53:21 +01002306 if (outputDesc->getActivityCount(clientVolSrc) > 0) {
2307 if (outputDesc->getActivityCount(clientVolSrc) == 1) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002308 // Automatically disable the remote submix input when output is stopped on a
2309 // re routing mix of type MIX_TYPE_RECORDERS
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002310 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
jiabin9a3361e2019-10-01 09:38:30 -07002311 if (isSingleDeviceType(
2312 outputDesc->devices().types(), &audio_is_remote_submix_device) &&
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002313 policyMix != nullptr &&
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002314 policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002315 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2316 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002317 policyMix->mDeviceAddress,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002318 "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07002319 }
2320 }
2321 bool forceDeviceUpdate = false;
2322 if (client->hasPreferredDevice(true)) {
François Gaffiec005e562018-11-06 15:04:49 +01002323 checkStrategyRoute(client->strategy(), AUDIO_IO_HANDLE_NONE);
Eric Laurent97ac8712018-07-27 18:59:02 -07002324 forceDeviceUpdate = true;
2325 }
2326
Eric Laurente552edb2014-03-10 17:42:56 -07002327 // decrement usage count of this stream on the output
Eric Laurent592dd7b2018-08-05 18:58:48 -07002328 outputDesc->setClientActive(client, false);
Paul McLeanaa981192015-03-21 09:55:15 -07002329
Eric Laurente552edb2014-03-10 17:42:56 -07002330 // store time at which the stream was stopped - see isStreamActive()
François Gaffie1c878552018-11-22 16:53:21 +01002331 if (outputDesc->getActivityCount(clientVolSrc) == 0 || forceDeviceUpdate) {
François Gaffiec005e562018-11-06 15:04:49 +01002332 outputDesc->setStopTime(client, systemTime());
François Gaffie11d30102018-11-02 16:09:09 +01002333 DeviceVector newDevices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Francois Gaffie3523ab32021-06-22 13:24:34 +02002334
2335 // If the routing does not change, if an output is routed on a device using HwGain
2336 // (aka setAudioPortConfig) and there are still active clients following different
2337 // volume group(s), force reapply volume
2338 bool requiresVolumeCheck = outputDesc->getActivityCount(clientVolSrc) == 0 &&
2339 outputDesc->useHwGain() && outputDesc->isAnyActive(VOLUME_SOURCE_NONE);
2340
Eric Laurente552edb2014-03-10 17:42:56 -07002341 // delay the device switch by twice the latency because stopOutput() is executed when
2342 // the track stop() command is received and at that time the audio track buffer can
2343 // still contain data that needs to be drained. The latency only covers the audio HAL
2344 // and kernel buffers. Also the latency does not always include additional delay in the
2345 // audio path (audio DSP, CODEC ...)
Francois Gaffie3523ab32021-06-22 13:24:34 +02002346 setOutputDevices(outputDesc, newDevices, false, outputDesc->latency()*2,
2347 nullptr, true /*requiresMuteCheck*/, requiresVolumeCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07002348
2349 // force restoring the device selection on other active outputs if it differs from the
2350 // one being selected for this output
Eric Laurent57de36c2016-09-28 16:59:11 -07002351 uint32_t delayMs = outputDesc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -07002352 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01002353 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07002354 if (desc != outputDesc &&
Eric Laurente552edb2014-03-10 17:42:56 -07002355 desc->isActive() &&
2356 outputDesc->sharesHwModuleWith(desc) &&
François Gaffie11d30102018-11-02 16:09:09 +01002357 (newDevices != desc->devices())) {
2358 DeviceVector newDevices2 = getNewOutputDevices(desc, false /*fromCache*/);
2359 bool force = desc->devices() != newDevices2;
Eric Laurentf3a5a602018-05-22 18:42:55 -07002360
François Gaffie11d30102018-11-02 16:09:09 +01002361 setOutputDevices(desc, newDevices2, force, delayMs);
2362
Eric Laurent57de36c2016-09-28 16:59:11 -07002363 // re-apply device specific volume if not done by setOutputDevice()
2364 if (!force) {
François Gaffie11d30102018-11-02 16:09:09 +01002365 applyStreamVolumes(desc, newDevices2.types(), delayMs);
Eric Laurent57de36c2016-09-28 16:59:11 -07002366 }
Eric Laurente552edb2014-03-10 17:42:56 -07002367 }
2368 }
2369 // update the outputs if stopping one with a stream that can affect notification routing
2370 handleNotificationRoutingForStream(stream);
2371 }
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002372
2373 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
2374 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Jean-Michel Trivi74e01fa2019-02-25 12:18:09 -08002375 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), false, outputDesc);
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002376 }
2377
François Gaffiec005e562018-11-06 15:04:49 +01002378 if (followsSameRouting(client->attributes(), attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07002379 selectOutputForMusicEffects();
2380 }
Eric Laurent96d1dda2022-03-14 17:14:19 +01002381
2382 checkLeBroadcastRoutes(wasLeUnicastActive, outputDesc, outputDesc->latency()*2);
2383
Eric Laurente552edb2014-03-10 17:42:56 -07002384 return NO_ERROR;
2385 } else {
Eric Laurentc75307b2015-03-17 15:29:32 -07002386 ALOGW("stopOutput() refcount is already 0");
Eric Laurente552edb2014-03-10 17:42:56 -07002387 return INVALID_OPERATION;
2388 }
2389}
2390
jiabinbce0c1d2020-10-05 11:20:18 -07002391bool AudioPolicyManager::releaseOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002392{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002393 ALOGV("%s portId %d", __FUNCTION__, portId);
2394
2395 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2396 if (outputDesc == 0) {
Andy Hung39efb7a2018-09-26 15:39:28 -07002397 // If an output descriptor is closed due to a device routing change,
2398 // then there are race conditions with releaseOutput from tracks
2399 // that may be destroyed (with no PlaybackThread) or a PlaybackThread
2400 // destroyed shortly thereafter.
2401 //
2402 // Here we just log a warning, instead of a fatal error.
Eric Laurent8fc147b2018-07-22 19:13:55 -07002403 ALOGW("releaseOutput() no output for client %d", portId);
jiabinbce0c1d2020-10-05 11:20:18 -07002404 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002405 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002406
2407 ALOGV("releaseOutput() %d", outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -07002408
Jaideep Sharma7bf382e2020-11-26 17:07:29 +05302409 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
2410 if (outputDesc->isClientActive(client)) {
2411 ALOGW("releaseOutput() inactivates portId %d in good faith", portId);
2412 stopOutput(portId);
2413 }
2414
Eric Laurent8fc147b2018-07-22 19:13:55 -07002415 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
2416 if (outputDesc->mDirectOpenCount <= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07002417 ALOGW("releaseOutput() invalid open count %d for output %d",
Eric Laurent8fc147b2018-07-22 19:13:55 -07002418 outputDesc->mDirectOpenCount, outputDesc->mIoHandle);
jiabinbce0c1d2020-10-05 11:20:18 -07002419 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002420 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002421 if (--outputDesc->mDirectOpenCount == 0) {
2422 closeOutput(outputDesc->mIoHandle);
Eric Laurentb52c1522014-05-20 11:27:36 -07002423 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07002424 }
2425 }
Jaideep Sharma7bf382e2020-11-26 17:07:29 +05302426
Andy Hung39efb7a2018-09-26 15:39:28 -07002427 outputDesc->removeClient(portId);
jiabinbce0c1d2020-10-05 11:20:18 -07002428 if (outputDesc->mPendingReopenToQueryProfiles && outputDesc->getClientCount() == 0) {
2429 // The output is pending reopened to query dynamic profiles and
2430 // there is no active clients
2431 closeOutput(outputDesc->mIoHandle);
2432 sp<SwAudioOutputDescriptor> newOutputDesc = openOutputWithProfileAndDevice(
2433 outputDesc->mProfile, mEngine->getActiveMediaDevices(mAvailableOutputDevices));
2434 if (newOutputDesc == nullptr) {
2435 ALOGE("%s failed to open output", __func__);
2436 }
2437 return true;
2438 }
2439 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002440}
2441
Eric Laurentcaf7f482014-11-25 17:50:47 -08002442status_t AudioPolicyManager::getInputForAttr(const audio_attributes_t *attr,
2443 audio_io_handle_t *input,
Mikhail Naganov2996f672019-04-18 12:29:59 -07002444 audio_unique_id_t riid,
Eric Laurentcaf7f482014-11-25 17:50:47 -08002445 audio_session_t session,
Svet Ganov3e5f14f2021-05-13 22:51:08 +00002446 const AttributionSourceState& attributionSource,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002447 const audio_config_base_t *config,
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002448 audio_input_flags_t flags,
Eric Laurent2ac76942017-06-22 17:17:09 -07002449 audio_port_handle_t *selectedDeviceId,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002450 input_type_t *inputType,
2451 audio_port_handle_t *portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002452{
François Gaffiec005e562018-11-06 15:04:49 +01002453 ALOGV("%s() source %d, sampling rate %d, format %#x, channel mask %#x, session %d, "
Eric Laurent2f2c1982021-06-02 14:03:11 +02002454 "flags %#x attributes=%s requested device ID %d",
2455 __func__, attr->source, config->sample_rate, config->format, config->channel_mask,
2456 session, flags, toString(*attr).c_str(), *selectedDeviceId);
Eric Laurente552edb2014-03-10 17:42:56 -07002457
Eric Laurentad2e7b92017-09-14 20:06:42 -07002458 status_t status = NO_ERROR;
Francois Gaffie716e1432019-01-14 16:58:59 +01002459 audio_attributes_t attributes = *attr;
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002460 sp<AudioPolicyMix> policyMix;
François Gaffie11d30102018-11-02 16:09:09 +01002461 sp<DeviceDescriptor> device;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002462 sp<AudioInputDescriptor> inputDesc;
2463 sp<RecordClientDescriptor> clientDesc;
2464 audio_port_handle_t requestedDeviceId = *selectedDeviceId;
Svet Ganov3e5f14f2021-05-13 22:51:08 +00002465 uid_t uid = VALUE_OR_RETURN_STATUS(aidl2legacy_int32_t_uid_t(attributionSource.uid));
Eric Laurent8f42ea12018-08-08 09:08:25 -07002466 bool isSoundTrigger;
Eric Laurent8f42ea12018-08-08 09:08:25 -07002467
2468 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
2469 if (*portId != AUDIO_PORT_HANDLE_NONE) {
2470 return INVALID_OPERATION;
2471 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08002472
Francois Gaffie716e1432019-01-14 16:58:59 +01002473 if (attr->source == AUDIO_SOURCE_DEFAULT) {
2474 attributes.source = AUDIO_SOURCE_MIC;
Eric Laurentfe231122017-11-17 17:48:06 -08002475 }
2476
Paul McLean466dc8e2015-04-17 13:15:36 -06002477 // Explicit routing?
Pattydd807582021-11-04 21:01:03 +08002478 sp<DeviceDescriptor> explicitRoutingDevice =
François Gaffie11d30102018-11-02 16:09:09 +01002479 mAvailableInputDevices.getDeviceFromId(*selectedDeviceId);
Paul McLean466dc8e2015-04-17 13:15:36 -06002480
Eric Laurentad2e7b92017-09-14 20:06:42 -07002481 // special case for mmap capture: if an input IO handle is specified, we reuse this input if
2482 // possible
2483 if ((flags & AUDIO_INPUT_FLAG_MMAP_NOIRQ) == AUDIO_INPUT_FLAG_MMAP_NOIRQ &&
2484 *input != AUDIO_IO_HANDLE_NONE) {
2485 ssize_t index = mInputs.indexOfKey(*input);
2486 if (index < 0) {
2487 ALOGW("getInputForAttr() unknown MMAP input %d", *input);
2488 status = BAD_VALUE;
2489 goto error;
2490 }
2491 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002492 RecordClientVector clients = inputDesc->getClientsForSession(session);
2493 if (clients.size() == 0) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07002494 ALOGW("getInputForAttr() unknown session %d on input %d", session, *input);
2495 status = BAD_VALUE;
2496 goto error;
2497 }
2498 // For MMAP mode, the first call to getInputForAttr() is made on behalf of audioflinger.
2499 // The second call is for the first active client and sets the UID. Any further call
Eric Laurent331679c2018-04-16 17:03:16 -07002500 // corresponds to a new client and is only permitted from the same UID.
2501 // If the first UID is silenced, allow a new UID connection and replace with new UID
Eric Laurent8f42ea12018-08-08 09:08:25 -07002502 if (clients.size() > 1) {
2503 for (const auto& client : clients) {
2504 // The client map is ordered by key values (portId) and portIds are allocated
2505 // incrementaly. So the first client in this list is the one opened by audio flinger
2506 // when the mmap stream is created and should be ignored as it does not correspond
2507 // to an actual client
2508 if (client == *clients.cbegin()) {
2509 continue;
2510 }
2511 if (uid != client->uid() && !client->isSilenced()) {
2512 ALOGW("getInputForAttr() bad uid %d for client %d uid %d",
2513 uid, client->portId(), client->uid());
2514 status = INVALID_OPERATION;
2515 goto error;
2516 }
Eric Laurent331679c2018-04-16 17:03:16 -07002517 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002518 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002519 *inputType = API_INPUT_LEGACY;
François Gaffie11d30102018-11-02 16:09:09 +01002520 device = inputDesc->getDevice();
Eric Laurentad2e7b92017-09-14 20:06:42 -07002521
Eric Laurentfecbceb2021-02-09 14:46:43 +01002522 ALOGV("%s reusing MMAP input %d for session %d", __FUNCTION__, *input, session);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002523 goto exit;
Eric Laurentad2e7b92017-09-14 20:06:42 -07002524 }
2525
2526 *input = AUDIO_IO_HANDLE_NONE;
2527 *inputType = API_INPUT_INVALID;
2528
Francois Gaffie716e1432019-01-14 16:58:59 +01002529 if (attributes.source == AUDIO_SOURCE_REMOTE_SUBMIX &&
2530 strncmp(attributes.tags, "addr=", strlen("addr=")) == 0) {
2531 status = mPolicyMixes.getInputMixForAttr(attributes, &policyMix);
Eric Laurentad2e7b92017-09-14 20:06:42 -07002532 if (status != NO_ERROR) {
jiabinc1de2df2019-05-07 14:26:40 -07002533 ALOGW("%s could not find input mix for attr %s",
2534 __func__, toString(attributes).c_str());
Eric Laurentad2e7b92017-09-14 20:06:42 -07002535 goto error;
François Gaffie036e1e92015-03-19 10:16:24 +01002536 }
jiabinc1de2df2019-05-07 14:26:40 -07002537 device = mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2538 String8(attr->tags + strlen("addr=")),
2539 AUDIO_FORMAT_DEFAULT);
2540 if (device == nullptr) {
Kevin Rocard04ed0462019-05-02 17:53:24 -07002541 ALOGW("%s could not find in Remote Submix device for source %d, tags %s",
jiabinc1de2df2019-05-07 14:26:40 -07002542 __func__, attributes.source, attributes.tags);
2543 status = BAD_VALUE;
2544 goto error;
2545 }
2546
Kevin Rocard25f9b052019-02-27 15:08:54 -08002547 if (is_mix_loopback_render(policyMix->mRouteFlags)) {
2548 *inputType = API_INPUT_MIX_PUBLIC_CAPTURE_PLAYBACK;
2549 } else {
2550 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
2551 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002552 } else {
François Gaffie11d30102018-11-02 16:09:09 +01002553 if (explicitRoutingDevice != nullptr) {
2554 device = explicitRoutingDevice;
Eric Laurent97ac8712018-07-27 18:59:02 -07002555 } else {
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01002556 // Prevent from storing invalid requested device id in clients
2557 requestedDeviceId = AUDIO_PORT_HANDLE_NONE;
yuanjiahsu0735bf32021-03-18 08:12:54 +08002558 device = mEngine->getInputDeviceForAttributes(attributes, uid, &policyMix);
yuanjiahsu4069d5d2021-04-19 07:54:27 +08002559 ALOGV_IF(device != nullptr, "%s found device type is 0x%X",
2560 __FUNCTION__, device->type());
Eric Laurent97ac8712018-07-27 18:59:02 -07002561 }
François Gaffie11d30102018-11-02 16:09:09 +01002562 if (device == nullptr) {
Francois Gaffie716e1432019-01-14 16:58:59 +01002563 ALOGW("getInputForAttr() could not find device for source %d", attributes.source);
Eric Laurentad2e7b92017-09-14 20:06:42 -07002564 status = BAD_VALUE;
2565 goto error;
Eric Laurent275e8e92014-11-30 15:14:47 -08002566 }
Alden DSouzab7d20782021-02-08 08:51:42 -08002567 if (device->type() == AUDIO_DEVICE_IN_ECHO_REFERENCE) {
2568 *inputType = API_INPUT_MIX_CAPTURE;
2569 } else if (policyMix) {
François Gaffie11d30102018-11-02 16:09:09 +01002570 ALOG_ASSERT(policyMix->mMixType == MIX_TYPE_RECORDERS, "Invalid Mix Type");
2571 // there is an external policy, but this input is attached to a mix of recorders,
2572 // meaning it receives audio injected into the framework, so the recorder doesn't
2573 // know about it and is therefore considered "legacy"
2574 *inputType = API_INPUT_LEGACY;
2575 } else if (audio_is_remote_submix_device(device->type())) {
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002576 *inputType = API_INPUT_MIX_CAPTURE;
François Gaffie11d30102018-11-02 16:09:09 +01002577 } else if (device->type() == AUDIO_DEVICE_IN_TELEPHONY_RX) {
Eric Laurent82db2692015-08-07 13:59:42 -07002578 *inputType = API_INPUT_TELEPHONY_RX;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002579 } else {
2580 *inputType = API_INPUT_LEGACY;
Eric Laurentc722f302014-12-10 11:21:49 -08002581 }
Ravi Kumar Alamandab367f5b2015-08-25 08:21:37 -07002582
Eric Laurent599c7582015-12-07 18:05:55 -08002583 }
2584
François Gaffiec005e562018-11-06 15:04:49 +01002585 *input = getInputForDevice(device, session, attributes, config, flags, policyMix);
Eric Laurent599c7582015-12-07 18:05:55 -08002586 if (*input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07002587 status = INVALID_OPERATION;
2588 goto error;
Eric Laurent599c7582015-12-07 18:05:55 -08002589 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08002590
Eric Laurent8f42ea12018-08-08 09:08:25 -07002591exit:
2592
François Gaffiec005e562018-11-06 15:04:49 +01002593 *selectedDeviceId = mAvailableInputDevices.contains(device) ?
2594 device->getId() : AUDIO_PORT_HANDLE_NONE;
Eric Laurent2ac76942017-06-22 17:17:09 -07002595
Francois Gaffie716e1432019-01-14 16:58:59 +01002596 isSoundTrigger = attributes.source == AUDIO_SOURCE_HOTWORD &&
Carter Hsud0cce2e2019-05-03 17:36:28 +08002597 mSoundTriggerSessions.indexOfKey(session) >= 0;
jiabin4ef93452019-09-10 14:29:54 -07002598 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002599
Mikhail Naganov2996f672019-04-18 12:29:59 -07002600 clientDesc = new RecordClientDescriptor(*portId, riid, uid, session, attributes, *config,
Francois Gaffie716e1432019-01-14 16:58:59 +01002601 requestedDeviceId, attributes.source, flags,
2602 isSoundTrigger);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002603 inputDesc = mInputs.valueFor(*input);
Andy Hung39efb7a2018-09-26 15:39:28 -07002604 inputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002605
2606 ALOGV("getInputForAttr() returns input %d type %d selectedDeviceId %d for port ID %d",
2607 *input, *inputType, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07002608
Eric Laurent599c7582015-12-07 18:05:55 -08002609 return NO_ERROR;
Eric Laurentad2e7b92017-09-14 20:06:42 -07002610
2611error:
Eric Laurentad2e7b92017-09-14 20:06:42 -07002612 return status;
Eric Laurent599c7582015-12-07 18:05:55 -08002613}
2614
2615
François Gaffie11d30102018-11-02 16:09:09 +01002616audio_io_handle_t AudioPolicyManager::getInputForDevice(const sp<DeviceDescriptor> &device,
Eric Laurent599c7582015-12-07 18:05:55 -08002617 audio_session_t session,
François Gaffiec005e562018-11-06 15:04:49 +01002618 const audio_attributes_t &attributes,
Eric Laurentfe231122017-11-17 17:48:06 -08002619 const audio_config_base_t *config,
Eric Laurent599c7582015-12-07 18:05:55 -08002620 audio_input_flags_t flags,
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002621 const sp<AudioPolicyMix> &policyMix)
Eric Laurent599c7582015-12-07 18:05:55 -08002622{
2623 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
François Gaffiec005e562018-11-06 15:04:49 +01002624 audio_source_t halInputSource = attributes.source;
Eric Laurent599c7582015-12-07 18:05:55 -08002625 bool isSoundTrigger = false;
2626
François Gaffiec005e562018-11-06 15:04:49 +01002627 if (attributes.source == AUDIO_SOURCE_HOTWORD) {
Eric Laurent599c7582015-12-07 18:05:55 -08002628 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
2629 if (index >= 0) {
2630 input = mSoundTriggerSessions.valueFor(session);
2631 isSoundTrigger = true;
2632 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_HW_HOTWORD);
2633 ALOGV("SoundTrigger capture on session %d input %d", session, input);
2634 } else {
2635 halInputSource = AUDIO_SOURCE_VOICE_RECOGNITION;
Eric Laurent5dbe4712014-09-19 19:04:57 -07002636 }
François Gaffiec005e562018-11-06 15:04:49 +01002637 } else if (attributes.source == AUDIO_SOURCE_VOICE_COMMUNICATION &&
Eric Laurentfe231122017-11-17 17:48:06 -08002638 audio_is_linear_pcm(config->format)) {
Haynes Mathew George851d3ff2017-06-19 20:01:57 -07002639 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_VOIP_TX);
Eric Laurent5dbe4712014-09-19 19:04:57 -07002640 }
2641
Carter Hsua3abb402021-10-26 11:11:20 +08002642 if (attributes.source == AUDIO_SOURCE_ULTRASOUND) {
2643 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_ULTRASOUND);
2644 }
2645
Andy Hungf129b032015-04-07 13:45:50 -07002646 // find a compatible input profile (not necessarily identical in parameters)
2647 sp<IOProfile> profile;
Eric Laurentfe231122017-11-17 17:48:06 -08002648 // sampling rate and flags may be updated by getInputProfile
2649 uint32_t profileSamplingRate = (config->sample_rate == 0) ?
2650 SAMPLE_RATE_HZ_DEFAULT : config->sample_rate;
Glenn Kasten730b9262018-03-29 15:01:26 -07002651 audio_format_t profileFormat;
Eric Laurentfe231122017-11-17 17:48:06 -08002652 audio_channel_mask_t profileChannelMask = config->channel_mask;
Andy Hungf129b032015-04-07 13:45:50 -07002653 audio_input_flags_t profileFlags = flags;
2654 for (;;) {
Glenn Kasten730b9262018-03-29 15:01:26 -07002655 profileFormat = config->format; // reset each time through loop, in case it is updated
François Gaffie11d30102018-11-02 16:09:09 +01002656 profile = getInputProfile(device, profileSamplingRate, profileFormat, profileChannelMask,
Andy Hungf129b032015-04-07 13:45:50 -07002657 profileFlags);
2658 if (profile != 0) {
2659 break; // success
Eric Laurent05067782016-06-01 18:27:28 -07002660 } else if (profileFlags & AUDIO_INPUT_FLAG_RAW) {
2661 profileFlags = (audio_input_flags_t) (profileFlags & ~AUDIO_INPUT_FLAG_RAW); // retry
Atneya Nair497fff12022-01-18 16:23:04 -05002662 } else if (profileFlags != AUDIO_INPUT_FLAG_NONE && audio_is_linear_pcm(config->format)) {
Andy Hungf129b032015-04-07 13:45:50 -07002663 profileFlags = AUDIO_INPUT_FLAG_NONE; // retry
2664 } else { // fail
François Gaffie11d30102018-11-02 16:09:09 +01002665 ALOGW("%s could not find profile for device %s, sampling rate %u, format %#x, "
Pattydd807582021-11-04 21:01:03 +08002666 "channel mask 0x%X, flags %#x", __func__, device->toString().c_str(),
François Gaffie11d30102018-11-02 16:09:09 +01002667 config->sample_rate, config->format, config->channel_mask, flags);
Eric Laurent599c7582015-12-07 18:05:55 -08002668 return input;
Eric Laurent5dbe4712014-09-19 19:04:57 -07002669 }
Eric Laurente552edb2014-03-10 17:42:56 -07002670 }
Glenn Kasten05ddca52016-02-11 08:17:12 -08002671 // Pick input sampling rate if not specified by client
Eric Laurentfe231122017-11-17 17:48:06 -08002672 uint32_t samplingRate = config->sample_rate;
Glenn Kasten05ddca52016-02-11 08:17:12 -08002673 if (samplingRate == 0) {
2674 samplingRate = profileSamplingRate;
2675 }
Eric Laurente552edb2014-03-10 17:42:56 -07002676
Eric Laurent322b4d22015-04-03 15:57:54 -07002677 if (profile->getModuleHandle() == 0) {
2678 ALOGE("getInputForAttr(): HW module %s not opened", profile->getModuleName());
Eric Laurent599c7582015-12-07 18:05:55 -08002679 return input;
Eric Laurentcf2c0212014-07-25 16:20:43 -07002680 }
2681
Eric Laurentec376dc2021-04-08 20:41:22 +02002682 // Reuse an already opened input if a client with the same session ID already exists
2683 // on that input
2684 for (size_t i = 0; i < mInputs.size(); i++) {
2685 sp <AudioInputDescriptor> desc = mInputs.valueAt(i);
2686 if (desc->mProfile != profile) {
2687 continue;
2688 }
2689 RecordClientVector clients = desc->clientsList();
2690 for (const auto &client : clients) {
2691 if (session == client->session()) {
2692 return desc->mIoHandle;
2693 }
2694 }
2695 }
2696
Eric Laurent3974e3b2017-12-07 17:58:43 -08002697 if (!profile->canOpenNewIo()) {
Eric Laurent4eb58f12018-12-07 16:41:02 -08002698 for (size_t i = 0; i < mInputs.size(); ) {
Eric Laurentc529cf62020-04-17 18:19:10 -07002699 sp<AudioInputDescriptor> desc = mInputs.valueAt(i);
Eric Laurent4eb58f12018-12-07 16:41:02 -08002700 if (desc->mProfile != profile) {
Carter Hsu9a645a92019-05-15 12:15:32 +08002701 i++;
Eric Laurent4eb58f12018-12-07 16:41:02 -08002702 continue;
2703 }
2704 // if sound trigger, reuse input if used by other sound trigger on same session
2705 // else
2706 // reuse input if active client app is not in IDLE state
2707 //
2708 RecordClientVector clients = desc->clientsList();
2709 bool doClose = false;
2710 for (const auto& client : clients) {
2711 if (isSoundTrigger != client->isSoundTrigger()) {
2712 continue;
2713 }
2714 if (client->isSoundTrigger()) {
2715 if (session == client->session()) {
2716 return desc->mIoHandle;
2717 }
2718 continue;
2719 }
2720 if (client->active() && client->appState() != APP_STATE_IDLE) {
2721 return desc->mIoHandle;
2722 }
2723 doClose = true;
2724 }
2725 if (doClose) {
2726 closeInput(desc->mIoHandle);
2727 } else {
2728 i++;
2729 }
2730 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002731 }
2732
Eric Laurentfe231122017-11-17 17:48:06 -08002733 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07002734
Eric Laurentfe231122017-11-17 17:48:06 -08002735 audio_config_t lConfig = AUDIO_CONFIG_INITIALIZER;
2736 lConfig.sample_rate = profileSamplingRate;
2737 lConfig.channel_mask = profileChannelMask;
2738 lConfig.format = profileFormat;
Eric Laurente3014102017-05-03 11:15:43 -07002739
François Gaffie11d30102018-11-02 16:09:09 +01002740 status_t status = inputDesc->open(&lConfig, device, halInputSource, profileFlags, &input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07002741
2742 // only accept input with the exact requested set of parameters
Eric Laurent599c7582015-12-07 18:05:55 -08002743 if (status != NO_ERROR || input == AUDIO_IO_HANDLE_NONE ||
Eric Laurentfe231122017-11-17 17:48:06 -08002744 (profileSamplingRate != lConfig.sample_rate) ||
2745 !audio_formats_match(profileFormat, lConfig.format) ||
2746 (profileChannelMask != lConfig.channel_mask)) {
2747 ALOGW("getInputForAttr() failed opening input: sampling rate %d"
Glenn Kasten49f36ba2017-12-06 13:02:02 -08002748 ", format %#x, channel mask %#x",
Eric Laurentfe231122017-11-17 17:48:06 -08002749 profileSamplingRate, profileFormat, profileChannelMask);
Eric Laurent599c7582015-12-07 18:05:55 -08002750 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfe231122017-11-17 17:48:06 -08002751 inputDesc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07002752 }
Eric Laurent599c7582015-12-07 18:05:55 -08002753 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07002754 }
2755
Eric Laurentc722f302014-12-10 11:21:49 -08002756 inputDesc->mPolicyMix = policyMix;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002757
Eric Laurent599c7582015-12-07 18:05:55 -08002758 addInput(input, inputDesc);
Eric Laurentb52c1522014-05-20 11:27:36 -07002759 mpClientInterface->onAudioPortListUpdate();
Paul McLean466dc8e2015-04-17 13:15:36 -06002760
Eric Laurent599c7582015-12-07 18:05:55 -08002761 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07002762}
2763
Eric Laurent4eb58f12018-12-07 16:41:02 -08002764status_t AudioPolicyManager::startInput(audio_port_handle_t portId)
Eric Laurentbb948092017-01-23 18:33:30 -08002765{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002766 ALOGV("%s portId %d", __FUNCTION__, portId);
2767
2768 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2769 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002770 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurentd52a28c2020-08-21 17:10:39 -07002771 return DEAD_OBJECT;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002772 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002773 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07002774 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002775 if (client->active()) {
2776 ALOGW("%s input %d client %d already started", __FUNCTION__, input, client->portId());
2777 return INVALID_OPERATION;
Eric Laurent4dc68062014-07-28 17:26:49 -07002778 }
2779
Eric Laurent8f42ea12018-08-08 09:08:25 -07002780 audio_session_t session = client->session();
2781
Eric Laurent4eb58f12018-12-07 16:41:02 -08002782 ALOGV("%s input:%d, session:%d)", __FUNCTION__, input, session);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002783
Eric Laurent4eb58f12018-12-07 16:41:02 -08002784 Vector<sp<AudioInputDescriptor>> activeInputs = mInputs.getActiveInputs();
Eric Laurent74708e72017-04-07 17:13:42 -07002785
Eric Laurent4eb58f12018-12-07 16:41:02 -08002786 status_t status = inputDesc->start();
2787 if (status != NO_ERROR) {
2788 return status;
Eric Laurent74708e72017-04-07 17:13:42 -07002789 }
Eric Laurente552edb2014-03-10 17:42:56 -07002790
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002791 // increment activity count before calling getNewInputDevice() below as only active sessions
Eric Laurent313d1e72016-01-29 09:56:57 -08002792 // are considered for device selection
Eric Laurent8f42ea12018-08-08 09:08:25 -07002793 inputDesc->setClientActive(client, true);
Eric Laurent313d1e72016-01-29 09:56:57 -08002794
Eric Laurent8f42ea12018-08-08 09:08:25 -07002795 // indicate active capture to sound trigger service if starting capture from a mic on
2796 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01002797 sp<DeviceDescriptor> device = getNewInputDevice(inputDesc);
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002798 if (device != nullptr) {
2799 status = setInputDevice(input, device, true /* force */);
2800 } else {
2801 ALOGW("%s no new input device can be found for descriptor %d",
2802 __FUNCTION__, inputDesc->getId());
2803 status = BAD_VALUE;
2804 }
Eric Laurente552edb2014-03-10 17:42:56 -07002805
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002806 if (status == NO_ERROR && inputDesc->activeCount() == 1) {
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002807 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002808 // if input maps to a dynamic policy with an activity listener, notify of state change
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002809 if ((policyMix != nullptr)
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002810 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
2811 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
Eric Laurent8f42ea12018-08-08 09:08:25 -07002812 MIX_STATE_MIXING);
Eric Laurent733ce942017-12-07 12:18:25 -08002813 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002814
François Gaffie11d30102018-11-02 16:09:09 +01002815 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
2816 if (primaryInputDevices.contains(device) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07002817 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 1) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07002818 mpClientInterface->setSoundTriggerCaptureState(true);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002819 }
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002820
Eric Laurent8f42ea12018-08-08 09:08:25 -07002821 // automatically enable the remote submix output when input is started if not
2822 // used by a policy mix of type MIX_TYPE_RECORDERS
2823 // For remote submix (a virtual device), we open only one input per capture request.
François Gaffie11d30102018-11-02 16:09:09 +01002824 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002825 String8 address = String8("");
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002826 if (policyMix == nullptr) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002827 address = String8("0");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002828 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
2829 address = policyMix->mDeviceAddress;
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002830 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07002831 if (address != "") {
2832 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2833 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002834 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurentc722f302014-12-10 11:21:49 -08002835 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07002836 }
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002837 } else if (status != NO_ERROR) {
2838 // Restore client activity state.
2839 inputDesc->setClientActive(client, false);
2840 inputDesc->stop();
Eric Laurente552edb2014-03-10 17:42:56 -07002841 }
2842
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002843 ALOGV("%s input %d source = %d status = %d exit",
2844 __FUNCTION__, input, client->source(), status);
Eric Laurente552edb2014-03-10 17:42:56 -07002845
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002846 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07002847}
2848
Eric Laurent8fc147b2018-07-22 19:13:55 -07002849status_t AudioPolicyManager::stopInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002850{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002851 ALOGV("%s portId %d", __FUNCTION__, portId);
2852
2853 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2854 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002855 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002856 return BAD_VALUE;
2857 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002858 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07002859 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002860 if (!client->active()) {
2861 ALOGW("%s input %d client %d already stopped", __FUNCTION__, input, client->portId());
Eric Laurente552edb2014-03-10 17:42:56 -07002862 return INVALID_OPERATION;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002863 }
Carter Hsue6139d52021-07-08 10:30:20 +08002864 auto old_source = inputDesc->source();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002865 inputDesc->setClientActive(client, false);
Paul McLean466dc8e2015-04-17 13:15:36 -06002866
Eric Laurent8f42ea12018-08-08 09:08:25 -07002867 inputDesc->stop();
2868 if (inputDesc->isActive()) {
Carter Hsue6139d52021-07-08 10:30:20 +08002869 auto current_source = inputDesc->source();
2870 setInputDevice(input, getNewInputDevice(inputDesc),
2871 old_source != current_source /* force */);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002872 } else {
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002873 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002874 // if input maps to a dynamic policy with an activity listener, notify of state change
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002875 if ((policyMix != nullptr)
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002876 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
2877 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
Eric Laurent8f42ea12018-08-08 09:08:25 -07002878 MIX_STATE_IDLE);
Eric Laurent84332aa2016-01-28 22:19:18 +00002879 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07002880
2881 // automatically disable the remote submix output when input is stopped if not
2882 // used by a policy mix of type MIX_TYPE_RECORDERS
François Gaffie11d30102018-11-02 16:09:09 +01002883 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002884 String8 address = String8("");
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002885 if (policyMix == nullptr) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002886 address = String8("0");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002887 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
2888 address = policyMix->mDeviceAddress;
Eric Laurent8f42ea12018-08-08 09:08:25 -07002889 }
2890 if (address != "") {
2891 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2892 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002893 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002894 }
2895 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07002896 resetInputDevice(input);
2897
2898 // indicate inactive capture to sound trigger service if stopping capture from a mic on
2899 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01002900 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
2901 if (primaryInputDevices.contains(inputDesc->getDevice()) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07002902 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07002903 mpClientInterface->setSoundTriggerCaptureState(false);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002904 }
2905 inputDesc->clearPreemptedSessions();
Eric Laurente552edb2014-03-10 17:42:56 -07002906 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002907 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07002908}
2909
Eric Laurent8fc147b2018-07-22 19:13:55 -07002910void AudioPolicyManager::releaseInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002911{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002912 ALOGV("%s portId %d", __FUNCTION__, portId);
2913
2914 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2915 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002916 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002917 return;
2918 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002919 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002920 audio_io_handle_t input = inputDesc->mIoHandle;
2921
Eric Laurent8f42ea12018-08-08 09:08:25 -07002922 ALOGV("%s %d", __FUNCTION__, input);
Paul McLean466dc8e2015-04-17 13:15:36 -06002923
Andy Hung39efb7a2018-09-26 15:39:28 -07002924 inputDesc->removeClient(portId);
Eric Laurent599c7582015-12-07 18:05:55 -08002925
Andy Hung39efb7a2018-09-26 15:39:28 -07002926 if (inputDesc->getClientCount() > 0) {
2927 ALOGV("%s(%d) %zu clients remaining", __func__, portId, inputDesc->getClientCount());
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002928 return;
2929 }
2930
Eric Laurent05b90f82014-08-27 15:32:29 -07002931 closeInput(input);
Eric Laurentb52c1522014-05-20 11:27:36 -07002932 mpClientInterface->onAudioPortListUpdate();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002933 ALOGV("%s exit", __FUNCTION__);
Eric Laurente552edb2014-03-10 17:42:56 -07002934}
2935
Eric Laurent8f42ea12018-08-08 09:08:25 -07002936void AudioPolicyManager::closeActiveClients(const sp<AudioInputDescriptor>& input)
Eric Laurent8fc147b2018-07-22 19:13:55 -07002937{
Eric Laurent8f42ea12018-08-08 09:08:25 -07002938 RecordClientVector clients = input->clientsList(true);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002939
2940 for (const auto& client : clients) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002941 closeClient(client->portId());
Eric Laurent8fc147b2018-07-22 19:13:55 -07002942 }
2943}
2944
Eric Laurent8f42ea12018-08-08 09:08:25 -07002945void AudioPolicyManager::closeClient(audio_port_handle_t portId)
2946{
2947 stopInput(portId);
2948 releaseInput(portId);
2949}
Eric Laurent8fc147b2018-07-22 19:13:55 -07002950
Eric Laurent0dd51852019-04-19 18:18:58 -07002951void AudioPolicyManager::checkCloseInputs() {
2952 // After connecting or disconnecting an input device, close input if:
2953 // - it has no client (was just opened to check profile) OR
2954 // - none of its supported devices are connected anymore OR
2955 // - one of its clients cannot be routed to one of its supported
2956 // devices anymore. Otherwise update device selection
2957 std::vector<audio_io_handle_t> inputsToClose;
2958 for (size_t i = 0; i < mInputs.size(); i++) {
2959 const sp<AudioInputDescriptor> input = mInputs.valueAt(i);
2960 if (input->clientsList().size() == 0
Eric Laurent85732f42020-03-19 11:31:10 -07002961 || !mAvailableInputDevices.containsAtLeastOne(input->supportedDevices())) {
Eric Laurent0dd51852019-04-19 18:18:58 -07002962 inputsToClose.push_back(mInputs.keyAt(i));
2963 } else {
2964 bool close = false;
2965 for (const auto& client : input->clientsList()) {
2966 sp<DeviceDescriptor> device =
yuanjiahsu0735bf32021-03-18 08:12:54 +08002967 mEngine->getInputDeviceForAttributes(client->attributes(), client->uid());
Eric Laurent0dd51852019-04-19 18:18:58 -07002968 if (!input->supportedDevices().contains(device)) {
2969 close = true;
2970 break;
2971 }
2972 }
2973 if (close) {
2974 inputsToClose.push_back(mInputs.keyAt(i));
2975 } else {
2976 setInputDevice(input->mIoHandle, getNewInputDevice(input));
2977 }
2978 }
2979 }
2980
2981 for (const audio_io_handle_t handle : inputsToClose) {
2982 ALOGV("%s closing input %d", __func__, handle);
2983 closeInput(handle);
Eric Laurent05b90f82014-08-27 15:32:29 -07002984 }
Eric Laurentd4692962014-05-05 18:13:44 -07002985}
2986
François Gaffie251c7f02018-11-07 10:41:08 +01002987void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream, int indexMin, int indexMax)
Eric Laurente552edb2014-03-10 17:42:56 -07002988{
2989 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08002990 if (indexMin < 0 || indexMax < 0) {
2991 ALOGE("%s for stream %d: invalid min %d or max %d", __func__, stream , indexMin, indexMax);
2992 return;
2993 }
Eric Laurentf5aa58d2019-02-22 18:20:11 -08002994 getVolumeCurves(stream).initVolume(indexMin, indexMax);
Eric Laurent28d09f02016-03-08 10:43:05 -08002995
2996 // initialize other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08002997 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
2998 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002999 continue;
3000 }
Eric Laurentf5aa58d2019-02-22 18:20:11 -08003001 getVolumeCurves((audio_stream_type_t)curStream).initVolume(indexMin, indexMax);
Eric Laurent223fd5c2014-11-11 13:43:36 -08003002 }
Eric Laurente552edb2014-03-10 17:42:56 -07003003}
3004
Eric Laurente0720872014-03-11 09:30:41 -07003005status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
François Gaffie53615e22015-03-19 09:24:12 +01003006 int index,
3007 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07003008{
François Gaffieaaac0fd2018-11-22 17:56:39 +01003009 auto attributes = mEngine->getAttributesForStreamType(stream);
Eric Laurent242a9f82020-03-23 15:57:04 -07003010 if (attributes == AUDIO_ATTRIBUTES_INITIALIZER) {
3011 ALOGW("%s: no group for stream %s, bailing out", __func__, toString(stream).c_str());
3012 return NO_ERROR;
3013 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01003014 ALOGV("%s: stream %s attributes=%s", __func__,
3015 toString(stream).c_str(), toString(attributes).c_str());
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003016 return setVolumeIndexForAttributes(attributes, index, device);
Eric Laurente552edb2014-03-10 17:42:56 -07003017}
3018
Eric Laurente0720872014-03-11 09:30:41 -07003019status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
François Gaffieaaac0fd2018-11-22 17:56:39 +01003020 int *index,
3021 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07003022{
François Gaffiec005e562018-11-06 15:04:49 +01003023 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
3024 // stream by the engine.
jiabin9a3361e2019-10-01 09:38:30 -07003025 DeviceTypeSet deviceTypes = {device};
Eric Laurent5a2b6292016-04-14 18:05:57 -07003026 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
jiabin9a3361e2019-10-01 09:38:30 -07003027 deviceTypes = mEngine->getOutputDevicesForStream(
3028 stream, true /*fromCache*/).types();
Eric Laurente552edb2014-03-10 17:42:56 -07003029 }
jiabin9a3361e2019-10-01 09:38:30 -07003030 return getVolumeIndex(getVolumeCurves(stream), *index, deviceTypes);
Eric Laurente552edb2014-03-10 17:42:56 -07003031}
3032
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003033status_t AudioPolicyManager::setVolumeIndexForAttributes(const audio_attributes_t &attributes,
François Gaffiecfe17322018-11-07 13:41:29 +01003034 int index,
3035 audio_devices_t device)
3036{
3037 // Get Volume group matching the Audio Attributes
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003038 auto group = mEngine->getVolumeGroupForAttributes(attributes);
3039 if (group == VOLUME_GROUP_NONE) {
3040 ALOGD("%s: no group matching with %s", __FUNCTION__, toString(attributes).c_str());
François Gaffiecfe17322018-11-07 13:41:29 +01003041 return BAD_VALUE;
3042 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003043 ALOGV("%s: group %d matching with %s", __FUNCTION__, group, toString(attributes).c_str());
François Gaffiecfe17322018-11-07 13:41:29 +01003044 status_t status = NO_ERROR;
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003045 IVolumeCurves &curves = getVolumeCurves(attributes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01003046 VolumeSource vs = toVolumeSource(group);
Eric Laurentf9cccec2022-11-16 19:12:00 +01003047 // AUDIO_STREAM_BLUETOOTH_SCO is only used for volume control so we remap
3048 // to AUDIO_STREAM_VOICE_CALL to match with relevant playback activity
3049 VolumeSource activityVs = (vs == toVolumeSource(AUDIO_STREAM_BLUETOOTH_SCO, false)) ?
3050 toVolumeSource(AUDIO_STREAM_VOICE_CALL, false) : vs;
François Gaffieaaac0fd2018-11-22 17:56:39 +01003051 product_strategy_t strategy = mEngine->getProductStrategyForAttributes(attributes);
3052
3053 status = setVolumeCurveIndex(index, device, curves);
3054 if (status != NO_ERROR) {
3055 ALOGE("%s failed to set curve index for group %d device 0x%X", __func__, group, device);
3056 return status;
3057 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003058
jiabin9a3361e2019-10-01 09:38:30 -07003059 DeviceTypeSet curSrcDevices;
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003060 auto curCurvAttrs = curves.getAttributes();
3061 if (!curCurvAttrs.empty() && curCurvAttrs.front() != defaultAttr) {
3062 auto attr = curCurvAttrs.front();
jiabin9a3361e2019-10-01 09:38:30 -07003063 curSrcDevices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false).types();
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003064 } else if (!curves.getStreamTypes().empty()) {
3065 auto stream = curves.getStreamTypes().front();
jiabin9a3361e2019-10-01 09:38:30 -07003066 curSrcDevices = mEngine->getOutputDevicesForStream(stream, false).types();
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003067 } else {
3068 ALOGE("%s: Invalid src %d: no valid attributes nor stream",__func__, vs);
3069 return BAD_VALUE;
3070 }
jiabin9a3361e2019-10-01 09:38:30 -07003071 audio_devices_t curSrcDevice = Volume::getDeviceForVolume(curSrcDevices);
3072 resetDeviceTypes(curSrcDevices, curSrcDevice);
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003073
François Gaffiecfe17322018-11-07 13:41:29 +01003074 // update volume on all outputs and streams matching the following:
3075 // - The requested stream (or a stream matching for volume control) is active on the output
3076 // - The device (or devices) selected by the engine for this stream includes
3077 // the requested device
3078 // - For non default requested device, currently selected device on the output is either the
3079 // requested device or one of the devices selected by the engine for this stream
3080 // - For default requested device (AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME), apply volume only if
3081 // no specific device volume value exists for currently selected device.
François Gaffieaaac0fd2018-11-22 17:56:39 +01003082 for (size_t i = 0; i < mOutputs.size(); i++) {
3083 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
jiabin9a3361e2019-10-01 09:38:30 -07003084 DeviceTypeSet curDevices = desc->devices().types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01003085
jiabin9a3361e2019-10-01 09:38:30 -07003086 if (curDevices.erase(AUDIO_DEVICE_OUT_SPEAKER_SAFE)) {
3087 curDevices.insert(AUDIO_DEVICE_OUT_SPEAKER);
Robert Lee5e66e792019-04-03 18:37:15 +08003088 }
Eric Laurentf9cccec2022-11-16 19:12:00 +01003089
3090 if (!(desc->isActive(activityVs) || isInCallOrScreening())) {
François Gaffieed91f582020-01-31 10:35:37 +01003091 continue;
3092 }
3093 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME &&
3094 curDevices.find(device) == curDevices.end()) {
3095 continue;
3096 }
3097 bool applyVolume = false;
3098 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
3099 curSrcDevices.insert(device);
3100 applyVolume = (curSrcDevices.find(
3101 Volume::getDeviceForVolume(curDevices)) != curSrcDevices.end());
3102 } else {
3103 applyVolume = !curves.hasVolumeIndexForDevice(curSrcDevice);
3104 }
3105 if (!applyVolume) {
3106 continue; // next output
3107 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01003108 // Inter / intra volume group priority management: Loop on strategies arranged by priority
3109 // If a higher priority strategy is active, and the output is routed to a device with a
3110 // HW Gain management, do not change the volume
François Gaffieaaac0fd2018-11-22 17:56:39 +01003111 if (desc->useHwGain()) {
François Gaffieed91f582020-01-31 10:35:37 +01003112 applyVolume = false;
Francois Gaffie593634d2021-06-22 13:31:31 +02003113 // If the volume source is active with higher priority source, ensure at least Sw Muted
3114 desc->setSwMute((index == 0), vs, curves.getStreamTypes(), curDevices, 0 /*delayMs*/);
François Gaffieaaac0fd2018-11-22 17:56:39 +01003115 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
3116 auto activeClients = desc->clientsList(true /*activeOnly*/, productStrategy,
3117 false /*preferredDevice*/);
3118 if (activeClients.empty()) {
3119 continue;
3120 }
3121 bool isPreempted = false;
3122 bool isHigherPriority = productStrategy < strategy;
3123 for (const auto &client : activeClients) {
Eric Laurentf9cccec2022-11-16 19:12:00 +01003124 if (isHigherPriority && (client->volumeSource() != activityVs)) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01003125 ALOGV("%s: Strategy=%d (\nrequester:\n"
3126 " group %d, volumeGroup=%d attributes=%s)\n"
3127 " higher priority source active:\n"
3128 " volumeGroup=%d attributes=%s) \n"
3129 " on output %zu, bailing out", __func__, productStrategy,
3130 group, group, toString(attributes).c_str(),
3131 client->volumeSource(), toString(client->attributes()).c_str(), i);
3132 applyVolume = false;
3133 isPreempted = true;
3134 break;
3135 }
3136 // However, continue for loop to ensure no higher prio clients running on output
Eric Laurentf9cccec2022-11-16 19:12:00 +01003137 if (client->volumeSource() == activityVs) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01003138 applyVolume = true;
3139 }
3140 }
3141 if (isPreempted || applyVolume) {
3142 break;
3143 }
3144 }
3145 if (!applyVolume) {
3146 continue; // next output
3147 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01003148 }
François Gaffieed91f582020-01-31 10:35:37 +01003149 //FIXME: workaround for truncated touch sounds
3150 // delayed volume change for system stream to be removed when the problem is
3151 // handled by system UI
3152 status_t volStatus = checkAndSetVolume(
3153 curves, vs, index, desc, curDevices,
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003154 ((vs == toVolumeSource(AUDIO_STREAM_SYSTEM, false))?
François Gaffieed91f582020-01-31 10:35:37 +01003155 TOUCH_SOUND_FIXED_DELAY_MS : 0));
3156 if (volStatus != NO_ERROR) {
3157 status = volStatus;
François Gaffieaaac0fd2018-11-22 17:56:39 +01003158 }
3159 }
François Gaffiecfe17322018-11-07 13:41:29 +01003160 mpClientInterface->onAudioVolumeGroupChanged(group, 0 /*flags*/);
3161 return status;
3162}
3163
François Gaffieaaac0fd2018-11-22 17:56:39 +01003164status_t AudioPolicyManager::setVolumeCurveIndex(int index,
François Gaffiecfe17322018-11-07 13:41:29 +01003165 audio_devices_t device,
3166 IVolumeCurves &volumeCurves)
3167{
3168 // VOICE_CALL stream has minVolumeIndex > 0 but can be muted directly by an
3169 // app that has MODIFY_PHONE_STATE permission.
François Gaffieaaac0fd2018-11-22 17:56:39 +01003170 bool hasVoice = hasVoiceStream(volumeCurves.getStreamTypes());
3171 if (((index < volumeCurves.getVolumeIndexMin()) && !(hasVoice && index == 0)) ||
François Gaffiecfe17322018-11-07 13:41:29 +01003172 (index > volumeCurves.getVolumeIndexMax())) {
3173 ALOGD("%s: wrong index %d min=%d max=%d", __FUNCTION__, index,
3174 volumeCurves.getVolumeIndexMin(), volumeCurves.getVolumeIndexMax());
3175 return BAD_VALUE;
3176 }
3177 if (!audio_is_output_device(device)) {
3178 return BAD_VALUE;
3179 }
3180
3181 // Force max volume if stream cannot be muted
3182 if (!volumeCurves.canBeMuted()) index = volumeCurves.getVolumeIndexMax();
3183
François Gaffieaaac0fd2018-11-22 17:56:39 +01003184 ALOGV("%s device %08x, index %d", __FUNCTION__ , device, index);
François Gaffiecfe17322018-11-07 13:41:29 +01003185 volumeCurves.addCurrentVolumeIndex(device, index);
3186 return NO_ERROR;
3187}
3188
3189status_t AudioPolicyManager::getVolumeIndexForAttributes(const audio_attributes_t &attr,
3190 int &index,
3191 audio_devices_t device)
3192{
3193 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
3194 // stream by the engine.
jiabin9a3361e2019-10-01 09:38:30 -07003195 DeviceTypeSet deviceTypes = {device};
François Gaffiecfe17322018-11-07 13:41:29 +01003196 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
Mikhail Naganovbb990f22022-06-15 00:46:43 +00003197 deviceTypes = mEngine->getOutputDevicesForAttributes(
jiabin9a3361e2019-10-01 09:38:30 -07003198 attr, nullptr, true /*fromCache*/).types();
François Gaffiecfe17322018-11-07 13:41:29 +01003199 }
jiabin9a3361e2019-10-01 09:38:30 -07003200 return getVolumeIndex(getVolumeCurves(attr), index, deviceTypes);
François Gaffiecfe17322018-11-07 13:41:29 +01003201}
3202
3203status_t AudioPolicyManager::getVolumeIndex(const IVolumeCurves &curves,
3204 int &index,
jiabin9a3361e2019-10-01 09:38:30 -07003205 const DeviceTypeSet& deviceTypes) const
François Gaffiecfe17322018-11-07 13:41:29 +01003206{
Mikhail Naganovbb990f22022-06-15 00:46:43 +00003207 if (!isSingleDeviceType(deviceTypes, audio_is_output_device)) {
François Gaffiecfe17322018-11-07 13:41:29 +01003208 return BAD_VALUE;
3209 }
jiabin9a3361e2019-10-01 09:38:30 -07003210 index = curves.getVolumeIndex(deviceTypes);
3211 ALOGV("%s: device %s index %d", __FUNCTION__, dumpDeviceTypes(deviceTypes).c_str(), index);
François Gaffiecfe17322018-11-07 13:41:29 +01003212 return NO_ERROR;
3213}
3214
3215status_t AudioPolicyManager::getMinVolumeIndexForAttributes(const audio_attributes_t &attr,
3216 int &index)
3217{
3218 index = getVolumeCurves(attr).getVolumeIndexMin();
3219 return NO_ERROR;
3220}
3221
3222status_t AudioPolicyManager::getMaxVolumeIndexForAttributes(const audio_attributes_t &attr,
3223 int &index)
3224{
3225 index = getVolumeCurves(attr).getVolumeIndexMax();
3226 return NO_ERROR;
3227}
3228
Eric Laurent36829f92017-04-07 19:04:42 -07003229audio_io_handle_t AudioPolicyManager::selectOutputForMusicEffects()
Eric Laurente552edb2014-03-10 17:42:56 -07003230{
3231 // select one output among several suitable for global effects.
3232 // The priority is as follows:
3233 // 1: An offloaded output. If the effect ends up not being offloadable,
3234 // AudioFlinger will invalidate the track and the offloaded output
3235 // will be closed causing the effect to be moved to a PCM output.
3236 // 2: A deep buffer output
Eric Laurent36829f92017-04-07 19:04:42 -07003237 // 3: The primary output
3238 // 4: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07003239
François Gaffiec005e562018-11-06 15:04:49 +01003240 DeviceVector devices = mEngine->getOutputDevicesForAttributes(
3241 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
François Gaffie11d30102018-11-02 16:09:09 +01003242 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07003243
Eric Laurent36829f92017-04-07 19:04:42 -07003244 if (outputs.size() == 0) {
3245 return AUDIO_IO_HANDLE_NONE;
3246 }
Eric Laurente552edb2014-03-10 17:42:56 -07003247
Eric Laurent36829f92017-04-07 19:04:42 -07003248 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
3249 bool activeOnly = true;
3250
3251 while (output == AUDIO_IO_HANDLE_NONE) {
3252 audio_io_handle_t outputOffloaded = AUDIO_IO_HANDLE_NONE;
3253 audio_io_handle_t outputDeepBuffer = AUDIO_IO_HANDLE_NONE;
3254 audio_io_handle_t outputPrimary = AUDIO_IO_HANDLE_NONE;
3255
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003256 for (audio_io_handle_t output : outputs) {
3257 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
Eric Laurent83d17c22019-04-02 17:10:01 -07003258 if (activeOnly && !desc->isActive(toVolumeSource(AUDIO_STREAM_MUSIC))) {
Eric Laurent36829f92017-04-07 19:04:42 -07003259 continue;
3260 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003261 ALOGV("selectOutputForMusicEffects activeOnly %d output %d flags 0x%08x",
3262 activeOnly, output, desc->mFlags);
Eric Laurent36829f92017-04-07 19:04:42 -07003263 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003264 outputOffloaded = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003265 }
3266 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003267 outputDeepBuffer = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003268 }
3269 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003270 outputPrimary = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003271 }
3272 }
3273 if (outputOffloaded != AUDIO_IO_HANDLE_NONE) {
3274 output = outputOffloaded;
3275 } else if (outputDeepBuffer != AUDIO_IO_HANDLE_NONE) {
3276 output = outputDeepBuffer;
3277 } else if (outputPrimary != AUDIO_IO_HANDLE_NONE) {
3278 output = outputPrimary;
3279 } else {
3280 output = outputs[0];
3281 }
3282 activeOnly = false;
3283 }
3284
3285 if (output != mMusicEffectOutput) {
Eric Laurent6c796322019-04-09 14:13:17 -07003286 mEffects.moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output);
Eric Laurent36829f92017-04-07 19:04:42 -07003287 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output);
3288 mMusicEffectOutput = output;
3289 }
3290
3291 ALOGV("selectOutputForMusicEffects selected output %d", output);
Eric Laurente552edb2014-03-10 17:42:56 -07003292 return output;
3293}
3294
Eric Laurent36829f92017-04-07 19:04:42 -07003295audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc __unused)
3296{
3297 return selectOutputForMusicEffects();
3298}
3299
Eric Laurente0720872014-03-11 09:30:41 -07003300status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07003301 audio_io_handle_t io,
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08003302 product_strategy_t strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07003303 int session,
3304 int id)
3305{
Eric Laurentb82e6b72019-11-22 17:25:04 -08003306 if (session != AUDIO_SESSION_DEVICE) {
3307 ssize_t index = mOutputs.indexOfKey(io);
Eric Laurente552edb2014-03-10 17:42:56 -07003308 if (index < 0) {
Eric Laurentb82e6b72019-11-22 17:25:04 -08003309 index = mInputs.indexOfKey(io);
3310 if (index < 0) {
3311 ALOGW("registerEffect() unknown io %d", io);
3312 return INVALID_OPERATION;
3313 }
Eric Laurente552edb2014-03-10 17:42:56 -07003314 }
3315 }
Eric Laurentbf8f69f2022-03-25 17:48:38 +01003316 bool isMusicEffect = (session != AUDIO_SESSION_OUTPUT_STAGE)
3317 && ((strategy == streamToStrategy(AUDIO_STREAM_MUSIC)
3318 || strategy == PRODUCT_STRATEGY_NONE));
3319 return mEffects.registerEffect(desc, io, session, id, isMusicEffect);
Eric Laurente552edb2014-03-10 17:42:56 -07003320}
3321
Eric Laurentc241b0d2018-11-28 09:08:49 -08003322status_t AudioPolicyManager::unregisterEffect(int id)
3323{
3324 if (mEffects.getEffect(id) == nullptr) {
3325 return INVALID_OPERATION;
3326 }
Eric Laurentc241b0d2018-11-28 09:08:49 -08003327 if (mEffects.isEffectEnabled(id)) {
3328 ALOGW("%s effect %d enabled", __FUNCTION__, id);
3329 setEffectEnabled(id, false);
3330 }
3331 return mEffects.unregisterEffect(id);
3332}
3333
3334status_t AudioPolicyManager::setEffectEnabled(int id, bool enabled)
3335{
3336 sp<EffectDescriptor> effect = mEffects.getEffect(id);
3337 if (effect == nullptr) {
3338 return INVALID_OPERATION;
3339 }
3340
3341 status_t status = mEffects.setEffectEnabled(id, enabled);
3342 if (status == NO_ERROR) {
3343 mInputs.trackEffectEnabled(effect, enabled);
3344 }
3345 return status;
3346}
3347
Eric Laurent6c796322019-04-09 14:13:17 -07003348
3349status_t AudioPolicyManager::moveEffectsToIo(const std::vector<int>& ids, audio_io_handle_t io)
3350{
3351 mEffects.moveEffects(ids, io);
3352 return NO_ERROR;
3353}
3354
Eric Laurentc75307b2015-03-17 15:29:32 -07003355bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
3356{
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003357 auto vs = toVolumeSource(stream, false);
3358 return vs != VOLUME_SOURCE_NONE ? mOutputs.isActive(vs, inPastMs) : false;
Eric Laurentc75307b2015-03-17 15:29:32 -07003359}
3360
3361bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream, uint32_t inPastMs) const
3362{
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003363 auto vs = toVolumeSource(stream, false);
3364 return vs != VOLUME_SOURCE_NONE ? mOutputs.isActiveRemotely(vs, inPastMs) : false;
Eric Laurentc75307b2015-03-17 15:29:32 -07003365}
3366
Eric Laurente0720872014-03-11 09:30:41 -07003367bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07003368{
3369 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003370 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08003371 if (inputDescriptor->isSourceActive(source)) {
Eric Laurente552edb2014-03-10 17:42:56 -07003372 return true;
3373 }
3374 }
3375 return false;
3376}
3377
Eric Laurent275e8e92014-11-30 15:14:47 -08003378// Register a list of custom mixes with their attributes and format.
3379// When a mix is registered, corresponding input and output profiles are
3380// added to the remote submix hw module. The profile contains only the
3381// parameters (sampling rate, format...) specified by the mix.
3382// The corresponding input remote submix device is also connected.
3383//
3384// When a remote submix device is connected, the address is checked to select the
3385// appropriate profile and the corresponding input or output stream is opened.
3386//
3387// When capture starts, getInputForAttr() will:
3388// - 1 look for a mix matching the address passed in attribtutes tags if any
3389// - 2 if none found, getDeviceForInputSource() will:
3390// - 2.1 look for a mix matching the attributes source
3391// - 2.2 if none found, default to device selection by policy rules
3392// At this time, the corresponding output remote submix device is also connected
3393// and active playback use cases can be transferred to this mix if needed when reconnecting
3394// after AudioTracks are invalidated
3395//
3396// When playback starts, getOutputForAttr() will:
3397// - 1 look for a mix matching the address passed in attribtutes tags if any
3398// - 2 if none found, look for a mix matching the attributes usage
3399// - 3 if none found, default to device and output selection by policy rules.
3400
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003401status_t AudioPolicyManager::registerPolicyMixes(const Vector<AudioMix>& mixes)
Eric Laurent275e8e92014-11-30 15:14:47 -08003402{
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003403 ALOGV("registerPolicyMixes() %zu mix(es)", mixes.size());
3404 status_t res = NO_ERROR;
Eric Laurentc209fe42020-06-05 18:11:23 -07003405 bool checkOutputs = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003406 sp<HwModule> rSubmixModule;
3407 // examine each mix's route type
3408 for (size_t i = 0; i < mixes.size(); i++) {
Eric Laurent97ac8712018-07-27 18:59:02 -07003409 AudioMix mix = mixes[i];
Kevin Rocard153f92d2018-12-18 18:33:28 -08003410 // Only capture of playback is allowed in LOOP_BACK & RENDER mode
3411 if (is_mix_loopback_render(mix.mRouteFlags) && mix.mMixType != MIX_TYPE_PLAYERS) {
3412 ALOGE("Unsupported Policy Mix %zu of %zu: "
3413 "Only capture of playback is allowed in LOOP_BACK & RENDER mode",
3414 i, mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003415 res = INVALID_OPERATION;
Eric Laurent275e8e92014-11-30 15:14:47 -08003416 break;
3417 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08003418 // LOOP_BACK and LOOP_BACK | RENDER have the same remote submix backend and are handled
3419 // in the same way.
Eric Laurent97ac8712018-07-27 18:59:02 -07003420 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003421 ALOGV("registerPolicyMixes() mix %zu of %zu is LOOP_BACK %d", i, mixes.size(),
3422 mix.mRouteFlags);
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003423 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003424 rSubmixModule = mHwModules.getModuleFromName(
3425 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
3426 if (rSubmixModule == 0) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003427 ALOGE("Unable to find audio module for submix, aborting mix %zu registration",
Mikhail Naganovd4120142017-12-06 15:49:22 -08003428 i);
3429 res = INVALID_OPERATION;
3430 break;
3431 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003432 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003433
Eric Laurent97ac8712018-07-27 18:59:02 -07003434 String8 address = mix.mDeviceAddress;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003435 audio_devices_t deviceTypeToMakeAvailable;
Eric Laurent97ac8712018-07-27 18:59:02 -07003436 if (mix.mMixType == MIX_TYPE_PLAYERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07003437 mix.mDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003438 deviceTypeToMakeAvailable = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
3439 } else {
3440 mix.mDeviceType = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
3441 deviceTypeToMakeAvailable = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Eric Laurent97ac8712018-07-27 18:59:02 -07003442 }
François Gaffie036e1e92015-03-19 10:16:24 +01003443
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003444 if (mPolicyMixes.registerMix(mix, 0 /*output desc*/) != NO_ERROR) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003445 ALOGE("Error registering mix %zu for address %s", i, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003446 res = INVALID_OPERATION;
3447 break;
3448 }
Eric Laurent97ac8712018-07-27 18:59:02 -07003449 audio_config_t outputConfig = mix.mFormat;
3450 audio_config_t inputConfig = mix.mFormat;
Eric Laurentc529cf62020-04-17 18:19:10 -07003451 // NOTE: audio flinger mixer does not support mono output: configure remote submix HAL
3452 // in stereo and let audio flinger do the channel conversion if needed.
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003453 outputConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
3454 inputConfig.channel_mask = AUDIO_CHANNEL_IN_STEREO;
jiabin5740f082019-08-19 15:08:30 -07003455 rSubmixModule->addOutputProfile(address.c_str(), &outputConfig,
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003456 AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address);
jiabin5740f082019-08-19 15:08:30 -07003457 rSubmixModule->addInputProfile(address.c_str(), &inputConfig,
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003458 AUDIO_DEVICE_IN_REMOTE_SUBMIX, address);
François Gaffie036e1e92015-03-19 10:16:24 +01003459
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003460 if ((res = setDeviceConnectionStateInt(deviceTypeToMakeAvailable,
jiabinc1de2df2019-05-07 14:26:40 -07003461 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
3462 address.string(), "remote-submix", AUDIO_FORMAT_DEFAULT)) != NO_ERROR) {
3463 ALOGE("Failed to set remote submix device available, type %u, address %s",
3464 mix.mDeviceType, address.string());
3465 break;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003466 }
Eric Laurent97ac8712018-07-27 18:59:02 -07003467 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
3468 String8 address = mix.mDeviceAddress;
Eric Laurent2c80be02019-01-23 18:06:37 -08003469 audio_devices_t type = mix.mDeviceType;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003470 ALOGV(" registerPolicyMixes() mix %zu of %zu is RENDER, dev=0x%X addr=%s",
Eric Laurent2c80be02019-01-23 18:06:37 -08003471 i, mixes.size(), type, address.string());
3472
3473 sp<DeviceDescriptor> device = mHwModules.getDeviceDescriptor(
3474 mix.mDeviceType, mix.mDeviceAddress,
3475 String8(), AUDIO_FORMAT_DEFAULT);
3476 if (device == nullptr) {
3477 res = INVALID_OPERATION;
3478 break;
3479 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003480
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003481 bool foundOutput = false;
Eric Laurentc529cf62020-04-17 18:19:10 -07003482 // First try to find an already opened output supporting the device
3483 for (size_t j = 0 ; j < mOutputs.size() && !foundOutput && res == NO_ERROR; j++) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003484 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurent2c80be02019-01-23 18:06:37 -08003485
Eric Laurentc529cf62020-04-17 18:19:10 -07003486 if (!desc->isDuplicated() && desc->supportedDevices().contains(device)) {
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003487 if (mPolicyMixes.registerMix(mix, desc) != NO_ERROR) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003488 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
3489 address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003490 res = INVALID_OPERATION;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003491 } else {
3492 foundOutput = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003493 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003494 }
3495 }
Eric Laurentc529cf62020-04-17 18:19:10 -07003496 // If no output found, try to find a direct output profile supporting the device
3497 for (size_t i = 0; i < mHwModules.size() && !foundOutput && res == NO_ERROR; i++) {
3498 sp<HwModule> module = mHwModules[i];
3499 for (size_t j = 0;
3500 j < module->getOutputProfiles().size() && !foundOutput && res == NO_ERROR;
3501 j++) {
3502 sp<IOProfile> profile = module->getOutputProfiles()[j];
3503 if (profile->isDirectOutput() && profile->supportsDevice(device)) {
3504 if (mPolicyMixes.registerMix(mix, nullptr) != NO_ERROR) {
3505 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
3506 address.string());
3507 res = INVALID_OPERATION;
3508 } else {
3509 foundOutput = true;
3510 }
3511 }
3512 }
3513 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003514 if (res != NO_ERROR) {
3515 ALOGE(" Error registering mix %zu for device 0x%X addr %s",
Eric Laurent2c80be02019-01-23 18:06:37 -08003516 i, type, address.string());
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003517 res = INVALID_OPERATION;
3518 break;
3519 } else if (!foundOutput) {
3520 ALOGE(" Output not found for mix %zu for device 0x%X addr %s",
Eric Laurent2c80be02019-01-23 18:06:37 -08003521 i, type, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003522 res = INVALID_OPERATION;
3523 break;
Eric Laurentc209fe42020-06-05 18:11:23 -07003524 } else {
3525 checkOutputs = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003526 }
Eric Laurentc722f302014-12-10 11:21:49 -08003527 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003528 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003529 if (res != NO_ERROR) {
3530 unregisterPolicyMixes(mixes);
Eric Laurentc209fe42020-06-05 18:11:23 -07003531 } else if (checkOutputs) {
3532 checkForDeviceAndOutputChanges();
3533 updateCallAndOutputRouting();
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003534 }
3535 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08003536}
3537
3538status_t AudioPolicyManager::unregisterPolicyMixes(Vector<AudioMix> mixes)
3539{
Eric Laurent7b279bb2015-12-14 10:18:23 -08003540 ALOGV("unregisterPolicyMixes() num mixes %zu", mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003541 status_t res = NO_ERROR;
Eric Laurentc209fe42020-06-05 18:11:23 -07003542 bool checkOutputs = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003543 sp<HwModule> rSubmixModule;
3544 // examine each mix's route type
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003545 for (const auto& mix : mixes) {
3546 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie036e1e92015-03-19 10:16:24 +01003547
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003548 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003549 rSubmixModule = mHwModules.getModuleFromName(
3550 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
3551 if (rSubmixModule == 0) {
3552 res = INVALID_OPERATION;
3553 continue;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003554 }
3555 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003556
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003557 String8 address = mix.mDeviceAddress;
Eric Laurent275e8e92014-11-30 15:14:47 -08003558
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003559 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003560 res = INVALID_OPERATION;
3561 continue;
3562 }
3563
Kevin Rocard04ed0462019-05-02 17:53:24 -07003564 for (auto device : {AUDIO_DEVICE_IN_REMOTE_SUBMIX, AUDIO_DEVICE_OUT_REMOTE_SUBMIX}) {
3565 if (getDeviceConnectionState(device, address.string()) ==
3566 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
3567 res = setDeviceConnectionStateInt(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
3568 address.string(), "remote-submix",
3569 AUDIO_FORMAT_DEFAULT);
3570 if (res != OK) {
3571 ALOGE("Error making RemoteSubmix device unavailable for mix "
3572 "with type %d, address %s", device, address.string());
3573 }
3574 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003575 }
jiabin5740f082019-08-19 15:08:30 -07003576 rSubmixModule->removeOutputProfile(address.c_str());
3577 rSubmixModule->removeInputProfile(address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003578
Kevin Rocard153f92d2018-12-18 18:33:28 -08003579 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003580 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003581 res = INVALID_OPERATION;
3582 continue;
Eric Laurentc209fe42020-06-05 18:11:23 -07003583 } else {
3584 checkOutputs = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003585 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003586 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003587 }
Eric Laurentc209fe42020-06-05 18:11:23 -07003588 if (res == NO_ERROR && checkOutputs) {
3589 checkForDeviceAndOutputChanges();
3590 updateCallAndOutputRouting();
3591 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003592 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08003593}
3594
Mikhail Naganov100f0122018-11-29 11:22:16 -08003595void AudioPolicyManager::dumpManualSurroundFormats(String8 *dst) const
3596{
3597 size_t i = 0;
3598 constexpr size_t audioFormatPrefixLen = sizeof("AUDIO_FORMAT_");
3599 for (const auto& fmt : mManualSurroundFormats) {
3600 if (i++ != 0) dst->append(", ");
3601 std::string sfmt;
3602 FormatConverter::toString(fmt, sfmt);
3603 dst->append(sfmt.size() >= audioFormatPrefixLen ?
3604 sfmt.c_str() + audioFormatPrefixLen - 1 : sfmt.c_str());
3605 }
3606}
3607
Eric Laurentc529cf62020-04-17 18:19:10 -07003608// Returns true if all devices types match the predicate and are supported by one HW module
3609bool AudioPolicyManager::areAllDevicesSupported(
jiabin6a02d532020-08-07 11:56:38 -07003610 const AudioDeviceTypeAddrVector& devices,
Eric Laurentc529cf62020-04-17 18:19:10 -07003611 std::function<bool(audio_devices_t)> predicate,
3612 const char *context) {
3613 for (size_t i = 0; i < devices.size(); i++) {
3614 sp<DeviceDescriptor> devDesc = mHwModules.getDeviceDescriptor(
jiabin0a488932020-08-07 17:32:40 -07003615 devices[i].mType, devices[i].getAddress(), String8(),
Eric Laurent0e26e3f2020-04-29 14:24:16 -07003616 AUDIO_FORMAT_DEFAULT, false /*allowToCreate*/, true /*matchAddress*/);
Eric Laurentc529cf62020-04-17 18:19:10 -07003617 if (devDesc == nullptr || (predicate != nullptr && !predicate(devices[i].mType))) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003618 ALOGE("%s: device type %#x address %s not supported or not match predicate",
jiabin0a488932020-08-07 17:32:40 -07003619 context, devices[i].mType, devices[i].getAddress());
Eric Laurentc529cf62020-04-17 18:19:10 -07003620 return false;
3621 }
3622 }
3623 return true;
3624}
3625
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003626status_t AudioPolicyManager::setUidDeviceAffinities(uid_t uid,
jiabin6a02d532020-08-07 11:56:38 -07003627 const AudioDeviceTypeAddrVector& devices) {
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003628 ALOGV("%s() uid=%d num devices %zu", __FUNCTION__, uid, devices.size());
Eric Laurentc529cf62020-04-17 18:19:10 -07003629 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
3630 return BAD_VALUE;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003631 }
3632 status_t res = mPolicyMixes.setUidDeviceAffinities(uid, devices);
Eric Laurentc529cf62020-04-17 18:19:10 -07003633 if (res != NO_ERROR) {
3634 ALOGE("%s() Could not set all device affinities for uid = %d", __FUNCTION__, uid);
3635 return res;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003636 }
Eric Laurentc529cf62020-04-17 18:19:10 -07003637
3638 checkForDeviceAndOutputChanges();
3639 updateCallAndOutputRouting();
3640
3641 return NO_ERROR;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003642}
3643
3644status_t AudioPolicyManager::removeUidDeviceAffinities(uid_t uid) {
3645 ALOGV("%s() uid=%d", __FUNCTION__, uid);
Oscar Azucena4b2a8212019-04-26 23:48:59 -07003646 status_t res = mPolicyMixes.removeUidDeviceAffinities(uid);
3647 if (res != NO_ERROR) {
Eric Laurentc529cf62020-04-17 18:19:10 -07003648 ALOGE("%s() Could not remove all device affinities for uid = %d",
Oscar Azucena4b2a8212019-04-26 23:48:59 -07003649 __FUNCTION__, uid);
3650 return INVALID_OPERATION;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003651 }
3652
Eric Laurentc529cf62020-04-17 18:19:10 -07003653 checkForDeviceAndOutputChanges();
3654 updateCallAndOutputRouting();
3655
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003656 return res;
3657}
3658
Eric Laurent2517af32020-11-25 15:31:27 +01003659
jiabin0a488932020-08-07 17:32:40 -07003660status_t AudioPolicyManager::setDevicesRoleForStrategy(product_strategy_t strategy,
3661 device_role_t role,
3662 const AudioDeviceTypeAddrVector &devices) {
3663 ALOGV("%s() strategy=%d role=%d %s", __func__, strategy, role,
3664 dumpAudioDeviceTypeAddrVector(devices).c_str());
Eric Laurentc529cf62020-04-17 18:19:10 -07003665
Eric Laurentc529cf62020-04-17 18:19:10 -07003666 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003667 return BAD_VALUE;
3668 }
jiabin0a488932020-08-07 17:32:40 -07003669 status_t status = mEngine->setDevicesRoleForStrategy(strategy, role, devices);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003670 if (status != NO_ERROR) {
jiabin0a488932020-08-07 17:32:40 -07003671 ALOGW("Engine could not set preferred devices %s for strategy %d role %d",
3672 dumpAudioDeviceTypeAddrVector(devices).c_str(), strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003673 return status;
3674 }
3675
3676 checkForDeviceAndOutputChanges();
Eric Laurent2517af32020-11-25 15:31:27 +01003677
3678 bool forceVolumeReeval = false;
3679 // FIXME: workaround for truncated touch sounds
3680 // to be removed when the problem is handled by system UI
3681 uint32_t delayMs = 0;
3682 if (strategy == mCommunnicationStrategy) {
3683 forceVolumeReeval = true;
3684 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
3685 updateInputRouting();
3686 }
3687 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003688
3689 return NO_ERROR;
3690}
3691
3692void AudioPolicyManager::updateCallAndOutputRouting(bool forceVolumeReeval, uint32_t delayMs)
3693{
3694 uint32_t waitMs = 0;
Eric Laurent96d1dda2022-03-14 17:14:19 +01003695 bool wasLeUnicastActive = isLeUnicastActive();
Francois Gaffie19fd6c52021-02-04 17:02:59 +01003696 if (updateCallRouting(true /*fromCache*/, delayMs, &waitMs) == NO_ERROR) {
Eric Laurentb36b4ac2020-08-21 12:50:41 -07003697 // Only apply special touch sound delay once
3698 delayMs = 0;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003699 }
3700 for (size_t i = 0; i < mOutputs.size(); i++) {
3701 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
3702 DeviceVector newDevices = getNewOutputDevices(outputDesc, true /*fromCache*/);
Francois Gaffie601801d2021-06-22 13:27:39 +02003703 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) ||
3704 (outputDesc != mPrimaryOutput && !isTelephonyRxOrTx(outputDesc))) {
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003705 // As done in setDeviceConnectionState, we could also fix default device issue by
3706 // preventing the force re-routing in case of default dev that distinguishes on address.
3707 // Let's give back to engine full device choice decision however.
Francois Gaffie601801d2021-06-22 13:27:39 +02003708 bool forceRouting = !newDevices.isEmpty();
3709 waitMs = setOutputDevices(outputDesc, newDevices, forceRouting, delayMs, nullptr,
3710 true /*requiresMuteCheck*/,
3711 !forceRouting /*requiresVolumeCheck*/);
Eric Laurentb36b4ac2020-08-21 12:50:41 -07003712 // Only apply special touch sound delay once
3713 delayMs = 0;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003714 }
3715 if (forceVolumeReeval && !newDevices.isEmpty()) {
3716 applyStreamVolumes(outputDesc, newDevices.types(), waitMs, true);
3717 }
3718 }
Eric Laurent96d1dda2022-03-14 17:14:19 +01003719 checkLeBroadcastRoutes(wasLeUnicastActive, nullptr, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003720}
3721
Eric Laurent2517af32020-11-25 15:31:27 +01003722void AudioPolicyManager::updateInputRouting() {
3723 for (const auto& activeDesc : mInputs.getActiveInputs()) {
Jaideep Sharma408349a2020-11-27 14:47:17 +05303724 // Skip for hotword recording as the input device switch
3725 // is handled within sound trigger HAL
3726 if (activeDesc->isSoundTrigger() && activeDesc->source() == AUDIO_SOURCE_HOTWORD) {
3727 continue;
3728 }
Eric Laurent2517af32020-11-25 15:31:27 +01003729 auto newDevice = getNewInputDevice(activeDesc);
3730 // Force new input selection if the new device can not be reached via current input
3731 if (activeDesc->mProfile->getSupportedDevices().contains(newDevice)) {
3732 setInputDevice(activeDesc->mIoHandle, newDevice);
3733 } else {
3734 closeInput(activeDesc->mIoHandle);
3735 }
3736 }
3737}
3738
jiabin0a488932020-08-07 17:32:40 -07003739status_t AudioPolicyManager::removeDevicesRoleForStrategy(product_strategy_t strategy,
3740 device_role_t role)
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003741{
Eric Laurentfecbceb2021-02-09 14:46:43 +01003742 ALOGV("%s() strategy=%d role=%d", __func__, strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003743
jiabin0a488932020-08-07 17:32:40 -07003744 status_t status = mEngine->removeDevicesRoleForStrategy(strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003745 if (status != NO_ERROR) {
Eric Laurent2517af32020-11-25 15:31:27 +01003746 ALOGV("Engine could not remove preferred device for strategy %d status %d",
3747 strategy, status);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003748 return status;
3749 }
3750
3751 checkForDeviceAndOutputChanges();
Eric Laurent2517af32020-11-25 15:31:27 +01003752
3753 bool forceVolumeReeval = false;
3754 // FIXME: workaround for truncated touch sounds
3755 // to be removed when the problem is handled by system UI
3756 uint32_t delayMs = 0;
3757 if (strategy == mCommunnicationStrategy) {
3758 forceVolumeReeval = true;
3759 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
3760 updateInputRouting();
3761 }
3762 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003763
3764 return NO_ERROR;
3765}
3766
jiabin0a488932020-08-07 17:32:40 -07003767status_t AudioPolicyManager::getDevicesForRoleAndStrategy(product_strategy_t strategy,
3768 device_role_t role,
3769 AudioDeviceTypeAddrVector &devices) {
3770 return mEngine->getDevicesForRoleAndStrategy(strategy, role, devices);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003771}
3772
Jiabin Huang3b98d322020-09-03 17:54:16 +00003773status_t AudioPolicyManager::setDevicesRoleForCapturePreset(
3774 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices) {
3775 ALOGV("%s() audioSource=%d role=%d %s", __func__, audioSource, role,
3776 dumpAudioDeviceTypeAddrVector(devices).c_str());
3777
Mikhail Naganov55773032020-10-01 15:08:13 -07003778 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003779 return BAD_VALUE;
3780 }
3781 status_t status = mEngine->setDevicesRoleForCapturePreset(audioSource, role, devices);
3782 ALOGW_IF(status != NO_ERROR,
3783 "Engine could not set preferred devices %s for audio source %d role %d",
3784 dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
3785
3786 return status;
3787}
3788
3789status_t AudioPolicyManager::addDevicesRoleForCapturePreset(
3790 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices) {
3791 ALOGV("%s() audioSource=%d role=%d %s", __func__, audioSource, role,
3792 dumpAudioDeviceTypeAddrVector(devices).c_str());
3793
Mikhail Naganov55773032020-10-01 15:08:13 -07003794 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003795 return BAD_VALUE;
3796 }
3797 status_t status = mEngine->addDevicesRoleForCapturePreset(audioSource, role, devices);
3798 ALOGW_IF(status != NO_ERROR,
3799 "Engine could not add preferred devices %s for audio source %d role %d",
3800 dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
3801
Eric Laurent2517af32020-11-25 15:31:27 +01003802 updateInputRouting();
Jiabin Huang3b98d322020-09-03 17:54:16 +00003803 return status;
3804}
3805
3806status_t AudioPolicyManager::removeDevicesRoleForCapturePreset(
3807 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector& devices)
3808{
3809 ALOGV("%s() audioSource=%d role=%d devices=%s", __func__, audioSource, role,
3810 dumpAudioDeviceTypeAddrVector(devices).c_str());
3811
Mikhail Naganov55773032020-10-01 15:08:13 -07003812 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003813 return BAD_VALUE;
3814 }
3815
3816 status_t status = mEngine->removeDevicesRoleForCapturePreset(
3817 audioSource, role, devices);
3818 ALOGW_IF(status != NO_ERROR,
3819 "Engine could not remove devices role (%d) for capture preset %d", role, audioSource);
3820
Eric Laurent2517af32020-11-25 15:31:27 +01003821 updateInputRouting();
Jiabin Huang3b98d322020-09-03 17:54:16 +00003822 return status;
3823}
3824
3825status_t AudioPolicyManager::clearDevicesRoleForCapturePreset(audio_source_t audioSource,
3826 device_role_t role) {
3827 ALOGV("%s() audioSource=%d role=%d", __func__, audioSource, role);
3828
3829 status_t status = mEngine->clearDevicesRoleForCapturePreset(audioSource, role);
3830 ALOGW_IF(status != NO_ERROR,
3831 "Engine could not clear devices role (%d) for capture preset %d", role, audioSource);
3832
Eric Laurent2517af32020-11-25 15:31:27 +01003833 updateInputRouting();
Jiabin Huang3b98d322020-09-03 17:54:16 +00003834 return status;
3835}
3836
3837status_t AudioPolicyManager::getDevicesForRoleAndCapturePreset(
3838 audio_source_t audioSource, device_role_t role, AudioDeviceTypeAddrVector &devices) {
3839 return mEngine->getDevicesForRoleAndCapturePreset(audioSource, role, devices);
3840}
3841
Oscar Azucena90e77632019-11-27 17:12:28 -08003842status_t AudioPolicyManager::setUserIdDeviceAffinities(int userId,
jiabin6a02d532020-08-07 11:56:38 -07003843 const AudioDeviceTypeAddrVector& devices) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01003844 ALOGV("%s() userId=%d num devices %zu", __func__, userId, devices.size());
Eric Laurentc529cf62020-04-17 18:19:10 -07003845 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
3846 return BAD_VALUE;
Oscar Azucena90e77632019-11-27 17:12:28 -08003847 }
Oscar Azucena90e77632019-11-27 17:12:28 -08003848 status_t status = mPolicyMixes.setUserIdDeviceAffinities(userId, devices);
3849 if (status != NO_ERROR) {
3850 ALOGE("%s() could not set device affinity for userId %d",
3851 __FUNCTION__, userId);
3852 return status;
3853 }
3854
3855 // reevaluate outputs for all devices
3856 checkForDeviceAndOutputChanges();
3857 updateCallAndOutputRouting();
3858
3859 return NO_ERROR;
3860}
3861
3862status_t AudioPolicyManager::removeUserIdDeviceAffinities(int userId) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01003863 ALOGV("%s() userId=%d", __FUNCTION__, userId);
Oscar Azucena90e77632019-11-27 17:12:28 -08003864 status_t status = mPolicyMixes.removeUserIdDeviceAffinities(userId);
3865 if (status != NO_ERROR) {
3866 ALOGE("%s() Could not remove all device affinities fo userId = %d",
3867 __FUNCTION__, userId);
3868 return status;
3869 }
3870
3871 // reevaluate outputs for all devices
3872 checkForDeviceAndOutputChanges();
3873 updateCallAndOutputRouting();
3874
3875 return NO_ERROR;
3876}
3877
Andy Hungc29d82b2018-10-05 12:23:17 -07003878void AudioPolicyManager::dump(String8 *dst) const
Eric Laurente552edb2014-03-10 17:42:56 -07003879{
Andy Hungc29d82b2018-10-05 12:23:17 -07003880 dst->appendFormat("\nAudioPolicyManager Dump: %p\n", this);
Mikhail Naganov0dbe87b2021-12-01 02:03:31 +00003881 dst->appendFormat(" Primary Output I/O handle: %d\n",
Eric Laurent87ffa392015-05-22 10:32:38 -07003882 hasPrimaryOutput() ? mPrimaryOutput->mIoHandle : AUDIO_IO_HANDLE_NONE);
Mikhail Naganov0d6a0332016-04-19 17:12:38 -07003883 std::string stateLiteral;
3884 AudioModeConverter::toString(mEngine->getPhoneState(), stateLiteral);
Andy Hungc29d82b2018-10-05 12:23:17 -07003885 dst->appendFormat(" Phone state: %s\n", stateLiteral.c_str());
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07003886 const char* forceUses[AUDIO_POLICY_FORCE_USE_CNT] = {
3887 "communications", "media", "record", "dock", "system",
3888 "HDMI system audio", "encoded surround output", "vibrate ringing" };
3889 for (audio_policy_force_use_t i = AUDIO_POLICY_FORCE_FOR_COMMUNICATION;
3890 i < AUDIO_POLICY_FORCE_USE_CNT; i = (audio_policy_force_use_t)((int)i + 1)) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08003891 audio_policy_forced_cfg_t forceUseValue = mEngine->getForceUse(i);
3892 dst->appendFormat(" Force use for %s: %d", forceUses[i], forceUseValue);
3893 if (i == AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND &&
3894 forceUseValue == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
3895 dst->append(" (MANUAL: ");
3896 dumpManualSurroundFormats(dst);
3897 dst->append(")");
3898 }
3899 dst->append("\n");
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07003900 }
Andy Hungc29d82b2018-10-05 12:23:17 -07003901 dst->appendFormat(" TTS output %savailable\n", mTtsOutputAvailable ? "" : "not ");
3902 dst->appendFormat(" Master mono: %s\n", mMasterMono ? "on" : "off");
Mikhail Naganovb3bcb4f2022-02-23 23:46:56 +00003903 dst->appendFormat(" Communication Strategy id: %d\n", mCommunnicationStrategy);
Mikhail Naganovb0fbc1b2023-04-28 13:06:32 -07003904 dst->appendFormat(" Config source: %s\n", mConfig->getSource().c_str());
Eric Laurent2517af32020-11-25 15:31:27 +01003905
Mikhail Naganov0f413b22021-12-02 05:29:27 +00003906 dst->append("\n");
3907 mAvailableOutputDevices.dump(dst, String8("Available output"), 1);
3908 dst->append("\n");
3909 mAvailableInputDevices.dump(dst, String8("Available input"), 1);
Mikhail Naganovb0fbc1b2023-04-28 13:06:32 -07003910 mHwModules.dump(dst);
Andy Hungc29d82b2018-10-05 12:23:17 -07003911 mOutputs.dump(dst);
3912 mInputs.dump(dst);
Mikhail Naganov0f413b22021-12-02 05:29:27 +00003913 mEffects.dump(dst, 1);
Andy Hungc29d82b2018-10-05 12:23:17 -07003914 mAudioPatches.dump(dst);
3915 mPolicyMixes.dump(dst);
3916 mAudioSources.dump(dst);
François Gaffiec005e562018-11-06 15:04:49 +01003917
Kevin Rocardb99cc752019-03-21 20:52:24 -07003918 dst->appendFormat(" AllowedCapturePolicies:\n");
3919 for (auto& policy : mAllowedCapturePolicies) {
3920 dst->appendFormat(" - uid=%d flag_mask=%#x\n", policy.first, policy.second);
3921 }
3922
François Gaffiec005e562018-11-06 15:04:49 +01003923 dst->appendFormat("\nPolicy Engine dump:\n");
3924 mEngine->dump(dst);
Andy Hungc29d82b2018-10-05 12:23:17 -07003925}
3926
3927status_t AudioPolicyManager::dump(int fd)
3928{
3929 String8 result;
3930 dump(&result);
Andy Hungbb54e202018-10-05 11:42:02 -07003931 write(fd, result.string(), result.size());
Eric Laurente552edb2014-03-10 17:42:56 -07003932 return NO_ERROR;
3933}
3934
Kevin Rocardb99cc752019-03-21 20:52:24 -07003935status_t AudioPolicyManager::setAllowedCapturePolicy(uid_t uid, audio_flags_mask_t capturePolicy)
3936{
3937 mAllowedCapturePolicies[uid] = capturePolicy;
3938 return NO_ERROR;
3939}
3940
Eric Laurente552edb2014-03-10 17:42:56 -07003941// This function checks for the parameters which can be offloaded.
3942// This can be enhanced depending on the capability of the DSP and policy
3943// of the system.
Eric Laurent90fe31c2020-11-26 20:06:35 +01003944audio_offload_mode_t AudioPolicyManager::getOffloadSupport(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07003945{
Eric Laurent90fe31c2020-11-26 20:06:35 +01003946 ALOGV("%s: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07003947 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurent90fe31c2020-11-26 20:06:35 +01003948 __func__, offloadInfo.sample_rate, offloadInfo.channel_mask,
Eric Laurente552edb2014-03-10 17:42:56 -07003949 offloadInfo.format,
3950 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
3951 offloadInfo.has_video);
3952
jiabin2b9d5a12021-12-10 01:06:29 +00003953 if (!isOffloadPossible(offloadInfo)) {
Eric Laurent90fe31c2020-11-26 20:06:35 +01003954 return AUDIO_OFFLOAD_NOT_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07003955 }
3956
3957 // See if there is a profile to support this.
3958 // AUDIO_DEVICE_NONE
François Gaffie11d30102018-11-02 16:09:09 +01003959 sp<IOProfile> profile = getProfileForOutput(DeviceVector() /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07003960 offloadInfo.sample_rate,
3961 offloadInfo.format,
3962 offloadInfo.channel_mask,
Michael Chana94fbb22018-04-24 14:31:19 +10003963 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD,
3964 true /* directOnly */);
Eric Laurent94365442021-01-08 18:36:05 +01003965 ALOGV("%s: profile %sfound%s", __func__, profile != nullptr ? "" : "NOT ",
3966 (profile != nullptr && (profile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD) != 0)
3967 ? ", supports gapless" : "");
Eric Laurent90fe31c2020-11-26 20:06:35 +01003968 if (profile == nullptr) {
3969 return AUDIO_OFFLOAD_NOT_SUPPORTED;
3970 }
3971 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD) != 0) {
3972 return AUDIO_OFFLOAD_GAPLESS_SUPPORTED;
3973 }
3974 return AUDIO_OFFLOAD_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07003975}
3976
Michael Chana94fbb22018-04-24 14:31:19 +10003977bool AudioPolicyManager::isDirectOutputSupported(const audio_config_base_t& config,
3978 const audio_attributes_t& attributes) {
3979 audio_output_flags_t output_flags = AUDIO_OUTPUT_FLAG_NONE;
François Gaffie58d4be52018-11-06 15:30:12 +01003980 audio_flags_to_audio_output_flags(attributes.flags, &output_flags);
Dorin Drimus9901eb02022-01-14 11:36:51 +00003981 DeviceVector outputDevices = mEngine->getOutputDevicesForAttributes(attributes);
3982 sp<IOProfile> profile = getProfileForOutput(outputDevices,
Michael Chana94fbb22018-04-24 14:31:19 +10003983 config.sample_rate,
3984 config.format,
3985 config.channel_mask,
3986 output_flags,
3987 true /* directOnly */);
3988 ALOGV("%s() profile %sfound with name: %s, "
3989 "sample rate: %u, format: 0x%x, channel_mask: 0x%x, output flags: 0x%x",
3990 __FUNCTION__, profile != 0 ? "" : "NOT ",
jiabin5740f082019-08-19 15:08:30 -07003991 (profile != 0 ? profile->getTagName().c_str() : "null"),
Michael Chana94fbb22018-04-24 14:31:19 +10003992 config.sample_rate, config.format, config.channel_mask, output_flags);
Dorin Drimusecc9f422022-03-09 17:57:40 +01003993
3994 // also try the MSD module if compatible profile not found
3995 if (profile == nullptr) {
3996 profile = getMsdProfileForOutput(outputDevices,
3997 config.sample_rate,
3998 config.format,
3999 config.channel_mask,
4000 output_flags,
4001 true /* directOnly */);
4002 ALOGV("%s() MSD profile %sfound with name: %s, "
4003 "sample rate: %u, format: 0x%x, channel_mask: 0x%x, output flags: 0x%x",
4004 __FUNCTION__, profile != 0 ? "" : "NOT ",
4005 (profile != 0 ? profile->getTagName().c_str() : "null"),
4006 config.sample_rate, config.format, config.channel_mask, output_flags);
4007 }
4008 return (profile != nullptr);
Michael Chana94fbb22018-04-24 14:31:19 +10004009}
4010
jiabin2b9d5a12021-12-10 01:06:29 +00004011bool AudioPolicyManager::isOffloadPossible(const audio_offload_info_t &offloadInfo,
4012 bool durationIgnored) {
4013 if (mMasterMono) {
4014 return false; // no offloading if mono is set.
4015 }
4016
4017 // Check if offload has been disabled
4018 if (property_get_bool("audio.offload.disable", false /* default_value */)) {
4019 ALOGV("%s: offload disabled by audio.offload.disable", __func__);
4020 return false;
4021 }
4022
4023 // Check if stream type is music, then only allow offload as of now.
4024 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
4025 {
4026 ALOGV("%s: stream_type != MUSIC, returning false", __func__);
4027 return false;
4028 }
4029
4030 //TODO: enable audio offloading with video when ready
4031 const bool allowOffloadWithVideo =
4032 property_get_bool("audio.offload.video", false /* default_value */);
4033 if (offloadInfo.has_video && !allowOffloadWithVideo) {
4034 ALOGV("%s: has_video == true, returning false", __func__);
4035 return false;
4036 }
4037
4038 //If duration is less than minimum value defined in property, return false
4039 const int min_duration_secs = property_get_int32(
4040 "audio.offload.min.duration.secs", -1 /* default_value */);
4041 if (!durationIgnored) {
4042 if (min_duration_secs >= 0) {
4043 if (offloadInfo.duration_us < min_duration_secs * 1000000LL) {
4044 ALOGV("%s: Offload denied by duration < audio.offload.min.duration.secs(=%d)",
4045 __func__, min_duration_secs);
4046 return false;
4047 }
4048 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
4049 ALOGV("%s: Offload denied by duration < default min(=%u)",
4050 __func__, OFFLOAD_DEFAULT_MIN_DURATION_SECS);
4051 return false;
4052 }
4053 }
4054
4055 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
4056 // creating an offloaded track and tearing it down immediately after start when audioflinger
4057 // detects there is an active non offloadable effect.
4058 // FIXME: We should check the audio session here but we do not have it in this context.
4059 // This may prevent offloading in rare situations where effects are left active by apps
4060 // in the background.
4061 if (mEffects.isNonOffloadableEffectEnabled()) {
4062 return false;
4063 }
4064
4065 return true;
4066}
4067
4068audio_direct_mode_t AudioPolicyManager::getDirectPlaybackSupport(const audio_attributes_t *attr,
4069 const audio_config_t *config) {
4070 audio_offload_info_t offloadInfo = AUDIO_INFO_INITIALIZER;
4071 offloadInfo.format = config->format;
4072 offloadInfo.sample_rate = config->sample_rate;
4073 offloadInfo.channel_mask = config->channel_mask;
4074 offloadInfo.stream_type = mEngine->getStreamTypeForAttributes(*attr);
4075 offloadInfo.has_video = false;
4076 offloadInfo.is_streaming = false;
4077 const bool offloadPossible = isOffloadPossible(offloadInfo, true /*durationIgnored*/);
4078
4079 audio_direct_mode_t directMode = AUDIO_DIRECT_NOT_SUPPORTED;
4080 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
4081 audio_flags_to_audio_output_flags(attr->flags, &flags);
4082 // only retain flags that will drive compressed offload or passthrough
4083 uint32_t relevantFlags = AUDIO_OUTPUT_FLAG_HW_AV_SYNC;
4084 if (offloadPossible) {
4085 relevantFlags |= AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD;
4086 }
4087 flags = (audio_output_flags_t)((flags & relevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
4088
Dorin Drimusfae3c642022-03-17 18:36:30 +01004089 DeviceVector engineOutputDevices = mEngine->getOutputDevicesForAttributes(*attr);
jiabin2b9d5a12021-12-10 01:06:29 +00004090 for (const auto& hwModule : mHwModules) {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004091 DeviceVector outputDevices = engineOutputDevices;
4092 // the MSD module checks for different conditions and output devices
4093 if (strcmp(hwModule->getName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0) {
4094 if (!msdHasPatchesToAllDevices(engineOutputDevices.toTypeAddrVector())) {
4095 continue;
4096 }
4097 outputDevices = getMsdAudioOutDevices();
4098 }
jiabin2b9d5a12021-12-10 01:06:29 +00004099 for (const auto& curProfile : hwModule->getOutputProfiles()) {
jiabinc8f7dfc2022-01-06 18:42:08 +00004100 if (!curProfile->isCompatibleProfile(outputDevices,
jiabin2b9d5a12021-12-10 01:06:29 +00004101 config->sample_rate, nullptr /*updatedSamplingRate*/,
4102 config->format, nullptr /*updatedFormat*/,
4103 config->channel_mask, nullptr /*updatedChannelMask*/,
4104 flags)) {
4105 continue;
4106 }
4107 // reject profiles not corresponding to a device currently available
4108 if (!mAvailableOutputDevices.containsAtLeastOne(curProfile->getSupportedDevices())) {
4109 continue;
4110 }
4111 if ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)
4112 != AUDIO_OUTPUT_FLAG_NONE) {
jiabinc6132d62022-01-01 07:36:31 +00004113 if ((directMode & AUDIO_DIRECT_OFFLOAD_GAPLESS_SUPPORTED)
jiabin2b9d5a12021-12-10 01:06:29 +00004114 != AUDIO_DIRECT_NOT_SUPPORTED) {
4115 // Already reports offload gapless supported. No need to report offload support.
4116 continue;
4117 }
4118 if ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD)
4119 != AUDIO_OUTPUT_FLAG_NONE) {
4120 // If offload gapless is reported, no need to report offload support.
4121 directMode = (audio_direct_mode_t) ((directMode &
4122 ~AUDIO_DIRECT_OFFLOAD_SUPPORTED) |
4123 AUDIO_DIRECT_OFFLOAD_GAPLESS_SUPPORTED);
4124 } else {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004125 directMode = (audio_direct_mode_t)(directMode | AUDIO_DIRECT_OFFLOAD_SUPPORTED);
jiabin2b9d5a12021-12-10 01:06:29 +00004126 }
4127 } else {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004128 directMode = (audio_direct_mode_t) (directMode | AUDIO_DIRECT_BITSTREAM_SUPPORTED);
jiabin2b9d5a12021-12-10 01:06:29 +00004129 }
4130 }
4131 }
4132 return directMode;
4133}
4134
Dorin Drimusf2196d82022-01-03 12:11:18 +01004135status_t AudioPolicyManager::getDirectProfilesForAttributes(const audio_attributes_t* attr,
4136 AudioProfileVector& audioProfilesVector) {
Dorin Drimus76e69572022-09-23 15:28:51 +00004137 if (mEffects.isNonOffloadableEffectEnabled()) {
4138 return OK;
4139 }
Dorin Drimusf2196d82022-01-03 12:11:18 +01004140 AudioDeviceTypeAddrVector devices;
Andy Hung6d23c0f2022-02-16 09:37:15 -08004141 status_t status = getDevicesForAttributes(*attr, &devices, false /* forVolume */);
Dorin Drimusf2196d82022-01-03 12:11:18 +01004142 if (status != OK) {
4143 return status;
4144 }
4145 ALOGV("%s: found %zu output devices for attributes.", __func__, devices.size());
4146 if (devices.empty()) {
4147 return OK; // no output devices for the attributes
4148 }
4149
4150 for (const auto& hwModule : mHwModules) {
Dorin Drimus94d94412022-02-02 09:05:02 +01004151 // the MSD module checks for different conditions
4152 if (strcmp(hwModule->getName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0) {
4153 continue;
4154 }
4155 for (const auto& outputProfile : hwModule->getOutputProfiles()) {
4156 if (!outputProfile->asAudioPort()->isDirectOutput()) {
Dorin Drimusf2196d82022-01-03 12:11:18 +01004157 continue;
4158 }
Dorin Drimus94d94412022-02-02 09:05:02 +01004159 // allow only profiles that support all the available and routed devices
4160 if (outputProfile->getSupportedDevices().getDevicesFromDeviceTypeAddrVec(devices).size()
Dorin Drimusf2196d82022-01-03 12:11:18 +01004161 != devices.size()) {
4162 continue;
4163 }
Dorin Drimus94d94412022-02-02 09:05:02 +01004164 audioProfilesVector.addAllValidProfiles(
4165 outputProfile->asAudioPort()->getAudioProfiles());
Dorin Drimusf2196d82022-01-03 12:11:18 +01004166 }
4167 }
Dorin Drimus94d94412022-02-02 09:05:02 +01004168
4169 // add the direct profiles from MSD if present and has audio patches to all the output(s)
4170 const auto& msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
4171 if (msdModule != nullptr) {
4172 if (msdHasPatchesToAllDevices(devices)) {
4173 ALOGV("%s: MSD audio patches set to all output devices.", __func__);
4174 for (const auto& outputProfile : msdModule->getOutputProfiles()) {
4175 if (!outputProfile->asAudioPort()->isDirectOutput()) {
4176 continue;
4177 }
4178 audioProfilesVector.addAllValidProfiles(
4179 outputProfile->asAudioPort()->getAudioProfiles());
4180 }
4181 } else {
4182 ALOGV("%s: MSD audio patches NOT set to all output devices.", __func__);
4183 }
4184 }
4185
Dorin Drimusf2196d82022-01-03 12:11:18 +01004186 return NO_ERROR;
4187}
4188
Eric Laurent6a94d692014-05-20 11:18:06 -07004189status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
4190 audio_port_type_t type,
4191 unsigned int *num_ports,
jiabin19cdba52020-11-24 11:28:58 -08004192 struct audio_port_v7 *ports,
Eric Laurent6a94d692014-05-20 11:18:06 -07004193 unsigned int *generation)
4194{
jiabin19cdba52020-11-24 11:28:58 -08004195 if (num_ports == nullptr || (*num_ports != 0 && ports == nullptr) ||
4196 generation == nullptr) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004197 return BAD_VALUE;
4198 }
4199 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
jiabin19cdba52020-11-24 11:28:58 -08004200 if (ports == nullptr) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004201 *num_ports = 0;
4202 }
4203
4204 size_t portsWritten = 0;
4205 size_t portsMax = *num_ports;
4206 *num_ports = 0;
4207 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07004208 // do not report devices with type AUDIO_DEVICE_IN_STUB or AUDIO_DEVICE_OUT_STUB
4209 // as they are used by stub HALs by convention
Eric Laurent6a94d692014-05-20 11:18:06 -07004210 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004211 for (const auto& dev : mAvailableOutputDevices) {
4212 if (dev->type() == AUDIO_DEVICE_OUT_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07004213 continue;
4214 }
4215 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004216 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07004217 }
4218 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07004219 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004220 }
4221 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004222 for (const auto& dev : mAvailableInputDevices) {
4223 if (dev->type() == AUDIO_DEVICE_IN_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07004224 continue;
4225 }
4226 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004227 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07004228 }
4229 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07004230 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004231 }
4232 }
4233 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
4234 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
4235 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
4236 mInputs[i]->toAudioPort(&ports[portsWritten++]);
4237 }
4238 *num_ports += mInputs.size();
4239 }
4240 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent84c70242014-06-23 08:46:27 -07004241 size_t numOutputs = 0;
4242 for (size_t i = 0; i < mOutputs.size(); i++) {
4243 if (!mOutputs[i]->isDuplicated()) {
4244 numOutputs++;
4245 if (portsWritten < portsMax) {
4246 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
4247 }
4248 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004249 }
Eric Laurent84c70242014-06-23 08:46:27 -07004250 *num_ports += numOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07004251 }
4252 }
4253 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07004254 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
Eric Laurent6a94d692014-05-20 11:18:06 -07004255 return NO_ERROR;
4256}
4257
Mikhail Naganov15f46712023-03-23 14:52:15 -07004258status_t AudioPolicyManager::listDeclaredDevicePorts(media::AudioPortRole role,
4259 std::vector<media::AudioPortFw>* _aidl_return) {
4260 auto pushPort = [&](const sp<DeviceDescriptor>& dev) -> status_t {
4261 audio_port_v7 port;
4262 dev->toAudioPort(&port);
4263 auto aidlPort = VALUE_OR_RETURN_STATUS(legacy2aidl_audio_port_v7_AudioPortFw(port));
4264 _aidl_return->push_back(std::move(aidlPort));
4265 return OK;
4266 };
4267
Mikhail Naganovb0fbc1b2023-04-28 13:06:32 -07004268 for (const auto& module : mHwModules) {
Mikhail Naganov15f46712023-03-23 14:52:15 -07004269 for (const auto& dev : module->getDeclaredDevices()) {
4270 if (role == media::AudioPortRole::NONE ||
4271 ((role == media::AudioPortRole::SOURCE)
4272 == audio_is_input_device(dev->type()))) {
4273 RETURN_STATUS_IF_ERROR(pushPort(dev));
4274 }
4275 }
4276 }
4277 return OK;
4278}
4279
jiabin19cdba52020-11-24 11:28:58 -08004280status_t AudioPolicyManager::getAudioPort(struct audio_port_v7 *port)
Eric Laurent6a94d692014-05-20 11:18:06 -07004281{
Eric Laurent99fcae42018-05-17 16:59:18 -07004282 if (port == nullptr || port->id == AUDIO_PORT_HANDLE_NONE) {
4283 return BAD_VALUE;
4284 }
4285 sp<DeviceDescriptor> dev = mAvailableOutputDevices.getDeviceFromId(port->id);
4286 if (dev != 0) {
4287 dev->toAudioPort(port);
4288 return NO_ERROR;
4289 }
4290 dev = mAvailableInputDevices.getDeviceFromId(port->id);
4291 if (dev != 0) {
4292 dev->toAudioPort(port);
4293 return NO_ERROR;
4294 }
4295 sp<SwAudioOutputDescriptor> out = mOutputs.getOutputFromId(port->id);
4296 if (out != 0) {
4297 out->toAudioPort(port);
4298 return NO_ERROR;
4299 }
4300 sp<AudioInputDescriptor> in = mInputs.getInputFromId(port->id);
4301 if (in != 0) {
4302 in->toAudioPort(port);
4303 return NO_ERROR;
4304 }
4305 return BAD_VALUE;
Eric Laurent6a94d692014-05-20 11:18:06 -07004306}
4307
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004308status_t AudioPolicyManager::createAudioPatch(const struct audio_patch *patch,
4309 audio_patch_handle_t *handle,
4310 uid_t uid)
Eric Laurent6a94d692014-05-20 11:18:06 -07004311{
François Gaffieafd4cea2019-11-18 15:50:22 +01004312 ALOGV("%s", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004313 if (handle == NULL || patch == NULL) {
4314 return BAD_VALUE;
4315 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004316 ALOGV("%s num sources %d num sinks %d", __func__, patch->num_sources, patch->num_sinks);
Mikhail Naganovac9858b2018-06-15 13:12:37 -07004317 if (!audio_patch_is_valid(patch)) {
Eric Laurent874c42872014-08-08 15:13:39 -07004318 return BAD_VALUE;
4319 }
4320 // only one source per audio patch supported for now
4321 if (patch->num_sources > 1) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004322 return INVALID_OPERATION;
4323 }
Eric Laurent874c42872014-08-08 15:13:39 -07004324 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004325 return INVALID_OPERATION;
4326 }
Eric Laurent874c42872014-08-08 15:13:39 -07004327 for (size_t i = 0; i < patch->num_sinks; i++) {
4328 if (patch->sinks[i].role != AUDIO_PORT_ROLE_SINK) {
4329 return INVALID_OPERATION;
4330 }
4331 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004332
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004333 sp<DeviceDescriptor> srcDevice = mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
4334 sp<DeviceDescriptor> sinkDevice = mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id);
4335 if (srcDevice == nullptr || sinkDevice == nullptr) {
4336 ALOGW("%s could not create patch, invalid sink and/or source device(s)", __func__);
4337 return BAD_VALUE;
4338 }
4339 ALOGV("%s between source %s and sink %s", __func__,
4340 srcDevice->toString().c_str(), sinkDevice->toString().c_str());
4341 audio_port_handle_t portId = PolicyAudioPort::getNextUniqueId();
4342 // Default attributes, default volume priority, not to infer with non raw audio patches.
4343 audio_attributes_t attributes = attributes_initializer(AUDIO_USAGE_MEDIA);
4344 const struct audio_port_config *source = &patch->sources[0];
4345 sp<SourceClientDescriptor> sourceDesc =
4346 new InternalSourceClientDescriptor(
4347 portId, uid, attributes, *source, srcDevice, sinkDevice,
4348 mEngine->getProductStrategyForAttributes(attributes), toVolumeSource(attributes));
4349
4350 status_t status =
4351 connectAudioSourceToSink(sourceDesc, sinkDevice, patch, *handle, uid, 0 /* delayMs */);
4352
4353 if (status != NO_ERROR) {
4354 return INVALID_OPERATION;
4355 }
4356 mAudioSources.add(portId, sourceDesc);
4357 return NO_ERROR;
4358}
4359
4360status_t AudioPolicyManager::connectAudioSourceToSink(
4361 const sp<SourceClientDescriptor>& sourceDesc, const sp<DeviceDescriptor> &sinkDevice,
4362 const struct audio_patch *patch,
4363 audio_patch_handle_t &handle,
4364 uid_t uid, uint32_t delayMs)
4365{
4366 status_t status = createAudioPatchInternal(patch, &handle, uid, delayMs, sourceDesc);
4367 if (status != NO_ERROR || mAudioPatches.indexOfKey(handle) < 0) {
4368 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
4369 return INVALID_OPERATION;
4370 }
4371 sourceDesc->connect(handle, sinkDevice);
4372 if (isMsdPatch(handle)) {
4373 return NO_ERROR;
4374 }
4375 // SW Bridge? (@todo: HW bridge, keep track of HwOutput for device selection "reconsideration")
4376 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
4377 ALOG_ASSERT(swOutput != nullptr, "%s: a swOutput shall always be associated", __func__);
4378 if (swOutput->getClient(sourceDesc->portId()) != nullptr) {
4379 ALOGW("%s source portId has already been attached to outputDesc", __func__);
4380 goto FailurePatchAdded;
4381 }
4382 status = swOutput->start();
4383 if (status != NO_ERROR) {
4384 goto FailureSourceAdded;
4385 }
4386 swOutput->addClient(sourceDesc);
4387 status = startSource(swOutput, sourceDesc, &delayMs);
4388 if (status != NO_ERROR) {
4389 ALOGW("%s failed to start source, error %d", __FUNCTION__, status);
4390 goto FailureSourceActive;
4391 }
4392 if (delayMs != 0) {
4393 usleep(delayMs * 1000);
4394 }
4395 return NO_ERROR;
4396
4397FailureSourceActive:
4398 swOutput->stop();
4399 releaseOutput(sourceDesc->portId());
4400FailureSourceAdded:
4401 sourceDesc->setSwOutput(nullptr);
4402FailurePatchAdded:
4403 releaseAudioPatchInternal(handle);
4404 return INVALID_OPERATION;
4405}
4406
4407status_t AudioPolicyManager::createAudioPatchInternal(const struct audio_patch *patch,
4408 audio_patch_handle_t *handle,
4409 uid_t uid, uint32_t delayMs,
4410 const sp<SourceClientDescriptor>& sourceDesc)
4411{
4412 ALOGV("%s num sources %d num sinks %d", __func__, patch->num_sources, patch->num_sinks);
Eric Laurent6a94d692014-05-20 11:18:06 -07004413 sp<AudioPatch> patchDesc;
4414 ssize_t index = mAudioPatches.indexOfKey(*handle);
4415
François Gaffieafd4cea2019-11-18 15:50:22 +01004416 ALOGV("%s source id %d role %d type %d", __func__, patch->sources[0].id,
4417 patch->sources[0].role,
4418 patch->sources[0].type);
Eric Laurent874c42872014-08-08 15:13:39 -07004419#if LOG_NDEBUG == 0
4420 for (size_t i = 0; i < patch->num_sinks; i++) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004421 ALOGV("%s sink %zu: id %d role %d type %d", __func__ ,i, patch->sinks[i].id,
4422 patch->sinks[i].role,
4423 patch->sinks[i].type);
Eric Laurent874c42872014-08-08 15:13:39 -07004424 }
4425#endif
Eric Laurent6a94d692014-05-20 11:18:06 -07004426
4427 if (index >= 0) {
4428 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01004429 ALOGV("%s mUidCached %d patchDesc->mUid %d uid %d",
4430 __func__, mUidCached, patchDesc->getUid(), uid);
4431 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004432 return INVALID_OPERATION;
4433 }
4434 } else {
Glenn Kastena13cde92016-03-28 15:26:02 -07004435 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07004436 }
4437
4438 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004439 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004440 if (outputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004441 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004442 return BAD_VALUE;
4443 }
Eric Laurent84c70242014-06-23 08:46:27 -07004444 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
4445 outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004446 if (patchDesc != 0) {
4447 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004448 ALOGV("%s source id differs for patch current id %d new id %d",
4449 __func__, patchDesc->mPatch.sources[0].id, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004450 return BAD_VALUE;
4451 }
4452 }
Eric Laurent874c42872014-08-08 15:13:39 -07004453 DeviceVector devices;
4454 for (size_t i = 0; i < patch->num_sinks; i++) {
4455 // Only support mix to devices connection
4456 // TODO add support for mix to mix connection
4457 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004458 ALOGV("%s source mix but sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07004459 return INVALID_OPERATION;
4460 }
4461 sp<DeviceDescriptor> devDesc =
4462 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
4463 if (devDesc == 0) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004464 ALOGV("%s out device not found for id %d", __func__, patch->sinks[i].id);
Eric Laurent874c42872014-08-08 15:13:39 -07004465 return BAD_VALUE;
4466 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004467
François Gaffie11d30102018-11-02 16:09:09 +01004468 if (!outputDesc->mProfile->isCompatibleProfile(DeviceVector(devDesc),
Eric Laurent874c42872014-08-08 15:13:39 -07004469 patch->sources[0].sample_rate,
François Gaffie53615e22015-03-19 09:24:12 +01004470 NULL, // updatedSamplingRate
4471 patch->sources[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07004472 NULL, // updatedFormat
François Gaffie53615e22015-03-19 09:24:12 +01004473 patch->sources[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07004474 NULL, // updatedChannelMask
François Gaffie53615e22015-03-19 09:24:12 +01004475 AUDIO_OUTPUT_FLAG_NONE /*FIXME*/)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004476 ALOGV("%s profile not supported for device %08x", __func__, devDesc->type());
Eric Laurent874c42872014-08-08 15:13:39 -07004477 return INVALID_OPERATION;
4478 }
4479 devices.add(devDesc);
4480 }
4481 if (devices.size() == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004482 return INVALID_OPERATION;
4483 }
Eric Laurent874c42872014-08-08 15:13:39 -07004484
Eric Laurent6a94d692014-05-20 11:18:06 -07004485 // TODO: reconfigure output format and channels here
François Gaffieafd4cea2019-11-18 15:50:22 +01004486 ALOGV("%s setting device %s on output %d",
4487 __func__, dumpDeviceTypes(devices.types()).c_str(), outputDesc->mIoHandle);
François Gaffie11d30102018-11-02 16:09:09 +01004488 setOutputDevices(outputDesc, devices, true, 0, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004489 index = mAudioPatches.indexOfKey(*handle);
4490 if (index >= 0) {
4491 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004492 ALOGW("%s setOutputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004493 }
4494 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01004495 patchDesc->setUid(uid);
4496 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004497 } else {
François Gaffieafd4cea2019-11-18 15:50:22 +01004498 ALOGW("%s setOutputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004499 return INVALID_OPERATION;
4500 }
4501 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
4502 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
4503 // input device to input mix connection
Eric Laurent874c42872014-08-08 15:13:39 -07004504 // only one sink supported when connecting an input device to a mix
4505 if (patch->num_sinks > 1) {
4506 return INVALID_OPERATION;
4507 }
François Gaffie53615e22015-03-19 09:24:12 +01004508 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004509 if (inputDesc == NULL) {
4510 return BAD_VALUE;
4511 }
4512 if (patchDesc != 0) {
4513 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
4514 return BAD_VALUE;
4515 }
4516 }
François Gaffie11d30102018-11-02 16:09:09 +01004517 sp<DeviceDescriptor> device =
Eric Laurent6a94d692014-05-20 11:18:06 -07004518 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01004519 if (device == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004520 return BAD_VALUE;
4521 }
4522
François Gaffie11d30102018-11-02 16:09:09 +01004523 if (!inputDesc->mProfile->isCompatibleProfile(DeviceVector(device),
Eric Laurent275e8e92014-11-30 15:14:47 -08004524 patch->sinks[0].sample_rate,
4525 NULL, /*updatedSampleRate*/
4526 patch->sinks[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07004527 NULL, /*updatedFormat*/
Eric Laurent275e8e92014-11-30 15:14:47 -08004528 patch->sinks[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07004529 NULL, /*updatedChannelMask*/
Eric Laurent275e8e92014-11-30 15:14:47 -08004530 // FIXME for the parameter type,
4531 // and the NONE
4532 (audio_output_flags_t)
Glenn Kasten6a8ab052014-07-24 14:08:35 -07004533 AUDIO_INPUT_FLAG_NONE)) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004534 return INVALID_OPERATION;
4535 }
4536 // TODO: reconfigure output format and channels here
François Gaffieafd4cea2019-11-18 15:50:22 +01004537 ALOGV("%s setting device %s on output %d", __func__,
François Gaffie11d30102018-11-02 16:09:09 +01004538 device->toString().c_str(), inputDesc->mIoHandle);
4539 setInputDevice(inputDesc->mIoHandle, device, true, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004540 index = mAudioPatches.indexOfKey(*handle);
4541 if (index >= 0) {
4542 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004543 ALOGW("%s setInputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004544 }
4545 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01004546 patchDesc->setUid(uid);
4547 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004548 } else {
François Gaffieafd4cea2019-11-18 15:50:22 +01004549 ALOGW("%s setInputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004550 return INVALID_OPERATION;
4551 }
4552 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
4553 // device to device connection
4554 if (patchDesc != 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07004555 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004556 return BAD_VALUE;
4557 }
4558 }
François Gaffie11d30102018-11-02 16:09:09 +01004559 sp<DeviceDescriptor> srcDevice =
Eric Laurent6a94d692014-05-20 11:18:06 -07004560 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01004561 if (srcDevice == 0) {
Eric Laurent58f8eb72014-09-12 16:19:41 -07004562 return BAD_VALUE;
4563 }
Eric Laurent874c42872014-08-08 15:13:39 -07004564
Eric Laurent6a94d692014-05-20 11:18:06 -07004565 //update source and sink with our own data as the data passed in the patch may
4566 // be incomplete.
François Gaffieafd4cea2019-11-18 15:50:22 +01004567 PatchBuilder patchBuilder;
4568 audio_port_config sourcePortConfig = {};
Dean Wheatley8bee85a2021-02-10 16:02:23 +11004569
4570 // if first sink is to MSD, establish single MSD patch
4571 if (getMsdAudioOutDevices().contains(
4572 mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id))) {
4573 ALOGV("%s patching to MSD", __FUNCTION__);
4574 patchBuilder = buildMsdPatch(false /*msdIsSource*/, srcDevice);
4575 goto installPatch;
4576 }
4577
François Gaffieafd4cea2019-11-18 15:50:22 +01004578 srcDevice->toAudioPortConfig(&sourcePortConfig, &patch->sources[0]);
4579 patchBuilder.addSource(sourcePortConfig);
Eric Laurent6a94d692014-05-20 11:18:06 -07004580
Eric Laurent874c42872014-08-08 15:13:39 -07004581 for (size_t i = 0; i < patch->num_sinks; i++) {
4582 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004583 ALOGV("%s source device but one sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07004584 return INVALID_OPERATION;
4585 }
François Gaffie11d30102018-11-02 16:09:09 +01004586 sp<DeviceDescriptor> sinkDevice =
Eric Laurent874c42872014-08-08 15:13:39 -07004587 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
François Gaffie11d30102018-11-02 16:09:09 +01004588 if (sinkDevice == 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07004589 return BAD_VALUE;
4590 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004591 audio_port_config sinkPortConfig = {};
4592 sinkDevice->toAudioPortConfig(&sinkPortConfig, &patch->sinks[i]);
4593 patchBuilder.addSink(sinkPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07004594
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004595 // Whatever Sw or Hw bridge, we do attach an SwOutput to an Audio Source for
4596 // volume management purpose (tracking activity)
4597 // In case of Hw bridge, it is a Work Around. The mixPort used is the one declared
4598 // in config XML to reach the sink so that is can be declared as available.
4599 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurent78b07302022-10-07 16:20:34 +02004600 sp<SwAudioOutputDescriptor> outputDesc;
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004601 if (!sourceDesc->isInternal()) {
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004602 // take care of dynamic routing for SwOutput selection,
4603 audio_attributes_t attributes = sourceDesc->attributes();
4604 audio_stream_type_t stream = sourceDesc->stream();
4605 audio_attributes_t resultAttr;
4606 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
4607 config.sample_rate = sourceDesc->config().sample_rate;
4608 config.channel_mask = sourceDesc->config().channel_mask;
4609 config.format = sourceDesc->config().format;
4610 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
4611 audio_port_handle_t selectedDeviceId = AUDIO_PORT_HANDLE_NONE;
4612 bool isRequestedDeviceForExclusiveUse = false;
4613 output_type_t outputType;
Eric Laurentb0a7bc92022-04-05 15:06:08 +02004614 bool isSpatialized;
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004615 getOutputForAttrInt(&resultAttr, &output, AUDIO_SESSION_NONE, &attributes,
4616 &stream, sourceDesc->uid(), &config, &flags,
4617 &selectedDeviceId, &isRequestedDeviceForExclusiveUse,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02004618 nullptr, &outputType, &isSpatialized);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004619 if (output == AUDIO_IO_HANDLE_NONE) {
4620 ALOGV("%s no output for device %s",
4621 __FUNCTION__, sinkDevice->toString().c_str());
4622 return INVALID_OPERATION;
4623 }
4624 outputDesc = mOutputs.valueFor(output);
4625 if (outputDesc->isDuplicated()) {
4626 ALOGE("%s output is duplicated", __func__);
4627 return INVALID_OPERATION;
4628 }
François Gaffie1765c5b2022-04-26 12:48:49 +02004629 bool closeOutput = outputDesc->mDirectOpenCount != 0;
4630 sourceDesc->setSwOutput(outputDesc, closeOutput);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004631 } else {
4632 // Same for "raw patches" aka created from createAudioPatch API
4633 SortedVector<audio_io_handle_t> outputs =
4634 getOutputsForDevices(DeviceVector(sinkDevice), mOutputs);
4635 // if the sink device is reachable via an opened output stream, request to
4636 // go via this output stream by adding a second source to the patch
4637 // description
4638 output = selectOutput(outputs);
4639 if (output == AUDIO_IO_HANDLE_NONE) {
4640 ALOGE("%s no output available for internal patch sink", __func__);
4641 return INVALID_OPERATION;
4642 }
4643 outputDesc = mOutputs.valueFor(output);
4644 if (outputDesc->isDuplicated()) {
4645 ALOGV("%s output for device %s is duplicated",
4646 __func__, sinkDevice->toString().c_str());
4647 return INVALID_OPERATION;
4648 }
François Gaffie1765c5b2022-04-26 12:48:49 +02004649 sourceDesc->setSwOutput(outputDesc, /* closeOutput= */ false);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004650 }
Eric Laurent3bcf8592015-04-03 12:13:24 -07004651 // create a software bridge in PatchPanel if:
Scott Randolphf3172402018-01-23 17:06:53 -08004652 // - source and sink devices are on different HW modules OR
Eric Laurent3bcf8592015-04-03 12:13:24 -07004653 // - audio HAL version is < 3.0
Francois Gaffie99896da2018-04-09 11:05:33 +02004654 // - audio HAL version is >= 3.0 but no route has been declared between devices
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004655 // - called from startAudioSource (aka sourceDesc is not internal) and source device
4656 // does not have a gain controller
François Gaffie11d30102018-11-02 16:09:09 +01004657 if (!srcDevice->hasSameHwModuleAs(sinkDevice) ||
4658 (srcDevice->getModuleVersionMajor() < 3) ||
François Gaffieafd4cea2019-11-18 15:50:22 +01004659 !srcDevice->getModule()->supportsPatch(srcDevice, sinkDevice) ||
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004660 (!sourceDesc->isInternal() &&
François Gaffieafd4cea2019-11-18 15:50:22 +01004661 srcDevice->getAudioPort()->getGains().size() == 0)) {
Eric Laurent3bcf8592015-04-03 12:13:24 -07004662 // support only one sink device for now to simplify output selection logic
Eric Laurent874c42872014-08-08 15:13:39 -07004663 if (patch->num_sinks > 1) {
Eric Laurent83b88082014-06-20 18:31:16 -07004664 return INVALID_OPERATION;
4665 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004666 sourceDesc->setUseSwBridge();
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004667 if (outputDesc != nullptr) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004668 audio_port_config srcMixPortConfig = {};
Ytai Ben-Tsvic9d2a912021-11-22 16:43:09 -08004669 outputDesc->toAudioPortConfig(&srcMixPortConfig, nullptr);
François Gaffieafd4cea2019-11-18 15:50:22 +01004670 // for volume control, we may need a valid stream
Eric Laurent78b07302022-10-07 16:20:34 +02004671 srcMixPortConfig.ext.mix.usecase.stream =
4672 (!sourceDesc->isInternal() || isCallTxAudioSource(sourceDesc)) ?
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004673 mEngine->getStreamTypeForAttributes(sourceDesc->attributes()) :
4674 AUDIO_STREAM_PATCH;
François Gaffieafd4cea2019-11-18 15:50:22 +01004675 patchBuilder.addSource(srcMixPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07004676 }
Eric Laurent83b88082014-06-20 18:31:16 -07004677 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004678 }
4679 // TODO: check from routing capabilities in config file and other conflicting patches
4680
Dean Wheatley8bee85a2021-02-10 16:02:23 +11004681installPatch:
François Gaffieafd4cea2019-11-18 15:50:22 +01004682 status_t status = installPatch(
4683 __func__, index, handle, patchBuilder.patch(), delayMs, uid, &patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07004684 if (status != NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004685 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
Eric Laurent6a94d692014-05-20 11:18:06 -07004686 return INVALID_OPERATION;
4687 }
4688 } else {
4689 return BAD_VALUE;
4690 }
4691 } else {
4692 return BAD_VALUE;
4693 }
4694 return NO_ERROR;
4695}
4696
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004697status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle, uid_t uid)
Eric Laurent6a94d692014-05-20 11:18:06 -07004698{
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004699 ALOGV("%s patch %d", __func__, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004700 ssize_t index = mAudioPatches.indexOfKey(handle);
4701
4702 if (index < 0) {
4703 return BAD_VALUE;
4704 }
4705 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01004706 ALOGV("%s() mUidCached %d patchDesc->mUid %d uid %d",
4707 __func__, mUidCached, patchDesc->getUid(), uid);
4708 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004709 return INVALID_OPERATION;
4710 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004711 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
4712 for (size_t i = 0; i < mAudioSources.size(); i++) {
4713 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
4714 if (sourceDesc != nullptr && sourceDesc->getPatchHandle() == handle) {
4715 portId = sourceDesc->portId();
4716 break;
4717 }
4718 }
4719 return portId != AUDIO_PORT_HANDLE_NONE ?
4720 stopAudioSource(portId) : releaseAudioPatchInternal(handle);
François Gaffieafd4cea2019-11-18 15:50:22 +01004721}
Eric Laurent6a94d692014-05-20 11:18:06 -07004722
François Gaffieafd4cea2019-11-18 15:50:22 +01004723status_t AudioPolicyManager::releaseAudioPatchInternal(audio_patch_handle_t handle,
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004724 uint32_t delayMs,
4725 const sp<SourceClientDescriptor>& sourceDesc)
François Gaffieafd4cea2019-11-18 15:50:22 +01004726{
4727 ALOGV("%s patch %d", __func__, handle);
4728 if (mAudioPatches.indexOfKey(handle) < 0) {
4729 ALOGE("%s: no patch found with handle=%d", __func__, handle);
4730 return BAD_VALUE;
4731 }
4732 sp<AudioPatch> patchDesc = mAudioPatches.valueFor(handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004733 struct audio_patch *patch = &patchDesc->mPatch;
François Gaffieafd4cea2019-11-18 15:50:22 +01004734 patchDesc->setUid(mUidCached);
Eric Laurent6a94d692014-05-20 11:18:06 -07004735 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004736 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004737 if (outputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004738 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004739 return BAD_VALUE;
4740 }
4741
François Gaffie11d30102018-11-02 16:09:09 +01004742 setOutputDevices(outputDesc,
4743 getNewOutputDevices(outputDesc, true /*fromCache*/),
4744 true,
4745 0,
4746 NULL);
Eric Laurent6a94d692014-05-20 11:18:06 -07004747 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
4748 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
François Gaffie53615e22015-03-19 09:24:12 +01004749 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004750 if (inputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004751 ALOGV("%s input not found for id %d", __func__, patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004752 return BAD_VALUE;
4753 }
4754 setInputDevice(inputDesc->mIoHandle,
Eric Laurentfb66dd92016-01-28 18:32:03 -08004755 getNewInputDevice(inputDesc),
Eric Laurent6a94d692014-05-20 11:18:06 -07004756 true,
4757 NULL);
4758 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004759 status_t status =
4760 mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
4761 ALOGV("%s patch panel returned %d patchHandle %d",
4762 __func__, status, patchDesc->getAfHandle());
4763 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004764 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004765 mpClientInterface->onAudioPatchListUpdate();
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004766 // SW or HW Bridge
4767 sp<SwAudioOutputDescriptor> outputDesc = nullptr;
4768 audio_patch_handle_t patchHandle = AUDIO_PATCH_HANDLE_NONE;
Francois Gaffie7feb8542020-04-06 17:39:47 +02004769 if (patch->num_sources > 1 && patch->sources[1].type == AUDIO_PORT_TYPE_MIX) {
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004770 outputDesc = mOutputs.getOutputFromId(patch->sources[1].id);
4771 } else if (patch->num_sources == 1 && sourceDesc != nullptr) {
4772 outputDesc = sourceDesc->swOutput().promote();
4773 }
4774 if (outputDesc == nullptr) {
4775 ALOGW("%s no output for id %d", __func__, patch->sources[0].id);
4776 // releaseOutput has already called closeOutput in case of direct output
4777 return NO_ERROR;
4778 }
François Gaffie1765c5b2022-04-26 12:48:49 +02004779 patchHandle = outputDesc->getPatchHandle();
4780 // When a Sw bridge is released, the mixer used by this bridge will release its
4781 // patch at AudioFlinger side. Hence, the mixer audio patch must be recreated
4782 // Reuse patch handle to force audio flinger removing initial mixer patch removal
4783 // updating hal patch handle (prevent leaks).
4784 // While using a HwBridge, force reconsidering device only if not reusing an existing
4785 // output and no more activity on output (will force to close).
4786 bool force = sourceDesc->useSwBridge() ||
4787 (sourceDesc->canCloseOutput() && !outputDesc->isActive());
4788 // APM pattern is to have always outputs opened / patch realized for reachable devices.
4789 // Update device may result to NONE (empty), coupled with force, it releases the patch.
4790 // Reconsider device only for cases:
4791 // 1 / Active Output
4792 // 2 / Inactive Output previously hosting HwBridge
4793 // 3 / Inactive Output previously hosting SwBridge that can be closed.
4794 bool updateDevice = outputDesc->isActive() || !sourceDesc->useSwBridge() ||
4795 sourceDesc->canCloseOutput();
4796 setOutputDevices(outputDesc,
4797 updateDevice ? getNewOutputDevices(outputDesc, true /*fromCache*/) :
4798 outputDesc->devices(),
4799 force,
4800 0,
4801 patchHandle == AUDIO_PATCH_HANDLE_NONE ? nullptr : &patchHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004802 } else {
4803 return BAD_VALUE;
4804 }
4805 } else {
4806 return BAD_VALUE;
4807 }
4808 return NO_ERROR;
4809}
4810
4811status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
4812 struct audio_patch *patches,
4813 unsigned int *generation)
4814{
François Gaffie53615e22015-03-19 09:24:12 +01004815 if (generation == NULL) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004816 return BAD_VALUE;
4817 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004818 *generation = curAudioPortGeneration();
François Gaffie53615e22015-03-19 09:24:12 +01004819 return mAudioPatches.listAudioPatches(num_patches, patches);
Eric Laurent6a94d692014-05-20 11:18:06 -07004820}
4821
Eric Laurente1715a42014-05-20 11:30:42 -07004822status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07004823{
Eric Laurente1715a42014-05-20 11:30:42 -07004824 ALOGV("setAudioPortConfig()");
4825
4826 if (config == NULL) {
4827 return BAD_VALUE;
4828 }
4829 ALOGV("setAudioPortConfig() on port handle %d", config->id);
4830 // Only support gain configuration for now
Eric Laurenta121f902014-06-03 13:32:54 -07004831 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
4832 return INVALID_OPERATION;
Eric Laurente1715a42014-05-20 11:30:42 -07004833 }
4834
Eric Laurenta121f902014-06-03 13:32:54 -07004835 sp<AudioPortConfig> audioPortConfig;
Eric Laurente1715a42014-05-20 11:30:42 -07004836 if (config->type == AUDIO_PORT_TYPE_MIX) {
4837 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004838 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07004839 if (outputDesc == NULL) {
4840 return BAD_VALUE;
4841 }
Eric Laurent84c70242014-06-23 08:46:27 -07004842 ALOG_ASSERT(!outputDesc->isDuplicated(),
4843 "setAudioPortConfig() called on duplicated output %d",
4844 outputDesc->mIoHandle);
Eric Laurenta121f902014-06-03 13:32:54 -07004845 audioPortConfig = outputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07004846 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
François Gaffie53615e22015-03-19 09:24:12 +01004847 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07004848 if (inputDesc == NULL) {
4849 return BAD_VALUE;
4850 }
Eric Laurenta121f902014-06-03 13:32:54 -07004851 audioPortConfig = inputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07004852 } else {
4853 return BAD_VALUE;
4854 }
4855 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
4856 sp<DeviceDescriptor> deviceDesc;
4857 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
4858 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
4859 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
4860 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
4861 } else {
4862 return BAD_VALUE;
4863 }
4864 if (deviceDesc == NULL) {
4865 return BAD_VALUE;
4866 }
Eric Laurenta121f902014-06-03 13:32:54 -07004867 audioPortConfig = deviceDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07004868 } else {
4869 return BAD_VALUE;
4870 }
4871
Mikhail Naganov7be71d22018-05-23 16:51:46 -07004872 struct audio_port_config backupConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07004873 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
4874 if (status == NO_ERROR) {
Mikhail Naganov7be71d22018-05-23 16:51:46 -07004875 struct audio_port_config newConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07004876 audioPortConfig->toAudioPortConfig(&newConfig, config);
4877 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
Eric Laurente1715a42014-05-20 11:30:42 -07004878 }
Eric Laurenta121f902014-06-03 13:32:54 -07004879 if (status != NO_ERROR) {
4880 audioPortConfig->applyAudioPortConfig(&backupConfig);
Eric Laurente1715a42014-05-20 11:30:42 -07004881 }
Eric Laurente1715a42014-05-20 11:30:42 -07004882
4883 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07004884}
4885
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004886void AudioPolicyManager::releaseResourcesForUid(uid_t uid)
4887{
Eric Laurentd60560a2015-04-10 11:31:20 -07004888 clearAudioSources(uid);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004889 clearAudioPatches(uid);
4890 clearSessionRoutes(uid);
4891}
4892
Eric Laurent6a94d692014-05-20 11:18:06 -07004893void AudioPolicyManager::clearAudioPatches(uid_t uid)
4894{
Eric Laurent0add0fd2014-12-04 18:58:14 -08004895 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004896 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
François Gaffieafd4cea2019-11-18 15:50:22 +01004897 if (patchDesc->getUid() == uid) {
Eric Laurent0add0fd2014-12-04 18:58:14 -08004898 releaseAudioPatch(mAudioPatches.keyAt(i), uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07004899 }
4900 }
4901}
4902
François Gaffiec005e562018-11-06 15:04:49 +01004903void AudioPolicyManager::checkStrategyRoute(product_strategy_t ps, audio_io_handle_t ouptutToSkip)
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004904{
François Gaffiec005e562018-11-06 15:04:49 +01004905 // Take the first attributes following the product strategy as it is used to retrieve the routed
4906 // device. All attributes wihin a strategy follows the same "routing strategy"
4907 auto attributes = mEngine->getAllAttributesForProductStrategy(ps).front();
4908 DeviceVector devices = mEngine->getOutputDevicesForAttributes(attributes, nullptr, false);
François Gaffie11d30102018-11-02 16:09:09 +01004909 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004910 for (size_t j = 0; j < mOutputs.size(); j++) {
4911 if (mOutputs.keyAt(j) == ouptutToSkip) {
4912 continue;
4913 }
4914 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(j);
François Gaffiec005e562018-11-06 15:04:49 +01004915 if (!outputDesc->isStrategyActive(ps)) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004916 continue;
4917 }
4918 // If the default device for this strategy is on another output mix,
4919 // invalidate all tracks in this strategy to force re connection.
4920 // Otherwise select new device on the output mix.
4921 if (outputs.indexOf(mOutputs.keyAt(j)) < 0) {
François Gaffiec005e562018-11-06 15:04:49 +01004922 for (auto stream : mEngine->getStreamTypesForProductStrategy(ps)) {
4923 mpClientInterface->invalidateStream(stream);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004924 }
4925 } else {
François Gaffie11d30102018-11-02 16:09:09 +01004926 setOutputDevices(
4927 outputDesc, getNewOutputDevices(outputDesc, false /*fromCache*/), false);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004928 }
4929 }
4930}
4931
4932void AudioPolicyManager::clearSessionRoutes(uid_t uid)
4933{
4934 // remove output routes associated with this uid
François Gaffiec005e562018-11-06 15:04:49 +01004935 std::vector<product_strategy_t> affectedStrategies;
Eric Laurent97ac8712018-07-27 18:59:02 -07004936 for (size_t i = 0; i < mOutputs.size(); i++) {
4937 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07004938 for (const auto& client : outputDesc->getClientIterable()) {
4939 if (client->hasPreferredDevice() && client->uid() == uid) {
4940 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
François Gaffiec005e562018-11-06 15:04:49 +01004941 auto clientStrategy = client->strategy();
4942 if (std::find(begin(affectedStrategies), end(affectedStrategies), clientStrategy) !=
4943 end(affectedStrategies)) {
4944 continue;
4945 }
4946 affectedStrategies.push_back(client->strategy());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004947 }
4948 }
4949 }
4950 // reroute outputs if necessary
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004951 for (const auto& strategy : affectedStrategies) {
4952 checkStrategyRoute(strategy, AUDIO_IO_HANDLE_NONE);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004953 }
4954
4955 // remove input routes associated with this uid
4956 SortedVector<audio_source_t> affectedSources;
Eric Laurent97ac8712018-07-27 18:59:02 -07004957 for (size_t i = 0; i < mInputs.size(); i++) {
4958 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07004959 for (const auto& client : inputDesc->getClientIterable()) {
4960 if (client->hasPreferredDevice() && client->uid() == uid) {
4961 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
4962 affectedSources.add(client->source());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004963 }
4964 }
4965 }
4966 // reroute inputs if necessary
4967 SortedVector<audio_io_handle_t> inputsToClose;
4968 for (size_t i = 0; i < mInputs.size(); i++) {
4969 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Eric Laurent4eb58f12018-12-07 16:41:02 -08004970 if (affectedSources.indexOf(inputDesc->source()) >= 0) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004971 inputsToClose.add(inputDesc->mIoHandle);
4972 }
4973 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004974 for (const auto& input : inputsToClose) {
4975 closeInput(input);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004976 }
4977}
4978
Eric Laurentd60560a2015-04-10 11:31:20 -07004979void AudioPolicyManager::clearAudioSources(uid_t uid)
4980{
4981 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004982 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
4983 if (sourceDesc->uid() == uid) {
Eric Laurentd60560a2015-04-10 11:31:20 -07004984 stopAudioSource(mAudioSources.keyAt(i));
4985 }
4986 }
4987}
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004988
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07004989status_t AudioPolicyManager::acquireSoundTriggerSession(audio_session_t *session,
4990 audio_io_handle_t *ioHandle,
4991 audio_devices_t *device)
4992{
Glenn Kastenf0c6d7d2016-02-26 10:44:04 -08004993 *session = (audio_session_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
4994 *ioHandle = (audio_io_handle_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
Francois Gaffie716e1432019-01-14 16:58:59 +01004995 audio_attributes_t attr = { .source = AUDIO_SOURCE_HOTWORD };
François Gaffiec005e562018-11-06 15:04:49 +01004996 *device = mEngine->getInputDeviceForAttributes(attr)->type();
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07004997
François Gaffiedf372692015-03-19 10:43:27 +01004998 return mSoundTriggerSessions.acquireSession(*session, *ioHandle);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07004999}
5000
Eric Laurentd60560a2015-04-10 11:31:20 -07005001status_t AudioPolicyManager::startAudioSource(const struct audio_port_config *source,
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005002 const audio_attributes_t *attributes,
5003 audio_port_handle_t *portId,
5004 uid_t uid)
Eric Laurent554a2772015-04-10 11:29:24 -07005005{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005006 ALOGV("%s", __FUNCTION__);
5007 *portId = AUDIO_PORT_HANDLE_NONE;
5008
5009 if (source == NULL || attributes == NULL || portId == NULL) {
5010 ALOGW("%s invalid argument: source %p attributes %p handle %p",
5011 __FUNCTION__, source, attributes, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005012 return BAD_VALUE;
5013 }
5014
Eric Laurentd60560a2015-04-10 11:31:20 -07005015 if (source->role != AUDIO_PORT_ROLE_SOURCE ||
5016 source->type != AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005017 ALOGW("%s INVALID_OPERATION source->role %d source->type %d",
5018 __FUNCTION__, source->role, source->type);
Eric Laurentd60560a2015-04-10 11:31:20 -07005019 return INVALID_OPERATION;
5020 }
5021
François Gaffie11d30102018-11-02 16:09:09 +01005022 sp<DeviceDescriptor> srcDevice =
Eric Laurentd60560a2015-04-10 11:31:20 -07005023 mAvailableInputDevices.getDevice(source->ext.device.type,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005024 String8(source->ext.device.address),
5025 AUDIO_FORMAT_DEFAULT);
François Gaffie11d30102018-11-02 16:09:09 +01005026 if (srcDevice == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005027 ALOGW("%s source->ext.device.type %08x not found", __FUNCTION__, source->ext.device.type);
Eric Laurentd60560a2015-04-10 11:31:20 -07005028 return BAD_VALUE;
5029 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005030
jiabin4ef93452019-09-10 14:29:54 -07005031 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurentd60560a2015-04-10 11:31:20 -07005032
François Gaffieaaac0fd2018-11-22 17:56:39 +01005033 sp<SourceClientDescriptor> sourceDesc =
François Gaffieafd4cea2019-11-18 15:50:22 +01005034 new SourceClientDescriptor(*portId, uid, *attributes, *source, srcDevice,
François Gaffieaaac0fd2018-11-22 17:56:39 +01005035 mEngine->getStreamTypeForAttributes(*attributes),
5036 mEngine->getProductStrategyForAttributes(*attributes),
5037 toVolumeSource(*attributes));
Eric Laurentd60560a2015-04-10 11:31:20 -07005038
5039 status_t status = connectAudioSource(sourceDesc);
5040 if (status == NO_ERROR) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005041 mAudioSources.add(*portId, sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07005042 }
5043 return status;
5044}
5045
Francois Gaffie601801d2021-06-22 13:27:39 +02005046sp<SourceClientDescriptor> AudioPolicyManager::startAudioSourceInternal(
5047 const struct audio_port_config *source, const audio_attributes_t *attributes, uid_t uid)
5048{
5049 ALOGV("%s", __FUNCTION__);
5050 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
5051
5052 status_t status = startAudioSource(source, attributes, &portId, uid);
5053 ALOGE_IF(status != OK, "%s: failed to start audio source (%d)", __func__, status);
5054 return mAudioSources.valueFor(portId);
5055}
5056
5057
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005058status_t AudioPolicyManager::connectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07005059{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005060 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->portId());
Eric Laurentd60560a2015-04-10 11:31:20 -07005061
5062 // make sure we only have one patch per source.
5063 disconnectAudioSource(sourceDesc);
5064
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005065 audio_attributes_t attributes = sourceDesc->attributes();
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005066 // May the device (dynamic) have been disconnected/reconnected, id has changed.
5067 sp<DeviceDescriptor> srcDevice = mAvailableInputDevices.getDevice(
5068 sourceDesc->srcDevice()->type(),
5069 String8(sourceDesc->srcDevice()->address().c_str()),
5070 AUDIO_FORMAT_DEFAULT);
François Gaffiec005e562018-11-06 15:04:49 +01005071 DeviceVector sinkDevices =
Francois Gaffieff1eb522020-05-06 18:37:04 +02005072 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false /*fromCache*/);
François Gaffiec005e562018-11-06 15:04:49 +01005073 ALOG_ASSERT(!sinkDevices.isEmpty(), "connectAudioSource(): no device found for attributes");
François Gaffie11d30102018-11-02 16:09:09 +01005074 sp<DeviceDescriptor> sinkDevice = sinkDevices.itemAt(0);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005075 if (!mAvailableOutputDevices.contains(sinkDevice)) {
5076 ALOGE("%s Device %s not available", __func__, sinkDevice->toString().c_str());
5077 return INVALID_OPERATION;
5078 }
François Gaffieafd4cea2019-11-18 15:50:22 +01005079 PatchBuilder patchBuilder;
5080 patchBuilder.addSink(sinkDevice).addSource(srcDevice);
5081 audio_patch_handle_t handle = AUDIO_PATCH_HANDLE_NONE;
François Gaffieafd4cea2019-11-18 15:50:22 +01005082
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005083 return connectAudioSourceToSink(
5084 sourceDesc, sinkDevice, patchBuilder.patch(), handle, mUidCached, 0 /*delayMs*/);
Eric Laurent554a2772015-04-10 11:29:24 -07005085}
5086
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005087status_t AudioPolicyManager::stopAudioSource(audio_port_handle_t portId)
Eric Laurent554a2772015-04-10 11:29:24 -07005088{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005089 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueFor(portId);
5090 ALOGV("%s port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005091 if (sourceDesc == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005092 ALOGW("%s unknown source for port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005093 return BAD_VALUE;
5094 }
5095 status_t status = disconnectAudioSource(sourceDesc);
5096
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005097 mAudioSources.removeItem(portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005098 return status;
5099}
5100
Andy Hung2ddee192015-12-18 17:34:44 -08005101status_t AudioPolicyManager::setMasterMono(bool mono)
5102{
5103 if (mMasterMono == mono) {
5104 return NO_ERROR;
5105 }
5106 mMasterMono = mono;
5107 // if enabling mono we close all offloaded devices, which will invalidate the
5108 // corresponding AudioTrack. The AudioTrack client/MediaPlayer is responsible
5109 // for recreating the new AudioTrack as non-offloaded PCM.
5110 //
5111 // If disabling mono, we leave all tracks as is: we don't know which clients
5112 // and tracks are able to be recreated as offloaded. The next "song" should
5113 // play back offloaded.
5114 if (mMasterMono) {
5115 Vector<audio_io_handle_t> offloaded;
5116 for (size_t i = 0; i < mOutputs.size(); ++i) {
5117 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
5118 if (desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
5119 offloaded.push(desc->mIoHandle);
5120 }
5121 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005122 for (const auto& handle : offloaded) {
5123 closeOutput(handle);
Andy Hung2ddee192015-12-18 17:34:44 -08005124 }
5125 }
5126 // update master mono for all remaining outputs
5127 for (size_t i = 0; i < mOutputs.size(); ++i) {
5128 updateMono(mOutputs.keyAt(i));
5129 }
5130 return NO_ERROR;
5131}
5132
5133status_t AudioPolicyManager::getMasterMono(bool *mono)
5134{
5135 *mono = mMasterMono;
5136 return NO_ERROR;
5137}
5138
Eric Laurentac9cef52017-06-09 15:46:26 -07005139float AudioPolicyManager::getStreamVolumeDB(
5140 audio_stream_type_t stream, int index, audio_devices_t device)
5141{
jiabin9a3361e2019-10-01 09:38:30 -07005142 return computeVolume(getVolumeCurves(stream), toVolumeSource(stream), index, {device});
Eric Laurentac9cef52017-06-09 15:46:26 -07005143}
5144
jiabin81772902018-04-02 17:52:27 -07005145status_t AudioPolicyManager::getSurroundFormats(unsigned int *numSurroundFormats,
5146 audio_format_t *surroundFormats,
Kriti Dang6537def2021-03-02 13:46:59 +01005147 bool *surroundFormatsEnabled)
jiabin81772902018-04-02 17:52:27 -07005148{
Kriti Dang6537def2021-03-02 13:46:59 +01005149 if (numSurroundFormats == nullptr || (*numSurroundFormats != 0 &&
5150 (surroundFormats == nullptr || surroundFormatsEnabled == nullptr))) {
jiabin81772902018-04-02 17:52:27 -07005151 return BAD_VALUE;
5152 }
Kriti Dang6537def2021-03-02 13:46:59 +01005153 ALOGV("%s() numSurroundFormats %d surroundFormats %p surroundFormatsEnabled %p",
5154 __func__, *numSurroundFormats, surroundFormats, surroundFormatsEnabled);
jiabin81772902018-04-02 17:52:27 -07005155
5156 size_t formatsWritten = 0;
5157 size_t formatsMax = *numSurroundFormats;
Kriti Dangef6be8f2020-11-05 11:58:19 +01005158
Mikhail Naganovb0fbc1b2023-04-28 13:06:32 -07005159 *numSurroundFormats = mConfig->getSurroundFormats().size();
Mikhail Naganov100f0122018-11-29 11:22:16 -08005160 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
5161 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Mikhail Naganovb0fbc1b2023-04-28 13:06:32 -07005162 for (const auto& format: mConfig->getSurroundFormats()) {
jiabin81772902018-04-02 17:52:27 -07005163 if (formatsWritten < formatsMax) {
Kriti Dang6537def2021-03-02 13:46:59 +01005164 surroundFormats[formatsWritten] = format.first;
Mikhail Naganov100f0122018-11-29 11:22:16 -08005165 bool formatEnabled = true;
5166 switch (forceUse) {
5167 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL:
Kriti Dang6537def2021-03-02 13:46:59 +01005168 formatEnabled = mManualSurroundFormats.count(format.first) != 0;
Mikhail Naganov100f0122018-11-29 11:22:16 -08005169 break;
5170 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER:
5171 formatEnabled = false;
5172 break;
5173 default: // AUTO or ALWAYS => true
5174 break;
jiabin81772902018-04-02 17:52:27 -07005175 }
5176 surroundFormatsEnabled[formatsWritten++] = formatEnabled;
5177 }
jiabin81772902018-04-02 17:52:27 -07005178 }
5179 return NO_ERROR;
5180}
5181
Kriti Dang6537def2021-03-02 13:46:59 +01005182status_t AudioPolicyManager::getReportedSurroundFormats(unsigned int *numSurroundFormats,
5183 audio_format_t *surroundFormats) {
5184 if (numSurroundFormats == nullptr || (*numSurroundFormats != 0 && surroundFormats == nullptr)) {
5185 return BAD_VALUE;
5186 }
5187 ALOGV("%s() numSurroundFormats %d surroundFormats %p",
5188 __func__, *numSurroundFormats, surroundFormats);
5189
5190 size_t formatsWritten = 0;
5191 size_t formatsMax = *numSurroundFormats;
5192 std::unordered_set<audio_format_t> formats; // Uses primary surround formats only
5193
5194 // Return formats from all device profiles that have already been resolved by
5195 // checkOutputsForDevice().
5196 for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
5197 sp<DeviceDescriptor> device = mAvailableOutputDevices[i];
5198 audio_devices_t deviceType = device->type();
5199 // Enabling/disabling formats are applied to only HDMI devices. So, this function
5200 // returns formats reported by HDMI devices.
5201 if (deviceType != AUDIO_DEVICE_OUT_HDMI) {
5202 continue;
5203 }
5204 // Formats reported by sink devices
5205 std::unordered_set<audio_format_t> formatset;
5206 if (auto it = mReportedFormatsMap.find(device); it != mReportedFormatsMap.end()) {
5207 formatset.insert(it->second.begin(), it->second.end());
5208 }
5209
5210 // Formats hard-coded in the in policy configuration file (if any).
5211 FormatVector encodedFormats = device->encodedFormats();
5212 formatset.insert(encodedFormats.begin(), encodedFormats.end());
5213 // Filter the formats which are supported by the vendor hardware.
5214 for (auto it = formatset.begin(); it != formatset.end(); ++it) {
Mikhail Naganovb0fbc1b2023-04-28 13:06:32 -07005215 if (mConfig->getSurroundFormats().count(*it) != 0) {
Kriti Dang6537def2021-03-02 13:46:59 +01005216 formats.insert(*it);
5217 } else {
Mikhail Naganovb0fbc1b2023-04-28 13:06:32 -07005218 for (const auto& pair : mConfig->getSurroundFormats()) {
Kriti Dang6537def2021-03-02 13:46:59 +01005219 if (pair.second.count(*it) != 0) {
5220 formats.insert(pair.first);
5221 break;
5222 }
5223 }
5224 }
5225 }
5226 }
5227 *numSurroundFormats = formats.size();
5228 for (const auto& format: formats) {
5229 if (formatsWritten < formatsMax) {
5230 surroundFormats[formatsWritten++] = format;
5231 }
5232 }
5233 return NO_ERROR;
5234}
5235
jiabin81772902018-04-02 17:52:27 -07005236status_t AudioPolicyManager::setSurroundFormatEnabled(audio_format_t audioFormat, bool enabled)
5237{
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005238 ALOGV("%s() format 0x%X enabled %d", __func__, audioFormat, enabled);
Mikhail Naganovb0fbc1b2023-04-28 13:06:32 -07005239 const auto& formatIter = mConfig->getSurroundFormats().find(audioFormat);
5240 if (formatIter == mConfig->getSurroundFormats().end()) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005241 ALOGW("%s() format 0x%X is not a known surround format", __func__, audioFormat);
jiabin81772902018-04-02 17:52:27 -07005242 return BAD_VALUE;
5243 }
5244
Mikhail Naganov100f0122018-11-29 11:22:16 -08005245 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND) !=
5246 AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005247 ALOGW("%s() not in manual mode for surround sound format selection", __func__);
jiabin81772902018-04-02 17:52:27 -07005248 return INVALID_OPERATION;
5249 }
5250
Mikhail Naganov100f0122018-11-29 11:22:16 -08005251 if ((mManualSurroundFormats.count(audioFormat) != 0) == enabled) {
jiabin81772902018-04-02 17:52:27 -07005252 return NO_ERROR;
5253 }
5254
Mikhail Naganov100f0122018-11-29 11:22:16 -08005255 std::unordered_set<audio_format_t> surroundFormatsBackup(mManualSurroundFormats);
jiabin81772902018-04-02 17:52:27 -07005256 if (enabled) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005257 mManualSurroundFormats.insert(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07005258 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005259 mManualSurroundFormats.insert(subFormat);
jiabin81772902018-04-02 17:52:27 -07005260 }
5261 } else {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005262 mManualSurroundFormats.erase(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07005263 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005264 mManualSurroundFormats.erase(subFormat);
jiabin81772902018-04-02 17:52:27 -07005265 }
5266 }
5267
5268 sp<SwAudioOutputDescriptor> outputDesc;
5269 bool profileUpdated = false;
jiabin9a3361e2019-10-01 09:38:30 -07005270 DeviceVector hdmiOutputDevices = mAvailableOutputDevices.getDevicesFromType(
5271 AUDIO_DEVICE_OUT_HDMI);
jiabin81772902018-04-02 17:52:27 -07005272 for (size_t i = 0; i < hdmiOutputDevices.size(); i++) {
5273 // Simulate reconnection to update enabled surround sound formats.
jiabince9f20e2019-09-12 16:29:15 -07005274 String8 address = String8(hdmiOutputDevices[i]->address().c_str());
jiabin5740f082019-08-19 15:08:30 -07005275 std::string name = hdmiOutputDevices[i]->getName();
jiabin81772902018-04-02 17:52:27 -07005276 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
5277 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
5278 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005279 name.c_str(),
5280 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005281 if (status != NO_ERROR) {
5282 continue;
5283 }
5284 status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
5285 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
5286 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005287 name.c_str(),
5288 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005289 profileUpdated |= (status == NO_ERROR);
5290 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08005291 // FIXME: Why doing this for input HDMI devices if we don't augment their reported formats?
jiabin9a3361e2019-10-01 09:38:30 -07005292 DeviceVector hdmiInputDevices = mAvailableInputDevices.getDevicesFromType(
jiabin81772902018-04-02 17:52:27 -07005293 AUDIO_DEVICE_IN_HDMI);
5294 for (size_t i = 0; i < hdmiInputDevices.size(); i++) {
5295 // Simulate reconnection to update enabled surround sound formats.
jiabince9f20e2019-09-12 16:29:15 -07005296 String8 address = String8(hdmiInputDevices[i]->address().c_str());
jiabin5740f082019-08-19 15:08:30 -07005297 std::string name = hdmiInputDevices[i]->getName();
jiabin81772902018-04-02 17:52:27 -07005298 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
5299 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
5300 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005301 name.c_str(),
5302 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005303 if (status != NO_ERROR) {
5304 continue;
5305 }
5306 status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
5307 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
5308 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005309 name.c_str(),
5310 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005311 profileUpdated |= (status == NO_ERROR);
5312 }
5313
jiabin81772902018-04-02 17:52:27 -07005314 if (!profileUpdated) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005315 ALOGW("%s() no audio profiles updated, undoing surround formats change", __func__);
Mikhail Naganov100f0122018-11-29 11:22:16 -08005316 mManualSurroundFormats = std::move(surroundFormatsBackup);
jiabin81772902018-04-02 17:52:27 -07005317 }
5318
5319 return profileUpdated ? NO_ERROR : INVALID_OPERATION;
5320}
5321
Eric Laurent5ada82e2019-08-29 17:53:54 -07005322void AudioPolicyManager::setAppState(audio_port_handle_t portId, app_state_t state)
Svet Ganovf4ddfef2018-01-16 07:37:58 -08005323{
Eric Laurent5ada82e2019-08-29 17:53:54 -07005324 ALOGV("%s(portId:%d, state:%d)", __func__, portId, state);
Eric Laurenta9f86652018-11-28 17:23:11 -08005325 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent5ada82e2019-08-29 17:53:54 -07005326 mInputs.valueAt(i)->setAppState(portId, state);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08005327 }
5328}
5329
jiabin6012f912018-11-02 17:06:30 -07005330bool AudioPolicyManager::isHapticPlaybackSupported()
5331{
5332 for (const auto& hwModule : mHwModules) {
5333 const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
5334 for (const auto &outProfile : outputProfiles) {
5335 struct audio_port audioPort;
5336 outProfile->toAudioPort(&audioPort);
5337 for (size_t i = 0; i < audioPort.num_channel_masks; i++) {
5338 if (audioPort.channel_masks[i] & AUDIO_CHANNEL_HAPTIC_ALL) {
5339 return true;
5340 }
5341 }
5342 }
5343 }
5344 return false;
5345}
5346
Carter Hsu325a8eb2022-01-19 19:56:51 +08005347bool AudioPolicyManager::isUltrasoundSupported()
5348{
5349 bool hasUltrasoundOutput = false;
5350 bool hasUltrasoundInput = false;
5351 for (const auto& hwModule : mHwModules) {
5352 const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
5353 if (!hasUltrasoundOutput) {
5354 for (const auto &outProfile : outputProfiles) {
5355 if (outProfile->getFlags() & AUDIO_OUTPUT_FLAG_ULTRASOUND) {
5356 hasUltrasoundOutput = true;
5357 break;
5358 }
5359 }
5360 }
5361
5362 const InputProfileCollection &inputProfiles = hwModule->getInputProfiles();
5363 if (!hasUltrasoundInput) {
5364 for (const auto &inputProfile : inputProfiles) {
5365 if (inputProfile->getFlags() & AUDIO_INPUT_FLAG_ULTRASOUND) {
5366 hasUltrasoundInput = true;
5367 break;
5368 }
5369 }
5370 }
5371
5372 if (hasUltrasoundOutput && hasUltrasoundInput)
5373 return true;
5374 }
5375 return false;
5376}
5377
Eric Laurent8340e672019-11-06 11:01:08 -08005378bool AudioPolicyManager::isCallScreenModeSupported()
5379{
Mikhail Naganovb0fbc1b2023-04-28 13:06:32 -07005380 return mConfig->isCallScreenModeSupported();
Eric Laurent8340e672019-11-06 11:01:08 -08005381}
5382
5383
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005384status_t AudioPolicyManager::disconnectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07005385{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005386 ALOGV("%s port Id %d", __FUNCTION__, sourceDesc->portId());
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005387 if (!sourceDesc->isConnected()) {
5388 ALOGV("%s port Id %d already disconnected", __FUNCTION__, sourceDesc->portId());
5389 return NO_ERROR;
5390 }
François Gaffieafd4cea2019-11-18 15:50:22 +01005391 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
5392 if (swOutput != 0) {
5393 status_t status = stopSource(swOutput, sourceDesc);
Eric Laurent733ce942017-12-07 12:18:25 -08005394 if (status == NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005395 swOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08005396 }
jiabinbce0c1d2020-10-05 11:20:18 -07005397 if (releaseOutput(sourceDesc->portId())) {
5398 // The output descriptor is reopened to query dynamic profiles. In that case, there is
5399 // no need to release audio patch here but just return NO_ERROR.
5400 return NO_ERROR;
5401 }
Eric Laurentd60560a2015-04-10 11:31:20 -07005402 } else {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005403 sp<HwAudioOutputDescriptor> hwOutputDesc = sourceDesc->hwOutput().promote();
Eric Laurentd60560a2015-04-10 11:31:20 -07005404 if (hwOutputDesc != 0) {
Eric Laurentd60560a2015-04-10 11:31:20 -07005405 // close Hwoutput and remove from mHwOutputs
5406 } else {
5407 ALOGW("%s source has neither SW nor HW output", __FUNCTION__);
5408 }
5409 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005410 status_t status = releaseAudioPatchInternal(sourceDesc->getPatchHandle(), 0, sourceDesc);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005411 sourceDesc->disconnect();
5412 return status;
Eric Laurentd60560a2015-04-10 11:31:20 -07005413}
5414
François Gaffiec005e562018-11-06 15:04:49 +01005415sp<SourceClientDescriptor> AudioPolicyManager::getSourceForAttributesOnOutput(
5416 audio_io_handle_t output, const audio_attributes_t &attr)
Eric Laurentd60560a2015-04-10 11:31:20 -07005417{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005418 sp<SourceClientDescriptor> source;
Eric Laurentd60560a2015-04-10 11:31:20 -07005419 for (size_t i = 0; i < mAudioSources.size(); i++) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005420 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005421 sp<SwAudioOutputDescriptor> outputDesc = sourceDesc->swOutput().promote();
François Gaffiec005e562018-11-06 15:04:49 +01005422 if (followsSameRouting(attr, sourceDesc->attributes()) &&
5423 outputDesc != 0 && outputDesc->mIoHandle == output) {
Eric Laurentd60560a2015-04-10 11:31:20 -07005424 source = sourceDesc;
5425 break;
5426 }
5427 }
5428 return source;
Eric Laurent554a2772015-04-10 11:29:24 -07005429}
5430
Eric Laurentb4f42a92022-01-17 17:37:31 +01005431bool AudioPolicyManager::canBeSpatializedInt(const audio_attributes_t *attr,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005432 const audio_config_t *config,
Andy Hung9dd1a5b2022-05-10 15:39:39 -07005433 const AudioDeviceTypeAddrVector &devices) const
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005434{
5435 // The caller can have the audio attributes criteria ignored by either passing a null ptr or
5436 // the AUDIO_ATTRIBUTES_INITIALIZER value.
Eric Laurentfa0f6742021-08-17 18:39:44 +02005437 // If attributes are specified, current policy is to only allow spatialization for media
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005438 // and game usages.
Eric Laurent39095982021-08-24 18:29:27 +02005439 if (attr != nullptr && *attr != AUDIO_ATTRIBUTES_INITIALIZER) {
5440 if (attr->usage != AUDIO_USAGE_MEDIA && attr->usage != AUDIO_USAGE_GAME) {
5441 return false;
5442 }
5443 if ((attr->flags & (AUDIO_FLAG_CONTENT_SPATIALIZED | AUDIO_FLAG_NEVER_SPATIALIZE)) != 0) {
5444 return false;
5445 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005446 }
5447
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005448 sp<IOProfile> profile =
Eric Laurent39095982021-08-24 18:29:27 +02005449 getSpatializerOutputProfile(config, devices);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005450 if (profile == nullptr) {
5451 return false;
5452 }
5453
5454 // The caller can have the audio config criteria ignored by either passing a null ptr or
5455 // the AUDIO_CONFIG_INITIALIZER value.
Eric Laurentfa0f6742021-08-17 18:39:44 +02005456 // If an audio config is specified, current policy is to only allow spatialization for
Eric Laurent39095982021-08-24 18:29:27 +02005457 // some positional channel masks.
Eric Laurent39095982021-08-24 18:29:27 +02005458
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005459 if (config != nullptr && *config != AUDIO_CONFIG_INITIALIZER) {
Andy Hung9dd1a5b2022-05-10 15:39:39 -07005460 if (!audio_is_channel_mask_spatialized(config->channel_mask)) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005461 return false;
5462 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005463 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005464 return true;
5465}
5466
5467void AudioPolicyManager::checkVirtualizerClientRoutes() {
5468 std::set<audio_stream_type_t> streamsToInvalidate;
5469 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent39095982021-08-24 18:29:27 +02005470 const sp<SwAudioOutputDescriptor>& desc = mOutputs[i];
5471 for (const sp<TrackClientDescriptor>& client : desc->getClientIterable()) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005472 audio_attributes_t attr = client->attributes();
5473 DeviceVector devices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false);
5474 AudioDeviceTypeAddrVector devicesTypeAddress = devices.toTypeAddrVector();
5475 audio_config_base_t clientConfig = client->config();
5476 audio_config_t config = audio_config_initializer(&clientConfig);
Eric Laurent39095982021-08-24 18:29:27 +02005477 if (desc != mSpatializerOutput
Andy Hung9dd1a5b2022-05-10 15:39:39 -07005478 && canBeSpatializedInt(&attr, &config, devicesTypeAddress)) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005479 streamsToInvalidate.insert(client->stream());
5480 }
5481 }
5482 }
5483
5484 for (audio_stream_type_t stream : streamsToInvalidate) {
5485 mpClientInterface->invalidateStream(stream);
5486 }
5487}
5488
Eric Laurente191d1b2022-04-15 11:59:25 +02005489
5490bool AudioPolicyManager::isOutputOnlyAvailableRouteToSomeDevice(
5491 const sp<SwAudioOutputDescriptor>& outputDesc) {
5492 if (outputDesc->isDuplicated()) {
5493 return false;
5494 }
5495 DeviceVector devices = outputDesc->supportedDevices();
5496 for (size_t i = 0; i < mOutputs.size(); i++) {
5497 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
5498 if (desc == outputDesc || desc->isDuplicated()) {
5499 continue;
5500 }
5501 DeviceVector sharedDevices = desc->filterSupportedDevices(devices);
5502 if (!sharedDevices.isEmpty()
5503 && (desc->devicesSupportEncodedFormats(sharedDevices.types())
5504 == outputDesc->devicesSupportEncodedFormats(sharedDevices.types()))) {
5505 return false;
5506 }
5507 }
5508 return true;
5509}
5510
5511
Eric Laurentfa0f6742021-08-17 18:39:44 +02005512status_t AudioPolicyManager::getSpatializerOutput(const audio_config_base_t *mixerConfig,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005513 const audio_attributes_t *attr,
5514 audio_io_handle_t *output) {
5515 *output = AUDIO_IO_HANDLE_NONE;
5516
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005517 DeviceVector devices = mEngine->getOutputDevicesForAttributes(*attr, nullptr, false);
5518 AudioDeviceTypeAddrVector devicesTypeAddress = devices.toTypeAddrVector();
5519 audio_config_t *configPtr = nullptr;
5520 audio_config_t config;
5521 if (mixerConfig != nullptr) {
5522 config = audio_config_initializer(mixerConfig);
5523 configPtr = &config;
5524 }
Andy Hung9dd1a5b2022-05-10 15:39:39 -07005525 if (!canBeSpatializedInt(attr, configPtr, devicesTypeAddress)) {
Eric Laurente191d1b2022-04-15 11:59:25 +02005526 ALOGV("%s provided attributes or mixer config cannot be spatialized", __func__);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005527 return BAD_VALUE;
5528 }
5529
5530 sp<IOProfile> profile =
Eric Laurent39095982021-08-24 18:29:27 +02005531 getSpatializerOutputProfile(configPtr, devicesTypeAddress);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005532 if (profile == nullptr) {
Eric Laurente191d1b2022-04-15 11:59:25 +02005533 ALOGV("%s no suitable output profile for provided attributes or mixer config", __func__);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005534 return BAD_VALUE;
5535 }
5536
Eric Laurente191d1b2022-04-15 11:59:25 +02005537 std::vector<sp<SwAudioOutputDescriptor>> spatializerOutputs;
Eric Laurent39095982021-08-24 18:29:27 +02005538 for (size_t i = 0; i < mOutputs.size(); i++) {
5539 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente191d1b2022-04-15 11:59:25 +02005540 if (!desc->isDuplicated()
5541 && (desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0) {
5542 spatializerOutputs.push_back(desc);
5543 ALOGV("%s adding opened spatializer Output %d", __func__, desc->mIoHandle);
Eric Laurent39095982021-08-24 18:29:27 +02005544 }
5545 }
Eric Laurente191d1b2022-04-15 11:59:25 +02005546 mSpatializerOutput.clear();
5547 bool outputsChanged = false;
5548 for (const auto& desc : spatializerOutputs) {
5549 if (desc->mProfile == profile
5550 && (configPtr == nullptr
5551 || configPtr->channel_mask == desc->mMixerChannelMask)) {
5552 mSpatializerOutput = desc;
5553 ALOGV("%s reusing current spatializer output %d", __func__, desc->mIoHandle);
5554 } else {
5555 ALOGV("%s closing spatializerOutput output %d to match channel mask %#x"
5556 " and devices %s", __func__, desc->mIoHandle,
5557 configPtr != nullptr ? configPtr->channel_mask : 0,
5558 devices.toString().c_str());
5559 closeOutput(desc->mIoHandle);
5560 outputsChanged = true;
5561 }
Eric Laurent39095982021-08-24 18:29:27 +02005562 }
5563
Eric Laurente191d1b2022-04-15 11:59:25 +02005564 if (mSpatializerOutput == nullptr) {
Eric Laurentb4f42a92022-01-17 17:37:31 +01005565 sp<SwAudioOutputDescriptor> desc =
5566 openOutputWithProfileAndDevice(profile, devices, mixerConfig);
Eric Laurente191d1b2022-04-15 11:59:25 +02005567 if (desc != nullptr) {
5568 mSpatializerOutput = desc;
5569 outputsChanged = true;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005570 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005571 }
5572
5573 checkVirtualizerClientRoutes();
5574
Eric Laurente191d1b2022-04-15 11:59:25 +02005575 if (outputsChanged) {
5576 mPreviousOutputs = mOutputs;
5577 mpClientInterface->onAudioPortListUpdate();
5578 }
5579
5580 if (mSpatializerOutput == nullptr) {
5581 ALOGV("%s could not open spatializer output with requested config", __func__);
5582 return BAD_VALUE;
5583 }
Eric Laurent39095982021-08-24 18:29:27 +02005584 *output = mSpatializerOutput->mIoHandle;
Eric Laurente191d1b2022-04-15 11:59:25 +02005585 ALOGV("%s returning new spatializer output %d", __func__, *output);
5586 return OK;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005587}
5588
Eric Laurentfa0f6742021-08-17 18:39:44 +02005589status_t AudioPolicyManager::releaseSpatializerOutput(audio_io_handle_t output) {
5590 if (mSpatializerOutput == nullptr) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005591 return INVALID_OPERATION;
5592 }
Eric Laurentfa0f6742021-08-17 18:39:44 +02005593 if (mSpatializerOutput->mIoHandle != output) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005594 return BAD_VALUE;
5595 }
Eric Laurent39095982021-08-24 18:29:27 +02005596
Eric Laurente191d1b2022-04-15 11:59:25 +02005597 if (!isOutputOnlyAvailableRouteToSomeDevice(mSpatializerOutput)) {
5598 ALOGV("%s closing spatializer output %d", __func__, mSpatializerOutput->mIoHandle);
5599 closeOutput(mSpatializerOutput->mIoHandle);
5600 //from now on mSpatializerOutput is null
5601 checkVirtualizerClientRoutes();
5602 }
Eric Laurent39095982021-08-24 18:29:27 +02005603
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005604 return NO_ERROR;
5605}
5606
Eric Laurente552edb2014-03-10 17:42:56 -07005607// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07005608// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07005609// ----------------------------------------------------------------------------
Eric Laurent6a94d692014-05-20 11:18:06 -07005610uint32_t AudioPolicyManager::nextAudioPortGeneration()
5611{
Mikhail Naganov2773dd72017-12-08 10:12:11 -08005612 return mAudioPortGeneration++;
Eric Laurent6a94d692014-05-20 11:18:06 -07005613}
5614
Mikhail Naganovb0fbc1b2023-04-28 13:06:32 -07005615AudioPolicyManager::AudioPolicyManager(const sp<const AudioPolicyConfig>& config,
Mikhail Naganovabb04782023-05-02 13:56:01 -07005616 EngineInstance&& engine,
Mikhail Naganovb0fbc1b2023-04-28 13:06:32 -07005617 AudioPolicyClientInterface *clientInterface)
Eric Laurente552edb2014-03-10 17:42:56 -07005618 :
Andy Hung4ef19fa2018-05-15 19:35:29 -07005619 mUidCached(AID_AUDIOSERVER), // no need to call getuid(), there's only one of us running.
Mikhail Naganovb0fbc1b2023-04-28 13:06:32 -07005620 mConfig(config),
Mikhail Naganovabb04782023-05-02 13:56:01 -07005621 mEngine(std::move(engine)),
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005622 mpClientInterface(clientInterface),
Eric Laurente552edb2014-03-10 17:42:56 -07005623 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
Eric Laurent3a4311c2014-03-17 12:00:47 -07005624 mA2dpSuspended(false),
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005625 mAudioPortGeneration(1),
5626 mBeaconMuteRefCount(0),
5627 mBeaconPlayingRefCount(0),
Eric Laurent9459fb02015-08-12 18:36:32 -07005628 mBeaconMuted(false),
Andy Hung2ddee192015-12-18 17:34:44 -08005629 mTtsOutputAvailable(false),
Eric Laurent36829f92017-04-07 19:04:42 -07005630 mMasterMono(false),
Eric Laurent4eb58f12018-12-07 16:41:02 -08005631 mMusicEffectOutput(AUDIO_IO_HANDLE_NONE)
Eric Laurente552edb2014-03-10 17:42:56 -07005632{
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005633}
François Gaffied1ab2bd2015-12-02 18:20:06 +01005634
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005635status_t AudioPolicyManager::initialize() {
Mikhail Naganovabb04782023-05-02 13:56:01 -07005636 if (mEngine == nullptr) {
5637 return NO_INIT;
François Gaffie2110e042015-03-24 08:41:51 +01005638 }
5639 mEngine->setObserver(this);
5640 status_t status = mEngine->initCheck();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005641 if (status != NO_ERROR) {
5642 LOG_FATAL("Policy engine not initialized(err=%d)", status);
5643 return status;
5644 }
François Gaffie2110e042015-03-24 08:41:51 +01005645
jiabin76e829d2023-04-04 21:02:36 +00005646 // The actual device selection cache will be updated when calling `updateDevicesAndOutputs`
5647 // at the end of this function.
5648 mEngine->initializeDeviceSelectionCache();
Eric Laurent1d69c872021-01-11 18:53:01 +01005649 mCommunnicationStrategy = mEngine->getProductStrategyForAttributes(
5650 mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL));
5651
Mikhail Naganovb0fbc1b2023-04-28 13:06:32 -07005652 // after parsing the config, mConfig contain all known devices;
Eric Laurente552edb2014-03-10 17:42:56 -07005653 // open all output streams needed to access attached devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07005654 onNewAudioModulesAvailableInt(nullptr /*newDevices*/);
François Gaffie11d30102018-11-02 16:09:09 +01005655
Eric Laurent3a4311c2014-03-17 12:00:47 -07005656 // make sure default device is reachable
Mikhail Naganovb0fbc1b2023-04-28 13:06:32 -07005657 if (const auto defaultOutputDevice = mConfig->getDefaultOutputDevice();
5658 defaultOutputDevice == nullptr ||
5659 !mAvailableOutputDevices.contains(defaultOutputDevice)) {
5660 ALOGE_IF(defaultOutputDevice != nullptr, "Default device %s is unreachable",
5661 defaultOutputDevice->toString().c_str());
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005662 status = NO_INIT;
Eric Laurent3a4311c2014-03-17 12:00:47 -07005663 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02005664 ALOGW_IF(mPrimaryOutput == nullptr, "The policy configuration does not declare a primary output");
Eric Laurente552edb2014-03-10 17:42:56 -07005665
Tomoharu Kasahara71c90912018-10-31 09:10:12 +09005666 // Silence ALOGV statements
5667 property_set("log.tag." LOG_TAG, "D");
5668
Eric Laurente552edb2014-03-10 17:42:56 -07005669 updateDevicesAndOutputs();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005670 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07005671}
5672
Eric Laurente0720872014-03-11 09:30:41 -07005673AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07005674{
Eric Laurente552edb2014-03-10 17:42:56 -07005675 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08005676 mOutputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07005677 }
5678 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08005679 mInputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07005680 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07005681 mAvailableOutputDevices.clear();
5682 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07005683 mOutputs.clear();
5684 mInputs.clear();
5685 mHwModules.clear();
Mikhail Naganov100f0122018-11-29 11:22:16 -08005686 mManualSurroundFormats.clear();
Mikhail Naganovb0fbc1b2023-04-28 13:06:32 -07005687 mConfig.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07005688}
5689
Eric Laurente0720872014-03-11 09:30:41 -07005690status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07005691{
Eric Laurent87ffa392015-05-22 10:32:38 -07005692 return hasPrimaryOutput() ? NO_ERROR : NO_INIT;
Eric Laurente552edb2014-03-10 17:42:56 -07005693}
5694
Eric Laurente552edb2014-03-10 17:42:56 -07005695// ---
5696
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005697void AudioPolicyManager::onNewAudioModulesAvailable()
5698{
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07005699 DeviceVector newDevices;
5700 onNewAudioModulesAvailableInt(&newDevices);
5701 if (!newDevices.empty()) {
5702 nextAudioPortGeneration();
5703 mpClientInterface->onAudioPortListUpdate();
5704 }
5705}
5706
5707void AudioPolicyManager::onNewAudioModulesAvailableInt(DeviceVector *newDevices)
5708{
Mikhail Naganovb0fbc1b2023-04-28 13:06:32 -07005709 for (const auto& hwModule : mConfig->getHwModules()) {
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005710 if (std::find(mHwModules.begin(), mHwModules.end(), hwModule) != mHwModules.end()) {
5711 continue;
5712 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005713 if (hwModule->getHandle() == AUDIO_MODULE_HANDLE_NONE) {
Mikhail Naganov1fba38c2023-05-03 17:45:36 -07005714 if (audio_module_handle_t handle = mpClientInterface->loadHwModule(hwModule->getName());
5715 handle != AUDIO_MODULE_HANDLE_NONE) {
5716 hwModule->setHandle(handle);
5717 } else {
5718 ALOGW("could not load HW module %s", hwModule->getName());
5719 continue;
5720 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005721 }
5722 mHwModules.push_back(hwModule);
Dean Wheatley12a87132021-04-16 10:08:49 +10005723 // open all output streams needed to access attached devices.
5724 // direct outputs are closed immediately after checking the availability of attached devices
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005725 // This also validates mAvailableOutputDevices list
5726 for (const auto& outProfile : hwModule->getOutputProfiles()) {
5727 if (!outProfile->canOpenNewIo()) {
5728 ALOGE("Invalid Output profile max open count %u for profile %s",
5729 outProfile->maxOpenCount, outProfile->getTagName().c_str());
5730 continue;
5731 }
5732 if (!outProfile->hasSupportedDevices()) {
5733 ALOGW("Output profile contains no device on module %s", hwModule->getName());
5734 continue;
5735 }
Carter Hsu1a3364a2022-01-21 15:32:56 +08005736 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_TTS) != 0 ||
5737 (outProfile->getFlags() & AUDIO_OUTPUT_FLAG_ULTRASOUND) != 0) {
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005738 mTtsOutputAvailable = true;
5739 }
5740
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005741 const DeviceVector &supportedDevices = outProfile->getSupportedDevices();
Mikhail Naganovb0fbc1b2023-04-28 13:06:32 -07005742 DeviceVector availProfileDevices = supportedDevices.filter(mConfig->getOutputDevices());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005743 sp<DeviceDescriptor> supportedDevice = 0;
Mikhail Naganovb0fbc1b2023-04-28 13:06:32 -07005744 if (supportedDevices.contains(mConfig->getDefaultOutputDevice())) {
5745 supportedDevice = mConfig->getDefaultOutputDevice();
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005746 } else {
5747 // choose first device present in profile's SupportedDevices also part of
5748 // mAvailableOutputDevices.
5749 if (availProfileDevices.isEmpty()) {
5750 continue;
5751 }
5752 supportedDevice = availProfileDevices.itemAt(0);
5753 }
Mikhail Naganovb0fbc1b2023-04-28 13:06:32 -07005754 if (!mConfig->getOutputDevices().contains(supportedDevice)) {
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005755 continue;
5756 }
5757 sp<SwAudioOutputDescriptor> outputDesc = new SwAudioOutputDescriptor(outProfile,
5758 mpClientInterface);
5759 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentf1f22e72021-07-13 14:04:14 +02005760 status_t status = outputDesc->open(nullptr /* halConfig */, nullptr /* mixerConfig */,
5761 DeviceVector(supportedDevice),
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005762 AUDIO_STREAM_DEFAULT,
5763 AUDIO_OUTPUT_FLAG_NONE, &output);
5764 if (status != NO_ERROR) {
5765 ALOGW("Cannot open output stream for devices %s on hw module %s",
5766 supportedDevice->toString().c_str(), hwModule->getName());
5767 continue;
5768 }
5769 for (const auto &device : availProfileDevices) {
5770 // give a valid ID to an attached device once confirmed it is reachable
5771 if (!device->isAttached()) {
5772 device->attach(hwModule);
5773 mAvailableOutputDevices.add(device);
jiabin1c4794b2020-05-05 10:08:05 -07005774 device->setEncapsulationInfoFromHal(mpClientInterface);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07005775 if (newDevices) newDevices->add(device);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005776 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
5777 }
5778 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02005779 if (mPrimaryOutput == nullptr &&
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005780 outProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
5781 mPrimaryOutput = outputDesc;
5782 }
Eric Laurent39095982021-08-24 18:29:27 +02005783 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
Eric Laurentc529cf62020-04-17 18:19:10 -07005784 outputDesc->close();
5785 } else {
5786 addOutput(output, outputDesc);
5787 setOutputDevices(outputDesc,
5788 DeviceVector(supportedDevice),
5789 true,
5790 0,
5791 NULL);
5792 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005793 }
5794 // open input streams needed to access attached devices to validate
5795 // mAvailableInputDevices list
5796 for (const auto& inProfile : hwModule->getInputProfiles()) {
5797 if (!inProfile->canOpenNewIo()) {
5798 ALOGE("Invalid Input profile max open count %u for profile %s",
5799 inProfile->maxOpenCount, inProfile->getTagName().c_str());
5800 continue;
5801 }
5802 if (!inProfile->hasSupportedDevices()) {
5803 ALOGW("Input profile contains no device on module %s", hwModule->getName());
5804 continue;
5805 }
5806 // chose first device present in profile's SupportedDevices also part of
5807 // available input devices
5808 const DeviceVector &supportedDevices = inProfile->getSupportedDevices();
Mikhail Naganovb0fbc1b2023-04-28 13:06:32 -07005809 DeviceVector availProfileDevices = supportedDevices.filter(mConfig->getInputDevices());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005810 if (availProfileDevices.isEmpty()) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01005811 ALOGV("%s: Input device list is empty! for profile %s",
5812 __func__, inProfile->getTagName().c_str());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005813 continue;
5814 }
5815 sp<AudioInputDescriptor> inputDesc =
5816 new AudioInputDescriptor(inProfile, mpClientInterface);
5817
5818 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
5819 status_t status = inputDesc->open(nullptr,
5820 availProfileDevices.itemAt(0),
5821 AUDIO_SOURCE_MIC,
5822 AUDIO_INPUT_FLAG_NONE,
5823 &input);
5824 if (status != NO_ERROR) {
5825 ALOGW("Cannot open input stream for device %s on hw module %s",
5826 availProfileDevices.toString().c_str(),
5827 hwModule->getName());
5828 continue;
5829 }
5830 for (const auto &device : availProfileDevices) {
5831 // give a valid ID to an attached device once confirmed it is reachable
5832 if (!device->isAttached()) {
5833 device->attach(hwModule);
5834 device->importAudioPortAndPickAudioProfile(inProfile, true);
5835 mAvailableInputDevices.add(device);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07005836 if (newDevices) newDevices->add(device);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005837 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
5838 }
5839 }
5840 inputDesc->close();
5841 }
5842 }
Eric Laurente191d1b2022-04-15 11:59:25 +02005843
5844 // Check if spatializer outputs can be closed until used.
5845 // mOutputs vector never contains duplicated outputs at this point.
5846 std::vector<audio_io_handle_t> outputsClosed;
5847 for (size_t i = 0; i < mOutputs.size(); i++) {
5848 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
5849 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0
5850 && !isOutputOnlyAvailableRouteToSomeDevice(desc)) {
5851 outputsClosed.push_back(desc->mIoHandle);
5852 desc->close();
5853 }
5854 }
5855 for (auto output : outputsClosed) {
5856 removeOutput(output);
5857 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005858}
5859
Eric Laurent98e38192018-02-15 18:31:53 -08005860void AudioPolicyManager::addOutput(audio_io_handle_t output,
5861 const sp<SwAudioOutputDescriptor>& outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07005862{
Eric Laurent1c333e22014-05-20 10:48:17 -07005863 mOutputs.add(output, outputDesc);
jiabin9a3361e2019-10-01 09:38:30 -07005864 applyStreamVolumes(outputDesc, DeviceTypeSet(), 0 /* delayMs */, true /* force */);
Andy Hung2ddee192015-12-18 17:34:44 -08005865 updateMono(output); // update mono status when adding to output list
Eric Laurent36829f92017-04-07 19:04:42 -07005866 selectOutputForMusicEffects();
Eric Laurent6a94d692014-05-20 11:18:06 -07005867 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07005868}
5869
François Gaffie53615e22015-03-19 09:24:12 +01005870void AudioPolicyManager::removeOutput(audio_io_handle_t output)
5871{
Francois Gaffiebce7cd42020-10-14 16:13:20 +02005872 if (mPrimaryOutput != 0 && mPrimaryOutput == mOutputs.valueFor(output)) {
5873 ALOGV("%s: removing primary output", __func__);
5874 mPrimaryOutput = nullptr;
5875 }
François Gaffie53615e22015-03-19 09:24:12 +01005876 mOutputs.removeItem(output);
Eric Laurent36829f92017-04-07 19:04:42 -07005877 selectOutputForMusicEffects();
François Gaffie53615e22015-03-19 09:24:12 +01005878}
5879
Eric Laurent98e38192018-02-15 18:31:53 -08005880void AudioPolicyManager::addInput(audio_io_handle_t input,
5881 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07005882{
Eric Laurent1c333e22014-05-20 10:48:17 -07005883 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07005884 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07005885}
Eric Laurente552edb2014-03-10 17:42:56 -07005886
François Gaffie11d30102018-11-02 16:09:09 +01005887status_t AudioPolicyManager::checkOutputsForDevice(const sp<DeviceDescriptor>& device,
François Gaffie53615e22015-03-19 09:24:12 +01005888 audio_policy_dev_state_t state,
François Gaffie11d30102018-11-02 16:09:09 +01005889 SortedVector<audio_io_handle_t>& outputs)
Eric Laurente552edb2014-03-10 17:42:56 -07005890{
François Gaffie11d30102018-11-02 16:09:09 +01005891 audio_devices_t deviceType = device->type();
jiabince9f20e2019-09-12 16:29:15 -07005892 const String8 &address = String8(device->address().c_str());
Eric Laurentc75307b2015-03-17 15:29:32 -07005893 sp<SwAudioOutputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07005894
François Gaffie11d30102018-11-02 16:09:09 +01005895 if (audio_device_is_digital(deviceType)) {
Eric Laurentcc750d32015-06-25 11:48:20 -07005896 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01005897 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07005898 }
Eric Laurente552edb2014-03-10 17:42:56 -07005899
Eric Laurent3b73df72014-03-11 09:06:29 -07005900 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
jiabinb4fed192020-09-22 14:45:40 -07005901 // first call getAudioPort to get the supported attributes from the HAL
5902 struct audio_port_v7 port = {};
5903 device->toAudioPort(&port);
5904 status_t status = mpClientInterface->getAudioPort(&port);
5905 if (status == NO_ERROR) {
5906 device->importAudioPort(port);
5907 }
5908
5909 // then list already open outputs that can be routed to this device
Eric Laurente552edb2014-03-10 17:42:56 -07005910 for (size_t i = 0; i < mOutputs.size(); i++) {
5911 desc = mOutputs.valueAt(i);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005912 if (!desc->isDuplicated() && desc->supportsDevice(device)
jiabin9a3361e2019-10-01 09:38:30 -07005913 && desc->devicesSupportEncodedFormats({deviceType})) {
François Gaffie11d30102018-11-02 16:09:09 +01005914 ALOGV("checkOutputsForDevice(): adding opened output %d on device %s",
5915 mOutputs.keyAt(i), device->toString().c_str());
5916 outputs.add(mOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07005917 }
5918 }
5919 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07005920 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08005921 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005922 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
5923 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
François Gaffie11d30102018-11-02 16:09:09 +01005924 if (profile->supportsDevice(device)) {
5925 profiles.add(profile);
5926 ALOGV("checkOutputsForDevice(): adding profile %zu from module %s",
5927 j, hwModule->getName());
Eric Laurente552edb2014-03-10 17:42:56 -07005928 }
5929 }
5930 }
5931
Eric Laurent7b279bb2015-12-14 10:18:23 -08005932 ALOGV(" found %zu profiles, %zu outputs", profiles.size(), outputs.size());
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005933
Eric Laurente552edb2014-03-10 17:42:56 -07005934 if (profiles.isEmpty() && outputs.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01005935 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07005936 return BAD_VALUE;
5937 }
5938
5939 // open outputs for matching profiles if needed. Direct outputs are also opened to
5940 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
5941 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07005942 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07005943
5944 // nothing to do if one output is already opened for this profile
5945 size_t j;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005946 for (j = 0; j < outputs.size(); j++) {
5947 desc = mOutputs.valueFor(outputs.itemAt(j));
Eric Laurente552edb2014-03-10 17:42:56 -07005948 if (!desc->isDuplicated() && desc->mProfile == profile) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07005949 // matching profile: save the sample rates, format and channel masks supported
5950 // by the profile in our device descriptor
François Gaffie11d30102018-11-02 16:09:09 +01005951 if (audio_device_is_digital(deviceType)) {
jiabin4ef93452019-09-10 14:29:54 -07005952 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07005953 }
Eric Laurente552edb2014-03-10 17:42:56 -07005954 break;
5955 }
5956 }
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005957 if (j != outputs.size()) {
Eric Laurente552edb2014-03-10 17:42:56 -07005958 continue;
5959 }
5960
Eric Laurent3974e3b2017-12-07 17:58:43 -08005961 if (!profile->canOpenNewIo()) {
5962 ALOGW("Max Output number %u already opened for this profile %s",
5963 profile->maxOpenCount, profile->getTagName().c_str());
5964 continue;
5965 }
5966
Eric Laurent83efe1c2017-07-09 16:51:08 -07005967 ALOGV("opening output for device %08x with params %s profile %p name %s",
jiabin5740f082019-08-19 15:08:30 -07005968 deviceType, address.string(), profile.get(), profile->getName().c_str());
jiabinbce0c1d2020-10-05 11:20:18 -07005969 desc = openOutputWithProfileAndDevice(profile, DeviceVector(device));
5970 audio_io_handle_t output = desc == nullptr ? AUDIO_IO_HANDLE_NONE : desc->mIoHandle;
Eric Laurentcf2c0212014-07-25 16:20:43 -07005971 if (output == AUDIO_IO_HANDLE_NONE) {
François Gaffie11d30102018-11-02 16:09:09 +01005972 ALOGW("checkOutputsForDevice() could not open output for device %x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07005973 profiles.removeAt(profile_index);
5974 profile_index--;
5975 } else {
5976 outputs.add(output);
Paul McLean9080a4c2015-06-18 08:24:02 -07005977 // Load digital format info only for digital devices
François Gaffie11d30102018-11-02 16:09:09 +01005978 if (audio_device_is_digital(deviceType)) {
jiabinbce0c1d2020-10-05 11:20:18 -07005979 // TODO: when getAudioPort is ready, it may not be needed to import the audio
5980 // port but just pick audio profile
jiabin4ef93452019-09-10 14:29:54 -07005981 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07005982 }
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07005983
François Gaffie11d30102018-11-02 16:09:09 +01005984 if (device_distinguishes_on_address(deviceType)) {
5985 ALOGV("checkOutputsForDevice(): setOutputDevices %s",
5986 device->toString().c_str());
5987 setOutputDevices(desc, DeviceVector(device), true/*force*/, 0/*delay*/,
5988 NULL/*patch handle*/);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005989 }
Eric Laurente552edb2014-03-10 17:42:56 -07005990 ALOGV("checkOutputsForDevice(): adding output %d", output);
5991 }
5992 }
5993
5994 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01005995 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07005996 return BAD_VALUE;
5997 }
Eric Laurentd4692962014-05-05 18:13:44 -07005998 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07005999 // check if one opened output is not needed any more after disconnecting one device
6000 for (size_t i = 0; i < mOutputs.size(); i++) {
6001 desc = mOutputs.valueAt(i);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006002 if (!desc->isDuplicated()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08006003 // exact match on device
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006004 if (device_distinguishes_on_address(deviceType) && desc->supportsDevice(device)
Francois Gaffiec7d4c222021-12-02 11:12:52 +01006005 && desc->containsSingleDeviceSupportingEncodedFormats(device)) {
François Gaffie11d30102018-11-02 16:09:09 +01006006 outputs.add(mOutputs.keyAt(i));
Francois Gaffie716e1432019-01-14 16:58:59 +01006007 } else if (!mAvailableOutputDevices.containsAtLeastOne(desc->supportedDevices())) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006008 ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
6009 mOutputs.keyAt(i));
6010 outputs.add(mOutputs.keyAt(i));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006011 }
Eric Laurente552edb2014-03-10 17:42:56 -07006012 }
6013 }
Eric Laurentd4692962014-05-05 18:13:44 -07006014 // Clear any profiles associated with the disconnected device.
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006015 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006016 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
6017 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
jiabinbce0c1d2020-10-05 11:20:18 -07006018 if (!profile->supportsDevice(device)) {
6019 continue;
6020 }
6021 ALOGV("checkOutputsForDevice(): "
6022 "clearing direct output profile %zu on module %s",
6023 j, hwModule->getName());
6024 profile->clearAudioProfiles();
6025 if (!profile->hasDynamicAudioProfile()) {
6026 continue;
6027 }
6028 // When a device is disconnected, if there is an IOProfile that contains dynamic
6029 // profiles and supports the disconnected device, call getAudioPort to repopulate
6030 // the capabilities of the devices that is supported by the IOProfile.
6031 for (const auto& supportedDevice : profile->getSupportedDevices()) {
6032 if (supportedDevice == device ||
6033 !mAvailableOutputDevices.contains(supportedDevice)) {
6034 continue;
6035 }
6036 struct audio_port_v7 port;
6037 supportedDevice->toAudioPort(&port);
6038 status_t status = mpClientInterface->getAudioPort(&port);
6039 if (status == NO_ERROR) {
6040 supportedDevice->importAudioPort(port);
6041 }
Eric Laurente552edb2014-03-10 17:42:56 -07006042 }
6043 }
6044 }
6045 }
6046 return NO_ERROR;
6047}
6048
François Gaffie11d30102018-11-02 16:09:09 +01006049status_t AudioPolicyManager::checkInputsForDevice(const sp<DeviceDescriptor>& device,
Eric Laurent0dd51852019-04-19 18:18:58 -07006050 audio_policy_dev_state_t state)
Eric Laurentd4692962014-05-05 18:13:44 -07006051{
Eric Laurent1f2f2232014-06-02 12:01:23 -07006052 sp<AudioInputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07006053
François Gaffie11d30102018-11-02 16:09:09 +01006054 if (audio_device_is_digital(device->type())) {
Eric Laurentcc750d32015-06-25 11:48:20 -07006055 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01006056 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07006057 }
6058
Eric Laurentd4692962014-05-05 18:13:44 -07006059 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
jiabinbf5f4262023-04-12 21:48:34 +00006060 // first call getAudioPort to get the supported attributes from the HAL
6061 struct audio_port_v7 port = {};
6062 device->toAudioPort(&port);
6063 status_t status = mpClientInterface->getAudioPort(&port);
6064 if (status == NO_ERROR) {
6065 device->importAudioPort(port);
6066 }
6067
Eric Laurent0dd51852019-04-19 18:18:58 -07006068 // look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07006069 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006070 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07006071 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006072 profile_index < hwModule->getInputProfiles().size();
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006073 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006074 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Eric Laurent275e8e92014-11-30 15:14:47 -08006075
François Gaffie11d30102018-11-02 16:09:09 +01006076 if (profile->supportsDevice(device)) {
6077 profiles.add(profile);
6078 ALOGV("checkInputsForDevice(): adding profile %zu from module %s",
6079 profile_index, hwModule->getName());
Eric Laurentd4692962014-05-05 18:13:44 -07006080 }
6081 }
6082 }
6083
Eric Laurent0dd51852019-04-19 18:18:58 -07006084 if (profiles.isEmpty()) {
6085 ALOGW("%s: No input profile available for device %s",
6086 __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07006087 return BAD_VALUE;
6088 }
6089
6090 // open inputs for matching profiles if needed. Direct inputs are also opened to
6091 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
6092 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
6093
Eric Laurent1c333e22014-05-20 10:48:17 -07006094 sp<IOProfile> profile = profiles[profile_index];
Eric Laurent3974e3b2017-12-07 17:58:43 -08006095
Eric Laurentd4692962014-05-05 18:13:44 -07006096 // nothing to do if one input is already opened for this profile
6097 size_t input_index;
6098 for (input_index = 0; input_index < mInputs.size(); input_index++) {
6099 desc = mInputs.valueAt(input_index);
6100 if (desc->mProfile == profile) {
François Gaffie11d30102018-11-02 16:09:09 +01006101 if (audio_device_is_digital(device->type())) {
jiabin4ef93452019-09-10 14:29:54 -07006102 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006103 }
Eric Laurentd4692962014-05-05 18:13:44 -07006104 break;
6105 }
6106 }
6107 if (input_index != mInputs.size()) {
6108 continue;
6109 }
6110
Eric Laurent3974e3b2017-12-07 17:58:43 -08006111 if (!profile->canOpenNewIo()) {
6112 ALOGW("Max Input number %u already opened for this profile %s",
6113 profile->maxOpenCount, profile->getTagName().c_str());
6114 continue;
6115 }
6116
Eric Laurentfe231122017-11-17 17:48:06 -08006117 desc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentcf2c0212014-07-25 16:20:43 -07006118 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
jiabinbf5f4262023-04-12 21:48:34 +00006119 status = desc->open(nullptr, device, AUDIO_SOURCE_MIC, AUDIO_INPUT_FLAG_NONE, &input);
Eric Laurentd4692962014-05-05 18:13:44 -07006120
Eric Laurentcf2c0212014-07-25 16:20:43 -07006121 if (status == NO_ERROR) {
jiabince9f20e2019-09-12 16:29:15 -07006122 const String8& address = String8(device->address().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07006123 if (!address.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006124 char *param = audio_device_address_to_parameter(device->type(), address);
Eric Laurentcf2c0212014-07-25 16:20:43 -07006125 mpClientInterface->setParameters(input, String8(param));
6126 free(param);
Eric Laurentd4692962014-05-05 18:13:44 -07006127 }
François Gaffie11d30102018-11-02 16:09:09 +01006128 updateAudioProfiles(device, input, profile->getAudioProfiles());
François Gaffie112b0af2015-11-19 16:13:25 +01006129 if (!profile->hasValidAudioProfile()) {
Eric Laurentd4692962014-05-05 18:13:44 -07006130 ALOGW("checkInputsForDevice() direct input missing param");
Eric Laurentfe231122017-11-17 17:48:06 -08006131 desc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07006132 input = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07006133 }
6134
Eric Laurent0dd51852019-04-19 18:18:58 -07006135 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07006136 addInput(input, desc);
6137 }
6138 } // endif input != 0
6139
Eric Laurentcf2c0212014-07-25 16:20:43 -07006140 if (input == AUDIO_IO_HANDLE_NONE) {
Pattydd807582021-11-04 21:01:03 +08006141 ALOGW("%s could not open input for device %s", __func__,
François Gaffie11d30102018-11-02 16:09:09 +01006142 device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07006143 profiles.removeAt(profile_index);
6144 profile_index--;
6145 } else {
François Gaffie11d30102018-11-02 16:09:09 +01006146 if (audio_device_is_digital(device->type())) {
jiabin4ef93452019-09-10 14:29:54 -07006147 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006148 }
Eric Laurentd4692962014-05-05 18:13:44 -07006149 ALOGV("checkInputsForDevice(): adding input %d", input);
6150 }
6151 } // end scan profiles
6152
6153 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006154 ALOGW("%s: No input available for device %s", __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07006155 return BAD_VALUE;
6156 }
6157 } else {
6158 // Disconnect
Eric Laurentd4692962014-05-05 18:13:44 -07006159 // Clear any profiles associated with the disconnected device.
Mikhail Naganovd4120142017-12-06 15:49:22 -08006160 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07006161 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006162 profile_index < hwModule->getInputProfiles().size();
Eric Laurentd4692962014-05-05 18:13:44 -07006163 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006164 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Francois Gaffie716e1432019-01-14 16:58:59 +01006165 if (profile->supportsDevice(device)) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08006166 ALOGV("checkInputsForDevice(): clearing direct input profile %zu on module %s",
6167 profile_index, hwModule->getName());
François Gaffie112b0af2015-11-19 16:13:25 +01006168 profile->clearAudioProfiles();
Eric Laurentd4692962014-05-05 18:13:44 -07006169 }
6170 }
6171 }
6172 } // end disconnect
6173
6174 return NO_ERROR;
6175}
6176
6177
Eric Laurente0720872014-03-11 09:30:41 -07006178void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07006179{
6180 ALOGV("closeOutput(%d)", output);
6181
François Gaffie1c878552018-11-22 16:53:21 +01006182 sp<SwAudioOutputDescriptor> closingOutput = mOutputs.valueFor(output);
6183 if (closingOutput == NULL) {
Eric Laurente552edb2014-03-10 17:42:56 -07006184 ALOGW("closeOutput() unknown output %d", output);
6185 return;
6186 }
Mikhail Naganov32ebca32019-03-22 15:42:52 -07006187 const bool closingOutputWasActive = closingOutput->isActive();
François Gaffie1c878552018-11-22 16:53:21 +01006188 mPolicyMixes.closeOutput(closingOutput);
Eric Laurent275e8e92014-11-30 15:14:47 -08006189
Eric Laurente552edb2014-03-10 17:42:56 -07006190 // look for duplicated outputs connected to the output being removed.
6191 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie1c878552018-11-22 16:53:21 +01006192 sp<SwAudioOutputDescriptor> dupOutput = mOutputs.valueAt(i);
6193 if (dupOutput->isDuplicated() &&
6194 (dupOutput->mOutput1 == closingOutput || dupOutput->mOutput2 == closingOutput)) {
6195 sp<SwAudioOutputDescriptor> remainingOutput =
6196 dupOutput->mOutput1 == closingOutput ? dupOutput->mOutput2 : dupOutput->mOutput1;
Eric Laurente552edb2014-03-10 17:42:56 -07006197 // As all active tracks on duplicated output will be deleted,
6198 // and as they were also referenced on the other output, the reference
6199 // count for their stream type must be adjusted accordingly on
6200 // the other output.
François Gaffie1c878552018-11-22 16:53:21 +01006201 const bool wasActive = remainingOutput->isActive();
6202 // Note: no-op on the closing output where all clients has already been set inactive
6203 dupOutput->setAllClientsInactive();
Eric Laurent733ce942017-12-07 12:18:25 -08006204 // stop() will be a no op if the output is still active but is needed in case all
6205 // active streams refcounts where cleared above
6206 if (wasActive) {
François Gaffie1c878552018-11-22 16:53:21 +01006207 remainingOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08006208 }
Eric Laurente552edb2014-03-10 17:42:56 -07006209 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
6210 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
6211
6212 mpClientInterface->closeOutput(duplicatedOutput);
François Gaffie53615e22015-03-19 09:24:12 +01006213 removeOutput(duplicatedOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07006214 }
6215 }
6216
Eric Laurent05b90f82014-08-27 15:32:29 -07006217 nextAudioPortGeneration();
6218
François Gaffie1c878552018-11-22 16:53:21 +01006219 ssize_t index = mAudioPatches.indexOfKey(closingOutput->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07006220 if (index >= 0) {
6221 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006222 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
6223 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07006224 mAudioPatches.removeItemsAt(index);
6225 mpClientInterface->onAudioPatchListUpdate();
6226 }
6227
Mikhail Naganov32ebca32019-03-22 15:42:52 -07006228 if (closingOutputWasActive) {
6229 closingOutput->stop();
6230 }
François Gaffie1c878552018-11-22 16:53:21 +01006231 closingOutput->close();
Eric Laurente552edb2014-03-10 17:42:56 -07006232
François Gaffie53615e22015-03-19 09:24:12 +01006233 removeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07006234 mPreviousOutputs = mOutputs;
Eric Laurentb4f42a92022-01-17 17:37:31 +01006235 if (closingOutput == mSpatializerOutput) {
6236 mSpatializerOutput.clear();
6237 }
Dean Wheatley3023b382018-08-09 07:42:40 +10006238
6239 // MSD patches may have been released to support a non-MSD direct output. Reset MSD patch if
6240 // no direct outputs are open.
François Gaffie11d30102018-11-02 16:09:09 +01006241 if (!getMsdAudioOutDevices().isEmpty()) {
Dean Wheatley3023b382018-08-09 07:42:40 +10006242 bool directOutputOpen = false;
6243 for (size_t i = 0; i < mOutputs.size(); i++) {
6244 if (mOutputs[i]->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
6245 directOutputOpen = true;
6246 break;
6247 }
6248 }
6249 if (!directOutputOpen) {
Michael Chan6fb34492020-12-08 15:44:49 +11006250 ALOGV("no direct outputs open, reset MSD patches");
6251 // TODO: The MSD patches to be established here may differ to current MSD patches due to
6252 // how output devices for patching are resolved. Avoid by caching and reusing the
6253 // arguments to mEngine->getOutputDevicesForAttributes() when resolving which output
6254 // devices to patch to. This may be complicated by the fact that devices may become
6255 // unavailable.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11006256 setMsdOutputPatches();
Dean Wheatley3023b382018-08-09 07:42:40 +10006257 }
6258 }
Eric Laurent05b90f82014-08-27 15:32:29 -07006259}
6260
6261void AudioPolicyManager::closeInput(audio_io_handle_t input)
6262{
6263 ALOGV("closeInput(%d)", input);
6264
6265 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
6266 if (inputDesc == NULL) {
6267 ALOGW("closeInput() unknown input %d", input);
6268 return;
6269 }
6270
Eric Laurent6a94d692014-05-20 11:18:06 -07006271 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07006272
François Gaffie11d30102018-11-02 16:09:09 +01006273 sp<DeviceDescriptor> device = inputDesc->getDevice();
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08006274 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07006275 if (index >= 0) {
6276 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006277 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
6278 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07006279 mAudioPatches.removeItemsAt(index);
6280 mpClientInterface->onAudioPatchListUpdate();
6281 }
6282
Eric Laurentfe231122017-11-17 17:48:06 -08006283 inputDesc->close();
Eric Laurent05b90f82014-08-27 15:32:29 -07006284 mInputs.removeItem(input);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07006285
François Gaffie11d30102018-11-02 16:09:09 +01006286 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
6287 if (primaryInputDevices.contains(device) &&
Haynes Mathew George1d539d92018-03-16 11:40:49 -07006288 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07006289 mpClientInterface->setSoundTriggerCaptureState(false);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07006290 }
Eric Laurente552edb2014-03-10 17:42:56 -07006291}
6292
François Gaffie11d30102018-11-02 16:09:09 +01006293SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevices(
6294 const DeviceVector &devices,
6295 const SwAudioOutputCollection& openOutputs)
Eric Laurente552edb2014-03-10 17:42:56 -07006296{
6297 SortedVector<audio_io_handle_t> outputs;
6298
François Gaffie11d30102018-11-02 16:09:09 +01006299 ALOGVV("%s() devices %s", __func__, devices.toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07006300 for (size_t i = 0; i < openOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01006301 ALOGVV("output %zu isDuplicated=%d device=%s",
Eric Laurent8c7e6da2015-04-21 17:37:00 -07006302 i, openOutputs.valueAt(i)->isDuplicated(),
François Gaffie11d30102018-11-02 16:09:09 +01006303 openOutputs.valueAt(i)->supportedDevices().toString().c_str());
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006304 if (openOutputs.valueAt(i)->supportsAllDevices(devices)
jiabin9a3361e2019-10-01 09:38:30 -07006305 && openOutputs.valueAt(i)->devicesSupportEncodedFormats(devices.types())) {
François Gaffie11d30102018-11-02 16:09:09 +01006306 ALOGVV("%s() found output %d", __func__, openOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07006307 outputs.add(openOutputs.keyAt(i));
6308 }
6309 }
6310 return outputs;
6311}
6312
Mikhail Naganov37977152018-07-11 15:54:44 -07006313void AudioPolicyManager::checkForDeviceAndOutputChanges(std::function<bool()> onOutputsChecked)
6314{
6315 // checkA2dpSuspend must run before checkOutputForAllStrategies so that A2DP
6316 // output is suspended before any tracks are moved to it
6317 checkA2dpSuspend();
6318 checkOutputForAllStrategies();
Kevin Rocard153f92d2018-12-18 18:33:28 -08006319 checkSecondaryOutputs();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11006320 if (onOutputsChecked != nullptr && onOutputsChecked()) checkA2dpSuspend();
Mikhail Naganov37977152018-07-11 15:54:44 -07006321 updateDevicesAndOutputs();
Mikhail Naganov7bd9b8d2018-11-15 02:09:03 +00006322 if (mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD) != 0) {
Michael Chan6fb34492020-12-08 15:44:49 +11006323 // TODO: The MSD patches to be established here may differ to current MSD patches due to how
6324 // output devices for patching are resolved. Nevertheless, AudioTracks affected by device
6325 // configuration changes will ultimately be rerouted correctly. We can still avoid
6326 // unnecessary rerouting by caching and reusing the arguments to
6327 // mEngine->getOutputDevicesForAttributes() when resolving which output devices to patch to.
6328 // This may be complicated by the fact that devices may become unavailable.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11006329 setMsdOutputPatches();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11006330 }
Jean-Michel Trivi9a6b9ad2020-10-22 16:46:43 -07006331 // an event that changed routing likely occurred, inform upper layers
6332 mpClientInterface->onRoutingUpdated();
Mikhail Naganov37977152018-07-11 15:54:44 -07006333}
6334
François Gaffiec005e562018-11-06 15:04:49 +01006335bool AudioPolicyManager::followsSameRouting(const audio_attributes_t &lAttr,
6336 const audio_attributes_t &rAttr) const
Eric Laurente552edb2014-03-10 17:42:56 -07006337{
François Gaffiec005e562018-11-06 15:04:49 +01006338 return mEngine->getProductStrategyForAttributes(lAttr) ==
6339 mEngine->getProductStrategyForAttributes(rAttr);
6340}
6341
Francois Gaffieff1eb522020-05-06 18:37:04 +02006342void AudioPolicyManager::checkAudioSourceForAttributes(const audio_attributes_t &attr)
6343{
6344 for (size_t i = 0; i < mAudioSources.size(); i++) {
6345 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
6346 if (sourceDesc != nullptr && followsSameRouting(attr, sourceDesc->attributes())
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02006347 && sourceDesc->getPatchHandle() == AUDIO_PATCH_HANDLE_NONE
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02006348 && !isCallRxAudioSource(sourceDesc) && !sourceDesc->isInternal()) {
Francois Gaffieff1eb522020-05-06 18:37:04 +02006349 connectAudioSource(sourceDesc);
6350 }
6351 }
6352}
6353
6354void AudioPolicyManager::clearAudioSourcesForOutput(audio_io_handle_t output)
6355{
6356 for (size_t i = 0; i < mAudioSources.size(); i++) {
6357 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
6358 if (sourceDesc != nullptr && sourceDesc->swOutput().promote() != nullptr
6359 && sourceDesc->swOutput().promote()->mIoHandle == output) {
6360 disconnectAudioSource(sourceDesc);
6361 }
6362 }
6363}
6364
François Gaffiec005e562018-11-06 15:04:49 +01006365void AudioPolicyManager::checkOutputForAttributes(const audio_attributes_t &attr)
6366{
6367 auto psId = mEngine->getProductStrategyForAttributes(attr);
6368
6369 DeviceVector oldDevices = mEngine->getOutputDevicesForAttributes(attr, 0, true /*fromCache*/);
6370 DeviceVector newDevices = mEngine->getOutputDevicesForAttributes(attr, 0, false /*fromCache*/);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07006371
François Gaffie11d30102018-11-02 16:09:09 +01006372 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevices(oldDevices, mPreviousOutputs);
6373 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevices(newDevices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07006374
Eric Laurentc209fe42020-06-05 18:11:23 -07006375 uint32_t maxLatency = 0;
Eric Laurent56ed8842022-11-15 16:04:41 +01006376 std::vector<sp<SwAudioOutputDescriptor>> invalidatedOutputs;
Eric Laurentc209fe42020-06-05 18:11:23 -07006377 // take into account dynamic audio policies related changes: if a client is now associated
6378 // to a different policy mix than at creation time, invalidate corresponding stream
Eric Laurent56ed8842022-11-15 16:04:41 +01006379 for (size_t i = 0; i < mPreviousOutputs.size(); i++) {
Eric Laurentc209fe42020-06-05 18:11:23 -07006380 const sp<SwAudioOutputDescriptor>& desc = mPreviousOutputs.valueAt(i);
6381 if (desc->isDuplicated()) {
6382 continue;
Jean-Michel Trivife472e22014-12-16 14:23:13 -08006383 }
Eric Laurentc209fe42020-06-05 18:11:23 -07006384 for (const sp<TrackClientDescriptor>& client : desc->getClientIterable()) {
6385 if (mEngine->getProductStrategyForAttributes(client->attributes()) != psId) {
6386 continue;
6387 }
6388 sp<AudioPolicyMix> primaryMix;
Dean Wheatleyd082f472022-02-04 11:10:48 +11006389 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->config(),
6390 client->uid(), client->flags(), primaryMix, nullptr);
Eric Laurentc209fe42020-06-05 18:11:23 -07006391 if (status != OK) {
6392 continue;
6393 }
yucliuf4de36d2020-09-14 14:57:56 -07006394 if (client->getPrimaryMix() != primaryMix || client->hasLostPrimaryMix()) {
Eric Laurent56ed8842022-11-15 16:04:41 +01006395 if (desc->isStrategyActive(psId) && maxLatency < desc->latency()) {
Eric Laurentc209fe42020-06-05 18:11:23 -07006396 maxLatency = desc->latency();
6397 }
Eric Laurent56ed8842022-11-15 16:04:41 +01006398 invalidatedOutputs.push_back(desc);
Eric Laurentc209fe42020-06-05 18:11:23 -07006399 }
Jean-Michel Trivife472e22014-12-16 14:23:13 -08006400 }
6401 }
6402
Eric Laurent56ed8842022-11-15 16:04:41 +01006403 if (srcOutputs != dstOutputs || !invalidatedOutputs.empty()) {
Eric Laurentac3a6902018-05-11 16:39:10 -07006404 // get maximum latency of all source outputs to determine the minimum mute time guaranteeing
6405 // audio from invalidated tracks will be rendered when unmuting
Eric Laurentac3a6902018-05-11 16:39:10 -07006406 for (audio_io_handle_t srcOut : srcOutputs) {
6407 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
Eric Laurentaa02db82019-09-05 17:31:49 -07006408 if (desc == nullptr) continue;
6409
6410 if (desc->isStrategyActive(psId) && maxLatency < desc->latency()) {
Eric Laurentac3a6902018-05-11 16:39:10 -07006411 maxLatency = desc->latency();
6412 }
Eric Laurentaa02db82019-09-05 17:31:49 -07006413
Eric Laurent56ed8842022-11-15 16:04:41 +01006414 bool invalidate = false;
Eric Laurentaa02db82019-09-05 17:31:49 -07006415 for (auto client : desc->clientsList(false /*activeOnly*/)) {
Eric Laurent78aade82019-09-13 18:55:08 -07006416 if (desc->isDuplicated() || !desc->mProfile->isDirectOutput()) {
Eric Laurentaa02db82019-09-05 17:31:49 -07006417 // a client on a non direct outputs has necessarily a linear PCM format
6418 // so we can call selectOutput() safely
6419 const audio_io_handle_t newOutput = selectOutput(dstOutputs,
6420 client->flags(),
6421 client->config().format,
6422 client->config().channel_mask,
jiabinebb6af42020-06-09 17:31:17 -07006423 client->config().sample_rate,
6424 client->session());
Eric Laurentaa02db82019-09-05 17:31:49 -07006425 if (newOutput != srcOut) {
6426 invalidate = true;
6427 break;
6428 }
6429 } else {
6430 sp<IOProfile> profile = getProfileForOutput(newDevices,
6431 client->config().sample_rate,
6432 client->config().format,
6433 client->config().channel_mask,
6434 client->flags(),
6435 true /* directOnly */);
6436 if (profile != desc->mProfile) {
6437 invalidate = true;
6438 break;
6439 }
6440 }
6441 }
Eric Laurent56ed8842022-11-15 16:04:41 +01006442 // mute strategy while moving tracks from one output to another
6443 if (invalidate) {
6444 invalidatedOutputs.push_back(desc);
6445 if (desc->isStrategyActive(psId)) {
6446 setStrategyMute(psId, true, desc);
6447 setStrategyMute(psId, false, desc, maxLatency * LATENCY_MUTE_FACTOR,
6448 newDevices.types());
6449 }
Eric Laurente552edb2014-03-10 17:42:56 -07006450 }
François Gaffiec005e562018-11-06 15:04:49 +01006451 sp<SourceClientDescriptor> source = getSourceForAttributesOnOutput(srcOut, attr);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02006452 if (source != nullptr && !isCallRxAudioSource(source) && !source->isInternal()) {
Eric Laurentd60560a2015-04-10 11:31:20 -07006453 connectAudioSource(source);
6454 }
Eric Laurente552edb2014-03-10 17:42:56 -07006455 }
6456
Eric Laurent56ed8842022-11-15 16:04:41 +01006457 ALOGV_IF(!(srcOutputs.isEmpty() || dstOutputs.isEmpty()),
6458 "%s: strategy %d, moving from output %s to output %s", __func__, psId,
6459 std::to_string(srcOutputs[0]).c_str(),
6460 std::to_string(dstOutputs[0]).c_str());
6461
François Gaffiec005e562018-11-06 15:04:49 +01006462 // Move effects associated to this stream from previous output to new output
6463 if (followsSameRouting(attr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07006464 selectOutputForMusicEffects();
Eric Laurente552edb2014-03-10 17:42:56 -07006465 }
François Gaffiec005e562018-11-06 15:04:49 +01006466 // Move tracks associated to this stream (and linked) from previous output to new output
Eric Laurent56ed8842022-11-15 16:04:41 +01006467 if (!invalidatedOutputs.empty()) {
Eric Laurentaa02db82019-09-05 17:31:49 -07006468 for (auto stream : mEngine->getStreamTypesForProductStrategy(psId)) {
6469 mpClientInterface->invalidateStream(stream);
6470 }
Eric Laurent56ed8842022-11-15 16:04:41 +01006471 for (sp<SwAudioOutputDescriptor> desc : invalidatedOutputs) {
jiabin49256852022-03-09 11:21:35 -08006472 desc->setTracksInvalidatedStatusByStrategy(psId);
6473 }
Eric Laurente552edb2014-03-10 17:42:56 -07006474 }
6475 }
6476}
6477
Eric Laurente0720872014-03-11 09:30:41 -07006478void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07006479{
François Gaffiec005e562018-11-06 15:04:49 +01006480 for (const auto &strategy : mEngine->getOrderedProductStrategies()) {
6481 auto attributes = mEngine->getAllAttributesForProductStrategy(strategy).front();
6482 checkOutputForAttributes(attributes);
Francois Gaffieff1eb522020-05-06 18:37:04 +02006483 checkAudioSourceForAttributes(attributes);
François Gaffiec005e562018-11-06 15:04:49 +01006484 }
Eric Laurente552edb2014-03-10 17:42:56 -07006485}
6486
Kevin Rocard153f92d2018-12-18 18:33:28 -08006487void AudioPolicyManager::checkSecondaryOutputs() {
6488 std::set<audio_stream_type_t> streamsToInvalidate;
jiabin10a03f12021-05-07 23:46:28 +00006489 TrackSecondaryOutputsMap trackSecondaryOutputs;
Kevin Rocard153f92d2018-12-18 18:33:28 -08006490 for (size_t i = 0; i < mOutputs.size(); i++) {
6491 const sp<SwAudioOutputDescriptor>& outputDescriptor = mOutputs[i];
6492 for (const sp<TrackClientDescriptor>& client : outputDescriptor->getClientIterable()) {
Eric Laurentc529cf62020-04-17 18:19:10 -07006493 sp<AudioPolicyMix> primaryMix;
6494 std::vector<sp<AudioPolicyMix>> secondaryMixes;
Dean Wheatleyd082f472022-02-04 11:10:48 +11006495 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->config(),
6496 client->uid(), client->flags(), primaryMix, &secondaryMixes);
Eric Laurentc529cf62020-04-17 18:19:10 -07006497 std::vector<sp<SwAudioOutputDescriptor>> secondaryDescs;
6498 for (auto &secondaryMix : secondaryMixes) {
6499 sp<SwAudioOutputDescriptor> outputDesc = secondaryMix->getOutput();
6500 if (outputDesc != nullptr &&
6501 outputDesc->mIoHandle != AUDIO_IO_HANDLE_NONE) {
6502 secondaryDescs.push_back(outputDesc);
6503 }
6504 }
6505
jiabin10a03f12021-05-07 23:46:28 +00006506 if (status != OK) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08006507 streamsToInvalidate.insert(client->stream());
jiabin10a03f12021-05-07 23:46:28 +00006508 } else if (!std::equal(
6509 client->getSecondaryOutputs().begin(),
6510 client->getSecondaryOutputs().end(),
6511 secondaryDescs.begin(), secondaryDescs.end())) {
jiabina5281062021-11-23 00:10:23 +00006512 if (!audio_is_linear_pcm(client->config().format)) {
6513 // If the format is not PCM, the tracks should be invalidated to get correct
6514 // behavior when the secondary output is changed.
6515 streamsToInvalidate.insert(client->stream());
6516 } else {
6517 std::vector<wp<SwAudioOutputDescriptor>> weakSecondaryDescs;
6518 std::vector<audio_io_handle_t> secondaryOutputIds;
6519 for (const auto &secondaryDesc: secondaryDescs) {
6520 secondaryOutputIds.push_back(secondaryDesc->mIoHandle);
6521 weakSecondaryDescs.push_back(secondaryDesc);
6522 }
6523 trackSecondaryOutputs.emplace(client->portId(), secondaryOutputIds);
6524 client->setSecondaryOutputs(std::move(weakSecondaryDescs));
jiabin10a03f12021-05-07 23:46:28 +00006525 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08006526 }
6527 }
6528 }
jiabin10a03f12021-05-07 23:46:28 +00006529 if (!trackSecondaryOutputs.empty()) {
6530 mpClientInterface->updateSecondaryOutputs(trackSecondaryOutputs);
6531 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08006532 for (audio_stream_type_t stream : streamsToInvalidate) {
jiabin10a03f12021-05-07 23:46:28 +00006533 ALOGD("%s Invalidate stream %d due to fail getting output for attr", __func__, stream);
Kevin Rocard153f92d2018-12-18 18:33:28 -08006534 mpClientInterface->invalidateStream(stream);
6535 }
6536}
6537
Eric Laurent2517af32020-11-25 15:31:27 +01006538bool AudioPolicyManager::isScoRequestedForComm() const {
6539 AudioDeviceTypeAddrVector devices;
6540 mEngine->getDevicesForRoleAndStrategy(mCommunnicationStrategy, DEVICE_ROLE_PREFERRED, devices);
6541 for (const auto &device : devices) {
6542 if (audio_is_bluetooth_out_sco_device(device.mType)) {
6543 return true;
6544 }
6545 }
6546 return false;
6547}
6548
Eric Laurent1a8b45f2022-04-13 16:01:47 +02006549bool AudioPolicyManager::isHearingAidUsedForComm() const {
6550 DeviceVector devices = mEngine->getOutputDevicesForStream(AUDIO_STREAM_VOICE_CALL,
6551 true /*fromCache*/);
6552 for (const auto &device : devices) {
6553 if (device->type() == AUDIO_DEVICE_OUT_HEARING_AID) {
6554 return true;
6555 }
6556 }
6557 return false;
6558}
6559
6560
Eric Laurente0720872014-03-11 09:30:41 -07006561void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07006562{
François Gaffie53615e22015-03-19 09:24:12 +01006563 audio_io_handle_t a2dpOutput = mOutputs.getA2dpOutput();
Aniket Kumar Lataa8ee9962018-01-31 20:24:23 -08006564 if (a2dpOutput == 0 || mOutputs.isA2dpOffloadedOnPrimary()) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07006565 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07006566 return;
6567 }
6568
Eric Laurent3a4311c2014-03-17 12:00:47 -07006569 bool isScoConnected =
jiabin9a3361e2019-10-01 09:38:30 -07006570 (mAvailableInputDevices.types().count(AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) != 0 ||
6571 !Intersection(mAvailableOutputDevices.types(), getAudioDeviceOutAllScoSet()).empty());
Eric Laurent2517af32020-11-25 15:31:27 +01006572 bool isScoRequested = isScoRequestedForComm();
Eric Laurentf732e072016-08-03 19:30:28 -07006573
6574 // if suspended, restore A2DP output if:
6575 // ((SCO device is NOT connected) ||
Eric Laurent2517af32020-11-25 15:31:27 +01006576 // ((SCO is not requested) &&
Eric Laurentf732e072016-08-03 19:30:28 -07006577 // (phone state is NOT in call) && (phone state is NOT ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07006578 //
Eric Laurentf732e072016-08-03 19:30:28 -07006579 // if not suspended, suspend A2DP output if:
6580 // (SCO device is connected) &&
Eric Laurent2517af32020-11-25 15:31:27 +01006581 // ((SCO is requested) ||
Eric Laurentf732e072016-08-03 19:30:28 -07006582 // ((phone state is in call) || (phone state is ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07006583 //
6584 if (mA2dpSuspended) {
Eric Laurentf732e072016-08-03 19:30:28 -07006585 if (!isScoConnected ||
Eric Laurent2517af32020-11-25 15:31:27 +01006586 (!isScoRequested &&
Eric Laurentf732e072016-08-03 19:30:28 -07006587 (mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) &&
François Gaffie2110e042015-03-24 08:41:51 +01006588 (mEngine->getPhoneState() != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07006589
6590 mpClientInterface->restoreOutput(a2dpOutput);
6591 mA2dpSuspended = false;
6592 }
6593 } else {
Eric Laurentf732e072016-08-03 19:30:28 -07006594 if (isScoConnected &&
Eric Laurent2517af32020-11-25 15:31:27 +01006595 (isScoRequested ||
Eric Laurentf732e072016-08-03 19:30:28 -07006596 (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) ||
François Gaffie2110e042015-03-24 08:41:51 +01006597 (mEngine->getPhoneState() == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07006598
6599 mpClientInterface->suspendOutput(a2dpOutput);
6600 mA2dpSuspended = true;
6601 }
6602 }
6603}
6604
François Gaffie11d30102018-11-02 16:09:09 +01006605DeviceVector AudioPolicyManager::getNewOutputDevices(const sp<SwAudioOutputDescriptor>& outputDesc,
6606 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07006607{
François Gaffie11d30102018-11-02 16:09:09 +01006608 DeviceVector devices;
6609
Jean-Michel Triviff155c62016-02-26 12:07:16 -08006610 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07006611 if (index >= 0) {
6612 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006613 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01006614 ALOGV("%s device %s forced by patch %d", __func__,
6615 outputDesc->devices().toString().c_str(), outputDesc->getPatchHandle());
6616 return outputDesc->devices();
Eric Laurent6a94d692014-05-20 11:18:06 -07006617 }
6618 }
6619
Dean Wheatley514b4312020-06-17 21:45:00 +10006620 // Do not retrieve engine device for outputs through MSD
6621 // TODO: support explicit routing requests by resetting MSD patch to engine device.
6622 if (outputDesc->devices() == getMsdAudioOutDevices()) {
6623 return outputDesc->devices();
6624 }
6625
Eric Laurent97ac8712018-07-27 18:59:02 -07006626 // Honor explicit routing requests only if no client using default routing is active on this
6627 // input: a specific app can not force routing for other apps by setting a preferred device.
6628 bool active; // unused
François Gaffie11d30102018-11-02 16:09:09 +01006629 sp<DeviceDescriptor> device =
François Gaffiec005e562018-11-06 15:04:49 +01006630 findPreferredDevice(outputDesc, PRODUCT_STRATEGY_NONE, active, mAvailableOutputDevices);
François Gaffie11d30102018-11-02 16:09:09 +01006631 if (device != nullptr) {
6632 return DeviceVector(device);
Eric Laurentf3a5a602018-05-22 18:42:55 -07006633 }
6634
François Gaffiea807ef92018-11-05 10:44:33 +01006635 // Legacy Engine cannot take care of bus devices and mix, so we need to handle the conflict
6636 // of setForceUse / Default Bus device here
6637 device = mPolicyMixes.getDeviceAndMixForOutput(outputDesc, mAvailableOutputDevices);
6638 if (device != nullptr) {
6639 return DeviceVector(device);
6640 }
6641
François Gaffiec005e562018-11-06 15:04:49 +01006642 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
6643 StreamTypeVector streams = mEngine->getStreamTypesForProductStrategy(productStrategy);
6644 auto attr = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05306645 auto hasStreamActive = [&](auto stream) {
6646 return hasStream(streams, stream) && isStreamActive(stream, 0);
6647 };
Eric Laurent484e9272018-06-07 17:29:23 -07006648
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05306649 auto doGetOutputDevicesForVoice = [&]() {
6650 return hasVoiceStream(streams) && (outputDesc == mPrimaryOutput ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01006651 outputDesc->isActive(toVolumeSource(AUDIO_STREAM_VOICE_CALL, false))) &&
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05306652 (isInCall() ||
Henrik Backlund07c654a2021-10-14 15:57:10 +02006653 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc)) &&
6654 !isStreamActive(AUDIO_STREAM_ENFORCED_AUDIBLE, 0);
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05306655 };
6656
6657 // With low-latency playing on speaker, music on WFD, when the first low-latency
6658 // output is stopped, getNewOutputDevices checks for a product strategy
6659 // from the list, as STRATEGY_SONIFICATION comes prior to STRATEGY_MEDIA.
Carter Hsucc58a6b2021-07-20 08:44:50 +00006660 // If an ALARM or ENFORCED_AUDIBLE stream is supported by the product strategy,
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05306661 // devices are returned for STRATEGY_SONIFICATION without checking whether the
6662 // stream is associated to the output descriptor.
6663 if (doGetOutputDevicesForVoice() || outputDesc->isStrategyActive(productStrategy) ||
6664 ((hasStreamActive(AUDIO_STREAM_ALARM) ||
6665 hasStreamActive(AUDIO_STREAM_ENFORCED_AUDIBLE)) &&
6666 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc))) {
François Gaffiec005e562018-11-06 15:04:49 +01006667 // Retrieval of devices for voice DL is done on primary output profile, cannot
6668 // check the route (would force modifying configuration file for this profile)
6669 devices = mEngine->getOutputDevicesForAttributes(attr, nullptr, fromCache);
6670 break;
6671 }
Eric Laurente552edb2014-03-10 17:42:56 -07006672 }
François Gaffiec005e562018-11-06 15:04:49 +01006673 ALOGV("%s selected devices %s", __func__, devices.toString().c_str());
François Gaffie11d30102018-11-02 16:09:09 +01006674 return devices;
Eric Laurent1c333e22014-05-20 10:48:17 -07006675}
6676
François Gaffie11d30102018-11-02 16:09:09 +01006677sp<DeviceDescriptor> AudioPolicyManager::getNewInputDevice(
6678 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurent1c333e22014-05-20 10:48:17 -07006679{
François Gaffie11d30102018-11-02 16:09:09 +01006680 sp<DeviceDescriptor> device;
Eric Laurent6a94d692014-05-20 11:18:06 -07006681
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08006682 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07006683 if (index >= 0) {
6684 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006685 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01006686 ALOGV("getNewInputDevice() device %s forced by patch %d",
6687 inputDesc->getDevice()->toString().c_str(), inputDesc->getPatchHandle());
6688 return inputDesc->getDevice();
Eric Laurent6a94d692014-05-20 11:18:06 -07006689 }
6690 }
6691
Eric Laurent97ac8712018-07-27 18:59:02 -07006692 // Honor explicit routing requests only if no client using default routing is active on this
6693 // input: a specific app can not force routing for other apps by setting a preferred device.
6694 bool active;
François Gaffie11d30102018-11-02 16:09:09 +01006695 device = findPreferredDevice(inputDesc, AUDIO_SOURCE_DEFAULT, active, mAvailableInputDevices);
6696 if (device != nullptr) {
6697 return device;
Eric Laurent97ac8712018-07-27 18:59:02 -07006698 }
6699
Eric Laurentdc95a252018-04-12 12:46:56 -07006700 // If we are not in call and no client is active on this input, this methods returns
Andy Hungf024a9e2019-01-30 16:01:02 -08006701 // a null sp<>, causing the patch on the input stream to be released.
yuanjiahsu0735bf32021-03-18 08:12:54 +08006702 audio_attributes_t attributes;
6703 uid_t uid;
6704 sp<RecordClientDescriptor> topClient = inputDesc->getHighestPriorityClient();
6705 if (topClient != nullptr) {
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01006706 attributes = topClient->attributes();
6707 uid = topClient->uid();
yuanjiahsu0735bf32021-03-18 08:12:54 +08006708 } else {
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01006709 attributes = { .source = AUDIO_SOURCE_DEFAULT };
6710 uid = 0;
yuanjiahsu0735bf32021-03-18 08:12:54 +08006711 }
6712
Francois Gaffie716e1432019-01-14 16:58:59 +01006713 if (attributes.source == AUDIO_SOURCE_DEFAULT && isInCall()) {
6714 attributes.source = AUDIO_SOURCE_VOICE_COMMUNICATION;
Eric Laurentdc95a252018-04-12 12:46:56 -07006715 }
Francois Gaffie716e1432019-01-14 16:58:59 +01006716 if (attributes.source != AUDIO_SOURCE_DEFAULT) {
yuanjiahsu0735bf32021-03-18 08:12:54 +08006717 device = mEngine->getInputDeviceForAttributes(attributes, uid);
Eric Laurentfb66dd92016-01-28 18:32:03 -08006718 }
Eric Laurent1c333e22014-05-20 10:48:17 -07006719
Eric Laurente552edb2014-03-10 17:42:56 -07006720 return device;
6721}
6722
Eric Laurent794fde22016-03-11 09:50:45 -08006723bool AudioPolicyManager::streamsMatchForvolume(audio_stream_type_t stream1,
6724 audio_stream_type_t stream2) {
Jean-Michel Trivi99bb2f92016-11-23 15:52:07 -08006725 return (stream1 == stream2);
Eric Laurent28d09f02016-03-08 10:43:05 -08006726}
6727
Dorin Drimusf2196d82022-01-03 12:11:18 +01006728// TODO - consider MSD routes b/214971780
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08006729status_t AudioPolicyManager::getDevicesForAttributes(
Andy Hung6d23c0f2022-02-16 09:37:15 -08006730 const audio_attributes_t &attr, AudioDeviceTypeAddrVector *devices, bool forVolume) {
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08006731 if (devices == nullptr) {
6732 return BAD_VALUE;
6733 }
Andy Hung6d23c0f2022-02-16 09:37:15 -08006734
6735 // Devices are determined in the following precedence:
6736 //
6737 // 1) Devices associated with a dynamic policy matching the attributes. This is often
6738 // a remote submix from MIX_ROUTE_FLAG_LOOP_BACK.
6739 //
6740 // If no such dynamic policy then
6741 // 2) Devices containing an active client using setPreferredDevice
6742 // with same strategy as the attributes.
6743 // (from the default Engine::getOutputDevicesForAttributes() implementation).
6744 //
6745 // If no corresponding active client with setPreferredDevice then
6746 // 3) Devices associated with the strategy determined by the attributes
6747 // (from the default Engine::getOutputDevicesForAttributes() implementation).
6748 //
6749 // See related getOutputForAttrInt().
6750
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08006751 // check dynamic policies but only for primary descriptors (secondary not used for audible
6752 // audio routing, only used for duplication for playback capture)
Eric Laurentc529cf62020-04-17 18:19:10 -07006753 sp<AudioPolicyMix> policyMix;
Dean Wheatleyd082f472022-02-04 11:10:48 +11006754 status_t status = mPolicyMixes.getOutputForAttr(attr, AUDIO_CONFIG_BASE_INITIALIZER,
6755 0 /*uid unknown here*/, AUDIO_OUTPUT_FLAG_NONE, policyMix, nullptr);
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08006756 if (status != OK) {
6757 return status;
6758 }
Andy Hung6d23c0f2022-02-16 09:37:15 -08006759
6760 DeviceVector curDevices;
6761 if (policyMix != nullptr && policyMix->getOutput() != nullptr &&
6762 // For volume control, skip LOOPBACK mixes which use AUDIO_DEVICE_OUT_REMOTE_SUBMIX
6763 // as they are unaffected by device/stream volume
6764 // (per SwAudioOutputDescriptor::isFixedVolume()).
6765 (!forVolume || policyMix->mDeviceType != AUDIO_DEVICE_OUT_REMOTE_SUBMIX)
6766 ) {
6767 sp<DeviceDescriptor> deviceDesc = mAvailableOutputDevices.getDevice(
6768 policyMix->mDeviceType, policyMix->mDeviceAddress, AUDIO_FORMAT_DEFAULT);
6769 curDevices.add(deviceDesc);
6770 } else {
6771 // The default Engine::getOutputDevicesForAttributes() uses findPreferredDevice()
6772 // which selects setPreferredDevice if active. This means forVolume call
6773 // will take an active setPreferredDevice, if such exists.
6774
6775 curDevices = mEngine->getOutputDevicesForAttributes(
6776 attr, nullptr /* preferredDevice */, false /* fromCache */);
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08006777 }
Andy Hung6d23c0f2022-02-16 09:37:15 -08006778
6779 if (forVolume) {
6780 // We alias the device AUDIO_DEVICE_OUT_SPEAKER_SAFE to AUDIO_DEVICE_OUT_SPEAKER
6781 // for single volume control in AudioService (such relationship should exist if
6782 // SPEAKER_SAFE is present).
6783 //
6784 // (This is unrelated to a different device grouping as Volume::getDeviceCategory)
6785 DeviceVector speakerSafeDevices =
6786 curDevices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER_SAFE);
6787 if (!speakerSafeDevices.isEmpty()) {
6788 curDevices.merge(
6789 mAvailableOutputDevices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER));
6790 curDevices.remove(speakerSafeDevices);
6791 }
6792 }
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08006793 for (const auto& device : curDevices) {
6794 devices->push_back(device->getDeviceTypeAddr());
6795 }
6796 return NO_ERROR;
6797}
6798
Eric Laurente0720872014-03-11 09:30:41 -07006799void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07006800 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07006801 case AUDIO_STREAM_MUSIC:
François Gaffiec005e562018-11-06 15:04:49 +01006802 checkOutputForAttributes(attributes_initializer(AUDIO_USAGE_NOTIFICATION));
Eric Laurente552edb2014-03-10 17:42:56 -07006803 updateDevicesAndOutputs();
6804 break;
6805 default:
6806 break;
6807 }
6808}
6809
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006810uint32_t AudioPolicyManager::handleEventForBeacon(int event) {
Eric Laurent9459fb02015-08-12 18:36:32 -07006811
6812 // skip beacon mute management if a dedicated TTS output is available
6813 if (mTtsOutputAvailable) {
6814 return 0;
6815 }
6816
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006817 switch(event) {
6818 case STARTING_OUTPUT:
6819 mBeaconMuteRefCount++;
6820 break;
6821 case STOPPING_OUTPUT:
6822 if (mBeaconMuteRefCount > 0) {
6823 mBeaconMuteRefCount--;
6824 }
6825 break;
6826 case STARTING_BEACON:
6827 mBeaconPlayingRefCount++;
6828 break;
6829 case STOPPING_BEACON:
6830 if (mBeaconPlayingRefCount > 0) {
6831 mBeaconPlayingRefCount--;
6832 }
6833 break;
6834 }
6835
6836 if (mBeaconMuteRefCount > 0) {
6837 // any playback causes beacon to be muted
6838 return setBeaconMute(true);
6839 } else {
6840 // no other playback: unmute when beacon starts playing, mute when it stops
6841 return setBeaconMute(mBeaconPlayingRefCount == 0);
6842 }
6843}
6844
6845uint32_t AudioPolicyManager::setBeaconMute(bool mute) {
6846 ALOGV("setBeaconMute(%d) mBeaconMuteRefCount=%d mBeaconPlayingRefCount=%d",
6847 mute, mBeaconMuteRefCount, mBeaconPlayingRefCount);
6848 // keep track of muted state to avoid repeating mute/unmute operations
6849 if (mBeaconMuted != mute) {
6850 // mute/unmute AUDIO_STREAM_TTS on all outputs
6851 ALOGV("\t muting %d", mute);
6852 uint32_t maxLatency = 0;
Francois Gaffie4404ddb2021-02-04 17:03:38 +01006853 auto ttsVolumeSource = toVolumeSource(AUDIO_STREAM_TTS, false);
6854 if (ttsVolumeSource == VOLUME_SOURCE_NONE) {
6855 ALOGV("\t no tts volume source available");
6856 return 0;
6857 }
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006858 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07006859 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
jiabin9a3361e2019-10-01 09:38:30 -07006860 setVolumeSourceMute(ttsVolumeSource, mute/*on*/, desc, 0 /*delay*/, DeviceTypeSet());
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006861 const uint32_t latency = desc->latency() * 2;
Eric Laurentcdb2b352020-07-23 10:57:02 -07006862 if (desc->isActive(latency * 2) && latency > maxLatency) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006863 maxLatency = latency;
6864 }
6865 }
6866 mBeaconMuted = mute;
6867 return maxLatency;
6868 }
6869 return 0;
6870}
6871
Eric Laurente0720872014-03-11 09:30:41 -07006872void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07006873{
François Gaffiec005e562018-11-06 15:04:49 +01006874 mEngine->updateDeviceSelectionCache();
Eric Laurente552edb2014-03-10 17:42:56 -07006875 mPreviousOutputs = mOutputs;
6876}
6877
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07006878uint32_t AudioPolicyManager::checkDeviceMuteStrategies(const sp<AudioOutputDescriptor>& outputDesc,
François Gaffiec005e562018-11-06 15:04:49 +01006879 const DeviceVector &prevDevices,
Eric Laurente552edb2014-03-10 17:42:56 -07006880 uint32_t delayMs)
6881{
6882 // mute/unmute strategies using an incompatible device combination
6883 // if muting, wait for the audio in pcm buffer to be drained before proceeding
6884 // if unmuting, unmute only after the specified delay
6885 if (outputDesc->isDuplicated()) {
6886 return 0;
6887 }
6888
6889 uint32_t muteWaitMs = 0;
François Gaffiec005e562018-11-06 15:04:49 +01006890 DeviceVector devices = outputDesc->devices();
6891 bool shouldMute = outputDesc->isActive() && (devices.size() >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07006892
François Gaffiec005e562018-11-06 15:04:49 +01006893 auto productStrategies = mEngine->getOrderedProductStrategies();
6894 for (const auto &productStrategy : productStrategies) {
6895 auto attributes = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
6896 DeviceVector curDevices =
6897 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false/*fromCache*/);
6898 curDevices = curDevices.filter(outputDesc->supportedDevices());
6899 bool mute = shouldMute && curDevices.containsAtLeastOne(devices) && curDevices != devices;
Eric Laurente552edb2014-03-10 17:42:56 -07006900 bool doMute = false;
6901
François Gaffiec005e562018-11-06 15:04:49 +01006902 if (mute && !outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07006903 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01006904 outputDesc->setStrategyMutedByDevice(productStrategy, true);
6905 } else if (!mute && outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07006906 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01006907 outputDesc->setStrategyMutedByDevice(productStrategy, false);
Eric Laurente552edb2014-03-10 17:42:56 -07006908 }
Eric Laurent99401132014-05-07 19:48:15 -07006909 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07006910 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07006911 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07006912 // skip output if it does not share any device with current output
François Gaffie11d30102018-11-02 16:09:09 +01006913 if (!desc->supportedDevices().containsAtLeastOne(outputDesc->supportedDevices())) {
Eric Laurente552edb2014-03-10 17:42:56 -07006914 continue;
6915 }
François Gaffiec005e562018-11-06 15:04:49 +01006916 ALOGVV("%s() %s (curDevice %s)", __func__,
6917 mute ? "muting" : "unmuting", curDevices.toString().c_str());
6918 setStrategyMute(productStrategy, mute, desc, mute ? 0 : delayMs);
6919 if (desc->isStrategyActive(productStrategy)) {
Eric Laurent99401132014-05-07 19:48:15 -07006920 if (mute) {
6921 // FIXME: should not need to double latency if volume could be applied
6922 // immediately by the audioflinger mixer. We must account for the delay
6923 // between now and the next time the audioflinger thread for this output
6924 // will process a buffer (which corresponds to one buffer size,
6925 // usually 1/2 or 1/4 of the latency).
6926 if (muteWaitMs < desc->latency() * 2) {
6927 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07006928 }
6929 }
6930 }
6931 }
6932 }
6933 }
6934
Eric Laurent99401132014-05-07 19:48:15 -07006935 // temporary mute output if device selection changes to avoid volume bursts due to
6936 // different per device volumes
François Gaffiec005e562018-11-06 15:04:49 +01006937 if (outputDesc->isActive() && (devices != prevDevices)) {
Eric Laurentdc462862016-07-19 12:29:53 -07006938 uint32_t tempMuteWaitMs = outputDesc->latency() * 2;
Jasmine Chaf6074fe2021-08-17 13:44:31 +08006939
Eric Laurentdc462862016-07-19 12:29:53 -07006940 if (muteWaitMs < tempMuteWaitMs) {
6941 muteWaitMs = tempMuteWaitMs;
Eric Laurent99401132014-05-07 19:48:15 -07006942 }
Jasmine Chaf6074fe2021-08-17 13:44:31 +08006943
6944 // If recommended duration is defined, replace temporary mute duration to avoid
6945 // truncated notifications at beginning, which depends on duration of changing path in HAL.
6946 // Otherwise, temporary mute duration is conservatively set to 4 times the reported latency.
6947 uint32_t tempRecommendedMuteDuration = outputDesc->getRecommendedMuteDurationMs();
6948 uint32_t tempMuteDurationMs = tempRecommendedMuteDuration > 0 ?
6949 tempRecommendedMuteDuration : outputDesc->latency() * 4;
6950
François Gaffieaaac0fd2018-11-22 17:56:39 +01006951 for (const auto &activeVs : outputDesc->getActiveVolumeSources()) {
6952 // make sure that we do not start the temporary mute period too early in case of
6953 // delayed device change
6954 setVolumeSourceMute(activeVs, true, outputDesc, delayMs);
6955 setVolumeSourceMute(activeVs, false, outputDesc, delayMs + tempMuteDurationMs,
François Gaffiec005e562018-11-06 15:04:49 +01006956 devices.types());
Eric Laurent99401132014-05-07 19:48:15 -07006957 }
6958 }
6959
Eric Laurente552edb2014-03-10 17:42:56 -07006960 // wait for the PCM output buffers to empty before proceeding with the rest of the command
6961 if (muteWaitMs > delayMs) {
6962 muteWaitMs -= delayMs;
6963 usleep(muteWaitMs * 1000);
6964 return muteWaitMs;
6965 }
6966 return 0;
6967}
6968
François Gaffie11d30102018-11-02 16:09:09 +01006969uint32_t AudioPolicyManager::setOutputDevices(const sp<SwAudioOutputDescriptor>& outputDesc,
6970 const DeviceVector &devices,
6971 bool force,
6972 int delayMs,
6973 audio_patch_handle_t *patchHandle,
Francois Gaffie3523ab32021-06-22 13:24:34 +02006974 bool requiresMuteCheck, bool requiresVolumeCheck)
Eric Laurente552edb2014-03-10 17:42:56 -07006975{
François Gaffie11d30102018-11-02 16:09:09 +01006976 ALOGV("%s device %s delayMs %d", __func__, devices.toString().c_str(), delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07006977 uint32_t muteWaitMs;
6978
6979 if (outputDesc->isDuplicated()) {
François Gaffie11d30102018-11-02 16:09:09 +01006980 muteWaitMs = setOutputDevices(outputDesc->subOutput1(), devices, force, delayMs,
6981 nullptr /* patchHandle */, requiresMuteCheck);
6982 muteWaitMs += setOutputDevices(outputDesc->subOutput2(), devices, force, delayMs,
6983 nullptr /* patchHandle */, requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07006984 return muteWaitMs;
6985 }
Eric Laurente552edb2014-03-10 17:42:56 -07006986
6987 // filter devices according to output selected
Francois Gaffie716e1432019-01-14 16:58:59 +01006988 DeviceVector filteredDevices = outputDesc->filterSupportedDevices(devices);
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01006989 DeviceVector prevDevices = outputDesc->devices();
Francois Gaffie3523ab32021-06-22 13:24:34 +02006990 DeviceVector availPrevDevices = mAvailableOutputDevices.filter(prevDevices);
Eric Laurente552edb2014-03-10 17:42:56 -07006991
François Gaffie11d30102018-11-02 16:09:09 +01006992 ALOGV("setOutputDevices() prevDevice %s", prevDevices.toString().c_str());
6993
6994 if (!filteredDevices.isEmpty()) {
6995 outputDesc->setDevices(filteredDevices);
Eric Laurente552edb2014-03-10 17:42:56 -07006996 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00006997
6998 // if the outputs are not materially active, there is no need to mute.
6999 if (requiresMuteCheck) {
François Gaffiec005e562018-11-06 15:04:49 +01007000 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevices, delayMs);
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00007001 } else {
7002 ALOGV("%s: suppressing checkDeviceMuteStrategies", __func__);
7003 muteWaitMs = 0;
7004 }
Eric Laurente552edb2014-03-10 17:42:56 -07007005
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02007006 bool outputRouted = outputDesc->isRouted();
7007
Eric Laurent79ea9582020-06-11 18:49:24 -07007008 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
7009 // output profile or if new device is not supported AND previous device(s) is(are) still
7010 // available (otherwise reset device must be done on the output)
Francois Gaffie3523ab32021-06-22 13:24:34 +02007011 if (!devices.isEmpty() && filteredDevices.isEmpty() && !availPrevDevices.empty()) {
Eric Laurent79ea9582020-06-11 18:49:24 -07007012 ALOGV("%s: unsupported device %s for output", __func__, devices.toString().c_str());
7013 // restore previous device after evaluating strategy mute state
7014 outputDesc->setDevices(prevDevices);
7015 return muteWaitMs;
7016 }
7017
Eric Laurente552edb2014-03-10 17:42:56 -07007018 // Do not change the routing if:
Eric Laurentb80a2a82014-10-27 16:07:59 -07007019 // the requested device is AUDIO_DEVICE_NONE
7020 // OR the requested device is the same as current device
7021 // AND force is not specified
7022 // AND the output is connected by a valid audio patch.
François Gaffie11d30102018-11-02 16:09:09 +01007023 // Doing this check here allows the caller to call setOutputDevices() without conditions
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02007024 if ((filteredDevices.isEmpty() || filteredDevices == prevDevices) && !force && outputRouted) {
François Gaffie11d30102018-11-02 16:09:09 +01007025 ALOGV("%s setting same device %s or null device, force=%d, patch handle=%d", __func__,
7026 filteredDevices.toString().c_str(), force, outputDesc->getPatchHandle());
Francois Gaffie3523ab32021-06-22 13:24:34 +02007027 if (requiresVolumeCheck && !filteredDevices.isEmpty()) {
7028 ALOGV("%s setting same device on routed output, force apply volumes", __func__);
7029 applyStreamVolumes(outputDesc, filteredDevices.types(), delayMs, true /*force*/);
7030 }
Eric Laurente552edb2014-03-10 17:42:56 -07007031 return muteWaitMs;
7032 }
7033
François Gaffie11d30102018-11-02 16:09:09 +01007034 ALOGV("%s changing device to %s", __func__, filteredDevices.toString().c_str());
Eric Laurent1c333e22014-05-20 10:48:17 -07007035
Eric Laurente552edb2014-03-10 17:42:56 -07007036 // do the routing
Francois Gaffie3523ab32021-06-22 13:24:34 +02007037 if (filteredDevices.isEmpty() || mAvailableOutputDevices.filter(filteredDevices).empty()) {
Eric Laurentc75307b2015-03-17 15:29:32 -07007038 resetOutputDevice(outputDesc, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07007039 } else {
François Gaffie11d30102018-11-02 16:09:09 +01007040 PatchBuilder patchBuilder;
7041 patchBuilder.addSource(outputDesc);
7042 ALOG_ASSERT(filteredDevices.size() <= AUDIO_PATCH_PORTS_MAX, "Too many sink ports");
7043 for (const auto &filteredDevice : filteredDevices) {
7044 patchBuilder.addSink(filteredDevice);
Eric Laurentc40d9692016-04-13 19:14:13 -07007045 }
7046
Jasmine Cha7f82d1a2020-03-16 13:21:47 +08007047 // Add half reported latency to delayMs when muteWaitMs is null in order
7048 // to avoid disordered sequence of muting volume and changing devices.
7049 installPatch(__func__, patchHandle, outputDesc.get(), patchBuilder.patch(),
7050 muteWaitMs == 0 ? (delayMs + (outputDesc->latency() / 2)) : delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07007051 }
Eric Laurente552edb2014-03-10 17:42:56 -07007052
7053 // update stream volumes according to new device
François Gaffie11d30102018-11-02 16:09:09 +01007054 applyStreamVolumes(outputDesc, filteredDevices.types(), delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07007055
7056 return muteWaitMs;
7057}
7058
Eric Laurentc75307b2015-03-17 15:29:32 -07007059status_t AudioPolicyManager::resetOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurent6a94d692014-05-20 11:18:06 -07007060 int delayMs,
7061 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07007062{
Eric Laurent6a94d692014-05-20 11:18:06 -07007063 ssize_t index;
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02007064 if (patchHandle == nullptr && !outputDesc->isRouted()) {
7065 return INVALID_OPERATION;
7066 }
Eric Laurent6a94d692014-05-20 11:18:06 -07007067 if (patchHandle) {
7068 index = mAudioPatches.indexOfKey(*patchHandle);
7069 } else {
Jean-Michel Triviff155c62016-02-26 12:07:16 -08007070 index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007071 }
7072 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07007073 return INVALID_OPERATION;
7074 }
Eric Laurent6a94d692014-05-20 11:18:06 -07007075 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007076 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07007077 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07007078 outputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
François Gaffieafd4cea2019-11-18 15:50:22 +01007079 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007080 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07007081 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07007082 return status;
7083}
7084
7085status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
François Gaffie11d30102018-11-02 16:09:09 +01007086 const sp<DeviceDescriptor> &device,
Eric Laurent6a94d692014-05-20 11:18:06 -07007087 bool force,
7088 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07007089{
7090 status_t status = NO_ERROR;
7091
Eric Laurent1f2f2232014-06-02 12:01:23 -07007092 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
François Gaffie11d30102018-11-02 16:09:09 +01007093 if ((device != nullptr) && ((device != inputDesc->getDevice()) || force)) {
7094 inputDesc->setDevice(device);
Eric Laurent1c333e22014-05-20 10:48:17 -07007095
François Gaffie11d30102018-11-02 16:09:09 +01007096 if (mAvailableInputDevices.contains(device)) {
Mikhail Naganovdc769682018-05-04 15:34:08 -07007097 PatchBuilder patchBuilder;
7098 patchBuilder.addSink(inputDesc,
Eric Laurentdaf92cc2014-07-22 15:36:10 -07007099 // AUDIO_SOURCE_HOTWORD is for internal use only:
7100 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
Mikhail Naganovdc769682018-05-04 15:34:08 -07007101 [inputDesc](const PatchBuilder::mix_usecase_t& usecase) {
7102 auto result = usecase;
7103 if (result.source == AUDIO_SOURCE_HOTWORD && !inputDesc->isSoundTrigger()) {
7104 result.source = AUDIO_SOURCE_VOICE_RECOGNITION;
7105 }
7106 return result; }).
Eric Laurent1c333e22014-05-20 10:48:17 -07007107 //only one input device for now
François Gaffie11d30102018-11-02 16:09:09 +01007108 addSource(device);
Mikhail Naganovdc769682018-05-04 15:34:08 -07007109 status = installPatch(__func__, patchHandle, inputDesc.get(), patchBuilder.patch(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07007110 }
7111 }
7112 return status;
7113}
7114
Eric Laurent6a94d692014-05-20 11:18:06 -07007115status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
7116 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07007117{
Eric Laurent1f2f2232014-06-02 12:01:23 -07007118 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07007119 ssize_t index;
7120 if (patchHandle) {
7121 index = mAudioPatches.indexOfKey(*patchHandle);
7122 } else {
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08007123 index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007124 }
7125 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07007126 return INVALID_OPERATION;
7127 }
Eric Laurent6a94d692014-05-20 11:18:06 -07007128 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007129 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07007130 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07007131 inputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
François Gaffieafd4cea2019-11-18 15:50:22 +01007132 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007133 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07007134 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07007135 return status;
7136}
7137
François Gaffie11d30102018-11-02 16:09:09 +01007138sp<IOProfile> AudioPolicyManager::getInputProfile(const sp<DeviceDescriptor> &device,
François Gaffie53615e22015-03-19 09:24:12 +01007139 uint32_t& samplingRate,
Andy Hungf129b032015-04-07 13:45:50 -07007140 audio_format_t& format,
7141 audio_channel_mask_t& channelMask,
François Gaffie53615e22015-03-19 09:24:12 +01007142 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07007143{
7144 // Choose an input profile based on the requested capture parameters: select the first available
7145 // profile supporting all requested parameters.
Andy Hungf129b032015-04-07 13:45:50 -07007146 //
7147 // TODO: perhaps isCompatibleProfile should return a "matching" score so we can return
7148 // the best matching profile, not the first one.
Eric Laurente552edb2014-03-10 17:42:56 -07007149
Glenn Kasten730b9262018-03-29 15:01:26 -07007150 sp<IOProfile> firstInexact;
7151 uint32_t updatedSamplingRate = 0;
7152 audio_format_t updatedFormat = AUDIO_FORMAT_INVALID;
7153 audio_channel_mask_t updatedChannelMask = AUDIO_CHANNEL_INVALID;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08007154 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08007155 for (const auto& profile : hwModule->getInputProfiles()) {
Eric Laurentd4692962014-05-05 18:13:44 -07007156 // profile->log();
Glenn Kasten730b9262018-03-29 15:01:26 -07007157 //updatedFormat = format;
François Gaffie11d30102018-11-02 16:09:09 +01007158 if (profile->isCompatibleProfile(DeviceVector(device), samplingRate,
Glenn Kasten730b9262018-03-29 15:01:26 -07007159 &samplingRate /*updatedSamplingRate*/,
Andy Hungf129b032015-04-07 13:45:50 -07007160 format,
Glenn Kasten730b9262018-03-29 15:01:26 -07007161 &format, /*updatedFormat*/
Andy Hungf129b032015-04-07 13:45:50 -07007162 channelMask,
Glenn Kasten730b9262018-03-29 15:01:26 -07007163 &channelMask /*updatedChannelMask*/,
7164 // FIXME ugly cast
7165 (audio_output_flags_t) flags,
7166 true /*exactMatchRequiredForInputFlags*/)) {
Eric Laurente552edb2014-03-10 17:42:56 -07007167 return profile;
7168 }
François Gaffie11d30102018-11-02 16:09:09 +01007169 if (firstInexact == nullptr && profile->isCompatibleProfile(DeviceVector(device),
Glenn Kasten730b9262018-03-29 15:01:26 -07007170 samplingRate,
7171 &updatedSamplingRate,
7172 format,
7173 &updatedFormat,
7174 channelMask,
7175 &updatedChannelMask,
7176 // FIXME ugly cast
7177 (audio_output_flags_t) flags,
7178 false /*exactMatchRequiredForInputFlags*/)) {
7179 firstInexact = profile;
7180 }
7181
Eric Laurente552edb2014-03-10 17:42:56 -07007182 }
7183 }
Glenn Kasten730b9262018-03-29 15:01:26 -07007184 if (firstInexact != nullptr) {
7185 samplingRate = updatedSamplingRate;
7186 format = updatedFormat;
7187 channelMask = updatedChannelMask;
7188 return firstInexact;
7189 }
Eric Laurente552edb2014-03-10 17:42:56 -07007190 return NULL;
7191}
7192
François Gaffieaaac0fd2018-11-22 17:56:39 +01007193float AudioPolicyManager::computeVolume(IVolumeCurves &curves,
7194 VolumeSource volumeSource,
François Gaffied1ab2bd2015-12-02 18:20:06 +01007195 int index,
jiabin9a3361e2019-10-01 09:38:30 -07007196 const DeviceTypeSet& deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07007197{
jiabin9a3361e2019-10-01 09:38:30 -07007198 float volumeDb = curves.volIndexToDb(Volume::getDeviceCategory(deviceTypes), index);
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07007199
7200 // handle the case of accessibility active while a ringtone is playing: if the ringtone is much
7201 // louder than the accessibility prompt, the prompt cannot be heard, thus masking the touch
7202 // exploration of the dialer UI. In this situation, bring the accessibility volume closer to
7203 // the ringtone volume
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007204 const auto callVolumeSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL, false);
7205 const auto ringVolumeSrc = toVolumeSource(AUDIO_STREAM_RING, false);
7206 const auto musicVolumeSrc = toVolumeSource(AUDIO_STREAM_MUSIC, false);
7207 const auto alarmVolumeSrc = toVolumeSource(AUDIO_STREAM_ALARM, false);
7208 const auto a11yVolumeSrc = toVolumeSource(AUDIO_STREAM_ACCESSIBILITY, false);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007209
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07007210 if (volumeSource == a11yVolumeSrc
François Gaffieaaac0fd2018-11-22 17:56:39 +01007211 && (AUDIO_MODE_RINGTONE == mEngine->getPhoneState()) &&
7212 mOutputs.isActive(ringVolumeSrc, 0)) {
7213 auto &ringCurves = getVolumeCurves(AUDIO_STREAM_RING);
jiabin9a3361e2019-10-01 09:38:30 -07007214 const float ringVolumeDb = computeVolume(ringCurves, ringVolumeSrc, index, deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007215 return ringVolumeDb - 4 > volumeDb ? ringVolumeDb - 4 : volumeDb;
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07007216 }
7217
Eric Laurentdcd4ab12018-06-29 17:45:13 -07007218 // in-call: always cap volume by voice volume + some low headroom
François Gaffieaaac0fd2018-11-22 17:56:39 +01007219 if ((volumeSource != callVolumeSrc && (isInCall() ||
7220 mOutputs.isActiveLocally(callVolumeSrc))) &&
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007221 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM, false) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01007222 volumeSource == ringVolumeSrc || volumeSource == musicVolumeSrc ||
7223 volumeSource == alarmVolumeSrc ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007224 volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION, false) ||
7225 volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false) ||
7226 volumeSource == toVolumeSource(AUDIO_STREAM_DTMF, false) ||
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07007227 volumeSource == a11yVolumeSrc)) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007228 auto &voiceCurves = getVolumeCurves(callVolumeSrc);
jiabin9a3361e2019-10-01 09:38:30 -07007229 int voiceVolumeIndex = voiceCurves.getVolumeIndex(deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007230 const float maxVoiceVolDb =
jiabin9a3361e2019-10-01 09:38:30 -07007231 computeVolume(voiceCurves, callVolumeSrc, voiceVolumeIndex, deviceTypes)
Eric Laurent7731b5a2018-04-06 15:47:22 -07007232 + IN_CALL_EARPIECE_HEADROOM_DB;
Abhijith Shastry329ddab2019-04-23 11:53:26 -07007233 // FIXME: Workaround for call screening applications until a proper audio mode is defined
7234 // to support this scenario : Exempt the RING stream from the audio cap if the audio was
7235 // programmatically muted.
7236 // VOICE_CALL stream has minVolumeIndex > 0 : Users cannot set the volume of voice calls to
7237 // 0. We don't want to cap volume when the system has programmatically muted the voice call
7238 // stream. See setVolumeCurveIndex() for more information.
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07007239 bool exemptFromCapping =
7240 ((volumeSource == ringVolumeSrc) || (volumeSource == a11yVolumeSrc))
7241 && (voiceVolumeIndex == 0);
Abhijith Shastry329ddab2019-04-23 11:53:26 -07007242 ALOGV_IF(exemptFromCapping, "%s volume source %d at vol=%f not capped", __func__,
7243 volumeSource, volumeDb);
7244 if ((volumeDb > maxVoiceVolDb) && !exemptFromCapping) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007245 ALOGV("%s volume source %d at vol=%f overriden by volume group %d at vol=%f", __func__,
7246 volumeSource, volumeDb, callVolumeSrc, maxVoiceVolDb);
7247 volumeDb = maxVoiceVolDb;
Jean-Michel Trivi719a9872017-08-05 13:51:35 -07007248 }
7249 }
Eric Laurente552edb2014-03-10 17:42:56 -07007250 // if a headset is connected, apply the following rules to ring tones and notifications
7251 // to avoid sound level bursts in user's ears:
Eric Laurent6af1c1d2016-04-14 11:20:44 -07007252 // - always attenuate notifications volume by 6dB
7253 // - attenuate ring tones volume by 6dB unless music is not playing and
7254 // speaker is part of the select devices
Eric Laurente552edb2014-03-10 17:42:56 -07007255 // - if music is playing, always limit the volume to current music volume,
7256 // with a minimum threshold at -36dB so that notification is always perceived.
jiabin9a3361e2019-10-01 09:38:30 -07007257 if (!Intersection(deviceTypes,
7258 {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP, AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES,
7259 AUDIO_DEVICE_OUT_WIRED_HEADSET, AUDIO_DEVICE_OUT_WIRED_HEADPHONE,
Eric Laurentc42df452020-08-07 10:51:53 -07007260 AUDIO_DEVICE_OUT_USB_HEADSET, AUDIO_DEVICE_OUT_HEARING_AID,
7261 AUDIO_DEVICE_OUT_BLE_HEADSET}).empty() &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01007262 ((volumeSource == alarmVolumeSrc ||
7263 volumeSource == ringVolumeSrc) ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007264 (volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION, false)) ||
7265 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM, false)) ||
7266 ((volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false)) &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01007267 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) &&
7268 curves.canBeMuted()) {
7269
Eric Laurente552edb2014-03-10 17:42:56 -07007270 // when the phone is ringing we must consider that music could have been paused just before
7271 // by the music application and behave as if music was active if the last music track was
7272 // just stopped
Eric Laurent3b73df72014-03-11 09:06:29 -07007273 if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY) ||
Eric Laurente552edb2014-03-10 17:42:56 -07007274 mLimitRingtoneVolume) {
François Gaffie43c73442018-11-08 08:21:55 +01007275 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
jiabin9a3361e2019-10-01 09:38:30 -07007276 DeviceTypeSet musicDevice =
François Gaffiec005e562018-11-06 15:04:49 +01007277 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
7278 nullptr, true /*fromCache*/).types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01007279 auto &musicCurves = getVolumeCurves(AUDIO_STREAM_MUSIC);
jiabin9a3361e2019-10-01 09:38:30 -07007280 float musicVolDb = computeVolume(musicCurves,
7281 musicVolumeSrc,
7282 musicCurves.getVolumeIndex(musicDevice),
7283 musicDevice);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007284 float minVolDb = (musicVolDb > SONIFICATION_HEADSET_VOLUME_MIN_DB) ?
7285 musicVolDb : SONIFICATION_HEADSET_VOLUME_MIN_DB;
7286 if (volumeDb > minVolDb) {
7287 volumeDb = minVolDb;
7288 ALOGV("computeVolume limiting volume to %f musicVol %f", minVolDb, musicVolDb);
Eric Laurente552edb2014-03-10 17:42:56 -07007289 }
Eric Laurent7b6385c2021-05-12 17:55:36 +02007290 if (Volume::getDeviceForVolume(deviceTypes) != AUDIO_DEVICE_OUT_SPEAKER
7291 && !Intersection(deviceTypes, {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP,
7292 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES}).empty()) {
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07007293 // on A2DP, also ensure notification volume is not too low compared to media when
7294 // intended to be played
François Gaffie43c73442018-11-08 08:21:55 +01007295 if ((volumeDb > -96.0f) &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01007296 (musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB > volumeDb)) {
jiabin9a3361e2019-10-01 09:38:30 -07007297 ALOGV("%s increasing volume for volume source=%d device=%s from %f to %f",
7298 __func__, volumeSource, dumpDeviceTypes(deviceTypes).c_str(), volumeDb,
François Gaffieaaac0fd2018-11-22 17:56:39 +01007299 musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB);
7300 volumeDb = musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB;
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07007301 }
7302 }
jiabin9a3361e2019-10-01 09:38:30 -07007303 } else if ((Volume::getDeviceForVolume(deviceTypes) != AUDIO_DEVICE_OUT_SPEAKER) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01007304 (!(volumeSource == alarmVolumeSrc || volumeSource == ringVolumeSrc))) {
François Gaffie43c73442018-11-08 08:21:55 +01007305 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07007306 }
7307 }
7308
François Gaffie43c73442018-11-08 08:21:55 +01007309 return volumeDb;
Eric Laurente552edb2014-03-10 17:42:56 -07007310}
7311
Eric Laurent3839bc02018-07-10 18:33:34 -07007312int AudioPolicyManager::rescaleVolumeIndex(int srcIndex,
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01007313 VolumeSource fromVolumeSource,
7314 VolumeSource toVolumeSource)
Eric Laurent3839bc02018-07-10 18:33:34 -07007315{
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01007316 if (fromVolumeSource == toVolumeSource) {
Eric Laurent3839bc02018-07-10 18:33:34 -07007317 return srcIndex;
7318 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01007319 auto &srcCurves = getVolumeCurves(fromVolumeSource);
7320 auto &dstCurves = getVolumeCurves(toVolumeSource);
Eric Laurentf5aa58d2019-02-22 18:20:11 -08007321 float minSrc = (float)srcCurves.getVolumeIndexMin();
7322 float maxSrc = (float)srcCurves.getVolumeIndexMax();
7323 float minDst = (float)dstCurves.getVolumeIndexMin();
7324 float maxDst = (float)dstCurves.getVolumeIndexMax();
Eric Laurent3839bc02018-07-10 18:33:34 -07007325
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08007326 // preserve mute request or correct range
7327 if (srcIndex < minSrc) {
7328 if (srcIndex == 0) {
7329 return 0;
7330 }
7331 srcIndex = minSrc;
7332 } else if (srcIndex > maxSrc) {
7333 srcIndex = maxSrc;
7334 }
Eric Laurent3839bc02018-07-10 18:33:34 -07007335 return (int)(minDst + ((srcIndex - minSrc) * (maxDst - minDst)) / (maxSrc - minSrc));
7336}
7337
François Gaffieaaac0fd2018-11-22 17:56:39 +01007338status_t AudioPolicyManager::checkAndSetVolume(IVolumeCurves &curves,
7339 VolumeSource volumeSource,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08007340 int index,
7341 const sp<AudioOutputDescriptor>& outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07007342 DeviceTypeSet deviceTypes,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08007343 int delayMs,
7344 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07007345{
François Gaffieaaac0fd2018-11-22 17:56:39 +01007346 // do not change actual attributes volume if the attributes is muted
7347 if (outputDesc->isMuted(volumeSource)) {
7348 ALOGVV("%s: volume source %d muted count %d active=%d", __func__, volumeSource,
7349 outputDesc->getMuteCount(volumeSource), outputDesc->isActive(volumeSource));
Eric Laurente552edb2014-03-10 17:42:56 -07007350 return NO_ERROR;
7351 }
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007352 VolumeSource callVolSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL, false);
7353 VolumeSource btScoVolSrc = toVolumeSource(AUDIO_STREAM_BLUETOOTH_SCO, false);
7354 bool isVoiceVolSrc = (volumeSource != VOLUME_SOURCE_NONE) && (callVolSrc == volumeSource);
7355 bool isBtScoVolSrc = (volumeSource != VOLUME_SOURCE_NONE) && (btScoVolSrc == volumeSource);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007356
Eric Laurent2517af32020-11-25 15:31:27 +01007357 bool isScoRequested = isScoRequestedForComm();
Eric Laurent1a8b45f2022-04-13 16:01:47 +02007358 bool isHAUsed = isHearingAidUsedForComm();
7359
Eric Laurente552edb2014-03-10 17:42:56 -07007360 // do not change in call volume if bluetooth is connected and vice versa
François Gaffieaaac0fd2018-11-22 17:56:39 +01007361 // if sco and call follow same curves, bypass forceUseForComm
7362 if ((callVolSrc != btScoVolSrc) &&
Eric Laurent2517af32020-11-25 15:31:27 +01007363 ((isVoiceVolSrc && isScoRequested) ||
Beibeif660a512023-02-28 17:00:34 +08007364 (isBtScoVolSrc && !(isScoRequested || isHAUsed))) &&
7365 !isSingleDeviceType(deviceTypes, AUDIO_DEVICE_OUT_TELEPHONY_TX)) {
Eric Laurent2517af32020-11-25 15:31:27 +01007366 ALOGV("%s cannot set volume group %d volume when is%srequested for comm", __func__,
Eric Laurent1a8b45f2022-04-13 16:01:47 +02007367 volumeSource, isScoRequested ? " " : " not ");
Eric Laurent571ef962020-07-24 11:43:48 -07007368 // Do not return an error here as AudioService will always set both voice call
7369 // and bluetooth SCO volumes due to stream aliasing.
7370 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07007371 }
jiabin9a3361e2019-10-01 09:38:30 -07007372 if (deviceTypes.empty()) {
7373 deviceTypes = outputDesc->devices().types();
Eric Laurentc75307b2015-03-17 15:29:32 -07007374 }
Eric Laurent275e8e92014-11-30 15:14:47 -08007375
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00007376 if (curves.getVolumeIndexMin() < 0 || curves.getVolumeIndexMax() < 0) {
7377 ALOGE("invalid volume index range");
7378 return BAD_VALUE;
7379 }
7380
jiabin9a3361e2019-10-01 09:38:30 -07007381 float volumeDb = computeVolume(curves, volumeSource, index, deviceTypes);
7382 if (outputDesc->isFixedVolume(deviceTypes) ||
Eric Laurent9698a4c2020-10-12 17:10:23 -07007383 // Force VoIP volume to max for bluetooth SCO device except if muted
7384 (index != 0 && (isVoiceVolSrc || isBtScoVolSrc) &&
jiabin9a3361e2019-10-01 09:38:30 -07007385 isSingleDeviceType(deviceTypes, audio_is_bluetooth_out_sco_device))) {
Eric Laurentffbc80f2015-03-18 18:30:19 -07007386 volumeDb = 0.0f;
Eric Laurent275e8e92014-11-30 15:14:47 -08007387 }
Francois Gaffie593634d2021-06-22 13:31:31 +02007388 const bool muted = (index == 0) && (volumeDb != 0.0f);
jiabin9a3361e2019-10-01 09:38:30 -07007389 outputDesc->setVolume(
Francois Gaffie593634d2021-06-22 13:31:31 +02007390 volumeDb, muted, volumeSource, curves.getStreamTypes(), deviceTypes, delayMs, force);
Eric Laurentc75307b2015-03-17 15:29:32 -07007391
Eric Laurente8f2c0f2021-08-17 11:17:19 +02007392 if (outputDesc == mPrimaryOutput && (isVoiceVolSrc || isBtScoVolSrc)) {
Eric Laurente552edb2014-03-10 17:42:56 -07007393 float voiceVolume;
Eric Laurentfad001d2019-06-11 19:17:57 -07007394 // 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 +01007395 if (isVoiceVolSrc) {
7396 voiceVolume = (float)index/(float)curves.getVolumeIndexMax();
Eric Laurente552edb2014-03-10 17:42:56 -07007397 } else {
Eric Laurentfad001d2019-06-11 19:17:57 -07007398 voiceVolume = index == 0 ? 0.0 : 1.0;
Eric Laurente552edb2014-03-10 17:42:56 -07007399 }
Eric Laurent18fba842016-03-31 14:41:26 -07007400 if (voiceVolume != mLastVoiceVolume) {
Eric Laurente552edb2014-03-10 17:42:56 -07007401 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
7402 mLastVoiceVolume = voiceVolume;
7403 }
7404 }
Eric Laurente552edb2014-03-10 17:42:56 -07007405 return NO_ERROR;
7406}
7407
Eric Laurentc75307b2015-03-17 15:29:32 -07007408void AudioPolicyManager::applyStreamVolumes(const sp<AudioOutputDescriptor>& outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07007409 const DeviceTypeSet& deviceTypes,
7410 int delayMs,
7411 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07007412{
jiabincd510522020-01-22 09:40:55 -08007413 ALOGVV("applyStreamVolumes() for device %s", dumpDeviceTypes(deviceTypes).c_str());
François Gaffieaaac0fd2018-11-22 17:56:39 +01007414 for (const auto &volumeGroup : mEngine->getVolumeGroups()) {
7415 auto &curves = getVolumeCurves(toVolumeSource(volumeGroup));
7416 checkAndSetVolume(curves, toVolumeSource(volumeGroup),
jiabin9a3361e2019-10-01 09:38:30 -07007417 curves.getVolumeIndex(deviceTypes),
7418 outputDesc, deviceTypes, delayMs, force);
Eric Laurente552edb2014-03-10 17:42:56 -07007419 }
7420}
7421
François Gaffiec005e562018-11-06 15:04:49 +01007422void AudioPolicyManager::setStrategyMute(product_strategy_t strategy,
7423 bool on,
7424 const sp<AudioOutputDescriptor>& outputDesc,
7425 int delayMs,
jiabin9a3361e2019-10-01 09:38:30 -07007426 DeviceTypeSet deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07007427{
François Gaffieaaac0fd2018-11-22 17:56:39 +01007428 std::vector<VolumeSource> sourcesToMute;
7429 for (auto attributes: mEngine->getAllAttributesForProductStrategy(strategy)) {
7430 ALOGVV("%s() attributes %s, mute %d, output ID %d", __func__,
7431 toString(attributes).c_str(), on, outputDesc->getId());
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007432 VolumeSource source = toVolumeSource(attributes, false);
7433 if ((source != VOLUME_SOURCE_NONE) &&
7434 (std::find(begin(sourcesToMute), end(sourcesToMute), source)
7435 == end(sourcesToMute))) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007436 sourcesToMute.push_back(source);
7437 }
Eric Laurente552edb2014-03-10 17:42:56 -07007438 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01007439 for (auto source : sourcesToMute) {
jiabin9a3361e2019-10-01 09:38:30 -07007440 setVolumeSourceMute(source, on, outputDesc, delayMs, deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007441 }
7442
Eric Laurente552edb2014-03-10 17:42:56 -07007443}
7444
François Gaffieaaac0fd2018-11-22 17:56:39 +01007445void AudioPolicyManager::setVolumeSourceMute(VolumeSource volumeSource,
7446 bool on,
7447 const sp<AudioOutputDescriptor>& outputDesc,
7448 int delayMs,
jiabin9a3361e2019-10-01 09:38:30 -07007449 DeviceTypeSet deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07007450{
jiabin9a3361e2019-10-01 09:38:30 -07007451 if (deviceTypes.empty()) {
7452 deviceTypes = outputDesc->devices().types();
Eric Laurente552edb2014-03-10 17:42:56 -07007453 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01007454 auto &curves = getVolumeCurves(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07007455 if (on) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007456 if (!outputDesc->isMuted(volumeSource)) {
Eric Laurentf5aa58d2019-02-22 18:20:11 -08007457 if (curves.canBeMuted() &&
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007458 (volumeSource != toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01007459 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) ==
7460 AUDIO_POLICY_FORCE_NONE))) {
jiabin9a3361e2019-10-01 09:38:30 -07007461 checkAndSetVolume(curves, volumeSource, 0, outputDesc, deviceTypes, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07007462 }
7463 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01007464 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not
7465 // ignored
7466 outputDesc->incMuteCount(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07007467 } else {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007468 if (!outputDesc->isMuted(volumeSource)) {
7469 ALOGV("%s unmuting non muted attributes!", __func__);
Eric Laurente552edb2014-03-10 17:42:56 -07007470 return;
7471 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01007472 if (outputDesc->decMuteCount(volumeSource) == 0) {
7473 checkAndSetVolume(curves, volumeSource,
jiabin9a3361e2019-10-01 09:38:30 -07007474 curves.getVolumeIndex(deviceTypes),
Eric Laurentc75307b2015-03-17 15:29:32 -07007475 outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07007476 deviceTypes,
Eric Laurente552edb2014-03-10 17:42:56 -07007477 delayMs);
7478 }
7479 }
7480}
7481
François Gaffie53615e22015-03-19 09:24:12 +01007482bool AudioPolicyManager::isValidAttributes(const audio_attributes_t *paa)
7483{
François Gaffiec005e562018-11-06 15:04:49 +01007484 // has flags that map to a stream type?
Eric Laurente83b55d2014-11-14 10:06:21 -08007485 if ((paa->flags & (AUDIO_FLAG_AUDIBILITY_ENFORCED | AUDIO_FLAG_SCO | AUDIO_FLAG_BEACON)) != 0) {
7486 return true;
7487 }
7488
7489 // has known usage?
7490 switch (paa->usage) {
7491 case AUDIO_USAGE_UNKNOWN:
7492 case AUDIO_USAGE_MEDIA:
7493 case AUDIO_USAGE_VOICE_COMMUNICATION:
7494 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
7495 case AUDIO_USAGE_ALARM:
7496 case AUDIO_USAGE_NOTIFICATION:
7497 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
7498 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
7499 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
7500 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
7501 case AUDIO_USAGE_NOTIFICATION_EVENT:
7502 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
7503 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
7504 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
7505 case AUDIO_USAGE_GAME:
Eric Laurent275e8e92014-11-30 15:14:47 -08007506 case AUDIO_USAGE_VIRTUAL_SOURCE:
Jean-Michel Trivi36867762016-12-29 12:03:28 -08007507 case AUDIO_USAGE_ASSISTANT:
Eric Laurent21777f82019-12-06 18:12:06 -08007508 case AUDIO_USAGE_CALL_ASSISTANT:
Hayden Gomes524159d2019-12-23 14:41:47 -08007509 case AUDIO_USAGE_EMERGENCY:
7510 case AUDIO_USAGE_SAFETY:
7511 case AUDIO_USAGE_VEHICLE_STATUS:
7512 case AUDIO_USAGE_ANNOUNCEMENT:
Eric Laurente83b55d2014-11-14 10:06:21 -08007513 break;
7514 default:
7515 return false;
7516 }
7517 return true;
7518}
7519
François Gaffie2110e042015-03-24 08:41:51 +01007520audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
7521{
7522 return mEngine->getForceUse(usage);
7523}
7524
Eric Laurent96d1dda2022-03-14 17:14:19 +01007525bool AudioPolicyManager::isInCall() const {
François Gaffie2110e042015-03-24 08:41:51 +01007526 return isStateInCall(mEngine->getPhoneState());
7527}
7528
Eric Laurent96d1dda2022-03-14 17:14:19 +01007529bool AudioPolicyManager::isStateInCall(int state) const {
François Gaffie2110e042015-03-24 08:41:51 +01007530 return is_state_in_call(state);
7531}
7532
Eric Laurentf9cccec2022-11-16 19:12:00 +01007533bool AudioPolicyManager::isCallAudioAccessible() const {
Eric Laurent74b71512019-11-06 17:21:57 -08007534 audio_mode_t mode = mEngine->getPhoneState();
7535 return (mode == AUDIO_MODE_IN_CALL)
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01007536 || (mode == AUDIO_MODE_CALL_SCREEN)
7537 || (mode == AUDIO_MODE_CALL_REDIRECT);
Eric Laurent74b71512019-11-06 17:21:57 -08007538}
7539
Eric Laurentf9cccec2022-11-16 19:12:00 +01007540bool AudioPolicyManager::isInCallOrScreening() const {
7541 audio_mode_t mode = mEngine->getPhoneState();
7542 return isStateInCall(mode) || mode == AUDIO_MODE_CALL_SCREEN;
7543}
7544
Eric Laurentd60560a2015-04-10 11:31:20 -07007545void AudioPolicyManager::cleanUpForDevice(const sp<DeviceDescriptor>& deviceDesc)
7546{
7547 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07007548 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02007549 if (sourceDesc->isConnected() && (sourceDesc->srcDevice()->equals(deviceDesc) ||
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02007550 sourceDesc->sinkDevice()->equals(deviceDesc))
7551 && !isCallRxAudioSource(sourceDesc)) {
Francois Gaffiea0e5c992020-09-29 16:05:07 +02007552 disconnectAudioSource(sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07007553 }
7554 }
7555
7556 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
7557 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
7558 bool release = false;
7559 for (size_t j = 0; j < patchDesc->mPatch.num_sources && !release; j++) {
7560 const struct audio_port_config *source = &patchDesc->mPatch.sources[j];
7561 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
7562 source->ext.device.type == deviceDesc->type()) {
7563 release = true;
7564 }
7565 }
Francois Gaffiea0e5c992020-09-29 16:05:07 +02007566 const char *address = deviceDesc->address().c_str();
Eric Laurentd60560a2015-04-10 11:31:20 -07007567 for (size_t j = 0; j < patchDesc->mPatch.num_sinks && !release; j++) {
7568 const struct audio_port_config *sink = &patchDesc->mPatch.sinks[j];
7569 if (sink->type == AUDIO_PORT_TYPE_DEVICE &&
Francois Gaffiea0e5c992020-09-29 16:05:07 +02007570 sink->ext.device.type == deviceDesc->type() &&
7571 (strnlen(address, AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0
7572 || strncmp(sink->ext.device.address, address,
7573 AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0)) {
Eric Laurentd60560a2015-04-10 11:31:20 -07007574 release = true;
7575 }
7576 }
7577 if (release) {
François Gaffieafd4cea2019-11-18 15:50:22 +01007578 ALOGV("%s releasing patch %u", __FUNCTION__, patchDesc->getHandle());
7579 releaseAudioPatch(patchDesc->getHandle(), patchDesc->getUid());
Eric Laurentd60560a2015-04-10 11:31:20 -07007580 }
7581 }
Francois Gaffie716e1432019-01-14 16:58:59 +01007582
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01007583 mInputs.clearSessionRoutesForDevice(deviceDesc);
7584
Francois Gaffie716e1432019-01-14 16:58:59 +01007585 mHwModules.cleanUpForDevice(deviceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07007586}
7587
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007588void AudioPolicyManager::modifySurroundFormats(
7589 const sp<DeviceDescriptor>& devDesc, FormatVector *formatsPtr) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007590 std::unordered_set<audio_format_t> enforcedSurround(
7591 devDesc->encodedFormats().begin(), devDesc->encodedFormats().end());
Mikhail Naganov100f0122018-11-29 11:22:16 -08007592 std::unordered_set<audio_format_t> allSurround; // A flat set of all known surround formats
Mikhail Naganovb0fbc1b2023-04-28 13:06:32 -07007593 for (const auto& pair : mConfig->getSurroundFormats()) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08007594 allSurround.insert(pair.first);
7595 for (const auto& subformat : pair.second) allSurround.insert(subformat);
7596 }
Phil Burk09bc4612016-02-24 15:58:15 -08007597
7598 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
7599 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Phil Burk0709b0a2016-03-31 12:54:57 -07007600 ALOGD("%s: forced use = %d", __FUNCTION__, forceUse);
Mikhail Naganov100f0122018-11-29 11:22:16 -08007601 // This is the resulting set of formats depending on the surround mode:
7602 // 'all surround' = allSurround
7603 // 'enforced surround' = enforcedSurround [may include IEC69137 which isn't raw surround fmt]
7604 // 'non-surround' = not in 'all surround' and not in 'enforced surround'
7605 // 'manual surround' = mManualSurroundFormats
7606 // AUTO: formats v 'enforced surround'
7607 // ALWAYS: formats v 'all surround' v 'enforced surround'
7608 // NEVER: formats ^ 'non-surround'
7609 // MANUAL: formats ^ ('non-surround' v 'manual surround' v (IEC69137 ^ 'enforced surround'))
Phil Burk09bc4612016-02-24 15:58:15 -08007610
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007611 std::unordered_set<audio_format_t> formatSet;
7612 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL
7613 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08007614 // formatSet is (formats ^ 'non-surround')
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007615 for (auto formatIter = formatsPtr->begin(); formatIter != formatsPtr->end(); ++formatIter) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08007616 if (allSurround.count(*formatIter) == 0 && enforcedSurround.count(*formatIter) == 0) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007617 formatSet.insert(*formatIter);
7618 }
7619 }
7620 } else {
7621 formatSet.insert(formatsPtr->begin(), formatsPtr->end());
7622 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08007623 formatsPtr->clear(); // Re-filled from the formatSet at the end.
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007624
jiabin81772902018-04-02 17:52:27 -07007625 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08007626 formatSet.insert(mManualSurroundFormats.begin(), mManualSurroundFormats.end());
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007627 // Enable IEC61937 when in MANUAL mode if it's enforced for this device.
7628 if (enforcedSurround.count(AUDIO_FORMAT_IEC61937) != 0) {
7629 formatSet.insert(AUDIO_FORMAT_IEC61937);
Phil Burk09bc4612016-02-24 15:58:15 -08007630 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08007631 } else if (forceUse != AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) { // AUTO or ALWAYS
7632 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS) {
7633 formatSet.insert(allSurround.begin(), allSurround.end());
Phil Burk07ac1142016-03-25 13:39:29 -07007634 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08007635 formatSet.insert(enforcedSurround.begin(), enforcedSurround.end());
Phil Burk09bc4612016-02-24 15:58:15 -08007636 }
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007637 for (const auto& format : formatSet) {
jiabin06e4bab2019-07-29 10:13:34 -07007638 formatsPtr->push_back(format);
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007639 }
Phil Burk0709b0a2016-03-31 12:54:57 -07007640}
7641
jiabin06e4bab2019-07-29 10:13:34 -07007642void AudioPolicyManager::modifySurroundChannelMasks(ChannelMaskSet *channelMasksPtr) {
7643 ChannelMaskSet &channelMasks = *channelMasksPtr;
Phil Burk0709b0a2016-03-31 12:54:57 -07007644 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
7645 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
7646
7647 // If NEVER, then remove support for channelMasks > stereo.
7648 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
jiabin06e4bab2019-07-29 10:13:34 -07007649 for (auto it = channelMasks.begin(); it != channelMasks.end();) {
7650 audio_channel_mask_t channelMask = *it;
Phil Burk0709b0a2016-03-31 12:54:57 -07007651 if (channelMask & ~AUDIO_CHANNEL_OUT_STEREO) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01007652 ALOGV("%s: force NEVER, so remove channelMask 0x%08x", __FUNCTION__, channelMask);
jiabin06e4bab2019-07-29 10:13:34 -07007653 it = channelMasks.erase(it);
Phil Burk0709b0a2016-03-31 12:54:57 -07007654 } else {
jiabin06e4bab2019-07-29 10:13:34 -07007655 ++it;
Phil Burk0709b0a2016-03-31 12:54:57 -07007656 }
7657 }
jiabin81772902018-04-02 17:52:27 -07007658 // If ALWAYS or MANUAL, then make sure we at least support 5.1
7659 } else if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS
7660 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Phil Burk0709b0a2016-03-31 12:54:57 -07007661 bool supports5dot1 = false;
7662 // Are there any channel masks that can be considered "surround"?
Mikhail Naganovcf84e592017-12-07 11:25:11 -08007663 for (audio_channel_mask_t channelMask : channelMasks) {
Phil Burk0709b0a2016-03-31 12:54:57 -07007664 if ((channelMask & AUDIO_CHANNEL_OUT_5POINT1) == AUDIO_CHANNEL_OUT_5POINT1) {
7665 supports5dot1 = true;
7666 break;
7667 }
7668 }
7669 // If not then add 5.1 support.
7670 if (!supports5dot1) {
jiabin06e4bab2019-07-29 10:13:34 -07007671 channelMasks.insert(AUDIO_CHANNEL_OUT_5POINT1);
Eric Laurentfecbceb2021-02-09 14:46:43 +01007672 ALOGV("%s: force MANUAL or ALWAYS, so adding channelMask for 5.1 surround", __func__);
Phil Burk0709b0a2016-03-31 12:54:57 -07007673 }
Phil Burk09bc4612016-02-24 15:58:15 -08007674 }
7675}
7676
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007677void AudioPolicyManager::updateAudioProfiles(const sp<DeviceDescriptor>& devDesc,
Phil Burk00eeb322016-03-31 12:41:00 -07007678 audio_io_handle_t ioHandle,
François Gaffie112b0af2015-11-19 16:13:25 +01007679 AudioProfileVector &profiles)
7680{
7681 String8 reply;
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007682 audio_devices_t device = devDesc->type();
Phil Burk0709b0a2016-03-31 12:54:57 -07007683
François Gaffie112b0af2015-11-19 16:13:25 +01007684 // Format MUST be checked first to update the list of AudioProfile
7685 if (profiles.hasDynamicFormat()) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07007686 reply = mpClientInterface->getParameters(
7687 ioHandle, String8(AudioParameter::keyStreamSupportedFormats));
jiabin81772902018-04-02 17:52:27 -07007688 ALOGV("%s: supported formats %d, %s", __FUNCTION__, ioHandle, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08007689 AudioParameter repliedParameters(reply);
jiabinf26596b2023-04-12 18:56:39 +00007690 FormatVector formats;
Eric Laurent62e4bc52016-02-02 18:37:28 -08007691 if (repliedParameters.get(
jiabinf26596b2023-04-12 18:56:39 +00007692 String8(AudioParameter::keyStreamSupportedFormats), reply) == NO_ERROR) {
7693 formats = formatsFromString(reply.string());
7694 } else if (devDesc->hasValidAudioProfile()) {
7695 ALOGD("%s: using the device profiles", __func__);
7696 formats = devDesc->getAudioProfiles().getSupportedFormats();
7697 } else {
7698 ALOGE("%s: failed to retrieve format, bailing out", __func__);
François Gaffie112b0af2015-11-19 16:13:25 +01007699 return;
7700 }
Kriti Dangef6be8f2020-11-05 11:58:19 +01007701 mReportedFormatsMap[devDesc] = formats;
Mikhail Naganov100f0122018-11-29 11:22:16 -08007702 if (device == AUDIO_DEVICE_OUT_HDMI
7703 || isDeviceOfModule(devDesc, AUDIO_HARDWARE_MODULE_ID_MSD)) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007704 modifySurroundFormats(devDesc, &formats);
Phil Burk00eeb322016-03-31 12:41:00 -07007705 }
jiabin3e277cc2019-09-10 14:27:34 -07007706 addProfilesForFormats(profiles, formats);
François Gaffie112b0af2015-11-19 16:13:25 +01007707 }
François Gaffie112b0af2015-11-19 16:13:25 +01007708
Mikhail Naganovcf84e592017-12-07 11:25:11 -08007709 for (audio_format_t format : profiles.getSupportedFormats()) {
jiabinf26596b2023-04-12 18:56:39 +00007710 std::optional<ChannelMaskSet> channelMasks;
jiabin06e4bab2019-07-29 10:13:34 -07007711 SampleRateSet samplingRates;
François Gaffie112b0af2015-11-19 16:13:25 +01007712 AudioParameter requestedParameters;
Mikhail Naganov388360c2016-10-17 17:09:41 -07007713 requestedParameters.addInt(String8(AudioParameter::keyFormat), format);
François Gaffie112b0af2015-11-19 16:13:25 +01007714
7715 if (profiles.hasDynamicRateFor(format)) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07007716 reply = mpClientInterface->getParameters(
7717 ioHandle,
7718 requestedParameters.toString() + ";" +
7719 AudioParameter::keyStreamSupportedSamplingRates);
François Gaffie112b0af2015-11-19 16:13:25 +01007720 ALOGV("%s: supported sampling rates %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08007721 AudioParameter repliedParameters(reply);
7722 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07007723 String8(AudioParameter::keyStreamSupportedSamplingRates), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08007724 samplingRates = samplingRatesFromString(reply.string());
jiabinf26596b2023-04-12 18:56:39 +00007725 } else {
7726 samplingRates = devDesc->getAudioProfiles().getSampleRatesFor(format);
François Gaffie112b0af2015-11-19 16:13:25 +01007727 }
7728 }
7729 if (profiles.hasDynamicChannelsFor(format)) {
7730 reply = mpClientInterface->getParameters(ioHandle,
7731 requestedParameters.toString() + ";" +
Mikhail Naganov388360c2016-10-17 17:09:41 -07007732 AudioParameter::keyStreamSupportedChannels);
François Gaffie112b0af2015-11-19 16:13:25 +01007733 ALOGV("%s: supported channel masks %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::keyStreamSupportedChannels), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08007737 channelMasks = channelMasksFromString(reply.string());
jiabinf26596b2023-04-12 18:56:39 +00007738 } else {
7739 channelMasks = devDesc->getAudioProfiles().getChannelMasksFor(format);
7740 }
7741 if (channelMasks.has_value() && (device == AUDIO_DEVICE_OUT_HDMI
7742 || isDeviceOfModule(devDesc, AUDIO_HARDWARE_MODULE_ID_MSD))) {
7743 modifySurroundChannelMasks(&channelMasks.value());
François Gaffie112b0af2015-11-19 16:13:25 +01007744 }
7745 }
jiabin3e277cc2019-09-10 14:27:34 -07007746 addDynamicAudioProfileAndSort(
jiabinf26596b2023-04-12 18:56:39 +00007747 profiles, new AudioProfile(
7748 format, channelMasks.value_or(ChannelMaskSet()), samplingRates));
François Gaffie112b0af2015-11-19 16:13:25 +01007749 }
7750}
Eric Laurentd60560a2015-04-10 11:31:20 -07007751
Mikhail Naganovdc769682018-05-04 15:34:08 -07007752status_t AudioPolicyManager::installPatch(const char *caller,
7753 audio_patch_handle_t *patchHandle,
7754 AudioIODescriptorInterface *ioDescriptor,
7755 const struct audio_patch *patch,
7756 int delayMs)
7757{
7758 ssize_t index = mAudioPatches.indexOfKey(
7759 patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE ?
7760 *patchHandle : ioDescriptor->getPatchHandle());
7761 sp<AudioPatch> patchDesc;
7762 status_t status = installPatch(
7763 caller, index, patchHandle, patch, delayMs, mUidCached, &patchDesc);
7764 if (status == NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01007765 ioDescriptor->setPatchHandle(patchDesc->getHandle());
Mikhail Naganovdc769682018-05-04 15:34:08 -07007766 }
7767 return status;
7768}
7769
7770status_t AudioPolicyManager::installPatch(const char *caller,
7771 ssize_t index,
7772 audio_patch_handle_t *patchHandle,
7773 const struct audio_patch *patch,
7774 int delayMs,
7775 uid_t uid,
7776 sp<AudioPatch> *patchDescPtr)
7777{
7778 sp<AudioPatch> patchDesc;
7779 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
7780 if (index >= 0) {
7781 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007782 afPatchHandle = patchDesc->getAfHandle();
Mikhail Naganovdc769682018-05-04 15:34:08 -07007783 }
7784
7785 status_t status = mpClientInterface->createAudioPatch(patch, &afPatchHandle, delayMs);
7786 ALOGV("%s() AF::createAudioPatch returned %d patchHandle %d num_sources %d num_sinks %d",
7787 caller, status, afPatchHandle, patch->num_sources, patch->num_sinks);
7788 if (status == NO_ERROR) {
7789 if (index < 0) {
7790 patchDesc = new AudioPatch(patch, uid);
François Gaffieafd4cea2019-11-18 15:50:22 +01007791 addAudioPatch(patchDesc->getHandle(), patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07007792 } else {
7793 patchDesc->mPatch = *patch;
7794 }
François Gaffieafd4cea2019-11-18 15:50:22 +01007795 patchDesc->setAfHandle(afPatchHandle);
Mikhail Naganovdc769682018-05-04 15:34:08 -07007796 if (patchHandle) {
François Gaffieafd4cea2019-11-18 15:50:22 +01007797 *patchHandle = patchDesc->getHandle();
Mikhail Naganovdc769682018-05-04 15:34:08 -07007798 }
7799 nextAudioPortGeneration();
7800 mpClientInterface->onAudioPatchListUpdate();
7801 }
7802 if (patchDescPtr) *patchDescPtr = patchDesc;
7803 return status;
7804}
7805
jiabinbce0c1d2020-10-05 11:20:18 -07007806bool AudioPolicyManager::areAllActiveTracksRerouted(const sp<SwAudioOutputDescriptor>& output)
7807{
7808 const TrackClientVector activeClients = output->getActiveClients();
7809 if (activeClients.empty()) {
7810 return true;
7811 }
7812 ssize_t index = mAudioPatches.indexOfKey(output->getPatchHandle());
7813 if (index < 0) {
7814 ALOGE("%s, no audio patch found while there are active clients on output %d",
7815 __func__, output->getId());
7816 return false;
7817 }
7818 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
7819 DeviceVector routedDevices;
7820 for (int i = 0; i < patchDesc->mPatch.num_sinks; ++i) {
7821 sp<DeviceDescriptor> device = mAvailableOutputDevices.getDeviceFromId(
7822 patchDesc->mPatch.sinks[i].id);
7823 if (device == nullptr) {
7824 ALOGE("%s, no audio device found with id(%d)",
7825 __func__, patchDesc->mPatch.sinks[i].id);
7826 return false;
7827 }
7828 routedDevices.add(device);
7829 }
7830 for (const auto& client : activeClients) {
jiabin49256852022-03-09 11:21:35 -08007831 if (client->isInvalid()) {
7832 // No need to take care about invalidated clients.
7833 continue;
7834 }
jiabinbce0c1d2020-10-05 11:20:18 -07007835 sp<DeviceDescriptor> preferredDevice =
7836 mAvailableOutputDevices.getDeviceFromId(client->preferredDeviceId());
7837 if (mEngine->getOutputDevicesForAttributes(
7838 client->attributes(), preferredDevice, false) == routedDevices) {
7839 return false;
7840 }
7841 }
7842 return true;
7843}
7844
7845sp<SwAudioOutputDescriptor> AudioPolicyManager::openOutputWithProfileAndDevice(
Eric Laurentb4f42a92022-01-17 17:37:31 +01007846 const sp<IOProfile>& profile, const DeviceVector& devices,
7847 const audio_config_base_t *mixerConfig)
jiabinbce0c1d2020-10-05 11:20:18 -07007848{
7849 for (const auto& device : devices) {
7850 // TODO: This should be checking if the profile supports the device combo.
7851 if (!profile->supportsDevice(device)) {
7852 return nullptr;
7853 }
7854 }
7855 sp<SwAudioOutputDescriptor> desc = new SwAudioOutputDescriptor(profile, mpClientInterface);
7856 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentb4f42a92022-01-17 17:37:31 +01007857 status_t status = desc->open(nullptr /* halConfig */, mixerConfig, devices,
jiabinbce0c1d2020-10-05 11:20:18 -07007858 AUDIO_STREAM_DEFAULT, AUDIO_OUTPUT_FLAG_NONE, &output);
7859 if (status != NO_ERROR) {
7860 return nullptr;
7861 }
7862
7863 // Here is where the out_set_parameters() for card & device gets called
7864 sp<DeviceDescriptor> device = devices.getDeviceForOpening();
7865 const audio_devices_t deviceType = device->type();
7866 const String8 &address = String8(device->address().c_str());
7867 if (!address.isEmpty()) {
7868 char *param = audio_device_address_to_parameter(deviceType, address.c_str());
7869 mpClientInterface->setParameters(output, String8(param));
7870 free(param);
7871 }
7872 updateAudioProfiles(device, output, profile->getAudioProfiles());
7873 if (!profile->hasValidAudioProfile()) {
7874 ALOGW("%s() missing param", __func__);
7875 desc->close();
7876 return nullptr;
7877 } else if (profile->hasDynamicAudioProfile()) {
7878 desc->close();
7879 output = AUDIO_IO_HANDLE_NONE;
7880 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
7881 profile->pickAudioProfile(
7882 config.sample_rate, config.channel_mask, config.format);
7883 config.offload_info.sample_rate = config.sample_rate;
7884 config.offload_info.channel_mask = config.channel_mask;
7885 config.offload_info.format = config.format;
7886
Eric Laurentb4f42a92022-01-17 17:37:31 +01007887 status = desc->open(&config, mixerConfig, devices,
jiabinbce0c1d2020-10-05 11:20:18 -07007888 AUDIO_STREAM_DEFAULT, AUDIO_OUTPUT_FLAG_NONE, &output);
7889 if (status != NO_ERROR) {
7890 return nullptr;
7891 }
7892 }
7893
7894 addOutput(output, desc);
Eric Laurentb4f42a92022-01-17 17:37:31 +01007895
baek.kim -61c20122022-07-27 10:05:32 +00007896 sp<DeviceDescriptor> speaker = mAvailableOutputDevices.getDevice(
7897 AUDIO_DEVICE_OUT_SPEAKER, String8(""), AUDIO_FORMAT_DEFAULT);
7898
jiabinbce0c1d2020-10-05 11:20:18 -07007899 if (audio_is_remote_submix_device(deviceType) && address != "0") {
7900 sp<AudioPolicyMix> policyMix;
7901 if (mPolicyMixes.getAudioPolicyMix(deviceType, address, policyMix) == NO_ERROR) {
7902 policyMix->setOutput(desc);
7903 desc->mPolicyMix = policyMix;
7904 } else {
7905 ALOGW("checkOutputsForDevice() cannot find policy for address %s",
7906 address.string());
7907 }
7908
baek.kim -61c20122022-07-27 10:05:32 +00007909 } else if (hasPrimaryOutput() && speaker != nullptr
7910 && mPrimaryOutput->supportsDevice(speaker) && !desc->supportsDevice(speaker)
Eric Laurentb4f42a92022-01-17 17:37:31 +01007911 && ((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0)) {
7912 // no duplicated output for:
7913 // - direct outputs
7914 // - outputs used by dynamic policy mixes
baek.kim -61c20122022-07-27 10:05:32 +00007915 // - outputs that supports SPEAKER while the primary output does not.
jiabinbce0c1d2020-10-05 11:20:18 -07007916 audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE;
7917
7918 //TODO: configure audio effect output stage here
7919
7920 // open a duplicating output thread for the new output and the primary output
7921 sp<SwAudioOutputDescriptor> dupOutputDesc =
7922 new SwAudioOutputDescriptor(nullptr, mpClientInterface);
7923 status = dupOutputDesc->openDuplicating(mPrimaryOutput, desc, &duplicatedOutput);
7924 if (status == NO_ERROR) {
7925 // add duplicated output descriptor
7926 addOutput(duplicatedOutput, dupOutputDesc);
7927 } else {
7928 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
7929 mPrimaryOutput->mIoHandle, output);
7930 desc->close();
7931 removeOutput(output);
7932 nextAudioPortGeneration();
7933 return nullptr;
7934 }
7935 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02007936 if (mPrimaryOutput == nullptr && profile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
7937 ALOGV("%s(): re-assigning mPrimaryOutput", __func__);
7938 mPrimaryOutput = desc;
7939 }
jiabinbce0c1d2020-10-05 11:20:18 -07007940 return desc;
7941}
7942
Mikhail Naganov1b2a7942017-12-08 10:18:09 -08007943} // namespace android